diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index 8af9f5342b2..cd3ba1dfa3a 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -12,22 +12,29 @@ on: - 'config/oxlint-performance-audit.json' - 'config/oxlint-plugins/*performance.mjs' - 'config/oxlint-plugins/quadratic-buffer-concat.mjs' - - 'config/scripts/*-plugin.test.mjs' - - '!config/scripts/static-analysis/oxlint-contracts/renderer-scrollbar-style-plugin.test.mjs' - # Keep in sync with the contract list in config/vitest.performance.config.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' + - '**/*.performance.test.ts' + - '**/*.performance.test.tsx' + # Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts; # without these a rename lands green and only breaks the next nightly. - - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts' + - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts' + - 'src/main/runtime/rpc/methods/projects/repo.test.ts' + - 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx' - 'src/main/sqlite/sync-database.test.ts' - 'src/main/runtime/orchestration/db/row-column-lists.test.ts' - - 'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts' - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' - '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' permissions: contents: read diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 0ee3b2bc649..edc22bc6505 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -1115,12 +1115,12 @@ jobs: src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts - src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts + src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts - src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts - src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts - src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts - src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts + src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts + src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts + src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts + src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts src/main/browser/extensions/profile-storage/browser-extension-persistence.electron.test.ts src/main/browser/extensions/profile-sessions/browser-extension-lifecycle.electron.test.ts diff --git a/cloud/apps/push/src/config.test.ts b/cloud/apps/push/src/config.test.ts deleted file mode 100644 index 44ad3430145..00000000000 --- a/cloud/apps/push/src/config.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { generateKeyPairSync } from 'node:crypto' - -import { describe, expect, it } from 'vitest' -import { loadPushConfig } from './config.js' - -function apnsKeyPem(): string { - return generateKeyPairSync('ec', { - namedCurve: 'P-256', - privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, - publicKeyEncoding: { type: 'spki', format: 'pem' } - }).privateKey -} - -const MINIMAL = { - ORCA_PUSH_PUBLIC_URL: 'https://push.onorca.dev', - ORCA_PUSH_FCM_PROJECT_ID: 'onorca-cloud' -} - -describe('push gateway config', () => { - - - - - it('requires an explicit FCM project instead of silently targeting production', () => { - expect(() => loadPushConfig({ ...MINIMAL, ORCA_PUSH_FCM_PROJECT_ID: undefined })).toThrow() - expect(() => loadPushConfig({ ...MINIMAL, ORCA_PUSH_FCM_PROJECT_ID: ' ' })).toThrow() - }) - - it('refuses a partial APNs credential', () => { - expect(() => loadPushConfig({ ...MINIMAL, ORCA_PUSH_APNS_KEY: apnsKeyPem() })).toThrow( - 'configured together' - ) - expect(() => - loadPushConfig({ - ...MINIMAL, - ORCA_PUSH_APNS_KEY: 'not-a-pem', - ORCA_PUSH_APNS_KEY_ID: 'ABCDE12345', - ORCA_PUSH_APPLE_TEAM_ID: 'TEAM123456' - }) - ).toThrow('PEM text') - }) - - it('requires a canonical HTTPS origin outside loopback', () => { - expect(() => - loadPushConfig({ ...MINIMAL, ORCA_PUSH_PUBLIC_URL: 'https://push.onorca.dev/v1' }) - ).toThrow('must be an origin') - expect(() => - loadPushConfig({ ...MINIMAL, ORCA_PUSH_PUBLIC_URL: 'http://push.onorca.dev' }) - ).toThrow('must use HTTPS') - expect( - loadPushConfig({ ...MINIMAL, ORCA_PUSH_PUBLIC_URL: 'http://localhost:8080' }).publicUrl - ).toBe('http://localhost:8080') - }) - - -}) diff --git a/cloud/apps/push/src/device-registry-store.test.ts b/cloud/apps/push/src/device-registry-store.test.ts index a5a2b944226..97f3e47acc5 100644 --- a/cloud/apps/push/src/device-registry-store.test.ts +++ b/cloud/apps/push/src/device-registry-store.test.ts @@ -148,24 +148,4 @@ describe('push device registry store', () => { (await devices.upsert({ ...androidDevice('device-0'), hostFingerprint: OTHER })).ok ).toBe(true) }) - - - - it('separates the same device id registered against two hosts', async () => { - const first = await upsertOk({ - hostFingerprint: OWNER, - deviceId: 'shared-device', - platform: 'ios', - token: 'a'.repeat(64), - apnsEnvironment: 'sandbox' - }) - const second = await upsertOk({ - hostFingerprint: OTHER, - deviceId: 'shared-device', - platform: 'ios', - token: 'c'.repeat(64), - apnsEnvironment: 'sandbox' - }) - expect(first).not.toBe(second) - }) }) 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/fcm-client.test.ts b/cloud/apps/push/src/fcm-client.test.ts index 70adcb8f180..107ef8c648d 100644 --- a/cloud/apps/push/src/fcm-client.test.ts +++ b/cloud/apps/push/src/fcm-client.test.ts @@ -1,4 +1,4 @@ -import { createHash } from 'node:crypto' + import { describe, expect, it } from 'vitest' import { FcmClient, type FcmRequest, type FcmResponse } from './fcm-client.js' import { buildPushDelivery } from './push-delivery-message.js' @@ -53,30 +53,6 @@ function client(response: FcmResponse) { describe('fcm client', () => { - it('carries every data value as a string and omits a null agent state', async () => { - const { fake, client: fcm } = client({ status: 200, body: '{}' }) - await fcm.send(delivery(null), { token: TOKEN }) - const message = JSON.parse(fake.requests[0]!.body) as { - message: { - android: Record - data: Record - } - } - expect(Object.values(message.message.data).every((value) => typeof value === 'string')).toBe( - true - ) - expect(message.message.data.agentState).toBeUndefined() - const tag = createHash('sha256') - .update(JSON.stringify([HOST, 'note-1'])) - .digest('hex') - expect(message.message.data.coalescedCount).toBeUndefined() - expect(message.message.data.tag).toBe(tag) - expect(message.message.android).not.toHaveProperty('collapse_key') - expect(message.message).not.toHaveProperty('notification') - expect(message.message.data).not.toHaveProperty('body') - }) - - it('marks an invalid-argument that names the token dead, and others an error', async () => { const named = client({ 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/cloud/apps/push/src/push-readiness.test.ts b/cloud/apps/push/src/push-readiness.test.ts deleted file mode 100644 index 45a57da4330..00000000000 --- a/cloud/apps/push/src/push-readiness.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { createPushReadiness } from './push-readiness.js' -import type { PushDatabase } from './push-database.js' - -it('shares a slow check and caches failures before retrying', async () => { - let clock = 0 - let reject!: (error: Error) => void - const query = vi.fn( - () => - new Promise((_, fail) => { - reject = fail - }) - ) - const ready = createPushReadiness({ query } as unknown as PushDatabase, { now: () => clock }) - const checks = Array.from({ length: 100 }, () => ready()) - expect(query).toHaveBeenCalledTimes(1) - reject(new Error('offline')) - expect(await Promise.all(checks)).toEqual(Array(100).fill(false)) - expect(await ready()).toBe(false) - expect(query).toHaveBeenCalledTimes(1) - clock = 10_000 - const retry = ready() - expect(query).toHaveBeenCalledTimes(2) - reject(new Error('offline')) - expect(await retry).toBe(false) -}) diff --git a/cloud/apps/relay-edge/src/env.ts b/cloud/apps/relay-edge/src/env.ts index 31de529480a..88cb6a0ca06 100644 --- a/cloud/apps/relay-edge/src/env.ts +++ b/cloud/apps/relay-edge/src/env.ts @@ -21,6 +21,9 @@ export type Env = { PING_INTERVAL_MS: string SILENCE_TIMEOUT_MS: string ORPHAN_GRACE_MS: string + // '0' stops offering the host-sent keepalive (host-relay-control.ts) and pings every control from + // the alarm again, including controls that took the offer earlier. Default: offered. + CLIENT_KEEPALIVE?: string // Object backend: store cleanup cadence (default 24 h) and how long an object keeps the data of // a host that moved away before wiping it (default 30 days). Tests shorten both. SWEEP_INTERVAL_MS?: string @@ -69,6 +72,7 @@ export type EdgeConfig = { orphanGraceMs: number sweepIntervalMs: number leftRetentionMs: number + clientKeepalive: boolean } const configs = new WeakMap() @@ -109,8 +113,11 @@ export function edgeConfig(env: Env): EdgeConfig { silenceTimeoutMs: positiveInt('silence_timeout', env.SILENCE_TIMEOUT_MS), orphanGraceMs: positiveInt('orphan_grace', env.ORPHAN_GRACE_MS), sweepIntervalMs: positiveInt('sweep_interval', env.SWEEP_INTERVAL_MS ?? String(24 * 60 * 60 * 1000)), - leftRetentionMs: positiveInt('left_retention', env.LEFT_RETENTION_MS ?? String(30 * 24 * 60 * 60 * 1000)) + leftRetentionMs: positiveInt('left_retention', env.LEFT_RETENTION_MS ?? String(30 * 24 * 60 * 60 * 1000)), + clientKeepalive: env.CLIENT_KEEPALIVE !== '0' } + // The offer carries the ping interval, which the contract bounds to 1..60 s. + config.clientKeepalive &&= config.pingIntervalMs >= 1_000 && config.pingIntervalMs <= 60_000 // Shipped desktops close a control that is silent for 75 s; a ping must arrive well inside it. if (config.pingIntervalMs >= config.silenceTimeoutMs) { throw new Error('relay_edge_config_ping_interval') } configs.set(env, config) diff --git a/cloud/apps/relay-edge/src/host-relay-base.ts b/cloud/apps/relay-edge/src/host-relay-base.ts index 672887fbc88..f3f34839b10 100644 --- a/cloud/apps/relay-edge/src/host-relay-base.ts +++ b/cloud/apps/relay-edge/src/host-relay-base.ts @@ -7,6 +7,7 @@ import { RELAY_CLOSE_CODE } from '../../../packages/relay-contract/src/close-cod import { CONTROL_CONTINUITY_LIMITS } from '../../../packages/relay-contract/src/control-continuity' import { ASSIGNMENT_LIMITS } from '../../../packages/relay-contract/src/assignment-invariants' import { relayHostCloseReasonFrom } from '../../../packages/relay-contract/src/host-close-reason' +import { RELAY_CLIENT_KEEPALIVE_ACK_FRAME, RELAY_CLIENT_KEEPALIVE_FRAME } from '../../../packages/relay-contract/src/control-messages' import { parseConnId } from './splice-slot' import { metric } from './metrics' import { ObjectStore } from './object-store' @@ -39,6 +40,11 @@ export type ControlAttachment = { lastRefreshAt?: number // Client ingress '/', for metrics. place?: string + // The host took the keepalive offer: it sends the keepalive frame, which the runtime answers + // without waking this object, so the alarm sends it no pings (keepalive() below). + clientKeepalive?: boolean + // A keepalive control found silent: one relay ping sent at this time (see probeSilentControls). + probeAt?: number } export type Attachment = ControlAttachment export type Conn = { @@ -65,6 +71,8 @@ export type AuthorizeResult = export type ConfirmResult = { ok: true; hello: RelayHello } | { ok: false; code: number } export const NO_DEADLINE = Number.MAX_SAFE_INTEGER +// How long a silent keepalive control has to answer the relay ping before it is closed. +export const KEEPALIVE_PROBE_MS = 10_000 export const SWEEP_AT_KEY = 'sweepAt' // 6 h ± 30 min, as the cells: desktops re-ask the director at least this often. export const LEASE_BASE_MS = 6 * 60 * 60 * 1000 @@ -80,6 +88,12 @@ export abstract class HostRelayBase extends DurableObject { protected recentPicks: { slot: number; at: number }[] = [] protected backendCache: EdgeBackend | null = null + constructor(ctx: DurableObjectState, env: Env) { + super(ctx, env) + // Answered by the runtime while the object sleeps: no wake, no alarm, no duration. + ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(RELAY_CLIENT_KEEPALIVE_FRAME, RELAY_CLIENT_KEEPALIVE_ACK_FRAME)) + } + protected get config(): EdgeConfig { return edgeConfig(this.env) } @@ -101,6 +115,17 @@ export abstract class HostRelayBase extends DurableObject { return a.phase === 'active' && now <= a.claims.exp } + // Host-sent keepalive in use for this control (and not switched off since it was offered). + protected keepalive(a: ControlAttachment): boolean { + return a.clientKeepalive === true && this.config.clientKeepalive + } + + // Last sign of life: any frame that woke the object, or a keepalive the runtime answered. + protected lastSeen(ws: WebSocket, a: ControlAttachment): number { + const answered = this.ctx.getWebSocketAutoResponseTimestamp(ws)?.getTime() ?? 0 + return Math.max(a.lastPongAt ?? 0, answered) + } + protected otherActiveControls(ws: WebSocket): WebSocket[] { return this.ctx.getWebSockets('control').filter((s) => s !== ws && this.attachment(s)?.phase === 'active') } @@ -144,7 +169,9 @@ export abstract class HostRelayBase extends DurableObject { // ---------------- lifecycle ---------------- - protected async onSocketGone(ws: WebSocket, code: number, reason: string): Promise { + // `goneAt`: when the control was last known alive plus the silence timeout, for a control found + // dead later than the alarm would have found it; the orphan grace counts from then. + protected async onSocketGone(ws: WebSocket, code: number, reason: string, goneAt = Date.now()): Promise { const a = this.attachment(ws) if (!a) { return } // During webSocketClose the closing socket is still listed; clear it first so it can't count as live. @@ -156,7 +183,7 @@ export abstract class HostRelayBase extends DurableObject { const hostReason = relayHostCloseReasonFrom(reason) await this.ctx.storage.put('session', { ...session, - orphanedAt: Date.now(), + orphanedAt: goneAt, ...(hostReason ? { closeReason: { reason: hostReason, expiresAt: Date.now() + ASSIGNMENT_LIMITS.dormantTtlMs } } : {}) }) } @@ -168,19 +195,32 @@ export abstract class HostRelayBase extends DurableObject { protected async reschedule(): Promise { let next = NO_DEADLINE + let conns: Record | null = null for (const ws of this.ctx.getWebSockets()) { const a = this.attachment(ws) if (!a) { continue } + if (a.k !== 'control' || a.phase !== 'active') { + next = Math.min(next, a.deadline) + continue + } next = Math.min( next, - ...(a.k === 'control' && a.phase === 'active' - ? [ - (a.lastPingAt ?? 0) + this.config.pingIntervalMs, - a.claims.exp + CONTROL_CONTINUITY_LIMITS.expiredAuthExistingSpliceGraceMs + 1, - (a.leaseExpiresAt ?? NO_DEADLINE - 1) + 1 - ] - : [a.deadline]) + a.claims.exp + CONTROL_CONTINUITY_LIMITS.expiredAuthExistingSpliceGraceMs + 1, + (a.leaseExpiresAt ?? NO_DEADLINE - 1) + 1 ) + if (!this.keepalive(a)) { + next = Math.min(next, (a.lastPingAt ?? 0) + this.config.pingIntervalMs) + continue + } + const seen = this.lastSeen(ws, a) + if (a.probeAt !== undefined && a.probeAt >= seen) { + next = Math.min(next, a.probeAt + KEEPALIVE_PROBE_MS) + continue + } + // Phones attached or waiting: their splices must close on time if the host dies, so check + // its silence when it would run out. Otherwise no alarm for liveness at all. + conns ??= await this.conns() + if (Object.keys(conns).length > 0) { next = Math.min(next, seen + this.config.silenceTimeoutMs + 1) } } const session = await this.ctx.storage.get('session') if (session?.orphanedAt != null) { next = Math.min(next, session.orphanedAt + this.config.orphanGraceMs) } diff --git a/cloud/apps/relay-edge/src/host-relay-control.ts b/cloud/apps/relay-edge/src/host-relay-control.ts index dddb466028d..16697097b1c 100644 --- a/cloud/apps/relay-edge/src/host-relay-control.ts +++ b/cloud/apps/relay-edge/src/host-relay-control.ts @@ -1,6 +1,6 @@ -// HostRelay control frames once a host is past the handshake: liveness, pongs, auth refresh and +// HostRelay control frames once a host is past the handshake: liveness, pongs, keepalives, auth refresh and // the host's credential commands. -import { AuthRefreshSchema, DeviceRevokeSchema, InviteCreateSchema } from '../../../packages/relay-contract/src/control-messages' +import { AuthRefreshSchema, DeviceRevokeSchema, InviteCreateSchema, RELAY_CLIENT_KEEPALIVE_ACK_FRAME } from '../../../packages/relay-contract/src/control-messages' import { DeviceCredentialInstallSchema, DeviceCredentialInstallStatusSchema, DeviceResumeConfirmSchema } from '../../../packages/relay-contract/src/credential-messages' import { RELAY_CLOSE_CODE } from '../../../packages/relay-contract/src/close-codes' import { RELAY_PROTOCOL_LIMITS } from '../../../packages/relay-contract/src/protocol-limits' @@ -12,6 +12,45 @@ import { HostRelayHandshake } from './host-relay-handshake' import type { ControlAttachment } from './host-relay-base' export abstract class HostRelayControl extends HostRelayHandshake { + // ---------------- silent keepalive controls ---------------- + + // Active controls silent past the timeout. No liveness field (attachments older than it): the + // alarm judges those, as before. + protected silentControls(now: number): { ws: WebSocket; a: ControlAttachment; seen: number }[] { + return this.ctx.getWebSockets('control').flatMap((ws) => { + const a = this.attachment(ws) + if (a?.k !== 'control' || a.phase !== 'active' || a.lastPongAt === undefined) { return [] } + const seen = this.lastSeen(ws, a) + return now - seen > this.config.silenceTimeoutMs ? [{ ws, a, seen }] : [] + }) + } + + // Where the host is going away anyway (export, erase, drain, a new control of the same host): a + // silent control is closed now. Its orphan time is the latest the ping alarm would have found it, + // so rebind and the orphan grace are never shorter than before. + protected async closeSilentControls(now = Date.now()): Promise { + for (const { ws, seen } of this.silentControls(now)) { + this.close(ws, RELAY_CLOSE_CODE.PEER_DROPPED, 'control silence timeout') + await this.onSocketGone(ws, RELAY_CLOSE_CODE.PEER_DROPPED, '', Math.min(now, seen + this.config.silenceTimeoutMs + this.config.pingIntervalMs)) + } + } + + // Where a phone needs the host: a silent keepalive control may be alive with its own timer held + // back (a sleeping app), so it is sent one relay ping, answered from socket I/O, and closed only if + // nothing arrives within KEEPALIVE_PROBE_MS (alarm). Meanwhile it counts as live, as a control + // inside the silence timeout always did. + protected async probeSilentControls(now = Date.now()): Promise { + let probed = false + for (const { ws, a, seen } of this.silentControls(now)) { + if (!this.keepalive(a) || (a.probeAt !== undefined && a.probeAt >= seen)) { continue } + this.send(ws, { type: 'ping', t: now }) + a.probeAt = now + this.attach(ws, a) + probed = true + } + if (probed) { await this.reschedule() } + } + // ---------------- control ---------------- protected async onControl(ws: WebSocket, a: ControlAttachment, message: string | ArrayBuffer): Promise { @@ -47,6 +86,12 @@ export abstract class HostRelayControl extends HostRelayHandshake { if (typeof body.t === 'number') { metric(this.env, 'pong_rtt_ms', now - body.t, '', [], '', a.place) } return } + // Normally answered by the runtime (host-relay-base.ts); a frame that differs only in spacing + // still gets its answer here. + if (type === 'keepalive') { + ws.send(RELAY_CLIENT_KEEPALIVE_ACK_FRAME) + return + } if (type === 'auth-refresh') { return this.onAuthRefresh(ws, body) } return this.onCommand(ws, a, type, body) } diff --git a/cloud/apps/relay-edge/src/host-relay-handshake.ts b/cloud/apps/relay-edge/src/host-relay-handshake.ts index ca9d83498d7..bc153be8a0c 100644 --- a/cloud/apps/relay-edge/src/host-relay-handshake.ts +++ b/cloud/apps/relay-edge/src/host-relay-handshake.ts @@ -2,7 +2,7 @@ // eligibility, and the proof that activates a control (generation, resume secret, pending conns). import nacl from 'tweetnacl' import { buildHostChallengePlaintext, buildHostProofMacInput, buildHostProofTranscript } from '../../../packages/relay-contract/src/host-proof-transcript' -import { HostChallengeAckSchema, HostHelloSchema, RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS } from '../../../packages/relay-contract/src/control-messages' +import { HostChallengeAckSchema, HostHelloSchema, RELAY_HOST_CAPABILITY_CLIENT_KEEPALIVE, RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS } from '../../../packages/relay-contract/src/control-messages' import { RELAY_CLOSE_CODE } from '../../../packages/relay-contract/src/close-codes' import { metric } from './metrics' import type { EdgeClaims } from './env' @@ -162,6 +162,7 @@ export abstract class HostRelayHandshake extends HostRelayBase { a.lastPingAt = now a.leaseExpiresAt = leaseExpiresAt a.deadline = NO_DEADLINE + a.clientKeepalive = this.config.clientKeepalive && a.caps.includes(RELAY_HOST_CAPABILITY_CLIENT_KEEPALIVE) delete a.expectedProof delete a.hello delete a.rebind @@ -188,6 +189,8 @@ export abstract class HostRelayHandshake extends HostRelayBase { activeConnIds: activeConnIds.slice(0, 8), pendingConns: pendingConns.slice(0, 8) }) + // After the ack, which strict shipped parsers must see unchanged; only hosts that asked get it. + if (a.clientKeepalive) { this.send(ws, { type: 'keepalive-offer', v: 1, intervalMs: this.config.pingIntervalMs }) } metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [], '', a.place) await this.reschedule() } diff --git a/cloud/apps/relay-edge/src/host-relay-phones.ts b/cloud/apps/relay-edge/src/host-relay-phones.ts index 22e5da6a35d..f9278f9589e 100644 --- a/cloud/apps/relay-edge/src/host-relay-phones.ts +++ b/cloud/apps/relay-edge/src/host-relay-phones.ts @@ -61,6 +61,8 @@ export abstract class HostRelayPhones extends HostRelayControl { return { ok: false, code: RELAY_CLOSE_CODE.DRAINING } } if (!reservation) { return { ok: false, code: RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL } } + // A keepalive host may have died unnoticed (no alarm watches an idle one): probe it first. + await this.probeSilentControls() const control = this.activeControl() const seated = control !== null && @@ -95,6 +97,8 @@ export abstract class HostRelayPhones extends HostRelayControl { relayDeviceId: reservation.relayDeviceId, attachDeadlineMs: RELAY_PROTOCOL_LIMITS.hostAttachDeadlineMs }) + // The first phone of a keepalive host arms its silence check (reschedule). + if (this.keepalive(control.a)) { await this.reschedule() } return { ok: true, connTicket, generation } } diff --git a/cloud/apps/relay-edge/src/host-relay.ts b/cloud/apps/relay-edge/src/host-relay.ts index 397b9dd3844..958232f8ff4 100644 --- a/cloud/apps/relay-edge/src/host-relay.ts +++ b/cloud/apps/relay-edge/src/host-relay.ts @@ -16,7 +16,7 @@ import type { AssignBody, DeviceRow } from './admin' import { ADMIN_JTI_KEY, admitJti, type AdminReplayGuard, type ReplayRefusal, type SeenJtis } from './admin-jti' import type { AssignResult, StoredAssignment } from './object-store' import type { EdgeClaims } from './env' -import { SWEEP_AT_KEY, type Session } from './host-relay-base' +import { KEEPALIVE_PROBE_MS, SWEEP_AT_KEY, type Session } from './host-relay-base' import { HostRelayPhones } from './host-relay-phones' export type { AuthorizeResult, ConfirmResult } from './host-relay-base' @@ -48,6 +48,7 @@ export class HostRelay extends HostRelayPhones { > { const refused = await this.claimAdminJti(replay) if (refused) { return refused } + await this.closeSilentControls() if (this.liveControls().length > 0) { return { outcome: 'busy' } } const devices = this.store.freezeForExport() await this.closeSplices(() => true, RELAY_CLOSE_CODE.WRONG_CELL, 'host moving') @@ -64,7 +65,8 @@ export class HostRelay extends HostRelayPhones { const assignment = this.store.assignment() // Another account now holds this machine's object; its move on wiped the earlier account's data. if (assignment && assignment.userId !== userId) { return { outcome: 'mismatch' } } - if (this.ctx.getWebSockets('control').length > 0 || this.store.activeBases() > 0) { return { outcome: 'busy' } } + await this.closeSilentControls() + if (this.liveControls().length > 0 || this.store.activeBases() > 0) { return { outcome: 'busy' } } await this.ctx.storage.deleteAlarm() await this.ctx.storage.deleteAll() this.storeCache = null @@ -76,6 +78,7 @@ export class HostRelay extends HostRelayPhones { // desktop re-asks the director), and goes through the same path as that expiry. The assignment, // devices and splices are left as they are. async adminDrain(replay?: AdminReplayGuard | null): Promise { + await this.closeSilentControls() const controls = this.liveControls() // An idle drain of a host nobody pushed changes nothing and must not give the object storage, // so its jti is not recorded; a copy of that token can at most drain a control that arrived @@ -128,6 +131,8 @@ export class HostRelay extends HostRelayPhones { }) } if (kind !== 'control') { return new Response(null, { status: 404 }) } + // A new control's hello decides rebind against the controls still listed. + await this.closeSilentControls() const origin = request.headers.get('x-edge-origin') ?? '' const claims = JSON.parse(request.headers.get('x-edge-claims') ?? 'null') as EdgeClaims const pair = new WebSocketPair() @@ -166,7 +171,15 @@ export class HostRelay extends HostRelayPhones { const a = this.attachment(ws) if (!a) { continue } if (a.k === 'control' && a.phase === 'active') { - if (now - (a.lastPongAt ?? now) > this.config.silenceTimeoutMs) { + const seen = a.lastPongAt === undefined ? now : this.lastSeen(ws, a) + // A keepalive control gets one relay ping first (probeSilentControls); closed if it stays silent. + if (this.keepalive(a) && now - seen > this.config.silenceTimeoutMs && (a.probeAt === undefined || a.probeAt < seen)) { + this.send(ws, { type: 'ping', t: now }) + a.probeAt = now + this.attach(ws, a) + continue + } + if (now - seen > this.config.silenceTimeoutMs && (!this.keepalive(a) || now - a.probeAt! >= KEEPALIVE_PROBE_MS - 50)) { this.close(ws, RELAY_CLOSE_CODE.PEER_DROPPED, 'control silence timeout') await this.onSocketGone(ws, RELAY_CLOSE_CODE.PEER_DROPPED, '') continue @@ -185,7 +198,7 @@ export class HostRelay extends HostRelayPhones { await this.onSocketGone(ws, RELAY_CLOSE_CODE.DRAINING, '') continue } - if (now - (a.lastPingAt ?? 0) >= this.config.pingIntervalMs - 50) { + if (!this.keepalive(a) && now - (a.lastPingAt ?? 0) >= this.config.pingIntervalMs - 50) { if (a.lastPingAt) { metric(this.env, 'alarm_lag_ms', Math.max(0, now - (a.lastPingAt + this.config.pingIntervalMs)), '', [], '', a.place) } this.send(ws, { type: 'ping', t: now }) a.lastPingAt = now diff --git a/cloud/apps/relay-edge/test/harness-mvp-object.ts b/cloud/apps/relay-edge/test/harness-mvp-object.ts index aedc78680d6..89ec43b1e7c 100644 --- a/cloud/apps/relay-edge/test/harness-mvp-object.ts +++ b/cloud/apps/relay-edge/test/harness-mvp-object.ts @@ -59,8 +59,10 @@ export async function mint(key: KeyLike, relayHostId: string, issuer = ISSUER): } // `drop` returns true for an outbound frame the test wants lost (a host that stops answering pings). -export function control(host: Host, jwt: string, epoch = EPOCH, opts: { drop?: (frame: string) => boolean } = {}) { - const events = { closes: [] as number[], opens: [] as { connId: string }[], drains: [] as Record[], dropped: 0 } +// `caps` replaces the shipped desktop's capability header (default: as shipped today). +export const SHIPPED_CAPS = 'pending-conn-details,idle-regional-rehome-v1' +export function control(host: Host, jwt: string, epoch = EPOCH, opts: { drop?: (frame: string) => boolean; caps?: string } = {}) { + const events = { closes: [] as number[], opens: [] as { connId: string }[], drains: [] as Record[], dropped: 0, pings: 0, offers: 0, acks: 0 } let transport: CloudRelayTransport | null = null const client = new RelayControlClient({ cellUrl: ORIGIN, @@ -78,10 +80,16 @@ export function control(host: Host, jwt: string, epoch = EPOCH, opts: { drop?: ( onClose: (code) => events.closes.push(code), createSocket: (url, token) => { const ws = new WebSocket(url, { - headers: { authorization: `Bearer ${token}`, 'x-orca-host-capabilities': 'pending-conn-details,idle-regional-rehome-v1' }, + headers: { authorization: `Bearer ${token}`, 'x-orca-host-capabilities': opts.caps ?? process.env.MVP_HOST_CAPS ?? SHIPPED_CAPS }, perMessageDeflate: false, maxPayload: 64 * 1024 }) + ws.on('message', (raw) => { + const type = (JSON.parse(raw.toString()) as { type?: unknown }).type + if (type === 'ping') { events.pings++ } + if (type === 'keepalive-offer') { events.offers++ } + if (type === 'keepalive-ack') { events.acks++ } + }) const send = ws.send.bind(ws) ws.send = ((data: string, ...rest: never[]) => { if (opts.drop?.(String(data))) { diff --git a/cloud/apps/relay-edge/test/mvp-object-hardening.ts b/cloud/apps/relay-edge/test/mvp-object-hardening.ts index a304dabe9e4..5bd6553acab 100644 --- a/cloud/apps/relay-edge/test/mvp-object-hardening.ts +++ b/cloud/apps/relay-edge/test/mvp-object-hardening.ts @@ -5,7 +5,7 @@ import { readdirSync } from 'node:fs' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' import type { KeyLike } from 'jose' -import { EPOCH, ORIGIN, adminCall, assign, control, mint, newHost, record, sleep, waitFor } from './harness-mvp-object' +import { EPOCH, ORIGIN, SHIPPED_CAPS, adminCall, assign, control, mint, newHost, record, sleep, waitFor } from './harness-mvp-object' // Local timing (mvp-object.ts): ping every 3 s, silence timeout 9 s. const SILENCE_MS = 9_000 @@ -47,6 +47,87 @@ export async function heartbeatCheck(key: KeyLike): Promise { } } +// K1: host-sent keepalive. A host advertising client-keepalive-v1 gets the offer, then sends the +// keepalive, which the runtime answers: the edge sends it no pings and it stays up. One that goes +// silent is not watched by any alarm while idle, but is closed 4408 the moment the director needs +// the host (export), and a live one is not. A host without the capability is pinged as before. +export async function keepaliveCheck(key: KeyLike): Promise { + const caps = `${SHIPPED_CAPS},client-keepalive-v1` + const liveHost = newHost() + const silentHost = newHost() + const legacyHost = newHost() + await Promise.all([liveHost, silentHost, legacyHost].map((h) => assign(h.relayHostId, 'edge', EPOCH, []))) + let muted = false + const live = control(liveHost, await mint(key, liveHost.relayHostId), EPOCH, { caps }) + const silent = control(silentHost, await mint(key, silentHost.relayHostId), EPOCH, { caps, drop: () => muted }) + const legacy = control(legacyHost, await mint(key, legacyHost.relayHostId)) + // Its keepalive timer stalls (a throttled app) but it still answers relay pings from socket I/O. + const nappingHost = newHost() + await assign(nappingHost.relayHostId, 'edge', EPOCH, []) + const napping = control(nappingHost, await mint(key, nappingHost.relayHostId), EPOCH, { caps, drop: (f) => muted && f === '{"type":"keepalive"}' }) + await Promise.all([live.client.connect(), silent.client.connect(), legacy.client.connect(), napping.client.connect()]) + try { + await sleep(1_000) + muted = true + await sleep(SILENCE_MS + 4_000) + record( + 'K1 keepalive host: offered, answered, no edge pings, up past the silence timeout', + live.events.offers === 1 && live.events.acks >= 3 && live.events.pings === 0 && live.client.isLive() && live.events.closes.length === 0, + `offers=${live.events.offers} acks=${live.events.acks} pings=${live.events.pings} closes=${live.events.closes}` + ) + record( + 'K1 host without the capability: no offer, pinged as before', + legacy.events.offers === 0 && legacy.events.pings >= 3 && legacy.client.isLive(), + `offers=${legacy.events.offers} pings=${legacy.events.pings}` + ) + // Local sweep alarm every 3 s: it finds the napping host silent and probes it with a relay ping. + record( + 'K2 keepalive host with a stalled timer: probed with a relay ping, answers, stays up', + napping.events.pings >= 1 && napping.client.isLive() && napping.events.closes.length === 0, + `pings=${napping.events.pings} dropped=${napping.events.dropped} closes=${napping.events.closes}` + ) + const nappingExport = await adminCall('export', { relayHostId: nappingHost.relayHostId }) + record('K2 export of the probed, answering host: busy', nappingExport.json?.outcome === 'busy', JSON.stringify(nappingExport.json?.outcome)) + const liveExport = await adminCall('export', { relayHostId: liveHost.relayHostId }) + const silentExport = await adminCall('export', { relayHostId: silentHost.relayHostId }) + await waitFor(() => silent.events.closes.length > 0, 3_000) + record( + 'K1 export: live keepalive host busy; silent one closed 4408 and exported', + liveExport.json?.outcome === 'busy' && silentExport.json?.outcome === 'exported' && silent.events.closes.includes(4408) && live.events.closes.length === 0, + `live=${JSON.stringify(liveExport.json?.outcome)} silent=${JSON.stringify(silentExport.json?.outcome)} closes=${silent.events.closes}` + ) + } finally { + live.client.closeNow() + silent.client.closeNow() + legacy.client.closeNow() + napping.client.closeNow() + } +} + +// K3: a keepalive host that goes fully silent is probed when an alarm runs (here the local 3 s +// sweep; in production the silence check armed while phones are attached), and closed 4408 when +// the probe goes unanswered: silence timeout plus the 10 s probe. +export async function keepaliveProbeCheck(key: KeyLike): Promise { + const host = newHost() + await assign(host.relayHostId, 'edge', EPOCH, []) + let muted = false + const c = control(host, await mint(key, host.relayHostId), EPOCH, { caps: `${SHIPPED_CAPS},client-keepalive-v1`, drop: () => muted }) + await c.client.connect() + muted = true + const started = Date.now() + try { + const closed = await waitFor(() => c.events.closes.length > 0, SILENCE_MS + 10_000 + 8_000) + const after = Date.now() - started + record( + 'K3 silent keepalive host: probed, then closed 4408 after the silence timeout plus the probe', + closed && c.events.closes.includes(4408) && c.events.pings >= 1 && after >= SILENCE_MS + 10_000 - 500, + `closedAfter=${after}ms pings=${c.events.pings} closes=${c.events.closes}` + ) + } finally { + c.client.closeNow() + } +} + // F5: POST /__admin/drain sends the host's controls back to the director (drain frame, 4503). export async function drainCheck(key: KeyLike): Promise { const host = newHost() diff --git a/cloud/apps/relay-edge/test/mvp-object.ts b/cloud/apps/relay-edge/test/mvp-object.ts index 8183bd102ba..5558bb2d179 100644 --- a/cloud/apps/relay-edge/test/mvp-object.ts +++ b/cloud/apps/relay-edge/test/mvp-object.ts @@ -41,7 +41,7 @@ import { waitFor, type Host } from './harness-mvp-object' -import { drainCheck, heartbeatCheck, objectHealthCheck } from './mvp-object-hardening' +import { drainCheck, heartbeatCheck, keepaliveCheck, keepaliveProbeCheck, objectHealthCheck } from './mvp-object-hardening' import { replayCheck, rotationCheck } from './mvp-object-replay' async function mainRemote(): Promise { @@ -107,7 +107,7 @@ async function main(): Promise { await sleep(500) } await run(host, privateKey, () => jwksHits) - await Promise.all([heartbeatCheck(privateKey), drainCheck(privateKey), replayCheck(), rotationCheck()]) + await Promise.all([heartbeatCheck(privateKey), keepaliveCheck(privateKey), keepaliveProbeCheck(privateKey), drainCheck(privateKey), replayCheck(), rotationCheck()]) await sweepCheck() await preAuthCheck(stateDir) await objectHealthCheck(stateDir) diff --git a/cloud/packages/relay-contract/src/control-messages.ts b/cloud/packages/relay-contract/src/control-messages.ts index c7b74de118a..bc7c8ffda89 100644 --- a/cloud/packages/relay-contract/src/control-messages.ts +++ b/cloud/packages/relay-contract/src/control-messages.ts @@ -51,6 +51,20 @@ export const RELAY_ASSIGNMENT_LEASE_HEADER = 'x-orca-relay-assignment-lease' // Advertise before sending pendingConns details: legacy strict parsers would reject the entire ack. export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' export const RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME = 'idle-regional-rehome-v1' +// The host can send the keepalive below. A relay that supports it says so with a keepalive-offer +// after the hello-ack; only then does the host send it. Relays that never offer keep pinging. +export const RELAY_HOST_CAPABILITY_CLIENT_KEEPALIVE = 'client-keepalive-v1' +// Exact frames: the edge answers the request without waking the host's object, so they never vary. +export const RELAY_CLIENT_KEEPALIVE_FRAME = '{"type":"keepalive"}' +export const RELAY_CLIENT_KEEPALIVE_ACK_FRAME = '{"type":"keepalive-ack"}' + +export const KeepaliveOfferSchema = z + .object({ + type: z.literal('keepalive-offer'), + v: z.literal(1), + intervalMs: z.number().int().min(1_000).max(60_000) + }) + .strict() export function parseRelayHostCapabilities( header: string | string[] | undefined diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index d0b3c431611..56905221b8e 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -1,13 +1,16 @@ // The CLI loads these paths after electron-vite replaces out/main. export const CLI_MAIN_ENTRY_NAMES = [ - 'agent-hooks/managed-agent-hook-controls', + 'agent-hooks/installation/managed-agent-hook-controls', 'gitlab/project-ref-parser', 'orca-profiles/profile-index-store', 'claude-accounts/keychain', + // The CLI checks a relocated runtime socket dir before it sends the auth token. + 'daemon/endpoint/publication/daemon-socket-endpoint-path', 'skills/bundled-skill-install/bundled-skill-local-host', '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/electron-builder.config.cjs b/config/electron-builder.config.cjs index 800c2d36089..a727851532d 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -345,6 +345,8 @@ module.exports = { 'out/main/antigravity/**', 'out/main/claude/**', 'out/main/codex/**', + // The CLI loads the socket-dir check; tsc-emitted output also needs its mode constants beside it. + 'out/main/daemon/endpoint/publication/daemon-{socket-endpoint-path,private-file-modes}.js', 'out/main/copilot/**', 'out/main/cursor/**', 'out/main/droid/**', @@ -372,6 +374,7 @@ module.exports = { '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 808de3a90be..b0f4d7fe4d4 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -2,7 +2,6 @@ # This is a RATCHET: counts may only go DOWN. Run `pnpm lint:ast-grep:flaky-tests` to list them. # Prune after a fix: pnpm check:flaky-test-pattern-ratchet --prune 1 test-no-in-test-import-actual:src/cli/runtime/launch-serve-replaced-app-restart.test.ts -1 test-no-in-test-import-actual:src/main/agent-hooks/server-status-persist-nonblocking.test.ts 1 test-no-in-test-import-actual:src/main/bitbucket/credential-connection.test.ts 4 test-no-in-test-import-actual:src/main/bitbucket/credential-store.test.ts 1 test-no-in-test-import-actual:src/main/bitbucket/status-no-decrypt.test.ts @@ -148,22 +147,21 @@ 1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts 2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts 1 test-no-real-time-wait:mobile/src/terminal/terminal-webview-tap-routing.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts -3 test-no-real-time-wait:src/main/agent-hooks/server-copilot-normalization.test.ts -2 test-no-real-time-wait:src/main/agent-hooks/server-transport-interference.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/server-turn-ended-at.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/server-turn-started-at.test.ts -5 test-no-real-time-wait:src/main/agent-hooks/wsl-hook-relay-manager.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts +2 test-no-real-time-wait:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts +5 test-no-real-time-wait:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts 2 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-scan-scope.test.ts 1 test-no-real-time-wait:src/main/antigravity/windows-hook-json-post.test.ts 1 test-no-real-time-wait:src/main/antigravity/windows-hook-payload-delivery.test.ts 1 test-no-real-time-wait:src/main/browser/cdp/input/guest-focused-frame-route.test.ts 3 test-no-real-time-wait:src/main/browser/cookies/browser-cookie-import-concurrency.test.ts -2 test-no-real-time-wait:src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts -1 test-no-real-time-wait:src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts -1 test-no-real-time-wait:src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts -1 test-no-real-time-wait:src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts +2 test-no-real-time-wait:src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts +1 test-no-real-time-wait:src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts +1 test-no-real-time-wait:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts +1 test-no-real-time-wait:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/execution-route-socket-duplex.test.ts 1 test-no-real-time-wait:src/main/browser/network/tunnels/remote-browser-socks-server.test.ts 1 test-no-real-time-wait:src/main/claude-accounts/claude-login-session.test.ts @@ -224,7 +222,6 @@ 1 test-no-real-time-wait:src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-quit.test.ts -1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-target-reconcile.test.ts 1 test-no-real-time-wait:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 2 test-no-real-time-wait:src/main/provider-process/provider-process-supervisor.integration.test.ts @@ -253,7 +250,7 @@ 3 test-no-real-time-wait:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 1 test-no-real-time-wait:src/main/skills/cloud/skill-cloud-direct-upload.test.ts 2 test-no-real-time-wait:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts -4 test-no-real-time-wait:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts +1 test-no-real-time-wait:src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts 1 test-no-real-time-wait:src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent-shell.integration.test.ts 2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts 3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev.test.ts @@ -464,20 +461,18 @@ 1 test-no-wall-clock:config/scripts/worktree-storage/reclaim-release-test-caches.test.ts 1 test-no-wall-clock:mobile/scripts/native-build-cache.test.ts 1 test-no-wall-clock:mobile/src/pairing/mobile-relay-invite-director.test.ts -1 test-no-wall-clock:mobile/src/transport/relay/mobile-relay-resume-director.test.ts -1 test-no-wall-clock:src/cli/format.test.ts 2 test-no-wall-clock:src/cli/runtime/serve-appimage-update.test.ts 4 test-no-wall-clock:src/cli/runtime/serve-bundle-park.test.ts 5 test-no-wall-clock:src/cli/runtime/serve-pid1-init-reaper.test.ts 1 test-no-wall-clock:src/cli/runtime/status-caller.test.ts -2 test-no-wall-clock:src/main/agent-hooks/managed-hook-timeout.test.ts -2 test-no-wall-clock:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts -1 test-no-wall-clock:src/main/agent-hooks/server-codex-capacity.test.ts -1 test-no-wall-clock:src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts -3 test-no-wall-clock:src/main/agent-hooks/server-ingest-structured-status.test.ts -4 test-no-wall-clock:src/main/agent-hooks/server-launch-resume-identity.test.ts -5 test-no-wall-clock:src/main/agent-hooks/spool.test.ts -2 test-no-wall-clock:src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts +1 test-no-wall-clock:src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts +1 test-no-wall-clock:src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts +3 test-no-wall-clock:src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts +4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts +5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts 2 test-no-wall-clock:src/main/ai-vault-search/session-search-indexer.test.ts 1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts 1 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts @@ -623,7 +618,7 @@ 4 test-no-wall-clock:src/main/skills/runtime-upload/skill-upload-process-restart.integration.test.ts 4 test-no-wall-clock:src/main/sqlite/sync-database.test.ts 4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts -8 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence.test.ts +6 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence.test.ts 4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts 2 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts 4 test-no-wall-clock:src/main/ssh/remote-exec/ssh-remote-commands.test.ts @@ -706,15 +701,15 @@ 1 test-timeout-needs-reason:src/cli/runtime/serve-pid1-init-reaper.test.ts 1 test-timeout-needs-reason:src/cli/skills-install.test.ts 2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts -4 test-timeout-needs-reason:src/main/agent-hooks/server-transport-interference.test.ts -1 test-timeout-needs-reason:src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts -1 test-timeout-needs-reason:src/main/agent-hooks/wsl-hook-relay-manager.test.ts +4 test-timeout-needs-reason:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts +1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts +1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-timeout-needs-reason:src/main/ai-vault/parse-cache/session-parse-cache-large-scan.test.ts 1 test-timeout-needs-reason:src/main/antigravity/native-macos-credentials.real.test.ts 1 test-timeout-needs-reason:src/main/antigravity/posix-hook-invocation.test.ts 2 test-timeout-needs-reason:src/main/antigravity/windows-hook-json-post.test.ts 3 test-timeout-needs-reason:src/main/antigravity/windows-hook-payload-delivery.test.ts -1 test-timeout-needs-reason:src/main/browser/agent-browser/agent-browser-bridge-raw-process.test.ts +1 test-timeout-needs-reason:src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.test.ts 1 test-timeout-needs-reason:src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts 2 test-timeout-needs-reason:src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/cookies/browser-cookie-import-partition-rollback.electron.test.ts @@ -722,8 +717,8 @@ 1 test-timeout-needs-reason:src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts -1 test-timeout-needs-reason:src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts -2 test-timeout-needs-reason:src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts +1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts +2 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts 3 test-timeout-needs-reason:src/main/claude-usage/scanner-incremental-reader.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-agent-sdk-exit-proof.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-background-run-isolation-real-cli.test.ts @@ -786,8 +781,6 @@ 1 test-timeout-needs-reason:src/main/skills/install/skill-bundle-process-termination.integration.test.ts 1 test-timeout-needs-reason:src/main/sqlite/sync-database-concurrent-backup.test.ts 2 test-timeout-needs-reason:src/main/ssh/connection/ssh-connection-sftp-wire.test.ts -1 test-timeout-needs-reason:src/main/managed-server/activation/orcad-exited-own-fence.test.ts -1 test-timeout-needs-reason:src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts 2 test-timeout-needs-reason:src/main/ssh/system-transport/forwarding/system-ssh-forward-process-real-openssh.test.ts 2 test-timeout-needs-reason:src/main/startup/single-instance-lock-exit.electron.test.ts 1 test-timeout-needs-reason:src/main/window/renderer-publication-throttle.electron.test.ts diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 880c5474b33..1e553776daa 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -88,7 +88,7 @@ 4 src/renderer/src/components/settings/runtime-environments/catalog/RuntimeEnvironmentsPane.tsx 1 src/renderer/src/components/settings/runtime-environments/catalog/use-runtime-environment-mutation-actions.ts 1 src/renderer/src/components/settings/setup-guide/SettingsSetupGuidePane.tsx -2 src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts +1 src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts 1 src/renderer/src/components/settings/shortcuts/ShortcutsPane.tsx 3 src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx 2 src/renderer/src/components/settings/tasks/TasksPane.tsx diff --git a/config/knip.json b/config/knip.json index 516010bb4d9..c9fe794f998 100644 --- a/config/knip.json +++ b/config/knip.json @@ -15,7 +15,7 @@ "src/main/worker-thread-child-process/worker-thread-child-process-entry.ts", "src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts", "src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts", - "src/main/agent-hooks/managed-agent-hook-controls.ts", + "src/main/agent-hooks/installation/managed-agent-hook-controls.ts", "src/main/claude-accounts/keychain.ts", "src/renderer/src/main.tsx", "src/renderer/src/popout.tsx", diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 639a055288a..096973f7717 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -29,7 +29,6 @@ 3 src/main/persistence/loading-store/state-serialization-secret-handling.ts 4 src/main/persistence/loading-store/workspace-session-snapshot-publication.ts 4 src/main/persistence/loading-store/workspace-session-terminal-binding-replay.ts -2 src/main/persistence/loading-store/workspace-session-write-listeners.ts 2 src/main/persistence/migrating-orcad-catalog/orcad-destination-client-state.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts 3 src/main/persistence/migrating-orcad-catalog/orcad-dormant-state-records.ts @@ -50,6 +49,7 @@ 1 src/main/persistence/tracking-repos/project-group-operations.ts 4 src/main/persistence/tracking-repos/repo-worktree-pruning.ts 3 src/main/persistence/tracking-repos/worktree-identity-migration.ts +2 src/main/persistence/workspace-session-domains.ts 2 src/main/pty/scrollback/terminal-scrollback-snapshots.ts 1 src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.ts 1 src/main/runtime/client/runtime-client-state.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt new file mode 100644 index 00000000000..ff70d4af49b --- /dev/null +++ b/config/main-sync-fs-baseline.txt @@ -0,0 +1,618 @@ +# Synchronous node:fs calls (every *Sync export) in production src/main and src/shared, per file. +# Startup-only or one-shot uses are fine to keep; per-RPC, per-spawn, per-focus or per-poll uses are the target. +# This is a RATCHET: counts may only go DOWN. +# Prune after removing calls: pnpm check:main-sync-fs-ratchet --prune +1 src/main/agent-hooks/first-work/first-work-rename-runtime.ts +2 src/main/agent-hooks/installation/configuration/hook-config-write-path.ts +1 src/main/agent-hooks/installation/configuration/hooks-json-read.ts +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 +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 +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 +1 src/main/ai-vault/scanners/omp/omp-session-root.ts +1 src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts +2 src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts +8 src/main/amp/hook-service.ts +2 src/main/amp/managed-plugin-install-status.ts +1 src/main/antigravity/antigravity-host-acp.ts +1 src/main/antigravity/native-account-launch.ts +5 src/main/antigravity/native-account-store.ts +2 src/main/antigravity/native-credential-backend.ts +7 src/main/antigravity/native-file-credentials.ts +12 src/main/artifacts/artifact-create-intent-store.ts +2 src/main/artifacts/artifact-share-record-store.ts +1 src/main/automations/external-manager-discovery.ts +7 src/main/bitbucket/credential-store.ts +1 src/main/browser-passwords/browser-password-chromium-import.ts +2 src/main/browser-passwords/browser-password-vault-file.ts +2 src/main/browser/agent-browser/helper-process/agent-browser-binary.ts +2 src/main/browser/agent-browser/helper-process/agent-browser-dependency-binary.ts +2 src/main/browser/agent-browser/helper-process/agent-browser-process-environment.ts +1 src/main/browser/agent-browser/session-lifecycle/agent-browser-session-reset.ts +2 src/main/browser/client-hosts/file-transfers/browser-client-download-relay.ts +1 src/main/browser/client-hosts/file-transfers/browser-client-upload-staging.ts +2 src/main/browser/client-hosts/leases/browser-host-client-identity.ts +1 src/main/browser/cookies/browser-cookie-import-diagnostics.ts +2 src/main/browser/cookies/chromium/chromium-cookie-path.ts +4 src/main/browser/cookies/chromium/chromium-cookie-snapshot.ts +1 src/main/browser/cookies/chromium/import-cookies.ts +3 src/main/browser/cookies/client-route/client-route-cookie-import-source-store.ts +2 src/main/browser/cookies/sources/browser-cookie-detection.ts +8 src/main/browser/cookies/sources/browser-cookie-firefox-import.ts +2 src/main/browser/cookies/sources/browser-cookie-key.ts +1 src/main/browser/cookies/sources/browser-cookie-safari-import.ts +5 src/main/browser/cookies/sources/browser-cookie-source-profiles.ts +11 src/main/browser/cookies/staging/browser-session-cookie-staging.ts +1 src/main/browser/downloads/browser-download-destination.ts +2 src/main/browser/extensions/api-runtime/browser-extension-worker-shim-source.ts +8 src/main/browser/extensions/installation/browser-extension-install-store.ts +1 src/main/browser/extensions/installation/browser-extension-load-directory.ts +1 src/main/browser/extensions/profile-sessions/browser-extension-session-loader.ts +2 src/main/browser/extensions/profile-storage/browser-extension-data-removal.ts +8 src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts +4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts +3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts +1 src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts +2 src/main/browser/electron-fixtures/popup-identity-electron-probe.ts +1 src/main/browser/identity/mode/browser-identity-mode-record.ts +2 src/main/browser/identity/mode/browser-identity-mode-store.ts +2 src/main/browser/network/egress/browser-route-egress-electron-launch.ts +4 src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts +5 src/main/browser/routing/partitions/browser-route-partition-binding-file.ts +3 src/main/browser/routing/partitions/browser-route-partition-binding-store.ts +4 src/main/browser/routing/partitions/browser-route-partition-pending-deletes.ts +4 src/main/browser/sessions/profiles/browser-session-meta-store.ts +2 src/main/browser/site-settings/browser-profile-site-store.ts +7 src/main/claude-accounts/claude-account-folder.ts +1 src/main/claude-accounts/claude-observed-config-dirs.ts +14 src/main/claude-accounts/claude-profile-history.ts +2 src/main/claude-accounts/claude-profile-homes.ts +1 src/main/claude-accounts/claude-profile-launch-preparation.ts +7 src/main/claude-accounts/claude-profile-paths.ts +26 src/main/claude-accounts/claude-profile-prompt-history.ts +5 src/main/claude-accounts/claude-profile-provisioning.ts +5 src/main/claude-accounts/claude-profile-router.ts +1 src/main/claude-accounts/claude-profile-settings.ts +1 src/main/claude-accounts/claude-profile-setup-worker.ts +1 src/main/claude-accounts/claude-profile-setup.ts +12 src/main/claude-accounts/claude-profile-sharing.ts +1 src/main/claude-accounts/claude-profile-wsl-router.ts +2 src/main/claude-accounts/keychain.ts +1 src/main/claude-accounts/runtime-paths.ts +3 src/main/claude/agent-view/agent-view-install.ts +1 src/main/claude/claude-diff-panel-auto-open.ts +14 src/main/claude/claude-folder-trust-file.ts +2 src/main/claude/claude-profile-hook-target.ts +1 src/main/claude/claude-rejected-api-key.ts +1 src/main/claude/claude-rewind-transcript.ts +1 src/main/claude/hook-service.ts +3 src/main/claude/statusline-install.ts +6 src/main/claude/windows-hook-files.ts +1 src/main/cli/appimage-copy-pre-extraction.ts +3 src/main/cli/appimage-extracted-root.ts +1 src/main/cli/appimage-extraction-pruning.ts +2 src/main/cli/appimage-generation-lease.ts +4 src/main/cli/appimage-generation-residency.ts +16 src/main/cli/appimage-stable-launcher.ts +1 src/main/cli/cli-command-inspection.ts +1 src/main/cli/cli-dev-launcher.ts +3 src/main/cli/cli-install-location.ts +2 src/main/cli/linux-bare-orca-dispatcher.ts +7 src/main/cli/linux-terminal-orca-cli-shim.ts +2 src/main/cli/wsl-managed-cli.ts +2 src/main/codex-accounts/codex-account-identity.ts +3 src/main/codex-accounts/codex-account-registration.ts +4 src/main/codex-accounts/codex-config-mirror.ts +1 src/main/codex-accounts/codex-credential-absence-grace.ts +1 src/main/codex-accounts/codex-login-auth-snapshot.ts +5 src/main/codex-accounts/codex-managed-home-lifecycle.ts +6 src/main/codex-accounts/codex-managed-home-path.ts +17 src/main/codex-accounts/fs-utils.ts +1 src/main/codex-accounts/guest-codex-account-homes.ts +6 src/main/codex-accounts/host-codex-managed-home-ownership.ts +2 src/main/codex-accounts/legacy-shared-auth-migration.ts +21 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts +36 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts +6 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts +1 src/main/codex-accounts/managed-codex-auth-readiness.ts +7 src/main/codex-accounts/runtime-home-service-auth-core.ts +5 src/main/codex-accounts/runtime-home-service-auth-provenance.ts +23 src/main/codex-accounts/runtime-home-service-auth-sync.ts +19 src/main/codex-accounts/runtime-home-service-legacy-migration.ts +1 src/main/codex-accounts/runtime-home-service-managed-home.ts +14 src/main/codex-accounts/runtime-home-service-paths.ts +1 src/main/codex-accounts/runtime-home-service-sync.ts +2 src/main/codex-accounts/runtime-home-service-wsl-core.ts +1 src/main/codex-usage/codex-session-file-discovery.ts +1 src/main/codex/configuration/codex-path-observation.ts +21 src/main/codex/configuration/homes/codex-home-paths.ts +6 src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts +8 src/main/codex/configuration/homes/codex-managed-home-rules.ts +5 src/main/codex/configuration/homes/codex-pane-account-registry.ts +5 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts +1 src/main/codex/configuration/settings/codex-config-path-reference-rewrite.ts +1 src/main/codex/configuration/settings/config-settings-baseline.ts +5 src/main/codex/configuration/settings/config-settings-promotion-write-target.ts +3 src/main/codex/configuration/settings/config-settings-promotion.ts +1 src/main/codex/configuration/shared-server/codex-daemon-socket-path-guard.ts +8 src/main/codex/configuration/toml/config-toml-atomic-write.ts +4 src/main/codex/history/backfill/codex-session-backfill-marker.ts +17 src/main/codex/history/bridges/codex-session-bridge.ts +5 src/main/codex/history/index/codex-session-index-heal-state.ts +2 src/main/codex/history/index/codex-state-db.ts +2 src/main/codex/history/resume/codex-session-resume-home.ts +2 src/main/codex/history/rollouts/codex-account-home-discovery.ts +1 src/main/codex/history/rollouts/codex-session-file-listing.ts +2 src/main/codex/history/rollouts/codex-session-link.ts +1 src/main/codex/hooks/installation/codex-hook-local-install.ts +2 src/main/codex/hooks/installation/codex-hook-local-maintenance.ts +4 src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts +2 src/main/codex/hooks/reconciliation/codex-hook-status.ts +4 src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts +3 src/main/codex/trust/grants/codex-trust-grant-ledger.ts +2 src/main/codex/trust/hooks/codex-hook-trust-derivation.ts +1 src/main/codex/trust/hooks/codex-hook-trust-memo.ts +2 src/main/codex/trust/hooks/codex-hook-user-mirroring.ts +4 src/main/codex/trust/hooks/hook-trust-promotion.ts +1 src/main/codex/trust/identity/codex-trust-identity.ts +1 src/main/codex/trust/toml/config-toml-project-trust.ts +7 src/main/codex/trust/toml/config-toml-trust.ts +2 src/main/computer/desktop-script-provider-paths.ts +1 src/main/computer/macos-native-provider-client.ts +3 src/main/computer/macos-native-provider-paths.ts +5 src/main/computer/macos-native-provider-transport.ts +1 src/main/computer/sidecar-client.ts +3 src/main/connector-cloud/connector-turn-events.ts +1 src/main/copilot/hook-service.ts +4 src/main/crash-reporting/appimage-crashpad-handler-exit.ts +2 src/main/credentials/credential-file-protection.ts +6 src/main/credentials/encrypted-api-key-file-store.ts +10 src/main/credentials/integration-credential-file.ts +1 src/main/credentials/integration-state-file-cache.ts +1 src/main/credentials/integration-token-file-cache.ts +2 src/main/credentials/saved-credential-readability.ts +2 src/main/daemon/admission/automatic-work-run-marker-store.ts +5 src/main/daemon/admission/host-terminal-ledger.ts +1 src/main/daemon/admission/legacy-restore-records.ts +1 src/main/daemon/daemon-entry.ts +1 src/main/daemon/endpoint/identity/daemon-endpoint-incarnation.ts +3 src/main/daemon/endpoint/identity/daemon-pid-identity.ts +2 src/main/daemon/endpoint/identity/daemon-pid-record-quarantine.ts +2 src/main/daemon/endpoint/identity/daemon-process-start-time.ts +2 src/main/daemon/endpoint/identity/daemon-ready-identity.ts +3 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts +7 src/main/daemon/endpoint/publication/daemon-endpoint-ownership.ts +1 src/main/daemon/endpoint/publication/daemon-endpoint-probe.ts +3 src/main/daemon/endpoint/publication/daemon-private-file-modes.ts +2 src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts +3 src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts +1 src/main/daemon/executable-host/linux/daemon-appimage-launch.ts +3 src/main/daemon/executable-host/linux/daemon-host-image.ts +2 src/main/daemon/executable-host/macos/macos-daemon-bundle.ts +9 src/main/daemon/executable-host/windows/daemon-host-build-inventory.ts +2 src/main/daemon/executable-host/windows/daemon-host-file-hash-cache.ts +3 src/main/daemon/executable-host/windows/daemon-host-manifest.ts +2 src/main/daemon/executable-host/windows/daemon-host-reclaim.ts +12 src/main/daemon/executable-host/windows/daemon-host-relocation.ts +4 src/main/daemon/health/daemon-health.ts +4 src/main/daemon/history/restoration/history-reader.ts +1 src/main/daemon/history/restoration/terminal-history-checkpoint-reader.ts +1 src/main/daemon/history/restoration/terminal-history-legacy-scrollback-restore.ts +1 src/main/daemon/history/storage/history-manager.ts +3 src/main/daemon/history/storage/terminal-history-metadata.ts +2 src/main/daemon/history/storage/terminal-history-permission-repair.ts +8 src/main/daemon/history/storage/terminal-history-recovery-quarantine.ts +1 src/main/daemon/history/storage/terminal-history-session-files.ts +3 src/main/daemon/history/storage/terminal-history-session-tombstone.ts +6 src/main/daemon/history/storage/terminal-history-session-writer.ts +1 src/main/daemon/launch/daemon-bundle-staleness.ts +1 src/main/daemon/launch/daemon-endpoint-adoption.ts +3 src/main/daemon/launch/daemon-generation-liveness.ts +2 src/main/daemon/launch/daemon-launch-paths.ts +1 src/main/daemon/launch/daemon-legacy-process-liveness.ts +2 src/main/daemon/launch/daemon-protocol-cleanup.ts +11 src/main/daemon/launch/daemon-spawner.ts +1 src/main/daemon/launch/daemon-stale-kill.ts +1 src/main/daemon/observability/daemon-adoption-telemetry-event.ts +1 src/main/daemon/observability/daemon-file-log.ts +3 src/main/daemon/permissions/daemon-tcc-attribution.ts +5 src/main/daemon/process-scopes/daemon-cgroup-scope.ts +1 src/main/daemon/process-scopes/daemon-user-manager-lifetime.ts +1 src/main/daemon/process-scopes/terminal-scopes-runtime.ts +2 src/main/daemon/process-scopes/terminal-scopes.ts +1 src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts +1 src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts +1 src/main/daemon/providers/routing/daemon-legacy-adapters.ts +2 src/main/daemon/pty-subprocess/spawn-preflight.ts +1 src/main/daemon/shell-readiness/shell-ready.ts +1 src/main/daemon/transport/client/daemon-client-token.ts +2 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts +4 src/main/devin/hook-config-json.ts +3 src/main/dsh/dsh-hook-packages.ts +3 src/main/dsh/hook-service.ts +1 src/main/emulator/android/android-sdk-host-discovery.ts +7 src/main/emulator/android/scrcpy-server-download.ts +1 src/main/emulator/emulator-probe.ts +2 src/main/emulator/serve-sim-detached-session.ts +7 src/main/emulator/serve-sim-execution.ts +17 src/main/emulator/serve-sim-runtime-materializer.ts +12 src/main/external-editors/external-editor-launch.ts +9 src/main/filesystem/durable-file-write.ts +2 src/main/filesystem/rolling-file-backup.ts +2 src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry-path.ts +1 src/main/foreign-sqlite-readers/foreign-sqlite-reader-spawn.ts +1 src/main/foreign-sqlite-readers/readers/cursor-profile.ts +1 src/main/foreign-sqlite-readers/readers/opencode-binder-sessions.ts +1 src/main/git/huge-folder-ignore.ts +5 src/main/git/repo-detection.ts +13 src/main/git/repo-git-marker-scan.ts +3 src/main/git/worktrees/catalog/worktree-git-path.ts +1 src/main/github/client/check/check-job-log-cache-retention-child.mjs +3 src/main/grok/grok-hook-backup-cleanup.ts +3 src/main/grok/grok-hook-owners.ts +4 src/main/grok/grok-hook-symlink-cleanup-marker.ts +4 src/main/grok/hook-service.ts +4 src/main/hang-watchdog/hang-detection-marker.ts +1 src/main/hang-watchdog/hang-watchdog-worker-path.ts +1 src/main/hang-watchdog/previous-hang-detection.ts +1 src/main/hermes/hermes-default-home.ts +10 src/main/hermes/hermes-home-filesystem.ts +2 src/main/hermes/hook-service.ts +2 src/main/host/secret-protection-report.ts +1 src/main/ipc/app.ts +1 src/main/ipc/command-path/command-path-directory-worker-client.ts +1 src/main/ipc/command-path/command-path-resolver.ts +4 src/main/ipc/diagnostics.ts +2 src/main/ipc/filesystem/access/filesystem-path-containment.ts +2 src/main/ipc/filesystem/watcher-process/parcel-watcher-canary-directory.ts +1 src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts +4 src/main/ipc/filesystem/watcher-process/parcel-watcher-delivery-canary.ts +3 src/main/ipc/filesystem/watcher-process/parcel-watcher-entry-path.ts +1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts +1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts +1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts +1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts +1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts +1 src/main/ipc/macos-keyboard-layout-snapshot.ts +1 src/main/ipc/notification-authorization-status.ts +1 src/main/ipc/pty/spawn-pane-env.ts +1 src/main/ipc/ssh/ssh-connect-flow.ts +2 src/main/ipc/worktree-remote.ts +2 src/main/ipc/wsl-guest-windows-drive-path.ts +7 src/main/jcode/hook-service.ts +8 src/main/jira/site-credential-store.ts +7 src/main/keybindings/keybinding-file-parser.ts +1 src/main/keybindings/keybinding-file.ts +13 src/main/kimi/hook-service.ts +3 src/main/kiro/hook-service.ts +1 src/main/kiro/standalone-hooks.ts +4 src/main/linear/linear-credential-paths.ts +3 src/main/linear/linear-legacy-viewer-store.ts +1 src/main/linear/linear-token-store.ts +3 src/main/linear/linear-workspace-registry.ts +1 src/main/macos-permissions/macos-tcc-prompt-notice.ts +3 src/main/managed-data-accounts/credential-capture.ts +18 src/main/managed-data-accounts/profile-removal.ts +10 src/main/managed-data-accounts/service.ts +1 src/main/managed-server/activation/orcad-held-fence-tokens.ts +1 src/main/managed-server/install/orcad-deployment-target.ts +2 src/main/managed-server/install/remote-versioned-install.ts +1 src/main/memory/darwin-process-footprint.ts +13 src/main/mimo/hook-service.ts +6 src/main/minimax/minimax-cookie-store.ts +1 src/main/muse/hook-config-json.ts +4 src/main/muse/hook-service.ts +2 src/main/native-chat/agent-session-attachments/agent-session-attachment-claims.ts +1 src/main/native-chat/agent-session-journal/database/journal-host-database.ts +1 src/main/native-chat/host-readable-transcript-path.ts +2 src/main/native-chat/wsl-transcript-fs-process-spawn.ts +1 src/main/node-runtime/appimage-bundled-node-runtime.ts +2 src/main/node-runtime/managed-runtime-release-install.ts +7 src/main/node-runtime/managed-runtime-release.ts +11 src/main/notebook/python-environments.ts +1 src/main/observability/bounded-log-file-writer.ts +2 src/main/observability/bundle.ts +6 src/main/observability/local-file-sink.ts +14 src/main/opencode/hook-service.ts +1 src/main/opencode/legacy-plugin-acl-retry.ts +2 src/main/opencode/opencode-overlay-manifest.ts +1 src/main/opencode/opencode-plugin-config-writer.ts +1 src/main/opencode/opencode-private-server.ts +1 src/main/opencode/opencode-wsl-text-task.ts +2 src/main/orca-profiles/new-profile-state.ts +3 src/main/orca-profiles/other-profile-workspace-catalog.ts +3 src/main/orca-profiles/profile-artifact-cloud-cleanup.ts +1 src/main/orca-profiles/profile-cloud-index.ts +4 src/main/orca-profiles/profile-cloud-session-store.ts +12 src/main/orca-profiles/profile-index-store.ts +5 src/main/orca-profiles/profile-legacy-state-import.ts +4 src/main/orca-profiles/profile-project-move-intent.ts +3 src/main/orca-profiles/profile-project-move-record.ts +4 src/main/orca-profiles/profile-project-state-file.ts +2 src/main/orcad/launcher.ts +7 src/main/orcad/node-pty-prebuilt-slot.ts +2 src/main/orcad/node-pty-precondition.ts +2 src/main/orcad/orcad-agent-browser-binary.ts +1 src/main/orcad/orcad-app-paths.ts +1 src/main/orcad/orcad-artifact-identity.ts +2 src/main/orcad/orcad-artifact-materializer.ts +12 src/main/orcad/orcad-bundled-runtime.ts +2 src/main/orcad/orcad-cli-launcher.ts +1 src/main/orcad/orcad-command-arguments.ts +1 src/main/orcad/orcad-completed-stop-receipt.ts +2 src/main/orcad/orcad-daemon-slot-pins.ts +2 src/main/orcad/orcad-data-root-locality.ts +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 +4 src/main/orcad/orcad-instance-lock.ts +7 src/main/orcad/orcad-local-serve-selection.ts +1 src/main/orcad/orcad-lock-clone-machine.ts +1 src/main/orcad/orcad-managed-stop-cancellation.ts +3 src/main/orcad/orcad-managed-stop-decision.ts +2 src/main/orcad/orcad-managed-stop-request.ts +4 src/main/orcad/orcad-plaintext-credential-migration.ts +5 src/main/orcad/orcad-process-start-time.ts +11 src/main/orcad/orcad-secret-key-record.ts +3 src/main/orcad/orcad-stale-lock-reclaim.ts +1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/orcad/orcad-wsl-holder-release.ts +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 +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 +3 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-staging.ts +17 src/main/persistence/migrating-orcad-catalog/orcad-migration-staged-file.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-scrollback-snapshot-transfer.ts +11 src/main/persistence/migrating-orcad-catalog/orcad-shell-history-installer.ts +7 src/main/persistence/migrating-orcad-catalog/orcad-terminal-history-installer.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-terminal-restore-hint-store.ts +1 src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.ts +1 src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts +6 src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts +2 src/main/persistence/moving-wsl-projects/wsl-move-slept-spool-sweep.ts +5 src/main/persistence/preferences/active-view-preference.ts +4 src/main/persistence/profile-state/legacy-json/profile-state-authority-exports.ts +2 src/main/persistence/profile-state/legacy-json/profile-state-export-path.ts +1 src/main/persistence/profile-state/legacy-json/profile-state-legacy-backup-path.ts +2 src/main/persistence/profile-state/legacy-json/profile-state-legacy-import.ts +8 src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts +6 src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts +5 src/main/persistence/profile-state/profile-state-access-identity.ts +12 src/main/persistence/profile-state/profile-state-access-owner.ts +3 src/main/persistence/profile-state/profile-state-access.ts +2 src/main/persistence/profile-state/profile-state-active-location.ts +5 src/main/persistence/profile-state/profile-state-authority-bootstrap.ts +1 src/main/persistence/profile-state/profile-state-authority-marker.ts +2 src/main/persistence/profile-state/profile-state-backup-path.ts +2 src/main/persistence/profile-state/profile-state-backup-worker.ts +5 src/main/persistence/profile-state/profile-state-database-quarantine.ts +9 src/main/persistence/profile-state/profile-state-database-recovery.ts +2 src/main/persistence/profile-state/profile-state-database.ts +4 src/main/persistence/profile-state/profile-state-migration.ts +6 src/main/persistence/profile-state/profile-state-offline-settings.ts +6 src/main/persistence/profile-state/profile-state-recovery-command.ts +8 src/main/persistence/profile-state/profile-state-recovery-copy.ts +2 src/main/persistence/profile-state/profile-state-recovery-crash-process.ts +1 src/main/persistence/profile-state/profile-state-recovery-required.ts +2 src/main/persistence/profile-state/profile-state-section-repair.ts +2 src/main/persistence/profile-state/profile-state-sqlite-authority.ts +1 src/main/persistence/profile-state/profile-state-startup-recovery-dialog.ts +2 src/main/persistence/profile-state/profile-state-storage-classification.ts +1 src/main/persistence/profile-state/profile-state-writer-worker-path.ts +2 src/main/persistence/restoring-sessions/floating-workspace-normalization.ts +1 src/main/persistence/tracking-repos/worktree-metadata-normalization.ts +1 src/main/persistence/window-save-divergence.ts +8 src/main/pi/legacy-omp-overlay-migration.ts +5 src/main/pi/titlebar-extension-service.ts +3 src/main/plugins/appearance/plugin-appearance-service.ts +2 src/main/plugins/installation/plugin-install-staging.ts +1 src/main/plugins/installation/plugin-install.ts +1 src/main/plugins/panels/plugin-frame-guest-sessions.ts +1 src/main/plugins/panels/plugin-source-transpile-client.ts +2 src/main/plugins/plugin-dev-watcher.ts +3 src/main/plugins/plugin-secrets-store.ts +3 src/main/plugins/plugin-storage-store.ts +1 src/main/plugins/testing/plugin-editor-static-check.ts +1 src/main/plugins/workers/plugin-host-process.ts +3 src/main/plugins/workers/plugin-worker-source-hooks.ts +8 src/main/ports/darwin-port-scan-lock.ts +1 src/main/ports/port-scan-command-client.ts +1 src/main/ports/port-scan-command-execution.ts +2 src/main/provider-process/provider-executable-missing.ts +5 src/main/providers/local-pty/local-pty-executable-spawn.ts +1 src/main/providers/local-pty/local-pty-session-operations.ts +1 src/main/providers/local-pty/local-pty-shell-ready-wrapper-root.ts +1 src/main/providers/macos-login-session-pty-probe.ts +3 src/main/providers/macos-tcc-login-shell.ts +3 src/main/providers/windows-powershell-executable.ts +2 src/main/providers/working-directory-validation.ts +4 src/main/pty/history/fish-history-session.ts +4 src/main/pty/history/terminal-history-deletion.ts +2 src/main/pty/history/terminal-history-paths.ts +5 src/main/pty/history/terminal-history.ts +1 src/main/pty/process-retirement/posix-pty-process-table.ts +12 src/main/pty/scrollback/overlay-mirror.ts +1 src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts +11 src/main/pty/scrollback/terminal-scrollback-snapshots.ts +2 src/main/pty/shell-startup/codex-shell-launch-preflight.ts +7 src/main/pty/shell-startup/git-bash.ts +3 src/main/pty/shell-startup/legacy-terminal-posix-tombstone.ts +9 src/main/pty/shell-startup/legacy-terminal-shim-dir.ts +1 src/main/pty/shell-startup/managed-ssh-host-login-shell.ts +1 src/main/pty/shell-startup/powershell-profile-env.ts +3 src/main/pty/shell-startup/shell-startup-env.ts +5 src/main/pty/shell-startup/shell-wrapper-file-writer.ts +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 +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 +1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts +2 src/main/runtime/push/push-unregister-outbox.ts +2 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +1 src/main/runtime/rpc/server/network-source-policy-store.ts +2 src/main/runtime/rpc/server/pairing/device-registry-corruption.ts +2 src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts +1 src/main/runtime/rpc/server/pairing/device-registry-file-read.ts +3 src/main/runtime/rpc/server/pairing/e2ee-keypair.ts +3 src/main/runtime/rpc/server/runtime-metadata.ts +2 src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts +5 src/main/runtime/rpc/unix-socket-transport.ts +3 src/main/runtime/rpc/ws-fallback-port-store.ts +2 src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts +1 src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts +1 src/main/server/serve-pairing-output.ts +2 src/main/speech/model-cache-path.ts +9 src/main/speech/model-manager.ts +10 src/main/speech/openai-api-key-store.ts +2 src/main/speech/speech-model-download-cleanup.ts +1 src/main/speech/speech-model-download-transport.ts +2 src/main/speech/speech-model-http-download.ts +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/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 +2 src/main/ssh/config/ssh-config-alias-claim.ts +5 src/main/ssh/config/ssh-config-include-expander.ts +1 src/main/ssh/config/ssh-config-parser.ts +1 src/main/ssh/config/ssh-g-config-resolution.ts +3 src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts +3 src/main/ssh/system-transport/ssh-control-socket.ts +3 src/main/ssh/system-transport/system-ssh-binary.ts +3 src/main/startup/cli-launch-redirect.ts +2 src/main/startup/configure-process.ts +4 src/main/startup/gpu-fallback-marker.ts +2 src/main/startup/http1-compatibility-marker.ts +5 src/main/startup/http1-compatibility-profile-state.ts +1 src/main/startup/linux-dev-shm-policy.ts +4 src/main/startup/linux-realtime-scheduling-guard.ts +1 src/main/startup/linux-rttime-limit.ts +2 src/main/startup/profile-state-recovery-preflight.ts +1 src/main/startup/startup-diagnostics.ts +1 src/main/startup/windows-app-data-path.ts +5 src/main/startup/windows-install-dir-acl-poison-marker.ts +1 src/main/startup/windows-install-dir-acl-probe.ts +1 src/main/startup/windows-install-dir-package-acl-grant.ts +4 src/main/startup/windows-install-dir-package-acl-repair.ts +3 src/main/startup/windows-renderer-runtime-files.ts +3 src/main/startup/windows-user-data-acl.ts +6 src/main/startup/x-display-artifacts.ts +2 src/main/stats/stats-file-loader.ts +2 src/main/text-generation/source-control-prompt-files.ts +1 src/main/updater/lifecycle/windows-update-install-directory.ts +9 src/main/updater/linux-package/appimage-runtime-identity.ts +1 src/main/updater/linux-package/linux-package-install-command.ts +1 src/main/updater/linux-package/linux-update-package-type.ts +6 src/main/updater/serve-update-handoff.ts +2 src/main/usage/usage-provider-store-lifecycle.ts +1 src/main/usage/usage-scan-worker-spawn.ts +1 src/main/warp-themes/discovery.ts +1 src/main/window/desktop-integration/custom-app-icon.ts +3 src/main/window/desktop-integration/macos-press-and-hold-default.ts +1 src/main/windows/windows-administrator-restart.ts +1 src/main/windows/windows-command-paths.ts +1 src/main/windows/windows-process-table.ts +1 src/main/worker-thread-child-process/worker-thread-child-process.ts +2 src/main/worker-threads/forked-child-entry-path.ts +4 src/main/workspace-hooks/hooks.ts +10 src/main/workspace-hooks/issue-command-file.ts +4 src/main/workspace-hooks/worktree-runner-script.ts +1 src/main/workspaces/catalog/folder-repo-git-conversion.ts +2 src/main/workspaces/catalog/folder-upgrade-worktree-path.ts +3 src/main/workspaces/execution-host/project-runtime-git-router.ts +1 src/main/workspaces/space-analysis/workspace-space-scan-worker-client.ts +1 src/main/wsl/execution/wsl-executable-path.ts +1 src/main/wsl/execution/wsl-interop-spawn-directory.ts +1 src/main/wsl/execution/wsl-node-runtime-prefetch.ts +3 src/main/wsl/filesystem/wsl-drive-project-new-default.ts +10 src/main/wsl/filesystem/wsl-drive-unc-conversion-stores.ts +2 src/main/wsl/host-lifecycle/wsl-host-automation-wake-store.ts +4 src/main/wsl/host-lifecycle/wsl-host-e2e-fake-connector.ts +1 src/main/wsl/host-lifecycle/wsl-host-early-wake.ts +1 src/main/wsl/host-lifecycle/wsl-orphan-holder-release.ts +1 src/main/zcode/hook-config-json.ts +12 src/main/zcode/zcode-plan-api-key-store.ts +6 src/shared/agent-hook-listener/claude-session-continuation.ts +4 src/shared/agent-hook-listener/reverse-file-region-scan.ts +3 src/shared/agent-hook-listener/transcript-reader.ts +3 src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.ts +13 src/shared/agent-hook-listener/transport/agent-hook-spool.ts +5 src/shared/agent-hook-listener/transport/endpoint-publication.ts +4 src/shared/agent-launch/startup/omp-fresh-config.ts +2 src/shared/appimage-cache-identity.ts +2 src/shared/bundled-web-client-manifest.ts +3 src/shared/bundled-web-client-root.ts +5 src/shared/cli-fs-reads.ts +3 src/shared/cli-runtime-pairing-inputs.ts +9 src/shared/codex-rollout-jsonl-cursor.ts +1 src/shared/codex-subagent-roster.ts +4 src/shared/ephemeral-vm-recipe-doctor.ts +1 src/shared/ephemeral-vm-recipe-runner.ts +1 src/shared/ephemeral-vm-runtime-feature-store.ts +1 src/shared/ephemeral-vm-runtime-store.ts +6 src/shared/file-content/node-bounded-file-reader.ts +5 src/shared/file-content/node-file-content-equality.ts +6 src/shared/file-content/node-source-copy-content-equality.ts +3 src/shared/grok-session-paths.ts +2 src/shared/jcode-session-files.ts +1 src/shared/muse-session-log.ts +1 src/shared/opencode-installed-plugin.ts +10 src/shared/opencode-plugin-atomic-write.ts +5 src/shared/opencode-tui-config-registration.ts +1 src/shared/opencode-tui-plugin-install.ts +2 src/shared/orcad-build-identity.ts +1 src/shared/plugins/declarative/testing/orca-testing.ts +2 src/shared/real-path-sync.ts +1 src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts +1 src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts +1 src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts +2 src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts +2 src/shared/remote-runtime/host-store/runtime-environment-store-records.ts +1 src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts +13 src/shared/secure-storage/secure-file.ts +1 src/shared/secure-storage/secure-path-metadata-snapshot.ts +1 src/shared/secure-storage/secure-path-windows-acl.ts +3 src/shared/serve-abort-park.ts +7 src/shared/serve-bundle-park.ts +1 src/shared/serve-user-data-path.ts +3 src/shared/source-scan/source-tree-scan.ts +5 src/shared/startup-command-staging.ts +1 src/shared/terminal/pty/native-process/pty-process-ceiling-state.ts +8 src/shared/windows-breakaway-launcher.ts +3 src/shared/windows-console-input.ts +2 src/shared/windows-interactive-login-spawn.ts +2 src/shared/windows-retry-file-operations.ts +2 src/shared/windows-security-addon.ts +1 src/shared/windows-transient-lock-removal.ts diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index e18069dc0c4..c9d69eefb60 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -5,7 +5,7 @@ # Some entries run in the daemon or orcad process, or are test harnesses outside the test-path # conventions. This is a RATCHET: counts may only go DOWN. # Prune after removing launches: pnpm check:main-sync-spawn-ratchet --prune -1 src/main/agent-hooks/installer-utils.ts +1 src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts 1 src/main/browser/network/egress/browser-route-egress-electron-launch.ts 1 src/main/browser/routing/partitions/browser-route-partition-binding-store.ts 1 src/main/claude-accounts/runtime-auth-service.ts diff --git a/config/packaged-runtime-node-modules.cjs b/config/packaged-runtime-node-modules.cjs index 34fa9e68a09..a5a9ed3bb33 100644 --- a/config/packaged-runtime-node-modules.cjs +++ b/config/packaged-runtime-node-modules.cjs @@ -76,7 +76,7 @@ const ELECTRON_ARCHITECTURE_BY_ENUM = { const PACKAGED_NATIVE_ARCHITECTURES = new Set(['ia32', 'x64', 'arm', 'arm64']) const PACKAGED_MAIN_REQUIRED_FILES = [ 'out/main/index.js', - 'out/main/agent-hooks/managed-agent-hook-controls.js' + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js' ] const PACKAGED_MAIN_SOURCE_RE = /^out\/main\/.+\.js$/ const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/ diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt index 69a3b63695c..a0a0ede85ea 100644 --- a/config/path-literal-baseline.txt +++ b/config/path-literal-baseline.txt @@ -23,5 +23,6 @@ tests/e2e/capture-opencode-tui-repro.mjs src/cli/cmd/tui/ui/spinner tests/e2e/cross-version-wire/released-chat-writers.ts src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts # Released source trees retain this actual registry; the current registry is checked first. tests/e2e/cross-version-wire/release-module-locations.ts src/main/runtime/rpc/methods/index.ts +tests/e2e/cross-version-wire/release-module-locations.ts src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts # Release tags with flat skill owners need the restored harness beside that actual source. .github/workflows/release-cut.yml src/main/skills/skill-provider-runtime-roots.test.ts diff --git a/config/performance-audit.md b/config/performance-audit.md index 3a11b03e7e8..e414cb79ba2 100644 --- a/config/performance-audit.md +++ b/config/performance-audit.md @@ -54,3 +54,11 @@ identity, queue-admission or retained-memory oracle. Confirm it fails with the old behavior. Use controlled, counterbalanced benchmark samples for timings; avoid new machine-dependent millisecond gates in the normal unit suite. A green source scan and these contracts cannot establish that the whole app is fast. + +Two count ratchets (counts per file may only fall) cover classes the audit only warns about: +`pnpm check:main-sync-fs-ratchet` counts synchronous `node:fs` calls (every `*Sync` export) in production `src/main` and `src/shared` +(`config/main-sync-fs-baseline.txt`), and `pnpm check:recurring-timer-ratchet` counts `setInterval` +calls in production `src/main`, `src/renderer`, `src/shared` and `src/cli` +(`config/recurring-timer-baseline.txt`). Both run in `check:ratchets` on every non-draft PR that runs static analysis. A new use either +moves off the hot path (async fs or a stat-fingerprint cache; a push signal, a visibility-gated or +backing-off timer) or raises its file's count with reviewer sign-off. diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 1ef89fe5148..04253a93e8e 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -4,19 +4,19 @@ src/cli/handlers/core.ts src/cli/handlers/interactive-login-interruption.ts src/cli/runtime/launch.ts -src/main/agent-hooks/managed-hook-owner-identity.ts -src/main/agent-hooks/wsl-hook-relay-link.ts -src/main/agent-hooks/wsl-hook-relay-manager.ts -src/main/agent-hooks/wsl-hook-relay-sentinel.ts +src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts src/main/ai-vault/scan-service/session-scanner-service-client-state.ts src/main/ai-vault/scan-service/session-scanner-service-client.ts src/main/ai-vault/scan-service/session-scanner-service-spawn.ts src/main/window/desktop-integration/app-icon.ts src/main/automations/precheck-runner.ts -src/main/browser/agent-browser/agent-browser-bridge-execution.ts -src/main/browser/agent-browser/agent-browser-bridge-raw-process.ts -src/main/browser/agent-browser/agent-browser-bridge-state.ts -src/main/browser/agent-browser/agent-browser-bridge-types.ts +src/main/browser/agent-browser/helper-process/agent-browser-bridge-execution.ts +src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.ts +src/main/browser/agent-browser/session-routing/agent-browser-bridge-state.ts +src/main/browser/agent-browser/session-lifecycle/agent-browser-session-state.ts src/main/browser/network/egress/browser-route-egress-electron-launch.ts src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 933ce4f0a05..b1a89fbefe0 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 diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt new file mode 100644 index 00000000000..343b138c771 --- /dev/null +++ b/config/recurring-timer-baseline.txt @@ -0,0 +1,92 @@ +# setInterval calls (global, or imported from node:timers / node:timers/promises) in production src/main, +# src/renderer, src/shared and src/cli, per file. Bare calls are resolved per scope; imported bindings follow the shared +# collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden). +# This is a RATCHET: counts may only go DOWN. +# Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune +1 src/cli/handlers/orchestration/check-keepalive.ts +1 src/cli/runtime/mac-app-update-bundle.ts +1 src/cli/runtime/serve-supervised-service.ts +1 src/main/agent-hooks/server/server-opencode-binder.ts +1 src/main/automations/retained-run-reconciliation.ts +1 src/main/automations/service.ts +1 src/main/browser/extensions/native-messaging/browser-extension-native-ports.ts +1 src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts +1 src/main/claude/agent-view/agent-view-bridge.ts +1 src/main/cli/appimage-serve-preparation.ts +1 src/main/codex-accounts/codex-login-session.ts +1 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts +1 src/main/crash-reporting/pre-gone-host-memory.ts +1 src/main/crash-reporting/process-gone-diagnostics.ts +1 src/main/crash-reporting/renderer-heap-allocation-profile.ts +1 src/main/daemon/admission/host-terminal-ledger.ts +1 src/main/daemon/admission/host-terminal-policy.ts +1 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts +1 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts +1 src/main/diagnostics/event-loop-delay-probe.ts +1 src/main/diagnostics/main-thread-churn-probe.ts +1 src/main/git/refs/maintenance/pack-refs-lock-ownership.ts +1 src/main/hang-watchdog/main-thread-hang-watchdog-entry.ts +1 src/main/hang-watchdog/main-thread-hang-watchdog.ts +2 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.ts +1 src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-subscription.ts +1 src/main/ipc/runtime-environments/runtime-environment-preference.ts +1 src/main/ipc/worktrees/git/worktree-git-common-narrow-watch.ts +1 src/main/ipc/worktrees/git/worktree-git-common-native-upgrade-poll.ts +1 src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts +1 src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts +1 src/main/native-chat/agent-session-wire/host/structured-agent-session-lease-renewer.ts +1 src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts +1 src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts +1 src/main/notifications/desktop-presence-reporter.ts +1 src/main/orcad/orcad-browser-install-park.ts +1 src/main/orcad/orcad-lock-clone-machine.ts +1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/plugins/catalog/plugin-auto-updater.ts +1 src/main/plugins/catalog/plugin-kill-list-service.ts +1 src/main/plugins/installation/plugin-git-repository.ts +1 src/main/plugins/plugin-service-housekeeping.ts +1 src/main/rate-limits/service/service-polling.ts +1 src/main/runtime/agent-state-rules/agent-state-rules-live-update.ts +1 src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts +3 src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +1 src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts +1 src/main/runtime/rpc/mobile-socket-wiring.ts +1 src/main/runtime/rpc/remote-runtime-server-heartbeat.ts +1 src/main/runtime/rpc/server/runtime-metadata-ownership-watch.ts +1 src/main/runtime/rpc/unix-socket-transport.ts +1 src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts +1 src/main/runtime/terminal/input/agent-prompt-permission-hold.ts +1 src/main/runtime/terminal/output/terminal-derived-agent-facts.ts +1 src/main/runtime/terminal/wait/terminal-idle-polls.ts +1 src/main/ssh/legacy-relay/bridge/legacy-relay-daily-activity.ts +1 src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts +1 src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts +1 src/main/ssh/protocol/ssh-channel-multiplexer.ts +1 src/main/startup/configure-process.ts +1 src/main/startup/event-loop-stall-probe.ts +1 src/main/startup/synthetic-title-runtime.ts +1 src/main/telemetry/wsl-usage-reporter.ts +1 src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts +1 src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts +1 src/renderer/src/app-shell/use-app-session-persistence.ts +1 src/renderer/src/components/browser-pane/browser-client-page-position-driver.ts +1 src/renderer/src/components/contextual-tours/use-contextual-tour.ts +1 src/renderer/src/components/editor/setup-contextual-copy.ts +1 src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.ts +1 src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx +1 src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.tsx +1 src/renderer/src/components/sidebar/workspace-card/activity/prompt-cache-countdown-clock.ts +1 src/renderer/src/components/status-bar/use-resource-memory-snapshot.ts +1 src/renderer/src/components/status-bar/use-runtime-host-resources.ts +1 src/renderer/src/components/tab-bar/tab-strip-drag-scroll.ts +1 src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.ts +1 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/RemoteRuntimeRecoveryCard.tsx +1 src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.ts +1 src/renderer/src/hooks/use-now.ts +1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts +1 src/renderer/src/lib/crash-diagnostics.ts +1 src/renderer/src/lib/window-visibility-interval.ts +1 src/renderer/src/lib/worker-auto-close.ts +1 src/renderer/src/runtime/hosts/wsl/wsl-refused-read-watch.ts +1 src/shared/remote-runtime/remote-runtime-socket-liveness.ts +1 src/shared/tmux-agent-hook-owner.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 46dcb8613d5..345522b5723 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -4449,18 +4449,18 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/browser-session-partition-policies.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.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", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.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/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/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/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/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", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/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/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/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/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts src/renderer/src/lib/workspace-doc-address-input.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list", "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", @@ -4478,11 +4478,11 @@ "src/renderer/src/store/slices/browser/browser.test.ts", "src/main/browser/document-preview/doc-preview-grant-registry.test.ts", "src/main/browser/document-preview/doc-preview-file-reader.test.ts", - "src/main/browser/sessions/browser-session-partition-policies.test.ts", + "src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts", "src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "src/main/browser/document-preview/doc-preview-failure-notice.test.ts", "src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts", - "src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.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/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", @@ -6389,7 +6389,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", @@ -6400,7 +6400,7 @@ "testFiles": [ "src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "src/main/agent-hooks/server-pane-authority.test.ts", + "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts", "src/main/ipc/agent-hooks.test.ts", "src/main/ipc/agent-pane-authority-ownership.test.ts", "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts", @@ -9253,7 +9253,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts --reporter=dot" + "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts --reporter=dot" ], "testFiles": [ "src/main/runtime/construction/orca-runtime.test.ts", @@ -9263,7 +9263,7 @@ "src/main/ssh/protocol/ssh-channel-multiplexer.test.ts", "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts", "src/wsl-guest/dispatcher-client-writer.test.ts", - "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts" + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts" ], "assertionRefs": [ { @@ -9304,7 +9304,7 @@ ] }, { - "file": "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts", + "file": "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts", "assertions": [ "WSL stdin forwards write(false), callback settlement, and drain without claiming a live WSL topology" ] diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 3e115b3f7cd..2a25d38facd 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -529,131 +529,131 @@ "src/main/persistence/preferences/active-view-preference.test.ts": 61, "src/main/providers/accounts/agent-auth-restart-preservation.test.ts": 55, "src/main/agent-launch/preflight/agent-cli-version-probe.test.ts": 72, - "src/main/agent-hooks/agent-tool-plugin-hooks.test.ts": 202, - "src/main/agent-hooks/agent-transition-detector.test.ts": 666, - "src/main/agent-hooks/cursor-replay-guard.test.ts": 403, - "src/main/agent-hooks/ended-process-reconciliation.test.ts": 775, - "src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts": 831, - "src/main/agent-hooks/first-work-branch-rename.test.ts": 857, - "src/main/agent-hooks/grok-replay-guard.test.ts": 533, - "src/main/agent-hooks/hook-process-capture.test.ts": 118, - "src/main/agent-hooks/hook-script-outside-orca.test.ts": 171, - "src/main/agent-hooks/installer-utils.test.ts": 264, - "src/main/agent-hooks/local-agent-cli-presence.test.ts": 153, - "src/main/agent-hooks/local-tmux-managed-pty.test.ts": 50, - "src/main/agent-hooks/locked-executable-rename.test.ts": 69, - "src/main/agent-hooks/managed-agent-hook-controls.test.ts": 250, - "src/main/agent-hooks/managed-hook-install-lock.test.ts": 226, - "src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts": 567, - "src/main/agent-hooks/managed-hook-script-refresh.test.ts": 1637, - "src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts": 1989, - "src/main/agent-hooks/managed-hook-timeout.test.ts": 2987, - "src/main/agent-hooks/managed-toml-ownership.test.ts": 52, - "src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts": 3479, - "src/main/agent-hooks/server-agent-presence.test.ts": 1257, - "src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts": 717, - "src/main/agent-hooks/server-ai-vault-liveness.test.ts": 643, - "src/main/agent-hooks/server-amp-normalization.test.ts": 607, - "src/main/agent-hooks/server-antigravity-resume-identity.test.ts": 820, - "src/main/agent-hooks/server-claude-blocked-prompt.test.ts": 681, - "src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts": 681, - "src/main/agent-hooks/server-claude-config-dir-observation.test.ts": 696, - "src/main/agent-hooks/server-claude-helper-kill.test.ts": 10279, - "src/main/agent-hooks/server-claude-helper-recovery.test.ts": 34523, - "src/main/agent-hooks/server-claude-normalization.test.ts": 683, - "src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts": 877, - "src/main/agent-hooks/server-claude-permission-tool-failure.test.ts": 674, - "src/main/agent-hooks/server-claude-permission-visibility.test.ts": 765, - "src/main/agent-hooks/server-claude-session-continuation.test.ts": 675, - "src/main/agent-hooks/server-claude-statusline.test.ts": 679, - "src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts": 5451, - "src/main/agent-hooks/server-claude-terminal-interrupt.test.ts": 802, - "src/main/agent-hooks/server-closed-tab-suppression.test.ts": 895, - "src/main/agent-hooks/server-codex-capacity.test.ts": 671, - "src/main/agent-hooks/server-codex-interrupt-hook.test.ts": 679, - "src/main/agent-hooks/server-codex-normalization.test.ts": 741, - "src/main/agent-hooks/server-codex-review-turn-end.test.ts": 860, - "src/main/agent-hooks/server-codex-side-thread.test.ts": 847, - "src/main/agent-hooks/server-codex-subagent-transcript.test.ts": 706, - "src/main/agent-hooks/server-codex-turn-interruption.test.ts": 716, - "src/main/agent-hooks/server-copilot-normalization.test.ts": 1125, - "src/main/agent-hooks/server-copilot-resume-identity.test.ts": 729, - "src/main/agent-hooks/server-cursor-normalization.test.ts": 645, - "src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts": 801, - "src/main/agent-hooks/server-grok-background-status.test.ts": 723, - "src/main/agent-hooks/server-grok-cancel.test.ts": 692, - "src/main/agent-hooks/server-grok-discovery.test.ts": 723, - "src/main/agent-hooks/server-hermes-resume-identity.test.ts": 941, - "src/main/agent-hooks/server-hook-http-ingest.test.ts": 719, - "src/main/agent-hooks/server-hook-session-binding.test.ts": 2674, - "src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts": 1088, - "src/main/agent-hooks/server-idle-process-owner.test.ts": 1014, - "src/main/agent-hooks/server-ingest-remote-codex-question.test.ts": 656, - "src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts": 647, - "src/main/agent-hooks/server-ingest-remote.test.ts": 653, - "src/main/agent-hooks/server-ingest-structured-state-clock.test.ts": 723, - "src/main/agent-hooks/server-ingest-structured-status.test.ts": 697, - "src/main/agent-hooks/server-ingest-terminal-status.test.ts": 673, - "src/main/agent-hooks/server-interrupt-inference-guards.test.ts": 685, - "src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts": 759, - "src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts": 937, - "src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts": 713, - "src/main/agent-hooks/server-last-status-hydrate-validation.test.ts": 737, - "src/main/agent-hooks/server-last-status-lead-boundary.test.ts": 768, - "src/main/agent-hooks/server-last-status-main-agent-fact.test.ts": 813, - "src/main/agent-hooks/server-last-status-restored-children.test.ts": 818, - "src/main/agent-hooks/server-last-status-write.test.ts": 745, - "src/main/agent-hooks/server-launch-resume-identity.test.ts": 735, - "src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts": 1716, - "src/main/agent-hooks/server-muse-session-log-poll.test.ts": 2772, - "src/main/agent-hooks/server-nested-agent-boundaries.test.ts": 657, - "src/main/agent-hooks/server-nested-agent-consumers.test.ts": 660, - "src/main/agent-hooks/server-nested-agent-model.test.ts": 665, - "src/main/agent-hooks/server-nested-same-provider-owner.test.ts": 708, - "src/main/agent-hooks/server-observation-provenance.test.ts": 672, - "src/main/agent-hooks/server-omp-retired-ingress.test.ts": 641, - "src/main/agent-hooks/server-omp-retirement-ack.test.ts": 676, - "src/main/agent-hooks/server-opencode-tui-identity.test.ts": 843, - "src/main/agent-hooks/server-opencode-writer-observation.test.ts": 681, - "src/main/agent-hooks/server-pane-authority.test.ts": 762, - "src/main/agent-hooks/server-process-lifetime-status.test.ts": 852, - "src/main/agent-hooks/server-prompt-sent-telemetry.test.ts": 701, - "src/main/agent-hooks/server-relayed-claude-cancel.test.ts": 901, - "src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts": 758, - "src/main/agent-hooks/server-reminted-pane-key.test.ts": 688, - "src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts": 764, - "src/main/agent-hooks/server-removed-worktree-status.test.ts": 687, - "src/main/agent-hooks/server-replay-evidence-clock.test.ts": 643, - "src/main/agent-hooks/server-restored-agent-status.test.ts": 694, - "src/main/agent-hooks/server-retired-pane-new-turn.test.ts": 666, - "src/main/agent-hooks/server-startup-lifecycle.test.ts": 718, - "src/main/agent-hooks/server-startup-prompt-control.test.ts": 697, - "src/main/agent-hooks/server-status-listener-fanout.test.ts": 783, - "src/main/agent-hooks/server-status-persist-nonblocking.test.ts": 697, - "src/main/agent-hooks/server-status-persist-throttle.test.ts": 860, - "src/main/agent-hooks/server-structured-canonical-status.test.ts": 765, - "src/main/agent-hooks/server-tmux-canonical.test.ts": 739, - "src/main/agent-hooks/server-tmux-wire.test.ts": 564, - "src/main/agent-hooks/server-transport-interference.test.ts": 1814, - "src/main/agent-hooks/server-turn-ended-at.test.ts": 990, - "src/main/agent-hooks/server-turn-started-at.test.ts": 898, + "src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts": 202, + "src/main/agent-hooks/observations/agent-transition-detector.test.ts": 666, + "src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts": 403, + "src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts": 775, + "src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts": 831, + "src/main/agent-hooks/first-work/first-work-branch-rename.test.ts": 857, + "src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts": 533, + "src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts": 118, + "src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts": 171, + "src/main/agent-hooks/installation/testing/installer-contract.test.ts": 264, + "src/main/agent-hooks/installation/local-agent-cli-presence.test.ts": 153, + "src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts": 50, + "src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts": 69, + "src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts": 250, + "src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts": 226, + "src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts": 567, + "src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts": 1637, + "src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts": 1989, + "src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts": 2987, + "src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts": 52, + "src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts": 3479, + "src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts": 1257, + "src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts": 717, + "src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts": 643, + "src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts": 607, + "src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts": 820, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts": 681, + "src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts": 681, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts": 696, + "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts": 10279, + "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts": 34523, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts": 683, + "src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts": 877, + "src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts": 674, + "src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts": 765, + "src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts": 675, + "src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts": 679, + "src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts": 5451, + "src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts": 802, + "src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts": 895, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts": 671, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts": 679, + "src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts": 741, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts": 860, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts": 847, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts": 706, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts": 716, + "src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts": 1125, + "src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts": 729, + "src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts": 645, + "src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts": 801, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts": 723, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts": 692, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts": 723, + "src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts": 941, + "src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts": 719, + "src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts": 2674, + "src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts": 1088, + "src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts": 1014, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts": 656, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts": 647, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts": 653, + "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts": 723, + "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts": 697, + "src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts": 673, + "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts": 685, + "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts": 759, + "src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts": 937, + "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts": 713, + "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts": 737, + "src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts": 768, + "src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts": 813, + "src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts": 818, + "src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts": 745, + "src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts": 735, + "src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts": 1716, + "src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts": 2772, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts": 657, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts": 660, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts": 665, + "src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts": 708, + "src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts": 672, + "src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts": 641, + "src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts": 676, + "src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts": 843, + "src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts": 681, + "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts": 762, + "src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts": 852, + "src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts": 701, + "src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts": 901, + "src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts": 758, + "src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts": 688, + "src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts": 764, + "src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts": 687, + "src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts": 643, + "src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts": 694, + "src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts": 666, + "src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts": 718, + "src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts": 697, + "src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts": 783, + "src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts": 697, + "src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts": 860, + "src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts": 765, + "src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts": 739, + "src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts": 564, + "src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts": 1814, + "src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts": 990, + "src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts": 898, "src/main/agent-hooks/server/program-status/hook-precedence.test.ts": 45, - "src/main/agent-hooks/spool.test.ts": 999, - "src/main/agent-hooks/terminal-handle-row-identity.test.ts": 669, - "src/main/agent-hooks/windows-batch-hook-launcher.test.ts": 108, - "src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts": 141, - "src/main/agent-hooks/windows-hook-payload-delivery.test.ts": 345, - "src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts": 262, - "src/main/agent-hooks/windows-powershell-hook-launcher.test.ts": 44, - "src/main/agent-hooks/wsl-guest-plugin-install.test.ts": 64, - "src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts": 1235, - "src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts": 2231, - "src/main/agent-hooks/wsl-hook-relay-manager.test.ts": 3176, - "src/main/agent-hooks/wsl-hook-relay-reattach.test.ts": 1280, - "src/main/agent-hooks/wsl-hook-relay-recovery.test.ts": 1529, - "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts": 62, - "src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts": 1951, - "src/main/agent-hooks/wsl-opencode-settings.test.ts": 1364, + "src/main/agent-hooks/server/testing/replay/spool.test.ts": 999, + "src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts": 669, + "src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts": 108, + "src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts": 141, + "src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts": 345, + "src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts": 262, + "src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts": 44, + "src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts": 64, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts": 1235, + "src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts": 2231, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts": 3176, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts": 1280, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts": 1529, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts": 62, + "src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts": 1951, + "src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts": 1364, "src/main/agent-launch/agent-launch-account-env.test.ts": 958, "src/main/agent-launch/agent-launch-executor-cancel.test.ts": 1455, "src/main/agent-launch/agent-launch-mode-settings.test.ts": 4041, @@ -899,18 +899,18 @@ "src/main/bitbucket/repository-ref.test.ts": 426, "src/main/bitbucket/status-no-decrypt.test.ts": 256, "src/main/updater/browser-sidecar-owner.test.ts": 53, - "src/main/browser/agent-browser/agent-browser-action-effects.test.ts": 487, - "src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts": 1017, - "src/main/browser/agent-browser/agent-browser-bridge-javascript-dialog.test.ts": 358, - "src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts": 752, - "src/main/browser/agent-browser/agent-browser-bridge-navigation.test.ts": 588, - "src/main/browser/agent-browser/agent-browser-bridge-raw-process-retention.test.ts": 1027, - "src/main/browser/agent-browser/agent-browser-bridge-raw-process.test.ts": 1179, - "src/main/browser/agent-browser/agent-browser-bridge-tab-routing.test.ts": 441, - "src/main/browser/agent-browser/agent-browser-orphan-sweep.test.ts": 59, + "src/main/browser/agent-browser/observation/agent-browser-action-effects.test.ts": 487, + "src/main/browser/agent-browser/command-queue/agent-browser-bridge-host-revocation.test.ts": 1017, + "src/main/browser/agent-browser/command-queue/agent-browser-bridge-javascript-dialog.test.ts": 358, + "src/main/browser/agent-browser/commands/agent-browser-bridge-keypress-input.test.ts": 752, + "src/main/browser/agent-browser/commands/agent-browser-bridge-navigation.test.ts": 588, + "src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process-retention.test.ts": 1027, + "src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.test.ts": 1179, + "src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts": 441, + "src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.test.ts": 59, "src/main/browser/cdp/input/agent-input-focus-guard.test.ts": 54, "src/main/browser/cdp/input/agent-input-injection.test.ts": 299, - "src/main/browser/guest-lifecycle/browser-agent-activity.test.ts": 128, + "src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts": 128, "src/main/browser/certificate-trust/browser-certificate-trust-controller.test.ts": 496, "src/main/browser/client-hosts/file-transfers/browser-client-download-relay.test.ts": 124, "src/main/browser/client-hosts/file-transfers/browser-client-download-routing.test.ts": 124, @@ -940,34 +940,34 @@ "src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts": 1807, "src/main/browser/cookies/browser-google-cookie-clear-target.test.ts": 6235, "src/main/browser/element-grab/browser-grab-payload.test.ts": 55, - "src/main/browser/guest-lifecycle/browser-guest-devtools-dock.test.ts": 57, - "src/main/browser/guest-lifecycle/input/browser-guest-shortcut-plugin-frame.test.ts": 280, - "src/main/browser/guest-lifecycle/input/browser-guest-shortcut-precedence.test.ts": 411, + "src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.test.ts": 57, + "src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-plugin-frame.test.ts": 280, + "src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-precedence.test.ts": 411, "src/main/browser/guest-lifecycle/input/browser-guest-target-url.test.ts": 50, "src/main/browser/guest-lifecycle/input/browser-guest-wheel-zoom-scroll.test.ts": 45, "src/main/browser/client-hosts/leases/browser-host-client-identity.test.ts": 97, "src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.test.ts": 74, - "src/main/browser/identity/browser-identity-mode-store.test.ts": 95, + "src/main/browser/identity/mode/browser-identity-mode-store.test.ts": 95, "src/main/browser/guest-lifecycle/prompts/browser-javascript-dialogs.test.ts": 54, - "src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts": 603, - "src/main/browser/guest-lifecycle/manager/browser-manager-auth-user-agent.test.ts": 555, - "src/main/browser/guest-lifecycle/manager/browser-manager-client-hosted-downloads.test.ts": 670, - "src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-downloads.test.ts": 589, - "src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest.test.ts": 633, - "src/main/browser/guest-lifecycle/manager/browser-manager-devtools-retirement.test.ts": 551, - "src/main/browser/guest-lifecycle/manager/browser-manager-downloads.test.ts": 592, - "src/main/browser/guest-lifecycle/manager/browser-manager-grab-capture.test.ts": 516, - "src/main/browser/guest-lifecycle/manager/browser-manager-grab-mode.test.ts": 567, - "src/main/browser/guest-lifecycle/manager/browser-manager-grab-selection.test.ts": 584, - "src/main/browser/guest-lifecycle/manager/browser-manager-guest-unload.test.ts": 534, + "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts": 603, + "src/main/browser/guest-lifecycle/manager/navigation/browser-manager-auth-user-agent.test.ts": 555, + "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts": 670, + "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-destroyed-guest-downloads.test.ts": 589, + "src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest.test.ts": 633, + "src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts": 551, + "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-downloads.test.ts": 592, + "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-capture.test.ts": 516, + "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-mode.test.ts": 567, + "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-selection.test.ts": 584, + "src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-unload.test.ts": 534, "src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts": 543, - "src/main/browser/guest-lifecycle/manager/browser-manager-load-failure-replay.test.ts": 549, - "src/main/browser/guest-lifecycle/manager/browser-manager-page-prompt-routing.test.ts": 560, - "src/main/browser/guest-lifecycle/manager/browser-manager-popup-child.test.ts": 503, - "src/main/browser/guest-lifecycle/manager/browser-manager-popup-routing.test.ts": 575, - "src/main/browser/guest-lifecycle/manager/browser-manager-tab-identity.test.ts": 619, - "src/main/browser/guest-lifecycle/manager/browser-manager-viewport-override.test.ts": 597, - "src/main/browser/guest-lifecycle/manager/browser-manager-viewport-ownership.test.ts": 550, + "src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts": 549, + "src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts": 560, + "src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts": 503, + "src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts": 575, + "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts": 619, + "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts": 597, + "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-ownership.test.ts": 550, "src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts": 101, "src/main/browser/network/execution-routes/browser-network-execution-route.test.ts": 272, "src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts": 127, @@ -981,7 +981,7 @@ "src/main/browser/guest-lifecycle/popups/browser-page-initiated-tab-budget.test.ts": 43, "src/main/browser/routing/input-ownership/browser-page-input-credit.test.ts": 50, "src/main/browser/guest-lifecycle/prompts/browser-page-prompts.test.ts": 74, - "src/main/browser/guest-lifecycle/popups/browser-popup-native-window.test.ts": 109, + "src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.test.ts": 109, "src/main/browser/identity/browser-process-user-agent.test.ts": 45, "src/main/browser/routing/guest-authority/browser-route-guest-popups.test.ts": 306, "src/main/browser/routing/partitions/browser-route-identity.test.ts": 47, @@ -1003,18 +1003,18 @@ "src/main/browser/cdp/screencast/browser-screencast-stream.test.ts": 223, "src/main/browser/cookies/staging/browser-session-cookie-staging.scoped.test.ts": 3741, "src/main/browser/cookies/staging/browser-session-cookie-staging.test.ts": 308, - "src/main/browser/sessions/browser-session-meta-store.test.ts": 43, - "src/main/browser/sessions/browser-session-partition-policies.test.ts": 979, - "src/main/browser/sessions/browser-session-partition-proxy-install.test.ts": 477, - "src/main/browser/sessions/browser-session-proxy.test.ts": 857, - "src/main/browser/sessions/browser-session-registry-identity.persistence.test.ts": 603, - "src/main/browser/sessions/browser-session-registry-startup-metadata.test.ts": 478, - "src/main/browser/sessions/browser-session-registry.test.ts": 883, - "src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts": 7167, - "src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts": 8280, - "src/main/browser/sessions/browser-session-user-agent-migration-inspection.test.ts": 229, - "src/main/browser/site-settings/browser-site-display-controller.test.ts": 95, - "src/main/browser/site-settings/browser-site-permission-prompt.test.ts": 338, + "src/main/browser/sessions/profiles/browser-session-meta-store.test.ts": 43, + "src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts": 979, + "src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts": 477, + "src/main/browser/sessions/proxy/browser-session-proxy.test.ts": 857, + "src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts": 603, + "src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts": 478, + "src/main/browser/sessions/profiles/browser-session-registry.test.ts": 883, + "src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts": 7167, + "src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts": 8280, + "src/main/browser/identity/mode/browser-retired-profile-identity-inspection.test.ts": 229, + "src/main/browser/site-settings/display/browser-site-display-controller.test.ts": 95, + "src/main/browser/site-settings/permissions/browser-site-permission-prompt.test.ts": 338, "src/main/browser/cdp/input/browser-text-insertion.test.ts": 51, "src/main/browser/webauthn/browser-webauthn-account-picker.test.ts": 78, "src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts": 358, @@ -1115,9 +1115,9 @@ "src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts": 237, "src/main/browser/extensions/declarative-net-request/engine-stages.test.ts": 112, "src/main/browser/extensions/declarative-net-request/engine.test.ts": 145, - "src/main/browser/extensions/declarative-net-request/redirect-url.test.ts": 66, - "src/main/browser/extensions/declarative-net-request/regex-filter.test.ts": 116, - "src/main/browser/extensions/declarative-net-request/url-pattern.test.ts": 84, + "src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts": 66, + "src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts": 116, + "src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts": 84, "src/main/browser/element-grab/grab-guest-overlay-follow.test.ts": 332, "src/main/browser/element-grab/grab-guest-script.test.ts": 107, "src/main/browser/cdp/debugger/guest-cdp-command.test.ts": 105, @@ -1134,7 +1134,7 @@ "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-host-command-admission.test.ts": 213, "src/main/browser/client-hosts/leases/paired-runtime-browser-host-lease.test.ts": 973, "src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts": 1150, - "src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.test.ts": 144, + "src/main/browser/electron-fixtures/popup-identity-electron-probe.test.ts": 144, "src/main/browser/network/tunnels/remote-browser-socks-buffering.test.ts": 384, "src/main/browser/network/tunnels/remote-browser-socks-server.test.ts": 309, "src/main/browser/cdp/snapshots/snapshot-engine.test.ts": 48, 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 ff1fea19e02..5519e995ad8 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 @@ -49,14 +49,14 @@ export const UNIT_EXCLUDE = [ 'tests/e2e/relay-region-correction.unit.test.ts', 'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts', // Electron probes with in-process deadlines; the package job runs them serially. - 'src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', 'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts', 'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts', 'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts', 'src/main/browser/extensions/profile-storage/browser-extension-persistence.electron.test.ts', 'src/main/browser/extensions/profile-sessions/browser-extension-lifecycle.electron.test.ts', 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 792e33eea61..f693ed3997d 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 @@ -23,7 +23,10 @@ describe('packaged runtime resources', () => { const sources = new Map([ ['out\\main\\index.js', 'const z = require("zod")'], - ['out\\main\\agent-hooks\\managed-agent-hook-controls.js', 'const YAML = require("yaml")'] + [ + 'out\\main\\agent-hooks\\installation\\managed-agent-hook-controls.js', + 'const YAML = require("yaml")' + ] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `\\${entry}`), @@ -48,7 +51,7 @@ describe('packaged runtime resources', () => { 'let p=null;function q(){return p??=import(`@anthropic-ai/claude-agent-sdk`),p}' ], [ - 'out/main/agent-hooks/managed-agent-hook-controls.js', + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js', 'import (`@anthropic-ai/claude-agent-sdk`)' ] ]) @@ -96,7 +99,7 @@ describe('packaged runtime resources', () => { // The entry points themselves carry no specifier; only the shared chunk does. const sources = new Map([ ['out/main/index.js', ''], - ['out/main/agent-hooks/managed-agent-hook-controls.js', ''], + ['out/main/agent-hooks/installation/managed-agent-hook-controls.js', ''], ['out/main/chunks/managed-agent-hook-controls-CWf8D-KR.js', 'require(`jsonc-parser`)'] ]) // listPackage includes directories that extractFile rejects; mock them to enforce the .js anchor. @@ -128,7 +131,7 @@ describe('packaged runtime resources', () => { const sources = new Map([ ['out/main/index.js', 'const all=[...require("jsonc-parser")]'], - ['out/main/agent-hooks/managed-agent-hook-controls.js', ''] + ['out/main/agent-hooks/installation/managed-agent-hook-controls.js', ''] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `/${entry}`), @@ -149,7 +152,10 @@ describe('packaged runtime resources', () => { // 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/managed-agent-hook-controls.js', 'state.import("android-sdk")'] + [ + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js', + 'state.import("android-sdk")' + ] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `/${entry}`), diff --git a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts index dd2ddb8fa18..774c2411787 100644 --- a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts +++ b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts @@ -9,23 +9,17 @@ import type { AppState } from '@/store/types' import type { AgentStatusBatchUpdate } from '@/store/slices/agent-status/agent-status-contract' import '@/store/slices/agent-status/agent-status' import { MAX_LIVE_AGENT_STATUSES } from '@/store/slices/agent-status/agent-status-capacity-eviction' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' -import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { makePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' -import { getDefaultSettings } from '../../../../src/shared/constants' +import type { createTestStore } from '@/store/testing/app-store-test-fixture' import { createAgentStatusPaneRoutingIndex, resolvePaneKeyFromRoutingIndex } from '@/hooks/ipc-events/agent-status-pane-routing-index' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' import { resolvePaneKey } from '@/hooks/ipc-events/agent-status-routing' const WORKTREES = 423 const EVENTS = 1_000 const BATCH_SIZE = 8 -const LEAF_ID = '11111111-1111-4111-8111-111111111111' const BASE_TIME = 2_000_000_000 const counters = { maps: 0, sets: 0, tabComparisons: 0 } @@ -58,62 +52,16 @@ function withAllocationCounting(run: () => T): T { } } -/** Tab list whose iteration is observable, so the nested-loop resolver's comparisons are countable. */ -class CountingTabList extends Array { - [Symbol.iterator](): ArrayIterator { - const iterator = super[Symbol.iterator]() - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - counters.tabComparisons += 1 - } - return result - } - return iterator - } -} - function buildFixture(countTabIteration: boolean) { - const store = createTestStore() - const settings = store.getState().settings ?? getDefaultSettings(tmpdir()) - const tabsByWorktree: AppState['tabsByWorktree'] = {} - const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {} - const worktrees: ReturnType[] = [] - const paneKeys: string[] = [] - const owners: { tabId: string; worktreeId: string }[] = [] - for (let index = 0; index < WORKTREES; index += 1) { - const worktreeId = `wt-${index}` - worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id })) - const tabs: ReturnType[] = [] - const unified: ReturnType[] = [] - for (let tab = 0; tab < (index % 2 === 0 ? 1 : 2); tab += 1) { - const tabId = `tab-${index}-${tab}` - tabs.push(makeTab({ id: tabId, worktreeId, title: `Terminal ${index}-${tab}` })) - unified.push( - makeUnifiedTab({ - id: tabId, - worktreeId, - groupId: `group-${index}`, - label: `Label ${index}` - }) - ) - paneKeys.push(makePaneKey(tabId, LEAF_ID)) - owners.push({ tabId, worktreeId }) - } - tabsByWorktree[worktreeId] = countTabIteration ? CountingTabList.from(tabs) : tabs - unifiedTabsByWorktree[worktreeId] = unified - } - store.setState({ - repos: [TEST_REPO], - worktreesByRepo: { [TEST_REPO.id]: worktrees }, - tabsByWorktree, - unifiedTabsByWorktree, - terminalLayoutsByTabId: {}, - setGeneratedTabTitlesFromAgentPrompts: () => {}, - settings: { ...settings, tabAutoGenerateTitle: false } - }) - return { store, paneKeys, owners } + const fixture = buildAgentStatusScaleFixture( + countTabIteration + ? () => { + counters.tabComparisons += 1 + } + : undefined + ) + fixture.store.setState({ setGeneratedTabTitlesFromAgentPrompts: () => {} }) + return fixture } function measure(run: () => void): number { diff --git a/config/scripts/performance/transport/browser-session-startup-metadata-benchmark.mjs b/config/scripts/performance/transport/browser-session-startup-metadata-benchmark.mjs index 6be6c3ddbaa..66926c291f9 100644 --- a/config/scripts/performance/transport/browser-session-startup-metadata-benchmark.mjs +++ b/config/scripts/performance/transport/browser-session-startup-metadata-benchmark.mjs @@ -3,7 +3,7 @@ import { execFileSync } from 'node:child_process' import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { dirname, join, resolve } from 'node:path' +import { dirname, join, posix, relative as relativePath, resolve } from 'node:path' import { performance } from 'node:perf_hooks' const root = resolve(import.meta.dirname, '../../../..') @@ -12,7 +12,7 @@ const require = createRequire(join(root, 'package.json')) const { build } = require('esbuild') const relative = 'src/main/browser/browser-session-registry.ts' const historicalTarget = join(root, relative) -const currentRelative = 'src/main/browser/sessions/browser-session-registry.ts' +const currentRelative = 'src/main/browser/sessions/profiles/browser-session-registry.ts' const target = join(root, currentRelative) const scratch = mkdtempSync(join(tmpdir(), 'orca-browser-meta-bench-')) const previousSource = execFileSync('git', ['show', `${baseline}:${relative}`], { @@ -56,23 +56,56 @@ const stubs = new Map([ 'export function attachBrowserExtensionsToProfileSession(profile,ids){globalThis.__metaBench.assignments.push([profile.id,ids])}' ] ]) +const baselineFiles = new Set( + execFileSync('git', ['ls-tree', '-r', '--name-only', baseline], { + cwd: root, + encoding: 'utf8', + maxBuffer: 32 * 1024 * 1024 + }) + .trim() + .split('\n') +) +function baselineDependency(importer, specifier) { + const owner = + importer === historicalTarget ? relative : relativePath(root, importer).split('\\').join('/') + const candidate = posix.normalize(posix.join(posix.dirname(owner), specifier)) + const found = [ + candidate, + `${candidate}.ts`, + `${candidate}.tsx`, + `${candidate}.js`, + `${candidate}/index.ts` + ].find((file) => baselineFiles.has(file)) + if (!found) { + throw new Error(`Missing actual baseline dependency: ${baseline}:${owner} -> ${specifier}`) + } + return join(root, found) +} const registryByVersion = {} try { for (const [version, source] of Object.entries(sources)) { const sourceTarget = version === 'before' ? historicalTarget : target const currentStubSpecifiers = new Map([ - ['./browser-session-cookie-staging', '../cookies/staging/browser-session-cookie-staging'], - ['./browser-session-route-policies', '../routing/sessions/browser-session-route-policies'], + ['./browser-session-cookie-staging', '../../cookies/staging/browser-session-cookie-staging'], + [ + './browser-session-partition-policies', + '../partition-policies/browser-session-partition-policies' + ], + ['./browser-session-route-policies', '../../routing/sessions/browser-session-route-policies'], + ['./browser-session-profile-retirement', './browser-session-profile-retirement'], [ '../persistence/loading-store/user-data-path', - '../../persistence/loading-store/user-data-path' + '../../../persistence/loading-store/user-data-path' ], - ['./browser-identity-mode-store', '../identity/browser-identity-mode-store'], - ['./browser-site-permission-store', '../site-settings/browser-site-permission-store'], - ['./browser-site-display-store', '../site-settings/browser-site-display-store'], + ['./browser-identity-mode-store', '../../identity/mode/browser-identity-mode-store'], + [ + './browser-site-permission-store', + '../../site-settings/permissions/browser-site-permission-store' + ], + ['./browser-site-display-store', '../../site-settings/display/browser-site-display-store'], [ './extensions/browser-extension-session-loader', - '../extensions/profile-sessions/browser-extension-session-loader' + '../../extensions/profile-sessions/browser-extension-session-loader' ] ]) const versionStubs = new Map( @@ -81,16 +114,12 @@ try { body ]) ) - const historicalDependencies = new Map([ - [ - './browser-session-meta-store', - join(root, 'src/main/browser/sessions/browser-session-meta-store.ts') - ], - [ - './browser-session-persisted-profile-validation', - join(root, 'src/main/browser/sessions/browser-session-persisted-profile-validation.ts') - ] - ]) + if (version === 'after') { + versionStubs.set( + './browser-profile-owned-stores', + 'export function forgetBrowserProfileOwnedStores(){return true}' + ) + } const output = join(scratch, `${version}.cjs`) await build({ stdin: { @@ -111,20 +140,35 @@ try { if (args.importer === sourceTarget && versionStubs.has(args.path)) { return { path: args.path, namespace: 'startup-stub' } } - if ( - version === 'before' && - args.importer === sourceTarget && - historicalDependencies.has(args.path) - ) { - return { path: historicalDependencies.get(args.path) } - } if ( args.path === 'node:fs' && args.importer.endsWith('/browser-session-meta-store.ts') ) { return { path: 'fs-probe', namespace: 'startup-stub' } } + if ( + version === 'before' && + args.path.startsWith('.') && + (args.importer === sourceTarget || args.namespace === 'startup-baseline') + ) { + return { + path: baselineDependency(args.importer, args.path), + namespace: 'startup-baseline' + } + } }) + builder.onLoad({ filter: /.*/, namespace: 'startup-baseline' }, (args) => ({ + contents: execFileSync( + 'git', + ['show', `${baseline}:${relativePath(root, args.path).split('\\').join('/')}`], + { + cwd: root, + encoding: 'utf8' + } + ), + loader: args.path.endsWith('.tsx') ? 'tsx' : 'ts', + resolveDir: dirname(args.path) + })) builder.onLoad({ filter: /.*/, namespace: 'startup-stub' }, (args) => ({ contents: args.path === 'fs-probe' diff --git a/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs b/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs index 4ded5ca11fe..74dbf9cd52b 100644 --- a/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs +++ b/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs @@ -310,10 +310,10 @@ async function main() { )) ;({ killAllPty } = await jiti.import('../../../../src/main/ipc/pty/kill-all.ts')) const { WslHookRelayManager, wslHookRelayManager } = await jiti.import( - '../../../../src/main/agent-hooks/wsl-hook-relay-manager.ts' + '../../../../src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts' ) const { ensureWslHookRelayForReattach } = await jiti.import( - '../../../../src/main/agent-hooks/wsl-hook-relay-reattach.ts' + '../../../../src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts' ) const { codexHookService } = await jiti.import( '../../../../src/main/codex/hooks/installation/hook-service.ts' diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 14eae82cea5..3bf510cc912 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -35,8 +35,15 @@ const RATCHET_INPUTS = { 'check-host-list-render-ratchet.mjs': ['src/renderer/src/'], 'check-id-only-store-write-ratchet.mjs': ['src/main/persistence/'], 'check-layout-writer-ratchets.mjs': ['src/main/', 'src/renderer/src/'], + 'check-main-sync-fs-ratchet.mjs': ['src/main/', 'src/shared/'], 'check-main-sync-spawn-ratchet.mjs': ['src/main/'], 'check-react-compiler-compat-ratchet.mjs': ['src/renderer/src/'], + 'check-recurring-timer-ratchet.mjs': [ + 'src/main/', + 'src/renderer/src/', + 'src/shared/', + 'src/cli/' + ], 'check-render-path-translate-ratchet.mjs': ['src/renderer/src/'], 'check-repo-host-read-ratchet.mjs': ['src/cli/', 'src/main/', 'src/shared/'], 'check-runtime-electron-ratchet.mjs': ['src/main/', 'src/cli/', 'src/shared/'], @@ -258,7 +265,9 @@ export function selectTypecheckProjects(files) { const RATCHET_SHARED_MODULES = { 'config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs': [ 'check-daemon-blocking-call-ratchet.mjs', - 'check-main-sync-spawn-ratchet.mjs' + 'check-main-sync-fs-ratchet.mjs', + 'check-main-sync-spawn-ratchet.mjs', + 'check-recurring-timer-ratchet.mjs' ], 'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [ 'check-react-compiler-compat-ratchet.mjs' diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index 7b3d7be3632..0a2bbe3c723 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -41,6 +41,8 @@ export const LINT_STEPS = [ 'check:workspace-record-read-ratchet', 'check:unproven-pty-retirement-ratchet', 'check:daemon-blocking-call-ratchet', + 'check:main-sync-fs-ratchet', + 'check:recurring-timer-ratchet', 'check:node-runtime-pin', 'check:path-literal-ratchet', 'check:host-list-render-ratchet', diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs index 01fce47e89b..15c416efd14 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs @@ -77,12 +77,12 @@ describe('main sync-spawn ratchet', () => { ], [ "const { execSync } = require('child_process')\nconst run = execSync\nrun('a')", - 2, + 1, ['execSync'] ], [ "function f() { const run = cp.execSync; run('a') }\nconst cp = require('child_process')", - 2, + 1, ['execSync'] ], [ @@ -91,10 +91,18 @@ describe('main sync-spawn ratchet', () => { ['execFileSync'] ], [ - "import { runProcessSync } from '@orca/process-host'\nconst run = runProcessSync", + "import { runProcessSync } from '@orca/process-host'\nconst run = runProcessSync\nrun(a)", 1, ['runProcessSync'] - ] + ], + // Binding an alias is setup; each call through it is a use, so an alias refactor keeps the count. + [ + "import { execSync } from 'child_process'\nconst run = execSync\nrun('a')\nrun('b')", + 2, + ['execSync'] + ], + ["import { execSync } from 'child_process'\nexport const run = execSync", 1, ['execSync']], + ["import { execSync } from 'child_process'\nconst out = execSync('a')", 1, ['execSync']] ])('counts %s', (source, count, symbols) => { expect(uses(source)).toEqual({ count, symbols }) }) diff --git a/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs b/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs index da92736ba0a..e17bb894adf 100644 --- a/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs +++ b/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs @@ -38,6 +38,15 @@ function isValueReference(node) { ) } +function isExportedDeclaration(declaration) { + const statement = declaration.parent?.parent + return ( + !!statement && + ts.isVariableStatement(statement) && + !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) +} + /** * Each family lists module specifiers (packages, or repo paths without extension) and the gated * exports to count, each with advice for the failure message. @@ -72,7 +81,7 @@ export function createGatedCallCollector(families, ratchetName) { ) } - // Count each gated value reference, alias use and re-export; imports alone do not count. + // Count each gated value reference, alias use and re-export; imports and plain alias bindings alone do not count. // File-wide, not scope-aware: computed specifiers/members and non-const holder flows are unresolved; local wrappers are not traced. function collectUses(file, contents) { // Escaped spellings and relative imports inside gated modules still need the full analysis. @@ -197,7 +206,7 @@ export function createGatedCallCollector(families, ratchetName) { identifiers.push(node) } else if (ts.isVariableDeclaration(node) && node.initializer) { if (ts.isIdentifier(node.name)) { - aliases.push({ name: node.name.text, initializer: node.initializer }) + aliases.push({ name: node.name.text, initializer: node.initializer, declaration: node }) } else if (ts.isObjectBindingPattern(node.name)) { destructures.push(node) } @@ -236,14 +245,30 @@ export function createGatedCallCollector(families, ratchetName) { } } } + // Binding a tracked alias is setup, not a use: its calls are charged instead, so an alias refactor + // keeps the count. Conditional/fallback aliases and exported bindings stay charged (conservative). + const aliasSetup = new Set() + for (const { name, initializer, declaration } of aliases) { + const target = unwrap(initializer) + if ( + functions.has(name) && + (ts.isIdentifier(target) || + ts.isPropertyAccessExpression(target) || + ts.isElementAccessExpression(target)) && + gatedFunction(target) && + !isExportedDeclaration(declaration) + ) { + aliasSetup.add(target) + } + } for (const node of members) { const name = propertyName(node) - if (moduleSymbols(node.expression)?.has(name)) { + if (!aliasSetup.has(node) && moduleSymbols(node.expression)?.has(name)) { recordUse(name) } } for (const node of identifiers) { - const name = functions.get(node.text) + const name = aliasSetup.has(node) ? null : functions.get(node.text) if (name) { recordUse(name) } diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs new file mode 100644 index 00000000000..82ad501f702 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs @@ -0,0 +1,115 @@ +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import { createGatedCallCollector } from '../../process-boundaries/gated-call-use-collector.mjs' +import { readTrackedSources, runCountRatchet } from '../../ratchet-baseline/ratchet-baseline.mjs' +import { isTestOnlySourcePath } from '../../process-boundaries/test-only-source-path.mjs' + +// Sync fs on Electron main stalls every window (and in the daemon/orcad, every terminal); per-spawn/RPC/focus stat and read sweeps were a recurring lag source (#39805, #35967, #38481). + +const BASELINE_PATH = 'config/main-sync-fs-baseline.txt' +// src/shared runs on main too; leaving it out would let a helper move bypass the gate. +const SCAN_ROOTS = ['src/main', 'src/shared'] +const ADVICE = + 'use node:fs/promises, or cache the result on a stat fingerprint outside the hot path' +// Every *Sync export of node:fs (descriptor and copy APIs included), listed so the baseline doesn't depend on the runtime. +const SYNC_FS = [ + 'accessSync', + 'appendFileSync', + 'chmodSync', + 'chownSync', + 'closeSync', + 'copyFileSync', + 'cpSync', + 'existsSync', + 'fchmodSync', + 'fchownSync', + 'fdatasyncSync', + 'fstatSync', + 'fsyncSync', + 'ftruncateSync', + 'futimesSync', + 'globSync', + 'lchmodSync', + 'lchownSync', + 'linkSync', + 'lstatSync', + 'lutimesSync', + 'mkdirSync', + 'mkdtempDisposableSync', + 'mkdtempSync', + 'openSync', + 'opendirSync', + 'readFileSync', + 'readSync', + 'readdirSync', + 'readlinkSync', + 'readvSync', + 'realpathSync', + 'renameSync', + 'rmSync', + 'rmdirSync', + 'statSync', + 'statfsSync', + 'symlinkSync', + 'truncateSync', + 'unlinkSync', + 'utimesSync', + 'writeFileSync', + 'writeSync', + 'writevSync' +] +const collector = createGatedCallCollector( + [ + { + modules: ['fs', 'node:fs', 'original-fs', 'graceful-fs'], + advice: Object.fromEntries(SYNC_FS.map((name) => [name, ADVICE])) + } + ], + 'main sync-fs' +) + +function isScannedPath(rel) { + return /\.[cm]?[jt]sx?$/.test(rel) && !rel.endsWith('.d.ts') && !isTestOnlySourcePath(rel) +} + +export function countSyncFsCalls(rel, source) { + return collector.collectUses(rel, source).count +} + +export function collectMainSyncFsCounts(root = process.cwd()) { + const counts = new Map() + for (const [rel, source] of readTrackedSources(root, SCAN_ROOTS, isScannedPath)) { + const count = countSyncFsCalls(rel, source) + if (count > 0) { + counts.set(rel, count) + } + } + return counts +} + +export function main(root = process.cwd(), arg = undefined) { + return runCountRatchet( + { + name: 'main-sync-fs', + baselinePath: BASELINE_PATH, + header: [ + '# Synchronous node:fs calls (every *Sync export) in production src/main and src/shared, per file.', + '# Startup-only or one-shot uses are fine to keep; per-RPC, per-spawn, per-focus or per-poll uses are the target.', + '# This is a RATCHET: counts may only go DOWN.', + '# Prune after removing calls: pnpm check:main-sync-fs-ratchet --prune' + ], + collect: collectMainSyncFsCounts, + unit: 'sync fs call(s)', + fix: [ + `Sync fs blocks the thread it runs on: Electron main (every window) or the daemon/orcad loop (every terminal). ${ADVICE}.`, + `A one-shot startup or shutdown use may raise the file's count in ${BASELINE_PATH} with reviewer sign-off.` + ] + }, + root, + arg + ) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd(), process.argv[2])) +} diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs new file mode 100644 index 00000000000..e038949c153 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs @@ -0,0 +1,168 @@ +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import ts from 'typescript-api' +import { createGatedCallCollector } from '../../process-boundaries/gated-call-use-collector.mjs' +import { readTrackedSources, runCountRatchet } from '../../ratchet-baseline/ratchet-baseline.mjs' +import { isTestOnlySourcePath } from '../../process-boundaries/test-only-source-path.mjs' + +// Fixed-cadence polls that never back off, settle or pause while hidden were the most common perf fix class (#39734, #38902, #33829, #39650). + +const BASELINE_PATH = 'config/recurring-timer-baseline.txt' +const SCAN_ROOTS = ['src/main', 'src/renderer/src', 'src/shared', 'src/cli'] +const TIMER_HOSTS = new Set(['window', 'globalThis', 'self', 'global']) +const TIMER_MODULES = ['timers', 'node:timers', 'timers/promises', 'node:timers/promises'] +const timerImports = createGatedCallCollector( + [ + { + modules: TIMER_MODULES, + advice: { setInterval: 'prefer a push signal or a backing-off timer' } + } + ], + 'recurring-timer' +) + +function isScannedPath(rel) { + return /\.[cm]?[jt]sx?$/.test(rel) && !rel.endsWith('.d.ts') && !isTestOnlySourcePath(rel) +} + +function isHostInterval(node) { + if (!ts.isIdentifier(node.expression) || !TIMER_HOSTS.has(node.expression.text)) { + return false + } + if (ts.isPropertyAccessExpression(node)) { + return node.name.text === 'setInterval' + } + return ( + ts.isElementAccessExpression(node) && + ts.isStringLiteralLike(node.argumentExpression) && + node.argumentExpression.text === 'setInterval' + ) +} + +// Skips transparent wrappers so `typeof (setInterval)` and `(setInterval) = x` read like the bare forms. +function outerExpression(node) { + let current = node + while (ts.isParenthesizedExpression(current.parent)) { + current = current.parent + } + return current +} + +// Reads the timer value: not a plain `=` target (compound assignments read it), a `typeof` probe or a JSX tag name. +function isRuntimeRead(node) { + const outer = outerExpression(node) + const parent = outer.parent + return !( + ts.isTypeOfExpression(parent) || + (ts.isBinaryExpression(parent) && + parent.left === outer && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) || + ((ts.isJsxOpeningElement(parent) || + ts.isJsxSelfClosingElement(parent) || + ts.isJsxClosingElement(parent)) && + parent.tagName === node) + ) +} + +// A value reference to the identifier, not a declaration, member name or key. +function isBareValueReference(node) { + const parent = node.parent + return ( + isRuntimeRead(node) && + !( + (ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isPropertyAssignment(parent) && parent.name === node) || + ts.isImportSpecifier(parent) || + ts.isExportSpecifier(parent) || + (ts.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) || + (ts.isVariableDeclaration(parent) && parent.name === node) || + (ts.isParameter(parent) && parent.name === node) || + ((ts.isFunctionDeclaration(parent) || ts.isMethodDeclaration(parent)) && parent.name === node) + ) + ) +} + +const SCOPE_OPTIONS = { noLib: true, noResolve: true, allowJs: true, types: [] } + +// Counts references, not calls, to the global timer, so `const every = setInterval; every(f)` and +// `window['setInterval']` are charged once. A bare name is the global when it binds to nothing +// declared in this file (resolved per scope); module bindings and their aliases are the collector's. +function countGlobalTimerReferences(source) { + const host = ts.createCompilerHost(SCOPE_OPTIONS) + host.getSourceFile = (name) => (name === source.fileName ? source : undefined) + const checker = ts.createProgram([source.fileName], SCOPE_OPTIONS, host).getTypeChecker() + let count = 0 + const visit = (node) => { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { + return + } + if ( + (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + isHostInterval(node) && + isRuntimeRead(node) + ) { + count += 1 + } else if (ts.isIdentifier(node) && node.text === 'setInterval' && isBareValueReference(node)) { + // A shorthand `{ setInterval }` names the property; its value is the binding being read. + const symbol = ts.isShorthandPropertyAssignment(node.parent) + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : checker.getSymbolAtLocation(node) + const declarations = symbol?.declarations ?? [] + if (!declarations.some((declaration) => declaration.getSourceFile() === source)) { + count += 1 + } + } + ts.forEachChild(node, visit) + } + visit(source) + return count +} + +export function countRecurringTimers(rel, source) { + if (!source.includes('setInterval')) { + return 0 + } + const file = ts.createSourceFile(rel, source, ts.ScriptTarget.Latest, true) + return countGlobalTimerReferences(file) + timerImports.collectUses(rel, source).count +} + +export function collectRecurringTimerCounts(root = process.cwd()) { + const counts = new Map() + for (const [rel, source] of readTrackedSources(root, SCAN_ROOTS, isScannedPath)) { + const count = countRecurringTimers(rel, source) + if (count > 0) { + counts.set(rel, count) + } + } + return counts +} + +export function main(root = process.cwd(), arg = undefined) { + return runCountRatchet( + { + name: 'recurring-timer', + baselinePath: BASELINE_PATH, + header: [ + '# setInterval calls (global, or imported from node:timers / node:timers/promises) in production src/main,', + '# src/renderer, src/shared and src/cli, per file. Bare calls are resolved per scope; imported bindings follow the shared', + '# collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden).', + '# This is a RATCHET: counts may only go DOWN.', + '# Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune' + ], + collect: collectRecurringTimerCounts, + unit: 'setInterval call(s)', + fix: [ + 'A fixed-cadence interval keeps working when nothing changes, the window is hidden or its dependency keeps failing.', + 'Prefer a push signal; otherwise use installWindowVisibilityInterval (renderer) or a timer that backs off and stops when idle.', + 'Rewriting it as a self-rescheduling setTimeout at the same fixed cadence is the same bug; review will treat it so.', + `An interval whose cadence is the feature (a clock, a heartbeat with a stop) may raise the file's count in ${BASELINE_PATH} with reviewer sign-off.` + ] + }, + root, + arg + ) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd(), process.argv[2])) +} diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs new file mode 100644 index 00000000000..51223986d45 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { countRecurringTimers } from './check-recurring-timer-ratchet.mjs' + +describe('recurring-timer ratchet', () => { + it.each([ + ['setInterval(poll, 1000)', 1], + ['window.setInterval(poll, 1)\nglobalThis.setInterval(poll, 1)\nobj.setInterval(1)', 2], + [ + "import { setInterval } from 'node:timers'\nsetInterval(poll, 1)\nwindow.setInterval(poll, 1)", + 2 + ], + ["const { setInterval } = require('node:timers')\nsetInterval(poll, 1)", 1], + ["import { setInterval as every } from 'node:timers/promises'\nevery(5000)", 1], + // Alias and destructure forms of an imported timer count once, like the direct call. + [ + "import * as timers from 'node:timers'\nconst setInterval = timers.setInterval\nsetInterval(poll, 1)", + 1 + ], + [ + "const timers = require('node:timers')\nconst { setInterval } = timers\nsetInterval(poll, 1)", + 1 + ], + ["const { setInterval } = await import('node:timers')\nsetInterval(poll, 1)", 1], + // An unrelated local binding must not hide a global poll elsewhere in the file. + ['function configure(setInterval) {\n return setInterval\n}\nsetInterval(poll, 1000)', 1], + ['type Configure = (setInterval: number) => void\nsetInterval(poll, 1000)', 1], + ['function a(setInterval) { setInterval(f) }\nfunction b() { setInterval(g, 1) }', 1], + ['function setInterval(f) {}\nsetInterval(poll)', 0], + // Aliases and bracket access of the global timer are charged at the reference. + ['const schedule = setInterval\nschedule(poll, 1000)', 1], + ["window['setInterval'](poll, 1000)", 1], + ['const every = window.setInterval\nevery(poll, 1)', 1], + ["if (typeof setInterval === 'function') {}\ntype T = typeof setInterval", 0], + ['const deps = { setInterval, clearInterval }\ndeps.setInterval(poll, 1)', 1], + ["setInterval = replacement\nwindow['setInterval'] = replacement\ntypeof (setInterval)", 0], + ['(window.setInterval ||= fallback)(poll, 1000)', 1] + ])('counts %s', (source, count) => { + expect(countRecurringTimers('src/main/example.ts', source)).toBe(count) + }) +}) 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 ab708cb3808..3fc7dd70837 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 @@ -92,7 +92,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/**/*allocation*.test.ts', 'src/**/*expiry*.test.ts', 'src/shared/own-retained-string.test.ts', - 'src/main/agent-hooks/server-transport-interference.test.ts', + 'src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts', 'src/main/plugins/workers/plugin-worker-supervision.integration.test.ts', 'src/main/plugins/workers/plugin-worker-dev-restart-storage.integration.test.ts', // Worker TypeScript loads through node:module registerHooks, which Bun lacks. @@ -123,12 +123,12 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts', 'src/main/browser/cookies/sources/browser-cookie-source-partition.test.ts', // Playwright's CDP transport needs Node's WebSocket implementation. - 'src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', 'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/ai-vault/scanners/devin/session-scanner-devin-db.test.ts', 'src/shared/workspace-session/workspace-session-salvage.test.ts', 'src/main/git/repo-detection.test.ts', diff --git a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs index bb2fb961100..c6c1856325e 100644 --- a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs +++ b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs @@ -102,8 +102,8 @@ const CODEX_INDEX_HEAL_CONTRACT_PREFIXES = [ 'src/main/codex/trust/identity/codex-trust-identity', 'src/main/codex/trust/toml/config-toml-hook-trust-', 'src/main/codex/configuration/toml/config-toml-key-path', - 'src/main/agent-hooks/posix-hook-command', - 'src/main/agent-hooks/hook-post-command', + 'src/main/agent-hooks/installation/commands/posix-hook-command', + 'src/main/agent-hooks/installation/scripts/hook-post-command', 'src/main/codex-cli/codex-read-only-app-server-args', 'src/main/agent-launch/trust/agent-trust-presets', 'src/main/codex/trust/toml/config-toml-trust', 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 29530b99e35..3166e02549d 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -126,14 +126,14 @@ export const WINDOWS_PACKAGE_PREFIXES = [ export const LINUX_PACKAGE_TESTS = [ 'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts', 'config/scripts/desktop-distribution/runtime-verification/packaged-repository-input-exclusion.test.mjs', - 'src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', 'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts', 'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts', 'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts', 'src/main/browser/extensions/profile-storage/browser-extension-persistence.electron.test.ts', 'src/main/browser/extensions/profile-sessions/browser-extension-lifecycle.electron.test.ts', @@ -173,14 +173,14 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts', 'src/shared/agent-launch/startup/omp-fresh-launch-cmd.win32.test.ts', 'src/shared/windows-batch-spawn.win32.test.ts', - 'src/main/agent-hooks/windows-hook-payload-delivery.test.ts', - 'src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts', + 'src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts', + 'src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts', 'src/main/jcode/hook-gate-script.test.ts', - 'src/main/agent-hooks/windows-native-hook-exe-hosts.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/windows-cmd-hook-command-unicode.test.ts', - 'src/main/agent-hooks/windows-batch-hook-launcher.test.ts', - 'src/main/agent-hooks/windows-powershell-hook-launcher.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/vitest.performance.config.ts b/config/vitest.performance.config.ts index 764857f9fe3..00967828447 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -23,7 +23,8 @@ const contracts = [ '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', - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + 'src/main/claude-usage/store-checkpoint-persistence.test.ts', + 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/docs/agents-md-refs/protected-telemetry-milestones/migration.json b/docs/agents-md-refs/protected-telemetry-milestones/migration.json new file mode 100644 index 00000000000..d5106116094 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/migration.json @@ -0,0 +1,1300 @@ +{ + "project_id": 406068, + "prepared": "2026-11-08", + "event_contract": "implementation worktree /tmp/orca-protected-telemetry/event-contract.json version 3 (implemented-locally-not-deployed)", + "applied": { + "insights": [ + { + "id": 9790198, + "url": "https://us.posthog.com/project/406068/insights/2M4eYB5Y", + "dashboards": [1795002], + "name": "D1/D3/D7/D30/D60/D90 active return: all vs agent_started", + "field": "description", + "before": "Fresh-install retention from first onboarding_started. Active means any app telemetry event on calendar days 1-N after start. D60/D90 show null until cohorts mature; telemetry opt-outs excluded. App-only; no website.", + "after": "Fresh-install retention from first onboarding_started. Active means any app telemetry event on calendar days 1-N after start. D60/D90 show null until cohorts mature; telemetry opt-outs excluded. App-only; no website. LEGACY: background-only and launch-only days count as active; not meaningful use. daemon_audit_eligibility is 0.1% sampled from 1.4.248 (2026-11-04).", + "refresh_check": "ok" + }, + { + "id": 8521005, + "url": "https://us.posthog.com/project/406068/insights/R7LdubT0", + "dashboards": [1570255], + "name": "D1/D3/D7 active return (any app event)", + "field": "description", + "before": "Fresh-install cohorts from first onboarding_started. Active means any app telemetry event on calendar day 1, days 1-3, or days 1-7 after start, including app_opened. Excludes telemetry opt-outs. App-only; no website.", + "after": "Fresh-install cohorts from first onboarding_started. Active means any app telemetry event on calendar day 1, days 1-3, or days 1-7 after start, including app_opened. Excludes telemetry opt-outs. App-only; no website. LEGACY: background-only and launch-only days count as active; not meaningful use. daemon_audit_eligibility is 0.1% sampled from 1.4.248 (2026-11-04).", + "refresh_check": "ok" + }, + { + "id": 11047236, + "url": "https://us.posthog.com/project/406068/insights/B4YE6JT8", + "dashboards": [1997904], + "name": "2-week / 30-day / 2-month window return (fresh installs)", + "field": "description", + "before": "Not any-return-by-day-N. Returned = any app event in days 8-14 / 24-30 / 54-60 after first onboarding_started (fresh_install). Eligible only after the window ends. Opt-outs excluded. Full UTC days through yesterday. App-only; no website.", + "after": "Not any-return-by-day-N. Returned = any app event in days 8-14 / 24-30 / 54-60 after first onboarding_started (fresh_install). Eligible only after the window ends. Opt-outs excluded. Full UTC days through yesterday. App-only; no website. LEGACY: background-only and launch-only days count as active; not meaningful use. daemon_audit_eligibility is 0.1% sampled from 1.4.248 (2026-11-04).", + "refresh_check": "ok" + }, + { + "id": 8418983, + "url": "https://us.posthog.com/project/406068/insights/bH1SnEQ0", + "dashboards": [1552346], + "name": "Any app activity daily active installs", + "field": "description", + "before": "Daily distinct installs with any Orca desktop app activity, including background app events. Requires install_id and orca_channel; website traffic and telemetry_opted_out events excluded. Not total installed base; telemetry-disabled installs are invisible.", + "after": "Daily distinct installs with any Orca desktop app activity, including background app events. Requires install_id and orca_channel; website traffic and telemetry_opted_out events excluded. Not total installed base; telemetry-disabled installs are invisible. Background events include daemon_audit_eligibility, 0.1% sampled from 1.4.248 (2026-11-04); not meaningful use.", + "refresh_check": "ok" + }, + { + "id": 13415841, + "url": "https://us.posthog.com/project/406068/insights/imWppJ9J", + "dashboards": [2258914], + "name": "LIVE: 24h confirmed agent prompt by randomized assignment", + "field": "description", + "before": "Fresh-install first onboarding since Oct 23 21:50 UTC; full 24h follow-up; event cutoff now minus 15 minutes. agent_prompt_sent is hook-confirmed input; count is installs with a prompt, not conversations. Unknown assignment excluded; opt-outs retained. Selector visibility is not directly tracked.", + "after": "Fresh-install first onboarding since Oct 23 21:50 UTC; full 24h follow-up; cutoff now minus 15 min. agent_prompt_sent is hook-confirmed input; counts installs with a prompt, not conversations. Unknown assignment excluded; opt-outs retained. Selector visibility not tracked. agent_prompt_sent is 1% sampled per event from 1.4.248 (2026-11-04 02:37 UTC); later rates undercount and are not rescalable.", + "refresh_check": "ok" + }, + { + "id": 9052828, + "url": "https://us.posthog.com/project/406068/insights/fXsB9Izz", + "dashboards": [1562016], + "name": "Onboarding funnel with user prompt sent", + "field": "description", + "before": "Fresh-install funnel after agent_prompt_sent appeared 2026-05-29 23:33 UTC. Code-verified: agent_prompt_sent means a non-empty user prompt was delivered/observed, not an assistant response. Current rows are hook-sourced launch_source=unknown. App-only; no website.", + "after": "Fresh-install funnel after agent_prompt_sent appeared 2026-05-29 23:33 UTC. Code-verified: agent_prompt_sent means a non-empty user prompt was delivered/observed, not an assistant response. Current rows are hook-sourced launch_source=unknown. App-only; no website. agent_prompt_sent is 1% sampled per event from 1.4.248 (2026-11-04 02:37 UTC); later rates undercount and are not rescalable.", + "refresh_check": "pre-existing out-of-memory on unchanged query (no cached result in pre-edit backup)" + }, + { + "id": 9077994, + "url": "https://us.posthog.com/project/406068/insights/iqibpxMi", + "dashboards": [1552346], + "name": "Agent usage by tracked agent over time", + "field": "description", + "before": "Daily distinct installs that used each tracked agent_kind. Counts agent_started or agent_prompt_sent once per install/day/agent_kind with no rollup bucket. agent_prompt_sent starts 2026-05-29, so earlier days mostly reflect starts. App-only; no website.", + "after": "Daily distinct installs that used each tracked agent_kind. Counts agent_started or agent_prompt_sent once per install/day/agent_kind with no rollup bucket. agent_prompt_sent starts 2026-05-29, so earlier days mostly reflect starts. App-only; no website. agent_prompt_sent is 1% sampled per event from 1.4.248 (2026-11-04 02:37 UTC); later rates undercount and are not rescalable.", + "refresh_check": "ok" + }, + { + "id": 9860787, + "url": "https://us.posthog.com/project/406068/insights/9StQAkAI", + "dashboards": [1552346], + "name": "Prompt users using 2+ agent harnesses in trailing 7d", + "field": "description", + "before": "Rolling full-UTC 7d windows. Denominator = users with agent_prompt_sent to any agent_kind; numerator = users with prompts to >1 distinct agent_kind. Uses prompt_sent, not agent_started, to avoid auto-start inflation. agent_prompt_sent began late 2026-05-29 UTC, so chart starts 2026-06-05. App-only; no website.", + "after": "Rolling full-UTC 7d windows. Denominator = users with agent_prompt_sent to any agent_kind; numerator = users with prompts to >1 distinct agent_kind. Uses prompt_sent, not agent_started, to avoid auto-start inflation. agent_prompt_sent began late 2026-05-29 UTC, so chart starts 2026-06-05. App-only; no website. Prompts are 1% sampled per event from 1.4.248 (2026-11-04); later windows undercount.", + "refresh_check": "ok" + }, + { + "id": 13282177, + "url": "https://us.posthog.com/project/406068/insights/3JTv1Zyc", + "dashboards": [2258914], + "name": "D1 and D3 retention by assignment: agent prompts, native chat and app reopening", + "field": "description", + "before": "LIVE on refresh; cutoff=now minus 15m. D1=[24h,48h), D3=[72h,96h) after first fresh-install onboarding from Oct 23 21:50 UTC. All starters with a full window; opt-outs retained. Three independent signals, not conversation counts. D3 rates are NULL until eligible; first windows complete around Oct 27 21:50 UTC. Assignment is not a selector impression. See dashboard description for live and snapshot", + "after": "LIVE on refresh; cutoff=now minus 15m. D1=[24h,48h), D3=[72h,96h) after first fresh-install onboarding from Oct 23 21:50 UTC; starters with a full window; opt-outs retained. Three independent signals, not conversation counts. Assignment is not a selector impression. Prompt signal is 1% sampled per event from 1.4.248 (2026-11-04): later cohorts undercount it.", + "refresh_check": "ok" + }, + { + "id": 9104852, + "url": "https://us.posthog.com/project/406068/insights/ZtyZtRM1", + "dashboards": [1562016], + "name": "Fresh-install activation milestones over time", + "field": "description", + "before": "Daily fresh-install cohorts since 2026-05-09. 'Agent auto-started' fires automatically on worktree creation, so it tracks reaching a worktree, not engagement; 'Prompt sent' is the real activation line. agent_prompt_sent starts 2026-05-29; tour/setup lines start 2026-06-03 and are null before. Current day partial. App-only; no website.", + "after": "Daily fresh-install cohorts since 2026-05-09. 'Agent auto-started' fires on worktree creation, so it tracks reaching a worktree, not engagement. 'Prompt sent' starts 2026-05-29 and is 1% sampled per event from 1.4.248 (2026-11-04), so its later drop is sampling, not behavior. Tour/setup lines start 2026-06-03. Current day partial. App-only; no website.", + "refresh_check": "ok" + }, + { + "id": 9108955, + "url": "https://us.posthog.com/project/406068/insights/MWGe77xd", + "dashboards": [1562016], + "name": "Fresh-install retention by first-session behavior (D1/D7)", + "field": "description", + "before": "D1/D7 return by first-session behavior. Fresh-install cohort, distinct_id, mature denominators. Buckets mutually exclusive by precedence: sent prompt > agent auto-started (no prompt) > project-ready (no agent) > abandoned. OBSERVATIONAL/self-selected, not causal. 'Sent prompt' D7 is survivorship-biased (agent_prompt_sent only since 2026-05-29); trust the D1 gradient. App-only; no website.", + "after": "D1/D7 return by first-session behavior; fresh installs, mature denominators. Buckets by precedence: sent prompt > agent auto-started > project-ready > abandoned. OBSERVATIONAL, not causal. 'Sent prompt' starts 2026-05-29 and is 1% sampled from 1.4.248 (2026-11-04), so later prompt senders fall into lower buckets. Trust the D1 gradient. App-only; no website.", + "refresh_check": "pre-existing out-of-memory on unchanged query (no cached result in pre-edit backup)" + } + ], + "dashboards": [ + { + "id": 1795002, + "url": "https://us.posthog.com/project/406068/dashboard/1795002", + "name": "Orca detailed retention", + "field": "description", + "before": "Investor review dashboard for fresh-install retention: D1/D3/D7/D30/D60/D90 active return, weekly cohorts, platform split, and repo-cohort retention. D60/D90 are expected to show no eligible users until cohorts mature. Active means any app telemetry event after day 0; telemetry opt-outs excluded. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic.", + "after": "Investor review dashboard for fresh-install retention: D1/D3/D7/D30/D60/D90 active return, weekly cohorts, platform split, and repo-cohort retention. D60/D90 are expected to show no eligible users until cohorts mature. Active means any app telemetry event after day 0; telemetry opt-outs excluded. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic. LEGACY note (2026-11-08): 'any app telemetry/event' also counts background-only days (e.g. daemon_audit_eligibility, 0.1% sampled from 1.4.248 since 2026-11-04) and launch-only days, so this is not meaningful-use retention. No meaningful-activity retention metric is live yet. Comeback tiles' agent_prompt_sent input is 1% sampled from 1.4.248." + }, + { + "id": 1997904, + "url": "https://us.posthog.com/project/406068/dashboard/1997904", + "name": "Orca 2-week / 30-day / 2-month retention", + "field": "description", + "before": "Fresh-install window retention by platform. 2-week = any app event on days 8-14, 30-day = 24-30, 2-month = 54-60. Not 'any return by day N'. Weekly trends are split macOS/Windows/Linux (20+ mature users per series). Volume tile is mix only. Anchored on first onboarding_started cohort=fresh_install from 2026-05-09; opt-outs excluded. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic.", + "after": "Fresh-install window retention by platform. 2-week = any app event on days 8-14, 30-day = 24-30, 2-month = 54-60. Not 'any return by day N'. Weekly trends are split macOS/Windows/Linux (20+ mature users per series). Volume tile is mix only. Anchored on first onboarding_started cohort=fresh_install from 2026-05-09; opt-outs excluded. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic. LEGACY note (2026-11-08): 'any app telemetry/event' also counts background-only days (e.g. daemon_audit_eligibility, 0.1% sampled from 1.4.248 since 2026-11-04) and launch-only days, so this is not meaningful-use retention. No meaningful-activity retention metric is live yet." + }, + { + "id": 1570255, + "url": "https://us.posthog.com/project/406068/dashboard/1570255", + "name": "Orca retention", + "field": "description", + "before": "Fresh-install retention from first onboarding_started cohort=fresh_install. D1/D3/D7 active means any app telemetry event on the exact calendar day after start, including app_opened. Agent-started chart limits denominator to users who reached agent_started. All retention tiles exclude telemetry opt-outs. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic.", + "after": "Fresh-install retention from first onboarding_started cohort=fresh_install. D1/D3/D7 active means any app telemetry event on the exact calendar day after start, including app_opened. Agent-started chart limits denominator to users who reached agent_started. All retention tiles exclude telemetry opt-outs. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic. LEGACY note (2026-11-08): 'any app telemetry/event' also counts background-only days (e.g. daemon_audit_eligibility, 0.1% sampled from 1.4.248 since 2026-11-04) and launch-only days, so this is not meaningful-use retention. No meaningful-activity retention metric is live yet." + }, + { + "id": 2258914, + "url": "https://us.posthog.com/project/406068/dashboard/2258914", + "name": "Onboarding language selector: agent usage, conversion and D1/D3 retention", + "field": "description", + "before": "Updated Oct 28: LIVE first-project conversion, confirmed prompt usage and D1/D3 retention use a 15-minute ingestion margin. Other tiles retain their Oct 25 snapshot; the original combined query timed out at the larger data volume. Randomized assignment is not a verified selector impression. D3 is activity during hours 72–96, among installs with complete follow-up.", + "after": "Updated Oct 28: LIVE first-project conversion, confirmed prompt usage and D1/D3 retention use a 15-minute ingestion margin. Other tiles retain their Oct 25 snapshot; the original combined query timed out at the larger data volume. Randomized assignment is not a verified selector impression. D3 is activity during hours 72–96, among installs with complete follow-up. Note (2026-11-08): agent_prompt_sent is randomly 1% sampled per event from 1.4.248 (first seen 2026-11-04 02:37 UTC); prompt-based rates for later cohorts undercount and cannot be rescaled to installs. native_chat_message_sent and app_opened are unsampled." + }, + { + "id": 1562016, + "url": "https://us.posthog.com/project/406068/dashboard/1562016", + "name": "Orca onboarding funnel (new users)", + "field": "description", + "before": "Fresh-install onboarding analysis anchored on first onboarding_started where cohort=fresh_install, grouped by PostHog distinct_id as install identity. Completion is not workspace_created alone: corrected completion is repo workspace through onboarding + folder completion + git completion without onboarding workspace. Folder completion is a real success path; git-completed/no-onboarding-workspace is a separate handoff bucket. workspace_created source=onboarding is linked git worktree create success, not workspace availability. D1+/D3+ means app_opened >=24h/>=72h after start with mature denominators. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic.", + "after": "Fresh-install onboarding analysis anchored on first onboarding_started where cohort=fresh_install, grouped by PostHog distinct_id as install identity. Completion is not workspace_created alone: corrected completion is repo workspace through onboarding + folder completion + git completion without onboarding workspace. Folder completion is a real success path; git-completed/no-onboarding-workspace is a separate handoff bucket. workspace_created source=onboarding is linked git worktree create success, not workspace availability. D1+/D3+ means app_opened >=24h/>=72h after start with mature denominators. Scope: Orca Electron app events with install_id and orca_channel; excludes onorca.dev website traffic. Note (2026-11-08): agent_prompt_sent is randomly 1% sampled per event from 1.4.248 (first seen 2026-11-04 02:37 UTC); prompt-based rates for later cohorts undercount and cannot be rescaled to installs. onboarding_completed has not carried is_git_repo since 2026-06-11 (it moved to repo_added.is_git_repo); tiles splitting completion by that field miss later folder/git completions." + } + ], + "unchanged": "queries, names, tiles, filters, dashboard membership, experiments", + "checks": "PATCH responses matched new descriptions; query, name and dashboards byte-identical to backups; dashboard tiles and filters unchanged. Backups: /tmp/orca-protected-telemetry/dashboard-backups-2026-11-08/." + }, + "staged_insights": [ + { + "key": "daily_meaningful_installs", + "dashboard_ids": [1534940], + "gate_step": 4, + "name": "Daily explicit-activity installs vs launched installs (supporting builds)", + "description": "Distinct installs with meaningful_activity_day per complete UTC day: explicit desktop/mobile-chat actions incl. terminal typing; never launch, resume, hook-only prompt or background. Misses phone-terminal and paired remote-runtime-only days, so not complete retention. Launched = app_opened on supporting builds. Starts at measured first-seen; no backfill.", + "query": { + "kind": "DataVisualizationNode", + "display": "ActionsLineGraph", + "source_file": "queries/daily-meaningful-installs.sql", + "chartSettings": { + "xAxis": { + "column": "day" + }, + "yAxis": [ + { + "column": "meaningful_installs" + }, + { + "column": "meaningful_fresh_installs" + }, + { + "column": "launched_installs_on_supporting_builds" + } + ] + } + } + }, + { + "key": "activation_24h", + "dashboard_ids": [1562016], + "gate_step": 5, + "name": "Fresh installs: workspace available and first observed agent interaction within 24h, by platform", + "description": "Anchor = first onboarding_started fresh_install on a supporting build, opt-outs excluded, full 24h+15m follow-up. Interaction = first_agent_interaction install_cohort=fresh: observed prompt/message submission, not provider success or agent launch. unattributed_prompt (may be automation) shown separately. Workspace = create, default checkout opened, or any repo_added with is_git_repo=false within the activation window; this is distinct from the onboarding repair's legacy/first-repo git/folder classification.", + "query": { + "kind": "DataTableNode", + "source_file": "queries/activation-24h.sql" + } + }, + { + "key": "activation_7d", + "dashboard_ids": [1562016], + "gate_step": 5, + "name": "Fresh installs: workspace available and first observed agent interaction within 7d, by platform", + "description": "Same definition as the 24h tile with a 7d window and full 7d+15m follow-up. install_cohort_mismatch counts fresh anchors whose first interaction is tagged existing (e.g. onboarding restarted after upgrade); they are not activations. Supporting builds are observed from data, not a hard-coded release.", + "query": { + "kind": "DataTableNode", + "source_file": "queries/activation-7d.sql" + } + }, + { + "key": "launch_vs_meaningful_return", + "dashboard_ids": [1795002, 1997904], + "gate_step": 6, + "name": "Fresh-install launch return vs explicit-activity return by platform (D1, D3, D7, 2-week, 30-day window)", + "description": "Same fresh-install cohort and complete-follow-up denominators. Explicit = meaningful_activity_day (desktop/mobile-chat actions; misses phone-terminal and paired remote-runtime-only days, so not complete retention); launch = app_opened. UTC days after anchor day; D3/D7 = return by that day. NULL until eligible. Legacy any-event tiles stay as history; do not join lines.", + "query": { + "kind": "DataTableNode", + "source_file": "queries/launch-vs-meaningful-return.sql" + } + } + ], + "post_cutover_relabels": [ + { + "id": 9790198, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 8521005, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047236, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790246, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790248, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790612, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047427, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047428, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047238, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047421, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047422, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047423, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 8821536, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9026328, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9053637, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047425, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 11047426, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790360, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790608, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790609, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + }, + { + "id": 9790610, + "action": "prefix name with 'Legacy any-event: ' and append pointer to launch_vs_meaningful_return", + "gate_step": 7 + } + ], + "gate_query": "queries/cutover-gate.sql", + "coverage_query": "queries/fresh-anchor-version-coverage.sql", + "inventory": { + "source": "GET /insights/?saved=true (168 insights, 2 pages) and GET /dashboards/ (14 dashboards), 2026-11-08", + "note": "depends_on is a text match on the saved query; any_event = HogQL event != 'telemetry_opted_out', RetentionQuery 'All events', or TrendsQuery all-events series.", + "insights": [ + { + "id": 8417925, + "short_id": "3ANPcn7Z", + "name": "Deprecated: old event-local onboarding cohort funnel", + "dashboards": [], + "kind": "FunnelsQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8417928, + "short_id": "x8s3DQ46", + "name": "Agent health: started vs error (by agent_kind)", + "dashboards": [], + "kind": "TrendsQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8417929, + "short_id": "PUSiijPG", + "name": "Daily active installs (by orca_channel)", + "dashboards": [], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8418984, + "short_id": "76Omnk6t", + "name": "Lifecycle: new vs returning vs dormant", + "dashboards": [], + "kind": "LifecycleQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8418991, + "short_id": "tBcaNJRH", + "name": "Activation gap: repo_added without agent_started by cohort", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8471929, + "short_id": "9r3roYHQ", + "name": "First-time-user workspace creation: success vs failure", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8471930, + "short_id": "o5scu9rP", + "name": "First-time-user agent_error by error_class", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8474106, + "short_id": "nFFKDzAT", + "name": "First repo -> agent activation by repo entry method", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8521002, + "short_id": "8SMrVf3T", + "name": "Retention: app_opened (all installs, daily)", + "dashboards": [], + "kind": "RetentionQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8521208, + "short_id": "t4EmcmK7", + "name": "Agents spawned per day, by agent_kind", + "dashboards": [], + "kind": "TrendsQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8521297, + "short_id": "Di97BXic", + "name": "Feature retention: D1 / D3 / D7 by feature (first-time anchored)", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8522315, + "short_id": "mcfl279F", + "name": "Event breadth vs no meaningful activity in 2d", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8663728, + "short_id": "NG7ML4jW", + "name": "First repo users by repo entry method", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8712884, + "short_id": "zNMGJoKC", + "name": "Fresh installs D3-any return after onboarding decision", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8821531, + "short_id": "aTQUzcsu", + "name": "QA inline tour outcome + completion", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8845563, + "short_id": "uqz23Lpr", + "name": "Fast D3 estimate: D1 calendar-day return", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 9026641, + "short_id": "kANxeILs", + "name": "Fresh installs D3-any meaningful work after onboarding/platform", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent"] + }, + { + "id": 9027034, + "short_id": "altQ3ADh", + "name": "Fresh installs D3-any return or work after onboarding decision", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started", "agent_prompt_sent"] + }, + { + "id": 11047237, + "short_id": "0BabDjdq", + "name": "Weekly cohorts: 2-week / 30-day / 2-month window return", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 13128607, + "short_id": "cCAEiuKu", + "name": "Directional tab-close adoption — sampled installs — Oct 21, 2026", + "dashboards": [], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8320041, + "short_id": "L6Ram2oh", + "name": "Daily active installs (app_opened)", + "dashboards": [1534940], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8320042, + "short_id": "j6upDpBw", + "name": "Weekly active installs (calendar weeks, app_opened)", + "dashboards": [1534940], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8320043, + "short_id": "uZgKuV7O", + "name": "Desktop app retention (app_opened)", + "dashboards": [1534940], + "kind": "RetentionQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8320044, + "short_id": "vpQI0yxv", + "name": "App activity growth accounting", + "dashboards": [1534940], + "kind": "LifecycleQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8320045, + "short_id": "3fMXHgFP", + "name": "Active installs by platform (last 14 days)", + "dashboards": [1534940], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8418983, + "short_id": "bH1SnEQ0", + "name": "Any app activity daily active installs", + "dashboards": [1552346], + "kind": "TrendsQuery", + "depends_on": ["any_event"] + }, + { + "id": 8418985, + "short_id": "vl3vR14W", + "name": "Stickiness: days active per week", + "dashboards": [1552346], + "kind": "StickinessQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8418986, + "short_id": "AIJVy8Xo", + "name": "Active installs by platform", + "dashboards": [1552346], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8418987, + "short_id": "TwguqKxo", + "name": "Daily active installs, stacked by app_version", + "dashboards": [1552346], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8521270, + "short_id": "5czjaMIK", + "name": "Distinct installs using each feature, per day", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8997693, + "short_id": "uK16O44a", + "name": "In-app repo stars by entry point", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 9077994, + "short_id": "iqibpxMi", + "name": "Agent usage by tracked agent over time", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent"] + }, + { + "id": 9860787, + "short_id": "9StQAkAI", + "name": "Prompt users using 2+ agent harnesses in trailing 7d", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["agent_prompt_sent"] + }, + { + "id": 11047583, + "short_id": "UbAuGqUG", + "name": "Linux users by latest app_version", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047658, + "short_id": "z3hpN56W", + "name": "On latest version: Linux vs Mac vs Windows", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047659, + "short_id": "79Wr5uD7", + "name": "Version recency mix by platform (14d fleet %)", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047660, + "short_id": "PPNSi5cZ", + "name": "App version distribution % by platform (top 12)", + "dashboards": [1552346], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 12434947, + "short_id": "N3kKYYHt", + "name": "Monthly active installs (app_opened, rolling 30 days)", + "dashboards": [1552346], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8471904, + "short_id": "XGjEOVWr", + "name": "Accepted repo/folder outcomes", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8471908, + "short_id": "MHjWVHlC", + "name": "First-time-user setup-step actions (post-rollout event)", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8471954, + "short_id": "mCbBnKPZ", + "name": "First-time users per day: opened-app vs added-first-repo", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8797194, + "short_id": "o3qfzye3", + "name": "Git completed, no onboarding workspace: later behavior", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8821536, + "short_id": "5NRXvb4z", + "name": "D3 active return by app version: all vs agent_started", + "dashboards": [1562016, 1570255], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "any_event"] + }, + { + "id": 8838695, + "short_id": "zyaXq4lJ", + "name": "Onboarding funnel: where users leave before completion", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 8923273, + "short_id": "3oewonyF", + "name": "Fresh-install high-level activation funnel", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8923532, + "short_id": "zKoJri8Y", + "name": "What happened before project-ready endpoint?", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["agent_started"] + }, + { + "id": 9052828, + "short_id": "fXsB9Izz", + "name": "Onboarding funnel with user prompt sent", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent"] + }, + { + "id": 9104852, + "short_id": "ZtyZtRM1", + "name": "Fresh-install activation milestones over time", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent"] + }, + { + "id": 9108955, + "short_id": "MWGe77xd", + "name": "Fresh-install retention by first-session behavior (D1/D7)", + "dashboards": [1562016], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started", "agent_prompt_sent"] + }, + { + "id": 8521005, + "short_id": "R7LdubT0", + "name": "D1/D3/D7 active return (any app event)", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 8521007, + "short_id": "0ebU6rrv", + "name": "D1/D3/D7 active return after agent_started", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "any_event"] + }, + { + "id": 8522294, + "short_id": "UWZ5RiOj", + "name": "Last meaningful event before churn (2d+ since last seen)", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 8840697, + "short_id": "1VVPYJ8k", + "name": "D3 retention proxy match by signal", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 8923127, + "short_id": "zeNCtwZf", + "name": "Fresh-install D3 non-returner drop-off reasons", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_started"] + }, + { + "id": 9026328, + "short_id": "3KIyq846", + "name": "D7 active return by platform", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9053637, + "short_id": "jgoTtubW", + "name": "D7 active return across cohort signals", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "any_event"] + }, + { + "id": 9104854, + "short_id": "z2HttOxb", + "name": "D1/D3/D7 active return after agent_started - 7d avg", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "any_event"] + }, + { + "id": 9219687, + "short_id": "h6OUMmVC", + "name": "D7 active return by week-1 feature depth (fresh installs)", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047425, + "short_id": "ySfAJORT", + "name": "D1 active return by platform", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047426, + "short_id": "ptPrfniz", + "name": "D3 active return by platform", + "dashboards": [1570255], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790198, + "short_id": "2M4eYB5Y", + "name": "D1/D3/D7/D30/D60/D90 active return: all vs agent_started", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "any_event"] + }, + { + "id": 9790246, + "short_id": "Cu0ugZU9", + "name": "Weekly fresh-install cohorts: D7/D30/D60/D90 active return", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790248, + "short_id": "CAB7tgTQ", + "name": "D30 active return by platform (fresh installs)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790259, + "short_id": "yXWkyHkz", + "name": "Workspace retention by repo cohort (nth_repo_added)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790360, + "short_id": "uhthznuN", + "name": "Native retention heatmap: fresh installs D0-D30", + "dashboards": [1795002], + "kind": "RetentionQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790608, + "short_id": "m7Y6tXay", + "name": "Native retention heatmap: macOS fresh installs D0-D30", + "dashboards": [1795002], + "kind": "RetentionQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790609, + "short_id": "7jkwDOyw", + "name": "Native retention heatmap: Windows fresh installs D0-D30", + "dashboards": [1795002], + "kind": "RetentionQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790610, + "short_id": "vAu1XSQV", + "name": "Native retention heatmap: Linux fresh installs D0-D30", + "dashboards": [1795002], + "kind": "RetentionQuery", + "depends_on": ["any_event"] + }, + { + "id": 9790612, + "short_id": "44sVkTWa", + "name": "Retention curve by platform: fresh installs D0-D30", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 9860667, + "short_id": "x0xzQZTk", + "name": "W2 productive comeback by repo cohort (weekly)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 9860714, + "short_id": "4xA3LHO9", + "name": "D30-window productive comeback by repo cohort (weekly)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 9862349, + "short_id": "LzvwreDS", + "name": "W2 productive comeback by platform (weekly)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 9862360, + "short_id": "nMw2QDc4", + "name": "D30-window productive comeback by platform (weekly)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 11047427, + "short_id": "dUL7qZX2", + "name": "Weekly any-return-by-D30 by platform", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047428, + "short_id": "gkIaeVKj", + "name": "Weekly any-return-by-D60 by platform", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047429, + "short_id": "AjnoOIgi", + "name": "D60-window productive comeback by platform (weekly)", + "dashboards": [1795002], + "kind": "HogQLQuery", + "depends_on": ["agent_started", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 11047236, + "short_id": "B4YE6JT8", + "name": "2-week / 30-day / 2-month window return (fresh installs)", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047238, + "short_id": "d8QEqrrw", + "name": "2-week / 30-day / 2-month window return by platform", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047421, + "short_id": "ssLoEqvW", + "name": "2-week window return by platform (weekly)", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047422, + "short_id": "sDWIHC8I", + "name": "30-day window return by platform (weekly)", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047423, + "short_id": "scpeujV9", + "name": "2-month window return by platform (weekly)", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 11047424, + "short_id": "lEnPXfTC", + "name": "Weekly fresh-install volume by platform", + "dashboards": [1997904], + "kind": "HogQLQuery", + "depends_on": ["any_event"] + }, + { + "id": 13282176, + "short_id": "81tNxzVh", + "name": "[Oct 25 snapshot] 24h onboarding flow handoff and agent input by randomized assignment", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": [ + "app_opened", + "agent_started", + "agent_prompt_sent", + "native_chat_message_sent" + ] + }, + { + "id": 13282177, + "short_id": "3JTv1Zyc", + "name": "D1 and D3 retention by assignment: agent prompts, native chat and app reopening", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": ["app_opened", "agent_prompt_sent", "native_chat_message_sent"] + }, + { + "id": 13282178, + "short_id": "BnC7Gjk1", + "name": "[Oct 25 snapshot] Treatment minus control: input, flow and D1 differences with 95% intervals", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": [ + "app_opened", + "agent_started", + "agent_prompt_sent", + "native_chat_message_sent" + ] + }, + { + "id": 13282179, + "short_id": "erBLlPW7", + "name": "[Oct 25 snapshot] Treatment-only picker use within 24h: opened and changed language", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": [ + "app_opened", + "agent_started", + "agent_prompt_sent", + "native_chat_message_sent" + ] + }, + { + "id": 13282180, + "short_id": "dEy4wYBH", + "name": "[Oct 25 snapshot] Cohort audit: assignment coverage, mature denominators and opt-outs", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": [ + "app_opened", + "agent_started", + "agent_prompt_sent", + "native_chat_message_sent" + ] + }, + { + "id": 13415841, + "short_id": "imWppJ9J", + "name": "LIVE: 24h confirmed agent prompt by randomized assignment", + "dashboards": [2258914], + "kind": "HogQLQuery", + "depends_on": ["agent_prompt_sent"] + }, + { + "id": 13461539, + "short_id": "hBk3Vbgt", + "name": "macOS 12 (Monterey): active installs in 24h, 7d and 30d", + "dashboards": [2279180], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 13461540, + "short_id": "KGvPgbKY", + "name": "Active macOS installs by latest OS version (last 30 days)", + "dashboards": [2279180], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 13792080, + "short_id": "vZr7OUjK", + "name": "Intel (x64) vs Apple Silicon: active macOS installs in 24h, 7d and 30d", + "dashboards": [2279180], + "kind": "HogQLQuery", + "depends_on": ["app_opened"] + }, + { + "id": 13534247, + "short_id": "unQzKtZu", + "name": "App return after exposure — daily retention by placement arm", + "dashboards": [2287466], + "kind": "RetentionQuery", + "depends_on": ["app_opened"] + }, + { + "id": 13534249, + "short_id": "Uo2BV932", + "name": "Terminal audience → chat default → chat message within 24h", + "dashboards": [2287466], + "kind": "FunnelsQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601867, + "short_id": "I44pQWTm", + "name": "1h chat adoption by placement — completed follow-up only", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601868, + "short_id": "jsZb4q64", + "name": "24h chat adoption by placement — completed follow-up only", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601877, + "short_id": "deRpnsB5", + "name": "7d chat adoption by placement — completed follow-up only", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601879, + "short_id": "huhquLT0", + "name": "Button emphasis — 1h chat adoption within placement arms", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601880, + "short_id": "pG7hGPox", + "name": "Targeting policy — 1h chat adoption within placement arms", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13601882, + "short_id": "uVetrCYw", + "name": "Guardrail — terminal-default switches within 24h", + "dashboards": [2287466], + "kind": "HogQLQuery", + "depends_on": ["native_chat_message_sent"] + }, + { + "id": 13537446, + "short_id": "KUMIquWd", + "name": "Escape-hatch users per 1k daily active users", + "dashboards": [2287832], + "kind": "TrendsQuery", + "depends_on": ["app_opened"] + } + ] + }, + "staged_validation": "All staged queries execute in production via /query/ and return no rows (events not deployed). Structural check substituting app_version 1.4.250 and 2026-11-05 bounds returned plausible launch and workspace values; this is not a production validation of the new events.", + "onboarding_git_repair_2026_11_08": { + "rules": "Legacy row = onboarding_completed path open_folder|clone_url and app_version <=1.4.45 (prerelease suffix allowed); its is_git_repo is trusted. Otherwise first repo_added after onboarding_started: is_git_repo true=git, false=plain folder, missing=unknown (never folder, never failure). Current-flow git readiness = add_repo_default_checkout_handoff result=opened_default_checkout (first seen 2026-06-04, 1.4.42).", + "evidence": { + "repo_added_is_git_repo_first_seen": "2026-06-11T02:35:28Z (1.4.60)", + "onboarding_completed_false_proxy_rows_1.4.46_plus": 1241, + "workspace_created_source_onboarding_last_seen": "2026-09-10T06:46:10Z", + "hogql_default_row_limit": 100 + }, + "validation": "Full-history async /query/ runs succeeded for every new query before save; legacy-window (2026-05-20..27) old vs new identical for 8838695, 8923273, 9050198 (old columns), 8923127 (label only); small legacy deltas on 8923532/9104872 come from legacy-start installs completing on current-flow builds. OOM equivalence on a 2h window (joins restricted to cohort ids on both sides): 9108955 and 8471904 identical; 9052828 identical to the LEFT JOIN reading of the original.", + "backups": "/tmp/orca-protected-telemetry/dashboard-backups-2026-11-08/onboarding-git-repair/", + "dashboard_1562016_description": "note replaced with the repaired git/folder rule", + "insights": [ + { + "id": 8471904, + "url": "https://us.posthog.com/project/406068/insights/XGjEOVWr", + "dashboards": [1562016], + "name": "Accepted repo/folder outcomes", + "change": "Pre-aggregated per install (fixes OOM); git/folder via legacy boundary + first repo_added.is_git_repo; new buckets: 'Completed git: default checkout opened', 'Completed: project added, git/folder unknown'.", + "query_sha256_12_before": "67706127a53a", + "query_sha256_12_after": "3eb2c22ad086", + "description_before": "Denominator is fresh installs with repo/folder accepted. Chart shows % only; table includes users and later behavior. Git completed with no onboarding workspace marker is still onboarding_completed, not completion drop-off. App-only; no website.", + "description_after": "Denominator: fresh installs with repo/folder accepted. Chart % only; table adds later behavior. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Default checkout = add_repo_default_checkout_handoff opened. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 9050198, + "url": "https://us.posthog.com/project/406068/insights/NFkAerEI", + "dashboards": [1562016], + "name": "Onboarding open-folder result: git repo vs plain folder", + "change": "Legacy open-folder columns guarded to <=1.4.45; added post_onboarding_folder_pick_{git,plain,unknown}_users from repo_added; LIMIT 1000 (was truncated at 100 rows/Aug 25).", + "query_sha256_12_before": "a09a6832aa74", + "query_sha256_12_after": "6397ed1516d6", + "description_before": "Fresh installs after 2026-05-20 source rollout. Splits successful onboarding open-folder completions by onboarding_completed.is_git_repo. This does not detect multiple nested repos; multiple-worktree telemetry is separate. App-only; no website.", + "description_after": "Legacy columns: in-onboarding open-folder path, <=1.4.45 only (step removed 2026-06-03). post_onboarding_folder_pick_* = first repo_added via folder picker after a current-flow completion, split by repo_added.is_git_repo (from 1.4.60, 2026-06-11); missing = unknown. Separate series, not one line. Today partial. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 8838695, + "url": "https://us.posthog.com/project/406068/insights/zyaXq4lJ", + "dashboards": [1562016], + "name": "Onboarding funnel: where users leave before completion", + "change": "Git/folder flags use legacy boundary + repo_added; removes 1.4.46+ is_git_repo=false proxies; stage order documented as legacy.", + "query_sha256_12_before": "7b11efa704a4", + "query_sha256_12_after": "5be38f2ef04e", + "description_before": "Sequential fresh-install funnel to onboarding_completed. Table adds agent_started users and a message-like launch proxy; no exact agent-message-sent event exists, so the proxy uses task/send launch sources. App-only; no website.", + "description_after": "Fresh-install funnel to onboarding_completed. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Stage order is legacy: since 1.4.46 onboarding completes before project choice, so stage 4 can exceed stage 3. Launch proxy uses task/send sources. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 8923532, + "url": "https://us.posthog.com/project/406068/insights/zKoJri8Y", + "dashboards": [1562016], + "name": "What happened before project-ready endpoint?", + "change": "Endpoint adds current-flow folder completion and default checkout opened; unknown project type excluded and counted (excluded_project_type_unknown).", + "query_sha256_12_before": "c72460d2fb21", + "query_sha256_12_after": "3094657c64a6", + "description_before": "Fresh installs that accepted a repo/folder but did not hit the onboarding project-ready endpoint. Chart shows % of this lost group; table splits git-completed and folder-picker paths. Endpoint is onboarding workspace_created source=onboarding OR folder completion. App-only; no website.", + "description_after": "Accepted repo/folder but no project-ready endpoint: legacy onboarding workspace, folder completion, or current-flow default checkout opened. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Unknown-type completions excluded (see excluded_project_type_unknown). App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 9104872, + "url": "https://us.posthog.com/project/406068/insights/6NQRUNxx", + "dashboards": [1562016], + "name": "Fresh-install onboarding completion - 7d avg", + "change": "Git/folder completion via legacy boundary + repo_added; LIMIT 1000 (was truncated at 100 rows/Aug 16).", + "query_sha256_12_before": "957b7d69c6fd", + "query_sha256_12_after": "9771e1f1c399", + "description_before": "Weighted trailing 7-cohort average of fresh-install onboarding completion, matching JlIt5J1N. Excludes telemetry opt-outs and current partial start day. App-only; no website.", + "description_after": "Weighted trailing 7-cohort fresh-install onboarding completion; opt-outs and current day excluded. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Git + folder < completion when project type is unknown or no project was added. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 8797194, + "url": "https://us.posthog.com/project/406068/insights/o3qfzye3", + "dashboards": [1562016], + "name": "Git completed, no onboarding workspace: later behavior", + "change": "Current-flow git bucket = first repo_added git with no default checkout opened; started_at guard fixed (minIf returns 1970, not NULL).", + "query_sha256_12_before": "1f4c8538b28f", + "query_sha256_12_after": "1ad73123e897", + "description_before": "Fresh-install users who completed with a git repo but never emitted workspace_created source=onboarding. Folder success is excluded. Shows selected post-completion app/repo/workspace/agent signals; workspace_created is linked worktree create success, not availability. App-only; no website.", + "description_after": "Fresh installs (real fresh onboarding_started) with git completion and no project-ready marker: legacy onboarding workspace, or current-flow default checkout opened. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Folder success excluded. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 8923127, + "url": "https://us.posthog.com/project/406068/insights/zeNCtwZf", + "dashboards": [1570255], + "name": "Fresh-install D3 non-returner drop-off reasons", + "change": "Git/folder flags via legacy boundary + repo_added; bucket 6 also requires no default checkout opened.", + "query_sha256_12_before": "7c4481dea7a2", + "query_sha256_12_after": "541340e31912", + "description_before": "D3-mature fresh installs excluding telemetry opt-outs with no app_opened on days 1-3, bucketed by deepest observed state in first 4 days. Chart shows % of non-returners only; heuristic, not causal proof. App-only; no website.", + "description_after": "D3-mature fresh installs (opt-outs excluded), no app_opened days 1-3, bucketed by deepest state in first 4 days. Heuristic, not causal. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Bucket 6 also requires no default checkout. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 8923273, + "url": "https://us.posthog.com/project/406068/insights/3oewonyF", + "dashboards": [1562016], + "name": "Fresh-install high-level activation funnel", + "change": "Folder completion via repo_added; work surface adds current-flow default checkout opened.", + "query_sha256_12_before": "7106703e0e78", + "query_sha256_12_after": "01885d0a81f3", + "description_before": "Strict fresh-install activation funnel excluding telemetry opt-outs and cohorts newer than D3. Work surface = explicit workspace/open/create, agent start, or completed folder. Chart is activation only; table includes full-cohort D3 context. App-only; no website.", + "description_after": "Fresh-install activation funnel; opt-outs and cohorts newer than D3 excluded. Work surface = workspace/open/create, agent start, folder completion, or current-flow default checkout opened. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 9052828, + "url": "https://us.posthog.com/project/406068/insights/fXsB9Izz", + "dashboards": [1562016], + "name": "Onboarding funnel with user prompt sent", + "change": "Pre-aggregated per install (fixes OOM); git/folder via legacy boundary + repo_added; denominator now all fresh starters (original RIGHT JOIN dropped starters with no matching events).", + "query_sha256_12_before": "bd7b83c690f7", + "query_sha256_12_after": "f4b78eb79cda", + "description_before": "Fresh-install funnel after agent_prompt_sent appeared 2026-05-29 23:33 UTC. Code-verified: agent_prompt_sent means a non-empty user prompt was delivered/observed, not an assistant response. Current rows are hook-sourced launch_source=unknown. App-only; no website. agent_prompt_sent is 1% sampled per event from 1.4.248 (2026-11-04 02:37 UTC); later rates undercount and are not rescalable.", + "description_after": "Fresh-install funnel after agent_prompt_sent appeared 2026-05-29. Prompt is 1% sampled per event from 1.4.248 (2026-11-04), so later rates undercount. Git/folder: onboarding_completed.is_git_repo only on <=1.4.45 legacy rows; later, first repo_added.is_git_repo after start (1.4.60+, 2026-06-11); missing = unknown, not folder. Stage order is legacy: stage 4 can exceed stage 3. App-only.", + "refresh_check": "ok (last_refresh after save)" + }, + { + "id": 9108955, + "url": "https://us.posthog.com/project/406068/insights/MWGe77xd", + "dashboards": [1562016], + "name": "Fresh-install retention by first-session behavior (D1/D7)", + "change": "OOM fix only: join restricted to the 5 events its aggregates read; description unchanged.", + "query_sha256_12_before": "57eacfbee986", + "query_sha256_12_after": "92260fa52aed", + "description_before": "D1/D7 return by first-session behavior; fresh installs, mature denominators. Buckets by precedence: sent prompt > agent auto-started > project-ready > abandoned. OBSERVATIONAL, not causal. 'Sent prompt' starts 2026-05-29 and is 1% sampled from 1.4.248 (2026-11-04), so later prompt senders fall into lower buckets. Trust the D1 gradient. App-only; no website.", + "description_after": "D1/D7 return by first-session behavior; fresh installs, mature denominators. Buckets by precedence: sent prompt > agent auto-started > project-ready > abandoned. OBSERVATIONAL, not causal. 'Sent prompt' starts 2026-05-29 and is 1% sampled from 1.4.248 (2026-11-04), so later prompt senders fall into lower buckets. Trust the D1 gradient. App-only; no website.", + "refresh_check": "ok (last_refresh after save)" + } + ], + "follow_up": [ + "9076383 (reference tile) and 9104852 still truncate at the 100-row HogQL default; 9076383's legacy regex also misses prerelease versions.", + "8838695/9052828 stage order is legacy; a current-flow onboarding funnel would be a new metric, not an edit." + ] + } +} diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-24h.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-24h.sql new file mode 100644 index 00000000000..bdc27a2a3f3 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-24h.sql @@ -0,0 +1,101 @@ +WITH + supporting_versions AS ( + SELECT DISTINCT toString(properties.app_version) AS v + FROM events + WHERE event IN ('first_agent_interaction', 'meaningful_activity_day') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + ), + opted_out AS ( + SELECT distinct_id AS uid + FROM events + WHERE event = 'telemetry_opted_out' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + anchors AS ( + SELECT + distinct_id AS uid, + min(timestamp) AS anchor_at, + formatDateTime(min(timestamp), '%Y-%m-%d') AS cohort_day, + argMin(coalesce(toString(properties.platform), 'unknown'), timestamp) AS platform, + argMin(toString(properties.app_version), timestamp) AS anchor_version + FROM events + WHERE event = 'onboarding_started' + AND properties.cohort = 'fresh_install' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + cohort AS ( + SELECT uid, anchor_at, cohort_day, platform + FROM anchors + WHERE anchor_at >= toDateTime('2026-11-08 00:00:00') + AND anchor_version IN (SELECT v FROM supporting_versions) + AND uid NOT IN (SELECT uid FROM opted_out) + ), + mature AS ( + SELECT uid, anchor_at, platform FROM cohort + WHERE anchor_at <= now() - INTERVAL 1455 MINUTE + ), + surface AS ( + SELECT m.uid AS uid, 1 AS has_surface, min(e.timestamp) AS surface_at + FROM events e + INNER JOIN mature m ON m.uid = e.distinct_id + WHERE e.timestamp >= toDateTime('2026-11-08 00:00:00') + AND e.timestamp >= m.anchor_at + AND e.timestamp < m.anchor_at + INTERVAL 24 HOUR + AND e.properties.orca_channel IS NOT NULL + AND ( + e.event = 'workspace_created' + OR (e.event = 'add_repo_setup_step_action' + AND toString(e.properties.action) IN ('open_existing', 'open_primary', 'create_worktree')) + OR (e.event = 'add_repo_default_checkout_handoff' + AND toString(e.properties.result) = 'opened_default_checkout') + OR (e.event = 'repo_added' AND toString(e.properties.is_git_repo) = 'false') + ) + GROUP BY m.uid + ), + interaction AS ( + SELECT + distinct_id AS uid, + 1 AS has_interaction, + min(timestamp) AS fai_at, + argMin(coalesce(toString(properties.install_cohort), 'unknown'), timestamp) AS fai_cohort, + argMin(coalesce(toString(properties.source), 'unknown'), timestamp) AS fai_source + FROM events + WHERE event = 'first_agent_interaction' + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + per_install AS ( + SELECT + m.platform AS platform, + s.has_surface = 1 AS surface_24h, + i.has_interaction = 1 AND i.fai_cohort = 'fresh' + AND i.fai_at >= m.anchor_at AND i.fai_at < m.anchor_at + INTERVAL 24 HOUR AS interaction_24h, + i.has_interaction = 1 AND i.fai_cohort = 'fresh' AND s.has_surface = 1 + AND i.fai_at >= s.surface_at AND i.fai_at < m.anchor_at + INTERVAL 24 HOUR AS interaction_after_surface_24h, + i.has_interaction = 1 AND i.fai_cohort != 'fresh' AS install_cohort_mismatch, + if(interaction_24h, i.fai_source, 'none') AS first_source + FROM mature m + LEFT JOIN surface s ON s.uid = m.uid + LEFT JOIN interaction i ON i.uid = m.uid + ) +SELECT + if(grouping(platform) = 1, 'all', platform) AS platform_group, + count() AS fresh_starters_complete_24h, + countIf(surface_24h) AS workspace_available_24h, + round(100.0 * workspace_available_24h / nullIf(fresh_starters_complete_24h, 0), 1) AS workspace_available_pct, + countIf(interaction_24h) AS first_interaction_24h, + round(100.0 * first_interaction_24h / nullIf(fresh_starters_complete_24h, 0), 1) AS first_interaction_pct, + countIf(interaction_24h AND first_source IN ('orca_send', 'native_chat', 'mobile_chat')) AS first_interaction_attributed_24h, + countIf(interaction_24h AND first_source = 'unattributed_prompt') AS first_interaction_unattributed_24h, + countIf(interaction_24h AND first_source NOT IN ('orca_send', 'native_chat', 'mobile_chat', 'unattributed_prompt')) AS first_interaction_unknown_source_24h, + countIf(interaction_after_surface_24h) AS interaction_after_workspace_24h, + countIf(install_cohort_mismatch) AS install_cohort_mismatch +FROM per_install +GROUP BY ROLLUP(platform) +ORDER BY platform_group diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-7d.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-7d.sql new file mode 100644 index 00000000000..856a9b96055 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/activation-7d.sql @@ -0,0 +1,101 @@ +WITH + supporting_versions AS ( + SELECT DISTINCT toString(properties.app_version) AS v + FROM events + WHERE event IN ('first_agent_interaction', 'meaningful_activity_day') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + ), + opted_out AS ( + SELECT distinct_id AS uid + FROM events + WHERE event = 'telemetry_opted_out' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + anchors AS ( + SELECT + distinct_id AS uid, + min(timestamp) AS anchor_at, + formatDateTime(min(timestamp), '%Y-%m-%d') AS cohort_day, + argMin(coalesce(toString(properties.platform), 'unknown'), timestamp) AS platform, + argMin(toString(properties.app_version), timestamp) AS anchor_version + FROM events + WHERE event = 'onboarding_started' + AND properties.cohort = 'fresh_install' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + cohort AS ( + SELECT uid, anchor_at, cohort_day, platform + FROM anchors + WHERE anchor_at >= toDateTime('2026-11-08 00:00:00') + AND anchor_version IN (SELECT v FROM supporting_versions) + AND uid NOT IN (SELECT uid FROM opted_out) + ), + mature AS ( + SELECT uid, anchor_at, platform FROM cohort + WHERE anchor_at <= now() - INTERVAL 10095 MINUTE + ), + surface AS ( + SELECT m.uid AS uid, 1 AS has_surface, min(e.timestamp) AS surface_at + FROM events e + INNER JOIN mature m ON m.uid = e.distinct_id + WHERE e.timestamp >= toDateTime('2026-11-08 00:00:00') + AND e.timestamp >= m.anchor_at + AND e.timestamp < m.anchor_at + INTERVAL 168 HOUR + AND e.properties.orca_channel IS NOT NULL + AND ( + e.event = 'workspace_created' + OR (e.event = 'add_repo_setup_step_action' + AND toString(e.properties.action) IN ('open_existing', 'open_primary', 'create_worktree')) + OR (e.event = 'add_repo_default_checkout_handoff' + AND toString(e.properties.result) = 'opened_default_checkout') + OR (e.event = 'repo_added' AND toString(e.properties.is_git_repo) = 'false') + ) + GROUP BY m.uid + ), + interaction AS ( + SELECT + distinct_id AS uid, + 1 AS has_interaction, + min(timestamp) AS fai_at, + argMin(coalesce(toString(properties.install_cohort), 'unknown'), timestamp) AS fai_cohort, + argMin(coalesce(toString(properties.source), 'unknown'), timestamp) AS fai_source + FROM events + WHERE event = 'first_agent_interaction' + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + per_install AS ( + SELECT + m.platform AS platform, + s.has_surface = 1 AS surface_7d, + i.has_interaction = 1 AND i.fai_cohort = 'fresh' + AND i.fai_at >= m.anchor_at AND i.fai_at < m.anchor_at + INTERVAL 168 HOUR AS interaction_7d, + i.has_interaction = 1 AND i.fai_cohort = 'fresh' AND s.has_surface = 1 + AND i.fai_at >= s.surface_at AND i.fai_at < m.anchor_at + INTERVAL 168 HOUR AS interaction_after_surface_7d, + i.has_interaction = 1 AND i.fai_cohort != 'fresh' AS install_cohort_mismatch, + if(interaction_7d, i.fai_source, 'none') AS first_source + FROM mature m + LEFT JOIN surface s ON s.uid = m.uid + LEFT JOIN interaction i ON i.uid = m.uid + ) +SELECT + if(grouping(platform) = 1, 'all', platform) AS platform_group, + count() AS fresh_starters_complete_7d, + countIf(surface_7d) AS workspace_available_7d, + round(100.0 * workspace_available_7d / nullIf(fresh_starters_complete_7d, 0), 1) AS workspace_available_pct, + countIf(interaction_7d) AS first_interaction_7d, + round(100.0 * first_interaction_7d / nullIf(fresh_starters_complete_7d, 0), 1) AS first_interaction_pct, + countIf(interaction_7d AND first_source IN ('orca_send', 'native_chat', 'mobile_chat')) AS first_interaction_attributed_7d, + countIf(interaction_7d AND first_source = 'unattributed_prompt') AS first_interaction_unattributed_7d, + countIf(interaction_7d AND first_source NOT IN ('orca_send', 'native_chat', 'mobile_chat', 'unattributed_prompt')) AS first_interaction_unknown_source_7d, + countIf(interaction_after_surface_7d) AS interaction_after_workspace_7d, + countIf(install_cohort_mismatch) AS install_cohort_mismatch +FROM per_install +GROUP BY ROLLUP(platform) +ORDER BY platform_group diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/cutover-gate.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/cutover-gate.sql new file mode 100644 index 00000000000..8e94f52798a --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/cutover-gate.sql @@ -0,0 +1,21 @@ +SELECT + event, + min(timestamp) AS first_seen_utc, + argMin(toString(properties.app_version), timestamp) AS first_seen_version, + argMin(toString(properties.orca_channel), timestamp) AS first_seen_channel, + uniq(toString(properties.app_version)) AS versions, + count() AS events, + uniq(distinct_id) AS installs, + count() - uniq(tuple(distinct_id, if(event = 'meaningful_activity_day', formatDateTime(timestamp, '%Y-%m-%d'), ''))) AS duplicate_events, + countIf(properties.sample_rate IS NOT NULL) AS events_with_sample_rate, + countIf(if(event = 'first_agent_interaction', properties.source, properties.trigger) IS NULL) AS missing_source_or_trigger, + countIf(properties.install_cohort IS NULL) AS missing_install_cohort, + groupUniqArray(toString(if(event = 'first_agent_interaction', properties.source, properties.trigger))) AS source_or_trigger_values, + groupUniqArray(toString(properties.agent_kind)) AS agent_kind_values, + groupUniqArray(toString(properties.install_cohort)) AS install_cohort_values, + groupUniqArray(coalesce(toString(properties.platform), 'unknown')) AS platforms +FROM events +WHERE event IN ('first_agent_interaction', 'meaningful_activity_day') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL +GROUP BY event diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/daily-meaningful-installs.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/daily-meaningful-installs.sql new file mode 100644 index 00000000000..6845574a509 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/daily-meaningful-installs.sql @@ -0,0 +1,15 @@ +SELECT + formatDateTime(timestamp, '%Y-%m-%d') AS day, + uniqIf(distinct_id, event = 'meaningful_activity_day') AS meaningful_installs, + uniqIf(distinct_id, event = 'meaningful_activity_day' AND toString(properties.install_cohort) = 'fresh') AS meaningful_fresh_installs, + uniqIf(distinct_id, event = 'app_opened' AND toString(properties.app_version) IN ( + SELECT DISTINCT toString(properties.app_version) FROM events + WHERE event = 'meaningful_activity_day' AND timestamp >= toDateTime('2026-11-08 00:00:00') + )) AS launched_installs_on_supporting_builds +FROM events +WHERE event IN ('meaningful_activity_day', 'app_opened') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND timestamp < toDateTime(formatDateTime(now(), '%Y-%m-%d 00:00:00')) + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL +GROUP BY day +ORDER BY day diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/fresh-anchor-version-coverage.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/fresh-anchor-version-coverage.sql new file mode 100644 index 00000000000..31de7a30c90 --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/fresh-anchor-version-coverage.sql @@ -0,0 +1,32 @@ +WITH + supporting_versions AS ( + SELECT DISTINCT toString(properties.app_version) AS v + FROM events + WHERE event IN ('first_agent_interaction', 'meaningful_activity_day') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + ), + anchors AS ( + SELECT + distinct_id AS uid, + min(timestamp) AS anchor_at, + formatDateTime(min(timestamp), '%Y-%m-%d') AS cohort_day, + argMin(coalesce(toString(properties.platform), 'unknown'), timestamp) AS platform, + argMin(toString(properties.app_version), timestamp) AS anchor_version + FROM events + WHERE event = 'onboarding_started' + AND properties.cohort = 'fresh_install' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ) +SELECT + cohort_day, + platform, + count() AS fresh_anchors, + countIf(anchor_version IN (SELECT v FROM supporting_versions)) AS on_supporting_build, + round(100.0 * on_supporting_build / nullIf(fresh_anchors, 0), 1) AS supporting_pct +FROM anchors +WHERE anchor_at >= toDateTime('2026-11-01 00:00:00') +GROUP BY cohort_day, platform +ORDER BY cohort_day, platform diff --git a/docs/agents-md-refs/protected-telemetry-milestones/queries/launch-vs-meaningful-return.sql b/docs/agents-md-refs/protected-telemetry-milestones/queries/launch-vs-meaningful-return.sql new file mode 100644 index 00000000000..a3de67f76fb --- /dev/null +++ b/docs/agents-md-refs/protected-telemetry-milestones/queries/launch-vs-meaningful-return.sql @@ -0,0 +1,93 @@ +WITH + supporting_versions AS ( + SELECT DISTINCT toString(properties.app_version) AS v + FROM events + WHERE event IN ('first_agent_interaction', 'meaningful_activity_day') + AND timestamp >= toDateTime('2026-11-08 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + ), + opted_out AS ( + SELECT distinct_id AS uid + FROM events + WHERE event = 'telemetry_opted_out' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + anchors AS ( + SELECT + distinct_id AS uid, + min(timestamp) AS anchor_at, + formatDateTime(min(timestamp), '%Y-%m-%d') AS cohort_day, + argMin(coalesce(toString(properties.platform), 'unknown'), timestamp) AS platform, + argMin(toString(properties.app_version), timestamp) AS anchor_version + FROM events + WHERE event = 'onboarding_started' + AND properties.cohort = 'fresh_install' + AND timestamp >= toDateTime('2026-10-09 00:00:00') + AND properties.install_id IS NOT NULL AND properties.orca_channel IS NOT NULL + GROUP BY uid + ), + cohort AS ( + SELECT uid, anchor_at, cohort_day, platform + FROM anchors + WHERE anchor_at >= toDateTime('2026-11-08 00:00:00') + AND anchor_version IN (SELECT v FROM supporting_versions) + AND uid NOT IN (SELECT uid FROM opted_out) + ), + last_complete AS ( + SELECT formatDateTime(now() - INTERVAL 1455 MINUTE, '%Y-%m-%d') AS day + ), + activity_days AS ( + SELECT + c.uid AS uid, + dateDiff('day', toDate(c.cohort_day), toDate(formatDateTime(e.timestamp, '%Y-%m-%d'))) AS day_n, + countIf(e.event = 'meaningful_activity_day') > 0 AS meaningful, + countIf(e.event = 'app_opened') > 0 AS launched + FROM events e + INNER JOIN cohort c ON c.uid = e.distinct_id + WHERE e.event IN ('meaningful_activity_day', 'app_opened') + AND e.timestamp >= toDateTime('2026-11-08 00:00:00') + AND e.timestamp > c.anchor_at + AND e.properties.orca_channel IS NOT NULL + GROUP BY uid, day_n + ), + per_install AS ( + SELECT + c.uid AS uid, + c.platform AS platform, + dateDiff('day', toDate(c.cohort_day), toDate((SELECT day FROM last_complete))) AS mature_days, + countIf(d.day_n = 1 AND d.meaningful) > 0 AS m_d1, + countIf(d.day_n BETWEEN 1 AND 3 AND d.meaningful) > 0 AS m_d3, + countIf(d.day_n BETWEEN 1 AND 7 AND d.meaningful) > 0 AS m_d7, + countIf(d.day_n BETWEEN 8 AND 14 AND d.meaningful) > 0 AS m_w2, + countIf(d.day_n BETWEEN 24 AND 30 AND d.meaningful) > 0 AS m_d30w, + countIf(d.day_n = 1 AND d.launched) > 0 AS l_d1, + countIf(d.day_n BETWEEN 1 AND 3 AND d.launched) > 0 AS l_d3, + countIf(d.day_n BETWEEN 1 AND 7 AND d.launched) > 0 AS l_d7, + countIf(d.day_n BETWEEN 8 AND 14 AND d.launched) > 0 AS l_w2, + countIf(d.day_n BETWEEN 24 AND 30 AND d.launched) > 0 AS l_d30w + FROM cohort c + LEFT JOIN activity_days d ON d.uid = c.uid + GROUP BY c.uid, c.cohort_day, c.platform + ) +SELECT + platform_group, + ['D1 (day 1)', 'D3 (days 1-3)', 'D7 (days 1-7)', '2-week (days 8-14)', '30-day (days 24-30)'][wi] AS window_label, + [1, 3, 7, 14, 30][wi] AS window_end_day, + countIf(mature_days >= [1, 3, 7, 14, 30][wi]) AS eligible_installs, + countIf(mature_days >= [1, 3, 7, 14, 30][wi] AND meaningful_flags[wi]) AS meaningful_returned, + round(100.0 * meaningful_returned / nullIf(eligible_installs, 0), 1) AS meaningful_pct, + countIf(mature_days >= [1, 3, 7, 14, 30][wi] AND launch_flags[wi]) AS launch_returned, + round(100.0 * launch_returned / nullIf(eligible_installs, 0), 1) AS launch_pct +FROM ( + SELECT + arrayJoin([platform, 'all']) AS platform_group, + arrayJoin([1, 2, 3, 4, 5]) AS wi, + mature_days, + [m_d1, m_d3, m_d7, m_w2, m_d30w] AS meaningful_flags, + [l_d1, l_d3, l_d7, l_w2, l_d30w] AS launch_flags + FROM per_install +) +GROUP BY platform_group, wi +ORDER BY wi, platform_group 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/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/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/mobile/rpc-foundation/goldens/aivault-history-scan-association.json b/mobile/rpc-foundation/goldens/aivault-history-scan-association.json index 94eb7c8032c..71b6bdaff77 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-scan-association.json +++ b/mobile/rpc-foundation/goldens/aivault-history-scan-association.json @@ -4,6 +4,11 @@ "family": "aiVault.history", "namedDeltas": [], "values": { + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "44a27dbf05e2": { "name": "status.get#1", "ordinal": 3, @@ -30,39 +35,7 @@ ] } }, - "7e8b2964ad63": { - "name": "streams-registered-at-teardown", - "ordinal": 8, - "value": [ - { - "cancelled": false, - "method": "agentSession.subscribeStatus", - "payload": "agentSession.subscribeStatus#1" - } - ] - }, - "7f300f2af8fd": { - "name": "aiVault.listSessions#2", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "98ac9d409279": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "issues": [], - "kind": "ready", - "sessions": [ - { - "agent": "pi", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - }, - "ad5b1230fc26": { + "69310cf221d2": { "name": "aiVault.listSessions#2", "ordinal": 6, "args": [ @@ -75,6 +48,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -109,10 +83,81 @@ } } }, - "b6a16cc83e18": { + "7a3238411452": { + "name": "aiVault.listSessions#2", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, + "7bdbee10feca": { "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "issues": [], + "sessions": [ + { + "agent": "pi", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + } + } + }, + "7e8b2964ad63": { + "name": "streams-registered-at-teardown", + "ordinal": 8, + "value": [ + { + "cancelled": false, + "method": "agentSession.subscribeStatus", + "payload": "agentSession.subscribeStatus#1" + } + ] + }, + "98ac9d409279": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "issues": [], + "kind": "ready", + "sessions": [ + { + "agent": "pi", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } }, "daf52dc85a58": { "name": "status.get#1", @@ -160,49 +205,6 @@ "value": { "$rpc": "undefined" } - }, - "f562eb25b111": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "issues": [], - "sessions": [ - { - "agent": "pi", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - } - } } }, "recording": { @@ -211,8 +213,8 @@ { "id": "ready", "observation": { - "sender": ["daf52dc85a58", "f562eb25b111"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "7bdbee10feca"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -223,8 +225,8 @@ { "id": "associated", "observation": { - "sender": ["daf52dc85a58", "f562eb25b111", "ad5b1230fc26"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "7bdbee10feca", "69310cf221d2"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, @@ -235,8 +237,8 @@ { "id": "cleanup", "observation": { - "sender": ["daf52dc85a58", "f562eb25b111", "ad5b1230fc26"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "7bdbee10feca", "69310cf221d2"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/aivault-history-scan-fulfilled.json b/mobile/rpc-foundation/goldens/aivault-history-scan-fulfilled.json index 90ae287ae9c..e67716ea050 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-scan-fulfilled.json +++ b/mobile/rpc-foundation/goldens/aivault-history-scan-fulfilled.json @@ -4,6 +4,55 @@ "family": "aiVault.history", "namedDeltas": [], "values": { + "03fd6edde488": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "issues": [], + "sessions": [ + { + "agent": "claude", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + } + } + }, + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "44a27dbf05e2": { "name": "status.get#1", "ordinal": 3, @@ -36,54 +85,6 @@ ] } }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "cb5715e0f275": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "issues": [], - "sessions": [ - { - "agent": "claude", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - } - } - }, "daf52dc85a58": { "name": "status.get#1", "ordinal": 2, @@ -138,8 +139,8 @@ { "id": "ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -150,8 +151,8 @@ { "id": "cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/aivault-history-scan-refresh.json b/mobile/rpc-foundation/goldens/aivault-history-scan-refresh.json index a17bf5126ab..06fafbf02ad 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-scan-refresh.json +++ b/mobile/rpc-foundation/goldens/aivault-history-scan-refresh.json @@ -4,14 +4,9 @@ "family": "aiVault.history", "namedDeltas": [], "values": { - "33f381559396": { - "name": "aiVault.listSessions#2", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":true,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "3f412a6bee67": { - "name": "aiVault.listSessions#2", - "ordinal": 6, + "03fd6edde488": { + "name": "aiVault.listSessions#1", + "ordinal": 4, "args": [ { "name": "method", @@ -20,8 +15,9 @@ { "name": "params", "value": { - "force": true, + "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -37,7 +33,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-3", "ok": true, "result": { "issues": [], @@ -45,13 +41,23 @@ { "agent": "claude", "cwd": "/repo/feature", - "id": "s2" + "id": "s1" } ] } } } }, + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, + "422563aac194": { + "name": "aiVault.listSessions#2", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":true,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "44a27dbf05e2": { "name": "status.get#1", "ordinal": 3, @@ -84,14 +90,9 @@ ] } }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "cb5715e0f275": { - "name": "aiVault.listSessions#1", - "ordinal": 4, + "c23f94d5e35f": { + "name": "aiVault.listSessions#2", + "ordinal": 6, "args": [ { "name": "method", @@ -100,8 +101,9 @@ { "name": "params", "value": { - "force": false, + "force": true, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -117,7 +119,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-3", + "id": "frame-4", "ok": true, "result": { "issues": [], @@ -125,7 +127,7 @@ { "agent": "claude", "cwd": "/repo/feature", - "id": "s1" + "id": "s2" } ] } @@ -202,8 +204,8 @@ { "id": "ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -214,8 +216,8 @@ { "id": "refreshed", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275", "3f412a6bee67"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "33f381559396"], + "sender": ["daf52dc85a58", "03fd6edde488", "c23f94d5e35f"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "422563aac194"], "settlements": { "mount": "eb79a9b3682a", "refresh": "eb79a9b3682a" @@ -227,8 +229,8 @@ { "id": "cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275", "3f412a6bee67"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "33f381559396"], + "sender": ["daf52dc85a58", "03fd6edde488", "c23f94d5e35f"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "422563aac194"], "settlements": { "mount": "eb79a9b3682a", "refresh": "eb79a9b3682a" diff --git a/mobile/rpc-foundation/goldens/aivault-history-scan-revisit.json b/mobile/rpc-foundation/goldens/aivault-history-scan-revisit.json index 8294e2d8f18..33d90e61fe8 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-scan-revisit.json +++ b/mobile/rpc-foundation/goldens/aivault-history-scan-revisit.json @@ -4,11 +4,94 @@ "family": "aiVault.history", "namedDeltas": [], "values": { + "03fd6edde488": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "issues": [], + "sessions": [ + { + "agent": "claude", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + } + } + }, + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "44a27dbf05e2": { "name": "status.get#1", "ordinal": 3, "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" }, + "74067e8858fa": { + "name": "aiVault.listSessions#2", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 31000 + } + }, + "7a3238411452": { + "name": "aiVault.listSessions#2", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "7e8b2964ad63": { "name": "streams-registered-at-teardown", "ordinal": 8, @@ -20,11 +103,6 @@ } ] }, - "7f300f2af8fd": { - "name": "aiVault.listSessions#2", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "9aa0df31dc4d": { "activeWorktreePath": "/repo/feature", "refreshing": false, @@ -62,11 +140,6 @@ ] } }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "c61a146bd377": { "status": "fulfilled", "startedAt": 31000, @@ -75,50 +148,7 @@ "$rpc": "undefined" } }, - "cb5715e0f275": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "issues": [], - "sessions": [ - { - "agent": "claude", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - } - } - }, - "d3637311be53": { + "c6add689704f": { "name": "aiVault.listSessions#2", "ordinal": 6, "args": [ @@ -131,6 +161,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -205,34 +236,6 @@ "ordinal": 1, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"agentSession.subscribeStatus\",\"params\":{}}" }, - "e702c32cb3d5": { - "name": "aiVault.listSessions#2", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 31000 - } - }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -248,8 +251,8 @@ { "id": "ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -260,8 +263,8 @@ { "id": "cached", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275", "e702c32cb3d5"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "03fd6edde488", "74067e8858fa"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a", "leave": "eb79a9b3682a", @@ -274,8 +277,8 @@ { "id": "revalidated", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275", "d3637311be53"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "03fd6edde488", "c6add689704f"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a", "leave": "eb79a9b3682a", @@ -288,8 +291,8 @@ { "id": "cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275", "d3637311be53"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "03fd6edde488", "c6add689704f"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a", "leave": "eb79a9b3682a", diff --git a/mobile/rpc-foundation/goldens/aivault-history-scan-worktrees-late.json b/mobile/rpc-foundation/goldens/aivault-history-scan-worktrees-late.json index 9fd95759ee2..54f4176da96 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-scan-worktrees-late.json +++ b/mobile/rpc-foundation/goldens/aivault-history-scan-worktrees-late.json @@ -4,6 +4,55 @@ "family": "aiVault.history", "namedDeltas": [], "values": { + "03fd6edde488": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "issues": [], + "sessions": [ + { + "agent": "claude", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + } + } + }, + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "44a27dbf05e2": { "name": "status.get#1", "ordinal": 3, @@ -36,54 +85,6 @@ ] } }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "cb5715e0f275": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "issues": [], - "sessions": [ - { - "agent": "claude", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - } - } - }, "daf52dc85a58": { "name": "status.get#1", "ordinal": 2, @@ -160,8 +161,8 @@ { "id": "ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a", "worktrees-loaded": "eb79a9b3682a" @@ -173,8 +174,8 @@ { "id": "cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a", "worktrees-loaded": "eb79a9b3682a" diff --git a/mobile/rpc-foundation/goldens/aivault-history-screen-listed.json b/mobile/rpc-foundation/goldens/aivault-history-screen-listed.json index 83bd3725664..f6035ae55c3 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-screen-listed.json +++ b/mobile/rpc-foundation/goldens/aivault-history-screen-listed.json @@ -30,7 +30,7 @@ "startedAt": 0 } }, - "07299f73583f": { + "27ef7c5c6263": { "name": "aiVault.listSessions#1", "ordinal": 6, "args": [ @@ -43,6 +43,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -58,11 +59,6 @@ "startedAt": 0 } }, - "595e6c3bbfed": { - "name": "aiVault.listSessions#1", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "7623e8b568b1": { "crash": { "$rpc": "null" @@ -95,42 +91,7 @@ } ] }, - "b7a7af14c8a5": { - "crash": { - "$rpc": "null" - }, - "elements": { - "ChevronLeft": 1, - "Defs": 1, - "LinearGradient": 1, - "Pressable": 5, - "Rect": 1, - "RefreshCw": 1, - "SafeAreaView": 1, - "Search": 1, - "SectionList": 1, - "Stop": 2, - "Svg": 1, - "Text": 5, - "TextInput": 1, - "View": 14 - }, - "labels": [ - "Back", - "Refresh agent sessions", - "Workspace", - "Project", - "All", - "Search sessions, repo:, path:" - ], - "text": ["Agent Session History", "orca-history", "Workspace", "Project", "All"] - }, - "d126597611a2": { - "name": "worktree.ps#1", - "ordinal": 3, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"supportsWorktreeVisibilitySourceDefaults\":true}}" - }, - "df6890cb4985": { + "a03eeea51ba8": { "name": "aiVault.listSessions#1", "ordinal": 6, "args": [ @@ -143,6 +104,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -194,6 +156,46 @@ } } }, + "b7a7af14c8a5": { + "crash": { + "$rpc": "null" + }, + "elements": { + "ChevronLeft": 1, + "Defs": 1, + "LinearGradient": 1, + "Pressable": 5, + "Rect": 1, + "RefreshCw": 1, + "SafeAreaView": 1, + "Search": 1, + "SectionList": 1, + "Stop": 2, + "Svg": 1, + "Text": 5, + "TextInput": 1, + "View": 14 + }, + "labels": [ + "Back", + "Refresh agent sessions", + "Workspace", + "Project", + "All", + "Search sessions, repo:, path:" + ], + "text": ["Agent Session History", "orca-history", "Workspace", "Project", "All"] + }, + "d126597611a2": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "dffc0668b556": { + "name": "aiVault.listSessions#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "e28c488ce6b2": { "name": "agentSession.subscribeStatus#1", "ordinal": 1, @@ -305,8 +307,8 @@ { "id": "worktrees-listed", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "07299f73583f"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "27ef7c5c6263"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, @@ -317,8 +319,8 @@ { "id": "ready", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "df6890cb4985"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "a03eeea51ba8"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, @@ -329,8 +331,8 @@ { "id": "cleanup", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "df6890cb4985"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "a03eeea51ba8"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/aivault-history-screen-worktrees.json b/mobile/rpc-foundation/goldens/aivault-history-screen-worktrees.json index abfbd736429..9b794c5f0fb 100644 --- a/mobile/rpc-foundation/goldens/aivault-history-screen-worktrees.json +++ b/mobile/rpc-foundation/goldens/aivault-history-screen-worktrees.json @@ -30,7 +30,7 @@ "startedAt": 0 } }, - "07299f73583f": { + "27ef7c5c6263": { "name": "aiVault.listSessions#1", "ordinal": 6, "args": [ @@ -43,6 +43,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -58,11 +59,6 @@ "startedAt": 0 } }, - "595e6c3bbfed": { - "name": "aiVault.listSessions#1", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "7623e8b568b1": { "crash": { "$rpc": "null" @@ -95,11 +91,51 @@ } ] }, + "a0b80301d553": { + "name": "aiVault.listSessions#1", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "d126597611a2": { "name": "worktree.ps#1", "ordinal": 3, "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"supportsWorktreeVisibilitySourceDefaults\":true}}" }, + "dffc0668b556": { + "name": "aiVault.listSessions#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "e28c488ce6b2": { "name": "agentSession.subscribeStatus#1", "ordinal": 1, @@ -191,40 +227,6 @@ } } } - }, - "f13239f2c039": { - "name": "aiVault.listSessions#1", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } } }, "recording": { @@ -245,8 +247,8 @@ { "id": "worktrees-listed", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "07299f73583f"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "27ef7c5c6263"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, @@ -257,8 +259,8 @@ { "id": "cleanup", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "f13239f2c039"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "a0b80301d553"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-aivault.history-aivault.listsessions-1.json b/mobile/rpc-foundation/goldens/matrix-aivault.history-aivault.listsessions-1.json index 33f7d253ef9..3d52b2d86ac 100644 --- a/mobile/rpc-foundation/goldens/matrix-aivault.history-aivault.listsessions-1.json +++ b/mobile/rpc-foundation/goldens/matrix-aivault.history-aivault.listsessions-1.json @@ -4,419 +4,7 @@ "family": "aiVault.history", "namedDeltas": [], "values": { - "2d708a37d5ea": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "30f2a42bed00": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "kind": "loading" - } - }, - "3f0d3328af85": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-3", - "ok": false - } - } - }, - "44a27dbf05e2": { - "name": "status.get#1", - "ordinal": 3, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "54a7c3bc47d2": { - "name": "aiVault.listSessions#2", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, - "6919c6d453c4": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } - }, - "758b3fde1948": { - "name": "streams-registered-at-teardown", - "ordinal": 6, - "value": [ - { - "cancelled": false, - "method": "agentSession.subscribeStatus", - "payload": "agentSession.subscribeStatus#1" - } - ] - }, - "7d9b0e9536df": { - "name": "aiVault.listSessions#2", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "7e8b2964ad63": { - "name": "streams-registered-at-teardown", - "ordinal": 8, - "value": [ - { - "cancelled": false, - "method": "agentSession.subscribeStatus", - "payload": "agentSession.subscribeStatus#1" - } - ] - }, - "7f300f2af8fd": { - "name": "aiVault.listSessions#2", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "86a28f6d8cdc": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "kind": "error", - "message": "outer refused" - } - }, - "8fc90c2a1d6c": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true - } - } - }, - "9aa0df31dc4d": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "issues": [], - "kind": "ready", - "sessions": [ - { - "agent": "claude", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - }, - "a60ec274c87f": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "kind": "error", - "message": "The host sent a reply this app could not read (aiVault.listSessions)" - } - }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, - "b838b12acde6": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "kind": "error", - "message": "Unknown method" - } - }, - "c23be45f1637": { - "activeWorktreePath": "/repo/feature", - "refreshing": false, - "scope": "workspace", - "screenState": { - "kind": "error", - "message": "Unable to load agent sessions" - } - }, - "c5a0bb1d4a76": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } - } - } - }, - "c7ccb71459eb": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "c967ce34a622": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } - }, - "cb5715e0f275": { + "03fd6edde488": { "name": "aiVault.listSessions#1", "ordinal": 4, "args": [ @@ -429,6 +17,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -459,7 +48,49 @@ } } }, - "d16bd9a670c3": { + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, + "22fcaac5d4c6": { + "name": "aiVault.listSessions#2", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "30f2a42bed00": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "kind": "loading" + } + }, + "3354c863b6ab": { "name": "aiVault.listSessions#1", "ordinal": 4, "args": [ @@ -472,6 +103,45 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "352956d73b28": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -496,7 +166,23 @@ } } }, - "d4b9d334dde7": { + "44a27dbf05e2": { + "name": "status.get#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "758b3fde1948": { + "name": "streams-registered-at-teardown", + "ordinal": 6, + "value": [ + { + "cancelled": false, + "method": "agentSession.subscribeStatus", + "payload": "agentSession.subscribeStatus#1" + } + ] + }, + "77e40752545b": { "name": "aiVault.listSessions#1", "ordinal": 4, "args": [ @@ -509,6 +195,7 @@ "value": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] } }, @@ -529,6 +216,369 @@ } } }, + "7a3238411452": { + "name": "aiVault.listSessions#2", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, + "7b5906668e74": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "7e8b2964ad63": { + "name": "streams-registered-at-teardown", + "ordinal": 8, + "value": [ + { + "cancelled": false, + "method": "agentSession.subscribeStatus", + "payload": "agentSession.subscribeStatus#1" + } + ] + }, + "7e910f2e6951": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } + }, + "86a28f6d8cdc": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "kind": "error", + "message": "outer refused" + } + }, + "95ba1077fb6d": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "9aa0df31dc4d": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "issues": [], + "kind": "ready", + "sessions": [ + { + "agent": "claude", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + }, + "9cfa0bcd2a8a": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-3", + "ok": false + } + } + }, + "a60ec274c87f": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "kind": "error", + "message": "The host sent a reply this app could not read (aiVault.listSessions)" + } + }, + "a91d79d0bc23": { + "name": "aiVault.listSessions#2", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "b838b12acde6": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "kind": "error", + "message": "Unknown method" + } + }, + "bcc1d8502cdb": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "c23be45f1637": { + "activeWorktreePath": "/repo/feature", + "refreshing": false, + "scope": "workspace", + "screenState": { + "kind": "error", + "message": "Unable to load agent sessions" + } + }, + "c82cd1b39ee0": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-3", + "ok": false + } + } + }, + "cd9a4ebd035d": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } + } + } + }, "daf52dc85a58": { "name": "status.get#1", "ordinal": 2, @@ -575,43 +625,6 @@ "value": { "$rpc": "undefined" } - }, - "f37a7212d893": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "" - }, - "id": "frame-3", - "ok": false - } - } } }, "recording": { @@ -620,8 +633,8 @@ { "id": "aivault-history-scan-fulfilled.normal:ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -632,8 +645,8 @@ { "id": "aivault-history-scan-fulfilled.normal:cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -644,8 +657,8 @@ { "id": "aivault-history-scan-fulfilled.result-absent:ready", "observation": { - "sender": ["daf52dc85a58", "d4b9d334dde7"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "77e40752545b"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -656,8 +669,8 @@ { "id": "aivault-history-scan-fulfilled.result-absent:cleanup", "observation": { - "sender": ["daf52dc85a58", "d4b9d334dde7"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "77e40752545b"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -668,8 +681,8 @@ { "id": "aivault-history-scan-fulfilled.result-null:ready", "observation": { - "sender": ["daf52dc85a58", "c7ccb71459eb"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "7b5906668e74"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -680,8 +693,8 @@ { "id": "aivault-history-scan-fulfilled.result-null:cleanup", "observation": { - "sender": ["daf52dc85a58", "c7ccb71459eb"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "7b5906668e74"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -692,8 +705,8 @@ { "id": "aivault-history-scan-fulfilled.inner-ok-missing:ready", "observation": { - "sender": ["daf52dc85a58", "2d708a37d5ea"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "95ba1077fb6d"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -704,8 +717,8 @@ { "id": "aivault-history-scan-fulfilled.inner-ok-missing:cleanup", "observation": { - "sender": ["daf52dc85a58", "2d708a37d5ea"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "95ba1077fb6d"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -716,8 +729,8 @@ { "id": "aivault-history-scan-fulfilled.inner-false-string-error:ready", "observation": { - "sender": ["daf52dc85a58", "c5a0bb1d4a76"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "3354c863b6ab"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -728,8 +741,8 @@ { "id": "aivault-history-scan-fulfilled.inner-false-string-error:cleanup", "observation": { - "sender": ["daf52dc85a58", "c5a0bb1d4a76"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "3354c863b6ab"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -740,8 +753,8 @@ { "id": "aivault-history-scan-fulfilled.inner-false-object-error:ready", "observation": { - "sender": ["daf52dc85a58", "c967ce34a622"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "cd9a4ebd035d"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -752,8 +765,8 @@ { "id": "aivault-history-scan-fulfilled.inner-false-object-error:cleanup", "observation": { - "sender": ["daf52dc85a58", "c967ce34a622"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "cd9a4ebd035d"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -764,8 +777,8 @@ { "id": "aivault-history-scan-fulfilled.outer-refused:ready", "observation": { - "sender": ["daf52dc85a58", "3f0d3328af85"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "c82cd1b39ee0"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -776,8 +789,8 @@ { "id": "aivault-history-scan-fulfilled.outer-refused:cleanup", "observation": { - "sender": ["daf52dc85a58", "3f0d3328af85"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "c82cd1b39ee0"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -788,8 +801,8 @@ { "id": "aivault-history-scan-fulfilled.outer-refused-no-message:ready", "observation": { - "sender": ["daf52dc85a58", "f37a7212d893"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "9cfa0bcd2a8a"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -800,8 +813,8 @@ { "id": "aivault-history-scan-fulfilled.outer-refused-no-message:cleanup", "observation": { - "sender": ["daf52dc85a58", "f37a7212d893"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "9cfa0bcd2a8a"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -812,8 +825,8 @@ { "id": "aivault-history-scan-fulfilled.method-not-found:ready", "observation": { - "sender": ["daf52dc85a58", "d16bd9a670c3"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "352956d73b28"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -824,8 +837,8 @@ { "id": "aivault-history-scan-fulfilled.method-not-found:cleanup", "observation": { - "sender": ["daf52dc85a58", "d16bd9a670c3"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "352956d73b28"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -836,8 +849,8 @@ { "id": "aivault-history-scan-fulfilled.transport-rejection:ready", "observation": { - "sender": ["daf52dc85a58", "8fc90c2a1d6c", "7d9b0e9536df"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "7e910f2e6951", "22fcaac5d4c6"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, @@ -848,8 +861,8 @@ { "id": "aivault-history-scan-fulfilled.transport-rejection:cleanup", "observation": { - "sender": ["daf52dc85a58", "8fc90c2a1d6c", "54a7c3bc47d2"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "7e910f2e6951", "a91d79d0bc23"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, @@ -860,8 +873,8 @@ { "id": "aivault-history-scan-fulfilled.transport-rejection-no-message:ready", "observation": { - "sender": ["daf52dc85a58", "6919c6d453c4", "7d9b0e9536df"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "bcc1d8502cdb", "22fcaac5d4c6"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, @@ -872,8 +885,8 @@ { "id": "aivault-history-scan-fulfilled.transport-rejection-no-message:cleanup", "observation": { - "sender": ["daf52dc85a58", "6919c6d453c4", "54a7c3bc47d2"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18", "7f300f2af8fd"], + "sender": ["daf52dc85a58", "bcc1d8502cdb", "a91d79d0bc23"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3", "7a3238411452"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-platform-status.json b/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-platform-status.json index ff07aab20a7..3e80fea83f5 100644 --- a/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-platform-status.json +++ b/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-platform-status.json @@ -30,34 +30,6 @@ "startedAt": 0 } }, - "07299f73583f": { - "name": "aiVault.listSessions#1", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "0cf3d278751b": { "name": "status.get#1", "ordinal": 4, @@ -192,6 +164,35 @@ } } }, + "27ef7c5c6263": { + "name": "aiVault.listSessions#1", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "2ce0b0bdae00": { "name": "status.get#2", "ordinal": 6, @@ -259,11 +260,6 @@ } } }, - "595e6c3bbfed": { - "name": "aiVault.listSessions#1", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "68435dd07fce": { "name": "status.get#2", "ordinal": 6, @@ -472,6 +468,41 @@ "Retry" ] }, + "a0b80301d553": { + "name": "aiVault.listSessions#1", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "a24196eaf702": { "name": "status.get#1", "ordinal": 4, @@ -584,6 +615,11 @@ "Update Orca on this host to browse agent session history." ] }, + "dffc0668b556": { + "name": "aiVault.listSessions#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "e28c488ce6b2": { "name": "agentSession.subscribeStatus#1", "ordinal": 1, @@ -676,40 +712,6 @@ } } }, - "f13239f2c039": { - "name": "aiVault.listSessions#1", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "f975325adbf9": { "crash": { "$rpc": "null" @@ -800,8 +802,8 @@ { "id": "aivault-history-screen-worktrees.normal:worktrees-listed", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "07299f73583f"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "27ef7c5c6263"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, @@ -812,8 +814,8 @@ { "id": "aivault-history-screen-worktrees.normal:cleanup", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "f13239f2c039"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "a0b80301d553"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-worktree.ps-1.json b/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-worktree.ps-1.json index 48e22cbe7ad..0111ee05d69 100644 --- a/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-worktree.ps-1.json +++ b/mobile/rpc-foundation/goldens/matrix-aivault.history-screen-worktree.ps-1.json @@ -30,34 +30,6 @@ "startedAt": 0 } }, - "07299f73583f": { - "name": "aiVault.listSessions#1", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, "111e9a5009ba": { "name": "streams-registered-at-teardown", "ordinal": 4, @@ -103,6 +75,35 @@ } } }, + "27ef7c5c6263": { + "name": "aiVault.listSessions#1", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "519ce9879c6f": { "name": "worktree.ps#1", "ordinal": 2, @@ -138,11 +139,6 @@ } } }, - "595e6c3bbfed": { - "name": "aiVault.listSessions#1", - "ordinal": 7, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "5a2900554f7f": { "name": "worktree.ps#1", "ordinal": 2, @@ -351,6 +347,41 @@ } } }, + "a0b80301d553": { + "name": "aiVault.listSessions#1", + "ordinal": 6, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, "bdd2f2097a96": { "name": "worktree.ps#1", "ordinal": 2, @@ -455,6 +486,11 @@ "ordinal": 3, "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"supportsWorktreeVisibilitySourceDefaults\":true}}" }, + "dffc0668b556": { + "name": "aiVault.listSessions#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "e28c488ce6b2": { "name": "agentSession.subscribeStatus#1", "ordinal": 1, @@ -579,40 +615,6 @@ } } }, - "f13239f2c039": { - "name": "aiVault.listSessions#1", - "ordinal": 6, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "fe3fd26f3355": { "name": "aiVault.listSessions#1", "ordinal": 6, @@ -707,8 +709,8 @@ { "id": "aivault-history-screen-worktrees.normal:worktrees-listed", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "07299f73583f"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "27ef7c5c6263"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, @@ -719,8 +721,8 @@ { "id": "aivault-history-screen-worktrees.normal:cleanup", "observation": { - "sender": ["ebc8d9683b5e", "e881d7dabb25", "f13239f2c039"], - "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "595e6c3bbfed"], + "sender": ["ebc8d9683b5e", "e881d7dabb25", "a0b80301d553"], + "payloads": ["e28c488ce6b2", "d126597611a2", "7c48e0564605", "dffc0668b556"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/goldens/matrix-aivault.history-status.get-1.json b/mobile/rpc-foundation/goldens/matrix-aivault.history-status.get-1.json index f95d159753a..c89d3b1d72c 100644 --- a/mobile/rpc-foundation/goldens/matrix-aivault.history-status.get-1.json +++ b/mobile/rpc-foundation/goldens/matrix-aivault.history-status.get-1.json @@ -4,6 +4,50 @@ "family": "aiVault.history", "namedDeltas": [], "values": { + "03fd6edde488": { + "name": "aiVault.listSessions#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "aiVault.listSessions" + }, + { + "name": "params", + "value": { + "force": false, + "limit": 500, + "scopeOnly": true, + "scopePaths": ["/repo/feature"] + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "issues": [], + "sessions": [ + { + "agent": "claude", + "cwd": "/repo/feature", + "id": "s1" + } + ] + } + } + } + }, "0753498763d5": { "name": "status.get#1", "ordinal": 2, @@ -58,6 +102,11 @@ "kind": "unsupported" } }, + "2182656920b3": { + "name": "aiVault.listSessions#1", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"],\"scopeOnly\":true}}" + }, "2289d07f6bea": { "name": "status.get#1", "ordinal": 2, @@ -316,11 +365,6 @@ } } }, - "b6a16cc83e18": { - "name": "aiVault.listSessions#1", - "ordinal": 5, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"aiVault.listSessions\",\"params\":{\"limit\":500,\"force\":false,\"scopePaths\":[\"/repo/feature\"]}}" - }, "b838b12acde6": { "activeWorktreePath": "/repo/feature", "refreshing": false, @@ -374,49 +418,6 @@ } } }, - "cb5715e0f275": { - "name": "aiVault.listSessions#1", - "ordinal": 4, - "args": [ - { - "name": "method", - "value": "aiVault.listSessions" - }, - { - "name": "params", - "value": { - "force": false, - "limit": 500, - "scopePaths": ["/repo/feature"] - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "issues": [], - "sessions": [ - { - "agent": "claude", - "cwd": "/repo/feature", - "id": "s1" - } - ] - } - } - } - }, "d0831ff38203": { "name": "status.get#1", "ordinal": 2, @@ -604,8 +605,8 @@ { "id": "aivault-history-scan-fulfilled.normal:ready", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, @@ -616,8 +617,8 @@ { "id": "aivault-history-scan-fulfilled.normal:cleanup", "observation": { - "sender": ["daf52dc85a58", "cb5715e0f275"], - "payloads": ["e28c488ce6b2", "44a27dbf05e2", "b6a16cc83e18"], + "sender": ["daf52dc85a58", "03fd6edde488"], + "payloads": ["e28c488ce6b2", "44a27dbf05e2", "2182656920b3"], "settlements": { "mount": "eb79a9b3682a" }, diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index 578ed240f88..5be06b0d6b0 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -15597,6 +15597,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15684,6 +15685,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15733,6 +15735,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15771,6 +15774,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15825,6 +15829,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15853,6 +15858,7 @@ "params": { "force": true, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15902,6 +15908,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -15952,6 +15959,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { @@ -21336,6 +21344,7 @@ "params": { "force": false, "limit": 500, + "scopeOnly": true, "scopePaths": ["/repo/feature"] }, "reply": { diff --git a/mobile/src/agent-history/agent-history-scope-paths.test.ts b/mobile/src/agent-history/agent-history-scope-paths.test.ts index 790408afb37..018129e9013 100644 --- a/mobile/src/agent-history/agent-history-scope-paths.test.ts +++ b/mobile/src/agent-history/agent-history-scope-paths.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { deriveMobileAiVaultScopePaths, - mobileAiVaultScanScopePaths + mobileAiVaultScanScopeArgs } from './agent-history-scope-paths' const worktree = (worktreeId: string, path: string) => ({ worktreeId, path, repoId: 'repo-1' }) @@ -14,11 +14,13 @@ describe('mobile AI Vault scope paths', () => { 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 scanPaths = mobileAiVaultScanScopePaths(scopePaths) + const scan = mobileAiVaultScanScopeArgs('project', scopePaths) expect(scopePaths).toHaveLength(201) - expect(scanPaths).toHaveLength(64) + expect(scan.scopePaths).toHaveLength(64) // Active worktree is seeded first, so it survives truncation. - expect(scanPaths[0]).toBe('/Users/ada/repo/app') + 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/agent-history/agent-history-scope-paths.ts b/mobile/src/agent-history/agent-history-scope-paths.ts index 5f1d7107780..ab0ba73465d 100644 --- a/mobile/src/agent-history/agent-history-scope-paths.ts +++ b/mobile/src/agent-history/agent-history-scope-paths.ts @@ -1,6 +1,7 @@ import { deriveAiVaultScopeSessionPaths } from '../../../src/shared/ai-vault/scanning/ai-vault-scope-paths' import { - AI_VAULT_SCOPE_PATHS_MAX_COUNT, + boundedAiVaultScopeArgs, + type AiVaultListArgs, type AiVaultScope } from '../../../src/shared/ai-vault/contracts/ai-vault-types' import type { Worktree } from '../worktree/workspace-list-types' @@ -23,9 +24,12 @@ export function deriveMobileAiVaultScopePaths( ) } -/** The scan hints sent to the host; older hosts reject oversized scopePaths, and hints only widen discovery. */ -export function mobileAiVaultScanScopePaths(scopePaths: readonly string[]): string[] { - return scopePaths.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT) +/** The scope sent to the host: capped because older hosts reject oversized scopePaths; All keeps the recency scan. */ +export function mobileAiVaultScanScopeArgs( + scope: AiVaultScope, + scopePaths: readonly string[] +): Pick { + return boundedAiVaultScopeArgs(scopePaths, scope !== 'all') } function toScopePathWorktree(worktree: ScopeWorktree) { diff --git a/mobile/src/agent-history/use-mobile-agent-history-state.ts b/mobile/src/agent-history/use-mobile-agent-history-state.ts index 49bad58128d..5b8ebe2e2bc 100644 --- a/mobile/src/agent-history/use-mobile-agent-history-state.ts +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -17,7 +17,7 @@ import { defineHostQuery, readHostQueryLive, useHostQuery } from '../query/host- import { hostScreenState } from '../query/host-query-screen-state' import { deriveMobileAiVaultScopePaths, - mobileAiVaultScanScopePaths + mobileAiVaultScanScopeArgs } from './agent-history-scope-paths' import { agentHistoryCapabilityRead, @@ -65,6 +65,7 @@ type ScanScope = { scopeFilterPaths: string[]; activeWorktreePath: string | null async function readAgentHistory( client: RpcClient, + scope: AiVaultScope, scan: ScanScope, force: boolean, associationRevision: number @@ -81,7 +82,8 @@ async function readAgentHistory( const reply = await agentHistorySessionScan.request(client, { limit: MOBILE_AI_VAULT_SESSION_LIMIT, force, - scopePaths: mobileAiVaultScanScopePaths(scan.scopeFilterPaths) + // From the query's own scope key, so rows cached under Workspace are always Workspace-only ones. + ...mobileAiVaultScanScopeArgs(scope, scan.scopeFilterPaths) }) const result = interpretOrThrowRefusalMessage( () => agentHistorySessionScan.interpret(reply), @@ -111,7 +113,7 @@ function agentHistoryQuery( // No desktop signal for new transcripts, so foreground revalidates once older than 30 s. refetchOnWindowFocus: true, fetch: (client, _target, input: { scope: AiVaultScope }) => - readAgentHistory(client, scan, force, startRevision(input.scope)) + readAgentHistory(client, input.scope, scan, force, startRevision(input.scope)) }) } diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index f29fbdbe557..e10689a2c98 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -29,7 +29,9 @@ const WORKTREE_CHANGE_EVENTS: ReadonlySet = new Set([ 'worktreesChanged', 'reposChanged', // The desktop Agents list changed; worktree.ps carries its verdicts. - 'agentListChanged' + 'agentListChanged', + // Agent status changes on hosts without the sidebar feed (worktree.rows-changed-event.v1). + 'worktreeRowsChanged' ]) export type HomeAccountsSetter = ( diff --git a/mobile/src/hooks/use-now.ts b/mobile/src/hooks/use-now.ts index b6e8f5a1b23..8db14cd3e69 100644 --- a/mobile/src/hooks/use-now.ts +++ b/mobile/src/hooks/use-now.ts @@ -95,6 +95,12 @@ function stopTimer(clock: SharedClock): void { * (one timer, one timestamp). It runs only in the foreground and catches up on return. */ export function useSharedNow(intervalMs = 30_000): number { + return useSharedNowSnapshot(intervalMs, readNow) +} + +const readNow = (now: number): number => now + +export function useSharedNowSnapshot(intervalMs: number, select: (now: number) => T): T { const clock = sharedClock(intervalMs) const subscribe = useCallback( (listener: () => void) => { @@ -128,6 +134,6 @@ export function useSharedNow(intervalMs = 30_000): number { }, [clock, intervalMs] ) - const read = useCallback(() => clock.now, [clock]) + const read = useCallback(() => select(clock.now), [clock, select]) return useSyncExternalStore(subscribe, read, read) } diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index 9703b867848..f93e01fc3a4 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -303,6 +303,12 @@ "uncommittedFiles_other": "{{count}} uncommitted" }, "failure": { + "forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.", + "forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat. Open it and fork from there.", + "forkOriginalMissingNamed": "{{agent}} could not find this response in \"{{detail}}\". Open that chat and fork from there.", + "forkOriginalUnavailableNamed": "{{agent}} cannot fork this response in \"{{detail}}\". Open that chat and fork from there.", + "forkOriginalLatestOnly": "{{agent}} can only fork the latest response in the original chat. Open that chat and fork its latest response once it has finished.", + "forkOriginalLatestOnlyNamed": "{{agent}} can only fork the latest response in \"{{detail}}\". Open that chat and fork its latest response once it has finished.", "pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal.", "providerResponseFailed": "{{agent}} couldn't finish this response. Open Details for more information.", "providerSafetyStopped": "{{agent}} stopped this response after a safety check. Review your request and send again.", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index b59fe072f68..c3cc0a461f3 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2543,6 +2543,12 @@ "fallback": "Worktree" }, "failure": { + "forkOriginalMissing": "{{agent}} could not find this response in the original chat. Open it and fork from there.", + "forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat. Open it and fork from there.", + "forkOriginalMissingNamed": "{{agent}} could not find this response in \"{{detail}}\". Open that chat and fork from there.", + "forkOriginalUnavailableNamed": "{{agent}} cannot fork this response in \"{{detail}}\". Open that chat and fork from there.", + "forkOriginalLatestOnly": "{{agent}} can only fork the latest response in the original chat. Open that chat and fork its latest response once it has finished.", + "forkOriginalLatestOnlyNamed": "{{agent}} can only fork the latest response in \"{{detail}}\". Open that chat and fork its latest response once it has finished.", "backgroundTasksRunning": "Background tasks are still running.", "waitForBackgroundTasks": "Wait for the background tasks to finish.", "agentStarting": "The agent is still starting.", diff --git a/mobile/src/query/first-paint-query-keys.ts b/mobile/src/query/first-paint-query-keys.ts index 1aa38969d5b..609962e2284 100644 --- a/mobile/src/query/first-paint-query-keys.ts +++ b/mobile/src/query/first-paint-query-keys.ts @@ -10,6 +10,7 @@ import { hostViewFamily, hostViewKey } from '../host-screen/host-view-memory' import { hostProjectSectionsQuery } from '../host-screen/use-host-project-sections' import { sessionTabsFamily, sessionTabsKey } from '../session/tabs/mobile-session-last-tabs' import { gitStatusQuery } from '../source-control/mobile-git-status-query' +import { firstPaintTaskKeys } from '../tasks/task-query-storage' import { hostQueryKey } from './host-query-key' import { persistedHostQueryKey, type PersistedHostQueryKey } from './host-query-persistence' @@ -33,6 +34,9 @@ export function firstPaintQueryKeys(hostId: string, route: URL): PersistedHostQu if (root !== 'h' || routeSegment(routeHost) !== hostId) { return [] } + if (screen === 'tasks') { + return firstPaintTaskKeys(hostId) + } const keys = screen === undefined ? [ diff --git a/mobile/src/query/host-query-persistence.ts b/mobile/src/query/host-query-persistence.ts index 9e03c13c677..9edf0f556df 100644 --- a/mobile/src/query/host-query-persistence.ts +++ b/mobile/src/query/host-query-persistence.ts @@ -48,6 +48,8 @@ function hostQueryPersistOf(query: Query): HostQueryPersist | undefined // Per world, the keys whose data came from the store and no read has replaced yet. const restoredKeys = new WeakMap>() +// Per world, its store; absent in a document that keeps queries in memory only. +const persistences = new WeakMap() /** * Whether a key still holds what an earlier launch stored: shown, but possibly days old and unconfirmed by @@ -65,6 +67,17 @@ function familyPrefix(family: string, persist: HostQueryPersist): strin // Stored data of any age paints (silently while online); this only bounds what a forgotten host leaves. const STORED_FOR_MS = 14 * 24 * 60 * 60 * 1000 +/** + * Restores stored keys a screen reads without observing them (its inputs come from its own state). + * Resolves once each is applied or missed; at once where nothing is stored. + */ +export function restoreStoredHostQueries( + queryClient: QueryClient, + keys: readonly PersistedHostQueryKey[] +): Promise { + return persistences.get(queryClient)?.restore(keys) ?? Promise.resolve() +} + export type HostQueryPersistence = { // Restores keys that hold no data yet, from one store read; resolves once each is applied or missed. restore(keys: readonly PersistedHostQueryKey[]): Promise @@ -117,8 +130,9 @@ export function createHostQueryPersistence( const settledAt = new Map() // The last data written per key and what it was stored as, so unchanged data keeps one stored object. const lastStored = new Map() - const restoring = new Set() - // Keys the boot read just found empty: the screen's first observer doesn't read them again. + // One store read per key at a time; a second caller waits on the first. + const restoring = new Map>() + // Keys a restore found empty: neither the screen's first observer nor a later restore reads them again. const missedAtBoot = new Set() const triedOnMiss = new WeakSet() const restored = new Set() @@ -177,11 +191,14 @@ export function createHostQueryPersistence( function restoreOne(queryKey: readonly unknown[], persist: HostQueryPersist) { const family = familyOf(queryKey) const queryHash = hashKey(queryKey) - if (family === null || restoring.has(queryHash)) { + if (family === null) { return Promise.resolve() } - restoring.add(queryHash) - return new Promise((settle) => { + const pending = restoring.get(queryHash) + if (pending) { + return pending + } + const restore = new Promise((settle) => { void persisterFor(family, persist) .retrieveQuery(queryHash, (record) => { if (queryClient.getQueryData(queryKey) === undefined) { @@ -202,6 +219,8 @@ export function createHostQueryPersistence( () => settle() ) }).finally(() => restoring.delete(queryHash)) + restoring.set(queryHash, restore) + return restore } queryClient.getQueryCache().subscribe((event) => { @@ -243,17 +262,22 @@ export function createHostQueryPersistence( void persisterFor(family, persist).persistQuery(query) }) - return { + const persistence: HostQueryPersistence = { async restore(keys) { const empty = keys.flatMap((key) => { const family = familyOf(key.queryKey) - return family !== null && queryClient.getQueryData(key.queryKey) === undefined + return family !== null && + queryClient.getQueryData(key.queryKey) === undefined && + !missedAtBoot.has(hashKey(key.queryKey)) ? [{ ...key, family }] : [] }) + // A key already being read joins that read below instead of reading again. await primer.prime( - empty.map(({ queryKey, persist, family }) => - orcaQueryStoreKey(`${familyPrefix(family, persist)}-${hashKey(queryKey)}`) + empty.flatMap(({ queryKey, persist, family }) => + restoring.has(hashKey(queryKey)) + ? [] + : [orcaQueryStoreKey(`${familyPrefix(family, persist)}-${hashKey(queryKey)}`)] ) ) await Promise.all( @@ -267,4 +291,6 @@ export function createHostQueryPersistence( }, flush: () => storage.flush() } + persistences.set(queryClient, persistence) + return persistence } diff --git a/mobile/src/session/MobileNativeChatForkProvider.tsx b/mobile/src/session/MobileNativeChatForkProvider.tsx index 27624a3c571..44f80dff88a 100644 --- a/mobile/src/session/MobileNativeChatForkProvider.tsx +++ b/mobile/src/session/MobileNativeChatForkProvider.tsx @@ -1,5 +1,6 @@ import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' -import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import { useHostProtocolGates } from '../components/host-protocol-gates-context' +import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { StructuredAgentSessionForkSource } from '../../../src/shared/agent-session/structured-agent-session-create' import { MobileNativeChatForkedFromContext } from './mobile-native-chat-notice-context' import { forkMobileStructuredChat } from './mobile-structured-chat-fork' @@ -19,19 +20,21 @@ export function MobileNativeChatForkProvider({ children: React.ReactNode }): React.JSX.Element { const { client, nativeChatController: chat, openNativeSession, worktreeId } = controller + const { statusPending } = useHostProtocolGates() // The controller is rebuilt each render; a fork reads its session state at the press. const latestController = useRef(controller) useLayoutEffect(() => { latestController.current = controller }) const createFork = useCallback( - (agent: AgentSessionHandleProvider, forkFrom: StructuredAgentSessionForkSource) => + (agent: TuiAgent, forkFrom: StructuredAgentSessionForkSource) => forkMobileStructuredChat(latestController.current, agent, forkFrom), [] ) const fork = useMobileNativeChatFork({ client, hostCapabilities: controller.hostCapabilities, + hostStatusPending: statusPending || controller.connState !== 'connected', agent: chat.nativeChatAgent, sessionId: resolveMobileNativeChatSessionId(controller.activeSessionTab), messages: chat.nativeChatSession.messages, diff --git a/mobile/src/session/agent-session-failure-copy.ts b/mobile/src/session/agent-session-failure-copy.ts index 22b0af20e34..541b5a76698 100644 --- a/mobile/src/session/agent-session-failure-copy.ts +++ b/mobile/src/session/agent-session-failure-copy.ts @@ -10,6 +10,42 @@ import { SEND_FAILURE_COPY } from './agent-session-send-failure-copy' const COPY: Record string> = { ...START_FAILURE_COPY, + forkOriginalMissing: (values) => + translate( + 'session.failure.forkOriginalMissing', + AGENT_SESSION_FAILURE_COPY.forkOriginalMissing, + values + ), + forkOriginalUnavailable: (values) => + translate( + 'session.failure.forkOriginalUnavailable', + AGENT_SESSION_FAILURE_COPY.forkOriginalUnavailable, + values + ), + forkOriginalMissingNamed: (values) => + translate( + 'session.failure.forkOriginalMissingNamed', + AGENT_SESSION_FAILURE_COPY.forkOriginalMissingNamed, + values + ), + forkOriginalUnavailableNamed: (values) => + translate( + 'session.failure.forkOriginalUnavailableNamed', + AGENT_SESSION_FAILURE_COPY.forkOriginalUnavailableNamed, + values + ), + forkOriginalLatestOnly: (values) => + translate( + 'session.failure.forkOriginalLatestOnly', + AGENT_SESSION_FAILURE_COPY.forkOriginalLatestOnly, + values + ), + forkOriginalLatestOnlyNamed: (values) => + translate( + 'session.failure.forkOriginalLatestOnlyNamed', + AGENT_SESSION_FAILURE_COPY.forkOriginalLatestOnlyNamed, + values + ), pluginInputRequired: (values) => translate( 'session.failure.pluginInputRequired', diff --git a/mobile/src/session/mobile-structured-agent-session-launch.test.ts b/mobile/src/session/mobile-structured-agent-session-launch.test.ts index 75975d2c9e8..2218b37ac4e 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.test.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.test.ts @@ -122,3 +122,31 @@ describe('mobile structured agent-session launch', () => { } ) }) + +it('settles a proven missing-original fork refusal but keeps a lost earlier attempt unknown', async () => { + const refusal = { + ok: true, + result: { + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' }, + createAttemptRefusedBeforeCommit: true, + message: 'Source chat unavailable' + } + } + } + const client = clientReturning({ ok: true, result: { supported: true } }, refusal) + const forkFrom = { sessionId: 'copied-chat', throughItemId: 'legacy:opencode:source:reply-1' } + expect( + (await createMobileStructuredAgentSession(client, 'workspace-1', 'opencode', forkFrom)).kind + ).toBe('failed') + const lost = clientReturning({ ok: true, result: { supported: true } }, refusal) + lost.sendRequest + .mockImplementationOnce(async () => ({ ok: true, result: { supported: true } })) + .mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('reply lost'))) + .mockResolvedValueOnce(refusal) + expect( + (await createMobileStructuredAgentSession(lost, 'workspace-1', 'opencode', forkFrom)).kind + ).toBe('unknown') +}) diff --git a/mobile/src/session/mobile-structured-agent-session-launch.ts b/mobile/src/session/mobile-structured-agent-session-launch.ts index a6a667587bd..55dbc1ebef0 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.ts @@ -1,9 +1,14 @@ -import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import { agentSessionForkSourceFailureWords } from '../../../src/shared/agent-session/failures/agent-session-failure-copy' +import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' +import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { AgentSessionAttachResult, AgentSessionMutationResult } from '../../../src/shared/agent-session/agent-session-wire' -import { isDefinitiveAgentSessionCreateRefusal } from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal' +import { + isDefinitiveAgentSessionCreateRefusal, + isAgentSessionForkSourceAdmissionRefusal +} from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal' import { createStructuredAgentSessionId, structuredAgentSessionCreateParams, @@ -38,7 +43,7 @@ export type MobileStructuredAgentLaunchResult = | { kind: 'unknown'; message: string } function createParamsFor( - agent: AgentSessionHandleProvider, + agent: TuiAgent, worktree: string, forkFrom: StructuredAgentSessionForkSource | undefined, tabPlacement: StructuredAgentSessionCreateParams['tabPlacement'] @@ -53,25 +58,22 @@ function createParamsFor( }) } -function unknownCreateResult( - agent: AgentSessionHandleProvider, - error: unknown -): MobileStructuredAgentLaunchResult { +function unknownCreateResult(agent: TuiAgent, error: unknown): MobileStructuredAgentLaunchResult { const message = error instanceof Error ? error.message.trim() : '' return { kind: 'unknown', message: message || unconfirmedMessage(agent) } } -function unconfirmedMessage(agent: AgentSessionHandleProvider): string { +function unconfirmedMessage(agent: TuiAgent): string { return `The ${TUI_AGENT_DISPLAY_NAMES[agent]} chat result could not be confirmed.` } -function failedMessage(agent: AgentSessionHandleProvider): string { +function failedMessage(agent: TuiAgent): string { return `Could not open ${TUI_AGENT_DISPLAY_NAMES[agent]} chat.` } // Only definitive refusal permits failure/fallback; uncertain creates may already own a session and must not create a sibling. function classifyCreateRefusal( - agent: AgentSessionHandleProvider, + agent: TuiAgent, code: string, message: string ): MobileStructuredAgentLaunchResult { @@ -84,7 +86,7 @@ function classifyCreateRefusal( export async function createMobileStructuredAgentSession( client: RpcClient, worktreeId: string, - agent: AgentSessionHandleProvider, + agent: TuiAgent, /** Sent only to a host advertising forks. */ forkFrom?: StructuredAgentSessionForkSource, /** Sent only to a host advertising create placement; the replay keeps it. */ @@ -132,12 +134,14 @@ export async function createMobileStructuredAgentSession( const params = createParamsFor(agent, worktree, forkFrom, tabPlacement) rememberMobileCreatedStructuredSession(params.envelope.sessionId, worktree) let response + let priorCreateOutcomeUnknown = false try { response = await structuredAgentSessionCreate.request(client, params, { timeoutMs: 15_000, budgetSpansConnect: true }) } catch { + priorCreateOutcomeUnknown = true // Replay the durable envelope once so a lost acknowledgement cannot create a sibling. try { response = await structuredAgentSessionCreate.request(client, params, { @@ -179,6 +183,22 @@ export async function createMobileStructuredAgentSession( ) { return unknownCreateResult(agent, new Error(unconfirmedMessage(agent))) } + if ( + forkFrom && + !priorCreateOutcomeUnknown && + result.refusal.createAttemptRefusedBeforeCommit === true && + isAgentSessionForkSourceAdmissionRefusal(result.refusal) + ) { + return { + kind: 'failed', + message: + agentSessionForkSourceFailureWords( + result.refusal.message, + TUI_AGENT_DISPLAY_NAMES[agent], + sayMobileAgentSessionFailure + ) ?? result.refusal.message + } + } return classifyCreateRefusal(agent, result.refusal.code, result.refusal.message) } if ( diff --git a/mobile/src/session/mobile-structured-chat-fork.ts b/mobile/src/session/mobile-structured-chat-fork.ts index 8570c685a0d..ff26e8eb7c7 100644 --- a/mobile/src/session/mobile-structured-chat-fork.ts +++ b/mobile/src/session/mobile-structured-chat-fork.ts @@ -1,7 +1,7 @@ import { translate } from '../i18n/mobile-i18n' import { triggerError } from '../platform/haptics' import { TUI_AGENT_DISPLAY_NAMES } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' -import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' +import type { TuiAgent } from '../../../src/shared/agent-launch/catalog/tui-agent' import type { StructuredAgentSessionCreateParams, StructuredAgentSessionForkSource @@ -48,7 +48,7 @@ export function mobileChatForkTabPlacement( * Resolves once the outcome is known, so the caller's action stays disabled until then. */ export async function forkMobileStructuredChat( scope: ForkScope, - agent: AgentSessionHandleProvider, + agent: TuiAgent, forkFrom: StructuredAgentSessionForkSource ): Promise { const agentName = TUI_AGENT_DISPLAY_NAMES[agent] diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessageTime.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatMessageTime.tsx index f94409b53f4..546e652ae83 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessageTime.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessageTime.tsx @@ -1,16 +1,15 @@ import { memo } from 'react' import { Text } from 'react-native' import { - NATIVE_CHAT_MESSAGE_FULL_TIME_FORMAT, - NATIVE_CHAT_MESSAGE_TIME_FORMAT + getNativeChatMessageDay, + getNativeChatMessageTimeFormatter } from '../../../../../src/shared/native-chat/transcript/native-chat-message-time' +import { useSharedNowSnapshot } from '../../../hooks/use-now' import { colors, typography } from '../../../theme/mobile-theme' import { themedStyleSheet } from '../../../theme/themed-styles' import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme' import { scaledType } from './mobile-native-chat-message-styles' -let formatters: { time: Intl.DateTimeFormat; full: Intl.DateTimeFormat } | null = null - export const MobileNativeChatMessageTime = memo(function MobileNativeChatMessageTime({ timestamp, fontScale @@ -19,20 +18,18 @@ export const MobileNativeChatMessageTime = memo(function MobileNativeChatMessage fontScale: number }): React.JSX.Element | null { useMobileColorScheme() + const today = useSharedNowSnapshot(30_000, getNativeChatMessageDay) const date = timestamp == null ? null : new Date(timestamp) if (!date || Number.isNaN(date.getTime())) { return null } - formatters ??= { - time: new Intl.DateTimeFormat(undefined, NATIVE_CHAT_MESSAGE_TIME_FORMAT), - full: new Intl.DateTimeFormat(undefined, NATIVE_CHAT_MESSAGE_FULL_TIME_FORMAT) - } + const formatter = getNativeChatMessageTimeFormatter(undefined, today) return ( - {formatters.time.format(date)} + {formatter.format(date, today.date)} ) }) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-fork.test.tsx b/mobile/src/session/native-chat/use-mobile-native-chat-fork.test.tsx new file mode 100644 index 00000000000..1bdd9668d50 --- /dev/null +++ b/mobile/src/session/native-chat/use-mobile-native-chat-fork.test.tsx @@ -0,0 +1,217 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY +} from '../../../../src/shared/agent-session/agent-session-create-capabilities' +import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import type { AgentJournalRenderItem } from '../../../../src/shared/agent-session/journal/agent-session-journal-types' +import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import { useMobileNativeChatFork, type MobileNativeChatFork } from './use-mobile-native-chat-fork' + +const renderers: ReactTestRenderer[] = [] + +afterEach(() => { + act(() => renderers.forEach((renderer) => renderer.unmount())) + renderers.length = 0 +}) + +/** A connection whose agent-list reads fail as scripted (true = fails), as when the socket drops. */ +function connection(failures: number | readonly boolean[]) { + const listeners = new Set<(state: 'connected' | 'reconnecting') => void>() + const script = + typeof failures === 'number' ? Array.from({ length: failures }, () => true) : [...failures] + let generation = 1 + const sendRequest = vi.fn(async () => { + if (script.shift() === true) { + throw new Error('Connection interrupted') + } + return { + ok: true, + result: { agents: [{ agent: 'claude', capabilities: { fork: 'checkpoint' } }] } + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook reads only sendRequest, onStateChange and getGeneration from its client. + const client = { + sendRequest, + getGeneration: () => generation, + onStateChange: (listener: (state: 'connected' | 'reconnecting') => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + } as unknown as RpcClient + const reconnect = () => listeners.forEach((listener) => listener('connected')) + const migrate = () => { + generation++ + reconnect() + } + return { client, sendRequest, reconnect, migrate } +} + +const reply: AgentJournalRenderItem = { + itemId: 'reply', + sequence: 1, + revision: 1, + observedAt: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ok' }] } +} +const message: NativeChatMessage = { + id: 'reply', + role: 'assistant', + blocks: [{ type: 'text', text: 'ok' }], + timestamp: 1, + source: 'transcript', + journalPosition: { sequence: 1, index: 0 } +} +const FORK_HOST = [AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY] +let latest: MobileNativeChatFork | null = null + +async function settle(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} + +it('offers an inherited OpenCode tip after the child advances and submits its displayed key', async () => { + let renderer!: ReactTestRenderer + const { client, sendRequest } = connection(0) + sendRequest.mockResolvedValue({ + ok: true, + result: { agents: [{ agent: 'opencode', capabilities: { fork: 'tip' } }] } + }) + const createFork = vi.fn(async () => {}) + const copied = { + ...message, + id: 'legacy:opencode:source:reply-1', + journalPosition: { sequence: 5, index: 0 } + } + const copiedPrompt: NativeChatMessage = { + ...message, + id: 'legacy:opencode:source:user-1', + role: 'user', + journalPosition: { sequence: 4, index: 0 } + } + const ownPrompt: NativeChatMessage = { + ...message, + id: 'legacy:opencode:child:user-2', + role: 'user', + journalPosition: { sequence: 7, index: 0 } + } + const own = { + ...message, + id: 'legacy:opencode:child:reply-2', + journalPosition: { sequence: 8, index: 0 } + } + const olderPrompt: NativeChatMessage = { + ...copiedPrompt, + id: 'legacy:opencode:source:user-0', + journalPosition: { sequence: 1, index: 0 } + } + const older = { + ...copied, + id: 'legacy:opencode:source:reply-0', + journalPosition: { sequence: 2, index: 0 } + } + function ForkProbe({ + hostCapabilities, + hostStatusPending = false + }: { + hostCapabilities: readonly string[] + hostStatusPending?: boolean + }) { + latest = useMobileNativeChatFork({ + client, + hostCapabilities, + hostStatusPending, + agent: 'opencode', + sessionId: 'child', + messages: [olderPrompt, older, copiedPrompt, copied, ownPrompt, own], + turnJournal: { + items: [ + { + ...reply, + itemId: olderPrompt.id, + sequence: 1, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { ...reply, itemId: older.id, sequence: 2 }, + { + ...reply, + itemId: copiedPrompt.id, + sequence: 4, + body: { kind: 'message', role: 'user', blocks: copiedPrompt.blocks } + }, + { ...reply, itemId: copied.id, sequence: 5 }, + { + ...reply, + itemId: 'orca:forked-from', + sequence: 6, + body: { kind: 'status', presentation: 'forked-from', text: 'Forked from source' } + }, + { + ...reply, + itemId: ownPrompt.id, + sequence: 7, + body: { kind: 'message', role: 'user', blocks: ownPrompt.blocks } + }, + { ...reply, itemId: own.id, sequence: 8 } + ], + submissions: [] + }, + agentWorking: false, + sessionForkSupport: 'supported', + createFork + }) + return null + } + await act(async () => { + renderer = create(createElement(ForkProbe, { hostCapabilities: FORK_HOST })) + renderers.push(renderer) + }) + await settle() + expect(latest?.offerFor(copied)).toBe('reserved') + expect(latest?.offerFor(older)).toBe('reserved') + expect(latest?.offerFor(own)).toBe('available') + await act(async () => { + renderer.update( + createElement(ForkProbe, { + hostCapabilities: [...FORK_HOST, AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY] + }) + ) + }) + expect(latest?.offerFor(copied)).toBe('available') + expect(latest?.offerFor(older)).toBe('available') + await act(async () => { + renderer.update( + createElement(ForkProbe, { + hostCapabilities: [...FORK_HOST, AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY], + hostStatusPending: true + }) + ) + }) + expect(latest?.offerFor(copied)).toBe('reserved') + expect(latest?.offerFor(own)).toBe('available') + await act(async () => { + renderer.update( + createElement(ForkProbe, { + hostCapabilities: [...FORK_HOST, AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY], + hostStatusPending: false + }) + ) + }) + expect(latest?.offerFor(copied)).toBe('available') + await act(async () => { + latest?.fork(copied) + }) + expect(createFork).toHaveBeenCalledWith('opencode', { + sessionId: 'child', + throughItemId: 'legacy:opencode:source:reply-1' + }) + await act(async () => { + renderer.update(createElement(ForkProbe, { hostCapabilities: FORK_HOST })) + }) + expect(latest?.offerFor(copied)).toBe('reserved') +}) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-fork.ts b/mobile/src/session/native-chat/use-mobile-native-chat-fork.ts index 9608e82f14a..e3b4eea5e20 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-fork.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-fork.ts @@ -13,16 +13,17 @@ import { type AgentSessionRegisteredAgent } from '../../../../src/shared/agent-session/agent-session-registered-agents' import type { AgentSessionOptionsResult } from '../../../../src/shared/agent-session/options/agent-session-options-result' -import { AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY } from '../../../../src/shared/agent-session/agent-session-create-capabilities' -import { latestAgentSessionContextClearSequence } from '../../../../src/shared/agent-session/agent-session-context-clear' import { - isAgentSessionHandleProvider, - type AgentSessionHandleProvider -} from '../../../../src/shared/agent-session/lifecycle/agent-session-provider-handle' + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY +} from '../../../../src/shared/agent-session/agent-session-create-capabilities' +import { latestAgentSessionContextClearSequence } from '../../../../src/shared/agent-session/agent-session-context-clear' +import { isTuiAgent } from '../../../../src/shared/agent-launch/catalog/tui-agent-config' +import type { TuiAgent } from '../../../../src/shared/agent-launch/catalog/tui-agent' import type { StructuredAgentSessionForkSource } from '../../../../src/shared/agent-session/structured-agent-session-create' import type { StructuredAgentSessionHostCapabilityState } from '../../../../src/shared/agent-session/structured-agent-session-host-capability' import { - nativeChatForkableItemIds, + nativeChatForkInventory, nativeChatForkSupport, nativeChatRowOffersFork } from '../../../../src/shared/native-chat/native-chat-fork-offer' @@ -155,6 +156,7 @@ function useRegisteredAgent( export function useMobileNativeChatFork(input: { client: RpcClient | null hostCapabilities: readonly string[] | undefined + hostStatusPending: boolean agent: string | null sessionId: string | null messages: readonly NativeChatMessage[] @@ -162,20 +164,23 @@ export function useMobileNativeChatFork(input: { agentWorking: boolean /** The chat's options read on its installed agent; the host's own discovery owns it. */ sessionForkSupport: AgentSessionOptionsResult['forkSupport'] - createFork: ( - agent: AgentSessionHandleProvider, - forkFrom: StructuredAgentSessionForkSource - ) => Promise + createFork: (agent: TuiAgent, forkFrom: StructuredAgentSessionForkSource) => Promise }): MobileNativeChatFork { const host: StructuredAgentSessionHostCapabilityState = !input.hostCapabilities ? 'unknown' : input.hostCapabilities.includes(AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY) ? 'supported' : 'unsupported' + const inheritedOriginal: StructuredAgentSessionHostCapabilityState = + !input.hostCapabilities || input.hostStatusPending + ? 'unknown' + : input.hostCapabilities.includes(AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY) + ? 'supported' + : 'unsupported' const registered = useRegisteredAgent(input.client, host, input.agent) const support = useMemo( - () => nativeChatForkSupport(host, registered, input.sessionForkSupport), - [host, registered, input.sessionForkSupport] + () => nativeChatForkSupport(host, registered, input.sessionForkSupport, inheritedOriginal), + [host, registered, input.sessionForkSupport, inheritedOriginal] ) const { messages, turnJournal, agentWorking, sessionId, agent, createFork } = input const turns = useMemo(() => { @@ -191,8 +196,8 @@ export function useMobileNativeChatFork(input: { }, [messages, turnJournal]) const contextFloorSequence = latestAgentSessionContextClearSequence(turnJournal?.items ?? []) // The sheet's row is a display projection; only one naming the agent's own message forks. - const forkableItemIds = useMemo( - () => nativeChatForkableItemIds(turnJournal?.items ?? []), + const { forkableItemIds, inheritedThroughSequence } = useMemo( + () => nativeChatForkInventory(turnJournal?.items ?? []), [turnJournal] ) // Reserved at the press, before any await, so a second press never starts a second fork. @@ -206,7 +211,7 @@ export function useMobileNativeChatFork(input: { const turnKey = turns.keyById.get(message.id) const offered = !!sessionId && - isAgentSessionHandleProvider(agent ?? '') && + isTuiAgent(agent ?? '') && nativeChatRowOffersFork( { message, @@ -214,7 +219,7 @@ export function useMobileNativeChatFork(input: { turnWorking: agentWorking && (turnKey === undefined || turnKey === turns.liveTurnKey), inLatestTurn: turnKey !== undefined && turnKey === turns.latestTurnKey }, - { support, contextFloorSequence, forkableItemIds } + { support, contextFloorSequence, forkableItemIds, inheritedThroughSequence } ) return !offered ? 'reserved' @@ -222,7 +227,17 @@ export function useMobileNativeChatFork(input: { ? 'disabled' : 'available' }, - [agent, agentWorking, contextFloorSequence, forkableItemIds, pending, sessionId, support, turns] + [ + agent, + agentWorking, + contextFloorSequence, + forkableItemIds, + inheritedThroughSequence, + pending, + sessionId, + support, + turns + ] ) const fork = useCallback( (message: NativeChatMessage) => { @@ -231,7 +246,7 @@ export function useMobileNativeChatFork(input: { offerFor(message) !== 'available' || !sessionId || !agent || - !isAgentSessionHandleProvider(agent) + !isTuiAgent(agent) ) { return } diff --git a/mobile/src/tasks/MobileTasksLegacySurface.tsx b/mobile/src/tasks/MobileTasksLegacySurface.tsx index 3d411602f71..ed32900e874 100644 --- a/mobile/src/tasks/MobileTasksLegacySurface.tsx +++ b/mobile/src/tasks/MobileTasksLegacySurface.tsx @@ -1,6 +1,6 @@ import { useState } from 'react' import { describeLoadError } from '../components/load-error-description' -import { mobileTasksListShowsError } from './mobile-tasks-list-state' +import { MobileTasksOfflineBanner, mobileTasksListShowsError } from './mobile-tasks-list-state' import type { ConnectionPresentationModel } from './use-mobile-tasks-connection-presentation' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { @@ -203,6 +203,8 @@ export function MobileTasksLegacySurface({ model }: { model: ConnectionPresentat ) : null} + + {renderMobileTasksListSurface(model, colorScheme, bottomBarHeight)} {renderMobileTasksSearchControl(model, setSearchBarHeight)} diff --git a/mobile/src/tasks/mobile-tasks-linear-list.tsx b/mobile/src/tasks/mobile-tasks-linear-list.tsx index a9081cf783e..aa4a51587a5 100644 --- a/mobile/src/tasks/mobile-tasks-linear-list.tsx +++ b/mobile/src/tasks/mobile-tasks-linear-list.tsx @@ -12,7 +12,7 @@ import { TaskProviderLogo, type MobileColorScheme } from './mobile-tasks-dependencies' -import { renderMobileTasksListState } from './mobile-tasks-list-state' +import { ignoreKeptRowPress, renderMobileTasksListState } from './mobile-tasks-list-state' import { styles } from './mobile-tasks-legacy-styles' import { createLinearTask, @@ -37,9 +37,13 @@ export function renderMobileTasksLinearList( mutatingStatus, refreshTasks, refreshing, - setActionItem, - setLinearStatusPickerItem + taskUiReady } = model + // The last list, kept before Tasks is ready, is read-only. + const setActionItem = taskUiReady ? model.setActionItem : ignoreKeptRowPress + const setLinearStatusPickerItem = taskUiReady + ? model.setLinearStatusPickerItem + : ignoreKeptRowPress const listState = renderMobileTasksListState(model, linearIssuesForView.length, bottomBarHeight) if (listState) { return listState diff --git a/mobile/src/tasks/mobile-tasks-list-state.tsx b/mobile/src/tasks/mobile-tasks-list-state.tsx index bc8e778dd37..b190e73ba31 100644 --- a/mobile/src/tasks/mobile-tasks-list-state.tsx +++ b/mobile/src/tasks/mobile-tasks-list-state.tsx @@ -1,4 +1,6 @@ import { CircleAlert, Inbox } from 'lucide-react-native' +import { StyleSheet, View } from 'react-native' +import { HostOfflineBanner, useHostOfflineBanner } from '../components/HostOfflineBanner' import { MobileLoadErrorState, MobileNoMatchState, @@ -6,10 +8,16 @@ import { MobileStateView } from '../components/MobileStateView' import { useForceReconnect } from '../transport/connection/host-client-hooks' +import { isConnectionOutage } from '../transport/connection/connection-health' +import { useHostDisplay } from '../transport/hosts/use-host-display' +import { useHostProfile } from '../transport/hosts/use-host-profile' +import { spacing } from '../theme/mobile-theme' import { translate } from '../i18n/mobile-i18n' import type { ConnectionPresentationModel } from './use-mobile-tasks-connection-presentation' import { clearMobileTasksSearch } from './mobile-tasks-search-control' +export function ignoreKeptRowPress(): void {} + /** True when the list body itself shows the load failure, so the banner above must not repeat it. */ export function mobileTasksListShowsError(model: ConnectionPresentationModel): boolean { if (!model.error) { @@ -117,3 +125,36 @@ function MobileTasksOfflineState({ hostId, bottomInset }: { hostId: string; bott /> ) } + +/** Over the last list while the desktop can't be reached, with when those rows were read. */ +export function MobileTasksOfflineBanner({ model }: { model: ConnectionPresentationModel }) { + const { hostId } = model + const forceReconnect = useForceReconnect() + const hostName = useHostDisplay(useHostProfile(hostId)).title + const banner = useHostOfflineBanner({ + client: model.client, + connState: model.connState, + lastConnectedAt: model.lastConnectedAt, + outage: isConnectionOutage(model.headerVerdict), + forceReconnect: forceReconnect && hostId ? () => void forceReconnect(hostId) : null, + hasData: model.showsKeptRows, + asOf: model.rowsReadAt + }) + if (!banner) { + return null + } + return ( + + + + ) +} + +const bannerStyles = StyleSheet.create({ + inset: { paddingHorizontal: spacing.lg, paddingBottom: spacing.sm } +}) diff --git a/mobile/src/tasks/mobile-tasks-list-surface.tsx b/mobile/src/tasks/mobile-tasks-list-surface.tsx index 7bb705711b9..866cd6bf557 100644 --- a/mobile/src/tasks/mobile-tasks-list-surface.tsx +++ b/mobile/src/tasks/mobile-tasks-list-surface.tsx @@ -24,10 +24,14 @@ export function renderMobileTasksListSurface( setLinearConnectError, setLinearConnectState, setShowLinearConnect, + showsKeptRows, taskUiReady, tasksSupported } = model - return !tasksSupported ? ( + // Kept rows are drawn as they were, ahead of connection prompts that a dropped connection resets. + return showsKeptRows ? ( + renderMobileTasksNonProjectLists(model, colorScheme, bottomBarHeight) + ) : !tasksSupported ? ( renderMobileTasksSupportState(model, bottomBarHeight) ) : provider === 'jira' && !jiraConnection.connected ? ( ({ - family: 'tasks.hydration', + ...taskHydrationStorage, // Keep raw Promise.all fail-fast behavior; an all-settled interpretation barrier would wait and could change error precedence. fetch: async (client) => { const [settingsReply, uiReply, preflightReply, linearReply] = await Promise.all([ @@ -72,7 +71,7 @@ export const taskHydrationQuery = defineHostQuery({ - family: 'tasks.jiraStatus', + ...taskJiraStatusStorage, fetch: (client) => jiraConnectionStatusProbe .request(client) @@ -82,17 +81,18 @@ export const taskJiraStatusQuery = defineHostQuery({ - family: 'tasks.list', + ...taskListStorage, gcTime: 10 * 60_000, retry: false }) @@ -230,91 +230,3 @@ export function taskListParams(input: TaskListInput, repoKey: string): HostQuery : null } } - -export function taskListKey(hostId: string, params: HostQueryParams): HostQueryKey { - return hostQueryKey(hostId, taskListQuery.family, TASKS_TARGET, params) -} - -type TaskListView = Pick< - ProviderLoadActionsModel, - | 'hostId' - | 'items' - | 'setError' - | 'setItems' - | 'setGithubPages' - | 'setGithubCurrentPage' - | 'setGithubRepoSources' - | 'setGithubSourceErrors' - | 'setGithubSourceFallbacks' - | 'setGithubCountedTotalPages' - | 'setLoading' - | 'setTaskListSettled' -> - -/** The lists each filter read last, and which of them a read in flight is standing on. */ -export function useTaskListCache(view: TaskListView) { - const queryClient = useQueryClient() - const { hostId } = view - // Set while kept rows stand in for a read in flight; drives the header's refresh line, not the list spinner. - const [revalidating, setRevalidating] = useState(false) - // The provider whose rows are on screen, so a provider switch never keeps another provider's rows. - const shownProviderRef = useRef(null) - const shownRowsRef = useRef(view.items) - useLayoutEffect(() => { - shownRowsRef.current = view.items - }, [view.items]) - - // Stops a replaced or abandoned read before its next repo; the kept rows stay as they were. - const cancelRead = useCallback((): void => { - void queryClient.cancelQueries( - { queryKey: [...hostScopeKey(hostId), taskListQuery.family], fetchStatus: 'fetching' }, - { silent: true } - ) - }, [hostId, queryClient]) - - // A read of `key` starts on that filter's kept rows, else on the same provider's rows still shown, else the spinner. - const begin = useCallback( - (key: HostQueryKey | null, provider: string): void => { - cancelRead() - const kept = key ? queryClient.getQueryData(key) : undefined - if (kept) { - shownProviderRef.current = provider - view.setItems(kept.items) - view.setError(kept.notice ?? '') - if (kept.github) { - const { sources } = kept.github - view.setGithubRepoSources((current) => ({ ...current, ...sources })) - view.setGithubPages([kept.items]) - view.setGithubCurrentPage(0) - view.setGithubSourceErrors(kept.github.sourceErrors) - view.setGithubSourceFallbacks(kept.github.sourceFallbacks) - view.setGithubCountedTotalPages(kept.github.countedTotalPages) - } - view.setTaskListSettled(true) - setRevalidating(true) - } else if (shownRowsRef.current.length > 0 && shownProviderRef.current === provider) { - setRevalidating(true) - } else { - view.setLoading(true) - } - }, - [cancelRead, queryClient] - ) - const shown = useCallback((provider: string): void => { - shownProviderRef.current = provider - }, []) - // The GitHub page count lands after the rows; keep it with them. - const rememberPageCount = useCallback( - (key: HostQueryKey | null, countedTotalPages: number): void => { - if (key) { - queryClient.setQueryData( - key, - (snapshot) => - snapshot?.github && { ...snapshot, github: { ...snapshot.github, countedTotalPages } } - ) - } - }, - [queryClient] - ) - return { revalidating, setRevalidating, begin, shown, cancelRead, rememberPageCount } -} diff --git a/mobile/src/tasks/task-query-storage.test.tsx b/mobile/src/tasks/task-query-storage.test.tsx new file mode 100644 index 00000000000..38096465db4 --- /dev/null +++ b/mobile/src/tasks/task-query-storage.test.tsx @@ -0,0 +1,177 @@ +import { createElement, type Dispatch, type SetStateAction } from 'react' +import { QueryClient, QueryClientProvider, notifyManager } from '@tanstack/react-query' +import { act, create } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { OrcaQueryStoreBackend } from '../device-store/query-storage' +import { hostQueryKey } from '../query/host-query-key' +import { createHostQueryPersistence } from '../query/host-query-persistence' +import type { TaskItem } from './mobile-tasks-project-workspace-types' +import { readKeptTaskHydration } from './task-queries' +import { useTaskListCache } from './use-task-list-cache' +import { + firstPaintTaskKeys, + NO_TASK_INPUT, + TASKS_TARGET, + taskHydrationStorage, + taskLastListKey, + taskLastListStorage, + taskListKey, + taskListStorage +} from './task-query-storage' + +vi.mock('react-native', () => ({ AppState: {} })) +notifyManager.setScheduler(queueMicrotask) + +const HOST = 'host-a' +const SAVED_AT = 1_794_000_000_000 +const params = { provider: 'linear', workspace: 'ws-1', teams: 'team-1', filter: 'assigned' } +const storedRow = { + key: 'linear:STA-12', + provider: 'linear', + title: 'Keep task lists between launches', + subtitle: 'STA-12', + status: 'In Progress', + updatedAt: '2026-11-07T10:00:00.000Z', + source: { id: 'issue-12', identifier: 'STA-12', title: 'Keep task lists between launches' } +} + +function memoryStore(hostId: string) { + const rows = new Map() + const backend: OrcaQueryStoreBackend = { + hostId, + read: async (keys) => ({ + 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 } +} + +// What one document leaves on disk for the next: each value as its read landed, then flushed. +async function storeFromEarlierLaunch( + store: ReturnType, + records: { queryKey: readonly unknown[]; persist: unknown; data: unknown }[] +) { + const earlier = new QueryClient() + const persistence = createHostQueryPersistence(earlier, store.backend) + for (const { queryKey, persist, data } of records) { + earlier.getQueryCache().build(earlier, { queryKey, meta: { persist } }) + earlier.setQueryData(queryKey, data, { updatedAt: SAVED_AT }) + } + await vi.runAllTimersAsync() + await persistence.flush() +} + +async function relaunch(store: ReturnType) { + const relaunched = new QueryClient() + const persistence = createHostQueryPersistence(relaunched, store.backend) + const restoring = persistence.restore(firstPaintTaskKeys(HOST)) + await vi.runAllTimersAsync() + await restoring + return relaunched +} + +describe('Tasks lists kept on the phone', () => { + beforeEach(() => { + vi.useFakeTimers({ now: SAVED_AT + 60_000 }) + }) + afterEach(() => { + vi.useRealTimers() + }) + + it('draws the list a provider showed at the last launch before Tasks is ready, rows only', async () => { + const store = memoryStore(HOST) + await storeFromEarlierLaunch(store, [ + { + queryKey: taskLastListKey(HOST, 'linear'), + persist: taskLastListStorage.persist, + data: params + }, + { + queryKey: taskListKey(HOST, params), + persist: taskListStorage.persist, + data: { items: [storedRow] } + } + ]) + const relaunched = await relaunch(store) + + const setItems = vi.fn>>() + const setError = vi.fn() + const shown: { rowsReadAt?: number | null } = {} + function Probe() { + shown.rowsReadAt = useTaskListCache({ + hostId: HOST, + items: [], + jiraConnection: { + connected: false, + sites: [], + selection: null, + credentialError: null, + unavailableReason: null + }, + provider: 'linear', + taskUiReady: false, + setItems, + setError, + setGithubPages: vi.fn(), + setGithubCurrentPage: vi.fn(), + setGithubRepoSources: vi.fn(), + setGithubSourceErrors: vi.fn(), + setGithubSourceFallbacks: vi.fn(), + setGithubCountedTotalPages: vi.fn(), + setLoading: vi.fn(), + setTaskListSettled: vi.fn() + }).rowsReadAt + return null + } + await act(async () => { + create(createElement(QueryClientProvider, { client: relaunched }, createElement(Probe))) + await vi.runAllTimersAsync() + }) + + expect(setItems).toHaveBeenCalledWith([storedRow]) + expect(shown.rowsReadAt).toBe(SAVED_AT) + // A failed first read's error stays up over the stored rows. + expect(setError).not.toHaveBeenCalled() + }) + + it('keeps agent launch commands and hook trust out of the stored hydration', async () => { + const store = memoryStore(HOST) + await storeFromEarlierLaunch(store, [ + { + queryKey: hostQueryKey(HOST, taskHydrationStorage.family, TASKS_TARGET, NO_TASK_INPUT), + persist: taskHydrationStorage.persist, + data: { + settings: { + visibleTaskProviders: ['github', 'linear'], + agentCmdOverrides: { claude: 'ANTHROPIC_API_KEY=sk-ant-secret claude' } + }, + ui: { + taskResumeState: { linearPreset: 'assigned' }, + trustedOrcaHooks: { 'repo-1': { setup: 'hash-trusted' } } + }, + glabInstalled: false, + linearConnected: true + } + } + ]) + const kept = readKeptTaskHydration(await relaunch(store), HOST) + expect(kept.stored).toBe(true) + expect(kept.hydration).toEqual({ + settings: { visibleTaskProviders: ['github', 'linear'] }, + ui: { taskResumeState: { linearPreset: 'assigned' } }, + glabInstalled: false, + linearConnected: true + }) + }) +}) diff --git a/mobile/src/tasks/task-query-storage.ts b/mobile/src/tasks/task-query-storage.ts new file mode 100644 index 00000000000..2979e6a0911 --- /dev/null +++ b/mobile/src/tasks/task-query-storage.ts @@ -0,0 +1,144 @@ +import * as z from 'zod' +import { hostQueryKey, type HostQueryParams, type HostQueryTarget } from '../query/host-query-key' +import { + persistedHostQueryKey, + type PersistedHostFamily, + type PersistedHostQueryKey +} from '../query/host-query-persistence' +import type { MobileJiraConnection } from './jira-mobile-connection' +import type { TaskHydration, TaskListSnapshot } from './task-queries' + +// Kept apart from task-queries so the page's first-paint keys don't pull the Tasks reads into boot. + +// Tasks reads span the desktop and the servers it relays to; the routed client sends each repo's read to its owner. +export const TASKS_TARGET: HostQueryTarget = { exec: 'local' } +export const NO_TASK_INPUT = {} + +const TASK_PROVIDERS = ['github', 'gitlab', 'linear', 'jira'] as const + +// Only what draws the screen's view: agent launch settings and hook trust stay off disk, and a +// stored copy is never acted on (the screen waits for a live read before Tasks is ready). +const VIEW_SETTING_KEYS = [ + 'defaultTaskSource', + 'defaultTaskViewPreset', + 'visibleTaskProviders', + 'defaultRepoSelection', + 'defaultLinearTeamSelection', + 'githubProjects' +] as const + +const storedHydrationSchema = z.object({ + settings: z.looseObject({}), + ui: z.object({ taskResumeState: z.looseObject({}).optional() }).nullable(), + glabInstalled: z.boolean(), + linearConnected: z.boolean() +}) + +export const taskHydrationStorage: PersistedHostFamily = { + family: 'tasks.hydration', + persist: { + version: 1, + dataSchema: z.custom((data) => storedHydrationSchema.safeParse(data).success), + strip: (hydration) => ({ + settings: Object.fromEntries( + VIEW_SETTING_KEYS.flatMap((key) => + hydration.settings[key] === undefined ? [] : [[key, hydration.settings[key]]] + ) + ), + ui: hydration.ui && { taskResumeState: hydration.ui.taskResumeState }, + glabInstalled: hydration.glabInstalled, + linearConnected: hydration.linearConnected + }) + } +} + +const storedJiraSchema = z.looseObject({ + connected: z.boolean(), + sites: z.array(z.looseObject({})), + selection: z.string().nullable() +}) + +export const taskJiraStatusStorage: PersistedHostFamily = { + family: 'tasks.jiraStatus', + persist: { + version: 1, + dataSchema: z.custom((data) => storedJiraSchema.safeParse(data).success) + } +} + +const storedTaskItemSchema = z.looseObject({ + key: z.string(), + provider: z.enum(['github', 'gitlab', 'gitlabTodo', 'linear', 'jira']), + title: z.string(), + subtitle: z.string(), + status: z.string(), + updatedAt: z.string(), + source: z.looseObject({}) +}) +const storedTaskListSchema = z.object({ + items: z.array(storedTaskItemSchema), + github: z + .object({ + sources: z.record(z.string(), z.looseObject({})), + sourceErrors: z.array(z.unknown()), + sourceFallbacks: z.array(z.unknown()), + countedTotalPages: z.number().nullable() + }) + .optional() +}) + +export const taskListStorage: PersistedHostFamily = { + family: 'tasks.list', + persist: { + version: 1, + dataSchema: z.custom((data) => storedTaskListSchema.safeParse(data).success), + // A read's warnings describe that read; a later launch shows its rows without them. + strip: (snapshot) => + snapshot.github + ? { + items: snapshot.items, + github: { ...snapshot.github, sourceErrors: [], sourceFallbacks: [] } + } + : { items: snapshot.items } + } +} + +/** Per provider, the inputs of the list it showed last, so the next launch knows which stored list to draw. */ +export const taskLastListStorage: PersistedHostFamily = { + family: 'tasks.lastList', + persist: { + version: 1, + dataSchema: z.custom( + (params) => + z + .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])) + .safeParse(params).success + ) + } +} + +export function taskLastListKey(hostId: string, provider: string) { + return hostQueryKey(hostId, taskLastListStorage.family, TASKS_TARGET, { provider }) +} + +export function taskListKey(hostId: string, params: HostQueryParams) { + return hostQueryKey(hostId, taskListStorage.family, TASKS_TARGET, params) +} + +/** What the Tasks screen draws before its first read: the view, Jira's status and which list each provider showed. */ +export function firstPaintTaskKeys(hostId: string): PersistedHostQueryKey[] { + const keys = [ + persistedHostQueryKey( + taskHydrationStorage, + hostQueryKey(hostId, taskHydrationStorage.family, TASKS_TARGET, NO_TASK_INPUT) + ), + persistedHostQueryKey( + taskJiraStatusStorage, + hostQueryKey(hostId, taskJiraStatusStorage.family, TASKS_TARGET, NO_TASK_INPUT) + ), + ...TASK_PROVIDERS.map((provider) => + persistedHostQueryKey(taskLastListStorage, taskLastListKey(hostId, provider)) + ) + ] + return keys.filter((key) => key !== null) +} diff --git a/mobile/src/tasks/use-mobile-tasks-connection-presentation.tsx b/mobile/src/tasks/use-mobile-tasks-connection-presentation.tsx index 3774718e3a5..c5f1dc5a86f 100644 --- a/mobile/src/tasks/use-mobile-tasks-connection-presentation.tsx +++ b/mobile/src/tasks/use-mobile-tasks-connection-presentation.tsx @@ -40,12 +40,21 @@ export function useMobileTasksConnectionPresentation(model: ProviderViewProjecti // Until the first read settles, an empty list is unread, not empty: keep the spinner up. const loading = model.loading || (connState === 'connected' && !model.taskListSettled && !model.error) + // Before Tasks is ready (connecting, offline, or waiting on its first read), the last list stays up, read-only. + // A failed first read on a live connection shows its error and Retry instead. + const showsKeptRows = + !model.tasksSupported && + !model.tasksUnsupported && + !isGithubProjectSearch && + !(connState === 'connected' && model.error) && + model.items.length > 0 return Object.assign(model, { headerVerdict, emptyLabel, hasSearch, isGithubProjectSearch, - loading + loading, + showsKeptRows }) } diff --git a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx index fd865fd72d2..7f92f4c8e35 100644 --- a/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx +++ b/mobile/src/tasks/use-mobile-tasks-runtime-hydration.tsx @@ -1,8 +1,10 @@ import { replaceEqualDeep, useQueryClient } from '@tanstack/react-query' +import { restoreStoredHostQueries } from '../query/host-query-persistence' import { connectionHostStatus } from '../query/host-status-query' import type { ClientSettingsActionsModel } from './use-mobile-tasks-client-settings-actions' import { resolveHydratedTaskViewState } from './mobile-tasks-hydrated-view-state' import { taskRuntimeStatusRead } from './mobile-task-runtime-operations' +import { firstPaintTaskKeys } from './task-query-storage' import { readKeptTaskHydration, readTaskHydration, @@ -16,7 +18,7 @@ import { normalizeVisibleTaskProviders, resolveVisibleTaskProvider } from '../../../src/shared/work-items/task-providers' -import { useState } from 'react' +import { useRef, useState } from 'react' import { translate } from '../i18n/mobile-i18n' import { EMPTY_GITHUB_PROJECT_SETTINGS } from './mobile-tasks-legacy-foundation' @@ -94,9 +96,91 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel const queryClient = useQueryClient() // Bumped by Retry after a failed hydration, which leaves support unknown. const [hydrationAttempt, setHydrationAttempt] = useState(0) + // Set once this screen has drawn a view, so a dropped connection keeps what the user has on screen. + const viewShownRef = useRef(false) + // What the screen draws: source, filters and query. Safe from a stored copy, which nothing acts on. + function applyView(hydration: TaskHydration): void { + viewShownRef.current = true + const { settings } = hydration + const resume = hydration.ui?.taskResumeState ?? {} + setGithubProjectHiddenFieldIdsByView(resume.githubProjectHiddenFieldIdsByView ?? {}) + + const preferredProviders = normalizeVisibleTaskProviders(settings.visibleTaskProviders) + const linearIsConnected = hydration.linearConnected + const availableProviders = filterAvailableTaskProviders(preferredProviders, { + gitlabInstalled: hydration.glabInstalled, + linearConnected: linearIsConnected + }) + const nextVisibleProviders = + preferredProviders.includes('linear') && !availableProviders.includes('linear') + ? [...availableProviders, 'linear' as const] + : availableProviders + setLinearConnected(linearIsConnected) + if (!linearIsConnected) { + setLinearWorkspaces([]) + setLinearTeams([]) + setSelectedLinearTeamIds(new Set()) + setSelectedLinearWorkspaceId(null) + } + setSelectedRepoIds(new Set(settings.defaultRepoSelection ?? [])) + defaultLinearTeamSelectionRef.current = settings.defaultLinearTeamSelection ?? null + const view = resolveHydratedTaskViewState({ + settings, + resume, + requestedTaskSource, + visibleProviders: nextVisibleProviders + }) + + setVisibleProviders(nextVisibleProviders) + setProvider(view.provider) + setGithubMode(resume.githubMode === 'project' ? 'project' : 'items') + setDefaultGitHubPreset(view.defaultGithubPreset) + setGithubPreset(view.githubPreset) + setGithubKind(view.githubKind) + setLinearFilter(view.linearFilter) + setJiraFilter(view.jiraFilter) + setGithubProjectSettings(settings.githubProjects ?? EMPTY_GITHUB_PROJECT_SETTINGS) + setQuery(view.query) + setAppliedQuery(view.appliedQuery) + } + + // Until Tasks is ready the screen keeps the view it last had, from this document or an earlier launch. + function applyKeptView(kept: ReturnType): void { + if (kept.hydration && !viewShownRef.current) { + if (kept.jira) { + setJiraConnection(kept.jira) + } + applyView(kept.hydration) + } + } + + // A screen opened in a document that booted on another route reads its stored view now. + useEffect(() => { + let stale = false + void restoreStoredHostQueries(queryClient, firstPaintTaskKeys(hostId)) + .catch(() => {}) + .then(() => { + if (!stale) { + applyKeptView(readKeptTaskHydration(queryClient, hostId)) + } + }) + return () => { + stale = true + } + }, [hostId, queryClient]) + // Open items, the create sheet and the workspace form outlive reconnects so typed drafts survive; their drawers hide until Tasks is ready again. // A layout effect, so a revisit opens on the kept hydration before the first frame. useLayoutEffect(() => { + // A read from this document: Tasks acts on it (launch settings, hook trust, resume writes). + function applyHydration(hydration: TaskHydration): void { + setRuntimeTaskSettings(hydration.settings) + setTrustedOrcaHooks(hydration.ui?.trustedOrcaHooks ?? {}) + taskResumeRef.current = hydration.ui?.taskResumeState ?? {} + applyView(hydration) + setTaskStateHydrated(true) + } + if (!client || connState !== 'connected') { taskResumeRef.current = {} setRuntimeTaskSettings({}) @@ -132,6 +216,7 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel setPendingHostedStateChange(null) setMergeMethodTaskItem(null) setMergeMethodProjectRow(null) + applyKeptView(readKeptTaskHydration(queryClient, hostId)) return } @@ -172,6 +257,7 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel let applied: TaskHydration | undefined if ( kept.hydration && + !kept.stored && landed && taskRuntimeStatusRead.interpret(landed.reply).capabilities?.includes(MOBILE_TASKS_CAPABILITY) ) { @@ -181,6 +267,8 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel } applyHydration(kept.hydration) applied = kept.hydration + } else { + applyKeptView(kept) } const hydrateTaskState = async (): Promise => { @@ -258,55 +346,6 @@ export function useMobileTasksRuntimeHydration(model: ClientSettingsActionsModel applyHydration(fresh) } - function applyHydration(hydration: TaskHydration): void { - const { settings } = hydration - setRuntimeTaskSettings(settings) - const uiState = hydration.ui - setTrustedOrcaHooks(uiState?.trustedOrcaHooks ?? {}) - const resume = uiState?.taskResumeState ?? {} - taskResumeRef.current = resume - setGithubProjectHiddenFieldIdsByView(resume.githubProjectHiddenFieldIdsByView ?? {}) - - const preferredProviders = normalizeVisibleTaskProviders(settings.visibleTaskProviders) - const linearIsConnected = hydration.linearConnected - const availableProviders = filterAvailableTaskProviders(preferredProviders, { - gitlabInstalled: hydration.glabInstalled, - linearConnected: linearIsConnected - }) - const nextVisibleProviders = - preferredProviders.includes('linear') && !availableProviders.includes('linear') - ? [...availableProviders, 'linear' as const] - : availableProviders - setLinearConnected(linearIsConnected) - if (!linearIsConnected) { - setLinearWorkspaces([]) - setLinearTeams([]) - setSelectedLinearTeamIds(new Set()) - setSelectedLinearWorkspaceId(null) - } - setSelectedRepoIds(new Set(settings.defaultRepoSelection ?? [])) - defaultLinearTeamSelectionRef.current = settings.defaultLinearTeamSelection ?? null - const view = resolveHydratedTaskViewState({ - settings, - resume, - requestedTaskSource, - visibleProviders: nextVisibleProviders - }) - - setVisibleProviders(nextVisibleProviders) - setProvider(view.provider) - setGithubMode(resume.githubMode === 'project' ? 'project' : 'items') - setDefaultGitHubPreset(view.defaultGithubPreset) - setGithubPreset(view.githubPreset) - setGithubKind(view.githubKind) - setLinearFilter(view.linearFilter) - setJiraFilter(view.jiraFilter) - setGithubProjectSettings(settings.githubProjects ?? EMPTY_GITHUB_PROJECT_SETTINGS) - setQuery(view.query) - setAppliedQuery(view.appliedQuery) - setTaskStateHydrated(true) - } - void hydrateTaskState().catch((err) => { if (stale) { return diff --git a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx index cbe77f8724f..02d4fed927b 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-list-loading.tsx @@ -9,7 +9,8 @@ import { useRef } from './mobile-tasks-dependencies' import { readTaskListRows } from './task-list-read' -import { readTaskList, taskListKey, taskListParams, useTaskListCache } from './task-queries' +import { readTaskList, taskListKey, taskListParams } from './task-queries' +import { useTaskListCache } from './use-task-list-cache' export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { const { @@ -54,7 +55,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { } = model const queryClient = useQueryClient() const unsettledLoadRef = useRef(0) - const { begin, shown, rememberPageCount, cancelRead, revalidating, setRevalidating } = + const { begin, shown, settle, rememberPageCount, cancelRead, revalidating, rowsReadAt } = useTaskListCache(model) // By content, so re-picking the same repos (a new Set) does not re-read. const savedRepoKey = [...selectedRepoIds].sort().join('\n') @@ -76,7 +77,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { if (options.silent) { setRefreshing(true) } else { - begin(listKey, provider) + begin(params, provider) } try { if (provider !== 'github' || githubMode !== 'items') { @@ -109,7 +110,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { if (!isCurrent()) { return } - shown(provider) + shown(provider, params) setItems(snapshot.items) setError(snapshot.notice ?? '') if (snapshot.github) { @@ -150,7 +151,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { if (isCurrent()) { setLoading(false) setRefreshing(false) - setRevalidating(false) + settle() setTaskListSettled(true) } } @@ -174,6 +175,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { begin, queryClient, rememberPageCount, + settle, shown, repoListEnsureLoaded, provider, @@ -215,10 +217,10 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { unsettledLoadRef.current = 0 setLoading(false) setRefreshing(false) - setRevalidating(false) + settle() } }, - [cancelRead, loadTasks, loadGenerationRef, setLoading, setRefreshing] + [cancelRead, loadTasks, loadGenerationRef, setLoading, setRefreshing, settle] ) // Server-repo changes quietly reload unfiltered lists; a changed loadTasks already owns filter reloads, while Jira/Linear read independently. const listedServerReposRef = useRef({ serverRepoList, loadTasks }) @@ -236,7 +238,7 @@ export function useMobileTasksTaskListLoading(model: ProviderLoadActionsModel) { void loadTasks({ silent: true }) } }, [serverRepoList, loadTasks, effectiveRepoIds.size, provider, connState, taskStateHydrated]) - return Object.assign(model, { loadTasks, captureTaskListRefresh, revalidating }) + return Object.assign(model, { loadTasks, captureTaskListRefresh, revalidating, rowsReadAt }) } export type TaskListLoadingModel = ReturnType diff --git a/mobile/src/tasks/use-task-list-cache.ts b/mobile/src/tasks/use-task-list-cache.ts new file mode 100644 index 00000000000..18a8dd3b3a9 --- /dev/null +++ b/mobile/src/tasks/use-task-list-cache.ts @@ -0,0 +1,191 @@ +import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query' +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { type HostQueryKey, type HostQueryParams, hostScopeKey } from '../query/host-query-key' +import { persistedHostQueryKey, restoreStoredHostQueries } from '../query/host-query-persistence' +import { taskListQuery, type TaskListSnapshot } from './task-queries' +import { + taskLastListKey, + taskLastListStorage, + taskListKey, + taskListStorage +} from './task-query-storage' +import type { ProviderLoadActionsModel } from './use-mobile-tasks-provider-load-actions' + +type TaskListView = Pick< + ProviderLoadActionsModel, + | 'hostId' + | 'items' + | 'jiraConnection' + | 'provider' + | 'setError' + | 'setItems' + | 'setGithubPages' + | 'setGithubCurrentPage' + | 'setGithubRepoSources' + | 'setGithubSourceErrors' + | 'setGithubSourceFallbacks' + | 'setGithubCountedTotalPages' + | 'setLoading' + | 'setTaskListSettled' + | 'taskUiReady' +> + +// Drawn by the screen, never fetched; the meta makes the write-behind keep it. +const LAST_LIST_META = { streamBacked: true, persist: taskLastListStorage.persist } + +/** The lists each filter read last, and which of them a read in flight is standing on. */ +export function useTaskListCache(view: TaskListView) { + const queryClient = useQueryClient() + const { hostId, provider, taskUiReady } = view + const jiraSelection = view.jiraConnection.selection + // Set while kept rows stand in for a read in flight; drives the header's refresh line, not the list spinner. + const [revalidating, setRevalidating] = useState(false) + // When the rows on screen were read from the host, possibly at an earlier launch. + const [rowsReadAt, setRowsReadAt] = useState(null) + // The provider whose rows are on screen, so a provider switch never keeps another provider's rows. + const shownProviderRef = useRef(null) + const shownRowsRef = useRef(view.items) + useLayoutEffect(() => { + shownRowsRef.current = view.items + }, [view.items]) + // The stored list a read or the not-yet-ready screen is waiting on; any later begin or settle drops it. + const awaitingStoredRef = useRef(null) + const { data: lastList } = useQuery({ + queryKey: taskLastListKey(hostId, provider), + queryFn: skipToken, + meta: LAST_LIST_META + }) + + // The list's notice and the refresh line belong to a read; the not-ready screen has none out, so draws rows only. + const paintRows = useCallback( + (key: HostQueryKey, kept: TaskListSnapshot, provider: string, underRead: boolean): void => { + shownProviderRef.current = provider + setRowsReadAt(queryClient.getQueryState(key)?.dataUpdatedAt || null) + view.setItems(kept.items) + if (underRead) { + view.setError(kept.notice ?? '') + } + if (kept.github) { + const { sources } = kept.github + view.setGithubRepoSources((current) => ({ ...current, ...sources })) + view.setGithubPages([kept.items]) + view.setGithubCurrentPage(0) + view.setGithubSourceErrors(kept.github.sourceErrors) + view.setGithubSourceFallbacks(kept.github.sourceFallbacks) + view.setGithubCountedTotalPages(kept.github.countedTotalPages) + } + view.setTaskListSettled(true) + if (underRead) { + setRevalidating(true) + } + }, + [queryClient] + ) + + // Calls `paint` with a list an earlier launch stored once the phone's store answers, unless something else landed first. + const whenStored = useCallback( + (key: HostQueryKey, paint: (snapshot: TaskListSnapshot) => void): object => { + const awaiting = {} + awaitingStoredRef.current = awaiting + const stored = persistedHostQueryKey(taskListStorage, key) + void restoreStoredHostQueries(queryClient, stored ? [stored] : []) + .catch(() => {}) + .then(() => { + const snapshot = queryClient.getQueryData(key) + if (awaitingStoredRef.current === awaiting && snapshot) { + awaitingStoredRef.current = null + paint(snapshot) + } + }) + return awaiting + }, + [queryClient] + ) + + // Until Tasks is ready (connecting, offline, or waiting on its first read), the screen shows the list it showed last. + useEffect(() => { + // A Jira list is one site's; the site chip comes from the Jira status, which a pick on the phone doesn't change. + const jiraSiteShown = lastList?.provider !== 'jira' || lastList.site === (jiraSelection ?? null) + if (taskUiReady || !lastList || !jiraSiteShown) { + return + } + const key = taskListKey(hostId, lastList) + const awaiting = whenStored(key, (snapshot) => { + // Rows this document read stay; another provider's rows give way. + if (shownRowsRef.current.length === 0 || shownProviderRef.current !== provider) { + paintRows(key, snapshot, provider, false) + } + }) + // A provider or host this screen has left no longer wants that list. + return () => { + if (awaitingStoredRef.current === awaiting) { + awaitingStoredRef.current = null + } + } + }, [hostId, jiraSelection, lastList, paintRows, provider, taskUiReady, whenStored]) + + // Stops a replaced or abandoned read before its next repo; the kept rows stay as they were. + const cancelRead = useCallback((): void => { + void queryClient.cancelQueries( + { queryKey: [...hostScopeKey(hostId), taskListQuery.family], fetchStatus: 'fetching' }, + { silent: true } + ) + }, [hostId, queryClient]) + + // A read of a list starts on that filter's kept rows, else on the same provider's rows still shown, else the + // spinner; it is also the list this provider opens on next launch. + const begin = useCallback( + (params: HostQueryParams | null, provider: string): void => { + cancelRead() + awaitingStoredRef.current = null + const key = params && taskListKey(hostId, params) + if (params) { + queryClient.setQueryData(taskLastListKey(hostId, provider), params) + } + const kept = key ? queryClient.getQueryData(key) : undefined + if (kept && key) { + paintRows(key, kept, provider, true) + return + } + if (shownRowsRef.current.length > 0 && shownProviderRef.current === provider) { + setRevalidating(true) + } else { + view.setLoading(true) + } + if (key) { + whenStored(key, (snapshot) => { + view.setLoading(false) + paintRows(key, snapshot, provider, true) + }) + } + }, + [cancelRead, hostId, paintRows, queryClient, whenStored] + ) + // A read landed and its rows are on screen. + const shown = useCallback( + (provider: string, params: HostQueryParams): void => { + awaitingStoredRef.current = null + shownProviderRef.current = provider + setRowsReadAt(queryClient.getQueryState(taskListKey(hostId, params))?.dataUpdatedAt || null) + }, + [hostId, queryClient] + ) + const settle = useCallback((): void => { + awaitingStoredRef.current = null + setRevalidating(false) + }, []) + // The GitHub page count lands after the rows; keep it with them. + const rememberPageCount = useCallback( + (key: HostQueryKey | null, countedTotalPages: number): void => { + if (key) { + queryClient.setQueryData( + key, + (snapshot) => + snapshot?.github && { ...snapshot, github: { ...snapshot.github, countedTotalPages } } + ) + } + }, + [queryClient] + ) + return { revalidating, rowsReadAt, begin, shown, settle, cancelRead, rememberPageCount } +} diff --git a/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts index 6848badb046..d828e708197 100644 --- a/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts @@ -147,6 +147,7 @@ export function taskListMountAdapters( serverRepoList: [], taskStateHydrated: true, tasksSupported: true, + taskUiReady: true, items: [], error: '', loading: false, diff --git a/mobile/src/transport/connection/client-context.test.ts b/mobile/src/transport/connection/client-context.test.ts index 448bd9e1ac5..d0faf1fb4b1 100644 --- a/mobile/src/transport/connection/client-context.test.ts +++ b/mobile/src/transport/connection/client-context.test.ts @@ -227,48 +227,6 @@ describe('useHostClient', () => { harness.unmount() }) - it('reports disconnected instead of hanging when the host id is unknown', async () => { - loadHostsMock.mockResolvedValue([]) - - const harness = await renderHarness('missing-host') - expect(connectMock).not.toHaveBeenCalled() - expect(harness.hook.client).toBeNull() - expect(harness.hook.state).toBe('disconnected') - - harness.unmount() - }) - - it('seeds connecting during the async open instead of flashing disconnected', async () => { - let resolveHosts: ((hosts: (typeof HOST)[]) => void) | null = null - const hostLookup = new Promise<(typeof HOST)[]>((resolve) => { - resolveHosts = resolve - }) - connectMock.mockReturnValue(makeFakeClient('connecting')) - loadHostsMock.mockReturnValue(hostLookup) - - const states: ConnectionState[] = [] - let renderer: ReactTestRenderer | null = null - function Probe(): null { - states.push(useHostClient(HOST.id).state) - return null - } - try { - act(() => { - renderer = create(createElement(RpcClientProvider, null, createElement(Probe))) - }) - expect(states.at(-1)).toBe('connecting') - - await act(async () => { - resolveHosts?.([HOST]) - await hostLookup - }) - expect(states.at(-1)).toBe('connecting') - expect(states).not.toContain('disconnected') - } finally { - act(() => renderer?.unmount()) - } - }) - it('keeps Retry amber through forceReconnect instead of grey-then-amber', async () => { const first = makeFakeClient('connected') const second = makeFakeClient('connecting') diff --git a/mobile/src/transport/connection/host-open-retry-scheduler.test.ts b/mobile/src/transport/connection/host-open-retry-scheduler.test.ts deleted file mode 100644 index 650bd62b92d..00000000000 --- a/mobile/src/transport/connection/host-open-retry-scheduler.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { HostOpenRetryScheduler } from './host-open-retry-scheduler' - -describe('HostOpenRetryScheduler', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => { - vi.useRealTimers() - }) - - it('cancels retry delivery', async () => { - const open = vi.fn() - const scheduler = new HostOpenRetryScheduler({ canRetry: () => true, open }) - scheduler.recordFailure('host-1', 1) - scheduler.cancel('host-1') - - await vi.advanceTimersByTimeAsync(60_000) - expect(open).not.toHaveBeenCalled() - }) -}) 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/encryption/base64-byte-codec.test.ts b/mobile/src/transport/encryption/base64-byte-codec.test.ts deleted file mode 100644 index 0dd9b0a5634..00000000000 --- a/mobile/src/transport/encryption/base64-byte-codec.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { encodeBase64Bytes } from './base64-byte-codec' - -describe('base64 byte codec', () => { - it('keeps the fallback when the native property is not callable', () => { - const bytes = new Uint8Array([255, 254]) - Object.defineProperty(bytes, 'toBase64', { value: undefined }) - expect(encodeBase64Bytes(bytes)).toBe('//4=') - }) - - it('preserves empty encoding for a detached byte view', () => { - const bytes = new Uint8Array([1, 2, 3]) - structuredClone(bytes.buffer, { transfer: [bytes.buffer] }) - expect(encodeBase64Bytes(bytes)).toBe('') - }) -}) diff --git a/mobile/src/transport/encryption/e2ee-v2-host-latch.test.ts b/mobile/src/transport/encryption/e2ee-v2-host-latch.test.ts index 2a00b5b97d2..b29618b4de8 100644 --- a/mobile/src/transport/encryption/e2ee-v2-host-latch.test.ts +++ b/mobile/src/transport/encryption/e2ee-v2-host-latch.test.ts @@ -5,34 +5,18 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(), setItem: vi.fn() } })) -const channelArgs: { onAuthenticated: () => void }[] = [] const stored = new Map() -vi.mock('./mobile-e2ee-v2-client-session', () => ({ - MobileE2EEV2ClientSession: { create: () => ({}) } -})) -vi.mock('./mobile-e2ee-v2-physical-channel', () => ({ - MobileE2EEV2PhysicalChannel: class { - constructor(args: { onAuthenticated: () => void }) { - channelArgs.push(args) - } - start = vi.fn() - handleMessage = vi.fn(async () => {}) - dispose = vi.fn() - } -})) import { createDirectE2EEFramingPolicy } from './direct-e2ee-framing-policy' import { hydrateE2EEV2HostLatch, isHostLatchedToE2EEV2, - latchHostToE2EEV2, resetE2EEV2HostLatchForTests } from './e2ee-v2-host-latch' describe('E2EE v2 host latch', () => { beforeEach(() => { resetE2EEV2HostLatchForTests() - channelArgs.length = 0 stored.clear() vi.mocked(AsyncStorage.getItem) .mockReset() @@ -73,16 +57,4 @@ describe('E2EE v2 host latch', () => { expect(policy.framingForNextDial()).toBe('v2') expect(policy.helloRefusalIsAuthFailure()).toBe(true) }) - - it('ignores malformed persisted entries', async () => { - vi.mocked(AsyncStorage.getItem).mockResolvedValueOnce(JSON.stringify(['a', 7, '', null])) - await hydrateE2EEV2HostLatch() - expect(isHostLatchedToE2EEV2('a')).toBe(true) - expect(isHostLatchedToE2EEV2('')).toBe(false) - expect(isHostLatchedToE2EEV2('7')).toBe(false) - expect(isHostLatchedToE2EEV2('null')).toBe(false) - latchHostToE2EEV2('b') - await Promise.resolve() - expect(stored.get('orca:e2ee-v2-hosts')).toBe('["a","b"]') - }) }) diff --git a/mobile/src/transport/hosts/host-removal-lifecycle.web.test.ts b/mobile/src/transport/hosts/host-removal-lifecycle.web.test.ts deleted file mode 100644 index 55e4b164b79..00000000000 --- a/mobile/src/transport/hosts/host-removal-lifecycle.web.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { removeHostAndCloseClient } from './host-removal-lifecycle.web' -import { isPageHostRemovalUnavailable } from './page-host-removal-refusal' - -describe('removing a host from the page', () => { - it('refuses with a code the screen can branch on', async () => { - const error = await removeHostAndCloseClient('host-1', vi.fn()).catch( - (reason: unknown) => reason - ) - expect(isPageHostRemovalUnavailable(error)).toBe(true) - expect({ - name: error instanceof Error ? error.name : null, - code: isPageHostRemovalUnavailable(error) ? error.code : null - }).toEqual({ - name: 'PageHostRemovalUnavailableError', - code: 'page_host_removal_unavailable' - }) - }) -}) diff --git a/mobile/src/transport/hosts/host-store-endpoint.test.ts b/mobile/src/transport/hosts/host-store-endpoint.test.ts index d0dad415844..e84ad12e8e4 100644 --- a/mobile/src/transport/hosts/host-store-endpoint.test.ts +++ b/mobile/src/transport/hosts/host-store-endpoint.test.ts @@ -1,13 +1,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage' import * as SecureStore from 'expo-secure-store' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - loadHosts, - RelayRoutingHostRemovedError, - resetHostStoreForTests, - setRelayRouting, - updateHostNameAndEndpoint -} from './host-store' +import { loadHosts, resetHostStoreForTests, updateHostNameAndEndpoint } from './host-store' import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store' vi.mock('@react-native-async-storage/async-storage', () => ({ @@ -44,10 +38,6 @@ describe('relay routing after a host edit', () => { const storage = new Map() - function writesTo(key: string): unknown[] { - return vi.mocked(AsyncStorage.setItem).mock.calls.filter(([written]) => written === key) - } - beforeEach(() => { resetHostStoreForTests() resetMobileRelayHostOverlayStoreForTests() @@ -99,17 +89,4 @@ describe('relay routing after a host edit', () => { relay }) }) - - it('refuses to write routing for a removed host and leaves no overlay behind', async () => { - storage.set('orca:hosts', '[]') - storage.set(OVERLAY_KEY, '[]') - - await expect(setRelayRouting('host-1', relay)).rejects.toBeInstanceOf( - RelayRoutingHostRemovedError - ) - - expect(writesTo(OVERLAY_KEY)).toEqual([]) - expect(writesTo('orca:hosts')).toEqual([]) - await expect(loadHosts()).resolves.toEqual([]) - }) }) diff --git a/mobile/src/transport/hosts/host-store.test.ts b/mobile/src/transport/hosts/host-store.test.ts index 351b7c51fe3..e6218ba96e8 100644 --- a/mobile/src/transport/hosts/host-store.test.ts +++ b/mobile/src/transport/hosts/host-store.test.ts @@ -48,8 +48,7 @@ import { resetHostStoreForTests, savePairedHost, setRelayRouting, - updateHostNameAndEndpoint, - updateLastConnected + updateHostNameAndEndpoint } from './host-store' import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store' @@ -136,36 +135,6 @@ describe('host-store list mutations', () => { expect(profiles.map(({ id }) => id)).toEqual([HOST_TWO.id]) }) - it('keeps orphaned metadata visible when its credential is missing', async () => { - secureStoreMock.getItemAsync.mockImplementation(async (key: string) => - key.endsWith(HOST_TWO.id) ? 'token-2' : null - ) - - const catalog = await loadHostCatalog() - - expect(catalog.find(({ id }) => id === HOST_ONE.id)).toMatchObject({ - credentialStatus: 'missing', - profile: null - }) - }) - - it('keeps existing metadata when pairing a distinct host', async () => { - await savePairedHost({ - id: 'host-new', - name: 'Host 3', - endpoint: 'ws://127.0.0.1:3', - publicKeyB64: 'key-new', - deviceToken: 'token-new', - lastConnected: 0 - }) - - expect(JSON.parse(storedHostsRaw).map(({ id }: { id: string }) => id)).toEqual([ - HOST_ONE.id, - HOST_TWO.id, - 'host-new' - ]) - }) - it('fails closed when durable host identity storage is unreadable', async () => { asyncStorageMock.getItem.mockRejectedValueOnce(new Error('storage unavailable')) @@ -361,14 +330,6 @@ describe('host-store list mutations', () => { const hosts = await loadHosts() expect(hosts.find((host) => host.id === newHost.id)?.deviceToken).toBe(newHost.deviceToken) }) - - it('resolves instead of rejecting when updateLastConnected hits unreadable storage', async () => { - // Void callers cannot catch rejection; unreadable storage must leave this bookkeeping best-effort. - storedHostsRaw = '{' - await expect(updateLastConnected(HOST_ONE.id)).resolves.toBeUndefined() - expect(asyncStorageMock.setItem).not.toHaveBeenCalled() - expect(storedHostsRaw).toBe('{') - }) }) describe('host-store pairing save after an Android encryption rejection', () => { @@ -419,38 +380,6 @@ describe('host-store pairing save after an Android encryption rejection', () => secureStoreMock.getItemAsync.mockResolvedValue(null) }) - it('saves the host when the reported Android failure is alias-local (#6600)', async () => { - const written = new Map() - // Model the alias-local hypothesis; no affected physical device was available. - secureStoreMock.setItemAsync.mockImplementation( - async (_key: string, value: string, options?: { keychainService?: string }) => { - if (options?.keychainService === undefined) { - throw ENCRYPT_REJECTION - } - written.set(options.keychainService, value) - } - ) - - await expect(savePairedHost(NEW_HOST)).resolves.toBeUndefined() - - expect(written.get('orca.pairing.v1')).toBe('device-token') - expect(JSON.parse(storedHostsRaw)).toEqual([ - { - id: NEW_HOST.id, - name: NEW_HOST.name, - endpoint: NEW_HOST.endpoint, - publicKeyB64: NEW_HOST.publicKeyB64, - lastConnected: NEW_HOST.lastConnected - } - ]) - }) - - it('still surfaces the failure when no keystore alias can accept the token', async () => { - secureStoreMock.setItemAsync.mockRejectedValue(ENCRYPT_REJECTION) - - await expect(savePairedHost(NEW_HOST)).rejects.toBe(ENCRYPT_REJECTION) - }) - it('serves the rotated token to loadHosts so the saved host survives a relaunch', async () => { const written = new Map() secureStoreMock.setItemAsync.mockImplementation( diff --git a/mobile/src/transport/hosts/pairing-keychain.test.ts b/mobile/src/transport/hosts/pairing-keychain.test.ts index ed38ee8904c..1bc92703683 100644 --- a/mobile/src/transport/hosts/pairing-keychain.test.ts +++ b/mobile/src/transport/hosts/pairing-keychain.test.ts @@ -69,16 +69,4 @@ describe('pairing keychain', () => { expect(asyncStorageMock.setItem).not.toHaveBeenCalled() expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled() }) - - it.each(['not-a-number', '', ' ', '0:pending'])( - 'refuses to write from malformed generation record %j', - async (raw) => { - generationRecord = raw - - await expect(writePairingKeychainItem(TOKEN_KEY, 'token')).rejects.toThrow( - /generation record is invalid/ - ) - expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled() - } - ) }) diff --git a/mobile/src/transport/relay/mobile-direct-endpoint-probe.test.ts b/mobile/src/transport/relay/mobile-direct-endpoint-probe.test.ts deleted file mode 100644 index e50d1e0e1bc..00000000000 --- a/mobile/src/transport/relay/mobile-direct-endpoint-probe.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { directPathForEndpoint } from './mobile-direct-endpoint-probe' - -describe('mobile direct endpoint probe', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('classifies a tailnet endpoint apart from a LAN one', () => { - expect(directPathForEndpoint('ws://100.64.0.2:6768')).toBe('tailscale') - expect(directPathForEndpoint('wss://desk.tail1234.ts.net:6768')).toBe('tailscale') - expect(directPathForEndpoint('ws://[fd7a:115c:a1e0::1]:6768')).toBe('tailscale') - // 100.0.0.0/10 is not the tailnet's 100.64.0.0/10. - expect(directPathForEndpoint('ws://100.12.0.2:6768')).toBe('lan') - expect(directPathForEndpoint('ws://192.168.1.10:6768')).toBe('lan') - }) -}) diff --git a/mobile/src/transport/relay/mobile-relay-resume-director.test.ts b/mobile/src/transport/relay/mobile-relay-resume-director.test.ts index e43bdb5e20a..5eae841fb37 100644 --- a/mobile/src/transport/relay/mobile-relay-resume-director.test.ts +++ b/mobile/src/transport/relay/mobile-relay-resume-director.test.ts @@ -11,34 +11,6 @@ const relay = { } describe('mobile relay resume director', () => { - it('uses a bounded POST body and never puts the bearer in the URL', async () => { - const fetchImpl = vi.fn( - async (_url: string, _init: RequestInit) => - new Response( - JSON.stringify({ - v: 1, - cellUrl: 'https://relay-c2.onorca.dev', - assignmentEpoch: 8, - leaseExpiresAt: Date.now() + 60_000 - }), - { status: 200, headers: { 'content-type': 'application/json' } } - ) - ) - - await expect( - resolveMobileRelayEndpoint({ relay, resumeToken: 'A'.repeat(43), fetchImpl }) - ).resolves.toMatchObject({ cellUrl: 'https://relay-c2.onorca.dev', assignmentEpoch: 8 }) - const [url, init] = fetchImpl.mock.calls[0]! - expect(url).toBe('https://relay.onorca.dev/v1/resolve') - expect(url).not.toContain('A'.repeat(43)) - expect(init).toMatchObject({ method: 'POST' }) - expect(JSON.parse(String(init.body))).toEqual({ - v: 1, - relayHostId: relay.relayHostId, - resumeToken: 'A'.repeat(43) - }) - }) - it('rejects non-canonical targets and oversized bodies', async () => { const badTarget = vi.fn( async () => diff --git a/mobile/src/transport/rpc/rpc-operation-barrier.test.ts b/mobile/src/transport/rpc/rpc-operation-barrier.test.ts index 5d7698b32bc..8a6233202b8 100644 --- a/mobile/src/transport/rpc/rpc-operation-barrier.test.ts +++ b/mobile/src/transport/rpc/rpc-operation-barrier.test.ts @@ -44,24 +44,6 @@ describe('the post-barrier combinator', () => { await expect(barrier).rejects.toThrow('method_not_found: no such method') }) - it('keeps the middle operation error when a later one also fails', async () => { - const barrier = interpretAtRpcBarrier([ - startRpcOperation(replying(rpcSuccess(rows)), workspaceListAtBarrier, {}), - startRpcOperation( - replying(rpcRefusal('conflict', 'middle refused')), - workspaceListAtBarrier, - {} - ), - startRpcOperation( - replying(rpcRefusal('runtime_error', 'later refused')), - workspaceListAtBarrier, - {} - ) - ]) - - await expect(barrier).rejects.toThrow('conflict: middle refused') - }) - it('rethrows a captured transport rejection as the original error object', async () => { const error = markRpcDeliveryUnknown(new Error('socket closed before response')) const dropped = new FakeSession('connected') diff --git a/mobile/src/transport/rpc/rpc-operation.test.ts b/mobile/src/transport/rpc/rpc-operation.test.ts deleted file mode 100644 index 81c736d4300..00000000000 --- a/mobile/src/transport/rpc/rpc-operation.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { FakeSession } from '../connection/mobile-endpoint-supervisor-test-fakes' - -import { isLogicalClientCutoverError } from '../connection/logical-client-cutover-error' -import { isRpcDeliveryUnknown, markRpcDeliveryUnknown } from './rpc-delivery-ambiguity' - -import { captureRpcOperationSettlement, runRpcOperation } from './rpc-operation' -import { workspaceListOrThrow } from './rpc-operation-test-families' - -describe('transport rejection stays on the promise channel', () => { - it('rejects with the original error object', async () => { - const error = new Error('socket closed') - const session = new FakeSession('connected') - session.sendRequest.mockRejectedValue(error) - - await expect(runRpcOperation(session, workspaceListOrThrow, {})).rejects.toBe(error) - }) - - it('keeps a delivery-unknown mark readable through the descriptor', async () => { - const error = markRpcDeliveryUnknown(new Error('socket closed before response')) - const session = new FakeSession('connected') - session.sendRequest.mockRejectedValue(error) - - const caught = await runRpcOperation(session, workspaceListOrThrow, {}).catch( - (thrown: unknown) => thrown - ) - - expect(caught).toBe(error) - expect(isRpcDeliveryUnknown(caught)).toBe(true) - }) - - // instanceof misses foreign bundle copies; cutover detection must also accept the exact message. - it('keeps a cutover error from another bundle copy recognisable', async () => { - class ForeignBundleCutoverError extends Error {} - const error = new ForeignBundleCutoverError('RPC interrupted by connection migration') - const session = new FakeSession('connected') - session.sendRequest.mockRejectedValue(error) - - const caught = await runRpcOperation(session, workspaceListOrThrow, {}).catch( - (thrown: unknown) => thrown - ) - - expect(caught).toBe(error) - expect(isLogicalClientCutoverError(caught)).toBe(true) - }) - - it('only captures a rejection when a caller names the all-settled helper', async () => { - const error = new Error('socket closed') - const session = new FakeSession('connected') - session.sendRequest.mockRejectedValue(error) - - await expect(captureRpcOperationSettlement(session, workspaceListOrThrow, {})).resolves.toEqual( - { status: 'rejected', error } - ) - }) -}) diff --git a/mobile/src/worktree/use-retired-worktree-names.test.tsx b/mobile/src/worktree/use-retired-worktree-names.test.tsx index 1a1e053243d..9ea39e0b1a4 100644 --- a/mobile/src/worktree/use-retired-worktree-names.test.tsx +++ b/mobile/src/worktree/use-retired-worktree-names.test.tsx @@ -69,16 +69,6 @@ function mountNames() { } describe('useRetiredWorktreeNames', () => { - it('holds the watermark too when a refresh fails', async () => { - const probe = mountNames() - await probe.settle(0, { 'repo-1': [] }, { 'repo-1': 3 }) - - probe.rerender({ repoId: 'repo-1', refreshKey: 'b' }) - await probe.fail(1) - - expect(probe.registry.exhaustedTiers).toBe(3) - }) - // Match desktop: refresh failure must not un-retire every name for the rest of the sheet session. it('keeps previously loaded names when a refresh fails', async () => { const probe = mountNames() diff --git a/mobile/src/worktree/worktree-display-name.test.ts b/mobile/src/worktree/worktree-display-name.test.ts deleted file mode 100644 index edb7a7f5a46..00000000000 --- a/mobile/src/worktree/worktree-display-name.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getLiveWorktreeDisplayName } from './worktree-display-name' - -describe('getLiveWorktreeDisplayName', () => { - it('uses the host-list display name for the current worktree', () => { - expect( - getLiveWorktreeDisplayName( - [ - { worktreeId: 'wt-1', displayName: 'Old' }, - { worktreeId: 'wt-2', displayName: 'Auto Generated Name' } - ], - 'wt-2' - ) - ).toBe('Auto Generated Name') - }) - - it('matches worktree.show payloads keyed by id', () => { - expect(getLiveWorktreeDisplayName([{ id: 'wt-1', displayName: 'Settled Name' }], 'wt-1')).toBe( - 'Settled Name' - ) - }) - - it('falls back to repo only when the display name is blank', () => { - expect( - getLiveWorktreeDisplayName( - [{ worktreeId: 'wt-1', displayName: ' ', repo: ' orca ' }], - 'wt-1' - ) - ).toBe('orca') - }) - - it('ignores snapshots that do not contain the current worktree', () => { - expect(getLiveWorktreeDisplayName([{ worktreeId: 'wt-1', displayName: 'Other' }], 'wt-2')).toBe( - null - ) - }) -}) diff --git a/package.json b/package.json index 283d28dcd45..4014ada5610 100644 --- a/package.json +++ b/package.json @@ -226,6 +226,8 @@ "build:packages": "node config/scripts/workspace-package-build/build-workspace-packages.mjs", "check:process-host-imports": "node config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs", "check:main-sync-spawn-ratchet": "node config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs", + "check:main-sync-fs-ratchet": "node config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs", + "check:recurring-timer-ratchet": "node config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs", "check:compat-boundary-imports": "node config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs", "check:import-boundaries": "bun config/scripts/static-analysis/process-boundaries/check-import-boundaries.mjs" }, diff --git a/skill-guides/orca-per-workspace-env.md b/skill-guides/orca-per-workspace-env.md index 76c94d8a566..bb27ceabc80 100644 --- a/skill-guides/orca-per-workspace-env.md +++ b/skill-guides/orca-per-workspace-env.md @@ -290,6 +290,26 @@ environmentRecipes: fresh recipe JSON because the pairing may have changed. `destroy` may be omitted only with `destroy: none`. The legacy keys `command` and `cleanup` still map to `create` and `destroy`. +Steps have no time limit by default. Set `timeoutSeconds` on the recipe to give them one, either +one number for every step or a map with any of `create`, `suspend`, `resume`, and `destroy`; values +are whole seconds from 1 to 86400. When a step runs past its limit, Orca stops the whole process +tree and reports a timeout. An invalid value is reported and the steps stay unlimited. + +```yaml +timeoutSeconds: + create: 1800 # slow image builds + destroy: 120 +``` + +A timed-out `create` may still have started a VM, so make `create` idempotent per +`ORCA_VM_INSTANCE_ID` or have it record the resource before slow work starts. + +Orca records each VM before `create` runs. If `create` started but never returned a result (it +failed, timed out, or Orca quit), Settings keeps the VM listed so the user can clean it up; if it +was cancelled or rejected before starting, nothing is kept. That destroy +payload has `instanceId` but no `recipeResult`, so `destroy` should find the resource from the +instance id (for example, a name built from `ORCA_VM_INSTANCE_ID`) or exit non-zero if it can't. + The base result, which is what Orca-server mode prints: ```json diff --git a/src/cli/automation-owner-conflict-recovery.test.ts b/src/cli/automation-owner-conflict-recovery.test.ts deleted file mode 100644 index fd6e64ea080..00000000000 --- a/src/cli/automation-owner-conflict-recovery.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { formatCliError } from './format' -import { RuntimeRpcFailureError } from './runtime-client' - -function conflict(code: string, message: string): RuntimeRpcFailureError { - return new RuntimeRpcFailureError({ - id: 'request-1', - ok: false, - error: { code, message: `${message}: ${code}` }, - _meta: { runtimeId: 'runtime-1' } - }) -} - -afterEach(() => vi.restoreAllMocks()) - -describe('automation owner conflicts read as CLI outcomes', () => { - it('leaves unrelated failures untouched', () => { - const output = formatCliError(conflict('runtime_error', 'Something else')) - - expect(output).toBe('Something else: runtime_error') - }) -}) diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 12f3f91b044..27f797ad678 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2074,6 +2074,26 @@ const ORCA_PER_WORKSPACE_ENV_MARKDOWN = [ "fresh recipe JSON because the pairing may have changed. `destroy` may be omitted only with", "`destroy: none`. The legacy keys `command` and `cleanup` still map to `create` and `destroy`.", "", + "Steps have no time limit by default. Set `timeoutSeconds` on the recipe to give them one, either", + "one number for every step or a map with any of `create`, `suspend`, `resume`, and `destroy`; values", + "are whole seconds from 1 to 86400. When a step runs past its limit, Orca stops the whole process", + "tree and reports a timeout. An invalid value is reported and the steps stay unlimited.", + "", + "```yaml", + "timeoutSeconds:", + " create: 1800 # slow image builds", + " destroy: 120", + "```", + "", + "A timed-out `create` may still have started a VM, so make `create` idempotent per", + "`ORCA_VM_INSTANCE_ID` or have it record the resource before slow work starts.", + "", + "Orca records each VM before `create` runs. If `create` started but never returned a result (it", + "failed, timed out, or Orca quit), Settings keeps the VM listed so the user can clean it up; if it", + "was cancelled or rejected before starting, nothing is kept. That destroy", + "payload has `instanceId` but no `recipeResult`, so `destroy` should find the resource from the", + "instance id (for example, a name built from `ORCA_VM_INSTANCE_ID`) or exit non-zero if it can't.", + "", "The base result, which is what Orca-server mode prints:", "", "```json", diff --git a/src/cli/format.test.ts b/src/cli/format.test.ts index f53b78fc4c5..7fba85f8000 100644 --- a/src/cli/format.test.ts +++ b/src/cli/format.test.ts @@ -1,17 +1,9 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { - formatAutomationShow, - formatComputerAction, - formatTerminalList, - formatWorktreeList, - printResult -} from './format' -import type { ComputerActionResult, RuntimeWorktreeRecord } from '../shared/runtime-types' -import type { Automation } from '../shared/automations/automation-definition' +import { printResult } from './format' let testScreenshotDir: string | null = null @@ -24,370 +16,7 @@ afterEach(() => { } }) -function worktree(overrides: Partial = {}): RuntimeWorktreeRecord { - const base: RuntimeWorktreeRecord = { - id: 'repo::/tmp/repo/child', - repoId: 'repo', - path: '/tmp/repo/child', - head: 'abc123', - branch: 'feature/child', - isBare: false, - isMainWorktree: false, - parentWorktreeId: null, - childWorktreeIds: [], - lineage: null, - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - git: { - path: '/tmp/repo/child', - head: 'abc123', - branch: 'feature/child', - isBare: false, - isMainWorktree: false - }, - displayName: '', - comment: '' - } - return { ...base, ...overrides } -} - -describe('formatWorktreeList', () => { - it('includes parent and child workspace relationships in text output', () => { - const output = formatWorktreeList({ - worktrees: [ - worktree({ - id: 'repo::/tmp/repo/parent', - path: '/tmp/repo/parent', - branch: 'feature/parent', - childWorktreeIds: ['repo::/tmp/repo/child'] - }), - worktree({ - parentWorktreeId: 'repo::/tmp/repo/parent' - }) - ], - totalCount: 2, - truncated: false - }) - - const [parent, child] = output.split('\n\n') - expect(parent).toContain('repo::/tmp/repo/parent feature/parent') - expect(parent).toContain('parentWorktreeId: null') - expect(parent).toContain('childWorktreeIds: repo::/tmp/repo/child') - expect(child).toContain('repo::/tmp/repo/child feature/child') - expect(child).toContain('parentWorktreeId: repo::/tmp/repo/parent') - expect(child).toContain('childWorktreeIds: []') - }) -}) - -describe('formatAutomationShow', () => { - function automation(overrides: Partial = {}): Automation { - return { - id: 'auto-1', - name: 'Nightly', - prompt: 'Run checks', - precheck: null, - agentId: 'codex', - projectId: 'repo-legacy', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', - dtstart: 0, - enabled: true, - nextRunAt: 0, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 0, - updatedAt: 0, - ...overrides - } - } - - it('shows explicit run context before the legacy repo id', () => { - const output = formatAutomationShow({ - automation: automation({ - runContext: { - kind: 'workspace-run', - projectId: 'github:stablyai/orca', - hostId: 'runtime:gpu', - projectHostSetupId: 'setup-gpu', - repoId: 'repo-gpu', - path: '/srv/orca' - } - }) - }) - - expect(output).toContain('runProjectId: github:stablyai/orca') - expect(output).toContain('runHostId: runtime:gpu') - expect(output).toContain('projectHostSetupId: setup-gpu') - expect(output).toContain('runRepoId: repo-gpu') - expect(output).toContain('runPath: /srv/orca') - expect(output).toContain('legacyRepoId: repo-legacy') - expect(output).not.toContain('projectId: repo-legacy') - }) -}) - -describe('formatTerminalList', () => { - it('prints visual split groups and nested terminal panes', () => { - const output = formatTerminalList({ - terminals: [ - { - handle: 'term_left', - ptyId: 'pty-left', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-left', - leafId: 'leaf-left', - title: 'Left', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - }, - { - handle: 'term_top', - ptyId: 'pty-top', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-right', - leafId: 'leaf-top', - title: 'Right top', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - }, - { - handle: 'term_bottom', - ptyId: 'pty-bottom', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-right', - leafId: 'leaf-bottom', - title: 'Right bottom', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - } - ], - totalCount: 3, - truncated: false, - visualLayouts: [ - { - worktreeId: 'wt-1', - worktreePath: '/repo', - root: { - type: 'split', - direction: 'horizontal', - first: { - type: 'group', - groupId: 'group-left', - activeTabId: 'tab-left', - tabs: [ - { - tabId: 'tab-left', - title: 'Left', - activeLeafId: 'leaf-left', - panes: { - type: 'terminal', - handle: 'term_left', - tabId: 'tab-left', - leafId: 'leaf-left', - title: 'Left', - connected: true, - active: true - } - } - ] - }, - second: { - type: 'group', - groupId: 'group-right', - activeTabId: 'tab-right', - tabs: [ - { - tabId: 'tab-right', - title: 'Right', - activeLeafId: 'leaf-bottom', - panes: { - type: 'pane-split', - direction: 'vertical', - first: { - type: 'terminal', - handle: 'term_top', - tabId: 'tab-right', - leafId: 'leaf-top', - title: 'Right top', - connected: true, - active: false - }, - second: { - type: 'terminal', - handle: 'term_bottom', - tabId: 'tab-right', - leafId: 'leaf-bottom', - title: 'Right bottom', - connected: true, - active: true - } - } - } - ] - } - } - } - ] - } as never) - - expect(output).toContain('visual layout:') - expect(output).toContain('/repo') - expect(output).toContain('split horizontal') - expect(output).toContain('group group-left') - expect(output).toContain('tab tab-left Left') - expect(output).toContain('* term_left Left tab=tab-left leaf=leaf-left') - expect(output).toContain('group group-right') - expect(output).toContain('pane split vertical') - expect(output).toContain(' term_top Right top tab=tab-right leaf=leaf-top') - expect(output).toContain('* term_bottom Right bottom tab=tab-right leaf=leaf-bottom') - }) -}) - -describe('formatComputerAction', () => { - it('preserves explicit window-index targeting in the suggested follow-up command', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 }, - window: { title: 'Document', id: 42, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' } - } - - const output = formatComputerAction('click', result, { - session: 'manual', - windowIndex: 1 - }) - - expect(output).toContain( - 'Use `orca computer get-app-state --app com.apple.finder --session manual --window-index 1`' - ) - }) - - it('uses snapshot window index for follow-up commands when the provider has no stable window id', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Linux Browser', bundleId: null, pid: 100 }, - window: { title: 'Inbox', id: null, index: 2, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'synthetic', - targetWindowId: null - } - } - - const output = formatComputerAction('click', result) - - const app = process.platform === 'win32' ? '"Linux Browser"' : "'Linux Browser'" - expect(output).toContain(`Use \`orca computer get-app-state --app ${app} --window-index 2\``) - expect(output).not.toContain('--window-id') - }) - - it('uses action target window index before snapshot fallback for ID-less providers', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Linux Browser', bundleId: null, pid: 100 }, - window: { title: 'Inbox', id: null, index: 4, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'synthetic', - targetWindowId: null, - targetWindowIndex: 2 - } - } - - const output = formatComputerAction('click', result) - - const app = process.platform === 'win32' ? '"Linux Browser"' : "'Linux Browser'" - expect(output).toContain(`Use \`orca computer get-app-state --app ${app} --window-index 2\``) - expect(output).not.toContain('--window-index 4') - expect(output).not.toContain('--window-id') - }) -}) - describe('printResult computer screenshots', () => { - it('skips screenshot temp cleanup when the cleanup marker is fresh', () => { - testScreenshotDir = mkdtempSync(join(tmpdir(), 'orca-format-test-')) - const expiredPath = join(testScreenshotDir, 'old-screenshot.png') - writeFileSync(expiredPath, 'old') - const expired = new Date(Date.now() - 48 * 60 * 60 * 1000) - utimesSync(expiredPath, expired, expired) - writeFileSync(join(testScreenshotDir, '.last-cleanup'), 'recent\n') - process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = testScreenshotDir - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined) - - printResult( - { - id: 'req/1', - ok: true, - result: { - screenshot: { - data: Buffer.from('png-data').toString('base64'), - format: 'png', - width: 1, - height: 1, - scale: 1 - }, - screenshotStatus: { state: 'captured' } - }, - _meta: { runtimeId: 'runtime-1' } - }, - true, - () => 'unused' - ) - - expect(existsSync(expiredPath)).toBe(true) - const output: { - result: { screenshot: { dataOmitted: boolean; path: string } } - } = JSON.parse(logSpy.mock.calls[0][0]) - expect(output.result.screenshot.dataOmitted).toBe(true) - expect(output.result.screenshot.path).toContain('req_1-screenshot.png') - expect(readFileSync(output.result.screenshot.path, 'utf8')).toBe('png-data') - }) - it('keeps inline screenshot data when temp export fails', () => { testScreenshotDir = join(tmpdir(), `orca-format-blocked-${Date.now()}`) writeFileSync(testScreenshotDir, 'not-a-directory') diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index f39a640858e..9cc19bf9f86 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -26,6 +26,12 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ load: async () => (await import('./handlers/core.js')).CORE_HANDLERS }, ...SERVE_PAIRING_HANDLER_GROUPS, + { + name: 'serve-reset-identity', + keys: ['serve reset-identity'], + load: async () => + (await import('./handlers/serve-reset-identity.js')).SERVE_RESET_IDENTITY_HANDLERS + }, { name: 'serve-service', keys: ['serve service install', 'serve service status', 'serve service uninstall'], diff --git a/src/cli/handlers/agent-hooks.test.ts b/src/cli/handlers/agent-hooks.test.ts index ae7dba93bdd..bff357168f7 100644 --- a/src/cli/handlers/agent-hooks.test.ts +++ b/src/cli/handlers/agent-hooks.test.ts @@ -83,7 +83,7 @@ vi.mock('../runtime-client', () => { } }) -vi.mock('../../main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock, getManagedAgentHookStatuses: getManagedAgentHookStatusesMock })) diff --git a/src/cli/handlers/agent-hooks.ts b/src/cli/handlers/agent-hooks.ts index 6689e9f86bb..522fa9d485c 100644 --- a/src/cli/handlers/agent-hooks.ts +++ b/src/cli/handlers/agent-hooks.ts @@ -163,7 +163,7 @@ async function setAgentHooksEnabled( enabled: boolean ): Promise { const { applyAgentStatusHooksEnabled, getManagedAgentHookStatuses } = - await import('../../main/agent-hooks/managed-agent-hook-controls.js') + await import('../../main/agent-hooks/installation/managed-agent-hook-controls.js') const updatedRuntime = await updateRunningRuntime(client, enabled) const offlineUpdate = updatedRuntime ? null : await updateEnabledOnDisk(enabled) const settingsPath = offlineUpdate?.settingsPath ?? (await getDataPath()) @@ -202,7 +202,7 @@ export const AGENT_HOOK_HANDLERS: Record = { 'agent hooks status': async ({ json, flags }) => { rejectRemoteHookSelection(flags) const { getManagedAgentHookStatuses } = - await import('../../main/agent-hooks/managed-agent-hook-controls.js') + await import('../../main/agent-hooks/installation/managed-agent-hook-controls.js') const result: AgentHookCommandResult = { enabled: (await readHookSettingsFromDisk()).agentStatusHooksEnabled, settingsPath: await getDataPath(), diff --git a/src/cli/handlers/orchestration/message-agent-views.ts b/src/cli/handlers/orchestration/message-agent-views.ts index d27fbb92df1..290fbf4fac2 100644 --- a/src/cli/handlers/orchestration/message-agent-views.ts +++ b/src/cli/handlers/orchestration/message-agent-views.ts @@ -5,6 +5,7 @@ import { type OrchestrationCheckOutput, type OrchestrationMessageSummary } from '../../../shared/orchestration/mailbox/orchestration-check-output' +import { formatReportFollowUpLine } from '../../../shared/orchestration/mailbox/orchestration-report-follow-up' import { escapeTerminalControlCharacters } from '../../../shared/terminal/output/terminal-control-character-escape' import { formatFieldPairs, orchestrationCliName, type OrchestrationAgentView } from './agent-view' import { withReceiptNext } from './receipt-next-text' @@ -20,6 +21,8 @@ export type MessageView = { priority?: string readOnly?: true handled?: boolean + /** What to do after a finished task's report, with its command; the runtime chooses it. */ + followUp?: string // Kept nested so sender-written payload can never stand in for Orca's own fields. payload?: Record | string } @@ -44,6 +47,9 @@ export function toMessageView( ? { readOnly: true as const } : {}), ...(options.recipient && message.read !== undefined ? { handled: message.read === 1 } : {}), + ...(message.follow_up && !isLegacyReadOnlyMessage(message, options.legacyCompatibilityActive) + ? { followUp: formatReportFollowUpLine(message.follow_up, orchestrationCliName()) } + : {}), ...payloadView(message) } } @@ -82,7 +88,7 @@ function nestsDeeperThan(value: unknown, depth: number): boolean { return depth === 0 || Object.values(value).some((child) => nestsDeeperThan(child, depth - 1)) } -export function formatMessageViewText(view: MessageView, replyCommand?: string): string { +export function formatMessageViewText(view: MessageView, actionLine?: string): string { const flags = [ view.priority === 'urgent' || view.priority === 'high' ? `[${view.priority.toUpperCase()}]` @@ -111,21 +117,27 @@ export function formatMessageViewText(view: MessageView, replyCommand?: string): ) ) } - if (replyCommand) { - lines.push(`Reply: ${replyCommand}`) + if (actionLine) { + lines.push(actionLine) } return lines.join('\n') } -/** Only a question awaits `reply`; reports and escalations name their own follow-up. */ -function replyCommandFor(message: OrchestrationMessageSummary, view: MessageView, checked: string) { - if (view.type !== 'question' || view.readOnly) { +/** Only a question awaits `reply`; a finished task's report names its follow-up instead. */ +function actionLineFor(message: OrchestrationMessageSummary, view: MessageView, checked: string) { + if (view.readOnly) { + return undefined + } + if (view.followUp) { + return view.followUp + } + if (view.type !== 'question') { return undefined } const target = message.to_handle ?? checked const from = target.startsWith('run:') || target.startsWith('dispatch:') ? '' : ` --from ${target}` - return `${orchestrationCliName()} orchestration reply --id ${message.id}${from} --body "..."` + return `Reply: ${orchestrationCliName()} orchestration reply --id ${message.id}${from} --body "..."` } export type CheckAgentResult = OrchestrationCheckOutput & { replayed?: boolean; next?: string } @@ -173,7 +185,7 @@ export function checkView( } const messages = fields.messages .map((view, index) => - formatMessageViewText(view, replyCommandFor(value.messages[index], view, checkedTerminal)) + formatMessageViewText(view, actionLineFor(value.messages[index], view, checkedTerminal)) ) .join('\n\n') return withReceiptNext( diff --git a/src/cli/handlers/orchestration/message-inbox-handlers.ts b/src/cli/handlers/orchestration/message-inbox-handlers.ts index 6c631abae4b..32d35acfb4b 100644 --- a/src/cli/handlers/orchestration/message-inbox-handlers.ts +++ b/src/cli/handlers/orchestration/message-inbox-handlers.ts @@ -19,27 +19,37 @@ import { formatMessageViewText, toMessageView, type MessageView } from './messag export const ORCHESTRATION_INBOX_HANDLERS: Record = { 'orchestration reply': async ({ flags, client, cwd, json }) => { const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from') - const result = await callOrchestrationMutation<{ message: { id: string }; next?: string }>( - client, - flags, - 'orchestration.reply', - { - id: getRequiredStringFlag(flags, 'id'), - body: getRequiredStringFlag(flags, 'body'), - run: getOptionalStringFlag(flags, 'run'), - from - } - ) + const result = await callOrchestrationMutation<{ + message: { id: string } + warnings?: { message: string }[] + next?: string + }>(client, flags, 'orchestration.reply', { + id: getRequiredStringFlag(flags, 'id'), + body: getRequiredStringFlag(flags, 'body'), + run: getOptionalStringFlag(flags, 'run'), + from + }) if (!flags.has('full')) { printOrchestrationResult(result, json, { fields: (value) => ({ messageId: value.message.id, + warnings: value.warnings?.length + ? value.warnings.map((warning) => warning.message) + : undefined, next: value.next }) }) return } - printResult(result, json, (value) => withReceiptNext(`Replied ${value.message.id}`, value)) + printResult(result, json, (value) => + withReceiptNext( + [ + `Replied ${value.message.id}`, + ...(value.warnings ?? []).map((warning) => `Warning: ${warning.message}`) + ].join('\n'), + value + ) + ) }, 'orchestration inbox': async ({ flags, client, json }) => { diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index ae2d63019d9..ac76e9c214a 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -1,6 +1,7 @@ import { renderOrchestrationArgv, type OrchestrationAgentView } from './agent-view' import type { WorkerListRunScope } from './worker-list-run-scope' import { isActionableOrchestrationFleetAttention } from '../../../shared/orchestration/fleet/orchestration-fleet-attention' +import { formatPrCommentRelativeTime } from '../../../shared/source-control/review-comments/pr-comment-time' type WorkerProjection = { runId?: string @@ -9,7 +10,8 @@ type WorkerProjection = { host: { id: string } workspace?: { id: string } | null stage: { activity: string } - liveness: { verdict: string } + liveness: { verdict: string; detail?: string } + evidence?: { lastObservedAt: number | null } nextAction: { argv: string[] } attention?: { categories: string[] } resource?: { terminalState?: string | null } | null @@ -49,6 +51,8 @@ type WorkerShowFields = { state: string stage: string liveness?: string + activity?: string + lastActivity?: string terminal?: string terminalState?: string workspace?: string @@ -69,7 +73,9 @@ export const WORKER_SHOW_VIEW: OrchestrationAgentView(values: T[] | undefined): T[] | undefined { return values && values.length > 0 ? values : undefined } + +/** Name what could not be verified, so a lost host never reads like a stuck worker. */ +function livenessField(projection: WorkerProjection | null | undefined): string | undefined { + const liveness = projection?.liveness + return liveness?.detail ? `${liveness.verdict} (${liveness.detail})` : liveness?.verdict +} + +/** Only a live worker's activity is known; a finished turn is an idle agent, not finished work. */ +function knownActivity(projection: WorkerProjection | null | undefined): string | undefined { + if (projection?.liveness.verdict !== 'live' || projection.stage.activity === 'unknown') { + return undefined + } + return projection.stage.activity === 'done' ? 'idle' : projection.stage.activity +} + +function lastActivity(projection: WorkerProjection | null | undefined): string | undefined { + const at = projection?.evidence?.lastObservedAt + return knownActivity(projection) && typeof at === 'number' + ? formatPrCommentRelativeTime(new Date(at).toISOString(), Date.now()) + : undefined +} diff --git a/src/cli/handlers/serve-reset-identity.test.ts b/src/cli/handlers/serve-reset-identity.test.ts new file mode 100644 index 00000000000..eb4fa8d2c89 --- /dev/null +++ b/src/cli/handlers/serve-reset-identity.test.ts @@ -0,0 +1,65 @@ +import { chmodSync, mkdtempSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { resetServeHostIdentity } from './serve-reset-identity' +import { loadOrCreateE2EEKeypair } from '../../main/runtime/rpc/server/pairing/e2ee-keypair' +import { DeviceRegistry } from '../../main/runtime/rpc/server/pairing/device-registry' +import { acquireOrcadInstanceLock } from '../../main/orcad/orcad-instance-lock' +import { + ensureHostInstanceIdentity, + hostInstanceIdFromEnv +} from '../../main/runtime/host-instance-identity' + +function pairedProfile() { + const dir = mkdtempSync(join(tmpdir(), 'orca-reset-identity-')) + chmodSync(dir, 0o700) + const registry = new DeviceRegistry(dir) + const { token } = registry.addDevice('Phone') + return { dir, token, publicKeyB64: loadOrCreateE2EEKeypair(dir).publicKeyB64 } +} + +describe('resetServeHostIdentity', () => { + it('rotates the key and removes paired devices, then stays put across restarts', async () => { + const before = pairedProfile() + await resetServeHostIdentity(before.dir) + + const publicKeyB64 = loadOrCreateE2EEKeypair(before.dir).publicKeyB64 + expect(publicKeyB64).not.toBe(before.publicKeyB64) + expect(new DeviceRegistry(before.dir).validateToken(before.token)).toBeNull() + expect(ensureHostInstanceIdentity(before.dir, null)).toEqual({ kind: 'unchanged' }) + // A variable adopted after the reset is only recorded. + expect( + ensureHostInstanceIdentity(before.dir, hostInstanceIdFromEnv({ ORCA_INSTANCE_ID: 'vm-a' })) + ).toEqual({ kind: 'recorded' }) + expect(loadOrCreateE2EEKeypair(before.dir).publicKeyB64).toBe(publicKeyB64) + }) + + it('refuses while an Orca holds the profile lock and changes nothing', async () => { + const before = pairedProfile() + const lock = acquireOrcadInstanceLock(before.dir) + try { + await expect(resetServeHostIdentity(before.dir)).rejects.toThrow(/Stop Orca/) + } finally { + lock.release() + } + expect(loadOrCreateE2EEKeypair(before.dir).publicKeyB64).toBe(before.publicKeyB64) + expect(new DeviceRegistry(before.dir).validateToken(before.token)).not.toBeNull() + }) + + it.skipIf(process.platform === 'win32')( + 'leaves desktop profile permissions alone when it refuses because the desktop app runs', + async () => { + const before = pairedProfile() + chmodSync(before.dir, 0o755) + const lock = acquireOrcadInstanceLock(before.dir, { role: 'desktop' }) + try { + await expect(resetServeHostIdentity(before.dir)).rejects.toThrow(/Stop Orca/) + } finally { + lock.release() + } + expect(statSync(before.dir).mode & 0o777).toBe(0o755) + expect(loadOrCreateE2EEKeypair(before.dir).publicKeyB64).toBe(before.publicKeyB64) + } + ) +}) diff --git a/src/cli/handlers/serve-reset-identity.ts b/src/cli/handlers/serve-reset-identity.ts new file mode 100644 index 00000000000..310b27eac9e --- /dev/null +++ b/src/cli/handlers/serve-reset-identity.ts @@ -0,0 +1,61 @@ +import type { CommandHandler } from '../dispatch' +import { RuntimeClientError } from '../runtime/types' +import { resolveLaunchUserDataPath } from '../runtime/launch-user-data-path' +import { pluginDevWatchConfirmFor } from '../plugin-dev-watch/plugin-dev-watch-approval' + +const RESET_WARNING = + "This gives this machine's Orca server a new pairing key and installation id and removes every " + + 'paired device. Desktops and phones paired with it must pair again.' + +export async function resetServeHostIdentity(userDataPath: string): Promise { + // Lazy: only this command needs orcad's lock code. + const { resetHostIdentityUnderLock } = + await import('../../main/orcad/orcad-host-identity-reset.js') + const result = resetHostIdentityUnderLock(userDataPath) + if (result.status === 'missing') { + throw new RuntimeClientError('not_found', `No Orca data at ${userDataPath}; nothing to reset.`) + } + if (result.status === 'running') { + throw new RuntimeClientError( + 'runtime_running', + `Stop Orca (the desktop app or \`orca serve\`) for ${userDataPath} first. ${result.message}` + ) + } + if (result.status === 'failed') { + throw new RuntimeClientError('reset_failed', `${result.message} Nothing was reset.`) + } + if (result.status === 'incomplete') { + throw new RuntimeClientError( + 'reset_incomplete', + `The reset did not finish (${result.message}). The next Orca start for ${userDataPath} finishes it before pairing is served; fix the cause first.` + ) + } +} + +export const SERVE_RESET_IDENTITY_HANDLERS: Record = { + 'serve reset-identity': async ({ flags, json }) => { + const userDataPath = resolveLaunchUserDataPath() + if (flags.get('yes') !== true) { + const confirm = pluginDevWatchConfirmFor(json) + if (!confirm) { + throw new RuntimeClientError( + 'confirmation_required', + `${RESET_WARNING} Run \`orca serve reset-identity --yes\` to continue.` + ) + } + if (!(await confirm(`${RESET_WARNING}\nReset ${userDataPath}? [y/N] `))) { + console.log('Cancelled; nothing changed.') + process.exitCode = 1 + return + } + } + await resetServeHostIdentity(userDataPath) + if (json) { + console.log(JSON.stringify({ ok: true, result: { reset: true, userDataPath } }, null, 2)) + return + } + console.log( + `Reset the pairing identity in ${userDataPath}. Start Orca again and pair clients with it.` + ) + } +} diff --git a/src/cli/orchestration-dispatch-refusal-format.test.ts b/src/cli/orchestration-dispatch-refusal-format.test.ts deleted file mode 100644 index df881ed4974..00000000000 --- a/src/cli/orchestration-dispatch-refusal-format.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' - -import { formatCliError, reportCliError } from './format' -import { RuntimeRpcFailureError, type RuntimeRpcFailure } from './runtime/types' - -afterEach(() => { - vi.restoreAllMocks() -}) - -// Runtime envelopes may contain codes introduced after this client; formatting must preserve them. - -it('prints an unknown code with its message and nextSteps unchanged', () => { - const failure: RuntimeRpcFailure = { - id: 'rpc_1', - ok: false, - error: { - code: 'code_from_a_newer_host', - message: 'Refused for a reason this CLI has never heard of.', - data: { nextSteps: ['Do the thing the newer host suggested.'] } - }, - _meta: { runtimeId: 'runtime_1' } - } - const error = new RuntimeRpcFailureError(failure) - - expect(formatCliError(error, { commandPath: ['orchestration', 'dispatch'] })).toBe( - 'Refused for a reason this CLI has never heard of.\nNext step: Do the thing the newer host suggested.' - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - reportCliError(error, true, { commandPath: ['orchestration', 'dispatch'] }) - expect(JSON.parse(log.mock.calls[0]?.[0] as string)).toEqual(failure) -}) diff --git a/src/cli/runtime-client-deferral.test.ts b/src/cli/runtime-client-deferral.test.ts index 8e78d6cae9f..ef6908fe9a7 100644 --- a/src/cli/runtime-client-deferral.test.ts +++ b/src/cli/runtime-client-deferral.test.ts @@ -37,7 +37,7 @@ vi.mock( ) // Stub hook writes: this suite runs real handlers that would otherwise edit the developer's agent configs. -vi.mock('../main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock, getManagedAgentHookStatuses: vi.fn(() => []) })) diff --git a/src/cli/runtime/offline-admission-commands.test.ts b/src/cli/runtime/offline-admission-commands.test.ts index 45527e3df55..bb6a0bdbbd7 100644 --- a/src/cli/runtime/offline-admission-commands.test.ts +++ b/src/cli/runtime/offline-admission-commands.test.ts @@ -26,7 +26,7 @@ vi.mock('@orca/process-host', async (original) => ({ })) // Exercise the existing hook installer on one isolated target; do not discover installed agents. -vi.mock('../../main/agent-hooks/managed-agent-hook-controls', async () => { +vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', async () => { const { claudeHookService } = await import('../../main/claude/hook-service.js') return { applyAgentStatusHooksEnabled: vi.fn(async (enabled: boolean) => [ diff --git a/src/cli/runtime/transport.ts b/src/cli/runtime/transport.ts index 758590548e4..eafc4672ff8 100644 --- a/src/cli/runtime/transport.ts +++ b/src/cli/runtime/transport.ts @@ -11,6 +11,7 @@ import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } f import { MAX_TIMER_DELAY_MS, isSafeTimerDelayMs } from '../../shared/timer-delay' import { runtimeAccessDeniedError } from './runtime-access-denied' import { MAX_LOCAL_RUNTIME_RPC_MESSAGE_BYTES } from '../../shared/local-runtime-rpc-limits' +import { daemonSocketDirIsTrusted } from '../../main/daemon/endpoint/publication/daemon-socket-endpoint-path' export async function sendRequest( metadata: RuntimeMetadata, @@ -43,6 +44,16 @@ export async function sendRequest( ) return } + // A relocated socket lives in shared /tmp; never send the auth token to a planted listener. + if (transport.kind === 'unix' && !daemonSocketDirIsTrusted(transport.endpoint)) { + reject( + new RuntimeClientError( + 'runtime_unavailable', + 'Orca runtime socket directory is not private to this user.' + ) + ) + return + } const socket = createConnection(transport.endpoint) let lineSegments: string[] = [] let settled = false diff --git a/src/cli/specs/serve.ts b/src/cli/specs/serve.ts index 91018e91a17..3bc6b770259 100644 --- a/src/cli/specs/serve.ts +++ b/src/cli/specs/serve.ts @@ -40,6 +40,7 @@ export const SERVE_COMMAND_SPECS: CommandSpec[] = [ "--reclaim-stale-lock starts nothing. When a start refuses because this profile's lock may belong to an Orca on another machine sharing this home (for example after a reboot, on a network home), it checks that the lock was written on a host with this name in an earlier boot, was last written or refreshed at least 5 minutes ago, and that nothing answers on this machine at its holder's endpoints. Those checks cannot rule out another machine with the same host name, so it then only prints what it found (exit 2); add --yes, once you are sure no other machine sharing this home runs Orca for this profile, to clear it (exit 0). It exits 1 when a check fails and 4 when there is no lock. --data-root names the data root the refusal printed. --json prints the status (none, eligible, refused or reclaimed). Linux only.", 'On macOS, after Orca serve aborts at startup (it could not register with Launch Services), later runs from the same environment refuse for 30 minutes with exit code 78. Use --force to try anyway.', '--supervise is for service managers (launchd, systemd). Orca serve then restarts the server itself with growing delays instead of exiting when it stops, waits while an update replaces the app, and waits while another Orca serves this profile. On the orcad runtime (the default), a supervised server does not start without its terminal daemon, because terminals outside it would not survive a restart; that counts as a failure. After 6 failures in 15 minutes it gives up and exits with code 0 so the manager stops too, and later supervised runs refuse until a new build is installed or --force is passed. Not available on Windows yet.', + "Copies of a machine image share the server's pairing identity. Set ORCA_INSTANCE_ID to a value unique to each instance, or run `orca serve reset-identity` on each copy.", 'Experimental and off by default: set ORCA_TERMINAL_PROCESS_CEILING= (64 or more) before the terminal host starts to have the OS cap how many processes each terminal may run (Linux, through a systemd user scope per terminal, which needs a user manager that outlives logout; Windows, through a job per terminal). `orca serve` reports the ceiling as on or off, with the reason.', 'Off by default: set ORCA_TERMINAL_MEMORY_MAX= (256M or more) and ORCA_TERMINAL_MEMORY_SWAP_MAX= (0 for no swap) before the terminal host starts to cap the memory and swap of each terminal on Linux, through the same per-terminal systemd user scope. A terminal over its limit has its largest process OOM-killed; the host and other terminals keep running. Sizes take K, M, G or T. A limit the host cannot enforce is skipped and logged in the terminal host log. No effect on macOS or Windows.' ], @@ -64,6 +65,18 @@ export const SERVE_COMMAND_SPECS: CommandSpec[] = [ ], examples: ['orca serve restore resume', 'orca serve restore resume --json'] }, + { + path: ['serve', 'reset-identity'], + summary: "Give this machine's Orca server a new pairing identity", + usage: 'orca serve reset-identity [--yes] [--json]', + allowedFlags: [...LOCAL_COMMAND_FLAGS, 'yes'], + notes: [ + 'Replaces the pairing key and installation id and removes every paired device, so clients must pair again. Use it on each copy of a machine image that was made after Orca had run, so the copies stop sharing one identity.', + 'Asks for confirmation in a terminal; pass --yes to skip it. Stop Orca (the desktop app or `orca serve`) for this profile first; the command refuses while it runs.', + 'To have each copy rotate on its own instead, start `orca serve` with ORCA_INSTANCE_ID set to a value unique to that instance (for example the cloud-init instance id). When the value differs from the one recorded with the current identity, Orca rotates it at startup. The first value seen is only recorded, and an unset variable never rotates anything.' + ], + examples: ['orca serve reset-identity', 'orca serve reset-identity --yes'] + }, { path: ['serve', 'service', 'install'], summary: 'Run orca serve as a per-user background service that restarts itself', diff --git a/src/main/acp/session/children/acp-structured-background-task-stop.test.ts b/src/main/acp/session/children/acp-structured-background-task-stop.test.ts index ec8d0bd65a8..e703a43caef 100644 --- a/src/main/acp/session/children/acp-structured-background-task-stop.test.ts +++ b/src/main/acp/session/children/acp-structured-background-task-stop.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from '../../../agent-hooks/server' +import { _internals } from '../../../agent-hooks/server/agent-hook-server' import { closeProviderTimelineRigs, SESSION as ADAPTER_SESSION diff --git a/src/main/acp/session/children/acp-structured-child-work.test.ts b/src/main/acp/session/children/acp-structured-child-work.test.ts index fed21606981..e223bf0130f 100644 --- a/src/main/acp/session/children/acp-structured-child-work.test.ts +++ b/src/main/acp/session/children/acp-structured-child-work.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { _internals } from '../../../agent-hooks/server' +import { _internals } from '../../../agent-hooks/server/agent-hook-server' import { closeProviderTimelineRigs } from '../../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' import { CALLER } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' import { HOST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' diff --git a/src/main/acp/session/testing/acp-structured-child-work.test-support.ts b/src/main/acp/session/testing/acp-structured-child-work.test-support.ts index c66bc99e2c7..7332c22fcd7 100644 --- a/src/main/acp/session/testing/acp-structured-child-work.test-support.ts +++ b/src/main/acp/session/testing/acp-structured-child-work.test-support.ts @@ -1,4 +1,4 @@ -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { AgentChildWorkEvidence } from '../../../../shared/agent-status/child-work/agent-status-child-work-evidence' import { makeStructuredAgentStatusSubject, diff --git a/src/main/agent-hooks/README.md b/src/main/agent-hooks/README.md index 033dfd26332..3ed3b46dc06 100644 --- a/src/main/agent-hooks/README.md +++ b/src/main/agent-hooks/README.md @@ -3,10 +3,10 @@ Orca learns what each agent is doing through two channels. Both write into the hook server's status store. -| Channel | How | What it carries | -| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| **Managed integrations** (this folder) | Per-agent hooks, plugins and extensions that POST to the loopback hook server. Installers are listed in `managed-agent-hook-registry.ts`; each agent's code lives in `src/main//`. | State, prompt, tool name and input, assistant reply, provider session id (resume and native chat), model, subagents | -| **OSC 7501** (Program Status Protocol, [spec](https://www.superlogical.com/rex/docs/build/program-status)) | The agent writes its own status into the terminal stream. Orca reads it from PTY output and answers the protocol's `?` probe. | State, blocked `kind`, one free-text line (`msg`), child records | +| Channel | How | What it carries | +| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | +| **Managed integrations** (this folder) | Per-agent hooks, plugins and extensions that POST to the loopback hook server. Installers are listed in `installation/managed-agent-hook-registry.ts`; each agent's code lives in `src/main//`. | State, prompt, tool name and input, assistant reply, provider session id (resume and native chat), model, subagents | +| **OSC 7501** (Program Status Protocol, [spec](https://www.superlogical.com/rex/docs/build/program-status)) | The agent writes its own status into the terminal stream. Orca reads it from PTY output and answers the protocol's `?` probe. | State, blocked `kind`, one free-text line (`msg`), child records | **Precedence:** hooks win, and OSC 7501 fills in wherever they don't speak. That covers: @@ -90,7 +90,7 @@ When an agent ships OSC 7501 support, or changes what it reports: ## Plugin tool hooks (`agent.tool.before` / `.after`) The hook server runs plugins' `agent.tool.before` and `.after` on each tool event it receives, after -it records status (`agent-tool-plugin-hooks.ts`). Only Claude Code's POSIX script waits for the +it records status (`tool-events/agent-tool-plugin-hooks.ts`). Only Claude Code's POSIX script waits for the answer: it sends `X-Orca-Hook-Decision: claude-pre-tool-use-v1` on PreToolUse, waits at most 8 s (Orca answers within 6 s), and prints Orca's `hookSpecificOutput` (a `deny`, or `updatedInput` without an approval) or `{}`. A timeout, an error or Orca being down prints `{}`, so the call diff --git a/src/main/agent-hooks/branch-rename-failure-output.ts b/src/main/agent-hooks/first-work/branch-rename-failure-output.ts similarity index 95% rename from src/main/agent-hooks/branch-rename-failure-output.ts rename to src/main/agent-hooks/first-work/branch-rename-failure-output.ts index 1534c120b72..6bf1648d4e8 100644 --- a/src/main/agent-hooks/branch-rename-failure-output.ts +++ b/src/main/agent-hooks/first-work/branch-rename-failure-output.ts @@ -1,7 +1,7 @@ import { formatAgentGenerationFailureOutputForDisplay, type AgentGenerationFailureOutput -} from '../text-generation/agent-failure-output' +} from '../../text-generation/agent-failure-output' // Keep full CLI diagnostics local and ephemeral; persist only the sanitized failure badge. const MAX_ENTRIES = 32 diff --git a/src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts b/src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts similarity index 89% rename from src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts index e18044fd9c7..a2efb8ae1a8 100644 --- a/src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import { wslMoveCutoverFixture as cutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' +import type { Repo } from '../../../shared/repo-types' +import { wslMoveCutoverFixture as cutover } from '../../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' +import { seedWslMoveCutover } from '../../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' import { loadWslMoveFence, resetWslMoveFenceForTests -} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' +} from '../../persistence/moving-wsl-projects/wsl-move-scope-guard' const { gitExecFileAsyncMock, generateBranchNameMock, resolveTextGenerationParamsMock } = vi.hoisted(() => ({ @@ -17,19 +17,19 @@ const { gitExecFileAsyncMock, generateBranchNameMock, resolveTextGenerationParam resolveTextGenerationParamsMock: vi.fn() })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/git-username', () => ({ resolveLocalGitUsername: vi.fn(async () => 'you') })) -vi.mock('../text-generation/commit-message-text-generation', () => ({ +vi.mock('../../git/git-username', () => ({ resolveLocalGitUsername: vi.fn(async () => 'you') })) +vi.mock('../../text-generation/commit-message-text-generation', () => ({ generateBranchNameFromContext: generateBranchNameMock, resolveTextGenerationParams: resolveTextGenerationParamsMock })) -vi.mock('../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: vi.fn(async () => ({ ok: true })) })) -vi.mock('../ipc/worktree-branch-name', () => ({ +vi.mock('../../ipc/worktree-branch-name', () => ({ computeBranchName: vi.fn((leaf: string) => `you/${leaf}`), getConfiguredBranchPrefix: vi.fn(() => 'you') })) @@ -45,7 +45,7 @@ import { gitResponder, makeBranchRenameDeps, workingEvent -} from './first-work-branch-rename-test-harness' +} from './testing/first-work-branch-rename-test-harness' const LOCAL_REPO: Repo = { id: REPO_ID, diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work/first-work-branch-rename.test.ts similarity index 93% rename from src/main/agent-hooks/first-work-branch-rename.test.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename.test.ts index 0e4243ad92c..a2e08567087 100644 --- a/src/main/agent-hooks/first-work-branch-rename.test.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import type * as CommitMessageTextGenerationModule from '../text-generation/commit-message-text-generation' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' +import type { Repo } from '../../../shared/repo-types' +import type * as CommitMessageTextGenerationModule from '../../text-generation/commit-message-text-generation' +import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' +import { StructuredAgentSessionStatusFeed } from '../../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from './first-work-structured-session-rename' -import '../../shared/worktree/id' +import '../../../shared/worktree/id' const { gitExecFileAsyncMock, @@ -25,22 +25,22 @@ const { getConfiguredBranchPrefixMock: vi.fn((_settings: unknown, username: string | null) => username) })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/git-username', () => ({ resolveLocalGitUsername: resolveLocalGitUsernameMock })) -vi.mock('../text-generation/commit-message-text-generation', () => ({ +vi.mock('../../git/git-username', () => ({ resolveLocalGitUsername: resolveLocalGitUsernameMock })) +vi.mock('../../text-generation/commit-message-text-generation', () => ({ generateBranchNameFromContext: generateBranchNameMock, resolveTextGenerationParams: resolveTextGenerationParamsMock })) await vi.importActual( - '../text-generation/commit-message-text-generation' + '../../text-generation/commit-message-text-generation' ) -vi.mock('../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: prepareLocalEnvMock })) -vi.mock('../ipc/worktree-branch-name', () => ({ +vi.mock('../../ipc/worktree-branch-name', () => ({ computeBranchName: computeBranchNameMock, getConfiguredBranchPrefix: getConfiguredBranchPrefixMock })) @@ -57,9 +57,9 @@ import { makeBranchRenameDeps, noUpstreamError, workingEvent -} from './first-work-branch-rename-test-harness' +} from './testing/first-work-branch-rename-test-harness' import { FIRST_WORK_GENERATION_RETRY_DELAYS_MS } from './first-work-generation-backoff' -import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' const REMOTE_REPO_BASE: Repo = { id: REPO_ID, diff --git a/src/main/agent-hooks/first-work-branch-rename.ts b/src/main/agent-hooks/first-work/first-work-branch-rename.ts similarity index 90% rename from src/main/agent-hooks/first-work-branch-rename.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename.ts index f68b94e2c3e..b0be745b23a 100644 --- a/src/main/agent-hooks/first-work-branch-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename.ts @@ -1,36 +1,36 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Repo } from '../../shared/repo-types' -import { isFolderRepo } from '../../shared/repo-kind' -import { getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem } from '../../shared/worktree/id' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { parsePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { Repo } from '../../../shared/repo-types' +import { isFolderRepo } from '../../../shared/repo-kind' +import { getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { humanizeBranchSlug, isAutoGeneratedCreatureBranchName, stripConfiguredBranchPrefix -} from '../../shared/source-control/ai/naming/branch-name-from-work' -import { getCommitMessageModelDiscoveryHostKey } from '../../shared/source-control/ai/generation/commit-message-host-key' -import { computeBranchName, getConfiguredBranchPrefix } from '../ipc/worktree-branch-name' -import { gitExecFileAsync } from '../git/runner' -import { resolveLocalGitUsername } from '../git/git-username' -import { resolveGitRouteForHost } from '../providers/execution-host-provider-dispatch' -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { withCheckoutLock } from '../git/branch-switch' +} from '../../../shared/source-control/ai/naming/branch-name-from-work' +import { getCommitMessageModelDiscoveryHostKey } from '../../../shared/source-control/ai/generation/commit-message-host-key' +import { computeBranchName, getConfiguredBranchPrefix } from '../../ipc/worktree-branch-name' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import { resolveLocalGitUsername } from '../../git/git-username' +import { resolveGitRouteForHost } from '../../providers/execution-host-provider-dispatch' +import { getRepoExecutionHostId } from '../../../shared/execution-host' +import { withCheckoutLock } from '../../git/branch-switch' import { probeBranchUpstream, renameCurrentBranch, resolveUniqueBranchName, type GitExec -} from '../git/branch-rename' +} from '../../git/branch-rename' import { generateBranchNameFromContext, resolveTextGenerationParams -} from '../text-generation/commit-message-text-generation' -import type { CommitMessageAgentEnvironmentResolvers } from '../text-generation/commit-message-agent-environment' -import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' +} from '../../text-generation/commit-message-text-generation' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { AgentGenerationFailureOutput } from '../../text-generation/agent-failure-output' import { resolveGenerationTarget } from './first-work-generation-target' import { runFolderWorkspaceTitleAutoRename } from './first-work-workspace-title-rename' -import { isWslMoveRepoBlocked } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' +import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' import { clearFirstWorkGenerationFailures, isFirstWorkGenerationBackingOff, diff --git a/src/main/agent-hooks/first-work-folder-rename.ts b/src/main/agent-hooks/first-work/first-work-folder-rename.ts similarity index 84% rename from src/main/agent-hooks/first-work-folder-rename.ts rename to src/main/agent-hooks/first-work/first-work-folder-rename.ts index c0266646b97..e28630215d9 100644 --- a/src/main/agent-hooks/first-work-folder-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-folder-rename.ts @@ -1,13 +1,13 @@ -import type { Repo } from '../../shared/repo-types' +import type { Repo } from '../../../shared/repo-types' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem -} from '../../shared/worktree/id' -import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { planWorktreeFolderRename } from '../ipc/worktree-folder-rename-target' -import { hostWorktreeTargetForRepo } from '../persistence/host-qualified-worktree-meta' -import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' +} from '../../../shared/worktree/id' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { planWorktreeFolderRename } from '../../ipc/worktree-folder-rename-target' +import { hostWorktreeTargetForRepo } from '../../persistence/host-qualified-worktree-meta' +import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' export type FirstWorkFolderRenameDeps = { getRepo: (repoId: string) => Repo | undefined diff --git a/src/main/agent-hooks/first-work-generation-backoff.ts b/src/main/agent-hooks/first-work/first-work-generation-backoff.ts similarity index 94% rename from src/main/agent-hooks/first-work-generation-backoff.ts rename to src/main/agent-hooks/first-work/first-work-generation-backoff.ts index a3a0affccf2..76074de126c 100644 --- a/src/main/agent-hooks/first-work-generation-backoff.ts +++ b/src/main/agent-hooks/first-work/first-work-generation-backoff.ts @@ -1,4 +1,4 @@ -import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' +import type { AgentGenerationFailureOutput } from '../../text-generation/agent-failure-output' // Usage-limit failures spawned hundreds of sessions on repeated working events (#9705); back off until recovery. export const FIRST_WORK_GENERATION_RETRY_DELAYS_MS: readonly number[] = [30_000, 120_000, 1_800_000] diff --git a/src/main/agent-hooks/first-work-generation-target.ts b/src/main/agent-hooks/first-work/first-work-generation-target.ts similarity index 76% rename from src/main/agent-hooks/first-work-generation-target.ts rename to src/main/agent-hooks/first-work/first-work-generation-target.ts index 0409165fda2..a7cd93095dd 100644 --- a/src/main/agent-hooks/first-work-generation-target.ts +++ b/src/main/agent-hooks/first-work/first-work-generation-target.ts @@ -1,8 +1,8 @@ -import type { CommitMessageGenerationTarget } from '../text-generation/commit-message-text-generation' +import type { CommitMessageGenerationTarget } from '../../text-generation/commit-message-text-generation' import { prepareLocalCommitMessageAgentEnv, type CommitMessageAgentEnvironmentResolvers -} from '../text-generation/commit-message-agent-environment' +} from '../../text-generation/commit-message-agent-environment' export async function resolveGenerationTarget( worktreePath: string, diff --git a/src/main/agent-hooks/first-work-rename-runtime.ts b/src/main/agent-hooks/first-work/first-work-rename-runtime.ts similarity index 88% rename from src/main/agent-hooks/first-work-rename-runtime.ts rename to src/main/agent-hooks/first-work/first-work-rename-runtime.ts index ef5ee766811..42152d68a16 100644 --- a/src/main/agent-hooks/first-work-rename-runtime.ts +++ b/src/main/agent-hooks/first-work/first-work-rename-runtime.ts @@ -1,16 +1,16 @@ import { existsSync } from 'node:fs' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import type { FirstWorkBranchRenameDeps } from './first-work-branch-rename' import { rememberBranchRenameFailureOutput } from './branch-rename-failure-output' import { renameWorktreeFolderOnFirstWork } from './first-work-folder-rename' -import { moveWorktree } from '../git/worktrees/movement/worktree-move' -import { isWslMoveFolderWorkspaceBlocked } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' -import type { Store } from '../persistence/loading-store/store' -import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { resolveWorktreeMetaOwner } from '../persistence/host-qualified-worktree-meta' +import { moveWorktree } from '../../git/worktrees/movement/worktree-move' +import { isWslMoveFolderWorkspaceBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' +import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { resolveWorktreeMetaOwner } from '../../persistence/host-qualified-worktree-meta' const ENABLE_FIRST_WORK_FOLDER_RENAME = false diff --git a/src/main/agent-hooks/first-work-structured-session-rename.ts b/src/main/agent-hooks/first-work/first-work-structured-session-rename.ts similarity index 88% rename from src/main/agent-hooks/first-work-structured-session-rename.ts rename to src/main/agent-hooks/first-work/first-work-structured-session-rename.ts index 6b15d1f9acd..eac832483f2 100644 --- a/src/main/agent-hooks/first-work-structured-session-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-structured-session-rename.ts @@ -1,4 +1,4 @@ -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' +import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' import { maybeAutoRenameBranchOnFirstWork, type FirstWorkBranchRenameDeps diff --git a/src/main/agent-hooks/first-work-workspace-title-rename.ts b/src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts similarity index 94% rename from src/main/agent-hooks/first-work-workspace-title-rename.ts rename to src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts index d075d39c219..d7d98c4a678 100644 --- a/src/main/agent-hooks/first-work-workspace-title-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts @@ -1,8 +1,8 @@ -import { humanizeBranchSlug } from '../../shared/source-control/ai/naming/branch-name-from-work' +import { humanizeBranchSlug } from '../../../shared/source-control/ai/naming/branch-name-from-work' import { generateBranchNameFromContext, resolveTextGenerationParams -} from '../text-generation/commit-message-text-generation' +} from '../../text-generation/commit-message-text-generation' import { resolveGenerationTarget } from './first-work-generation-target' import type { FirstWorkBranchRenameDeps } from './first-work-branch-rename' import { retryFailedGeneration } from './first-work-generation-backoff' diff --git a/src/main/agent-hooks/first-work-branch-rename-test-harness.ts b/src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts similarity index 89% rename from src/main/agent-hooks/first-work-branch-rename-test-harness.ts rename to src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts index 2627651dec2..b2c48c53ce9 100644 --- a/src/main/agent-hooks/first-work-branch-rename-test-harness.ts +++ b/src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts @@ -1,12 +1,12 @@ import type { vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Repo } from '../../shared/repo-types' -import '../../shared/worktree/id' -import { WORKTREE_ID_SEPARATOR } from '../../shared/terminal/pty/lifecycle/pty-session-id-format' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { Repo } from '../../../../shared/repo-types' +import '../../../../shared/worktree/id' +import { WORKTREE_ID_SEPARATOR } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' import type { FirstWorkBranchRenameDeps, FirstWorkBranchRenameEvent -} from './first-work-branch-rename' +} from '../first-work-branch-rename' export const REPO_ID = 'repo1' export const WORKTREE_ID = `${REPO_ID}${WORKTREE_ID_SEPARATOR}/repo/wt` diff --git a/src/main/agent-hooks/agent-home-login-shell.ts b/src/main/agent-hooks/installation/agent-home-login-shell.ts similarity index 100% rename from src/main/agent-hooks/agent-home-login-shell.ts rename to src/main/agent-hooks/installation/agent-home-login-shell.ts diff --git a/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts new file mode 100644 index 00000000000..82b599b4a5e --- /dev/null +++ b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts @@ -0,0 +1,119 @@ +import { + getWindowsNativeHookAgent, + WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME +} from './windows-native-hook-executable' + +import type { HookCommandConfig, HookDefinition } from '../configuration/hook-config-schema' + +// Match script names so reinstalls sweep entries from old and parallel installations. +export function createManagedCommandMatcher( + scriptFileName: string +): (command: string | undefined) => boolean { + const scriptStem = scriptFileName.replace(/\.(?:cmd|ps1|sh)$/, '') + // Sweep every platform suffix after a platform switch. + const needles = [ + `agent-hooks/${scriptFileName}`, + `agent-hooks/${scriptStem}.cmd`, + `agent-hooks/${scriptStem}.ps1`, + `agent-hooks/${scriptStem}.sh` + ] + // The native executable selects its provider through argv[1]. + const nativeHook = `agent-hooks/${WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME} ${getWindowsNativeHookAgent(scriptFileName)} ` + return (command) => { + if (!command) { + return false + } + const decodedCommand = decodePowerShellEncodedCommand(command) + const searchText = decodedCommand ? `${command}\n${decodedCommand}` : command + const normalizedCommand = searchText.replaceAll('\\', '/') + return ( + needles.some((needle) => normalizedCommand.includes(needle)) || + normalizedCommand.split('\n').some((line) => `${line} `.includes(nativeHook)) + ) + } +} + +function decodePowerShellEncodedCommand(command: string): string | null { + const match = command.match(/\s-EncodedCommand\s+(\S+)/i) + if (!match) { + return null + } + try { + return Buffer.from(match[1], 'base64').toString('utf16le') + } catch { + return null + } +} + +export function removeManagedCommands( + definitions: HookDefinition[], + isManagedCommand: (command: string | undefined) => boolean +): HookDefinition[] { + return definitions.flatMap((definition) => { + const directCommandKeys = ['command', 'bash', 'powershell'] as const + const directManagedKeys = directCommandKeys.filter((key) => isManagedCommand(definition[key])) + const hasNestedHooks = Array.isArray(definition.hooks) + const hasManagedNestedHook = + hasNestedHooks && + definition.hooks!.some((hook) => hookHasManagedCommand(hook, isManagedCommand)) + + if (directManagedKeys.length === 0 && !hasManagedNestedHook) { + return [definition] + } + + const nextDefinition: HookDefinition = { ...definition } + for (const key of directManagedKeys) { + delete nextDefinition[key] + } + + if (hasManagedNestedHook) { + const filteredHooks = definition.hooks!.filter( + (hook) => !hookHasManagedCommand(hook, isManagedCommand) + ) + if (filteredHooks.length > 0) { + nextDefinition.hooks = filteredHooks + } else { + delete nextDefinition.hooks + } + } + + const hasCommandAfterCleanup = + directCommandKeys.some((key) => typeof nextDefinition[key] === 'string') || + (Array.isArray(nextDefinition.hooks) && nextDefinition.hooks.length > 0) + if (!hasCommandAfterCleanup) { + return [] + } + + return [nextDefinition] + }) +} + +function hookHasManagedCommand(hook: HookCommandConfig, matches: (value?: string) => boolean) { + const args = Array.isArray(hook.args) ? hook.args : [] + return matches(hook.command) || args.some((arg) => typeof arg === 'string' && matches(arg)) +} + +// Users may opt a managed hook into async; keep that choice when the hook is rewritten. +export function withPreviousManagedAsync( + hook: HookCommandConfig, + definitions: HookDefinition[], + matches: (command: string | undefined) => boolean +): HookCommandConfig { + const async = definitions + .flatMap((definition) => (Array.isArray(definition.hooks) ? definition.hooks : [])) + .find((prev) => typeof prev.async === 'boolean' && hookHasManagedCommand(prev, matches))?.async + return async === undefined ? hook : { ...hook, async } +} + +export function hookDefinitionHasManagedCommand( + definition: HookDefinition, + isManagedCommand: (command: string | undefined) => boolean +): boolean { + return ( + isManagedCommand(definition.command) || + isManagedCommand(definition.bash) || + isManagedCommand(definition.powershell) || + (Array.isArray(definition.hooks) && + definition.hooks.some((hook) => hookHasManagedCommand(hook, isManagedCommand))) + ) +} diff --git a/src/main/agent-hooks/posix-hook-command.ts b/src/main/agent-hooks/installation/commands/posix-hook-command.ts similarity index 87% rename from src/main/agent-hooks/posix-hook-command.ts rename to src/main/agent-hooks/installation/commands/posix-hook-command.ts index 4b5b6a27651..8413c466d1e 100644 --- a/src/main/agent-hooks/posix-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/posix-hook-command.ts @@ -1,5 +1,5 @@ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from './hook-stdin-contract' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../scripts/hook-stdin-contract' // Missing scripts must become silent no-ops rather than fail every tool call. export function wrapPosixHookCommand( diff --git a/src/main/agent-hooks/runtime-home-hook-command.ts b/src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts similarity index 97% rename from src/main/agent-hooks/runtime-home-hook-command.ts rename to src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts index 30b446ca652..bccb999d740 100644 --- a/src/main/agent-hooks/runtime-home-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts @@ -1,9 +1,9 @@ -import { HOOK_PARENT_CAPTURE } from './hook-process-capture' +import { HOOK_PARENT_CAPTURE } from '../scripts/hook-process-capture' import { POSIX_HOOK_STDIN_DRAIN_COMMAND, WINDOWS_GIT_BASH_HOOK_ENVIRONMENT_GUARD, WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD -} from './hook-stdin-contract' +} from '../scripts/hook-stdin-contract' import { encodeWindowsPowerShellHookCommand, WINDOWS_POWERSHELL_HOOK_SWITCHES diff --git a/src/main/agent-hooks/managed-hook-command-env.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/managed-hook-command-env.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-command-env.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/managed-hook-command-env.test-fixture.ts diff --git a/src/main/agent-hooks/windows-git-bash-path.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/windows-git-bash-path.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture.ts diff --git a/src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts similarity index 93% rename from src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts index 627344e1d8d..ce599a059dd 100644 --- a/src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts +++ b/src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts @@ -1,7 +1,7 @@ import { runProcessSync } from '@orca/process-host' import { join, resolve } from 'node:path' -const REPO_ROOT = resolve(import.meta.dirname, '../../..') +const REPO_ROOT = resolve(import.meta.dirname, '../../../../../..') const BUILD_OUTPUT = join( REPO_ROOT, 'native', diff --git a/src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts similarity index 90% rename from src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts index 8a71bf49c09..646af426d11 100644 --- a/src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts +++ b/src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts @@ -1,6 +1,6 @@ import { runProcess } from '@orca/process-host' import { expect } from 'vitest' -import { wrapWindowsHookCommand } from './installer-utils' +import { wrapWindowsHookCommand } from '../windows-hook-command' // A fresh runner's first encoded-PowerShell launch took 5-40s; per-hook bounds detect stdin hangs, not cold start. export const WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS = 90_000 diff --git a/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts b/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts new file mode 100644 index 00000000000..27063100583 --- /dev/null +++ b/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts @@ -0,0 +1,42 @@ +import type { AgentHookSource } from '../../../../shared/agent-hook-listener/transport/agent-hook-relay' + +/** Extra form lines precede payload@- and must end with ` ^`. */ +export function buildWindowsAgentHookPostCommand( + source: AgentHookSource, + extraFormLines: readonly string[] = [] +): string { + // Avoid PowerShell startup; qualify curl to prevent repo-local payload interception. + return [ + `"%SystemRoot%\\System32\\curl.exe" -sS -X POST "http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}" ^`, + ' --connect-timeout 0.5 --max-time 1.5 ^', + ' -H "Content-Type: application/x-www-form-urlencoded" ^', + ' -H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%" ^', + ' --data-urlencode "paneKey=%ORCA_PANE_KEY%" ^', + ' --data-urlencode "tabId=%ORCA_TAB_ID%" ^', + ' --data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%" ^', + ' --data-urlencode "worktreeId=%ORCA_WORKTREE_ID%" ^', + ' --data-urlencode "env=%ORCA_AGENT_HOOK_ENV%" ^', + ' --data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%" ^', + ...extraFormLines, + ' --data-urlencode "payload@-" >nul 2>nul' + ].join('\r\n') +} + +// curl.exe avoids PowerShell startup and code-page corruption of UTF-8 payloads. +export function buildWindowsAgentHookCurlPostCommand(source: AgentHookSource): string { + return [ + '"%SystemRoot%\\System32\\curl.exe" -sS -X POST', + `"http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}"`, + '--connect-timeout 0.5 --max-time 1.5', + '-H "Content-Type: application/x-www-form-urlencoded"', + '-H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%"', + '--data-urlencode "paneKey=%ORCA_PANE_KEY%"', + '--data-urlencode "tabId=%ORCA_TAB_ID%"', + '--data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%"', + '--data-urlencode "worktreeId=%ORCA_WORKTREE_ID%"', + '--data-urlencode "env=%ORCA_AGENT_HOOK_ENV%"', + '--data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%"', + '--data-urlencode "payload@-"', + '>nul 2>&1' + ].join(' ') +} diff --git a/src/main/agent-hooks/windows-batch-hook-launcher.test.ts b/src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts similarity index 93% rename from src/main/agent-hooks/windows-batch-hook-launcher.test.ts rename to src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts index a2ba64ac858..11dd2824b3f 100644 --- a/src/main/agent-hooks/windows-batch-hook-launcher.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts @@ -3,10 +3,10 @@ import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import '../claude/hook-settings' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import '../../../claude/hook-settings' import { wrapWindowsBatchHookCommand } from './windows-direct-cmd-hook-command' -import './windows-git-bash-path.test-fixture' +import './testing/windows-git-bash-path.test-fixture' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' describe.skipIf(process.platform !== 'win32')('guarded Windows batch hook commands', () => { diff --git a/src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts b/src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts similarity index 93% rename from src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts rename to src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts index c00ddf9e26b..54a4d77aa41 100644 --- a/src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts @@ -5,22 +5,18 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as osModule from 'node:os' import { runProcess } from '@orca/process-host' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { - isPlainObject, - readHooksJson, - WINDOWS_CMD_SAFE_PATH, - wrapWindowsHookCommand, - writeHooksJson -} from './installer-utils' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { isPlainObject, readHooksJson } from '../configuration/hooks-json-read' +import { WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './windows-hook-command' +import { writeHooksJson } from '../configuration/hooks-json-write' import { wrapWindowsBatchHookCommand, wrapWindowsDirectCmdHookCommand } from './windows-direct-cmd-hook-command' -import { AntigravityHookService } from '../antigravity/hook-service' -import { ANTIGRAVITY_EVENTS } from '../antigravity/hook-events' +import { AntigravityHookService } from '../../../antigravity/hook-service' +import { ANTIGRAVITY_EVENTS } from '../../../antigravity/hook-events' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) vi.mock('electron', () => ({ app: { getPath: () => process.cwd() } })) diff --git a/src/main/agent-hooks/windows-direct-cmd-hook-command.ts b/src/main/agent-hooks/installation/commands/windows-direct-cmd-hook-command.ts similarity index 100% rename from src/main/agent-hooks/windows-direct-cmd-hook-command.ts rename to src/main/agent-hooks/installation/commands/windows-direct-cmd-hook-command.ts diff --git a/src/main/agent-hooks/windows-hook-command.ts b/src/main/agent-hooks/installation/commands/windows-hook-command.ts similarity index 90% rename from src/main/agent-hooks/windows-hook-command.ts rename to src/main/agent-hooks/installation/commands/windows-hook-command.ts index ed6a5d6797c..99bd67a669e 100644 --- a/src/main/agent-hooks/windows-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/windows-hook-command.ts @@ -1,5 +1,5 @@ -import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' -import { WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD } from './hook-stdin-contract' +import { quotePowerShellLiteral } from '../../../../shared/powershell-native-argument' +import { WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD } from '../scripts/hook-stdin-contract' import { wrapWindowsPowerShellEncodedCommand, type WindowsPowerShellHookOptions diff --git a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts b/src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts similarity index 93% rename from src/main/agent-hooks/windows-hook-payload-delivery.test.ts rename to src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts index 424d4d95549..f2da1c10215 100644 --- a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { createServer, type Server } from 'node:http' import { lstatSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +import { removeTreeSync } from '../../../../shared/windows-transient-lock-removal' import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import type * as osModule from 'node:os' @@ -34,30 +34,31 @@ vi.mock('os', async (importOriginal) => { } }) -import { ClaudeHookService } from '../claude/hook-service' -import { CommandCodeHookService } from '../command-code/hook-service' -import { CopilotHookService } from '../copilot/hook-service' -import { DroidHookService } from '../droid/hook-service' -import { DevinHookService } from '../devin/hook-service' -import { DshHookService } from '../dsh/hook-service' -import { GeminiHookService } from '../gemini/hook-service' -import { GrokHookService } from '../grok/hook-service' -import { KimiHookService } from '../kimi/hook-service' -import { KiroHookService } from '../kiro/hook-service' -import { MuseHookService } from '../muse/hook-service' -import { getMuseManagedHooksPath } from '../muse/hook-settings' -import { zcodeHookService } from '../zcode/hook-service' -import { readHooksJson, WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './installer-utils' -import { getConfigPath } from '../claude/hook-settings' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import { ClaudeHookService } from '../../../claude/hook-service' +import { CommandCodeHookService } from '../../../command-code/hook-service' +import { CopilotHookService } from '../../../copilot/hook-service' +import { DroidHookService } from '../../../droid/hook-service' +import { DevinHookService } from '../../../devin/hook-service' +import { DshHookService } from '../../../dsh/hook-service' +import { GeminiHookService } from '../../../gemini/hook-service' +import { GrokHookService } from '../../../grok/hook-service' +import { KimiHookService } from '../../../kimi/hook-service' +import { KiroHookService } from '../../../kiro/hook-service' +import { MuseHookService } from '../../../muse/hook-service' +import { getMuseManagedHooksPath } from '../../../muse/hook-settings' +import { zcodeHookService } from '../../../zcode/hook-service' +import { readHooksJson } from '../configuration/hooks-json-read' +import { WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './windows-hook-command' +import { getConfigPath } from '../../../claude/hook-settings' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' +} from './testing/windows-native-hook-exe.test-fixture' import { WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS, warmWindowsEncodedPowerShell -} from './windows-powershell-warm-up.test-fixture' +} from './testing/windows-powershell-warm-up.test-fixture' const PANE_KEY = 'tab-1:leaf-1' const HOOK_TOKEN = 'payload-delivery-token' diff --git a/src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts b/src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts similarity index 95% rename from src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts rename to src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts index ea65d89829b..61448369a28 100644 --- a/src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts @@ -4,16 +4,16 @@ import { createServer, type IncomingMessage, type Server } from 'node:http' import { copyFileSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { getManagedScript } from '../claude/hook-script' -import { CLAUDE_HOOK_SETTINGS, getManagedLifecycleHook } from '../claude/hook-settings' -import { getWindowsClaudeHookEntry } from '../claude/windows-hook-files' -import { WINDOWS_CMD_SAFE_PATH } from './installer-utils' +import { removeTreeSync } from '../../../../shared/windows-transient-lock-removal' +import { getManagedScript } from '../../../claude/hook-script' +import { CLAUDE_HOOK_SETTINGS, getManagedLifecycleHook } from '../../../claude/hook-settings' +import { getWindowsClaudeHookEntry } from '../../../claude/windows-hook-files' +import { WINDOWS_CMD_SAFE_PATH } from './windows-hook-command' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' -import { findGitBash } from './windows-git-bash-path.test-fixture' +} from './testing/windows-native-hook-exe.test-fixture' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' const PAYLOAD = JSON.stringify({ diff --git a/src/main/agent-hooks/windows-native-hook-executable.ts b/src/main/agent-hooks/installation/commands/windows-native-hook-executable.ts similarity index 100% rename from src/main/agent-hooks/windows-native-hook-executable.ts rename to src/main/agent-hooks/installation/commands/windows-native-hook-executable.ts diff --git a/src/main/agent-hooks/windows-powershell-hook-launcher.test.ts b/src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts similarity index 100% rename from src/main/agent-hooks/windows-powershell-hook-launcher.test.ts rename to src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts diff --git a/src/main/agent-hooks/windows-powershell-hook-launcher.ts b/src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.ts similarity index 100% rename from src/main/agent-hooks/windows-powershell-hook-launcher.ts rename to src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.ts diff --git a/src/main/agent-hooks/installation/configuration/hook-config-schema.ts b/src/main/agent-hooks/installation/configuration/hook-config-schema.ts new file mode 100644 index 00000000000..34d6b679b71 --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hook-config-schema.ts @@ -0,0 +1,40 @@ +export type HookCommandConfig = { + type: 'command' + command: string + args?: string[] + timeout?: number + async?: boolean + statusMessage?: string + [key: string]: unknown +} + +export type HookDefinition = { + matcher?: string + command?: string + bash?: string + powershell?: string + hooks?: HookCommandConfig[] + [key: string]: unknown +} + +export type HooksConfig = { + hooks?: Record + [key: string]: unknown +} + +// Host-level backstop independent of curl and provider-specific timeouts. +export const MANAGED_HOOK_TIMEOUT_SECONDS = 10 + +export const MANAGED_HOOK_TIMEOUT_MILLISECONDS = MANAGED_HOOK_TIMEOUT_SECONDS * 1000 + +// Claude-shaped schemas nest command hooks; Cursor puts command on the definition itself. +export function buildManagedCommandHook( + command: string, + timeout = MANAGED_HOOK_TIMEOUT_SECONDS +): HookCommandConfig { + return { type: 'command', command, timeout } +} + +export function buildManagedCommandDefinition(command: string): HookDefinition { + return { command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } +} diff --git a/src/main/agent-hooks/hook-config-write-path.ts b/src/main/agent-hooks/installation/configuration/hook-config-write-path.ts similarity index 100% rename from src/main/agent-hooks/hook-config-write-path.ts rename to src/main/agent-hooks/installation/configuration/hook-config-write-path.ts diff --git a/src/main/agent-hooks/hooks-json-read.ts b/src/main/agent-hooks/installation/configuration/hooks-json-read.ts similarity index 90% rename from src/main/agent-hooks/hooks-json-read.ts rename to src/main/agent-hooks/installation/configuration/hooks-json-read.ts index 066dbe53f3e..42c125c00f6 100644 --- a/src/main/agent-hooks/hooks-json-read.ts +++ b/src/main/agent-hooks/installation/configuration/hooks-json-read.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import type { HooksConfig } from './installer-utils' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import type { HooksConfig } from './hook-config-schema' export function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) diff --git a/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts b/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts new file mode 100644 index 00000000000..3861f7898e1 --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts @@ -0,0 +1,69 @@ +import { randomUUID } from 'node:crypto' +import type { SFTPWrapper } from 'ssh2' +import type { HooksConfig } from './hook-config-schema' +import { parseHooksJsonText } from './hooks-json-read' +import { + DEFAULT_REMOTE_CONFIG_MODE, + readFile, + writeFile, + getRemoteFileModeOrDefault, + rename, + unlink, + chmod, + mkdirpRemote, + dirnamePosix, + isNoEntryError +} from '../remote/hook-sftp-operations' + +/** Null means invalid JSON, {} means missing; propagate other I/O failures. */ +export async function readHooksJsonRemote( + sftp: SFTPWrapper, + remotePath: string +): Promise { + let body: string + try { + body = await readFile(sftp, remotePath) + } catch (err) { + if (isNoEntryError(err)) { + return {} + } + throw err + } + return parseHooksJsonText(body) +} + +/** Atomically replace the remote config without rotating local-style backups. */ +export async function writeHooksJsonRemote( + sftp: SFTPWrapper, + remotePath: string, + config: Record, + // JSONC callers can supply text edited in place. + options?: { serialized?: string } +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` + // Preserve mtime and inode on repeated installs. + try { + const existing = await readFile(sftp, remotePath) + if (existing === serialized) { + return + } + } catch { + // Retry through the write path after a failed read. + } + // Atomic replacement prevents interrupted writes from truncating live settings. + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) + await writeFile(sftp, tmp, serialized, mode) + await chmod(sftp, tmp, mode) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/hooks-json-write-async.ts b/src/main/agent-hooks/installation/configuration/hooks-json-write-async.ts similarity index 100% rename from src/main/agent-hooks/hooks-json-write-async.ts rename to src/main/agent-hooks/installation/configuration/hooks-json-write-async.ts diff --git a/src/main/agent-hooks/installation/configuration/hooks-json-write.ts b/src/main/agent-hooks/installation/configuration/hooks-json-write.ts new file mode 100644 index 00000000000..caee6ca49eb --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hooks-json-write.ts @@ -0,0 +1,71 @@ +import { + existsSync, + mkdirSync, + readFileSync, + statSync, + writeFileSync, + chmodSync, + renameSync, + unlinkSync +} from 'node:fs' + +import { dirname, join } from 'node:path' + +import { randomUUID } from 'node:crypto' +import { resolveHooksJsonWritePath } from './hook-config-write-path' +import { writeRollingFileBackup } from '../../../filesystem/rolling-file-backup' + +export function writeHooksJson( + configPath: string, + // Fallback serialization accepts provider-specific JSON shapes, including nested hooks.events. + config: Record, + // JSONC callers supply edited text while retaining atomic writes and backups. + options?: { preserveMode?: boolean; defaultMode?: number; serialized?: string } +): void { + const writePath = resolveHooksJsonWritePath(configPath) + const dir = dirname(writePath) + mkdirSync(dir, { recursive: true }) + + // Unique temp paths isolate concurrent writers and preserve the original on write failure. + const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) + const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` + // Preserve owner-only permissions: agent configs can contain API keys. + const existingMode = + options?.preserveMode !== false && existsSync(writePath) + ? statSync(writePath).mode & 0o777 + : options?.defaultMode + + // Identical reinstalls must not rotate away the last recoverable backup. + if (existsSync(writePath)) { + try { + if (readFileSync(writePath, 'utf-8') === serialized) { + return + } + } catch { + // Retry through the write path after a failed read. + } + } + + try { + // Windows read-only mode could prevent deleting a failed temporary write. + const tmpMode = process.platform === 'win32' ? undefined : existingMode + writeFileSync(tmpPath, serialized, { encoding: 'utf-8', mode: tmpMode, flag: 'wx' }) + if (existingMode !== undefined && process.platform !== 'win32') { + // Preserve requested permissions even with a stricter process umask. + chmodSync(tmpPath, existingMode) + } + // Keep one prior version for recovery from a bad merge. + if (existsSync(writePath)) { + writeRollingFileBackup(writePath, `${writePath}.bak`) + } + renameSync(tmpPath, writePath) + } finally { + if (existsSync(tmpPath)) { + try { + unlinkSync(tmpPath) + } catch { + // best effort + } + } + } +} diff --git a/src/main/agent-hooks/managed-hooks-json-events.ts b/src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts similarity index 94% rename from src/main/agent-hooks/managed-hooks-json-events.ts rename to src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts index fac57d23e64..f786474bc5b 100644 --- a/src/main/agent-hooks/managed-hooks-json-events.ts +++ b/src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts @@ -1,4 +1,4 @@ -import { isPlainObject } from './installer-utils' +import { isPlainObject } from './hooks-json-read' /** Treat malformed user-edited nodes as absent events when reporting installation status. */ export function readManagedHookEventsFromJson( diff --git a/src/main/agent-hooks/managed-toml-ownership.test.ts b/src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts similarity index 100% rename from src/main/agent-hooks/managed-toml-ownership.test.ts rename to src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts diff --git a/src/main/agent-hooks/managed-toml-ownership.ts b/src/main/agent-hooks/installation/configuration/managed-toml-ownership.ts similarity index 100% rename from src/main/agent-hooks/managed-toml-ownership.ts rename to src/main/agent-hooks/installation/configuration/managed-toml-ownership.ts diff --git a/src/main/agent-hooks/install-telemetry.ts b/src/main/agent-hooks/installation/install-telemetry.ts similarity index 63% rename from src/main/agent-hooks/install-telemetry.ts rename to src/main/agent-hooks/installation/install-telemetry.ts index 5502c07bb8c..b64fa1fce86 100644 --- a/src/main/agent-hooks/install-telemetry.ts +++ b/src/main/agent-hooks/installation/install-telemetry.ts @@ -1,6 +1,6 @@ -import { errnoCodeOrUnknown } from '../../shared/errno-code' -import type { HookInstallAgent } from '../../shared/telemetry-events' -import { track } from '../telemetry/client' +import { errnoCodeOrUnknown } from '../../../shared/errno-code' +import type { HookInstallAgent } from '../../../shared/telemetry-daemon-event-schemas' +import { track } from '../../telemetry/client' export function recordManagedHookInstallFailure(agent: HookInstallAgent, error: unknown): void { try { diff --git a/src/main/agent-hooks/local-agent-cli-presence.test.ts b/src/main/agent-hooks/installation/local-agent-cli-presence.test.ts similarity index 94% rename from src/main/agent-hooks/local-agent-cli-presence.test.ts rename to src/main/agent-hooks/installation/local-agent-cli-presence.test.ts index 56d19bac881..723e0fdb83c 100644 --- a/src/main/agent-hooks/local-agent-cli-presence.test.ts +++ b/src/main/agent-hooks/installation/local-agent-cli-presence.test.ts @@ -2,13 +2,13 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ManagedAgentHookTarget } from '../../shared/managed-agent-hook-targets' +import type { ManagedAgentHookTarget } from '../../../shared/managed-agent-hook-targets' import { detectLocalManagedAgentCliPresence } from './local-agent-cli-presence' const { mergePersistedWindowsPathAsyncMock } = vi.hoisted(() => ({ mergePersistedWindowsPathAsyncMock: vi.fn(async (_env: NodeJS.ProcessEnv) => undefined) })) -vi.mock('../pty/environment/windows-environment-path', () => ({ +vi.mock('../../pty/environment/windows-environment-path', () => ({ mergePersistedWindowsPathAsync: mergePersistedWindowsPathAsyncMock })) diff --git a/src/main/agent-hooks/local-agent-cli-presence.ts b/src/main/agent-hooks/installation/local-agent-cli-presence.ts similarity index 91% rename from src/main/agent-hooks/local-agent-cli-presence.ts rename to src/main/agent-hooks/installation/local-agent-cli-presence.ts index 76d44cf188b..4533059fcf3 100644 --- a/src/main/agent-hooks/local-agent-cli-presence.ts +++ b/src/main/agent-hooks/installation/local-agent-cli-presence.ts @@ -2,22 +2,22 @@ import { constants } from 'node:fs' import { access, stat } from 'node:fs/promises' import { homedir } from 'node:os' import path from 'node:path' -import type { AgentHookTarget } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { AgentHookTarget } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { extractExecutableToken, hasPathSeparatorToken, isSafeExecutableBasename -} from '../../shared/managed-agent-command-token' -import type { ManagedAgentHookTarget } from '../../shared/managed-agent-hook-targets' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { mapWithConcurrency } from '../../shared/map-with-concurrency' -import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' -import { mergePersistedWindowsPathAsync } from '../pty/environment/windows-environment-path' -import { resolvePathEnvKey } from '../pty/environment/windows-path-segment-merge' +} from '../../../shared/managed-agent-command-token' +import type { ManagedAgentHookTarget } from '../../../shared/managed-agent-hook-targets' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import { hydrateShellPath, mergePathSegments } from '../../startup/hydrate-shell-path' +import { mergePersistedWindowsPathAsync } from '../../pty/environment/windows-environment-path' +import { resolvePathEnvKey } from '../../pty/environment/windows-path-segment-merge' import { isUnderWindowsDriveMount, readGuestWindowsDriveMounts -} from '../ipc/wsl-guest-windows-drive-path' +} from '../../ipc/wsl-guest-windows-drive-path' export type LocalCliPresenceState = 'found' | 'missing' | 'unknown' export type LocalCliPresenceByAgent = Partial< diff --git a/src/main/agent-hooks/managed-hook-install-lock.test.ts b/src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-install-lock.test.ts rename to src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts diff --git a/src/main/agent-hooks/managed-hook-install-lock.ts b/src/main/agent-hooks/installation/locking/managed-hook-install-lock.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-install-lock.ts rename to src/main/agent-hooks/installation/locking/managed-hook-install-lock.ts diff --git a/src/main/agent-hooks/managed-hook-lock-claims.ts b/src/main/agent-hooks/installation/locking/managed-hook-lock-claims.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-lock-claims.ts rename to src/main/agent-hooks/installation/locking/managed-hook-lock-claims.ts diff --git a/src/main/agent-hooks/managed-hook-lock-records.ts b/src/main/agent-hooks/installation/locking/managed-hook-lock-records.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-lock-records.ts rename to src/main/agent-hooks/installation/locking/managed-hook-lock-records.ts diff --git a/src/main/agent-hooks/managed-hook-owner-identity.ts b/src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-owner-identity.ts rename to src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts diff --git a/src/main/agent-hooks/managed-agent-hook-controls.test.ts b/src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts similarity index 99% rename from src/main/agent-hooks/managed-agent-hook-controls.test.ts rename to src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts index 3bbd19f82e8..5a2cf7af25e 100644 --- a/src/main/agent-hooks/managed-agent-hook-controls.test.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts @@ -19,7 +19,7 @@ vi.mock('./local-agent-cli-presence', () => ({ detectLocalManagedAgentCliPresence: mocks.detect })) -vi.mock('../claude/claude-hook-event-versions', () => ({ +vi.mock('../../claude/claude-hook-event-versions', () => ({ probeClaudeCliVersion: mocks.probeClaudeVersion })) diff --git a/src/main/agent-hooks/managed-agent-hook-controls.ts b/src/main/agent-hooks/installation/managed-agent-hook-controls.ts similarity index 94% rename from src/main/agent-hooks/managed-agent-hook-controls.ts rename to src/main/agent-hooks/installation/managed-agent-hook-controls.ts index 00868c771cb..76e1e46da60 100644 --- a/src/main/agent-hooks/managed-agent-hook-controls.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-controls.ts @@ -1,18 +1,18 @@ import type { AgentHookInstallStatus, AgentHookTarget -} from '../../shared/agent-hook-listener/configuration/agent-hook-types' +} from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { getManagedAgentHookTarget, isManagedAgentHookTarget -} from '../../shared/managed-agent-hook-targets' -import { normalizeDisabledTuiAgents } from '../../shared/agent-launch/catalog/tui-agent-selection' -import type { GlobalSettings } from '../../shared/global-settings-types' +} from '../../../shared/managed-agent-hook-targets' +import { normalizeDisabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection' +import type { GlobalSettings } from '../../../shared/global-settings-types' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { probeClaudeCliVersion } from '../claude/claude-hook-event-versions' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { probeClaudeCliVersion } from '../../claude/claude-hook-event-versions' import { detectLocalManagedAgentCliPresence } from './local-agent-cli-presence' import { MANAGED_AGENT_HOOK_ASYNC_REMOVERS, diff --git a/src/main/agent-hooks/managed-agent-hook-registry.ts b/src/main/agent-hooks/installation/managed-agent-hook-registry.ts similarity index 79% rename from src/main/agent-hooks/managed-agent-hook-registry.ts rename to src/main/agent-hooks/installation/managed-agent-hook-registry.ts index 9b272d5d420..91feaeae5d8 100644 --- a/src/main/agent-hooks/managed-agent-hook-registry.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-registry.ts @@ -1,27 +1,27 @@ -import { codebuddyHookService } from '../codebuddy/hook-service' -import { qwenCodeHookService } from '../qwen-code/hook-service' -import { qoderCnHookService, qoderHookService } from '../qoder/hook-service' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import type { HookInstallAgent } from '../../shared/telemetry-events' -import { ampHookService } from '../amp/hook-service' -import { antigravityHookService } from '../antigravity/hook-service' -import { claudeHookService } from '../claude/hook-service' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import { commandCodeHookService } from '../command-code/hook-service' -import { copilotHookService } from '../copilot/hook-service' -import { cursorHookService } from '../cursor/hook-service' -import { devinHookService } from '../devin/hook-service' -import { dshHookService } from '../dsh/hook-service' -import { droidHookService } from '../droid/hook-service' -import { geminiHookService } from '../gemini/hook-service' -import { grokHookService } from '../grok/hook-service' -import { hermesHookService } from '../hermes/hook-service' -import { jcodeHookService } from '../jcode/hook-service' -import { kimiHookService } from '../kimi/hook-service' -import { kiroHookService } from '../kiro/hook-service' -import { museHookService } from '../muse/hook-service' -import { openClaudeHookService } from '../openclaude/hook-service' -import { zcodeHookService } from '../zcode/hook-service' +import { codebuddyHookService } from '../../codebuddy/hook-service' +import { qwenCodeHookService } from '../../qwen-code/hook-service' +import { qoderCnHookService, qoderHookService } from '../../qoder/hook-service' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { HookInstallAgent } from '../../../shared/telemetry-daemon-event-schemas' +import { ampHookService } from '../../amp/hook-service' +import { antigravityHookService } from '../../antigravity/hook-service' +import { claudeHookService } from '../../claude/hook-service' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import { commandCodeHookService } from '../../command-code/hook-service' +import { copilotHookService } from '../../copilot/hook-service' +import { cursorHookService } from '../../cursor/hook-service' +import { devinHookService } from '../../devin/hook-service' +import { dshHookService } from '../../dsh/hook-service' +import { droidHookService } from '../../droid/hook-service' +import { geminiHookService } from '../../gemini/hook-service' +import { grokHookService } from '../../grok/hook-service' +import { hermesHookService } from '../../hermes/hook-service' +import { jcodeHookService } from '../../jcode/hook-service' +import { kimiHookService } from '../../kimi/hook-service' +import { kiroHookService } from '../../kiro/hook-service' +import { museHookService } from '../../muse/hook-service' +import { openClaudeHookService } from '../../openclaude/hook-service' +import { zcodeHookService } from '../../zcode/hook-service' export type ManagedAgentHookInstallOptions = { userInitiated?: boolean; cliVersion?: string } export type ManagedAgentHookInstaller = readonly [ diff --git a/src/main/agent-hooks/managed-agent-hook-startup.ts b/src/main/agent-hooks/installation/managed-agent-hook-startup.ts similarity index 100% rename from src/main/agent-hooks/managed-agent-hook-startup.ts rename to src/main/agent-hooks/installation/managed-agent-hook-startup.ts diff --git a/src/main/agent-hooks/managed-hook-detection-commands.ts b/src/main/agent-hooks/installation/managed-hook-detection-commands.ts similarity index 77% rename from src/main/agent-hooks/managed-hook-detection-commands.ts rename to src/main/agent-hooks/installation/managed-hook-detection-commands.ts index 274a43a930d..0378b0aba67 100644 --- a/src/main/agent-hooks/managed-hook-detection-commands.ts +++ b/src/main/agent-hooks/installation/managed-hook-detection-commands.ts @@ -1,13 +1,13 @@ -import type { AgentHookTarget } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { AgentHookTarget } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { extractExecutableToken, isSafeOverrideExecutableToken -} from '../../shared/managed-agent-command-token' -import { MANAGED_AGENT_HOOK_TARGETS } from '../../shared/managed-agent-hook-targets' -import { normalizeDisabledTuiAgents } from '../../shared/agent-launch/catalog/tui-agent-selection' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { TuiAgentDetectionCommand } from '../../shared/agent-launch/catalog/tui-agent-detection-commands' -import { parseClaudeCliVersionOutput } from '../claude/claude-hook-event-versions' +} from '../../../shared/managed-agent-command-token' +import { MANAGED_AGENT_HOOK_TARGETS } from '../../../shared/managed-agent-hook-targets' +import { normalizeDisabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { TuiAgentDetectionCommand } from '../../../shared/agent-launch/catalog/tui-agent-detection-commands' +import { parseClaudeCliVersionOutput } from '../../claude/claude-hook-event-versions' export type ManagedHookDetectionSettings = Partial< Pick< diff --git a/src/main/agent-hooks/opencode-plugin-settings.ts b/src/main/agent-hooks/installation/opencode-plugin-settings.ts similarity index 85% rename from src/main/agent-hooks/opencode-plugin-settings.ts rename to src/main/agent-hooks/installation/opencode-plugin-settings.ts index 8514cba992b..6818153fb7a 100644 --- a/src/main/agent-hooks/opencode-plugin-settings.ts +++ b/src/main/agent-hooks/installation/opencode-plugin-settings.ts @@ -1,5 +1,5 @@ -import type { PluginSources } from '../../wsl-guest/plugin-overlay' -import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' +import { isAgentStatusHooksEnabledForAgent } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' function enabled(settings: ManagedHookDetectionSettings, agent: 'opencode' | 'opencode2'): boolean { diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/installation/remote-managed-hook-installers.ts similarity index 77% rename from src/main/agent-hooks/remote-managed-hook-installers.ts rename to src/main/agent-hooks/installation/remote-managed-hook-installers.ts index d73da317035..c95c3c871a9 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/installation/remote-managed-hook-installers.ts @@ -1,30 +1,30 @@ -import { codebuddyHookService } from '../codebuddy/hook-service' -import { qwenCodeHookService } from '../qwen-code/hook-service' -import { qoderCnHookService, qoderHookService } from '../qoder/hook-service' +import { codebuddyHookService } from '../../codebuddy/hook-service' +import { qwenCodeHookService } from '../../qwen-code/hook-service' +import { qoderCnHookService, qoderHookService } from '../../qoder/hook-service' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus, AgentHookTarget -} from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { ampHookService } from '../amp/hook-service' -import { claudeHookService } from '../claude/hook-service' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import { geminiHookService } from '../gemini/hook-service' -import { antigravityHookService } from '../antigravity/hook-service' -import { cursorHookService } from '../cursor/hook-service' -import { commandCodeHookService } from '../command-code/hook-service' -import { copilotHookService } from '../copilot/hook-service' -import { devinHookService } from '../devin/hook-service' -import { droidHookService } from '../droid/hook-service' -import { grokHookService } from '../grok/hook-service' -import { hermesHookService } from '../hermes/hook-service' -import { jcodeHookService } from '../jcode/hook-service' -import { kimiHookService } from '../kimi/hook-service' -import { kiroHookService } from '../kiro/hook-service' -import { dshHookService } from '../dsh/hook-service' -import { museHookService } from '../muse/hook-service' -import { zcodeHookService } from '../zcode/hook-service' -import { openClaudeHookService } from '../openclaude/hook-service' +} from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { ampHookService } from '../../amp/hook-service' +import { claudeHookService } from '../../claude/hook-service' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import { geminiHookService } from '../../gemini/hook-service' +import { antigravityHookService } from '../../antigravity/hook-service' +import { cursorHookService } from '../../cursor/hook-service' +import { commandCodeHookService } from '../../command-code/hook-service' +import { copilotHookService } from '../../copilot/hook-service' +import { devinHookService } from '../../devin/hook-service' +import { droidHookService } from '../../droid/hook-service' +import { grokHookService } from '../../grok/hook-service' +import { hermesHookService } from '../../hermes/hook-service' +import { jcodeHookService } from '../../jcode/hook-service' +import { kimiHookService } from '../../kimi/hook-service' +import { kiroHookService } from '../../kiro/hook-service' +import { dshHookService } from '../../dsh/hook-service' +import { museHookService } from '../../muse/hook-service' +import { zcodeHookService } from '../../zcode/hook-service' +import { openClaudeHookService } from '../../openclaude/hook-service' export type RemoteManagedHookInstallOptions = { /** Redirected runtime CODEX_HOME, including managed WSL homes. */ diff --git a/src/main/agent-hooks/installer-utils-remote.ts b/src/main/agent-hooks/installation/remote/hook-sftp-operations.ts similarity index 51% rename from src/main/agent-hooks/installer-utils-remote.ts rename to src/main/agent-hooks/installation/remote/hook-sftp-operations.ts index 4ac7f9c655e..fb342c59d4d 100644 --- a/src/main/agent-hooks/installer-utils-remote.ts +++ b/src/main/agent-hooks/installation/remote/hook-sftp-operations.ts @@ -1,160 +1,9 @@ -// Share parsing and merge rules with local installation; replace only filesystem operations. - -import { randomUUID } from 'node:crypto' import type { SFTPWrapper, FileEntryWithStats } from 'ssh2' -import type { HooksConfig } from './installer-utils' -import { parseHooksJsonText } from './hooks-json-read' +export const DEFAULT_REMOTE_CONFIG_MODE = 0o600 -const DEFAULT_REMOTE_CONFIG_MODE = 0o600 const REMOTE_SFTP_OPERATION_TIMEOUT_MS = 10_000 -/** Null means invalid JSON, {} means missing; propagate other I/O failures. */ -export async function readHooksJsonRemote( - sftp: SFTPWrapper, - remotePath: string -): Promise { - let body: string - try { - body = await readFile(sftp, remotePath) - } catch (err) { - if (isNoEntryError(err)) { - return {} - } - throw err - } - return parseHooksJsonText(body) -} - -/** Atomically replace the remote config without rotating local-style backups. */ -export async function writeHooksJsonRemote( - sftp: SFTPWrapper, - remotePath: string, - config: Record, - // JSONC callers can supply text edited in place. - options?: { serialized?: string } -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` - // Preserve mtime and inode on repeated installs. - try { - const existing = await readFile(sftp, remotePath) - if (existing === serialized) { - return - } - } catch { - // Retry through the write path after a failed read. - } - // Atomic replacement prevents interrupted writes from truncating live settings. - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) - await writeFile(sftp, tmp, serialized, mode) - await chmod(sftp, tmp, mode) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - -/** POSIX SSH targets only: paths and script payloads follow POSIX conventions. */ -export async function writeManagedScriptRemote( - sftp: SFTPWrapper, - remotePath: string, - content: string -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - try { - const existing = await readFile(sftp, remotePath) - if (existing === content) { - await chmod(sftp, remotePath, 0o755) - return - } - } catch { - // Retry through the atomic write path after a failed read. - } - - // Publish only a complete executable script; existing configs may invoke it during reinstall. - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - await writeFile(sftp, tmp, content, 0o755) - await chmod(sftp, tmp, 0o755) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - -export async function readTextFileRemote( - sftp: SFTPWrapper, - remotePath: string -): Promise { - try { - return await readFile(sftp, remotePath) - } catch (err) { - if (isNoEntryError(err)) { - return null - } - throw err - } -} - -/** Null means the directory is missing; propagate other I/O failures. */ -export async function listRemoteDirectory( - sftp: SFTPWrapper, - remotePath: string -): Promise { - try { - return (await readdir(sftp, remotePath)).map((entry) => entry.filename) - } catch (err) { - if (isNoEntryError(err)) { - return null - } - throw err - } -} - -export async function writeTextFileRemoteAtomic( - sftp: SFTPWrapper, - remotePath: string, - content: string -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - try { - const existing = await readFile(sftp, remotePath) - if (existing === content) { - return - } - } catch { - // Retry through the atomic write path after a failed read. - } - - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) - await writeFile(sftp, tmp, content, mode) - await chmod(sftp, tmp, mode) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - function sftpOperation( label: string, run: (callback: (err: unknown, value?: T) => void) => void @@ -194,14 +43,14 @@ function sftpOperation( }) } -async function readFile(sftp: SFTPWrapper, remotePath: string): Promise { +export async function readFile(sftp: SFTPWrapper, remotePath: string): Promise { const data = await sftpOperation(`readFile ${remotePath}`, (callback) => { sftp.readFile(remotePath, 'utf8', callback) }) return typeof data === 'string' ? data : data.toString('utf8') } -async function writeFile( +export async function writeFile( sftp: SFTPWrapper, remotePath: string, content: string, @@ -221,7 +70,7 @@ async function statMode(sftp: SFTPWrapper, remotePath: string): Promise return stats.mode & 0o7777 } -async function getRemoteFileModeOrDefault( +export async function getRemoteFileModeOrDefault( sftp: SFTPWrapper, remotePath: string, defaultMode: number @@ -236,7 +85,7 @@ async function getRemoteFileModeOrDefault( } } -async function rename(sftp: SFTPWrapper, src: string, dst: string): Promise { +export async function rename(sftp: SFTPWrapper, src: string, dst: string): Promise { if (typeof sftp.ext_openssh_rename === 'function') { try { await renameOpenSsh(sftp, src, dst) @@ -264,19 +113,22 @@ async function renameOpenSsh(sftp: SFTPWrapper, src: string, dst: string): Promi }) } -async function unlink(sftp: SFTPWrapper, remotePath: string): Promise { +export async function unlink(sftp: SFTPWrapper, remotePath: string): Promise { await sftpOperation(`unlink ${remotePath}`, (callback) => { sftp.unlink(remotePath, callback) }) } -async function chmod(sftp: SFTPWrapper, remotePath: string, mode: number): Promise { +export async function chmod(sftp: SFTPWrapper, remotePath: string, mode: number): Promise { await sftpOperation(`chmod ${remotePath}`, (callback) => { sftp.chmod(remotePath, mode, callback) }) } -async function readdir(sftp: SFTPWrapper, remotePath: string): Promise { +export async function readdir( + sftp: SFTPWrapper, + remotePath: string +): Promise { return await sftpOperation(`readdir ${remotePath}`, (callback) => { sftp.readdir(remotePath, callback) }) @@ -288,7 +140,7 @@ async function mkdir(sftp: SFTPWrapper, remotePath: string): Promise { }) } -async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { +export async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { if (remotePath === '/' || remotePath === '' || remotePath === '.') { return } @@ -312,7 +164,7 @@ async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { + try { + return await readFile(sftp, remotePath) + } catch (err) { + if (isNoEntryError(err)) { + return null + } + throw err + } +} + +/** Null means the directory is missing; propagate other I/O failures. */ +export async function listRemoteDirectory( + sftp: SFTPWrapper, + remotePath: string +): Promise { + try { + return (await readdir(sftp, remotePath)).map((entry) => entry.filename) + } catch (err) { + if (isNoEntryError(err)) { + return null + } + throw err + } +} + +export async function writeTextFileRemoteAtomic( + sftp: SFTPWrapper, + remotePath: string, + content: string +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + try { + const existing = await readFile(sftp, remotePath) + if (existing === content) { + return + } + } catch { + // Retry through the atomic write path after a failed read. + } + + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) + await writeFile(sftp, tmp, content, mode) + await chmod(sftp, tmp, mode) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/agent-hook-memory-sftp.test-fixture.ts b/src/main/agent-hooks/installation/remote/testing/agent-hook-memory-sftp.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/agent-hook-memory-sftp.test-fixture.ts rename to src/main/agent-hooks/installation/remote/testing/agent-hook-memory-sftp.test-fixture.ts diff --git a/src/main/agent-hooks/managed-hook-local-filesystem.test-fixture.ts b/src/main/agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-local-filesystem.test-fixture.ts rename to src/main/agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture.ts diff --git a/src/main/agent-hooks/claude-background-job-guard.ts b/src/main/agent-hooks/installation/scripts/claude-background-job-guard.ts similarity index 100% rename from src/main/agent-hooks/claude-background-job-guard.ts rename to src/main/agent-hooks/installation/scripts/claude-background-job-guard.ts diff --git a/src/main/agent-hooks/cursor-replay-guard.test.ts b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts similarity index 77% rename from src/main/agent-hooks/cursor-replay-guard.test.ts rename to src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts index 82802ffd057..413ae77c29b 100644 --- a/src/main/agent-hooks/cursor-replay-guard.test.ts +++ b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) -import { runVendorHook } from './vendor-hook-delivery.test-fixture' +import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture' -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-service' -import { getManagedScript as getCursorManagedScript } from '../cursor/hook-script' +import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service' +import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script' const CLAUDE_SCRIPT_OPTIONS = { skipWhenDevinImportsClaude: true, diff --git a/src/main/agent-hooks/cursor-replay-guard.ts b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.ts similarity index 100% rename from src/main/agent-hooks/cursor-replay-guard.ts rename to src/main/agent-hooks/installation/scripts/cursor-replay-guard.ts diff --git a/src/main/agent-hooks/grok-replay-guard.test.ts b/src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts similarity index 85% rename from src/main/agent-hooks/grok-replay-guard.test.ts rename to src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts index 78407c2929e..b21f154bc0d 100644 --- a/src/main/agent-hooks/grok-replay-guard.test.ts +++ b/src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts @@ -2,9 +2,9 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-service' -import { getManagedScript as getCursorManagedScript } from '../cursor/hook-script' -import { runVendorHook } from './vendor-hook-delivery.test-fixture' +import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service' +import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script' +import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture' const CLAUDE_SCRIPT_OPTIONS = { skipWhenDevinImportsClaude: true, diff --git a/src/main/agent-hooks/grok-replay-guard.ts b/src/main/agent-hooks/installation/scripts/grok-replay-guard.ts similarity index 100% rename from src/main/agent-hooks/grok-replay-guard.ts rename to src/main/agent-hooks/installation/scripts/grok-replay-guard.ts diff --git a/src/main/agent-hooks/hook-post-command.ts b/src/main/agent-hooks/installation/scripts/hook-post-command.ts similarity index 94% rename from src/main/agent-hooks/hook-post-command.ts rename to src/main/agent-hooks/installation/scripts/hook-post-command.ts index 8cac17f0526..b0c6ce3e807 100644 --- a/src/main/agent-hooks/hook-post-command.ts +++ b/src/main/agent-hooks/installation/scripts/hook-post-command.ts @@ -1,6 +1,6 @@ -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { ORCA_HOOK_RAW_JSON_TRANSPORT } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { AGENT_HOOK_METADATA_CACHE_DIR } from '../../shared/agent-hook-listener/transport/agent-hook-spool' +import type { AgentHookSource } from '../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { ORCA_HOOK_RAW_JSON_TRANSPORT } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { AGENT_HOOK_METADATA_CACHE_DIR } from '../../../../shared/agent-hook-listener/transport/agent-hook-spool' // Older curl needs C numeric parsing; keep the parent script's UTF-8 locale unchanged. export function posixCurlCommand(curlCommand = 'curl'): string { diff --git a/src/main/agent-hooks/hook-process-capture.test.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts similarity index 85% rename from src/main/agent-hooks/hook-process-capture.test.ts rename to src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts index 6671f77ecea..bc749510993 100644 --- a/src/main/agent-hooks/hook-process-capture.test.ts +++ b/src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts @@ -3,10 +3,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { wrapRuntimeHomeHookCommand } from './runtime-home-hook-command' +import { wrapRuntimeHomeHookCommand } from '../commands/runtime-home-hook-command' import { buildHookProcessCapture } from './hook-process-capture' -import { readAgentProcessIdentity } from '../../shared/agent-status/process/agent-process-presence' -import { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { readAgentProcessIdentity } from '../../../../shared/agent-status/process/agent-process-presence' +import { probeAgentProcessPresence } from '../../../../shared/agent-status/process/agent-process-presence-probe' describe('Claude outer hook process capture', () => { it.skipIf(process.platform === 'win32').each([undefined, 'Asia/Tokyo'])( diff --git a/src/main/agent-hooks/hook-process-capture.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts similarity index 100% rename from src/main/agent-hooks/hook-process-capture.ts rename to src/main/agent-hooks/installation/scripts/hook-process-capture.ts diff --git a/src/main/agent-hooks/hook-script-outside-orca.test.ts b/src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts similarity index 98% rename from src/main/agent-hooks/hook-script-outside-orca.test.ts rename to src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts index 25c0abe3991..b94fcd9ac5a 100644 --- a/src/main/agent-hooks/hook-script-outside-orca.test.ts +++ b/src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts @@ -11,7 +11,7 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { getManagedScript } from '../codex/hooks/definitions/codex-hook-script' +import { getManagedScript } from '../../../codex/hooks/definitions/codex-hook-script' import { buildPosixHookSpoolLines } from './hook-stdin-contract' const roots: string[] = [] diff --git a/src/main/agent-hooks/hook-stdin-contract.ts b/src/main/agent-hooks/installation/scripts/hook-stdin-contract.ts similarity index 100% rename from src/main/agent-hooks/hook-stdin-contract.ts rename to src/main/agent-hooks/installation/scripts/hook-stdin-contract.ts diff --git a/src/main/agent-hooks/locked-executable-rename.test.ts b/src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts similarity index 100% rename from src/main/agent-hooks/locked-executable-rename.test.ts rename to src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts diff --git a/src/main/agent-hooks/locked-executable-rename.ts b/src/main/agent-hooks/installation/scripts/locked-executable-rename.ts similarity index 96% rename from src/main/agent-hooks/locked-executable-rename.ts rename to src/main/agent-hooks/installation/scripts/locked-executable-rename.ts index 091fbf83e3f..d45c90576ca 100644 --- a/src/main/agent-hooks/locked-executable-rename.ts +++ b/src/main/agent-hooks/installation/scripts/locked-executable-rename.ts @@ -1,6 +1,6 @@ import { existsSync, renameSync, rmSync } from 'node:fs' import { rename, rm, stat } from 'node:fs/promises' -import { isPermissionError } from '../filesystem/permission-errors' +import { isPermissionError } from '../../../filesystem/permission-errors' /** Windows permits renaming a running executable aside so a new build can take its path. */ export function getLockedExecutableAsidePath(targetPath: string): string { diff --git a/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts new file mode 100644 index 00000000000..d8bb5590c93 --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts @@ -0,0 +1,7 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' + +// Parallel Orca instances must share one user-wide script path. +export function getSharedManagedScriptPath(scriptFileName: string): string { + return join(homedir(), '.orca', 'agent-hooks', scriptFileName) +} diff --git a/src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts similarity index 96% rename from src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts index 77c5b3d5be7..24fcba35e5a 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import type * as NodeOsModule from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' const state = vi.hoisted((): { home: string; syncCalls: { name: string; target: string }[] } => ({ home: '', @@ -36,7 +36,7 @@ vi.mock('node:os', async (importOriginal) => { vi.mock('electron', () => ({ app: { getPath: () => '/tmp/orca-user-data' } })) -import { MANAGED_AGENT_HOOK_SCRIPT_REFRESHERS } from './managed-agent-hook-registry' +import { MANAGED_AGENT_HOOK_SCRIPT_REFRESHERS } from '../managed-agent-hook-registry' function syncCallsUnderHome(): string[] { return state.syncCalls diff --git a/src/main/agent-hooks/managed-hook-script-refresh.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts similarity index 94% rename from src/main/agent-hooks/managed-hook-script-refresh.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts index 761d77e7bff..067f10062fc 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as CodexHookHashLookup from '../codex/trust/hooks/codex-hook-hash-lookup' +import type * as CodexHookHashLookup from '../../../codex/trust/hooks/codex-hook-hash-lookup' import { existsSync, chmodSync, @@ -45,11 +45,11 @@ const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) -vi.mock('../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ +vi.mock('../../../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ ...(await importOriginal()), resolveCodexHookAnswerForLaunch: async () => ( - await import('../codex/hooks/installation/hook-service-test-harness') + await import('../../../codex/hooks/installation/hook-service-test-harness') ).codexHookAnswerForTests() })) @@ -68,7 +68,7 @@ vi.mock('os', async (importOriginal) => { }) import { refreshManagedScriptIfPresent } from './managed-hook-script-refresh' -import { ClaudeHookService } from '../claude/hook-service' +import { ClaudeHookService } from '../../../claude/hook-service' describe('refreshManagedScriptIfPresent', () => { it('rewrites an existing script and refuses to create a missing one', async () => { diff --git a/src/main/agent-hooks/managed-hook-script-refresh.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts similarity index 95% rename from src/main/agent-hooks/managed-hook-script-refresh.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts index a5a78c97a56..91c4a785b17 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { grantDirAclAsync } from '../windows/windows-directory-acl' -import { isPermissionError } from '../filesystem/permission-errors' +import { grantDirAclAsync } from '../../../windows/windows-directory-acl' +import { isPermissionError } from '../../../filesystem/permission-errors' import { renameOverLockedTargetAsync } from './locked-executable-rename' type ExistingScript = { exists: false } | { exists: true; content: Buffer | null } diff --git a/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts new file mode 100644 index 00000000000..101257aa580 --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts @@ -0,0 +1,67 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync } from 'node:fs' + +import { dirname, join } from 'node:path' + +import { randomUUID } from 'node:crypto' +import { grantDirAcl } from '../../../windows/windows-directory-acl' +import { isPermissionError } from '../../../filesystem/permission-errors' +import { renameOverLockedTarget } from './locked-executable-rename' + +// Atomic replacement protects scripts being read by in-flight hooks. +export function writeManagedScript( + scriptPath: string, + content: string | Buffer, + options: { moveLockedTargetAside?: boolean } = {} +): void { + const dir = dirname(scriptPath) + mkdirSync(dir, { recursive: true }) + + if (existsSync(scriptPath)) { + try { + if (readFileSync(scriptPath).equals(Buffer.from(content))) { + if (process.platform !== 'win32') { + chmodSync(scriptPath, 0o755) + } + return + } + } catch { + // Fall through to the atomic write path. + } + } + + const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) + try { + writeScriptWithAclRetry(tmpPath, content) + // Publish with execute permission so POSIX guards never skip a newly installed script. + if (process.platform !== 'win32') { + chmodSync(tmpPath, 0o755) + } + renameOverLockedTarget(tmpPath, scriptPath, options.moveLockedTargetAside === true) + } finally { + if (existsSync(tmpPath)) { + try { + unlinkSync(tmpPath) + } catch { + // best effort + } + } + } +} + +// Retry Windows EPERM once after repairing a restrictive directory ACL. +function writeScriptWithAclRetry(scriptPath: string, content: string | Buffer): void { + try { + writeFileSync(scriptPath, content, 'utf-8') + } catch (error) { + if (isPermissionError(error) && process.platform === 'win32') { + try { + grantDirAcl(dirname(scriptPath)) + writeFileSync(scriptPath, content, 'utf-8') + return + } catch { + // a failed grant is not actionable; re-throw the original EPERM + } + } + throw error + } +} diff --git a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts similarity index 86% rename from src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts index 1e5ee4fd94b..c6cffd1ba59 100644 --- a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts @@ -1,13 +1,13 @@ // POSIX hooks drain before exit; Windows missing-context hooks may exit without owning stdin. import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as CodexHookHashLookup from '../codex/trust/hooks/codex-hook-hash-lookup' +import type * as CodexHookHashLookup from '../../../codex/trust/hooks/codex-hook-hash-lookup' import { spawnProcess } from '@orca/process-host' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as osModule from 'node:os' -import type * as NativeHookExecutableModule from './windows-native-hook-executable' +import type * as NativeHookExecutableModule from '../commands/windows-native-hook-executable' let isolatedUserDataDir = '' let previousUserDataPath: string | undefined @@ -40,16 +40,16 @@ const { homedirMock, bundledHook } = vi.hoisted(() => { }) // Test the real built executable without packaged resource lookup. -vi.mock('./windows-native-hook-executable', async (importOriginal) => ({ +vi.mock('../commands/windows-native-hook-executable', async (importOriginal) => ({ ...(await importOriginal()), resolveBundledWindowsNativeHookExecutable: () => bundledHook.path })) -vi.mock('../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ +vi.mock('../../../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ ...(await importOriginal()), resolveCodexHookAnswerForLaunch: async () => ( - await import('../codex/hooks/installation/hook-service-test-harness') + await import('../../../codex/hooks/installation/hook-service-test-harness') ).codexHookAnswerForTests() })) @@ -67,34 +67,34 @@ vi.mock('os', async (importOriginal) => { } }) -import '../antigravity/hook-service' -import { ClaudeHookService } from '../claude/hook-service' -import '../claude/hook-settings' -import '../codex/hooks/installation/hook-service' -import '../codex/hooks/installation/codex-hook-service-implementation' -import '../command-code/hook-service' -import '../copilot/hook-service' -import '../cursor/hook-service' -import '../devin/hook-service' -import '../droid/hook-service' -import '../gemini/hook-service' -import '../grok/hook-service' -import '../kimi/hook-service' +import '../../../antigravity/hook-service' +import { ClaudeHookService } from '../../../claude/hook-service' +import '../../../claude/hook-settings' +import '../../../codex/hooks/installation/hook-service' +import '../../../codex/hooks/installation/codex-hook-service-implementation' +import '../../../command-code/hook-service' +import '../../../copilot/hook-service' +import '../../../cursor/hook-service' +import '../../../devin/hook-service' +import '../../../droid/hook-service' +import '../../../gemini/hook-service' +import '../../../grok/hook-service' +import '../../../kimi/hook-service' + +import '../../../openclaude/hook-service' -import '../openclaude/hook-service' -import './installer-utils' import { POSIX_HOOK_STDIN_READER } from './hook-stdin-contract' -import './runtime-home-hook-command' -import './agent-hook-memory-sftp.test-fixture' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import '../commands/runtime-home-hook-command' +import '../remote/testing/agent-hook-memory-sftp.test-fixture' +import { findGitBash } from '../commands/testing/windows-git-bash-path.test-fixture' import { WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS, warmWindowsEncodedPowerShell -} from './windows-powershell-warm-up.test-fixture' +} from '../commands/testing/windows-powershell-warm-up.test-fixture' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' +} from '../commands/testing/windows-native-hook-exe.test-fixture' const REMOTE_HOME = '/home/dev' const LARGE_PAYLOAD = Buffer.alloc(1_000_000, 'x') diff --git a/src/main/agent-hooks/managed-hook-timeout.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts similarity index 95% rename from src/main/agent-hooks/managed-hook-timeout.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts index efdb31cb61b..ed6ac082b4a 100644 --- a/src/main/agent-hooks/managed-hook-timeout.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts @@ -25,9 +25,9 @@ vi.mock('os', async (importOriginal) => { homedir: homedirMock.mockImplementation(actual.homedir) } }) -import '../codex/hooks/installation/hook-service' -import { CodexHookService } from '../codex/hooks/installation/codex-hook-service-implementation' -import { createAgentHookMemorySftp as createFakeSftp } from './agent-hook-memory-sftp.test-fixture' +import '../../../codex/hooks/installation/hook-service' +import { CodexHookService } from '../../../codex/hooks/installation/codex-hook-service-implementation' +import { createAgentHookMemorySftp as createFakeSftp } from '../remote/testing/agent-hook-memory-sftp.test-fixture' const REMOTE_HOME = '/home/dev' diff --git a/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts b/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts new file mode 100644 index 00000000000..4a2fc5973cc --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts @@ -0,0 +1,44 @@ +import { randomUUID } from 'node:crypto' +import type { SFTPWrapper } from 'ssh2' +import { + readFile, + writeFile, + rename, + unlink, + chmod, + mkdirpRemote, + dirnamePosix +} from '../remote/hook-sftp-operations' + +/** POSIX SSH targets only: paths and script payloads follow POSIX conventions. */ +export async function writeManagedScriptRemote( + sftp: SFTPWrapper, + remotePath: string, + content: string +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + try { + const existing = await readFile(sftp, remotePath) + if (existing === content) { + await chmod(sftp, remotePath, 0o755) + return + } + } catch { + // Retry through the atomic write path after a failed read. + } + + // Publish only a complete executable script; existing configs may invoke it during reinstall. + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + await writeFile(sftp, tmp, content, 0o755) + await chmod(sftp, tmp, 0o755) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts b/src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts similarity index 100% rename from src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts rename to src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts diff --git a/src/main/agent-hooks/vendor-hook-delivery.test-fixture.ts b/src/main/agent-hooks/installation/scripts/testing/vendor-hook-delivery.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/vendor-hook-delivery.test-fixture.ts rename to src/main/agent-hooks/installation/scripts/testing/vendor-hook-delivery.test-fixture.ts diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installation/testing/installer-contract.test.ts similarity index 95% rename from src/main/agent-hooks/installer-utils.test.ts rename to src/main/agent-hooks/installation/testing/installer-contract.test.ts index 51ef481467c..e3797f0e102 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installation/testing/installer-contract.test.ts @@ -14,14 +14,12 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcessSync } from '@orca/process-host' -import { - wrapPosixHookCommand, - wrapWindowsHookCommand, - writeHooksJson, - type HooksConfig -} from './installer-utils' -import './hook-post-command' -import { wrapRuntimeHomeHookCommand } from './runtime-home-hook-command' +import { wrapPosixHookCommand } from '../commands/posix-hook-command' +import { wrapWindowsHookCommand } from '../commands/windows-hook-command' +import { writeHooksJson } from '../configuration/hooks-json-write' +import type { HooksConfig } from '../configuration/hook-config-schema' +import '../scripts/hook-post-command' +import { wrapRuntimeHomeHookCommand } from '../commands/runtime-home-hook-command' let tmpDir: string let configPath: string diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts deleted file mode 100644 index d0865969033..00000000000 --- a/src/main/agent-hooks/installer-utils.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { - existsSync, - mkdirSync, - readFileSync, - statSync, - writeFileSync, - chmodSync, - renameSync, - unlinkSync -} from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join } from 'node:path' -import { randomUUID } from 'node:crypto' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { grantDirAcl } from '../windows/windows-directory-acl' -import { isPermissionError } from '../filesystem/permission-errors' -import { resolveHooksJsonWritePath } from './hook-config-write-path' -import { writeRollingFileBackup } from '../filesystem/rolling-file-backup' -import { renameOverLockedTarget } from './locked-executable-rename' -import { - getWindowsNativeHookAgent, - WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME -} from './windows-native-hook-executable' - -export type HookCommandConfig = { - type: 'command' - command: string - args?: string[] - timeout?: number - async?: boolean - statusMessage?: string - [key: string]: unknown -} - -export type HookDefinition = { - matcher?: string - command?: string - bash?: string - powershell?: string - hooks?: HookCommandConfig[] - [key: string]: unknown -} - -export type HooksConfig = { - hooks?: Record - [key: string]: unknown -} - -// Host-level backstop independent of curl and provider-specific timeouts. -export const MANAGED_HOOK_TIMEOUT_SECONDS = 10 -export const MANAGED_HOOK_TIMEOUT_MILLISECONDS = MANAGED_HOOK_TIMEOUT_SECONDS * 1000 - -// Claude-shaped schemas nest command hooks; Cursor puts command on the definition itself. -export function buildManagedCommandHook( - command: string, - timeout = MANAGED_HOOK_TIMEOUT_SECONDS -): HookCommandConfig { - return { type: 'command', command, timeout } -} - -export function buildManagedCommandDefinition(command: string): HookDefinition { - return { command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } -} - -export { - isPlainObject, - readHooksJson, - readHooksJsonWithRaw, - type HooksJsonSnapshot -} from './hooks-json-read' - -// Match script names so reinstalls sweep entries from old and parallel installations. -export function createManagedCommandMatcher( - scriptFileName: string -): (command: string | undefined) => boolean { - const scriptStem = scriptFileName.replace(/\.(?:cmd|ps1|sh)$/, '') - // Sweep every platform suffix after a platform switch. - const needles = [ - `agent-hooks/${scriptFileName}`, - `agent-hooks/${scriptStem}.cmd`, - `agent-hooks/${scriptStem}.ps1`, - `agent-hooks/${scriptStem}.sh` - ] - // The native executable selects its provider through argv[1]. - const nativeHook = `agent-hooks/${WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME} ${getWindowsNativeHookAgent(scriptFileName)} ` - return (command) => { - if (!command) { - return false - } - const decodedCommand = decodePowerShellEncodedCommand(command) - const searchText = decodedCommand ? `${command}\n${decodedCommand}` : command - const normalizedCommand = searchText.replaceAll('\\', '/') - return ( - needles.some((needle) => normalizedCommand.includes(needle)) || - normalizedCommand.split('\n').some((line) => `${line} `.includes(nativeHook)) - ) - } -} - -function decodePowerShellEncodedCommand(command: string): string | null { - const match = command.match(/\s-EncodedCommand\s+(\S+)/i) - if (!match) { - return null - } - try { - return Buffer.from(match[1], 'base64').toString('utf16le') - } catch { - return null - } -} - -// Parallel Orca instances must share one user-wide script path. -export function getSharedManagedScriptPath(scriptFileName: string): string { - return join(homedir(), '.orca', 'agent-hooks', scriptFileName) -} - -export { wrapPosixHookCommand } from './posix-hook-command' - -export { - wrapWindowsPowerShellEncodedCommand, - WINDOWS_POWERSHELL_HOOK_SWITCHES -} from './windows-powershell-hook-launcher' - -export { - buildWindowsHookPowerShellCommand, - isSafeUnicodeWindowsBatchHookPath, - WINDOWS_CMD_SAFE_PATH, - wrapWindowsHookCommand -} from './windows-hook-command' - -/** Extra form lines precede payload@- and must end with ` ^`. */ -export function buildWindowsAgentHookPostCommand( - source: AgentHookSource, - extraFormLines: readonly string[] = [] -): string { - // Avoid PowerShell startup; qualify curl to prevent repo-local payload interception. - return [ - `"%SystemRoot%\\System32\\curl.exe" -sS -X POST "http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}" ^`, - ' --connect-timeout 0.5 --max-time 1.5 ^', - ' -H "Content-Type: application/x-www-form-urlencoded" ^', - ' -H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%" ^', - ' --data-urlencode "paneKey=%ORCA_PANE_KEY%" ^', - ' --data-urlencode "tabId=%ORCA_TAB_ID%" ^', - ' --data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%" ^', - ' --data-urlencode "worktreeId=%ORCA_WORKTREE_ID%" ^', - ' --data-urlencode "env=%ORCA_AGENT_HOOK_ENV%" ^', - ' --data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%" ^', - ...extraFormLines, - ' --data-urlencode "payload@-" >nul 2>nul' - ].join('\r\n') -} - -// curl.exe avoids PowerShell startup and code-page corruption of UTF-8 payloads. -export function buildWindowsAgentHookCurlPostCommand(source: AgentHookSource): string { - return [ - '"%SystemRoot%\\System32\\curl.exe" -sS -X POST', - `"http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}"`, - '--connect-timeout 0.5 --max-time 1.5', - '-H "Content-Type: application/x-www-form-urlencoded"', - '-H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%"', - '--data-urlencode "paneKey=%ORCA_PANE_KEY%"', - '--data-urlencode "tabId=%ORCA_TAB_ID%"', - '--data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%"', - '--data-urlencode "worktreeId=%ORCA_WORKTREE_ID%"', - '--data-urlencode "env=%ORCA_AGENT_HOOK_ENV%"', - '--data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%"', - '--data-urlencode "payload@-"', - '>nul 2>&1' - ].join(' ') -} - -export function removeManagedCommands( - definitions: HookDefinition[], - isManagedCommand: (command: string | undefined) => boolean -): HookDefinition[] { - return definitions.flatMap((definition) => { - const directCommandKeys = ['command', 'bash', 'powershell'] as const - const directManagedKeys = directCommandKeys.filter((key) => isManagedCommand(definition[key])) - const hasNestedHooks = Array.isArray(definition.hooks) - const hasManagedNestedHook = - hasNestedHooks && - definition.hooks!.some((hook) => hookHasManagedCommand(hook, isManagedCommand)) - - if (directManagedKeys.length === 0 && !hasManagedNestedHook) { - return [definition] - } - - const nextDefinition: HookDefinition = { ...definition } - for (const key of directManagedKeys) { - delete nextDefinition[key] - } - - if (hasManagedNestedHook) { - const filteredHooks = definition.hooks!.filter( - (hook) => !hookHasManagedCommand(hook, isManagedCommand) - ) - if (filteredHooks.length > 0) { - nextDefinition.hooks = filteredHooks - } else { - delete nextDefinition.hooks - } - } - - const hasCommandAfterCleanup = - directCommandKeys.some((key) => typeof nextDefinition[key] === 'string') || - (Array.isArray(nextDefinition.hooks) && nextDefinition.hooks.length > 0) - if (!hasCommandAfterCleanup) { - return [] - } - - return [nextDefinition] - }) -} - -function hookHasManagedCommand(hook: HookCommandConfig, matches: (value?: string) => boolean) { - const args = Array.isArray(hook.args) ? hook.args : [] - return matches(hook.command) || args.some((arg) => typeof arg === 'string' && matches(arg)) -} - -// Users may opt a managed hook into async; keep that choice when the hook is rewritten. -export function withPreviousManagedAsync( - hook: HookCommandConfig, - definitions: HookDefinition[], - matches: (command: string | undefined) => boolean -): HookCommandConfig { - const async = definitions - .flatMap((definition) => (Array.isArray(definition.hooks) ? definition.hooks : [])) - .find((prev) => typeof prev.async === 'boolean' && hookHasManagedCommand(prev, matches))?.async - return async === undefined ? hook : { ...hook, async } -} - -export function hookDefinitionHasManagedCommand( - definition: HookDefinition, - isManagedCommand: (command: string | undefined) => boolean -): boolean { - return ( - isManagedCommand(definition.command) || - isManagedCommand(definition.bash) || - isManagedCommand(definition.powershell) || - (Array.isArray(definition.hooks) && - definition.hooks.some((hook) => hookHasManagedCommand(hook, isManagedCommand))) - ) -} - -// Atomic replacement protects scripts being read by in-flight hooks. -export function writeManagedScript( - scriptPath: string, - content: string | Buffer, - options: { moveLockedTargetAside?: boolean } = {} -): void { - const dir = dirname(scriptPath) - mkdirSync(dir, { recursive: true }) - - if (existsSync(scriptPath)) { - try { - if (readFileSync(scriptPath).equals(Buffer.from(content))) { - if (process.platform !== 'win32') { - chmodSync(scriptPath, 0o755) - } - return - } - } catch { - // Fall through to the atomic write path. - } - } - - const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) - try { - writeScriptWithAclRetry(tmpPath, content) - // Publish with execute permission so POSIX guards never skip a newly installed script. - if (process.platform !== 'win32') { - chmodSync(tmpPath, 0o755) - } - renameOverLockedTarget(tmpPath, scriptPath, options.moveLockedTargetAside === true) - } finally { - if (existsSync(tmpPath)) { - try { - unlinkSync(tmpPath) - } catch { - // best effort - } - } - } -} - -// Retry Windows EPERM once after repairing a restrictive directory ACL. -function writeScriptWithAclRetry(scriptPath: string, content: string | Buffer): void { - try { - writeFileSync(scriptPath, content, 'utf-8') - } catch (error) { - if (isPermissionError(error) && process.platform === 'win32') { - try { - grantDirAcl(dirname(scriptPath)) - writeFileSync(scriptPath, content, 'utf-8') - return - } catch { - // a failed grant is not actionable; re-throw the original EPERM - } - } - throw error - } -} - -export function writeHooksJson( - configPath: string, - // Fallback serialization accepts provider-specific JSON shapes, including nested hooks.events. - config: Record, - // JSONC callers supply edited text while retaining atomic writes and backups. - options?: { preserveMode?: boolean; defaultMode?: number; serialized?: string } -): void { - const writePath = resolveHooksJsonWritePath(configPath) - const dir = dirname(writePath) - mkdirSync(dir, { recursive: true }) - - // Unique temp paths isolate concurrent writers and preserve the original on write failure. - const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) - const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` - // Preserve owner-only permissions: agent configs can contain API keys. - const existingMode = - options?.preserveMode !== false && existsSync(writePath) - ? statSync(writePath).mode & 0o777 - : options?.defaultMode - - // Identical reinstalls must not rotate away the last recoverable backup. - if (existsSync(writePath)) { - try { - if (readFileSync(writePath, 'utf-8') === serialized) { - return - } - } catch { - // Retry through the write path after a failed read. - } - } - - try { - // Windows read-only mode could prevent deleting a failed temporary write. - const tmpMode = process.platform === 'win32' ? undefined : existingMode - writeFileSync(tmpPath, serialized, { encoding: 'utf-8', mode: tmpMode, flag: 'wx' }) - if (existingMode !== undefined && process.platform !== 'win32') { - // Preserve requested permissions even with a stricter process umask. - chmodSync(tmpPath, existingMode) - } - // Keep one prior version for recovery from a bad merge. - if (existsSync(writePath)) { - writeRollingFileBackup(writePath, `${writePath}.bak`) - } - renameSync(tmpPath, writePath) - } finally { - if (existsSync(tmpPath)) { - try { - unlinkSync(tmpPath) - } catch { - // best effort - } - } - } -} - -export { writeHooksJsonAsync } from './hooks-json-write-async' diff --git a/src/main/agent-hooks/agent-transition-detector.test.ts b/src/main/agent-hooks/observations/agent-transition-detector.test.ts similarity index 94% rename from src/main/agent-hooks/agent-transition-detector.test.ts rename to src/main/agent-hooks/observations/agent-transition-detector.test.ts index 0b6d61f33aa..13bb1ba51be 100644 --- a/src/main/agent-hooks/agent-transition-detector.test.ts +++ b/src/main/agent-hooks/observations/agent-transition-detector.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' +import { AgentHookServer } from '../server/agent-hook-server' import { AgentTransitionDetector, type AgentPaneChange } from './agent-transition-detector' -import type { AgentTransitionStep } from '../../shared/agent-status/lifecycle/agent-transitions.test-fixture' +import type { AgentTransitionStep } from '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) const WT = 'repo-1::/tmp/a' const OTHER_WT = 'repo-1::/tmp/b' diff --git a/src/main/agent-hooks/agent-transition-detector.ts b/src/main/agent-hooks/observations/agent-transition-detector.ts similarity index 94% rename from src/main/agent-hooks/agent-transition-detector.ts rename to src/main/agent-hooks/observations/agent-transition-detector.ts index 2a579dfe393..1aaa6046d1b 100644 --- a/src/main/agent-hooks/agent-transition-detector.ts +++ b/src/main/agent-hooks/observations/agent-transition-detector.ts @@ -1,5 +1,5 @@ -import { resolveAgentStatusWorktreeId } from '../../shared/agent-status/identity/agent-status-worktree-attribution' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import { resolveAgentStatusWorktreeId } from '../../../shared/agent-status/identity/agent-status-worktree-attribution' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { agentPhaseTransition, hookRowAgentPhase, @@ -8,14 +8,14 @@ import { titleAgentPhase, type AgentPhase, type AgentTransition -} from '../../shared/agent-status/lifecycle/agent-transitions' -import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' +} from '../../../shared/agent-status/lifecycle/agent-transitions' +import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' import { getConnectionExecutionHostId, LOCAL_EXECUTION_HOST_ID, type ExecutionHostId -} from '../../shared/execution-host' -import type { AgentHookServer } from './server' +} from '../../../shared/execution-host' +import type { AgentHookServer } from '../server/agent-hook-server' export type AgentTransitionStore = Pick< AgentHookServer, diff --git a/src/main/agent-hooks/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts similarity index 69% rename from src/main/agent-hooks/local-hook-root-evidence.ts rename to src/main/agent-hooks/observations/local-hook-root-evidence.ts index 03ec1717c78..413ae59469b 100644 --- a/src/main/agent-hooks/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -1,12 +1,12 @@ -import type { AgentHookServer } from './server' +import type { AgentHookServer } from '../server/agent-hook-server' import { createLocalHookPaneRootResolver, createLocalPtyInventoryReader, type LocalPtyInventoryReader } from './local-tmux-managed-pty' -import { createLocalHookRootEvidenceReader } from '../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' -import { getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' +import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' +import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' /** Hooks posted on this host name panes its own provider owns; their roots come from that * provider's inventory, read lazily because daemon swaps replace the provider. */ diff --git a/src/main/agent-hooks/local-tmux-managed-pty.test.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts similarity index 96% rename from src/main/agent-hooks/local-tmux-managed-pty.test.ts rename to src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts index f324d43ace8..fc229bc9ed0 100644 --- a/src/main/agent-hooks/local-tmux-managed-pty.test.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts @@ -4,7 +4,7 @@ import { createLocalPtyInventoryReader, createLocalTmuxManagedPtyResolver } from './local-tmux-managed-pty' -import type { PtyProcessInfo } from '../providers/pty-provider-contract' +import type { PtyProcessInfo } from '../../providers/pty-provider-contract' const row: PtyProcessInfo = { id: 'pty', diff --git a/src/main/agent-hooks/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts similarity index 94% rename from src/main/agent-hooks/local-tmux-managed-pty.ts rename to src/main/agent-hooks/observations/local-tmux-managed-pty.ts index edd4e2a1a61..e3d6a683309 100644 --- a/src/main/agent-hooks/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -1,6 +1,6 @@ -import type { PtyProcessInfo } from '../providers/pty-provider-contract' -import type { TmuxManagedPty } from '../../shared/tmux-agent-hook-contract' -import type { HookPaneProcessIo } from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { PtyProcessInfo } from '../../providers/pty-provider-contract' +import type { TmuxManagedPty } from '../../../shared/tmux-agent-hook-contract' +import type { HookPaneProcessIo } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' type InventoryOptions = { getPtyId: (paneKey: string) => string | undefined | null diff --git a/src/main/agent-hooks/migration-unsupported-pty-state.ts b/src/main/agent-hooks/observations/migration-unsupported-pty-state.ts similarity index 95% rename from src/main/agent-hooks/migration-unsupported-pty-state.ts rename to src/main/agent-hooks/observations/migration-unsupported-pty-state.ts index 0d5dd17f084..c1e35d2b03c 100644 --- a/src/main/agent-hooks/migration-unsupported-pty-state.ts +++ b/src/main/agent-hooks/observations/migration-unsupported-pty-state.ts @@ -1,4 +1,4 @@ -import type { MigrationUnsupportedPtyEntry } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { MigrationUnsupportedPtyEntry } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' type MigrationUnsupportedPtyEvent = | { type: 'set'; entry: MigrationUnsupportedPtyEntry } diff --git a/src/main/agent-hooks/restored-status-dead-terminal-sweep.ts b/src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts similarity index 90% rename from src/main/agent-hooks/restored-status-dead-terminal-sweep.ts rename to src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts index cd485f64fae..cd856a1303c 100644 --- a/src/main/agent-hooks/restored-status-dead-terminal-sweep.ts +++ b/src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts @@ -2,13 +2,13 @@ import { getConnectionExecutionHostId, parseExecutionHostId, type ExecutionHostId -} from '../../shared/execution-host' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../shared/project-group-types' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { isLocalHookConnectionId } from '../../shared/wsl-hook-relay-contract' -import type { AgentHookServer } from './server' +} from '../../../shared/execution-host' +import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../shared/project-group-types' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { isLocalHookConnectionId } from '../../../shared/wsl-hook-relay-contract' +import type { AgentHookServer } from '../server/agent-hook-server' type RestoredStatusSweepServer = Pick< AgentHookServer, diff --git a/src/main/agent-hooks/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts similarity index 89% rename from src/main/agent-hooks/agent-hook-runtime-deps.ts rename to src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index f48cc6836e6..1d65427fe77 100644 --- a/src/main/agent-hooks/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { AgentStatusObservedPaneIdentities } from '../runtime/terminal/identity/agent-status-observed-pane-identity' -import type { AgentHookServer } from './server' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { AgentStatusObservedPaneIdentities } from '../../runtime/terminal/identity/agent-status-observed-pane-identity' +import type { AgentHookServer } from '../server/agent-hook-server' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' type RuntimeDeps = NonNullable[2]> diff --git a/src/main/agent-hooks/agent-status-pane-index.ts b/src/main/agent-hooks/runtime/agent-status-pane-index.ts similarity index 82% rename from src/main/agent-hooks/agent-status-pane-index.ts rename to src/main/agent-hooks/runtime/agent-status-pane-index.ts index 75a38ac615f..2abd2153c7d 100644 --- a/src/main/agent-hooks/agent-status-pane-index.ts +++ b/src/main/agent-hooks/runtime/agent-status-pane-index.ts @@ -1,4 +1,4 @@ -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' /** Index once per snapshot to avoid rematerializing rows for every pane. */ export function indexAgentStatusRowsByPaneKey( diff --git a/src/main/agent-hooks/hook-status-session-tabs-republish.ts b/src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts similarity index 96% rename from src/main/agent-hooks/hook-status-session-tabs-republish.ts rename to src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts index 460aae88aa3..9df5ff4e61d 100644 --- a/src/main/agent-hooks/hook-status-session-tabs-republish.ts +++ b/src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts @@ -1,4 +1,4 @@ -import type { AgentHookServer } from './server' +import type { AgentHookServer } from '../server/agent-hook-server' type SessionTabsRepublisher = { getTerminalWorktreeIdForHandle(handle: string): string | null diff --git a/src/main/agent-hooks/server-codex-normalization.test.ts b/src/main/agent-hooks/server-codex-normalization.test.ts deleted file mode 100644 index d8944e6ff0c..00000000000 --- a/src/main/agent-hooks/server-codex-normalization.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' - -const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ - getCohortAtEmitMock: vi.fn(), - trackMock: vi.fn() -})) - -vi.mock('../telemetry/client', () => ({ - track: trackMock -})) - -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: getCohortAtEmitMock -})) - -beforeEach(() => { - _internals.resetCachesForTests() - trackMock.mockReset() - getCohortAtEmitMock.mockReset() - getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('Codex hook normalization', () => { - it('tracks nested subagents with their role, model, and lifecycle state', () => { - const root = _internals.normalizeHookPayload( - 'codex', - buildBody({ - hook_event_name: 'UserPromptSubmit', - prompt: 'Coordinate the review', - model: 'gpt-5.4' - }), - 'production' - ) - expect(root?.payload.model).toBe('gpt-5.4') - - const started = _internals.normalizeHookPayload( - 'codex', - buildBody({ - hook_event_name: 'SubagentStart', - session_id: 'child-session', - agent_id: 'child-session', - agent_type: 'reviewer', - model: 'gpt-5.4-mini' - }), - 'production' - ) - expect(started?.providerSession).toBeUndefined() - expect(started?.payload).toMatchObject({ - state: 'working', - prompt: 'Coordinate the review', - model: 'gpt-5.4', - subagents: [ - { - id: 'child-session', - agentType: 'reviewer', - model: 'gpt-5.4-mini', - state: 'working' - } - ] - }) - - const waiting = _internals.normalizeHookPayload( - 'codex', - buildBody({ - hook_event_name: 'PermissionRequest', - agent_id: 'child-session', - agent_type: 'reviewer', - model: 'gpt-5.4-mini', - tool_name: 'exec_command', - tool_input: { cmd: 'git fetch' } - }), - 'production' - ) - expect(waiting?.payload.state).toBe('waiting') - expect(waiting?.payload.subagents?.[0].state).toBe('waiting') - - const workingAgain = _internals.normalizeHookPayload( - 'codex', - buildBody({ - hook_event_name: 'PreToolUse', - agent_id: 'child-session', - agent_type: 'reviewer', - model: 'gpt-5.4-mini', - tool_name: 'exec_command', - tool_input: { cmd: 'git fetch' } - }), - 'production' - ) - expect(workingAgain?.payload.state).toBe('working') - expect(workingAgain?.payload.subagents?.[0].state).toBe('working') - - const rootStop = _internals.normalizeHookPayload( - 'codex', - buildBody({ hook_event_name: 'Stop', model: 'gpt-5.4' }), - 'production' - ) - expect(rootStop?.payload.state).toBe('done') - expect(rootStop?.payload.subagents).toBeUndefined() - - const resumedChild = _internals.normalizeHookPayload( - 'codex', - buildBody({ - hook_event_name: 'PreToolUse', - agent_id: 'child-session', - agent_type: 'reviewer', - model: 'gpt-5.4-mini', - tool_name: 'exec_command', - tool_input: { cmd: 'pnpm test' } - }), - 'production' - ) - expect(resumedChild?.payload.state).toBe('working') - expect(resumedChild?.payload.subagents?.[0]).toMatchObject({ - id: 'child-session', - state: 'working' - }) - - const stopped = _internals.normalizeHookPayload( - 'codex', - buildBody({ hook_event_name: 'SubagentStop', agent_id: 'child-session' }), - 'production' - ) - expect(stopped?.payload.state).toBe('done') - expect(stopped?.payload.subagents).toBeUndefined() - }) -}) - -describe.each(['opencode', 'opencode2'] as const)('%s hook normalization', (source) => { - it.each([ - ['UnknownError', 'failure', undefined], - ['MessageAbortedError', 'cancellation', true] - ])('retains the reported root outcome for %s', (errorName, outcome, interrupted) => { - const result = _internals.normalizeHookPayload( - source, - buildBody({ - hook_event_name: 'SessionIdle', - root_state: 'done', - root_turn_error_name: errorName - }), - 'production' - ) - expect(result?.payload.mainAgent).toMatchObject({ state: 'done', outcome }) - expect(result?.payload.interrupted).toBe(interrupted) - }) - - it('does not infer an outcome for an older plugin', () => { - const result = _internals.normalizeHookPayload( - source, - buildBody({ hook_event_name: 'SessionIdle' }), - 'production' - ) - expect(result?.payload.mainAgent).toBeUndefined() - }) - - it('keeps a root failure beside still-working child work', () => { - const result = _internals.normalizeHookPayload( - source, - buildBody({ - hook_event_name: 'SessionBusy', - root_state: 'done', - root_turn_error_name: 'api' - }), - 'production' - ) - expect(result?.payload.state).toBe('working') - expect(result?.payload.mainAgent).toMatchObject({ state: 'done', outcome: 'failure' }) - }) - - it('caps oversized MessagePart text from stale (pre-throttle) plugin builds', () => { - // Older plugins resend full replies on each update; cap per-event work. - const assistant = _internals.normalizeHookPayload( - source, - buildBody({ - hook_event_name: 'MessagePart', - role: 'assistant', - text: 'a'.repeat(500_000) - }), - 'production' - ) - expect(assistant?.payload.lastAssistantMessage?.length).toBe(8_000) - - const user = _internals.normalizeHookPayload( - source, - buildBody({ - hook_event_name: 'MessagePart', - role: 'user', - text: 'u'.repeat(500_000), - messageID: 'msg-cap' - }), - 'production' - ) - expect(user?.payload.prompt?.length).toBe(200) - }) -}) diff --git a/src/main/agent-hooks/server-copilot-normalization.test.ts b/src/main/agent-hooks/server-copilot-normalization.test.ts deleted file mode 100644 index bd0c75609db..00000000000 --- a/src/main/agent-hooks/server-copilot-normalization.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody } from './server.test-fixtures' - -const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ - getCohortAtEmitMock: vi.fn(), - trackMock: vi.fn() -})) - -vi.mock('../telemetry/client', () => ({ - track: trackMock -})) - -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: getCohortAtEmitMock -})) - -beforeEach(() => { - _internals.resetCachesForTests() - trackMock.mockReset() - getCohortAtEmitMock.mockReset() - getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('Copilot hook normalization', () => { - it('updates Copilot Stop with final transcript text after a non-blocking retry', async () => { - const server = new AgentHookServer() - const tmpDir = mkdtempSync(join(tmpdir(), 'orca-copilot-transcript-retry-')) - const transcriptPath = join(tmpDir, 'events.jsonl') - writeFileSync(transcriptPath, '') - await server.start({ env: 'production' }) - try { - const env = server.buildPtyEnv() - const listener = vi.fn() - server.setListener(listener) - - await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/copilot`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify( - buildBody({ - hook_event_name: 'PostToolUse', - tool_result: { text_result_for_llm: 'stale tool output' } - }) - ) - }) - const response = await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/copilot`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify( - buildBody({ hook_event_name: 'Stop', transcript_path: transcriptPath }) - ) - }) - - expect(response.status).toBe(204) - await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/copilot`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify(buildBody({ hook_event_name: 'SessionEnd', reason: 'complete' })) - }) - expect(listener).toHaveBeenLastCalledWith( - expect.objectContaining({ - payload: expect.objectContaining({ - state: 'done', - lastAssistantMessage: undefined - }) - }) - ) - - // Let the first 50ms retry miss so continuation across SessionEnd is proven. - await new Promise((resolve) => setTimeout(resolve, 70)) - writeFileSync( - transcriptPath, - `${JSON.stringify({ - type: 'assistant.message', - data: { content: 'Done after transcript flush.' } - })}\n` - ) - await new Promise((resolve) => setTimeout(resolve, 120)) - - expect(listener).toHaveBeenLastCalledWith( - expect.objectContaining({ - payload: expect.objectContaining({ - state: 'done', - lastAssistantMessage: 'Done after transcript flush.' - }) - }) - ) - } finally { - server.stop() - rmSync(tmpDir, { recursive: true, force: true }) - } - }) - - it('updates Grok Stop with final chat-history text after a non-blocking retry', async () => { - const server = new AgentHookServer() - const tmpDir = mkdtempSync(join(tmpdir(), 'orca-grok-chat-history-retry-')) - const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf528' - const cwd = join(tmpDir, 'workspace') - const sessionDir = join(tmpDir, '.grok', 'sessions', encodeURIComponent(cwd), sessionId) - mkdirSync(sessionDir, { recursive: true }) - writeFileSync(join(sessionDir, 'chat_history.jsonl'), '') - vi.stubEnv('HOME', tmpDir) - vi.stubEnv('USERPROFILE', tmpDir) - await server.start({ env: 'production' }) - try { - const env = server.buildPtyEnv() - const listener = vi.fn() - server.setListener(listener) - - await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/grok`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify(buildBody({ hookEventName: 'user_prompt_submit', prompt: 'hihi' })) - }) - const response = await fetch(`http://127.0.0.1:${env.ORCA_AGENT_HOOK_PORT}/hook/grok`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify(buildBody({ hookEventName: 'Stop', sessionId, cwd })) - }) - - expect(response.status).toBe(204) - expect(listener).toHaveBeenLastCalledWith( - expect.objectContaining({ - payload: expect.objectContaining({ - state: 'done', - lastAssistantMessage: undefined - }) - }) - ) - - writeFileSync( - join(sessionDir, 'chat_history.jsonl'), - `${JSON.stringify({ type: 'assistant', content: 'Hi! How can I help you today?' })}\n` - ) - await new Promise((resolve) => setTimeout(resolve, 120)) - - expect(listener).toHaveBeenLastCalledWith( - expect.objectContaining({ - payload: expect.objectContaining({ - state: 'done', - lastAssistantMessage: 'Hi! How can I help you today?' - }) - }) - ) - } finally { - server.stop() - vi.unstubAllEnvs() - rmSync(tmpDir, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/agent-hooks/server-status-persist-nonblocking.test.ts b/src/main/agent-hooks/server-status-persist-nonblocking.test.ts deleted file mode 100644 index cfca74a39c4..00000000000 --- a/src/main/agent-hooks/server-status-persist-nonblocking.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as fs from 'node:fs' -import * as fsPromises from 'node:fs/promises' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { AtomicSnapshotWriter } from '../persistence/atomic-snapshot-writer' - -type FsModule = typeof fs -type FsPromisesModule = typeof fsPromises - -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) -})) -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, renameSync: vi.fn(actual.renameSync) } -}) -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, rename: vi.fn(actual.rename) } -}) - -describe('last-status persistence stays off the main thread', () => { - let userDataPath: string - let server: AgentHookServer - - const lastStatusPath = (): string => join(userDataPath, 'agent-hooks', 'last-status.json') - const readPrompt = (): unknown => - JSON.parse(readFileSync(lastStatusPath(), 'utf8')).entries[PANE]?.payload?.prompt - // Exclude synchronous endpoint startup writes from status-persistence checks. - const statusRenameSyncCalls = (): number => - vi.mocked(fs.renameSync).mock.calls.filter(([, to]) => String(to) === lastStatusPath()).length - const prompt = (text: string): Promise => - postHookEvent(server, buildBody({ hook_event_name: 'UserPromptSubmit', prompt: text })) - - beforeEach(async () => { - _internals.resetCachesForTests() - userDataPath = mkdtempSync(join(tmpdir(), 'orca-persist-nonblocking-')) - server = new AgentHookServer() - await server.start({ env: 'production', userDataPath }) - }) - - afterEach(() => { - server.stop() - vi.mocked(fsPromises.rename).mockReset() - vi.restoreAllMocks() - rmSync(userDataPath, { recursive: true, force: true }) - }) - - it('keeps answering queued hooks and preserves the quit flush while a rename is held open', async () => { - const actualRename = await vi.importActual('node:fs/promises') - let releaseRename: () => void = () => {} - const renameHeld = new Promise((resolve) => { - vi.mocked(fsPromises.rename).mockImplementationOnce(async (from, to) => { - resolve() - await new Promise((release) => { - releaseRename = release - }) - return actualRename.rename(from, to) - }) - }) - vi.mocked(fsPromises.rename).mockImplementation(actualRename.rename) - const write = vi.spyOn(AtomicSnapshotWriter.prototype, 'write') - const writeSync = vi.spyOn(AtomicSnapshotWriter.prototype, 'writeSync') - - expect((await prompt('first')).status).toBe(204) - await renameHeld - - expect((await prompt('while renaming')).status).toBe(204) - expect((await prompt('queued while renaming')).status).toBe(204) - expect(writeSync).not.toHaveBeenCalled() - expect(statusRenameSyncCalls()).toBe(0) - - // An older async rename must not undo the synchronous quit flush. - server.flushStatusPersistSync() - expect(writeSync).toHaveBeenCalledTimes(1) - expect(readPrompt()).toBe('queued while renaming') - releaseRename() - await write.mock.results[0]?.value - expect(readPrompt()).toBe('queued while renaming') - }) -}) diff --git a/src/main/agent-hooks/server-status-persist-throttle.test.ts b/src/main/agent-hooks/server-status-persist-throttle.test.ts deleted file mode 100644 index e9dc5042863..00000000000 --- a/src/main/agent-hooks/server-status-persist-throttle.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { STATUS_PERSIST_MIN_INTERVAL_MS } from './server/server-constants' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { AtomicSnapshotWriter } from '../persistence/atomic-snapshot-writer' - -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) -})) - -class ProbeServer extends AgentHookServer { - persistTimerArmed(): boolean { - return this.statusPersistTimer !== null - } - - persistDueAt(): number { - return this.statusPersistDueAt - } -} - -describe('last-status persist throttle', () => { - let userDataPath: string - let server: ProbeServer - - const lastStatusPath = (): string => join(userDataPath, 'agent-hooks', 'last-status.json') - const readPrompt = (): unknown => - JSON.parse(readFileSync(lastStatusPath(), 'utf8')).entries[PANE]?.payload?.prompt - const prompt = (text: string, launchToken?: string): Promise => - postHookEvent( - server, - buildBody( - { hook_event_name: 'UserPromptSubmit', prompt: text }, - launchToken ? { launchToken } : {} - ) - ) - - beforeEach(async () => { - _internals.resetCachesForTests() - // Real loopback POSTs need fake time to advance. - vi.useFakeTimers({ - shouldAdvanceTime: true, - toFake: ['setTimeout', 'clearTimeout', 'Date'] - }) - userDataPath = mkdtempSync(join(tmpdir(), 'orca-persist-throttle-')) - server = new ProbeServer() - await server.start({ env: 'production', userDataPath }) - }) - - afterEach(() => { - server.stop() - vi.useRealTimers() - vi.restoreAllMocks() - rmSync(userDataPath, { recursive: true, force: true }) - }) - - it('caps a steady stream at one write per window without pushing the timer back', async () => { - const write = vi.spyOn(AtomicSnapshotWriter.prototype, 'write') - let unchangedWhileArmed = 0 - for (let i = 0; i < 60; i++) { - const armedBefore = server.persistTimerArmed() - const dueBefore = server.persistDueAt() - await prompt(`stream ${i}`) - if (armedBefore && server.persistTimerArmed()) { - expect(server.persistDueAt()).toBe(dueBefore) - unchangedWhileArmed++ - } - if (server.persistTimerArmed()) { - expect(server.persistDueAt() - Date.now()).toBeLessThanOrEqual( - STATUS_PERSIST_MIN_INTERVAL_MS - ) - } - await vi.advanceTimersByTimeAsync(500) - } - await vi.advanceTimersByTimeAsync(STATUS_PERSIST_MIN_INTERVAL_MS) - expect(write).toHaveBeenCalledTimes(7) - expect(unchangedWhileArmed).toBeGreaterThan(40) - await Promise.all(write.mock.results.map((result) => result.value)) - expect(readPrompt()).toBe('stream 59') - expect(server.persistTimerArmed()).toBe(false) - }) - - it('writes an authority change immediately instead of waiting for the window', async () => { - const write = vi.spyOn(AtomicSnapshotWriter.prototype, 'write') - await prompt('first') - await vi.advanceTimersByTimeAsync(1) - expect(write).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(500) - await prompt('second') - expect(server.persistTimerArmed()).toBe(true) - - await prompt('third', 'launch-token-new') - await vi.advanceTimersByTimeAsync(1) - expect(write).toHaveBeenCalledTimes(2) - await write.mock.results[1]?.value - expect(JSON.parse(readFileSync(lastStatusPath(), 'utf8')).entries[PANE]).toMatchObject({ - launchTokenHash: expect.any(String) - }) - }) - - it('flushStatusPersistSync cancels the armed timer and writes synchronously', async () => { - const write = vi.spyOn(AtomicSnapshotWriter.prototype, 'write') - const writeSync = vi.spyOn(AtomicSnapshotWriter.prototype, 'writeSync') - await prompt('first') - await vi.advanceTimersByTimeAsync(1) - await write.mock.results[0]?.value - await prompt('second') - expect(server.persistTimerArmed()).toBe(true) - - server.flushStatusPersistSync() - expect(server.persistTimerArmed()).toBe(false) - expect(writeSync).toHaveBeenCalledTimes(1) - expect(readPrompt()).toBe('second') - - await vi.advanceTimersByTimeAsync(STATUS_PERSIST_MIN_INTERVAL_MS * 2) - expect(write).toHaveBeenCalledTimes(1) - }) - - it('stop then start leaves no armed timer and never overwrites the file with stale state', async () => { - const write = vi.spyOn(AtomicSnapshotWriter.prototype, 'write') - await prompt('first') - await vi.advanceTimersByTimeAsync(1) - await write.mock.results[0]?.value - await prompt('final before stop') - expect(server.persistTimerArmed()).toBe(true) - - server.stop() - const afterStop = readFileSync(lastStatusPath(), 'utf8') - expect(readPrompt()).toBe('final before stop') - await server.start({ env: 'production', userDataPath }) - expect(server.persistTimerArmed()).toBe(false) - - await vi.advanceTimersByTimeAsync(STATUS_PERSIST_MIN_INTERVAL_MS * 2) - expect(write).toHaveBeenCalledTimes(1) - expect(readFileSync(lastStatusPath(), 'utf8')).toBe(afterStop) - }) - - it('warns once for a failing async write and retries in the next window', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const write = vi - .spyOn(AtomicSnapshotWriter.prototype, 'write') - .mockRejectedValueOnce(new Error('disk full')) - .mockRejectedValueOnce(new Error('disk full')) - const persistWarnings = (): number => - warn.mock.calls.filter(([message]) => - String(message).includes('failed to write last-status file') - ).length - - await prompt('first') - await vi.advanceTimersByTimeAsync(1) - expect(write).toHaveBeenCalledTimes(1) - expect(persistWarnings()).toBe(1) - expect(server.persistTimerArmed()).toBe(true) - - await vi.advanceTimersByTimeAsync(STATUS_PERSIST_MIN_INTERVAL_MS) - expect(write).toHaveBeenCalledTimes(2) - expect(persistWarnings()).toBe(1) - - await vi.advanceTimersByTimeAsync(STATUS_PERSIST_MIN_INTERVAL_MS) - expect(write).toHaveBeenCalledTimes(3) - await write.mock.results[2]?.value - expect(readPrompt()).toBe('first') - expect(persistWarnings()).toBe(1) - }) -}) diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts deleted file mode 100644 index f66f4b38526..00000000000 --- a/src/main/agent-hooks/server.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Shared listener internals let relays host the same pipeline without Electron. -import { clearAllListenerCaches } from '../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { parseFormEncodedBody } from '../../shared/agent-hook-listener/request-body' -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServerAgentPresence } from './server/server-agent-presence' - -export class AgentHookServer extends AgentHookServerAgentPresence {} - -export const agentHookServer = new AgentHookServer() - -export const _internals = { - // Bind normalization to singleton state so tests exercise its caches. - normalizeHookPayload: ( - source: AgentHookSource, - body: unknown, - expectedEnv: string - ): AgentHookEventPayload | null => - normalizeHookPayload(agentHookServer._getStateForTests(), source, body, expectedEnv), - parseFormEncodedBody, - resetCachesForTests: (): void => { - clearAllListenerCaches(agentHookServer._getStateForTests()) - agentHookServer._resetCanonicalStatusForTests() - agentHookServer._resetRowOwnershipForTests() - agentHookServer._resetPromptSentDedupeForTests() - agentHookServer._resetConnectionTimestampWatermarksForTests() - } -} diff --git a/src/main/agent-hooks/server/server-agent-presence.ts b/src/main/agent-hooks/server/agent-hook-server.ts similarity index 88% rename from src/main/agent-hooks/server/server-agent-presence.ts rename to src/main/agent-hooks/server/agent-hook-server.ts index 0bd520d83a1..85a6fccb2a6 100644 --- a/src/main/agent-hooks/server/server-agent-presence.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -1,3 +1,8 @@ +import { clearAllListenerCaches } from '../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' @@ -5,7 +10,6 @@ import { ClaudeSessionContinuationTracker, resolvePaneClaudeContinuation } from '../../../shared/agent-hook-listener/claude-session-continuation' -import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { isSameAgentProcess, type AgentProcessVerdict @@ -13,7 +17,7 @@ import { import { probeAgentProcessPresence } from '../../../shared/agent-status/process/agent-process-presence-probe' import { AgentHookServerLifecycle } from './server-lifecycle' -export abstract class AgentHookServerAgentPresence extends AgentHookServerLifecycle { +export class AgentHookServer extends AgentHookServerLifecycle { private readonly presenceChecks = new WeakMap< AgentHookEventPayload, { @@ -239,3 +243,23 @@ export abstract class AgentHookServerAgentPresence extends AgentHookServerLifecy : null } } + +export const agentHookServer = new AgentHookServer() + +export const _internals = { + // Bind normalization to singleton state so tests exercise its caches. + normalizeHookPayload: ( + source: AgentHookSource, + body: unknown, + expectedEnv: string + ): AgentHookEventPayload | null => + normalizeHookPayload(agentHookServer._getStateForTests(), source, body, expectedEnv), + parseFormEncodedBody, + resetCachesForTests: (): void => { + clearAllListenerCaches(agentHookServer._getStateForTests()) + agentHookServer._resetCanonicalStatusForTests() + agentHookServer._resetRowOwnershipForTests() + agentHookServer._resetPromptSentDedupeForTests() + agentHookServer._resetConnectionTimestampWatermarksForTests() + } +} diff --git a/src/main/agent-hooks/server/last-status-saved-rows.ts b/src/main/agent-hooks/server/last-status-saved-rows.ts new file mode 100644 index 00000000000..9ce192497ab --- /dev/null +++ b/src/main/agent-hooks/server/last-status-saved-rows.ts @@ -0,0 +1,50 @@ +import type { KeyedJsonRow } from '../../sqlite/row-cache/keyed-json-row-cache' +import { parseKeyedJsonRows } from '../../sqlite/row-cache/keyed-json-row-cache' +import { LAST_STATUS_FILE_VERSION } from './server-constants' +import type { LastStatusFile } from './server-types' + +type RowKind = 'entry' | 'commitment' | 'exits' + +// Follows LAST_STATUS_FILE_VERSION (a mismatched cache rebuilds empty, as the file did); the +// low digits version the row layout. +export const LAST_STATUS_SCHEMA_VERSION = LAST_STATUS_FILE_VERSION * 100 + 2 + +const rowKey = (kind: RowKind, key: string): string => `${kind}\u0000${key}` + +/** One row per pane entry and per authority commitment, plus the exit list. */ +export function rowsOf(file: LastStatusFile): KeyedJsonRow[] { + const rows: KeyedJsonRow[] = [] + for (const [key, value] of Object.entries(file.entries)) { + rows.push({ key: rowKey('entry', key), json: JSON.stringify(value) }) + } + for (const [key, value] of Object.entries(file.authorityCommitments ?? {})) { + rows.push({ key: rowKey('commitment', key), json: JSON.stringify(value) }) + } + if (file.agentExits && file.agentExits.length > 0) { + rows.push({ key: rowKey('exits', ''), json: JSON.stringify(file.agentExits) }) + } + return rows +} + +/** The last-status document the rows hold; an unreadable row is dropped (a save deletes it). */ +export function assemble(rows: readonly KeyedJsonRow[]): Required { + const file: Required = { + version: LAST_STATUS_FILE_VERSION, + entries: {}, + authorityCommitments: {}, + agentExits: [] + } + for (const { key: id, value } of parseKeyedJsonRows(rows)) { + const separator = id.indexOf('\u0000') + const kind = id.slice(0, separator) + const key = id.slice(separator + 1) + if (kind === 'entry') { + Object.assign(file.entries, { [key]: value }) + } else if (kind === 'commitment') { + Object.assign(file.authorityCommitments, { [key]: value }) + } else if (kind === 'exits' && Array.isArray(value)) { + file.agentExits = value + } + } + return file +} diff --git a/src/main/agent-hooks/server/last-status-store.ts b/src/main/agent-hooks/server/last-status-store.ts new file mode 100644 index 00000000000..1b115f13b0f --- /dev/null +++ b/src/main/agent-hooks/server/last-status-store.ts @@ -0,0 +1,106 @@ +import { dirname, join } from 'node:path' + +import { KeyedJsonRowCache, type KeyedJsonRow } from '../../sqlite/row-cache/keyed-json-row-cache' +import type { LastStatusFile } from './server-types' +import { assemble, LAST_STATUS_SCHEMA_VERSION, rowsOf } from './last-status-saved-rows' + +export type SavedStatus = { document: unknown; source: 'legacy' | 'rows' } + +export function lastStatusDatabasePath(legacyJsonPath: string): string { + return join(dirname(legacyJsonPath), 'last-status.db') +} + +/** + * Restart cache for agent status, one row per pane, per authority commitment, plus the exit + * list: a save rewrites only rows whose content changed. It runs on the main thread, so it + * never waits on another connection's lock beyond the caller's small bound. + */ +export class LastStatusStore { + private readonly cache: KeyedJsonRowCache + private savedRows: KeyedJsonRow[] = [] + /** The older build's file read at startup, until hydration admits or rejects it. */ + private legacyReceipt: string | undefined + private pendingImport: string | undefined + /** + * Set when the saved rows or an older build's file could not be read at startup. The session + * then neither writes nor deletes, so rows it never read and a file it never imported both + * survive for a later start. Authority commitments are then not persisted this session, as + * when the JSON file was unwritable before. + */ + private disabled = false + + constructor(legacyJsonPath: string) { + this.cache = new KeyedJsonRowCache(lastStatusDatabasePath(legacyJsonPath), { + schemaVersion: LAST_STATUS_SCHEMA_VERSION, + busyTimeoutMs: 0, + legacyPath: legacyJsonPath + }) + } + + get isDisabled(): boolean { + return this.disabled + } + + /** The saved document (unvalidated) and where it came from, or undefined when none. */ + read(busyTimeoutMs: number): SavedStatus | undefined { + const loaded = this.cache.load(parseDocument, busyTimeoutMs) + if (loaded.kind === 'unavailable') { + this.disabled = true + throw loaded.error + } + this.savedRows = loaded.rows + if (loaded.kind === 'import') { + this.legacyReceipt = loaded.receipt + return { document: loaded.value.document, source: 'legacy' } + } + return this.readRows() + } + + /** The saved rows from the last read, for when hydration rejects a legacy file. */ + readRows(): SavedStatus | undefined { + return this.savedRows.length > 0 + ? { document: assemble(this.savedRows), source: 'rows' } + : undefined + } + + /** Hydration admitted the legacy file; the next commit records it imported and removes it. */ + confirmLegacyImport(): void { + this.pendingImport = this.legacyReceipt + } + + /** Hydration rejected the legacy file: remove it and keep the rows. */ + rejectLegacy(): void { + if (this.legacyReceipt !== undefined) { + this.cache.discardLegacy(this.legacyReceipt) + this.legacyReceipt = undefined + } + } + + /** Writes changed rows in one transaction; throws on lock or I/O failure for a later retry. */ + write(file: LastStatusFile, busyTimeoutMs: number): boolean { + if (this.disabled) { + return false + } + this.cache.write(rowsOf(file), { importReceipt: this.pendingImport, busyTimeoutMs }) + this.pendingImport = undefined + this.legacyReceipt = undefined + return true + } + + close(): void { + this.cache.close() + this.savedRows = [] + this.legacyReceipt = undefined + this.pendingImport = undefined + this.disabled = false + } +} + +function parseDocument(text: string): { document: unknown } | null { + try { + return { document: JSON.parse(text) } + } catch { + console.warn('[agent-hooks] last-status file is not valid JSON; ignoring') + return null + } +} diff --git a/src/main/agent-hooks/server/server-constants.ts b/src/main/agent-hooks/server/server-constants.ts index 602c59866ac..3e0d3f17737 100644 --- a/src/main/agent-hooks/server/server-constants.ts +++ b/src/main/agent-hooks/server/server-constants.ts @@ -7,8 +7,14 @@ export const CODEX_SUBAGENT_POLL_MS = 1_000 // Version 1 lacked ordering clocks; mismatched caches hydrate empty. export const LAST_STATUS_FILE_VERSION = 2 -// Throttle ordinary writes; authority changes bypass the window and quit flushes synchronously. -export const STATUS_PERSIST_MIN_INTERVAL_MS = 5_000 +// Saved status only seeds the "restored, unconfirmed" view after a restart, so routine saves can +// wait minutes; authority changes bypass the window and quit, hook-disable and stop flush now. +export const STATUS_PERSIST_MIN_INTERVAL_MS = 3 * 60_000 +// A failed save (often another connection's lock) retries on its own short backoff. +export const STATUS_PERSIST_RETRY_MIN_MS = 1_000 +export const STATUS_PERSIST_RETRY_MAX_MS = 30_000 +// Routine saves never wait on a lock; quit-time flushes wait at most this long. +export const STATUS_FLUSH_BUSY_TIMEOUT_MS = 200 export const AGENT_PROMPT_SENT_AGENT_KINDS = new Set(AGENT_KIND_VALUES) // Expire orphaned PTY rows so old work cannot resurrect on hydration. diff --git a/src/main/agent-hooks/server/server-hydration.ts b/src/main/agent-hooks/server/server-hydration.ts index 24bbedab96d..ebabcfb7ad3 100644 --- a/src/main/agent-hooks/server/server-hydration.ts +++ b/src/main/agent-hooks/server/server-hydration.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs' - import { admitLegacyAgentStatus, clearLegacyAgentStatuses @@ -11,7 +9,8 @@ import { import { seedCodexStateFromSnapshot } from '../../../shared/agent-hook-listener/providers/codex-state' import { AGENT_STATUS_PERSISTED_HYDRATION_MODE } from '../../../shared/agent-status/transport/agent-status-legacy-adapter' import { AGENT_STATUS_HYDRATE_MAX_AGE_MS as HYDRATE_MAX_AGE_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' -import { LAST_STATUS_FILE_VERSION } from './server-constants' +import { LAST_STATUS_FILE_VERSION, STATUS_FLUSH_BUSY_TIMEOUT_MS } from './server-constants' +import type { SavedStatus } from './last-status-store' import type { EnrichedAgentHookEventPayload, LastStatusFile } from './server-types' import { authorityCommitmentsMatch, @@ -33,26 +32,43 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup clearLegacyAgentStatuses(this.state) this.hydratedLaunchTokenHashByPaneKey.clear() this.persistedAuthorityCommitmentsByPaneKey.clear() - let raw: string + const store = this.getStatusStore() + let saved: SavedStatus | undefined try { - raw = readFileSync(this.lastStatusFilePath, 'utf8') + saved = store?.read(STATUS_FLUSH_BUSY_TIMEOUT_MS) } catch (err) { - // Why: missing file is normal (first launch); other errors degrade to empty hydration + one warn. - if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { - console.warn('[agent-hooks] failed to read last-status file:', err) + // Status is a restart cache; an unreadable store degrades to empty hydration + one warn. + // The store then stays read-only for this session, so rows it never read survive. + console.warn('[agent-hooks] failed to read saved agent status:', err) + return + } + if (!store || !saved) { + return + } + if (saved.source === 'legacy') { + if (this.admitSavedStatus(saved.document)) { + // Only an admitted file is recorded as imported, once rows holding it commit. + store.confirmLegacyImport() + } else { + // A rejected file must not stand in for the rows: drop it and restore those instead. + store.rejectLegacy() + const rows = store.readRows() + if (rows) { + this.admitSavedStatus(rows.document) + } } - return - } - let parsed: unknown - try { - parsed = JSON.parse(raw) - } catch { - console.warn('[agent-hooks] last-status file is not valid JSON; ignoring') - return + } else { + this.admitSavedStatus(saved.document) } + // Repairs and a migrated legacy file are saved now; an unchanged store writes nothing. + this.runStatusPersist() + } + + /** False when the document is rejected whole; nothing from it is admitted then. */ + private admitSavedStatus(parsed: unknown): boolean { if (typeof parsed !== 'object' || parsed === null) { console.warn('[agent-hooks] last-status file is not an object; ignoring') - return + return false } const file = parsed as Partial if (file.version !== LAST_STATUS_FILE_VERSION) { @@ -61,12 +77,12 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup file.version )} != ${LAST_STATUS_FILE_VERSION}); ignoring` ) - return + return false } const entries = file.entries if (typeof entries !== 'object' || entries === null) { console.warn('[agent-hooks] last-status file entries missing or wrong shape; ignoring') - return + return false } let hydrated = 0 let dropped = 0 @@ -163,12 +179,7 @@ export abstract class AgentHookServerHydration extends AgentHookServerTabCleanup `[agent-hooks] last-status hydrate dropped ${dropped} entries (kept ${hydrated})` ) } - if (dropped > 0 || prunedLegacyClaudeSubagents > 0 || scrubbedLegacyLaunchTokens > 0) { - this.runStatusPersist() - } else if (hydrated > 0) { - // Reuse raw bytes for dedup only after lossless hydration. - this.primeStatusPersistBaseline(raw) - } + return true } listUnconfirmedRestoredStatuses(): EnrichedAgentHookEventPayload[] { diff --git a/src/main/agent-hooks/server/server-lifecycle.ts b/src/main/agent-hooks/server/server-lifecycle.ts index 194d7c5c0d4..22035d2950a 100644 --- a/src/main/agent-hooks/server/server-lifecycle.ts +++ b/src/main/agent-hooks/server/server-lifecycle.ts @@ -20,7 +20,7 @@ import { trackEmptyPaneKeyHook } from './server-transport-rules' import { AgentHookServerStatusHookLifecycle } from './server-status-hook-lifecycle' import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../shared/agent-launch/startup/opencode-startup-prompt' import { CLAUDE_AGENT_VIEW_PATH } from '../../../shared/claude-agent-view' -import { respondAfterAgentToolPluginHooks } from '../agent-tool-plugin-hooks' +import { respondAfterAgentToolPluginHooks } from '../tool-events/agent-tool-plugin-hooks' import type { HookServerStartOptions } from './server-types' diff --git a/src/main/agent-hooks/server/server-persistence.ts b/src/main/agent-hooks/server/server-persistence.ts index c3767e2ffb8..3e955f2cb55 100644 --- a/src/main/agent-hooks/server/server-persistence.ts +++ b/src/main/agent-hooks/server/server-persistence.ts @@ -2,7 +2,13 @@ import { createHash } from 'node:crypto' import { isValidPaneKey } from './server-status-identity' import { AGENT_STATUS_HYDRATE_MAX_AGE_MS as HYDRATE_MAX_AGE_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' -import { LAST_STATUS_FILE_VERSION, STATUS_PERSIST_MIN_INTERVAL_MS } from './server-constants' +import { + LAST_STATUS_FILE_VERSION, + STATUS_FLUSH_BUSY_TIMEOUT_MS, + STATUS_PERSIST_MIN_INTERVAL_MS, + STATUS_PERSIST_RETRY_MAX_MS, + STATUS_PERSIST_RETRY_MIN_MS +} from './server-constants' import type { EnrichedAgentHookEventPayload, LastStatusFile, @@ -12,19 +18,26 @@ import type { import { authorityCommitmentsMatch } from './server-persistence-validation' import { AgentHookServerHydration } from './server-hydration' import { pruneAgentExits, serializeAgentExits } from './agent-exit-evidence' -import { AtomicSnapshotWriter } from '../../persistence/atomic-snapshot-writer' +import { LastStatusStore } from './last-status-store' +import { nextRetryDelayMs } from '../../sqlite/row-cache/row-cache-failure' export abstract class AgentHookServerPersistence extends AgentHookServerHydration { - private statusSnapshotWriter: AtomicSnapshotWriter | null = null - private statusSnapshotWriterPath: string | null = null + private statusStore: LastStatusStore | null = null + private statusStorePath: string | null = null private statusPersistFailing = false + private statusPersistRetryDelayMs = 0 + private statusPersistRetryAt = 0 - protected serializeStatusFile(): string { + protected buildStatusFile(): LastStatusFile { const entries: Record = {} const authorityCommitments: Record = {} const conflictedCommitments = new Set() + // Restart drops anything older than the TTL, so saving it would only carry dead rows forward. + const ttlCutoff = Date.now() - HYDRATE_MAX_AGE_MS for (const [paneKey, commitment] of this.persistedAuthorityCommitmentsByPaneKey) { - authorityCommitments[paneKey] = { ...commitment } + if (commitment.observedAt >= ttlCutoff) { + authorityCommitments[paneKey] = { ...commitment } + } } for (const [paneKey, payload] of this.state.lastStatusByPaneKey) { // Why: never persist invalid keys (matches the hydrate-path invariant). @@ -33,7 +46,7 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio } const enrichedPayload = payload as EnrichedAgentHookEventPayload // Journal projections must not compete with unconfirmed copies hydrated from this cache. - if (enrichedPayload.structuredHost) { + if (enrichedPayload.structuredHost || enrichedPayload.receivedAt < ttlCutoff) { continue } const { @@ -77,17 +90,20 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio } } // Panes without successor agents would otherwise retain exit evidence forever. - pruneAgentExits(this.agentExitedAtByPaneKey, Date.now() - HYDRATE_MAX_AGE_MS, (paneKey) => + pruneAgentExits(this.agentExitedAtByPaneKey, ttlCutoff, (paneKey) => this.state.lastStatusByPaneKey.has(paneKey) ) - const agentExits = serializeAgentExits(this.agentExitedAtByPaneKey) - const file: LastStatusFile = { + // Runtime keeps an old exit for a live row; the saved copy keeps it only beside a saved row. + const agentExits = serializeAgentExits(this.agentExitedAtByPaneKey).filter( + (exit) => + exit.at >= ttlCutoff || exit.paneKeys.some((paneKey) => Object.hasOwn(entries, paneKey)) + ) + return { version: LAST_STATUS_FILE_VERSION, entries, authorityCommitments, ...(agentExits.length > 0 ? { agentExits } : {}) } - return JSON.stringify(file) } // Leading-edge throttling prevents event streams from postponing writes indefinitely (#26720). @@ -99,12 +115,14 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio // Persist authority changes immediately to preserve spool replay filtering after a crash. const urgent = this.currentAuthorityFingerprint() !== this.lastPersistedAuthorityFingerprint // A wall-clock rollback must not defer persistence indefinitely. - const dueAt = urgent + const throttledAt = urgent ? now : Math.min( this.lastStatusPersistStartedAt + STATUS_PERSIST_MIN_INTERVAL_MS, now + STATUS_PERSIST_MIN_INTERVAL_MS ) + // After a failed save every attempt, urgent or not, waits for the short retry backoff. + const dueAt = this.statusPersistRetryAt > now ? this.statusPersistRetryAt : throttledAt if (this.statusPersistTimer) { if (dueAt >= this.statusPersistDueAt) { return @@ -114,7 +132,7 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio this.statusPersistDueAt = Math.max(dueAt, now) this.statusPersistTimer = setTimeout(() => { this.statusPersistTimer = null - this.startStatusPersist() + this.runStatusPersist() }, this.statusPersistDueAt - now) // Quit flushes synchronously; this timer must not keep the runtime alive. if (typeof this.statusPersistTimer.unref === 'function') { @@ -122,60 +140,71 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio } } - flushStatusPersistSync(): void { + /** Quit, stop and hook-disable: one bounded lock wait, then the failure is reported. */ + flushStatusPersistSync(): boolean { this.cancelStatusPersistTimer() if (!this.lastStatusFilePath) { - return + return true } - this.runStatusPersist() + return this.runStatusPersist(STATUS_FLUSH_BUSY_TIMEOUT_MS) } - /** Quit, hook-disable and hydration repair need synchronous writes; routine updates are async. */ - protected runStatusPersist(): void { - const writer = this.getStatusSnapshotWriter() - if (!writer) { - return + /** Writes only changed rows; a failure (including a held lock) retries with backoff. */ + protected runStatusPersist(busyTimeoutMs = 0): boolean { + const store = this.getStatusStore() + if (!store) { + return true + } + if (store.isDisabled) { + // Nothing reaches disk this session; flush callers must not read that as saved. + return false } this.lastStatusPersistStartedAt = Date.now() - this.lastPersistedAuthorityFingerprint = this.currentAuthorityFingerprint() + const fingerprint = this.currentAuthorityFingerprint() try { - writer.writeSync(() => this.serializeStatusFile()) - this.statusPersistFailing = false + store.write(this.buildStatusFile(), busyTimeoutMs) } catch (err) { this.reportStatusPersistFailure(err) + this.statusPersistRetryDelayMs = nextRetryDelayMs(this.statusPersistRetryDelayMs, { + minMs: STATUS_PERSIST_RETRY_MIN_MS, + maxMs: STATUS_PERSIST_RETRY_MAX_MS + }) + this.statusPersistRetryAt = Date.now() + this.statusPersistRetryDelayMs + // Retry even if no later mutation arrives. + this.scheduleStatusPersist() + return false } - } - - protected primeStatusPersistBaseline(onDiskJson: string): void { - this.getStatusSnapshotWriter()?.primeCommittedContent(onDiskJson) - this.lastPersistedAuthorityFingerprint = this.currentAuthorityFingerprint() + // Only a committed save can stand in for the authority it carries. + this.lastPersistedAuthorityFingerprint = fingerprint + this.statusPersistFailing = false + this.statusPersistRetryDelayMs = 0 + this.statusPersistRetryAt = 0 + return true } protected closeStatusSnapshotWriter(): void { this.cancelStatusPersistTimer() - this.statusSnapshotWriter?.close() - this.statusSnapshotWriter = null - this.statusSnapshotWriterPath = null + this.statusStore?.close() + this.statusStore = null + this.statusStorePath = null this.lastStatusPersistStartedAt = Number.NEGATIVE_INFINITY this.lastPersistedAuthorityFingerprint = null this.statusPersistFailing = false + this.statusPersistRetryDelayMs = 0 + this.statusPersistRetryAt = 0 } - protected getStatusSnapshotWriter(): AtomicSnapshotWriter | null { + protected getStatusStore(): LastStatusStore | null { const filePath = this.lastStatusFilePath if (!filePath) { return null } - if (!this.statusSnapshotWriter || this.statusSnapshotWriterPath !== filePath) { - this.statusSnapshotWriter?.close() - this.statusSnapshotWriter = new AtomicSnapshotWriter(() => filePath, { - fileMode: 0o600, - directoryMode: 0o700, - skipUnchanged: true - }) - this.statusSnapshotWriterPath = filePath + if (!this.statusStore || this.statusStorePath !== filePath) { + this.statusStore?.close() + this.statusStore = new LastStatusStore(filePath) + this.statusStorePath = filePath } - return this.statusSnapshotWriter + return this.statusStore } /** Revision counters and live tokens avoid per-event hashing or serialization. */ @@ -191,30 +220,6 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio return fingerprint } - private startStatusPersist(): void { - const writer = this.getStatusSnapshotWriter() - if (!writer) { - return - } - this.lastStatusPersistStartedAt = Date.now() - this.lastPersistedAuthorityFingerprint = this.currentAuthorityFingerprint() - writer - .write(() => this.serializeStatusFile()) - .then( - () => { - this.statusPersistFailing = false - }, - (err: unknown) => { - if (this.statusSnapshotWriter !== writer) { - return - } - this.reportStatusPersistFailure(err) - // Retry even if no later mutation arrives. - this.scheduleStatusPersist() - } - ) - } - private cancelStatusPersistTimer(): void { if (this.statusPersistTimer) { clearTimeout(this.statusPersistTimer) @@ -224,7 +229,7 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio private reportStatusPersistFailure(err: unknown): void { if (!this.statusPersistFailing) { - console.warn('[agent-hooks] failed to write last-status file:', err) + console.warn('[agent-hooks] failed to save agent status:', err) } this.statusPersistFailing = true } diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index 7d785558d47..50540e4d621 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -56,6 +56,7 @@ import type { } from './server-types' import { RevisionedMap } from './revisioned-map' import { forgetAgentExit, type AgentExitEvidence } from './agent-exit-evidence' +import type { LastStatusStore } from './last-status-store' export abstract class AgentHookServerState { protected canWriteLegacyStatusRow(entry: AgentHookEventPayload): boolean { @@ -308,10 +309,9 @@ export abstract class AgentHookServerState { payload: AgentHookEventPayload | EnrichedAgentHookEventPayload, launchTokenHashOverride?: string ): AgentHookAuthorityEvidence | null - protected abstract serializeStatusFile(): string protected abstract scheduleStatusPersist(): void - protected abstract runStatusPersist(): void - protected abstract primeStatusPersistBaseline(onDiskJson: string): void + protected abstract runStatusPersist(): boolean + protected abstract getStatusStore(): LastStatusStore | null abstract _getStateForTests(): HookListenerState abstract _resetPromptSentDedupeForTests(): void diff --git a/src/main/agent-hooks/server-accepted-reply.test.ts b/src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts similarity index 84% rename from src/main/agent-hooks/server-accepted-reply.test.ts rename to src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts index 2a873d3d9fd..9b3bb13694b 100644 --- a/src/main/agent-hooks/server-accepted-reply.test.ts +++ b/src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts @@ -1,15 +1,16 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import { mainAgentDoneAt } from '../../shared/agent-status/lifecycle/main-agent-status' -import type { AutomationRun } from '../../shared/automations/history/automation-run' -import { createRuntimeAutomationRunTerminalObserver } from '../automations/runtime-terminal-run-observer' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' +import { mainAgentDoneAt } from '../../../../../shared/agent-status/lifecycle/main-agent-status' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { createRuntimeAutomationRunTerminalObserver } from '../../../../automations/runtime-terminal-run-observer' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) @@ -58,7 +59,7 @@ describe('accepted lead reply', () => { expect(replyForCurrentRow()).toBe(REPLY) server.flushStatusPersistSync() for (const published of [ - readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8'), + readSavedStatus(join(userDataPath, 'agent-hooks', 'last-status.json')), JSON.stringify(server.getStatusSnapshot()) ]) { expect(published).not.toContain('MIDDLE-MARKER') diff --git a/src/main/agent-hooks/server-closed-tab-suppression.test.ts b/src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts similarity index 97% rename from src/main/agent-hooks/server-closed-tab-suppression.test.ts rename to src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts index 8e171a99a38..70dafb046a5 100644 --- a/src/main/agent-hooks/server-closed-tab-suppression.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts @@ -1,20 +1,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createHash } from 'node:crypto' -import { AgentHookServer, _internals } from './server' -import { CLOSED_AGENT_STATUS_TAB_IDS_MAX } from './server/server-constants' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { buildBody, PANE, LEAF_2, LEAF_3 } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { CLOSED_AGENT_STATUS_TAB_IDS_MAX } from '../../server-constants' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { buildBody, PANE, LEAF_2, LEAF_3 } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-omp-retired-ingress.test.ts b/src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts similarity index 90% rename from src/main/agent-hooks/server-omp-retired-ingress.test.ts rename to src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts index 1cb38afb372..2746269d8a1 100644 --- a/src/main/agent-hooks/server-omp-retired-ingress.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) afterEach(() => vi.restoreAllMocks()) const working = { agentType: 'omp', state: 'working', prompt: 'new turn' } diff --git a/src/main/agent-hooks/server-omp-retirement-ack.test.ts b/src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts similarity index 92% rename from src/main/agent-hooks/server-omp-retirement-ack.test.ts rename to src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts index ae0bfe338f6..ebf219467eb 100644 --- a/src/main/agent-hooks/server-omp-retirement-ack.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { GOOD_PANE, PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { GOOD_PANE, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) const ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' const hook = { paneKey: PANE, diff --git a/src/main/agent-hooks/server-pane-authority.test.ts b/src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts similarity index 96% rename from src/main/agent-hooks/server-pane-authority.test.ts rename to src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts index e1ebfc2df6e..d7449fc32e0 100644 --- a/src/main/agent-hooks/server-pane-authority.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' -import { PANE_KEY_ALIASES_MAX } from './server/server-constants' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE_KEY_ALIASES_MAX } from '../../server-constants' const SOURCE = makePaneKey('tab-source', '11111111-1111-4111-8111-111111111111') const TARGET = makePaneKey('tab-target', '22222222-2222-4222-8222-222222222222') diff --git a/src/main/agent-hooks/server-reminted-pane-key.test.ts b/src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts similarity index 90% rename from src/main/agent-hooks/server-reminted-pane-key.test.ts rename to src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts index 14f63089f48..3b580b0f963 100644 --- a/src/main/agent-hooks/server-reminted-pane-key.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts @@ -1,20 +1,21 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { readSavedStatus, hasSavedStatus } from '../persistence/last-status.test-fixtures' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, GOOD_PANE, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, GOOD_PANE, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) @@ -80,10 +81,10 @@ describe('reminted $$ pane keys on the OMP hook pipeline', () => { }) ]) server.flushStatusPersistSync() - expect(existsSync(lastStatusPath())).toBe(true) - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) as { + expect(hasSavedStatus(lastStatusPath())).toBe(true) + const file: { entries: Record - } + } = JSON.parse(readSavedStatus(lastStatusPath())) expect(file.entries[PANE]?.payload.state).toBe('done') expect(file.entries[REMINTED]).toBeUndefined() } finally { diff --git a/src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts similarity index 93% rename from src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts rename to src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts index 62606e5729c..cbc55586b5c 100644 --- a/src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts @@ -1,11 +1,12 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import { createHash } from 'node:crypto' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { LEAF_1 } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { LEAF_1 } from '../server.test-fixtures' const REMOVED = 'repo::/removed' const KEPT = 'repo::/kept' @@ -72,7 +73,7 @@ describe('removed-worktree foreign authority', () => { expect(server.getCurrentAuthorityObservations()).toEqual([]) server.flushStatusPersistSync() const file = JSON.parse( - readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8') + readSavedStatus(join(userDataPath, 'agent-hooks', 'last-status.json')) ) expect(file.authorityCommitments[PANE]).toBeUndefined() } finally { @@ -141,7 +142,7 @@ describe('removed-worktree foreign authority', () => { ) server.flushStatusPersistSync() const file = JSON.parse( - readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8') + readSavedStatus(join(userDataPath, 'agent-hooks', 'last-status.json')) ) expect(file.authorityCommitments[PANE]).toMatchObject({ worktreeId: KEPT, @@ -219,7 +220,7 @@ describe('removed-worktree foreign authority', () => { } server.flushStatusPersistSync() const file = JSON.parse( - readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8') + readSavedStatus(join(userDataPath, 'agent-hooks', 'last-status.json')) ) expect(file.authorityCommitments[PANE]).toMatchObject({ worktreeId: KEPT, diff --git a/src/main/agent-hooks/server-removed-worktree-status.test.ts b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts similarity index 92% rename from src/main/agent-hooks/server-removed-worktree-status.test.ts rename to src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts index e05dbe504e3..25f7c5d74f4 100644 --- a/src/main/agent-hooks/server-removed-worktree-status.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts @@ -1,10 +1,11 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { LEAF_1, LEAF_2, LEAF_3, LEAF_4, LEAF_5, recentTs } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { LEAF_1, LEAF_2, LEAF_3, LEAF_4, LEAF_5, recentTs } from '../server.test-fixtures' const REMOVED = 'repo-1::/workspace/removed' const KEPT = 'repo-1::/workspace/kept' @@ -72,7 +73,7 @@ describe('AgentHookServer removed-worktree retirement', () => { server.clearStatusEntriesForConnection('idle@box') const persisted = () => { server.flushStatusPersistSync() - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + const file = JSON.parse(readSavedStatus(lastStatusPath())) return { entries: Object.keys(file.entries).sort(), commitments: Object.keys(file.authorityCommitments ?? {}) @@ -156,7 +157,7 @@ describe('AgentHookServer removed-worktree retirement', () => { reportLocally('done') server.flushStatusPersistSync() - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + const file = JSON.parse(readSavedStatus(lastStatusPath())) if (localWorktree === REMOVED) { expect(file.authorityCommitments?.[pane]).toMatchObject({ worktreeId: KEPT }) expect(file.entries[pane]).toBeUndefined() diff --git a/src/main/agent-hooks/server-retired-pane-new-turn.test.ts b/src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts similarity index 91% rename from src/main/agent-hooks/server-retired-pane-new-turn.test.ts rename to src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts index ab9e005bed0..66dbcaf20dd 100644 --- a/src/main/agent-hooks/server-retired-pane-new-turn.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts @@ -1,14 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import type { AgentHookSource } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ trackMock: vi.fn(), getCohortAtEmitMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-claude-statusline.test.ts b/src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-statusline.test.ts rename to src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts index edb5008a285..0f5132ad5ca 100644 --- a/src/main/agent-hooks/server-claude-statusline.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer } from './server' -import type { ClaudeStatusLineRateLimits } from '../../shared/claude-statusline-rate-limits' +import { AgentHookServer } from '../../agent-hook-server' +import type { ClaudeStatusLineRateLimits } from '../../../../../shared/claude-statusline-rate-limits' describe('AgentHookServer /statusline/claude', () => { let server: AgentHookServer diff --git a/src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts b/src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts similarity index 96% rename from src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts index fc7a48b7f87..ee591caafaf 100644 --- a/src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts @@ -12,18 +12,18 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' +import { AgentHookServer, _internals } from '../../agent-hook-server' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-hook-http-ingest.test.ts b/src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts similarity index 96% rename from src/main/agent-hooks/server-hook-http-ingest.test.ts rename to src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts index d5ba925b721..0d12cee0e50 100644 --- a/src/main/agent-hooks/server-hook-http-ingest.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-startup-lifecycle.test.ts b/src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts similarity index 85% rename from src/main/agent-hooks/server-startup-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts index 59153450bb0..e81d00e1006 100644 --- a/src/main/agent-hooks/server-startup-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts @@ -2,17 +2,20 @@ import { afterEach, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import type { drainAgentHookSpoolAsync } from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import type * as HookSpoolModule from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import { getEndpointFileName } from '../../shared/agent-hook-listener/transport/endpoint-publication' +import { AgentHookServer } from '../../agent-hook-server' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import type { drainAgentHookSpoolAsync } from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import type * as HookSpoolModule from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import { getEndpointFileName } from '../../../../../shared/agent-hook-listener/transport/endpoint-publication' const drain = vi.hoisted(() => vi.fn()) -vi.mock('../../shared/agent-hook-listener/transport/agent-hook-spool', async (importOriginal) => ({ - ...(await importOriginal()), - drainAgentHookSpoolAsync: drain -})) +vi.mock( + '../../../../../shared/agent-hook-listener/transport/agent-hook-spool', + async (importOriginal) => ({ + ...(await importOriginal()), + drainAgentHookSpoolAsync: drain + }) +) const directories: string[] = [] const servers: { stop: () => void }[] = [] diff --git a/src/main/agent-hooks/server-startup-prompt-control.test.ts b/src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts similarity index 84% rename from src/main/agent-hooks/server-startup-prompt-control.test.ts rename to src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts index 87827926b68..db4c6ce33b4 100644 --- a/src/main/agent-hooks/server-startup-prompt-control.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts @@ -1,11 +1,12 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { readSavedStatus, hasSavedStatus } from '../persistence/last-status.test-fixtures' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { parseAgentHookEndpointFile } from '../../shared/agent-hook-listener/transport/agent-hook-endpoint-file' -import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../shared/agent-launch/startup/opencode-startup-prompt' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { parseAgentHookEndpointFile } from '../../../../../shared/agent-hook-listener/transport/agent-hook-endpoint-file' +import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../../../shared/agent-launch/startup/opencode-startup-prompt' +import { PANE } from '../server.test-fixtures' describe('startup prompt control with status hooks disabled', () => { it.each([false, true])( @@ -28,8 +29,8 @@ describe('startup prompt control with status hooks disabled', () => { throw new Error('missing status persistence path') } server.stop() - expect(existsSync(statusPath)).toBe(true) - expect(JSON.parse(readFileSync(statusPath, 'utf8')).entries[PANE]).toMatchObject({ + expect(hasSavedStatus(statusPath)).toBe(true) + expect(JSON.parse(readSavedStatus(statusPath)).entries[PANE]).toMatchObject({ paneKey: PANE, worktreeId: 'folder-1', payload: { state: 'done', prompt: 'terminal status survives quit', agentType: 'opencode' } diff --git a/src/main/agent-hooks/server-transport-interference.test.ts b/src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts similarity index 93% rename from src/main/agent-hooks/server-transport-interference.test.ts rename to src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts index 12d8f354dec..e8b6ce0d085 100644 --- a/src/main/agent-hooks/server-transport-interference.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts @@ -2,10 +2,10 @@ import { connect } from 'node:net' import { IncomingMessage, ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HookTransportInterferenceReport } from '../../shared/agent-hook-listener/transport/agent-hook-transport-interference' -import { AgentHookServer } from './server' -import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../shared/agent-launch/startup/opencode-startup-prompt' -import { HOOK_REQUEST_SLOWLORIS_MS } from '../../shared/agent-hook-listener/listener-limits' +import type { HookTransportInterferenceReport } from '../../../../../shared/agent-hook-listener/transport/agent-hook-transport-interference' +import { AgentHookServer } from '../../agent-hook-server' +import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../../../shared/agent-launch/startup/opencode-startup-prompt' +import { HOOK_REQUEST_SLOWLORIS_MS } from '../../../../../shared/agent-hook-listener/listener-limits' async function postTruncatedHook( port: number, diff --git a/src/main/agent-hooks/server-ai-vault-liveness.test.ts b/src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts similarity index 92% rename from src/main/agent-hooks/server-ai-vault-liveness.test.ts rename to src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts index b19c9dcdcec..16f29b1072c 100644 --- a/src/main/agent-hooks/server-ai-vault-liveness.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts @@ -2,8 +2,8 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' const PANE = makePaneKey('external-live', '11111111-1111-4111-8111-111111111111') const PROVIDER_SESSION = { key: 'session_id' as const, id: 'session-live' } diff --git a/src/main/agent-hooks/server-claude-resume-record-continuity.test.ts b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-resume-record-continuity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts index 480d4f35423..6ba51d5812e 100644 --- a/src/main/agent-hooks/server-claude-resume-record-continuity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts @@ -2,9 +2,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from './server/program-status/hook-precedence' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../program-status/hook-precedence' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' const SESSION = '70efcb3f-ae17-4863-9318-649f5469408b' diff --git a/src/main/agent-hooks/server-claude-session-continuation.test.ts b/src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts similarity index 83% rename from src/main/agent-hooks/server-claude-session-continuation.test.ts rename to src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts index 3cb205c11b8..4cdf640a915 100644 --- a/src/main/agent-hooks/server-claude-session-continuation.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts @@ -1,15 +1,16 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { readSavedStatus } from '../persistence/last-status.test-fixtures' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' -import { buildBody, GOOD_PANE, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' +import { buildBody, GOOD_PANE, PANE, postHookEvent } from '../server.test-fixtures' const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) @@ -104,7 +105,7 @@ describe('Claude session continued into a daemon job', () => { expect(after?.prompt).toBe(before?.prompt) server.flushStatusPersistSync() const persisted = JSON.parse( - readFileSync(join(root, 'orca', 'agent-hooks', 'last-status.json'), 'utf8') + readSavedStatus(join(root, 'orca', 'agent-hooks', 'last-status.json')) ) expect(persisted.entries[PANE].providerSession.id).toBe(FORK) }) diff --git a/src/main/agent-hooks/server-copilot-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-copilot-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts index a6b595c350d..476e1a49bfe 100644 --- a/src/main/agent-hooks/server-copilot-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts @@ -2,12 +2,12 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import { AgentHookServer } from './server' -import { type Body, buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import { AgentHookServer } from '../../agent-hook-server' +import { type Body, buildBody, PANE, postHookEvent } from '../server.test-fixtures' const ROOT = 'cf0e6ff2-9ede-46de-a430-5778cf8da164' const CHILD = 'copilot-helper' diff --git a/src/main/agent-hooks/server-hermes-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-hermes-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts index 66691cd4422..d53513294c4 100644 --- a/src/main/agent-hooks/server-hermes-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts @@ -2,14 +2,14 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const ROOT = 'local-parent' const CHILD = '20261024_child' diff --git a/src/main/agent-hooks/server-hook-session-binding.test.ts b/src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts similarity index 87% rename from src/main/agent-hooks/server-hook-session-binding.test.ts rename to src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts index cc2b7889686..072fd90e027 100644 --- a/src/main/agent-hooks/server-hook-session-binding.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts @@ -1,44 +1,49 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import type { BrowserWindow } from 'electron' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { HookSessionBindingRendererFixture } from '../../shared/agent-hook-listener/state/agent-hook-session-binding.test-fixture' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { HookSessionBindingRendererFixture } from '../../../../../shared/agent-hook-listener/state/agent-hook-session-binding.test-fixture' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { createHookListenerState, admitLegacyAgentStatus -} from '../../shared/agent-hook-listener/listener-state' -import { readAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence' -import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../shared/agent-status/transport/agent-status-legacy-adapter' -import { getDefaultWorkspaceSession } from '../../shared/constants' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { RelayProviderHookNormalization } from '../../wsl-guest/agent-hook-provider-normalization' -import { hookRowPaneResumeRecord } from '../runtime/session-lifecycle/projection/hook-row-pane-resume-record' +} from '../../../../../shared/agent-hook-listener/listener-state' +import { readAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence' +import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../../../shared/agent-status/transport/agent-status-legacy-adapter' +import { getDefaultWorkspaceSession } from '../../../../../shared/constants' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { RelayProviderHookNormalization } from '../../../../../wsl-guest/agent-hook-provider-normalization' +import { hookRowPaneResumeRecord } from '../../../../runtime/session-lifecycle/projection/hook-row-pane-resume-record' import { hookStatusResumeCommand, quitResumeRecords, resumeStatusFromHookRow -} from '../runtime/terminal/stop/hook-status-resume-records' +} from '../../../../runtime/terminal/stop/hook-status-resume-records' import { installMainWindowAgentStatusListeners, clearMainWindowAgentStatusListeners -} from '../startup/main-window-agent-status' -import { agentHookServer as server } from './server' -import { buildBody, PANE, GOOD_PANE, postHookEvent } from './server.test-fixtures' +} from '../../../../startup/main-window-agent-status' +import { agentHookServer as server } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE, postHookEvent } from '../server.test-fixtures' const bridge = vi.hoisted(() => ({ send: vi.fn<(channel: string, data: AgentStatusIpcPayload) => void>() })) -vi.mock('../startup/main-process-state', () => ({ +vi.mock('../../../../startup/main-process-state', () => ({ mainProcessState: { mainWindow: { isDestroyed: () => false, webContents: bridge }, runtime: null } })) -vi.mock('../window/dashboard-popout-window', () => ({ getDashboardPopoutWindow: () => null })) -vi.mock('../startup/synthetic-title-runtime', () => ({ stopSyntheticTitleSpinnerTimer: () => {} })) +vi.mock('../../../../window/dashboard-popout-window', () => ({ + getDashboardPopoutWindow: () => null +})) +vi.mock('../../../../startup/synthetic-title-runtime', () => ({ + stopSyntheticTitleSpinnerTimer: () => {} +})) const rendererFixture: unknown = await vi.importActual( - '../../renderer/src/store/slices/agent-status/hook-session-binding-renderer.test-fixture' + '../../../../../renderer/src/store/slices/agent-status/hook-session-binding-renderer.test-fixture' ) function isRendererFixture(value: unknown): value is HookSessionBindingRendererFixture { return ( @@ -253,8 +258,9 @@ it.each([257, 512])( server.stop() // Exact legacy representation: a helper ID with no positive observation of its own. const path = join(dir, 'agent-hooks', 'last-status.json') - const saved = JSON.parse(readFileSync(path, 'utf8')) + const saved = JSON.parse(readSavedStatus(path)) saved.entries[PANE].agentPresence.session = id + // An older build's file wins over the saved rows on the next start. writeFileSync(path, JSON.stringify(saved)) await restart() await tool('different-session') diff --git a/src/main/agent-hooks/server-launch-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts similarity index 92% rename from src/main/agent-hooks/server-launch-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts index f6f1978f31b..396f7741356 100644 --- a/src/main/agent-hooks/server-launch-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const RESUMED = { key: 'session_id' as const, id: 'resumed-session' } diff --git a/src/main/agent-hooks/server-nested-agent-boundaries.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts similarity index 92% rename from src/main/agent-hooks/server-nested-agent-boundaries.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts index 8bf72bf7640..7570c06c56e 100644 --- a/src/main/agent-hooks/server-nested-agent-boundaries.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-agent-consumers.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts similarity index 83% rename from src/main/agent-hooks/server-nested-agent-consumers.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts index 847d65015bd..c9e1a79d245 100644 --- a/src/main/agent-hooks/server-nested-agent-consumers.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { buildRuntimeMobileAgentStatus } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildRuntimeMobileAgentStatus } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-agent-model.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts similarity index 90% rename from src/main/agent-hooks/server-nested-agent-model.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts index deb4119d6e4..6691b0afd49 100644 --- a/src/main/agent-hooks/server-nested-agent-model.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-same-provider-owner.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts similarity index 83% rename from src/main/agent-hooks/server-nested-same-provider-owner.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts index 477bedac070..7dbc60dff96 100644 --- a/src/main/agent-hooks/server-nested-same-provider-owner.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-opencode-writer-observation.test.ts b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts similarity index 81% rename from src/main/agent-hooks/server-opencode-writer-observation.test.ts rename to src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts index 5c206bf848d..ff1f3b0170c 100644 --- a/src/main/agent-hooks/server-opencode-writer-observation.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts @@ -1,26 +1,20 @@ import { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture -} from '../runtime/terminal/identity/agent-status-observed-pane-identity' -import { OPEN_CODE_WRITER_TOPOLOGY } from './server/cli-writer-observation' -import { toAgentStatusIpcPayload } from './server/server-status-identity' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' +} from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' +import { OPEN_CODE_WRITER_TOPOLOGY } from '../../cli-writer-observation' +import { toAgentStatusIpcPayload } from '../../server-status-identity' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: async () => 'unverifiable' })) -class WriterObservationTestServer extends AgentHookServer { - persistedWriterState(): string { - return this.serializeStatusFile() - } -} - const servers: AgentHookServer[] = [] afterEach(() => { for (const server of servers.splice(0)) { @@ -28,8 +22,8 @@ afterEach(() => { } }) -async function createServer(): Promise { - const server = new WriterObservationTestServer() +async function createServer(): Promise { + const server = new AgentHookServer() servers.push(server) await server.start({ env: 'production' }) return server @@ -120,7 +114,6 @@ describe('OpenCode writer observation', () => { expect(JSON.stringify(value)).not.toContain('pane-owned') expect(Object.getOwnPropertySymbols(structuredClone(value).providerSession ?? {})).toEqual([]) } - expect(server.persistedWriterState()).not.toContain('pane-owned') for (const extra of [{}, { opencodeSharedServer: 1 }]) { await post(extra) expect(observation()?.topology).not.toBe('pane-owned') diff --git a/src/main/agent-hooks/terminal-handle-row-identity.test.ts b/src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts similarity index 92% rename from src/main/agent-hooks/terminal-handle-row-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts index 9ab60d53759..80bcf54ef99 100644 --- a/src/main/agent-hooks/terminal-handle-row-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { selectFreshExplicitAgentStatus } from '../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' -import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' +import { AgentHookServer } from '../../agent-hook-server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { selectFreshExplicitAgentStatus } from '../../../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { wslHookRelayConnectionId } from '../../../../../shared/wsl-hook-relay-contract' const PANE_KEY = 'tab-handle:33333333-3333-4333-8333-333333333333' const HANDLE = 'term_identity' diff --git a/src/main/agent-hooks/claude-cancel-capture.test-fixture.ts b/src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts similarity index 91% rename from src/main/agent-hooks/claude-cancel-capture.test-fixture.ts rename to src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts index bb5dcf75fbd..2b9eafd496f 100644 --- a/src/main/agent-hooks/claude-cancel-capture.test-fixture.ts +++ b/src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { AGENT_INTERRUPT_SETTLE_MS } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' +import { AGENT_INTERRUPT_SETTLE_MS } from '../../../../../shared/agent-status/lifecycle/agent-interrupt-intent' const capturedHook = z.object({ kind: z.literal('hook'), @@ -28,7 +28,7 @@ export type CapturedRecord = z.infer export function loadCapture(name: string): CapturedRecord[] { return readFileSync( - join(__dirname, '..', '..', 'shared', '__fixtures__', `${name}.jsonl`), + join(__dirname, '..', '..', '..', '..', '..', 'shared', '__fixtures__', `${name}.jsonl`), 'utf8' ) .trim() diff --git a/src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts b/src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts similarity index 86% rename from src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts rename to src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts index f46e2d488df..ba117bf65b0 100644 --- a/src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts +++ b/src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { extractAllOscTitleEntries } from '../../shared/agent-status/title/osc-title-extraction' +import { extractAllOscTitleEntries } from '../../../../../shared/agent-status/title/osc-title-extraction' const captureEvent = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('title'), title: z.string(), atMs: z.number() }), @@ -9,7 +9,7 @@ const captureEvent = z.discriminatedUnion('kind', [ ]) export function loadClaudeInterruptCapture(name: string) { - const base = join(__dirname, '../runtime/__fixtures__', `claude-interrupt-${name}`) + const base = join(__dirname, '../../../../runtime/__fixtures__', `claude-interrupt-${name}`) const transcript = readFileSync(`${base}.txt`, 'utf8') const events = z.array(captureEvent).parse(JSON.parse(readFileSync(`${base}.input.json`, 'utf8'))) const titleEntries = extractAllOscTitleEntries(transcript) diff --git a/src/main/agent-hooks/server-claude-helper-kill.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts similarity index 91% rename from src/main/agent-hooks/server-claude-helper-kill.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts index fe25c65c80b..79d2fb290f8 100644 --- a/src/main/agent-hooks/server-claude-helper-kill.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts @@ -2,15 +2,15 @@ import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/pro import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { selectFreshExplicitAgentStatus } from '../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' -import { selectRuntimeHookAgentRowForPane } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection' -import { buildRunningAgentChildRowModels } from '../../shared/running-agent-child-rows' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { selectFreshExplicitAgentStatus } from '../../../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { selectRuntimeHookAgentRowForPane } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection' +import { buildRunningAgentChildRowModels } from '../../../../../shared/running-agent-child-rows' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) const servers: { stop: () => void }[] = [] @@ -44,7 +44,7 @@ async function host(kind: string, initial: Record[] = []) { ( await readFile( new URL( - `../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, + `../../../../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, import.meta.url ), 'utf8' diff --git a/src/main/agent-hooks/server-claude-helper-recovery.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-helper-recovery.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts index e7702995c23..cada292132b 100644 --- a/src/main/agent-hooks/server-claude-helper-recovery.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts @@ -4,17 +4,17 @@ import { tmpdir } from 'node:os' import { createServer } from 'node:http' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { ClaudeHelperKillPoller } from '../../shared/agent-hook-listener/providers/claude-helper-kill-poller' -import '../../shared/agent-hook-listener/providers/claude-transcript-decoder' -import * as cursor from '../../shared/agent-hook-listener/providers/claude-transcript-cursor' -import '../../shared/agent-hook-listener/transcripts/agent-transcript-poll-scheduler' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { ClaudeHelperKillPoller } from '../../../../../shared/agent-hook-listener/providers/claude-helper-kill-poller' +import '../../../../../shared/agent-hook-listener/providers/claude-transcript-decoder' +import * as cursor from '../../../../../shared/agent-hook-listener/providers/claude-transcript-cursor' +import '../../../../../shared/agent-hook-listener/transcripts/agent-transcript-poll-scheduler' // Complete captured lifecycle records, with runtime replay seeded by real persisted HTTP state. -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) const servers: { stop: () => void }[] = [] @@ -51,7 +51,7 @@ async function load(stream: string): Promise[]> { return ( await readFile( new URL( - `../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, + `../../../../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, import.meta.url ), 'utf8' diff --git a/src/main/agent-hooks/server-claude-terminal-interrupt.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts similarity index 94% rename from src/main/agent-hooks/server-claude-terminal-interrupt.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts index 5a0b6885950..25271e944cf 100644 --- a/src/main/agent-hooks/server-claude-terminal-interrupt.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from '../server.test-fixtures' import { loadClaudeInterruptCapture } from './claude-terminal-interrupt-capture.test-fixture' -import { createTerminalTitleTracker } from '../../shared/terminal/output/terminal-output-side-effects' +import { createTerminalTitleTracker } from '../../../../../shared/terminal/output/terminal-output-side-effects' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) let server: AgentHookServer diff --git a/src/main/agent-hooks/server-interrupt-inference-guards.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts similarity index 98% rename from src/main/agent-hooks/server-interrupt-inference-guards.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts index 08940da57fd..80d23e8188a 100644 --- a/src/main/agent-hooks/server-interrupt-inference-guards.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts similarity index 96% rename from src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts index 61dc79c709c..8e7022748c9 100644 --- a/src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-relayed-claude-cancel.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts similarity index 97% rename from src/main/agent-hooks/server-relayed-claude-cancel.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts index 671ddbf97aa..cef90654fd8 100644 --- a/src/main/agent-hooks/server-relayed-claude-cancel.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts @@ -3,9 +3,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' import { hookAt, loadCapture, type CapturedHook } from './claude-cancel-capture.test-fixture' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ @@ -13,8 +13,8 @@ const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const temporaryPaths: string[] = [] const running: { stop: () => void }[] = [] diff --git a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts similarity index 94% rename from src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts index 46464397956..f711a261ae2 100644 --- a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-turn-ended-at.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts similarity index 97% rename from src/main/agent-hooks/server-turn-ended-at.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts index 695f97cfd0a..6289c4c35f3 100644 --- a/src/main/agent-hooks/server-turn-ended-at.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts @@ -2,11 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) // Only identified turns or verified Stop revisions mint an end; repeats and ambiguity never mint another. describe('the host-stamped turn end', () => { diff --git a/src/main/agent-hooks/server-turn-started-at.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts similarity index 90% rename from src/main/agent-hooks/server-turn-started-at.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts index dd3749e0b99..c315a61c31f 100644 --- a/src/main/agent-hooks/server-turn-started-at.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts @@ -1,17 +1,18 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() @@ -124,9 +125,7 @@ describe('the host-stamped turn start', () => { expect(pushed.at(-1)).toBe(started) server.flushStatusPersistSync() server.stop() - const file = JSON.parse( - readFileSync(join(userDataPath, 'agent-hooks', 'last-status.json'), 'utf8') - ) + const file = JSON.parse(readSavedStatus(join(userDataPath, 'agent-hooks', 'last-status.json'))) expect(file.entries[PANE].turnStartedAt).toBe(started) const restarted = await startServer() diff --git a/src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts index c376744fbf0..57e55ea2ebb 100644 --- a/src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts @@ -1,14 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-claude-permission-batch-release.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts similarity index 98% rename from src/main/agent-hooks/server-claude-permission-batch-release.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts index d7edeca89c0..b0dd862a04c 100644 --- a/src/main/agent-hooks/server-claude-permission-batch-release.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-claude-permission-tool-failure.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-permission-tool-failure.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts index 6248d8f238f..08fb7a0fed7 100644 --- a/src/main/agent-hooks/server-claude-permission-tool-failure.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-claude-permission-visibility.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts similarity index 98% rename from src/main/agent-hooks/server-claude-permission-visibility.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts index 660c6dc2500..294a901f15d 100644 --- a/src/main/agent-hooks/server-claude-permission-visibility.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server/testing/persistence/last-status.test-fixtures.ts b/src/main/agent-hooks/server/testing/persistence/last-status.test-fixtures.ts new file mode 100644 index 00000000000..4a2dcda0489 --- /dev/null +++ b/src/main/agent-hooks/server/testing/persistence/last-status.test-fixtures.ts @@ -0,0 +1,42 @@ +import { existsSync, mkdirSync } from 'node:fs' +import { dirname } from 'node:path' + +import SyncDatabase from '../../../../sqlite/sync-database' +import { lastStatusDatabasePath } from '../../last-status-store' +import { assemble } from '../../last-status-saved-rows' + +/** What a restart restores, in the last-status file shape, read straight from the saved rows. */ +export function readSavedStatus(lastStatusPath: string): string { + const db = new SyncDatabase(lastStatusDatabasePath(lastStatusPath), { + readonly: true, + fileMustExist: true + }) + try { + const rows = db + .prepare('SELECT key, value FROM rows ORDER BY seq') + .all() + .map((row) => ({ key: String(row.key), json: String(row.value) })) + const { agentExits, ...file } = assemble(rows) + return JSON.stringify(agentExits.length > 0 ? { ...file, agentExits } : file) + } finally { + db.close() + } +} + +export function hasSavedStatus(lastStatusPath: string): boolean { + if (!existsSync(lastStatusDatabasePath(lastStatusPath))) { + return false + } + return Object.keys(JSON.parse(readSavedStatus(lastStatusPath)).entries).length > 0 +} + +/** Another connection holding the write lock, as a second process would. */ +export function holdSavedStatusLock(lastStatusPath: string): () => void { + mkdirSync(dirname(lastStatusPath), { recursive: true }) + const db = new SyncDatabase(lastStatusDatabasePath(lastStatusPath)) + db.exec('BEGIN EXCLUSIVE') + return () => { + db.exec('ROLLBACK') + db.close() + } +} diff --git a/src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts index c666a276b2a..3f36e949da2 100644 --- a/src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts index 50f927557ef..5df796b53a5 100644 --- a/src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE, GOOD_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE, GOOD_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-hydrate-validation.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts similarity index 71% rename from src/main/agent-hooks/server-last-status-hydrate-validation.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts index 09c2db1e40c..b3701652b41 100644 --- a/src/main/agent-hooks/server-last-status-hydrate-validation.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts @@ -1,38 +1,29 @@ +import { readSavedStatus, hasSavedStatus } from './last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - statSync, - utimesSync, - writeFileSync -} from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { buildBody, postHookEvent, recentTs, PANE, GOOD_PANE, - LEAF_2, - LEAF_5 -} from './server.test-fixtures' + LEAF_2 +} from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) @@ -124,42 +115,18 @@ describe('Last-status persistence', () => { buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'about to drop' }) ) server.flushStatusPersistSync() - let parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + let parsed = JSON.parse(readSavedStatus(lastStatusPath())) expect(parsed.entries[PANE]).toBeTruthy() server.clearPaneState(PANE) server.flushStatusPersistSync() - parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + parsed = JSON.parse(readSavedStatus(lastStatusPath())) expect(parsed.entries[PANE]).toBeUndefined() } finally { server.stop() } }) - it('skips a write when the serialized contents are byte-identical to the previous write', async () => { - const server = new AgentHookServer() - await server.start({ - env: 'production', - userDataPath - }) - try { - await postHookEvent( - server, - buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'first' }) - ) - server.flushStatusPersistSync() - utimesSync(lastStatusPath(), 1, 1) - const firstMtime = statSync(lastStatusPath()).mtimeMs - - server.clearPaneState(makePaneKey('non-existent', LEAF_5)) - server.flushStatusPersistSync() - const secondMtime = statSync(lastStatusPath()).mtimeMs - expect(secondMtime).toBe(firstMtime) - } finally { - server.stop() - } - }) - it('stop() flushes pending debounced writes synchronously', async () => { const server = new AgentHookServer() await server.start({ @@ -175,8 +142,8 @@ describe('Last-status persistence', () => { } finally { server.stop() } - expect(existsSync(lastStatusPath())).toBe(true) - const parsed = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + expect(hasSavedStatus(lastStatusPath())).toBe(true) + const parsed = JSON.parse(readSavedStatus(lastStatusPath())) expect(parsed.entries[PANE]?.payload?.prompt).toBe('flush me') }) }) diff --git a/src/main/agent-hooks/server-last-status-lead-boundary.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts similarity index 95% rename from src/main/agent-hooks/server-last-status-lead-boundary.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts index 35f22f1f239..6d428b401dd 100644 --- a/src/main/agent-hooks/server-last-status-lead-boundary.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-last-status-main-agent-fact.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts similarity index 95% rename from src/main/agent-hooks/server-last-status-main-agent-fact.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts index 252dcf47233..51baddf328d 100644 --- a/src/main/agent-hooks/server-last-status-main-agent-fact.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts new file mode 100644 index 00000000000..d11d5b340ed --- /dev/null +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-migration.test.ts @@ -0,0 +1,94 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { recentTs, PANE } from '../server.test-fixtures' +import { holdSavedStatusLock } from './last-status.test-fixtures' + +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: () => ({ nth_repo_added: 2 }) +})) + +describe('saved agent status from an older build', () => { + let userDataPath: string + const lastStatusPath = (): string => join(userDataPath, 'agent-hooks', 'last-status.json') + const writeLegacyFile = (prompt: string): void => { + mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true }) + writeFileSync( + lastStatusPath(), + JSON.stringify({ + version: 2, + entries: { + [PANE]: { + paneKey: PANE, + tabId: 'tab-1', + receivedAt: recentTs(), + stateStartedAt: recentTs(), + payload: { state: 'done', prompt, agentType: 'claude' } + } + } + }) + ) + } + const restoredPrompt = async (): Promise => { + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + try { + return server.getStatusSnapshot()[0]?.prompt + } finally { + server.stop() + } + } + + beforeEach(() => { + _internals.resetCachesForTests() + userDataPath = mkdtempSync(join(tmpdir(), 'orca-last-status-migration-')) + }) + + afterEach(() => { + rmSync(userDataPath, { recursive: true, force: true }) + }) + + it('moves the old file into the saved rows once and keeps restoring from them', async () => { + writeLegacyFile('from the old file') + + expect(await restoredPrompt()).toBe('from the old file') + expect(existsSync(lastStatusPath())).toBe(false) + expect(await restoredPrompt()).toBe('from the old file') + }) + + it('leaves the old file alone for a session whose rows cannot be read', async () => { + writeLegacyFile('from the old file') + const release = holdSavedStatusLock(lastStatusPath()) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + release() + server.stop() + expect(existsSync(lastStatusPath())).toBe(true) + + expect(await restoredPrompt()).toBe('from the old file') + expect(existsSync(lastStatusPath())).toBe(false) + }) + + it('keeps the saved rows when an old file is rejected', async () => { + writeLegacyFile('saved in rows') + expect(await restoredPrompt()).toBe('saved in rows') + writeFileSync(lastStatusPath(), 'null') + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect(await restoredPrompt()).toBe('saved in rows') + expect(existsSync(lastStatusPath())).toBe(false) + expect(await restoredPrompt()).toBe('saved in rows') + }) + + it('prefers a file an older build wrote after the rows were saved', async () => { + writeLegacyFile('first') + expect(await restoredPrompt()).toBe('first') + + writeLegacyFile('written by an older build later') + expect(await restoredPrompt()).toBe('written by an older build later') + }) +}) diff --git a/src/main/agent-hooks/server-last-status-restored-children.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-restored-children.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts index cb4f96ba0df..812b2270511 100644 --- a/src/main/agent-hooks/server-last-status-restored-children.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-write.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts similarity index 91% rename from src/main/agent-hooks/server-last-status-write.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts index 2f04341bc41..27365f808c8 100644 --- a/src/main/agent-hooks/server-last-status-write.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts @@ -1,21 +1,22 @@ +import { readSavedStatus, hasSavedStatus } from './last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) @@ -67,8 +68,8 @@ describe('Last-status persistence', () => { ) ) server.flushStatusPersistSync() - expect(existsSync(lastStatusPath())).toBe(true) - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + expect(hasSavedStatus(lastStatusPath())).toBe(true) + const file = JSON.parse(readSavedStatus(lastStatusPath())) expect(file.version).toBe(2) expect(file.entries[PANE]).toMatchObject({ paneKey: PANE, @@ -92,7 +93,7 @@ describe('Last-status persistence', () => { state: 'done', stateStartedAt: expect.any(Number) }) - expect(readFileSync(lastStatusPath(), 'utf8')).not.toContain('launch-bearer-must-not-persist') + expect(readSavedStatus(lastStatusPath())).not.toContain('launch-bearer-must-not-persist') } finally { server.stop() } @@ -135,7 +136,7 @@ describe('Last-status persistence', () => { ]) expect(server.getStatusSnapshotForPane(PANE)[0]?.launchToken).toBeUndefined() - const persisted = readFileSync(lastStatusPath(), 'utf8') + const persisted = readSavedStatus(lastStatusPath()) expect(persisted).not.toContain(launchToken) expect(JSON.parse(persisted).entries[PANE]).toMatchObject({ launchTokenHash }) } finally { @@ -192,7 +193,7 @@ describe('Last-status persistence', () => { first.flushStatusPersistSync() first.stop() - const afterClear = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + const afterClear = JSON.parse(readSavedStatus(lastStatusPath())) expect(afterClear.entries).toEqual({}) expect(afterClear.authorityCommitments[PANE]).toMatchObject({ paneKey: PANE, @@ -263,7 +264,7 @@ describe('Last-status persistence', () => { expect(trackMock).not.toHaveBeenCalledWith('agent_prompt_sent', expect.anything()) firstServer.flushStatusPersistSync() - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) + const file = JSON.parse(readSavedStatus(lastStatusPath())) expect(file.entries[PANE]).toMatchObject({ providerSessionOnly: true, providerSession: { diff --git a/src/main/agent-hooks/server-observation-provenance.test.ts b/src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts similarity index 78% rename from src/main/agent-hooks/server-observation-provenance.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts index 707c6de2479..62bfbf2a44e 100644 --- a/src/main/agent-hooks/server-observation-provenance.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts @@ -1,17 +1,18 @@ +import { hasSavedStatus, readSavedStatus } from './last-status.test-fixtures' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const LEAF = '11111111-1111-4111-8111-111111111111' const PANE = makePaneKey('tab-1', LEAF) @@ -60,8 +61,8 @@ describe('agent status observation provenance', () => { server.flushStatusPersistSync() const path = join(userDataPath, 'agent-hooks', 'last-status.json') - expect(existsSync(path)).toBe(true) - const file = readFileSync(path, 'utf8') + expect(hasSavedStatus(path)).toBe(true) + const file = readSavedStatus(path) // Process-local sequencing cannot remain ordering authority after restart. expect(file).not.toContain('observation') expect(JSON.parse(file).entries[PANE].observation).toBeUndefined() diff --git a/src/main/agent-hooks/server-restored-agent-status.test.ts b/src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts similarity index 92% rename from src/main/agent-hooks/server-restored-agent-status.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts index 49d29fef55e..7ab071e2870 100644 --- a/src/main/agent-hooks/server-restored-agent-status.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { GOOD_PANE as REMOTE_PANE, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { GOOD_PANE as REMOTE_PANE, PANE } from '../server.test-fixtures' describe('restored agent status', () => { let userDataPath: string diff --git a/src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts b/src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts new file mode 100644 index 00000000000..1c418ec3b7d --- /dev/null +++ b/src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts @@ -0,0 +1,90 @@ +import { holdSavedStatusLock, readSavedStatus } from './last-status.test-fixtures' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' + +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) +})) + +describe('saved agent status cadence', () => { + let userDataPath: string + let server: AgentHookServer + + const lastStatusPath = (): string => join(userDataPath, 'agent-hooks', 'last-status.json') + const readPrompt = (): unknown => + JSON.parse(readSavedStatus(lastStatusPath())).entries[PANE]?.payload?.prompt + const prompt = (text: string, launchToken?: string): Promise => + postHookEvent( + server, + buildBody( + { hook_event_name: 'UserPromptSubmit', prompt: text }, + launchToken ? { launchToken } : {} + ) + ) + + beforeEach(async () => { + _internals.resetCachesForTests() + // Real loopback POSTs need fake time to advance. + vi.useFakeTimers({ + shouldAdvanceTime: true, + toFake: ['setTimeout', 'clearTimeout', 'Date'] + }) + userDataPath = mkdtempSync(join(tmpdir(), 'orca-persist-throttle-')) + server = new AgentHookServer() + await server.start({ env: 'production', userDataPath }) + }) + + afterEach(() => { + server.stop() + vi.useRealTimers() + vi.restoreAllMocks() + rmSync(userDataPath, { recursive: true, force: true }) + }) + + it('saves an authority change at once while a routine update waits for the window', async () => { + await prompt('first') + await vi.advanceTimersByTimeAsync(1) + expect(readPrompt()).toBe('first') + + await prompt('second') + await vi.advanceTimersByTimeAsync(1) + expect(readPrompt()).toBe('first') + + await prompt('third', 'launch-token-new') + await vi.advanceTimersByTimeAsync(1) + expect(JSON.parse(readSavedStatus(lastStatusPath())).entries[PANE]).toMatchObject({ + launchTokenHash: expect.any(String), + payload: expect.objectContaining({ prompt: 'third' }) + }) + }) + + it('saves the latest status at stop and a restart keeps it', async () => { + await prompt('first') + await vi.advanceTimersByTimeAsync(1) + await prompt('final before stop') + + server.stop() + expect(readPrompt()).toBe('final before stop') + + await server.start({ env: 'production', userDataPath }) + expect(server.getStatusSnapshot()[0]?.prompt).toBe('final before stop') + }) + + it('saves an authority change within seconds once a held lock clears', async () => { + await prompt('first') + await vi.advanceTimersByTimeAsync(1) + const release = holdSavedStatusLock(lastStatusPath()) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + await prompt('new owner', 'launch-token-new') + await vi.advanceTimersByTimeAsync(1) + release() + + await vi.advanceTimersByTimeAsync(2_000) + expect(readPrompt()).toBe('new owner') + }) +}) diff --git a/src/main/agent-hooks/server-agent-presence.test.ts b/src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts similarity index 91% rename from src/main/agent-hooks/server-agent-presence.test.ts rename to src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts index 3dbaad35f30..1eb588b08c5 100644 --- a/src/main/agent-hooks/server-agent-presence.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts @@ -2,16 +2,16 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async (): Promise<'live' | 'unverifiable' | 'exited'> => 'unverifiable') ) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-hook-root-acquisition.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts similarity index 97% rename from src/main/agent-hooks/server-hook-root-acquisition.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts index 08ef8a93e59..982b2de7ba6 100644 --- a/src/main/agent-hooks/server-hook-root-acquisition.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts @@ -2,9 +2,9 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import type { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import type { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { NOW, CLAUDE, @@ -23,9 +23,9 @@ import { registerRootTestHarness } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root-provenance.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts similarity index 96% rename from src/main/agent-hooks/server-hook-root-provenance.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts index 862168007bb..d926d208476 100644 --- a/src/main/agent-hooks/server-hook-root-provenance.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { PANE } from './server.test-fixtures' +import { PANE } from '../server.test-fixtures' -import '../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import '../../wsl-guest/agent-hook-server' -import '../../wsl-guest/relay-pane-root' -import './local-tmux-managed-pty' +import '../../../../../wsl-guest/agent-hook-server' +import '../../../../../wsl-guest/relay-pane-root' +import '../../../observations/local-tmux-managed-pty' import { NOW, @@ -35,9 +35,9 @@ import { type Proc } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root-replay.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts similarity index 94% rename from src/main/agent-hooks/server-hook-root-replay.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts index 7fb1e4ffdd0..ea3922d640d 100644 --- a/src/main/agent-hooks/server-hook-root-replay.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts @@ -2,15 +2,15 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { PANE } from './server.test-fixtures' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { PANE } from '../server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { readHookRootEvidence, type HookPaneRoot -} from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { startOrcadAgentHookServer } from '../orcad/orcad-managed-agent-hooks' +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { startOrcadAgentHookServer } from '../../../../orcad/orcad-managed-agent-hooks' import { NOW, CLAUDE, @@ -29,9 +29,9 @@ import { type Proc } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root.test-fixtures.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts similarity index 93% rename from src/main/agent-hooks/server-hook-root.test-fixtures.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts index f02642ab2db..c1944c69eed 100644 --- a/src/main/agent-hooks/server-hook-root.test-fixtures.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts @@ -1,15 +1,15 @@ import { rmSync } from 'node:fs' import { afterEach, beforeEach, expect, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import type { AgentProcessIdentity } from '../../shared/agent-status/process/agent-process-presence' -import { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import type { AgentProcessIdentity } from '../../../../../shared/agent-status/process/agent-process-presence' +import { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' import { readHookRootEvidence, type HookPaneProcessIo, type HookPaneRoot -} from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { ProcessTableRow } from '../../shared/process-table-snapshot' +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { ProcessTableRow } from '../../../../../shared/process-table-snapshot' // Shared harness for the hook server's pane-root acquisition tests. Each test file mocks // '../telemetry/client', '../telemetry/cohort-classifier' and the process probe module. diff --git a/src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts b/src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts similarity index 88% rename from src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts index d21d4b41347..c314525df3a 100644 --- a/src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts @@ -1,12 +1,12 @@ import { afterEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-idle-process-owner.test.ts b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts similarity index 95% rename from src/main/agent-hooks/server-idle-process-owner.test.ts rename to src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts index c09295979e0..f16f83c8204 100644 --- a/src/main/agent-hooks/server-idle-process-owner.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts @@ -2,16 +2,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { buildRuntimeMobileAgentStatus } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildRuntimeMobileAgentStatus } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-amp-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts similarity index 92% rename from src/main/agent-hooks/server-amp-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts index bf6f5061b78..8dccccd8d43 100644 --- a/src/main/agent-hooks/server-amp-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { _internals } from '../../../agent-hook-server' +import { buildBody } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-antigravity-background-command-hold.test.ts b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts similarity index 87% rename from src/main/agent-hooks/server-antigravity-background-command-hold.test.ts rename to src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts index ace807b350a..d1b29eaad49 100644 --- a/src/main/agent-hooks/server-antigravity-background-command-hold.test.ts +++ b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts @@ -2,10 +2,10 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from './server/program-status/hook-precedence' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../../program-status/hook-precedence' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' let dir: string let server: AgentHookServer diff --git a/src/main/agent-hooks/server-antigravity-resume-identity.test.ts b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-antigravity-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts index bf0f0373028..d33950bbfd3 100644 --- a/src/main/agent-hooks/server-antigravity-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import { TRANSCRIPT_MAX_SCAN_BYTES } from '../../shared/agent-hook-listener/transcript-reader' -import { AgentHookServer } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../../shared/agent-launch/startup/agent-resume-argv' +import { TRANSCRIPT_MAX_SCAN_BYTES } from '../../../../../../shared/agent-hook-listener/transcript-reader' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' // Exact origin metadata and hook shape captured from agy 1.4.11; paths/IDs are test-local. const ROOT = '6bba92d4-47e1-440a-9571-b12bb2d474bc' diff --git a/src/main/agent-hooks/server-claude-blocked-prompt.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts similarity index 88% rename from src/main/agent-hooks/server-claude-blocked-prompt.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts index 7110215005a..92df34ee30c 100644 --- a/src/main/agent-hooks/server-claude-blocked-prompt.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { createProgramStatusProjector } from '../../shared/program-status/agent-status-projector' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' +import { createProgramStatusProjector } from '../../../../../../shared/program-status/agent-status-projector' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) let server: AgentHookServer let projector: ReturnType diff --git a/src/main/agent-hooks/server-claude-config-dir-observation.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts similarity index 74% rename from src/main/agent-hooks/server-claude-config-dir-observation.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts index 91c4082e2f4..51245f74e48 100644 --- a/src/main/agent-hooks/server-claude-config-dir-observation.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts @@ -2,14 +2,14 @@ import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, GOOD_PANE, PANE, postHookEvent } from './server.test-fixtures' -import { ClaudeObservedConfigDirs } from '../claude-accounts/claude-observed-config-dirs' -import { installClaudeObservedConfigDirs } from '../claude-accounts/claude-profile-installed-router' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, GOOD_PANE, PANE, postHookEvent } from '../../server.test-fixtures' +import { ClaudeObservedConfigDirs } from '../../../../../claude-accounts/claude-observed-config-dirs' +import { installClaudeObservedConfigDirs } from '../../../../../claude-accounts/claude-profile-installed-router' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: async () => 'live' })) diff --git a/src/main/agent-hooks/server-claude-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts index 6318211f1ba..4d6f9f42f38 100644 --- a/src/main/agent-hooks/server-claude-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { _internals } from '../../../agent-hook-server' +import { buildBody } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-codex-capacity.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts similarity index 92% rename from src/main/agent-hooks/server-codex-capacity.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts index 879b52edb24..9df7e909d78 100644 --- a/src/main/agent-hooks/server-codex-capacity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { CODEX_CAPACITY_MESSAGE } from '../../shared/codex-native-notice' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' +import { CODEX_CAPACITY_MESSAGE } from '../../../../../../shared/codex-native-notice' afterEach(() => _internals.resetCachesForTests()) diff --git a/src/main/agent-hooks/server-codex-interrupt-hook.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts similarity index 92% rename from src/main/agent-hooks/server-codex-interrupt-hook.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts index aa8360341ef..cd72f4f9ee3 100644 --- a/src/main/agent-hooks/server-codex-interrupt-hook.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-codex-review-turn-end.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts similarity index 95% rename from src/main/agent-hooks/server-codex-review-turn-end.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts index b1a0dc190f7..c437a330f66 100644 --- a/src/main/agent-hooks/server-codex-review-turn-end.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts @@ -9,13 +9,13 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, postHookEvent } from '../../server.test-fixtures' // Captured from a completed Codex CLI 0.159.0 /review; session and turn IDs were replaced. const reviewRecords = readFileSync( - new URL('./__fixtures__/codex-review-child-0159.jsonl', import.meta.url), + new URL('../../../../__fixtures__/codex-review-child-0159.jsonl', import.meta.url), 'utf8' ) .trimEnd() diff --git a/src/main/agent-hooks/server-codex-side-thread.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts similarity index 98% rename from src/main/agent-hooks/server-codex-side-thread.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts index bf9d3a9a323..b2602cf3297 100644 --- a/src/main/agent-hooks/server-codex-side-thread.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, postHookEvent } from '../../server.test-fixtures' // Shapes captured from Codex 0.164: a /side fork is its own session with no rollout. const MAIN = '01a16f91-ac03-73f2-acdc-2bc83dbedce3' diff --git a/src/main/agent-hooks/server-codex-subagent-transcript.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts similarity index 97% rename from src/main/agent-hooks/server-codex-subagent-transcript.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts index 744554663a0..575ca65c93c 100644 --- a/src/main/agent-hooks/server-codex-subagent-transcript.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts @@ -3,8 +3,8 @@ import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') const CHILD_ID = '019fa65f-3144-7151-9c02-cff7a28f316f' diff --git a/src/main/agent-hooks/server-codex-turn-interruption.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts similarity index 97% rename from src/main/agent-hooks/server-codex-turn-interruption.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts index d3ffcb886e8..5cdced2e665 100644 --- a/src/main/agent-hooks/server-codex-turn-interruption.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { PANE } from '../../server.test-fixtures' const line = (payload: unknown): string => `${JSON.stringify({ type: 'event_msg', payload })}\n` diff --git a/src/main/agent-hooks/server-cursor-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts similarity index 90% rename from src/main/agent-hooks/server-cursor-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts index 9948bf9e90f..f61b10697c1 100644 --- a/src/main/agent-hooks/server-cursor-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { agentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-grok-background-status.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts similarity index 94% rename from src/main/agent-hooks/server-grok-background-status.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts index b298d7ceec4..399b5bc6f81 100644 --- a/src/main/agent-hooks/server-grok-background-status.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts @@ -2,17 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { AgentSessionTransitionRecorder } from '../stats/agent-session-transition-recorder' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { AgentSessionTransitionRecorder } from '../../../../../stats/agent-session-transition-recorder' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-grok-cancel.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts similarity index 83% rename from src/main/agent-hooks/server-grok-cancel.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts index 52f0a1d5e04..1237c8122ee 100644 --- a/src/main/agent-hooks/server-grok-cancel.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts @@ -1,16 +1,18 @@ // Grok 1.0.70: Esc never cancels and Ctrl+C can open a stop dialog; only StopCancelled reports a cancel. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import type { AgentInterruptInputIntent } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' +import type { AgentInterruptInputIntent } from '../../../../../../shared/agent-status/lifecycle/agent-interrupt-intent' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-grok-discovery.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts similarity index 94% rename from src/main/agent-hooks/server-grok-discovery.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts index 5570ab9d8cf..fd5ab84b161 100644 --- a/src/main/agent-hooks/server-grok-discovery.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts @@ -2,9 +2,9 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import * as agentHookListener from '../../shared/agent-hook-listener/grok-result-discovery' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' +import * as agentHookListener from '../../../../../../shared/agent-hook-listener/grok-result-discovery' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') diff --git a/src/main/agent-hooks/server-muse-session-log-poll.test.ts b/src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts similarity index 95% rename from src/main/agent-hooks/server-muse-session-log-poll.test.ts rename to src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts index f0f60cc36f5..34cc0f7728f 100644 --- a/src/main/agent-hooks/server-muse-session-log-poll.test.ts +++ b/src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts @@ -3,9 +3,9 @@ import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'n import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import type { EnrichedAgentHookEventPayload } from './server/server-types' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import type { EnrichedAgentHookEventPayload } from '../../../server-types' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') const SESSION_ID = '01a0caa3-0e77-7d41-bad7-46283a45633d' diff --git a/src/main/agent-hooks/server-opencode-tui-identity.test.ts b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts similarity index 88% rename from src/main/agent-hooks/server-opencode-tui-identity.test.ts rename to src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts index bd87e0e315a..84bb1a998e4 100644 --- a/src/main/agent-hooks/server-opencode-tui-identity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts @@ -2,9 +2,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { lookupOpenCodeSessionPane } from '../../shared/agent-hook-listener/opencode-session-registry' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import { lookupOpenCodeSessionPane } from '../../../../../../shared/agent-hook-listener/opencode-session-registry' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_A = makePaneKey('tab-a', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') diff --git a/src/main/agent-hooks/server-status-listener-fanout.test.ts b/src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts similarity index 96% rename from src/main/agent-hooks/server-status-listener-fanout.test.ts rename to src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts index 8120569fb0f..2e5d11ed9e4 100644 --- a/src/main/agent-hooks/server-status-listener-fanout.test.ts +++ b/src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, GOOD_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/ended-process-reconciliation.test.ts b/src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts similarity index 96% rename from src/main/agent-hooks/ended-process-reconciliation.test.ts rename to src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts index 9d0be0aceba..9a94104ed0e 100644 --- a/src/main/agent-hooks/ended-process-reconciliation.test.ts +++ b/src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts @@ -2,9 +2,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const LEAF = '11111111-1111-4111-8111-111111111111' const PANE = makePaneKey('tab-1', LEAF) diff --git a/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts similarity index 87% rename from src/main/agent-hooks/server-ingest-remote-codex-question.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts index a4a8469e713..b225204259e 100644 --- a/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts @@ -1,15 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { createHookListenerState, seedLegacyAgentStatusForTests -} from '../../shared/agent-hook-listener/listener-state' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { AgentHookServer, _internals } from './server' -import { PANE, buildBody } from './server.test-fixtures' +} from '../../../../../shared/agent-hook-listener/listener-state' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE, buildBody } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts similarity index 89% rename from src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts index fd9be19a4e2..4b8b6e4c152 100644 --- a/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts @@ -2,17 +2,17 @@ import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createShedSubagentsField } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { pollCodexTranscriptStatus } from '../../shared/agent-hook-listener/providers/codex-transcript-poll' -import { transcriptPollUpdate } from '../../shared/agent-hook-listener/transcript-poll-policy' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { AgentHookServer, _internals } from './server' -import { PANE, buildBody } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createShedSubagentsField } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { pollCodexTranscriptStatus } from '../../../../../shared/agent-hook-listener/providers/codex-transcript-poll' +import { transcriptPollUpdate } from '../../../../../shared/agent-hook-listener/transcript-poll-policy' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE, buildBody } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-ingest-remote.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts similarity index 79% rename from src/main/agent-hooks/server-ingest-remote.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts index d8286646eb5..1c727f7beed 100644 --- a/src/main/agent-hooks/server-ingest-remote.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts @@ -1,18 +1,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' -import { AGENT_STATUS_RUNS_RUNTIME_CAPABILITY } from '../../shared/agent-status/contracts/agent-status-run-capability' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { AGENT_STATUS_RUNS_RUNTIME_CAPABILITY } from '../../../../../shared/agent-status/contracts/agent-status-run-capability' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts b/src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts similarity index 90% rename from src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts rename to src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts index 24541691f72..71462710607 100644 --- a/src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts +++ b/src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts @@ -3,20 +3,20 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import { hookAt, loadCapture } from './claude-cancel-capture.test-fixture' -import selfDenied from '../claude/__fixtures__/claude-self-denied-permission-hooks.json' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' +import { hookAt, loadCapture } from '../interruptions/claude-cancel-capture.test-fixture' +import selfDenied from '../../../../claude/__fixtures__/claude-self-denied-permission-hooks.json' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const records = loadCapture('claude-permission-approve-deny-hooks') const prompt = hookAt(records, 0).payload diff --git a/src/main/agent-hooks/server-replay-evidence-clock.test.ts b/src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts similarity index 86% rename from src/main/agent-hooks/server-replay-evidence-clock.test.ts rename to src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts index e9c0bb4b3a4..599dfe50a0a 100644 --- a/src/main/agent-hooks/server-replay-evidence-clock.test.ts +++ b/src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import type { EnrichedAgentHookEventPayload } from './server/server-types' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import type { EnrichedAgentHookEventPayload } from '../../server-types' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const CONNECTION = 'conn-1' const T0 = 1_800_000_000_000 diff --git a/src/main/agent-hooks/spool.test.ts b/src/main/agent-hooks/server/testing/replay/spool.test.ts similarity index 94% rename from src/main/agent-hooks/spool.test.ts rename to src/main/agent-hooks/server/testing/replay/spool.test.ts index 412246660b6..110d8ca0302 100644 --- a/src/main/agent-hooks/spool.test.ts +++ b/src/main/agent-hooks/server/testing/replay/spool.test.ts @@ -1,3 +1,4 @@ +import { readSavedStatus } from '../persistence/last-status.test-fixtures' import { describe, expect, it } from 'vitest' import { appendFileSync, @@ -17,12 +18,12 @@ import { drainAgentHookSpoolAsync, launchTokenHash, type SpoolRecord -} from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import { AgentHookServer, _internals } from './server' -import { buildBody } from './server.test-fixtures' -import { _internals as codexInternals } from '../codex/hooks/installation/hook-service' -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-script' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +} from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody } from '../server.test-fixtures' +import { _internals as codexInternals } from '../../../../codex/hooks/installation/hook-service' +import { getManagedScript as getClaudeManagedScript } from '../../../../claude/hook-script' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' describe('agent hook spool', () => { it('waits for a newline before replaying a complete-looking final record', async () => { @@ -138,7 +139,7 @@ describe('agent hook spool', () => { expect(snapshot).toHaveLength(1) expect(snapshot[0]!.subagents).toBeUndefined() restarted.flushStatusPersistSync() - expect(readFileSync(restarted.lastStatusPath!, 'utf8')).not.toContain('isReplay') + expect(readSavedStatus(restarted.lastStatusPath!)).not.toContain('isReplay') } finally { restarted.stop() } diff --git a/src/main/agent-hooks/server.test-fixtures.ts b/src/main/agent-hooks/server/testing/server.test-fixtures.ts similarity index 93% rename from src/main/agent-hooks/server.test-fixtures.ts rename to src/main/agent-hooks/server/testing/server.test-fixtures.ts index 1479f9330ab..9b380067b2f 100644 --- a/src/main/agent-hooks/server.test-fixtures.ts +++ b/src/main/agent-hooks/server/testing/server.test-fixtures.ts @@ -1,5 +1,5 @@ -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import type { AgentHookServer } from './server' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { AgentHookServer } from '../agent-hook-server' export const LEAF_1 = '11111111-1111-4111-8111-111111111111' export const LEAF_2 = '22222222-2222-4222-8222-222222222222' diff --git a/src/main/agent-hooks/server-ingest-structured-state-clock.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts similarity index 89% rename from src/main/agent-hooks/server-ingest-structured-state-clock.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts index f4ff1bffb5e..c919c8780ca 100644 --- a/src/main/agent-hooks/server-ingest-structured-state-clock.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts @@ -1,10 +1,10 @@ // Use the session lifecycle clock across projections; older summaries retain ingest continuity. import { beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer, _internals } from './server' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentChildWorkEvidence } from '../../../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { makeStructuredAgentStatusSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' +import { AgentHookServer, _internals } from '../../agent-hook-server' const SESSION = 'b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e' const SUBJECT = makeStructuredAgentStatusSubject( diff --git a/src/main/agent-hooks/server-ingest-structured-status.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts similarity index 90% rename from src/main/agent-hooks/server-ingest-structured-status.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts index 08659472d24..cc49e5ec750 100644 --- a/src/main/agent-hooks/server-ingest-structured-status.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts @@ -1,28 +1,29 @@ -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' +import { readSavedStatus } from '../persistence/last-status.test-fixtures' +import { makeStructuredAgentStatusSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' +import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { isFreshNonDoneAgentStatus } from '../../shared/agent-status/contracts/agent-status-freshness' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentChildWorkEvidence } from '../../../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { isFreshNonDoneAgentStatus } from '../../../../../shared/agent-status/contracts/agent-status-freshness' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId -} from '../../shared/agent-session/view/structured-agent-session-projection' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +} from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) @@ -215,9 +216,9 @@ describe('structured rows and last-status.json', () => { server.stop() } - const file = JSON.parse(readFileSync(lastStatusPath(), 'utf8')) as { + const file: { entries: Record - } + } = JSON.parse(readSavedStatus(lastStatusPath())) expect(Object.keys(file.entries)).toEqual([PANE]) const restored = new AgentHookServer() diff --git a/src/main/agent-hooks/server-structured-canonical-status.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts similarity index 89% rename from src/main/agent-hooks/server-structured-canonical-status.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts index 0ec09ac098f..4d79694cf68 100644 --- a/src/main/agent-hooks/server-structured-canonical-status.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts @@ -3,17 +3,17 @@ import { makeStructuredAgentStatusSubject, type AgentStatusExecutionScope, type AgentStatusStructuredSessionSubject -} from '../../shared/agent-status/contracts/agent-status-subject' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' +} from '../../../../../shared/agent-status/contracts/agent-status-subject' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId -} from '../../shared/agent-session/view/structured-agent-session-projection' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +} from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) const SESSION = 'canonical-session-one' const SCOPE: AgentStatusExecutionScope = { diff --git a/src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts similarity index 89% rename from src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts rename to src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts index 6038b0f28eb..0c9aaed459f 100644 --- a/src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts +++ b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts @@ -1,15 +1,15 @@ // No hook fires at lease expiry, so the server must release owed-notification holds itself. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { CLAUDE_OWED_TASK_NOTIFICATION_LEASE_MS } from '../../shared/agent-hook-listener/providers/claude-owed-task-notifications' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from './server.test-fixtures' +import { CLAUDE_OWED_TASK_NOTIFICATION_LEASE_MS } from '../../../../../shared/agent-hook-listener/providers/claude-owed-task-notifications' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) // The fixture's owner process is fictional; the pane's owning Claude is still running. -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn(async () => 'live') })) diff --git a/src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts similarity index 94% rename from src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts index 4d0e98c6387..bb306de2ae9 100644 --- a/src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts @@ -2,14 +2,14 @@ import { readFileSync, mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer, _internals } from './server' -import { createRuntimeAutomationRunTerminalObserver } from '../automations/runtime-terminal-run-observer' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { createRuntimeAutomationRunTerminalObserver } from '../../../../automations/runtime-terminal-run-observer' import { createTranscriptPane, TRANSCRIPT_PANE_PTY_ID -} from '../runtime/orca-runtime-tests/agent-transcript-pane-test-harness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +} from '../../../../runtime/orca-runtime-tests/agent-transcript-pane-test-harness' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' vi.mock('electron', () => ({ BrowserWindow: { fromId: vi.fn(() => null) }, @@ -18,12 +18,15 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp') } })) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) type CapturedHook = { scenario: string; kind: string; payload?: Record } const hooks: CapturedHook[] = readFileSync( - join(import.meta.dirname, '../../shared/__fixtures__/claude-task-notification-hooks.jsonl'), + join( + import.meta.dirname, + '../../../../../shared/__fixtures__/claude-task-notification-hooks.jsonl' + ), 'utf8' ) .trim() @@ -190,7 +193,7 @@ describe.each([false, true])('real automation Claude wake-up oracle remote=%s', const server = await host(remote, 'transcript-launch') const controller = new AbortController() const ready = readFileSync( - join(import.meta.dirname, '../runtime/__fixtures__/claude-ready-task-wakeup.txt'), + join(import.meta.dirname, '../../../../runtime/__fixtures__/claude-ready-task-wakeup.txt'), 'utf8' ) const pane = await createTranscriptPane( diff --git a/src/main/agent-hooks/server-prompt-sent-telemetry.test.ts b/src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts similarity index 96% rename from src/main/agent-hooks/server-prompt-sent-telemetry.test.ts rename to src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts index 5013ec39c1d..3488f31c9ec 100644 --- a/src/main/agent-hooks/server-prompt-sent-telemetry.test.ts +++ b/src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, GOOD_PANE, FRESH_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE, FRESH_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-ingest-terminal-status.test.ts b/src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts similarity index 96% rename from src/main/agent-hooks/server-ingest-terminal-status.test.ts rename to src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts index 7d2d02f363e..a03ad6e54b4 100644 --- a/src/main/agent-hooks/server-ingest-terminal-status.test.ts +++ b/src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-process-lifetime-status.test.ts b/src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts similarity index 96% rename from src/main/agent-hooks/server-process-lifetime-status.test.ts rename to src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts index 262c82f4db7..359054798d4 100644 --- a/src/main/agent-hooks/server-process-lifetime-status.test.ts +++ b/src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' let dir: string let server: AgentHookServer diff --git a/src/main/agent-hooks/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts similarity index 86% rename from src/main/agent-hooks/server-tmux-canonical.test.ts rename to src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index 01d0baad4b9..7ff17f52581 100644 --- a/src/main/agent-hooks/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -1,18 +1,20 @@ import { createHash } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { postHookEvent } from '../server.test-fixtures' import { TMUX_TEST_PANE, TMUX_TEST_ROOT, TMUX_TEST_ROWS, tmuxTestBody -} from '../../shared/tmux-status.test-fixture' +} from '../../../../../shared/tmux-status.test-fixture' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn()) -vi.mock('../../shared/tmux-host-attachment-probe', () => ({ probeTmuxHostAttachments: probe })) +vi.mock('../../../../../shared/tmux-host-attachment-probe', () => ({ + probeTmuxHostAttachments: probe +})) class CanonicalTestServer extends AgentHookServer { hasLegacyRow(): boolean { return this.state.lastStatusByPaneKey.has(TMUX_TEST_PANE) diff --git a/src/main/agent-hooks/server-tmux-wire.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts similarity index 89% rename from src/main/agent-hooks/server-tmux-wire.test.ts rename to src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts index 7b9ac0d0cf7..5944f21e770 100644 --- a/src/main/agent-hooks/server-tmux-wire.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const time = 1_800_000_000_000 const envelope = { source: 'opencode', diff --git a/src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts b/src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts similarity index 78% rename from src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts rename to src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts index d39ceb7d270..bbed8b3c40f 100644 --- a/src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts +++ b/src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginHookName } from '../../shared/plugins/contributions/plugin-hook-contribution' -import { setPluginHookRunner } from '../plugins/hooks/plugin-hook-dispatch' -import { setAgentToolHookTerminalResolver } from './agent-tool-call-reader' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import type { PluginHookName } from '../../../../../shared/plugins/contributions/plugin-hook-contribution' +import { setPluginHookRunner } from '../../../../plugins/hooks/plugin-hook-dispatch' +import { setAgentToolHookTerminalResolver } from '../../../tool-events/agent-tool-call-reader' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/agent-tool-call-reader.ts b/src/main/agent-hooks/tool-events/agent-tool-call-reader.ts similarity index 88% rename from src/main/agent-hooks/agent-tool-call-reader.ts rename to src/main/agent-hooks/tool-events/agent-tool-call-reader.ts index 0d7f62ad9ed..3527e45afc6 100644 --- a/src/main/agent-hooks/agent-tool-call-reader.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-call-reader.ts @@ -1,15 +1,15 @@ import type { z } from 'zod' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import { normalizeHookEventName } from '../../shared/agent-hook-listener/provider-event-names' -import { parseAgentHookJson } from '../../shared/agent-hook-listener/request-body' -import { parseJsonObjectString } from '../../shared/agent-hook-listener/interactive-tool' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { normalizeHookEventName } from '../../../shared/agent-hook-listener/provider-event-names' +import { parseAgentHookJson } from '../../../shared/agent-hook-listener/request-body' +import { parseJsonObjectString } from '../../../shared/agent-hook-listener/interactive-tool' import { normalizeCopilotEventName, readCopilotToolCall, resolveCopilotEventName -} from '../../shared/agent-hook-listener/providers/copilot-tool-fields' -import type { agentToolAfterHookPayloadSchema } from '../../shared/plugins/events/plugin-hook-payloads' +} from '../../../shared/agent-hook-listener/providers/copilot-tool-fields' +import type { agentToolAfterHookPayloadSchema } from '../../../shared/plugins/events/plugin-hook-payloads' const BEFORE_EVENTS = new Set([ 'pre_tool_use', diff --git a/src/main/agent-hooks/agent-tool-plugin-hooks.test.ts b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts similarity index 90% rename from src/main/agent-hooks/agent-tool-plugin-hooks.test.ts rename to src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts index 7b39e961aee..19a470c8c12 100644 --- a/src/main/agent-hooks/agent-tool-plugin-hooks.test.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts @@ -1,8 +1,8 @@ import type { ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PluginHookName } from '../../shared/plugins/contributions/plugin-hook-contribution' -import type { PluginHookChainOutcome } from '../../shared/plugins/workers/plugin-hook-chain' -import { setPluginHookRunner } from '../plugins/hooks/plugin-hook-dispatch' +import type { PluginHookName } from '../../../shared/plugins/contributions/plugin-hook-contribution' +import type { PluginHookChainOutcome } from '../../../shared/plugins/workers/plugin-hook-chain' +import { setPluginHookRunner } from '../../plugins/hooks/plugin-hook-dispatch' import { answerAgentToolPluginHooks, respondAfterAgentToolPluginHooks diff --git a/src/main/agent-hooks/agent-tool-plugin-hooks.ts b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts similarity index 94% rename from src/main/agent-hooks/agent-tool-plugin-hooks.ts rename to src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts index 0fd41298dd7..b983d058624 100644 --- a/src/main/agent-hooks/agent-tool-plugin-hooks.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts @@ -1,12 +1,12 @@ import type { IncomingHttpHeaders, ServerResponse } from 'node:http' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { PLUGIN_HOOK_SPECS } from '../../shared/plugins/events/plugin-hook-payloads' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { PLUGIN_HOOK_SPECS } from '../../../shared/plugins/events/plugin-hook-payloads' import { notifyPluginHook, PluginHookDeniedError, pluginHookWanted, runPluginHook -} from '../plugins/hooks/plugin-hook-dispatch' +} from '../../plugins/hooks/plugin-hook-dispatch' import { readAgentToolCall, type AgentToolCallOwner } from './agent-tool-call-reader' /** Sent by hook scripts that print Orca's answer as Claude Code's PreToolUse decision. */ diff --git a/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts b/src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts similarity index 72% rename from src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts rename to src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts index 6413152e5af..d21a8c35790 100644 --- a/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts +++ b/src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts @@ -1,6 +1,6 @@ -import type { AgentHookServer } from './server' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INFER_INTERRUPT_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-interrupt-reconciliation' +import type { AgentHookServer } from '../server/agent-hook-server' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INFER_INTERRUPT_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-interrupt-reconciliation' /** A host revision proves this relay supports the command; older relays keep the legacy path. */ export function bindRemoteClaudeInterruptReconciliation( diff --git a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts b/src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts rename to src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts index 98a192efd91..ed1ed3ded3e 100644 --- a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts +++ b/src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts @@ -13,10 +13,10 @@ import { delimiter, join } from 'node:path' import { createServer } from 'node:net' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { WslHookRelayManager } from './wsl-hook-relay-manager' -import { createManagedHookLocalFilesystem } from './managed-hook-local-filesystem.test-fixture' -import { codexHookService } from '../codex/hooks/installation/hook-service' +import { AgentHookServer } from '../../server/agent-hook-server' +import { WslHookRelayManager } from '../wsl-hook-relay-manager' +import { createManagedHookLocalFilesystem } from '../../installation/remote/testing/managed-hook-local-filesystem.test-fixture' +import { codexHookService } from '../../../codex/hooks/installation/hook-service' const BUNDLE_DIR = join(process.cwd(), 'out', 'relay', 'wsl') const BUNDLE_JS = join(BUNDLE_DIR, 'wsl-agent-hook-relay.js') diff --git a/src/main/agent-hooks/wsl-agent-plugin-readiness.ts b/src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts similarity index 82% rename from src/main/agent-hooks/wsl-agent-plugin-readiness.ts rename to src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts index 78727a9b930..5a766c2ff30 100644 --- a/src/main/agent-hooks/wsl-agent-plugin-readiness.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts @@ -1,17 +1,17 @@ -import { getAgentLaunchExecutableName } from '../../shared/agent-launch/startup/agent-command-line-intent' +import { getAgentLaunchExecutableName } from '../../../shared/agent-launch/startup/agent-command-line-intent' import { isAgentStatusHooksEnabledForAgent, type AgentStatusHooksSettings -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import type { ClaudeAgentViewSettings } from '../../shared/claude-agent-view' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { ClaudeAgentViewSettings } from '../../../shared/claude-agent-view' import { detectExplicitPiAgentKindFromCommand, isPiCompatibleAgentType, type PiAgentKind -} from '../../shared/pi-agent-kind' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +} from '../../../shared/pi-agent-kind' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { wslHookRelayManager, type WslHookRelayManager } from './wsl-hook-relay-manager' -import { blockedWslDistroForExec } from '../wsl/discovery/wsl-background-exec-gate' +import { blockedWslDistroForExec } from '../../wsl/discovery/wsl-background-exec-gate' export async function awaitExplicitAgentPluginGuestReadiness(args: { isWsl: boolean diff --git a/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts b/src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts similarity index 89% rename from src/main/agent-hooks/wsl-bridge-daemon-sessions.ts rename to src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts index 519eabbb3c1..bf59f85bddc 100644 --- a/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts @@ -6,9 +6,9 @@ import { getDaemonProvider, listLiveDaemonSessions -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { SessionInfo } from '../daemon/protocol/daemon-session-info' -import { parseWslUncPath } from '../../shared/wsl-paths' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { SessionInfo } from '../../daemon/protocol/daemon-session-info' +import { parseWslUncPath } from '../../../shared/wsl-paths' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' /** 'unverifiable' when any daemon generation couldn't answer: the relay then stays. */ diff --git a/src/main/agent-hooks/wsl-bridge-pty-presence.ts b/src/main/agent-hooks/wsl-relay/wsl-bridge-pty-presence.ts similarity index 100% rename from src/main/agent-hooks/wsl-bridge-pty-presence.ts rename to src/main/agent-hooks/wsl-relay/wsl-bridge-pty-presence.ts diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts similarity index 94% rename from src/main/agent-hooks/wsl-guest-plugin-install.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts index 3d6fdf68d1c..d3b3092339e 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' function fakeMux( request: () => Promise, diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.ts b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts similarity index 83% rename from src/main/agent-hooks/wsl-guest-plugin-install.ts rename to src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts index a9da7757ace..716c24f4303 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts @@ -1,9 +1,9 @@ -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { isRecord } from '../../shared/agent-status/child-work/agent-status-child-work-value-guards' -import { selectOpenCodePluginSources } from './opencode-plugin-settings' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import { selectOpenCodePluginSources } from '../installation/opencode-plugin-settings' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' type GuestPluginInstallDeps = { pluginSources: () => PluginSources diff --git a/src/main/agent-hooks/wsl-hook-fs-adapter.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts similarity index 92% rename from src/main/agent-hooks/wsl-hook-fs-adapter.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts index 103c91aeb55..e5985e0fb65 100644 --- a/src/main/agent-hooks/wsl-hook-fs-adapter.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts @@ -1,15 +1,15 @@ // Adapt the guest fs bridge to SFTP so WSL can reuse SSH hook installers over the existing relay. import type { SFTPWrapper } from 'ssh2' -import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import type { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' import { buildManagedHookDetectionCommands, readManagedHookDetectionResult, type ManagedHookDetectionSettings -} from './managed-hook-detection-commands' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../shared/wsl-hook-relay-contract' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +} from '../installation/managed-hook-detection-commands' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../../shared/wsl-hook-relay-contract' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' export async function installWslGuestHooks(options: { mux: SshChannelMultiplexer diff --git a/src/main/agent-hooks/wsl-hook-relay-deps.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts similarity index 82% rename from src/main/agent-hooks/wsl-hook-relay-deps.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts index 9a5f21fcce6..5c74107a65b 100644 --- a/src/main/agent-hooks/wsl-hook-relay-deps.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts @@ -1,42 +1,42 @@ -import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from '../claude/agent-view/agent-view-mod-source' -import { bindRemoteClaudeInterruptReconciliation } from './ssh-agent-hook-interrupt-reconciliation' +import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from '../../claude/agent-view/agent-view-mod-source' +import { bindRemoteClaudeInterruptReconciliation } from '../transport/ssh-agent-hook-interrupt-reconciliation' import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { AGENT_STATUS_LEGACY_UNADVERTISED_PEER_CAPABILITIES } from '../../shared/agent-status/transport/agent-status-legacy-adapter' -import { agentHookServer } from './server' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { AGENT_STATUS_LEGACY_UNADVERTISED_PEER_CAPABILITIES } from '../../../shared/agent-status/transport/agent-status-legacy-adapter' +import { agentHookServer } from '../server/agent-hook-server' import { createLocalPtyInventoryReader, createWslBridgePaneRootReader -} from './local-tmux-managed-pty' -import { getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' -import { getOpenCode2PluginSource, getOpenCodePluginSource } from '../opencode/hook-service' -import { getPiAgentStatusExtensionSource } from '../pi/agent-status-extension-source' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +} from '../observations/local-tmux-managed-pty' +import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' +import { getOpenCode2PluginSource, getOpenCodePluginSource } from '../../opencode/hook-service' +import { getPiAgentStatusExtensionSource } from '../../pi/agent-status-extension-source' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' import { resolveWslHookRelayBundle, runWslInstallProcess, spawnWslRelayProcess } from './wsl-hook-relay-launch' import { waitForWslRelaySentinel } from './wsl-hook-relay-sentinel' -import { resolveWslDefaultDistro as resolveSharedWslDefaultDistro } from '../wsl/discovery/wsl-default-distro' +import { resolveWslDefaultDistro as resolveSharedWslDefaultDistro } from '../../wsl/discovery/wsl-default-distro' import { deferUntilWslDistroRunning, isWslDistroRunning -} from '../wsl/discovery/wsl-background-distro-gate' -import { isWslAgentHookRelayEnabled } from '../../shared/agent-hook-listener/transport/agent-hook-relay' +} from '../../wsl/discovery/wsl-background-distro-gate' +import { isWslAgentHookRelayEnabled } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { wslBridgePtyPresence, type WslBridgePtyPresence } from './wsl-bridge-pty-presence' import { readDaemonBridgeSessions, type DaemonBridgeSessionVerdict } from './wsl-bridge-daemon-sessions' -import { blockedWslDistroForExec } from '../wsl/discovery/wsl-background-exec-gate' +import { blockedWslDistroForExec } from '../../wsl/discovery/wsl-background-exec-gate' // Concurrent wsl.exe spawns can trigger transient E_UNEXPECTED failures. export const WSL_RELAY_TRANSIENT_RETRY_DELAY_MS = 2_000 diff --git a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts similarity index 92% rename from src/main/agent-hooks/wsl-hook-relay-guest-install.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts index 8240e4b1876..90a0bd09df2 100644 --- a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts @@ -1,16 +1,16 @@ import { WSL_HOOK_FS_METHODS, wslHookRelayEndpointFilePath -} from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/wsl-hook-relay-contract' import type { WslRelayDistroState } from './wsl-hook-relay-state' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import type { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { installWslGuestHooks } from './wsl-hook-fs-adapter' import { REINSTALL_MIN_INTERVAL_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { openCodePluginSettingsKey } from './opencode-plugin-settings' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { openCodePluginSettingsKey } from '../installation/opencode-plugin-settings' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' type GuestInstallDeps = { installHooks: typeof installRemoteManagedAgentHooks diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-idle-stop.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-launch.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts similarity index 91% rename from src/main/agent-hooks/wsl-hook-relay-launch.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts index 93a65618f8f..47458275181 100644 --- a/src/main/agent-hooks/wsl-hook-relay-launch.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts @@ -2,21 +2,21 @@ import type { PipedChildProcess } from '@orca/process-host/process-spec' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { spawnProcess } from '@orca/process-host' -import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' -import { withWslGuestLauncherRevision } from '../wsl/execution/wsl-guest-launcher-revision' -import { orcadPosixNodeRuntimeGlobs } from '../managed-server/install/orcad-node-runtime-globs' +import { relayBundleCandidates } from '../../wsl/execution/relay-bundle-paths' +import { withWslGuestLauncherRevision } from '../../wsl/execution/wsl-guest-launcher-revision' +import { orcadPosixNodeRuntimeGlobs } from '../../managed-server/install/orcad-node-runtime-globs' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' import { MAX_STARTUP_BUFFER_BYTES, type waitForWslRelaySentinel, type WslRelayStartupFailure } from './wsl-hook-relay-sentinel' -import { addOrcaWslInteropEnv } from '../pty/shell-startup/wsl-orca-env' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import { resolveWslExecutablePath } from '../wsl/execution/wsl-executable-path' -import { buildWslExecArgs } from '../../shared/wsl-login-shell-command' -import { resolveWslInteropSpawnCwd } from '../wsl/execution/wsl-interop-spawn-directory' +import { addOrcaWslInteropEnv } from '../../pty/shell-startup/wsl-orca-env' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import { resolveWslExecutablePath } from '../../wsl/execution/wsl-executable-path' +import { buildWslExecArgs } from '../../../shared/wsl-login-shell-command' +import { resolveWslInteropSpawnCwd } from '../../wsl/execution/wsl-interop-spawn-directory' import { WSL_HOOK_RELAY_BUNDLE_NAME, WSL_HOOK_RELAY_DIR, @@ -25,7 +25,7 @@ import { WSL_HOOK_RELAY_STALE_EXIT_CODE, WSL_HOOK_RELAY_VERSION_ENV, WSL_HOOK_RELAY_VERSION_FILE -} from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/wsl-hook-relay-contract' const INSTALL_TIMEOUT_MS = 30_000 diff --git a/src/main/agent-hooks/wsl-hook-relay-link.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts similarity index 88% rename from src/main/agent-hooks/wsl-hook-relay-link.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts index 2212d4e776f..a526b0f3c71 100644 --- a/src/main/agent-hooks/wsl-hook-relay-link.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts @@ -1,12 +1,12 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_PANE_ROOT_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' -import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../shared/claude-agent-view' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { wslHookRelayConnectionId } from '../../../shared/wsl-hook-relay-contract' +import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../../shared/claude-agent-view' import type { WslHookRelayManagerDeps } from './wsl-hook-relay-deps' export type WslRelayLinkOptions = { diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts similarity index 97% rename from src/main/agent-hooks/wsl-hook-relay-manager.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts index 1622fad6e1a..dcf4b5694d7 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts @@ -4,23 +4,23 @@ import { join } from 'node:path' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { registerWslHookFsHandlers } from '../../wsl-guest/wsl-hook-fs-bridge' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { registerWslHookFsHandlers } from '../../../wsl-guest/wsl-hook-fs-bridge' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' import { createWslHookSftpAdapter, installWslGuestHooks } from './wsl-hook-fs-adapter' import { installRemoteManagedAgentHooks, REMOTE_MANAGED_HOOK_INSTALLER_AGENTS -} from './remote-managed-hook-installers' +} from '../installation/remote-managed-hook-installers' import { WslHookRelayManager } from './wsl-hook-relay-manager' -import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../shared/claude-agent-view' +import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../../shared/claude-agent-view' import { awaitExplicitAgentPluginGuestReadiness } from './wsl-agent-plugin-readiness' import { FAILURE_COOLDOWN_BASE_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' type GuestHarness = { transport: MultiplexerTransport diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-manager.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts index 112baed1ec8..72e13043e44 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts @@ -17,14 +17,14 @@ import { import { wireWslRelayLink } from './wsl-hook-relay-link' import type { WslRelayRecovery } from './wsl-hook-relay-recovery' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' -import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { sanitizeWslHookInstanceKey } from '../../shared/wsl-hook-relay-contract' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' +import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { sanitizeWslHookInstanceKey } from '../../../shared/wsl-hook-relay-contract' import { recordManagedWslCodexHome, wslRuntimeHomePathsEqual -} from '../codex/configuration/homes/managed-wsl-codex-home-registry' +} from '../../codex/configuration/homes/managed-wsl-codex-home-registry' import { createWslRelayRecoveryForManager, markWslRelayFailed, diff --git a/src/main/agent-hooks/wsl-hook-relay-reattach.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-reattach.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-reattach.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts similarity index 89% rename from src/main/agent-hooks/wsl-hook-relay-reattach.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts index af8e18cafce..f86d3d9e498 100644 --- a/src/main/agent-hooks/wsl-hook-relay-reattach.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../providers/pty-spawn-result' +import type { PtySpawnResult } from '../../providers/pty-spawn-result' import { wslHookRelayManager } from './wsl-hook-relay-manager' type ReattachResult = Pick diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-recovery.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts index 8480c84ce36..471dcbce2f8 100644 --- a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts @@ -1,4 +1,4 @@ -import type * as WslBackgroundDistroGate from '../wsl/discovery/wsl-background-distro-gate' +import type * as WslBackgroundDistroGate from '../../wsl/discovery/wsl-background-distro-gate' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { WslRelayRecovery, type WslRelayRecoveryState } from './wsl-hook-relay-recovery' @@ -7,7 +7,7 @@ import type { WslRelayRestartSetup } from './wsl-hook-relay-state' const { noteWslDistroMayHaveStoppedMock } = vi.hoisted(() => ({ noteWslDistroMayHaveStoppedMock: vi.fn() })) -vi.mock('../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ +vi.mock('../../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ ...(await importOriginal()), ...(await (() => ({ noteWslDistroMayHaveStopped: noteWslDistroMayHaveStoppedMock diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-recovery.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts similarity index 98% rename from src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts index ab57642fd8f..0940efda51d 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../../ssh/protocol/relay-handshake' import { MAX_STARTUP_BUFFER_BYTES, waitForWslRelaySentinel, diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts similarity index 96% rename from src/main/agent-hooks/wsl-hook-relay-sentinel.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts index f70b5725281..293e4583be8 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts @@ -1,7 +1,7 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../../ssh/protocol/relay-handshake' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' export const MAX_STARTUP_BUFFER_BYTES = 64 * 1024 diff --git a/src/main/agent-hooks/wsl-hook-relay-state-key.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-key.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-state-key.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-key.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-state-machine.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts index 069a73ca434..fd5d9f6ef54 100644 --- a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts @@ -1,9 +1,9 @@ import { WslRelayRecovery } from './wsl-hook-relay-recovery' -import type { WslHookRelayManagerDeps } from './wsl-hook-relay-deps' + import type { WslRelayDistroState, WslRelayRestartSetup } from './wsl-hook-relay-state' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' -import { FAILURE_COOLDOWN_MAX_MS } from './wsl-hook-relay-deps' -import { noteWslDistroMayHaveStopped } from '../wsl/discovery/wsl-background-distro-gate' +import { type WslHookRelayManagerDeps, FAILURE_COOLDOWN_MAX_MS } from './wsl-hook-relay-deps' +import { noteWslDistroMayHaveStopped } from '../../wsl/discovery/wsl-background-distro-gate' type RelayFailureState = { distro: string diff --git a/src/main/agent-hooks/wsl-hook-relay-state.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts similarity index 93% rename from src/main/agent-hooks/wsl-hook-relay-state.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts index 3fc4bbbe268..69c5b27bd1d 100644 --- a/src/main/agent-hooks/wsl-hook-relay-state.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts @@ -1,4 +1,4 @@ -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' export type WslRelayDistroState = { distro: string diff --git a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts similarity index 94% rename from src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts index bf93187c45e..8266372ccbe 100644 --- a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts @@ -4,18 +4,18 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' -import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { PluginOverlayManager } from '../../../wsl-guest/plugin-overlay' +import { createInstallPluginsHandler } from '../../../wsl-guest/wsl-install-plugins-handler' import { WslHookRelayManager } from './wsl-hook-relay-manager' import { REINSTALL_MIN_INTERVAL_MS } from './wsl-hook-relay-deps' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { WSL_HOOK_FS_METHODS } from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { WSL_HOOK_FS_METHODS } from '../../../shared/wsl-hook-relay-contract' function gate() { const reached = Promise.withResolvers() diff --git a/src/main/agent-hooks/wsl-opencode-settings.test.ts b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts similarity index 90% rename from src/main/agent-hooks/wsl-opencode-settings.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts index 227cd891012..889f1867534 100644 --- a/src/main/agent-hooks/wsl-opencode-settings.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts @@ -2,12 +2,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' -import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { PluginOverlayManager } from '../../../wsl-guest/plugin-overlay' +import { createInstallPluginsHandler } from '../../../wsl-guest/wsl-install-plugins-handler' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { maybeRerunWslRelayGuestInstall, diff --git a/src/main/ai-vault/ai-vault-runtime-scan.ts b/src/main/ai-vault/ai-vault-runtime-scan.ts index 36f4729b10f..23c48f085f5 100644 --- a/src/main/ai-vault/ai-vault-runtime-scan.ts +++ b/src/main/ai-vault/ai-vault-runtime-scan.ts @@ -81,6 +81,9 @@ function runtimeScanArgs( if (listArgs?.scopePaths !== undefined) { scanArgs.scopePaths = listArgs.scopePaths } + if (listArgs?.scopeOnly === true) { + scanArgs.scopeOnly = true + } if (listArgs?.includeAntigravityIdeSessions === true) { scanArgs.includeAntigravityIdeSessions = true } diff --git a/src/main/ai-vault/cached-session-list.ts b/src/main/ai-vault/cached-session-list.ts index 56e05f1ab13..9d54fd2554c 100644 --- a/src/main/ai-vault/cached-session-list.ts +++ b/src/main/ai-vault/cached-session-list.ts @@ -145,9 +145,11 @@ export async function listAiVaultSessions( if (args?.force === true) { clearAiVaultBackgroundRestartCircuit() } + // A full list for the same paths holds every row a scope-only one would, so All -> Project needs no rescan. + const fullKey = args?.scopeOnly ? aiVaultLocalScanScopeKey({ ...args, scopeOnly: false }) : key if ( args?.force !== true && - cachedList?.key === key && + (cachedList?.key === key || cachedList?.key === fullKey) && cachedList.expiresAt > now && aiVaultCachedDepthServes(cachedList.depth, depth, args?.scopePaths) ) { @@ -180,6 +182,7 @@ export async function listAiVaultSessions( limit: args?.limit, unlimited: args?.unlimited, scopePaths: args?.scopePaths ? scope.scanScopePaths : undefined, + scopeOnly: args?.scopeOnly, ...roots }, scanSignal, diff --git a/src/main/ai-vault/runtime-session-scanner.ts b/src/main/ai-vault/runtime-session-scanner.ts index 95d300068d7..85eeb7242db 100644 --- a/src/main/ai-vault/runtime-session-scanner.ts +++ b/src/main/ai-vault/runtime-session-scanner.ts @@ -4,6 +4,7 @@ import { z } from 'zod' import { AI_VAULT_AGENTS, AI_VAULT_SCOPE_PATHS_MAX_COUNT, + boundedAiVaultScopeArgs, type AiVaultListArgs, type AiVaultListResult, type AiVaultSession @@ -87,7 +88,7 @@ export async function scanRuntimeAiVaultSessions( force: args.force, ...(args.afterFingerprint !== undefined ? { afterFingerprint: args.afterFingerprint } : {}), // Cap paths for older hosts too; omitted scope paths lose deep-history coverage, not recent sessions. - scopePaths: args.scopePaths?.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT), + ...boundedAiVaultScopeArgs(args.scopePaths, args.scopeOnly), executionHostId }, options.timeoutMs diff --git a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts index facf7c026e0..7d6025ebd0f 100644 --- a/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts +++ b/src/main/ai-vault/scanners/claude/claude-project-dir-encoding.ts @@ -15,19 +15,6 @@ export function encodeClaudeProjectPath(pathValue: string): string { return trimmed.replace(/[^a-zA-Z0-9]/g, '-') } -/** Require an encoded separator boundary so orca cannot match its sibling orcadyne. */ -export function isClaudeProjectDirInScope( - projectDirName: string, - scopePrefixes: ReadonlySet | readonly string[] -): boolean { - for (const prefix of scopePrefixes) { - if (projectDirName === prefix || projectDirName.startsWith(`${prefix}-`)) { - return true - } - } - return false -} - // Claude Code names a longer encoded path's bucket `-`; older versions kept the full name. const CLAUDE_BUCKET_NAME_MAX_LENGTH = 200 @@ -40,24 +27,38 @@ export function claudeProjectBucketScopePrefixes(pathValue: string): string[] { ) } -/** Like isClaudeProjectDirInScope, but a root (`-`, `C--`) keeps its separator, so it prefixes every bucket. */ +/** Whether a bucket is a scope's own or one below it; see claudeProjectBucketNameBelowScope. */ export function isClaudeProjectBucketInScope( projectDirName: string, - scopePrefixes: ReadonlySet + scopePrefixes: Iterable ): boolean { for (const prefix of scopePrefixes) { - const isRoot = prefix === '-' || /^[A-Za-z]--$/.test(prefix) - if ( - isRoot - ? projectDirName.startsWith(prefix) - : isClaudeProjectDirInScope(projectDirName, [prefix]) - ) { + if (claudeProjectBucketNameBelowScope(projectDirName, prefix) !== null) { return true } } return false } +/** The encoded path below one scope prefix (`''` for the scope's own bucket), or null when the bucket is outside it. + * An encoded separator boundary keeps orca from matching its sibling orcadyne; a root (`-`, `C--`) keeps its separator. */ +export function claudeProjectBucketNameBelowScope( + projectDirName: string, + scopePrefix: string +): string | null { + if (projectDirName === scopePrefix) { + return '' + } + const isRoot = scopePrefix === '-' || /^[A-Za-z]--$/.test(scopePrefix) + const head = isRoot ? scopePrefix : `${scopePrefix}-` + return projectDirName.startsWith(head) ? projectDirName.slice(head.length) : null +} + +/** A name this long may be a `-` cut that no longer spells the path; legacy full names are this long too. */ +export function mayBeHashedClaudeProjectBucketName(projectDirName: string): boolean { + return projectDirName.length > CLAUDE_BUCKET_NAME_MAX_LENGTH +} + /** Transcripts sit in project buckets (depth 0); `/` folders below hold only subagent and tool output. */ export function isClaudeProjectBucketDirectory(_name: string, depth: number): boolean { return depth === 0 diff --git a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts index 7a743a0b37b..6ee20e13d50 100644 --- a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts +++ b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts @@ -121,23 +121,27 @@ async function writeSharedRootTranscripts(sessionsDir: string): Promise { } describe('scanAiVaultSessions with overlapping Pi and OMP roots', () => { - const sameFolder = (sessionsDir: string): string => sessionsDir const parentFolder = (sessionsDir: string): string => join(sessionsDir, '..') + const sameFolder = (sessionsDir: string): string => sessionsDir it.each([ - { layout: 'the same folder', piRoot: sameFolder, scope: {} }, // PI_CODING_AGENT_DIR=: Pi walks , OMP walks /sessions. { layout: 'a parent folder', piRoot: parentFolder, scope: {} }, - // A one-row cap sends the rest through scope recovery: Pi's buckets and OMP's walk. - { - layout: 'the same folder for a workspace', - piRoot: sameFolder, - scope: { scopePaths: ['/repo/app'], limit: 1 } - }, // Scope recovery reads Pi's cwd buckets, which sit under the agent folder's sessions/. { layout: 'a parent folder for a workspace', piRoot: parentFolder, scope: { scopePaths: ['/repo/app'], limit: 1 } + }, + // Workspace and Project skip the recency pass for cwd-bucket agents. + { + layout: 'the same folder for a scope-only workspace', + piRoot: sameFolder, + scope: { scopePaths: ['/repo/app'], scopeOnly: true } + }, + { + layout: 'a parent folder for a scope-only workspace', + piRoot: parentFolder, + scope: { scopePaths: ['/repo/app'], scopeOnly: true } } ])('lists each transcript once under its writer when Pi scans $layout', async (testCase) => { const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-pi-omp-shared-')) diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index bcbd59b8b4b..719b9428ddb 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -15,6 +15,7 @@ import type { FileWithMtime } from './session-scanner-types' import { extractString, parseJsonObject } from './session-scanner-values' import { scanIssueTextFromError } from './session-scan-issues' import { isMissingTranscriptPathError } from './session-scanner-discovery' +import { noteAiVaultScanFileFound } from './ai-vault-scan-progress' // Limit representative probing when a bucket contains transcripts without cwd records. const REPRESENTATIVE_CWD_LINE_LIMIT = 200 @@ -24,7 +25,7 @@ const TRANSCRIPT_EXTENSIONS = new Set(['.jsonl']) // Bucket encodings are lossy; retain Claude’s cache and verify other transcripts individually. const PROJECT_DIR_CWD_CACHE_MAX = 2048 const projectDirCwdCache = new Map() -export type IssueSink = (issue: AiVaultScanIssue) => void +export type IssueSink = (issue: AiVaultScanIssue, error?: unknown) => void export function resetProjectDirCwdCacheForTests(): void { projectDirCwdCache.clear() @@ -38,7 +39,7 @@ export function recordRefusal( agent: AiVaultAgent ): void { if (!isMissingTranscriptPathError(error)) { - issues({ agent, path, ...scanIssueTextFromError(error) }) + issues({ agent, path, ...scanIssueTextFromError(error) }, error) } } @@ -74,7 +75,11 @@ export function cwdBucketScopePrefixes( ): Set { const prefixes = new Set() for (const scopePath of scopePaths) { - for (const candidate of scopePathCandidates(scopePath)) { + // Encoders add the NFC spelling; a cwd recorded in NFD names its bucket differently. + for (const candidate of scopePathCandidates(scopePath).flatMap((path) => [ + path, + path.normalize('NFD') + ])) { for (const prefix of layout.encodeScopePrefixes(candidate)) { prefixes.add(prefix.toLowerCase()) } @@ -212,6 +217,8 @@ export async function collectBucketFiles(args: { inScope?: ReturnType issues: IssueSink collected: Map + // Files whose first lines name no cwd go here, bounded on their own, instead of being dropped. + unknown?: Map limit: number excludedFilePaths: ReadonlySet signal?: AbortSignal @@ -221,19 +228,28 @@ export async function collectBucketFiles(args: { await yieldToEventLoop() } throwIfAiVaultScanCancelled(args.signal) - if (args.collected.has(path) || args.excludedFilePaths.has(path)) { + if (args.collected.has(path) || args.unknown?.has(path) || args.excludedFilePaths.has(path)) { continue } try { + let collected = args.collected if (args.inScope) { const cwd = await readFirstCwd(path, args.issues, args.agent, args.signal) - if (!args.inScope(cwd, path)) { + if (cwd === null && args.unknown) { + collected = args.unknown + } else if (!args.inScope(cwd, path)) { continue } } const fileStat = await wslGatedStat(path, 'scan', args.signal) throwIfAiVaultScanCancelled(args.signal) - addBoundedFile(args.collected, args.limit, { + // Scope-only scans don't list cwd-bucket agents recursively, so their file count comes from here. + noteAiVaultScanFileFound(args.signal, args.agent, { + path, + dev: fileStat.dev, + ino: fileStat.ino + }) + addBoundedFile(collected, args.limit, { path, mtimeMs: fileStat.mtimeMs, modifiedAt: fileStat.mtime.toISOString(), diff --git a/src/main/ai-vault/session-scanner-scope-inventory.ts b/src/main/ai-vault/session-scanner-scope-inventory.ts index c0408671123..4a716638b6b 100644 --- a/src/main/ai-vault/session-scanner-scope-inventory.ts +++ b/src/main/ai-vault/session-scanner-scope-inventory.ts @@ -20,7 +20,10 @@ import { const TRANSCRIPT_EXTENSIONS = new Set(['.jsonl']) export type CwdBucketInventory = { layout: CwdBucketLayout - directories: string[][] + // With no recency pass behind it, files a cwd probe can't place are kept for the parse to decide. + scopeOnly: boolean + // unverified: a scope-only Claude bucket whose newest transcripts named no in-scope cwd. + directories: { paths: string[]; unverified: boolean }[] issues: { before: number; issue: AiVaultScanIssue }[] } @@ -37,6 +40,7 @@ type InScopeDiscoveryArgs = { limit: number excludedFilePaths: ReadonlySet issues: AiVaultScanIssue[] + scopeOnly?: boolean signal?: AbortSignal } @@ -54,7 +58,12 @@ export async function inventoryCwdBucketFiles( args: Omit, issueLimit = SCAN_ISSUE_LIMIT ): Promise { - const inventory: CwdBucketInventory = { layout, directories: [], issues: [] } + const inventory: CwdBucketInventory = { + layout, + scopeOnly: args.scopeOnly === true, + directories: [], + issues: [] + } if (args.scopePaths.length === 0 || args.limit <= 0) { return inventory } @@ -82,10 +91,15 @@ export async function inventoryCwdBucketFiles( ) for (const directory of directories) { await yieldScanInventory(index++, args.signal) + let unverified = false if (layout.agent === 'claude') { const cwd = await cachedProjectDirCwd(directory, record, layout.agent, args.signal) + // No cwd found, or a folder sharing the lossy name: without a recency pass, the parse decides. if (!inScope(cwd, directory)) { - continue + if (!args.scopeOnly) { + continue + } + unverified = true } } const paths: string[] = [] @@ -101,7 +115,7 @@ export async function inventoryCwdBucketFiles( throwIfAiVaultScanCancelled(args.signal) recordRefusal(record, directory, err, layout.agent) } - inventory.directories.push(paths) + inventory.directories.push({ paths, unverified }) } } finally { close() @@ -120,6 +134,8 @@ export async function selectCwdBucketFiles( ): Promise { const { layout } = inventory const collected = new Map() + // Bounded apart so files the parse may reject never push out ones already known to be in scope. + const unverified = new Map() const record: IssueSink = (issue) => recordSessionScanIssue(args.issues, issue) const inScope = createAiVaultScopeCwdMatcher(args.scopePaths) let issueIndex = 0 @@ -128,16 +144,17 @@ export async function selectCwdBucketFiles( while (inventory.issues[issueIndex]?.before === index) { record(inventory.issues[issueIndex++].issue) } - const paths = inventory.directories[index] - if (!paths) { + const directory = inventory.directories[index] + if (!directory) { break } await collectBucketFiles({ - paths, + paths: directory.paths, agent: layout.agent, inScope: layout.agent !== 'claude' ? inScope : undefined, issues: record, - collected, + collected: directory.unverified ? unverified : collected, + ...(inventory.scopeOnly ? { unknown: unverified } : {}), limit: args.limit, excludedFilePaths: args.excludedFilePaths, signal: args.signal @@ -145,5 +162,7 @@ export async function selectCwdBucketFiles( } inventory.directories.length = 0 inventory.issues.length = 0 - return [...collected.values()].sort((left, right) => right.mtimeMs - left.mtimeMs) + return [...collected.values(), ...unverified.values()].sort( + (left, right) => right.mtimeMs - left.mtimeMs + ) } diff --git a/src/main/ai-vault/session-scanner-scope-only.test.ts b/src/main/ai-vault/session-scanner-scope-only.test.ts new file mode 100644 index 00000000000..79c23eb7ecb --- /dev/null +++ b/src/main/ai-vault/session-scanner-scope-only.test.ts @@ -0,0 +1,328 @@ +import { mkdtemp, mkdir, rm, utimes, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots } from './session-scanner-test-fixtures' +import { + aiVaultSessionInScope, + createAiVaultScopeCwdMatcher +} from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' + +let tempRoots: string[] = [] + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +async function writeClaudeSession(args: { + claudeRoot: string + dirName: string + sessionId: string + cwd: string + iso: string + // Records before the first cwd, like a long run of snapshot or summary lines. + cwdlessLines?: number + // File time when it differs from the transcript's own time. + mtime?: string +}): Promise { + const dir = join(args.claudeRoot, args.dirName) + await mkdir(dir, { recursive: true }) + const records: unknown[] = Array.from({ length: args.cwdlessLines ?? 0 }, () => ({ + type: 'file-history-snapshot', + sessionId: args.sessionId + })) + records.push({ + type: 'user', + sessionId: args.sessionId, + timestamp: args.iso, + cwd: args.cwd, + message: { role: 'user', content: `work in ${args.cwd}` } + }) + const filePath = join(dir, `${args.sessionId}.jsonl`) + await writeFile(filePath, records.map((record) => JSON.stringify(record)).join('\n')) + const time = new Date(args.mtime ?? args.iso) + await utimes(filePath, time, time) +} + +async function writeCodexSession( + codexRoot: string, + args: { id: string; cwd: string; iso: string; mtime: string } +): Promise { + const dir = join(codexRoot, '2026', '06', '01') + await mkdir(dir, { recursive: true }) + const filePath = join(dir, `rollout-2026-06-01T00-00-00-${args.id}.jsonl`) + await writeFile( + filePath, + [ + { timestamp: args.iso, type: 'session_meta', payload: { id: args.id, cwd: args.cwd } }, + { + timestamp: args.iso, + type: 'response_item', + payload: { type: 'message', role: 'user', content: [{ type: 'text', text: 'hi' }] } + } + ] + .map((record) => JSON.stringify(record)) + .join('\n') + ) + const time = new Date(args.mtime) + await utimes(filePath, time, time) +} + +// What main's Workspace tab shows: the full scan, filtered to the scope as the renderer does. +async function workspaceSessionIds( + root: string, + scopePaths: string[], + options: { scopeOnly?: boolean; limit?: number } +): Promise { + const result = await scanAiVaultSessions({ + ...isolatedScanRoots(root), + platform: 'darwin', + scopePaths, + ...options + }) + const inScope = createAiVaultScopeCwdMatcher(scopePaths) + return result.sessions + .filter((session) => aiVaultSessionInScope(inScope, session)) + .map((session) => session.sessionId) + .sort() +} + +async function tempRoot(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-only-')) + tempRoots.push(root) + return root +} + +describe('scanAiVaultSessions scopeOnly', () => { + it('keeps recent sessions whose bucket or first lines name no in-scope cwd', async () => { + const root = await tempRoot() + const claudeRoot = isolatedScanRoots(root).claudeProjectsDir + // The bucket's only transcript records its cwd after the 200 lines the bucket probe reads. + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-app', + sessionId: 'late-cwd', + cwd: '/repo/app', + iso: '2026-06-01T00:00:00.000Z', + cwdlessLines: 250 + }) + // `/repo/my-app` and `/repo/my/app` share one bucket name; the newest transcript is the other folder's. + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-my-app', + sessionId: 'shared-bucket', + cwd: '/repo/my/app', + iso: '2026-06-02T00:00:00.000Z' + }) + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-my-app', + sessionId: 'other-folder', + cwd: '/repo/my-app', + iso: '2026-06-03T00:00:00.000Z' + }) + // CodeBuddy's transcripts are checked one by one; this one also records its cwd late. + const codebuddyDir = join(isolatedScanRoots(root).codebuddyProjectsDir, 'repo-app') + await mkdir(codebuddyDir, { recursive: true }) + await writeFile( + join(codebuddyDir, 'codebuddy-late-cwd.jsonl'), + [ + ...Array.from({ length: 250 }, () => ({ type: 'file-history-snapshot' })), + { + type: 'message', + timestamp: '2026-06-04T00:00:00.000Z', + sessionId: 'codebuddy-late-cwd', + cwd: '/repo/app', + role: 'user', + content: [{ type: 'input_text', text: 'work in /repo/app' }] + } + ] + .map((record) => JSON.stringify(record)) + .join('\n') + ) + const scopePaths = ['/repo/app', '/repo/my/app'] + + const main = await workspaceSessionIds(root, scopePaths, {}) + expect(main).toEqual(['codebuddy-late-cwd', 'late-cwd', 'shared-bucket']) + await expect(workspaceSessionIds(root, scopePaths, { scopeOnly: true })).resolves.toEqual(main) + }) + + it('matches buckets whose names use the other Unicode form', async () => { + const root = await tempRoot() + const cwd = '/repo/cafe\u0301' + const dir = join(isolatedScanRoots(root).codebuddyProjectsDir, 'repo-cafe\u0301') + await mkdir(dir, { recursive: true }) + await writeFile( + join(dir, 'nfd.jsonl'), + JSON.stringify({ + type: 'message', + timestamp: '2026-06-01T00:00:00.000Z', + sessionId: 'nfd', + cwd, + role: 'user', + content: [{ type: 'input_text', text: 'hi' }] + }) + ) + // Claude turns each non-alphanumeric code unit into a dash, so an NFD cwd names `-repo-cafe-`. + await writeClaudeSession({ + claudeRoot: isolatedScanRoots(root).claudeProjectsDir, + dirName: '-repo-cafe-', + sessionId: 'claude-nfd', + cwd, + iso: '2026-06-02T00:00:00.000Z' + }) + const scopePaths = [cwd.normalize('NFC')] + + const main = await workspaceSessionIds(root, scopePaths, {}) + expect(main).toEqual(['claude-nfd', 'nfd']) + await expect(workspaceSessionIds(root, scopePaths, { scopeOnly: true })).resolves.toEqual(main) + }) + + it('keeps every in-scope session main shows when the scope holds more than the limit', async () => { + const root = await tempRoot() + const claudeRoot = isolatedScanRoots(root).claudeProjectsDir + for (let index = 0; index < 4; index++) { + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-app', + sessionId: `in-scope-${index}`, + cwd: '/repo/app', + iso: `2026-06-0${index + 1}T00:00:00.000Z` + }) + } + + // Main shows the recency pass's 2 plus the scope pass's 2 more. + const main = await workspaceSessionIds(root, ['/repo/app'], { limit: 2 }) + expect(main).toHaveLength(4) + await expect( + workspaceSessionIds(root, ['/repo/app'], { limit: 2, scopeOnly: true }) + ).resolves.toEqual(main) + }) + + it('keeps in-scope rows when unverified files are newer than them', async () => { + const root = await tempRoot() + const claudeRoot = isolatedScanRoots(root).claudeProjectsDir + const inScope = (sessionId: string, day: string) => + writeClaudeSession({ + claudeRoot, + dirName: '-repo-app', + sessionId, + cwd: '/repo/app', + iso: `2026-06-${day}T00:00:00.000Z` + }) + await inScope('a1', '10') + await inScope('a2', '09') + // A sibling whose name also starts `-repo-app`, with cwds past the probe: its files must not take a3's or a4's slot. + for (const [sessionId, day] of [ + ['web-1', '08'], + ['web-2', '07'] + ]) { + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-app-web', + sessionId, + cwd: '/repo/app-web', + iso: `2026-06-${day}T00:00:00.000Z`, + cwdlessLines: 250 + }) + } + await inScope('a3', '05') + await inScope('a4', '04') + + const main = await workspaceSessionIds(root, ['/repo/app'], { limit: 2 }) + expect(main).toEqual(['a1', 'a2', 'a3', 'a4']) + await expect( + workspaceSessionIds(root, ['/repo/app'], { limit: 2, scopeOnly: true }) + ).resolves.toEqual(main) + }) + + it('keeps recency rows whose transcript time is older than their file time', async () => { + const root = await tempRoot() + const codexRoot = isolatedScanRoots(root).codexSessionsDir + // Newest file first: a group whose transcripts say they are old, ahead of newer-dated ones (imported logs). + const groups: { cwd: string; mtimeDay: string; isoDay: string }[] = [ + { cwd: '/repo/app', mtimeDay: '20', isoDay: '02' }, + { cwd: '/elsewhere', mtimeDay: '18', isoDay: '10' }, + { cwd: '/repo/app', mtimeDay: '16', isoDay: '12' } + ] + let index = 0 + for (const group of groups) { + for (let copy = 0; copy < 2; copy++) { + await writeCodexSession(codexRoot, { + id: `019e9693-64fc-7370-9c18-7e625c5950${index++}0`, + cwd: group.cwd, + iso: `2026-06-${group.isoDay}T0${copy}:00:00.000Z`, + mtime: `2026-06-${group.mtimeDay}T0${copy}:00:00.000Z` + }) + } + } + // Old Claude rows elsewhere with the newest files: main parses past them, scope-only never lists them. + for (let copy = 0; copy < 2; copy++) { + await writeClaudeSession({ + claudeRoot: isolatedScanRoots(root).claudeProjectsDir, + dirName: '-elsewhere', + sessionId: `claude-${copy}`, + cwd: '/elsewhere', + iso: `2026-01-0${copy + 1}T00:00:00.000Z`, + mtime: `2026-06-2${copy + 2}T00:00:00.000Z` + }) + } + + const main = await workspaceSessionIds(root, ['/repo/app'], { limit: 2 }) + expect(main).toHaveLength(4) + await expect( + workspaceSessionIds(root, ['/repo/app'], { limit: 2, scopeOnly: true }) + ).resolves.toEqual(main) + }) + + it('returns only in-scope rows', async () => { + const root = await tempRoot() + const claudeRoot = isolatedScanRoots(root).claudeProjectsDir + await writeClaudeSession({ + claudeRoot, + dirName: '-repo-app', + sessionId: 'in-scope', + cwd: '/repo/app', + iso: '2026-06-01T00:00:00.000Z' + }) + await writeClaudeSession({ + claudeRoot, + dirName: '-elsewhere', + sessionId: 'elsewhere', + cwd: '/elsewhere', + iso: '2026-06-02T00:00:00.000Z' + }) + // Codex has no cwd buckets, so it still goes through the recency pass. + const codexDir = join(isolatedScanRoots(root).codexSessionsDir, '2026', '06', '03') + await mkdir(codexDir, { recursive: true }) + const codexId = '019e9693-64fc-7370-9c18-7e625c595d0f' + await writeFile( + join(codexDir, `rollout-2026-06-03T00-00-00-${codexId}.jsonl`), + [ + { + timestamp: '2026-06-03T00:00:00.000Z', + type: 'session_meta', + payload: { id: codexId, cwd: '/elsewhere' } + }, + { + timestamp: '2026-06-03T00:00:01.000Z', + type: 'response_item', + payload: { type: 'message', role: 'user', content: [{ type: 'text', text: 'hi' }] } + } + ] + .map((record) => JSON.stringify(record)) + .join('\n') + ) + + const result = await scanAiVaultSessions({ + ...isolatedScanRoots(root), + platform: 'darwin', + scopePaths: ['/repo/app'], + scopeOnly: true + }) + + expect(result.sessions.map((session) => session.sessionId)).toEqual(['in-scope']) + }) +}) diff --git a/src/main/ai-vault/session-scanner-scope-walk.ts b/src/main/ai-vault/session-scanner-scope-walk.ts index 41689d6bbcd..b082062866d 100644 --- a/src/main/ai-vault/session-scanner-scope-walk.ts +++ b/src/main/ai-vault/session-scanner-scope-walk.ts @@ -1,5 +1,8 @@ import { SCAN_ISSUE_LIMIT } from './session-scan-issues' -import { createAiVaultScopeCwdMatcher } from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' +import { + aiVaultSessionInScope, + createAiVaultScopeCwdMatcher +} from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import type { AiVaultScanIssue, AiVaultSession @@ -33,7 +36,11 @@ import type { SessionFileCandidate, SessionFileDiscovery } from './session-scanner-types' -import { AI_VAULT_SCOPE_CWD_SOURCES, scopeWalksAgentFiles } from './session-scope-cwd' +import { + AI_VAULT_SCOPE_CWD_SOURCES, + scopeOnlyScan, + scopeWalksAgentFiles +} from './session-scope-cwd' import { sidecarUnchanged } from './parse-cache/session-sidecar-stat' import { prioritizeAntigravityTranscriptCandidates } from './scanners/antigravity/antigravity-transcript-candidates' @@ -57,11 +64,14 @@ export async function scanInScopeSessions(args: ScopeScanArgs): Promise workload?.settle(candidate, 'bucket', parsed) + settled: (candidate, parsed) => workload?.settle(candidate, 'bucket', parsed), + // Unverified bucket files are placed by their parsed cwd. + admitSession: inScope ? (session) => aiVaultSessionInScope(inScope, session) : undefined }) return [...bucketed, ...walked] } @@ -213,6 +225,7 @@ export async function prepareScopeScan( .map((discovery) => discovery.rootDir), scopePaths, limit: args.limit, + scopeOnly: scopeOnlyScan(args.options), signal: args.options.signal }, issueLimit @@ -220,7 +233,7 @@ export async function prepareScopeScan( issueLimit -= inventory.issues.length inventories.push(inventory) if (workload) { - for (const paths of inventory.directories) { + for (const { paths } of inventory.directories) { for (const path of paths) { await yieldScanInventory(index++, args.options.signal) workload.registerPath(source.layout.agent, path, 'bucket') diff --git a/src/main/ai-vault/session-scanner-scope.test.ts b/src/main/ai-vault/session-scanner-scope.test.ts index 0af9cfc9b68..13efa226630 100644 --- a/src/main/ai-vault/session-scanner-scope.test.ts +++ b/src/main/ai-vault/session-scanner-scope.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots } from './session-scanner-test-fixtures' import type { AiVaultScanOptions } from './session-scanner-types' let tempRoots: string[] = [] @@ -12,27 +13,10 @@ afterEach(async () => { tempRoots = [] }) -// Isolate Claude fixtures from every other source root. function scopedScanOptions(claudeProjectsDir: string, extra: Partial) { return { + ...isolatedScanRoots(claudeProjectsDir), claudeProjectsDir, - codexSessionsDir: '/nonexistent/codex', - geminiSessionsDir: '/nonexistent/gemini', - antigravityBrainDir: '/nonexistent/antigravity', - copilotSessionsDir: '/nonexistent/copilot', - cursorProjectsDir: '/nonexistent/cursor', - opencodeStorageDir: '/nonexistent/opencode', - opencodeDbPaths: [], - grokSessionsDir: '/nonexistent/grok', - devinTranscriptsDir: '/nonexistent/devin', - hermesSessionsDir: '/nonexistent/hermes', - rovoSessionsDir: '/nonexistent/rovo', - openclawStateDir: '/nonexistent/openclaw', - openclawLegacyStateDir: '/nonexistent/openclaw-legacy', - piSessionsDir: '/nonexistent/pi', - droidSessionsDir: '/nonexistent/droid', - droidProjectsDir: '/nonexistent/droid-projects', - kimiSessionsDir: '/nonexistent/kimi', ...extra } satisfies AiVaultScanOptions } diff --git a/src/main/ai-vault/session-scanner-source-discovery.ts b/src/main/ai-vault/session-scanner-source-discovery.ts index 8a2e8df2d54..dc844dcda35 100644 --- a/src/main/ai-vault/session-scanner-source-discovery.ts +++ b/src/main/ai-vault/session-scanner-source-discovery.ts @@ -7,7 +7,7 @@ import { antigravityDiscoveries } from './scanners/antigravity/session-scanner-a import { AI_VAULT_AGENT_SOURCES, type AiVaultAgentSource } from './session-scanner-agent-sources' import { normalizedWslHomeDirs } from './session-scanner-roots' import { configureOpenCodeWslReaders } from './scanners/opencode/reader-transport/session-scanner-opencode-wsl-client' -import { scopeWalksAgentFiles } from './session-scope-cwd' +import { scopeOnlyScan, scopeWalksAgentFiles } from './session-scope-cwd' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' export { DEFAULT_CODEX_HOME_DIR } from './session-scanner-agent-sources' @@ -51,6 +51,14 @@ function agentDiscoveries( issues: AiVaultScanIssue[] ): Promise[] { const rootDirs = source.rootDirs(options, wslHomeDirs) + // Scope-only reads cwd buckets through the scope pass; Pi stays listed because OMP's dedupe needs its listing. + if ( + scopeOnlyScan(options) && + !scopeWalksAgentFiles(agent, options.scopePaths) && + agent !== 'pi' + ) { + return rootDirs.map(async (rootDir) => ({ agent, rootDir, files: [] })) + } const discover = (rootDir: string): Promise => discoverFiles({ rootDir, diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index 468615ebb7f..54b7eadcb08 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -59,6 +59,8 @@ export type AiVaultScanOptions = { limitPerAgent?: number // Include sessions for these workspace paths beyond the recency cap (AI_VAULT_SCOPE_CWD_SOURCES). scopePaths?: readonly string[] + // Return only scopePaths sessions, skipping the global recency pass (Workspace and Project). + scopeOnly?: boolean platform?: NodeJS.Platform executionHostId?: ExecutionHostId signal?: AbortSignal diff --git a/src/main/ai-vault/session-scanner.ts b/src/main/ai-vault/session-scanner.ts index ef007200382..dbe45b44195 100644 --- a/src/main/ai-vault/session-scanner.ts +++ b/src/main/ai-vault/session-scanner.ts @@ -26,6 +26,11 @@ import { } from './scanners/cursor/session-scanner-cursor-chat-meta' import type { AiVaultScanOptions } from './session-scanner-types' import { clampPositiveInteger } from './session-scanner-values' +import { scopeOnlyScan } from './session-scope-cwd' +import { + aiVaultSessionInScope, + createAiVaultScopeCwdMatcher +} from '../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' import { DEFAULT_AI_VAULT_SCAN_LIMIT } from '../../shared/ai-vault/scanning/ai-vault-session-depth' import { withDevinSessionsDbScan } from './scanners/devin/session-scanner-devin-db' @@ -33,7 +38,7 @@ import { withOpenCodeSqliteScanScope } from './scanners/opencode/sqlite/session- const SESSION_PARSE_CANDIDATE_MULTIPLIER = 2 -/** Return recency-capped sessions plus recovered in-scope sessions, deduplicated and sorted. */ +/** Return recency-capped sessions plus recovered in-scope sessions (only those for scopeOnly), deduplicated and sorted. */ export async function scanAiVaultSessions( options: AiVaultScanOptions = {} ): Promise { @@ -80,9 +85,11 @@ async function scanAiVaultSessionStores(options: AiVaultScanOptions): Promise workload?.settle(candidate, 'global', parsed) }) - const cappedSessions = dedupeScannedSessions(parsedSessions) - .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) - .slice(0, limit) + const recentSessions = dedupeScannedSessions(parsedSessions).sort( + (left, right) => sessionSortTime(right) - sessionSortTime(left) + ) + // Scope-only keeps the recency pass for agents without cwd buckets, but returns only its in-scope rows. + const inScope = scopeOnly ? createAiVaultScopeCwdMatcher(options.scopePaths ?? []) : null + const cappedSessions = inScope + ? recentSessions.filter((session) => aiVaultSessionInScope(inScope, session)) + : recentSessions.slice(0, limit) const scopeSessions = await scanInScopeSessions({ inventory, discoveries, options, limit, - alreadyParsedFilePaths: new Set(cappedSessions.map((session) => session.filePath)), + alreadyParsedFilePaths: new Set( + (scopeOnly ? recentSessions : cappedSessions).map((session) => session.filePath) + ), platform, executionHostId, issues, diff --git a/src/main/ai-vault/session-scope-cwd.ts b/src/main/ai-vault/session-scope-cwd.ts index 11b337fa5ce..92c4fbc33b3 100644 --- a/src/main/ai-vault/session-scope-cwd.ts +++ b/src/main/ai-vault/session-scope-cwd.ts @@ -6,7 +6,11 @@ import { PI_CWD_BUCKET_LAYOUT, type CwdBucketLayout } from './session-cwd-bucket-layouts' -import type { FileWithMtime, SessionFileCandidate } from './session-scanner-types' +import type { + AiVaultScanOptions, + FileWithMtime, + SessionFileCandidate +} from './session-scanner-types' import { asRecord } from './session-scanner-record-value' import { extractString, parseJsonObject } from './session-scanner-values' import { clineManifestCwd } from './scanners/cline/session-scanner-cline-parser' @@ -146,6 +150,13 @@ export const AI_VAULT_SCOPE_CWD_SOURCES: Record +): boolean { + return options.scopeOnly === true && (options.scopePaths?.length ?? 0) > 0 +} + export function scopeWalksAgentFiles( agent: AiVaultAgent, scopePaths: readonly string[] | undefined diff --git a/src/main/amp/hook-service.ts b/src/main/amp/hook-service.ts index bff09351ee8..7674aa7c126 100644 --- a/src/main/amp/hook-service.ts +++ b/src/main/amp/hook-service.ts @@ -7,7 +7,7 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/co import { readTextFileRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' import { AMP_PLUGIN_FILE, AMP_PLUGIN_MARKER, diff --git a/src/main/antigravity/antigravity-chat-account.ts b/src/main/antigravity/antigravity-chat-account.ts index 705f8294c1c..491cb7f1f4e 100644 --- a/src/main/antigravity/antigravity-chat-account.ts +++ b/src/main/antigravity/antigravity-chat-account.ts @@ -16,6 +16,7 @@ import { antigravityBrowserHelperWorks } from './antigravity-browser-helper' import { AcpLaunchGate } from '../acp/launch/acp-launch-gate' import { ANTIGRAVITY_ACP_HOME } from '../../shared/antigravity-session-origin' import { ANTIGRAVITY_CHAT_HOME_FOLDER } from './antigravity-chat-home' +import { antigravityUserHome, linkAntigravityUserSkills } from './antigravity-chat-user-skills' type SignInOwner = Pick const retained = new ProviderAcquisitionStarts() @@ -85,6 +86,7 @@ export const antigravityChatAccount = { ) } await folder.prepare?.(env) + await linkAntigravityUserSkills(home, antigravityUserHome(env)) const path = join(home, ANTIGRAVITY_ACP_HOME, 'settings.json') const projection = { auth: { type: auth.method }, diff --git a/src/main/antigravity/antigravity-chat-user-skills.test.ts b/src/main/antigravity/antigravity-chat-user-skills.test.ts new file mode 100644 index 00000000000..2ad430400ed --- /dev/null +++ b/src/main/antigravity/antigravity-chat-user-skills.test.ts @@ -0,0 +1,89 @@ +import type * as FsPromises from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, readlink, rm, rmdir, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { linkAntigravityUserSkills } from './antigravity-chat-user-skills' + +const fsCalls = vi.hoisted(() => ({ count: 0 })) +vi.mock('node:fs/promises', async (importOriginal) => { + const real = await importOriginal() + const counted = + (fn: (...args: A) => Promise) => + (...args: A) => { + fsCalls.count++ + return fn(...args) + } + return { ...real, lstat: counted(real.lstat), rmdir: vi.fn(real.rmdir) } +}) + +let root: string +let chatHome: string +let userHome: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'agy-user-skills-')) + chatHome = join(root, 'antigravity-chat') + userHome = join(root, 'home') + await mkdir(join(userHome, '.gemini', 'config', 'skills', 'orca-cli'), { recursive: true }) + await writeFile(join(userHome, '.gemini', 'config', 'skills', 'orca-cli', 'SKILL.md'), 'skill') +}) + +afterEach(async () => { + vi.mocked(rmdir).mockRestore() + await rm(root, { recursive: true, force: true }) +}) + +it('replaces the empty placeholder with a link to the user skills', async () => { + await mkdir(join(chatHome, 'config', 'skills'), { recursive: true }) + + await linkAntigravityUserSkills(chatHome, userHome) + + const linked = join(chatHome, 'config', 'skills', 'orca-cli', 'SKILL.md') + expect(await readFile(linked, 'utf8')).toBe('skill') + // No ~/.gemini/antigravity-cli/skills, so nothing is linked there. + await expect(readlink(join(chatHome, 'antigravity-cli', 'skills'))).rejects.toThrow() +}) + +it('removes a link whose target is gone', async () => { + const link = join(chatHome, 'antigravity-cli', 'skills') + const target = join(userHome, '.gemini', 'antigravity-cli', 'skills') + await mkdir(join(chatHome, 'antigravity-cli'), { recursive: true }) + await mkdir(target, { recursive: true }) + // Windows creates directory links without extra rights only as junctions, to a target that exists. + await symlink(target, link, process.platform === 'win32' ? 'junction' : 'dir') + await rm(target, { recursive: true }) + + await linkAntigravityUserSkills(chatHome, userHome) + + await expect(readlink(link)).rejects.toThrow() +}) + +it('lets one launch finish linking before another starts on the same chat home', async () => { + const realRmdir = vi.mocked(rmdir).getMockImplementation()! + await mkdir(join(chatHome, 'config', 'skills'), { recursive: true }) + let release!: () => void + const held = new Promise((resolve) => (release = resolve)) + let first!: () => void + const firstRemoving = new Promise((resolve) => (first = resolve)) + vi.mocked(rmdir).mockImplementationOnce(async (path) => { + first() + await held + return realRmdir(path) + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const one = linkAntigravityUserSkills(chatHome, userHome) + await firstRemoving + const before = fsCalls.count + const two = linkAntigravityUserSkills(chatHome, userHome) + // A second launch that started at once would already have looked at the folder. + expect(fsCalls.count).toBe(before) + release() + await Promise.all([one, two]) + + expect(warn).not.toHaveBeenCalled() + const linked = join(chatHome, 'config', 'skills', 'orca-cli', 'SKILL.md') + expect(await readFile(linked, 'utf8')).toBe('skill') + warn.mockRestore() +}) diff --git a/src/main/antigravity/antigravity-chat-user-skills.ts b/src/main/antigravity/antigravity-chat-user-skills.ts new file mode 100644 index 00000000000..5c829b450ed --- /dev/null +++ b/src/main/antigravity/antigravity-chat-user-skills.ts @@ -0,0 +1,119 @@ +import { lstat, mkdir, readlink, rmdir, stat, symlink, unlink } from 'node:fs/promises' +import { homedir } from 'node:os' +import { dirname, join, resolve } from 'node:path' + +// The server reads user-wide skills from these folders under GEMINI_HOME. +const SKILL_FOLDERS = [ + ['config', 'skills'], + ['antigravity-cli', 'skills'] +] as const + +/** The home the server's Python `expanduser` resolves, where `~/.gemini` lives. */ +export function antigravityUserHome( + env: Readonly>, + platform: NodeJS.Platform = process.platform +): string { + if (platform === 'win32') { + if (env.USERPROFILE) { + return env.USERPROFILE + } + return env.HOMEDRIVE && env.HOMEPATH ? `${env.HOMEDRIVE}${env.HOMEPATH}` : homedir() + } + return env.HOME || homedir() +} + +// One chat home is linked by one launch at a time; another launch waits and then finds the links. +const linking = new Map>() + +/** The chat's private GEMINI_HOME isolates its sign-in; link its skill folders to `~/.gemini`'s + * so skills installed for Antigravity reach the chat. Never fails the launch. */ +export function linkAntigravityUserSkills( + chatHome: string, + userHome: string, + platform: NodeJS.Platform = process.platform +): Promise { + const run = (linking.get(chatHome) ?? Promise.resolve()).then(() => + linkSkillFolders(chatHome, userHome, platform) + ) + linking.set(chatHome, run) + void run.then(() => { + if (linking.get(chatHome) === run) { + linking.delete(chatHome) + } + }) + return run +} + +async function linkSkillFolders( + chatHome: string, + userHome: string, + platform: NodeJS.Platform +): Promise { + for (const segments of SKILL_FOLDERS) { + const link = join(chatHome, ...segments) + const target = join(userHome, '.gemini', ...segments) + await linkSkillFolder(link, target, platform).catch((error: unknown) => { + console.warn('[antigravity] user skills not linked into the chat home:', link, error) + }) + } +} + +async function linkSkillFolder( + link: string, + target: string, + platform: NodeJS.Platform +): Promise { + const entry = await lstat(link).catch(ignoreMissing) + // An unreadable target changes nothing; only a missing one removes the link. + const targetExists = await stat(target).then( + (found) => found.isDirectory(), + (error: unknown) => ignoreMissing(error) ?? false + ) + if (entry?.isSymbolicLink()) { + if (targetExists && (await linksTo(link, target, platform))) { + return + } + // The harness creates this folder itself, and its mkdir fails on a dangling link. + await unlink(link) + } else if (entry) { + if (!targetExists || !entry.isDirectory()) { + return + } + // An empty folder is the harness's placeholder; rmdir refuses one with content, which stays. + await rmdir(link) + } + if (!targetExists) { + return + } + await mkdir(dirname(link), { recursive: true, mode: 0o700 }) + await symlink(target, link, platform === 'win32' ? 'junction' : 'dir').catch( + async (error: unknown) => { + if (await linksTo(link, target, platform).catch(() => false)) { + return + } + // A running chat's harness may have recreated its placeholder meanwhile. + if ((await lstat(link)).isDirectory()) { + await rmdir(link) + await symlink(target, link, platform === 'win32' ? 'junction' : 'dir') + return + } + throw error + } + ) +} + +async function linksTo(link: string, target: string, platform: NodeJS.Platform): Promise { + const linked = resolve(dirname(link), await readlink(link)) + return platform === 'win32' ? linked.toLowerCase() === target.toLowerCase() : linked === target +} + +function ignoreMissing(error: unknown): undefined { + if ( + error instanceof Error && + 'code' in error && + (error.code === 'ENOENT' || error.code === 'ENOTDIR') + ) { + return undefined + } + throw error +} diff --git a/src/main/antigravity/hook-script.ts b/src/main/antigravity/hook-script.ts index a75bb4b317e..b3450f0e386 100644 --- a/src/main/antigravity/hook-script.ts +++ b/src/main/antigravity/hook-script.ts @@ -1,11 +1,11 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { buildHookProcessCapture } from '../agent-hooks/hook-process-capture' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { buildHookProcessCapture } from '../agent-hooks/installation/scripts/hook-process-capture' import { buildPosixHookPayloadCapture, POSIX_HOOK_JSON_STDIN, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { ANTIGRAVITY_PRE_TOOL_USE_DECISION } from './hook-events' export function getManagedScript( diff --git a/src/main/antigravity/hook-service.test.ts b/src/main/antigravity/hook-service.test.ts index 20ae7b9d529..09d2a620568 100644 --- a/src/main/antigravity/hook-service.test.ts +++ b/src/main/antigravity/hook-service.test.ts @@ -17,7 +17,7 @@ vi.mock('os', async () => { }) import { AntigravityHookService } from './hook-service' -import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' const ANTIGRAVITY_PRE_INVOCATION_COMMAND = process.platform === 'win32' ? 'antigravity-pre-invocation.cmd' : 'antigravity-hook.sh' diff --git a/src/main/antigravity/hook-service.ts b/src/main/antigravity/hook-service.ts index 9f18556a05e..c26bd687e34 100644 --- a/src/main/antigravity/hook-service.ts +++ b/src/main/antigravity/hook-service.ts @@ -5,33 +5,31 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - getSharedManagedScriptPath, - readHooksJson, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, - type HookDefinition -} from '../agent-hooks/installer-utils' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { WINDOWS_ANTIGRAVITY_JSON_POST_SCRIPT } from './windows-hook-json-post' import { restoreManagedScript, refreshManagedScriptIfPresent, scriptStillExists -} from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { ANTIGRAVITY_EVENTS, ANTIGRAVITY_PRE_TOOL_USE_DECISION, type AntigravityEvent } from './hook-events' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { HOOK_PARENT_CAPTURE } from '../agent-hooks/hook-process-capture' +import { HOOK_PARENT_CAPTURE } from '../agent-hooks/installation/scripts/hook-process-capture' import { getManagedScript, getWindowsWrapperScript } from './hook-script' import { buildInstalledConfig, diff --git a/src/main/antigravity/hooks-json-bundle.ts b/src/main/antigravity/hooks-json-bundle.ts index 2a1f90a671a..ed81c036623 100644 --- a/src/main/antigravity/hooks-json-bundle.ts +++ b/src/main/antigravity/hooks-json-bundle.ts @@ -1,12 +1,14 @@ import { buildManagedCommandHook, - createManagedCommandMatcher, - hookDefinitionHasManagedCommand, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + hookDefinitionHasManagedCommand, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' import { ANTIGRAVITY_EVENTS, ANTIGRAVITY_HOOK_BUNDLE_NAME, diff --git a/src/main/antigravity/posix-hook-invocation.test.ts b/src/main/antigravity/posix-hook-invocation.test.ts index 1b9b2472b7a..9f1ca040701 100644 --- a/src/main/antigravity/posix-hook-invocation.test.ts +++ b/src/main/antigravity/posix-hook-invocation.test.ts @@ -9,7 +9,7 @@ import { tokenizeCommandLine } from '../../shared/agent-status/process/agent-com import { spawnProcess } from '@orca/process-host' import { AntigravityHookService } from './hook-service' import { ANTIGRAVITY_PRE_TOOL_USE_DECISION } from './hook-events' -import { wrapPosixHookCommand } from '../agent-hooks/posix-hook-command' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' import { readAgentProcess } from '../../shared/agent-status/process/agent-process-presence-probe' import { diff --git a/src/main/antigravity/windows-hook-json-post.ts b/src/main/antigravity/windows-hook-json-post.ts index 736ae3a4fd1..5732f1ff1fd 100644 --- a/src/main/antigravity/windows-hook-json-post.ts +++ b/src/main/antigravity/windows-hook-json-post.ts @@ -2,7 +2,7 @@ import { HOOK_REQUEST_MAX_BYTES } from '../../shared/agent-hook-listener/request import { POSIX_HOOK_JSON_STDIN_FIRST_BYTE_TIMEOUT_SECONDS, POSIX_HOOK_JSON_STDIN_IDLE_TIMEOUT_SECONDS -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' // curl reads payload@- before starting its timeout; agy can keep that pipe open. export const WINDOWS_ANTIGRAVITY_JSON_POST_SCRIPT = String.raw` diff --git a/src/main/browser-passwords/browser-password-chromium-import.test.ts b/src/main/browser-passwords/browser-password-chromium-import.test.ts index 65e680215ff..0284bd33c31 100644 --- a/src/main/browser-passwords/browser-password-chromium-import.test.ts +++ b/src/main/browser-passwords/browser-password-chromium-import.test.ts @@ -6,7 +6,7 @@ import { DatabaseSync } from 'node:sqlite' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as DetectionModule from '../browser/cookies/sources/browser-cookie-source-profiles' import type * as SnapshotModule from '../browser/cookies/chromium/chromium-cookie-snapshot' -import type { EncryptionKeyResult } from '../browser/cookies/sources/browser-cookie-sqlite' +import type { EncryptionKeyResult } from '../browser/cookies/sources/chromium-encryption-key-contract' type FixtureState = { root: string diff --git a/src/main/browser-passwords/browser-password-chromium-import.ts b/src/main/browser-passwords/browser-password-chromium-import.ts index bab73eb6e72..d3d0dd137c8 100644 --- a/src/main/browser-passwords/browser-password-chromium-import.ts +++ b/src/main/browser-passwords/browser-password-chromium-import.ts @@ -12,7 +12,7 @@ import { type ChromiumBrowserDef } from '../browser/cookies/sources/browser-cookie-source-profiles' import { getEncryptionKey } from '../browser/cookies/sources/browser-cookie-key' -import type { EncryptionKeyResult } from '../browser/cookies/sources/browser-cookie-sqlite' +import type { EncryptionKeyResult } from '../browser/cookies/sources/chromium-encryption-key-contract' import { createChromiumCookieSnapshot } from '../browser/cookies/chromium/chromium-cookie-snapshot' import type { BrowserPasswordImportRow } from './browser-password-import-merge' diff --git a/src/main/browser-passwords/browser-password-guest-service.test.ts b/src/main/browser-passwords/browser-password-guest-service.test.ts index dae21dd25a0..26d198cf40e 100644 --- a/src/main/browser-passwords/browser-password-guest-service.test.ts +++ b/src/main/browser-passwords/browser-password-guest-service.test.ts @@ -12,7 +12,7 @@ vi.mock('electron', () => ({ on: (channel: string, handler: (...args: unknown[]) => void) => handlers.set(channel, handler) } })) -vi.mock('../browser/browser-manager', () => ({ +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getRendererContextForGuest: () => ({ browserPageId: 'page', renderer }), getGuestWebContentsId: () => 411 diff --git a/src/main/browser-passwords/browser-password-guest-service.ts b/src/main/browser-passwords/browser-password-guest-service.ts index d5ff760c8b8..03d3bc44881 100644 --- a/src/main/browser-passwords/browser-password-guest-service.ts +++ b/src/main/browser-passwords/browser-password-guest-service.ts @@ -16,7 +16,7 @@ import { type BrowserPasswordGuestFieldFocused, type BrowserPasswordSuggestion } from '../../shared/browser-passwords-types' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { BrowserPasswordLoginTracker } from './browser-password-login-tracker' import { toBrowserPasswordOrigin } from './browser-password-origin' import { diff --git a/src/main/browser-passwords/browser-password-picker-keyboard.ts b/src/main/browser-passwords/browser-password-picker-keyboard.ts index 6edc37027fd..b6b07dfd83f 100644 --- a/src/main/browser-passwords/browser-password-picker-keyboard.ts +++ b/src/main/browser-passwords/browser-password-picker-keyboard.ts @@ -1,7 +1,7 @@ import type { WebContents } from 'electron' import type { BrowserPasswordFieldFocusEvent } from '../../shared/browser-passwords-types' import { isAgentInjectingInput } from '../browser/cdp/input/agent-input-injection' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { browserPasswordVaultForGuest as vaultForGuest } from './browser-password-vault-access' import { BROWSER_PASSWORDS_RENDERER_EVENTS } from './browser-password-save-prompts' diff --git a/src/main/browser-passwords/browser-password-save-prompts.test.ts b/src/main/browser-passwords/browser-password-save-prompts.test.ts index 16cb9027b82..29d5781cd64 100644 --- a/src/main/browser-passwords/browser-password-save-prompts.test.ts +++ b/src/main/browser-passwords/browser-password-save-prompts.test.ts @@ -7,7 +7,7 @@ import type { BrowserPasswordGuestCapture } from '../../shared/browser-passwords import { BrowserPasswordStore } from './browser-password-store' const send = vi.fn() -vi.mock('../browser/browser-manager', () => ({ +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getRendererContextForGuest: () => ({ browserPageId: 'page-1', diff --git a/src/main/browser-passwords/browser-password-save-prompts.ts b/src/main/browser-passwords/browser-password-save-prompts.ts index 9839a4a0ca0..525c1e4c1ec 100644 --- a/src/main/browser-passwords/browser-password-save-prompts.ts +++ b/src/main/browser-passwords/browser-password-save-prompts.ts @@ -3,7 +3,7 @@ import type { BrowserPasswordSavePrompt, BrowserPasswordSavePromptResponse } from '../../shared/browser-passwords-types' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import type { BrowserPasswordSucceededLogin } from './browser-password-login-tracker' import { decideBrowserPasswordSave } from './browser-password-save-decision' import type { BrowserPasswordStore } from './browser-password-store' diff --git a/src/main/browser-passwords/browser-password-vault-access.ts b/src/main/browser-passwords/browser-password-vault-access.ts index fc3de699ec7..54bea76771c 100644 --- a/src/main/browser-passwords/browser-password-vault-access.ts +++ b/src/main/browser-passwords/browser-password-vault-access.ts @@ -1,5 +1,5 @@ import { session, type Session, type WebContents } from 'electron' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { localSshBrowserProfileIdForSession } from '../browser/routing/local-host-partitions/local-ssh-browser-partitions' import type { BrowserPasswordStore } from './browser-password-store' import { getBrowserPasswordVault } from './browser-password-vaults' diff --git a/src/main/browser/agent-browser/agent-browser-bridge-process.ts b/src/main/browser/agent-browser/agent-browser-bridge-process.ts deleted file mode 100644 index c0d5fa979c9..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-process.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { app } from 'electron' -import { existsSync } from 'node:fs' -import { join } from 'node:path' -import { platform, arch } from 'node:os' -import type { WebContents } from 'electron' -import { BrowserError } from '../browser-error' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import { EMBEDDED_NAVIGATION_TIMEOUT_MS } from './agent-browser-bridge-types' -import { ensureDependencyBinaryExecutable } from './agent-browser-dependency-binary' -import { isAgentBrowserStaleRefError } from './agent-browser-batch-command' - -export function agentBrowserNativeName(): string { - const ext = process.platform === 'win32' ? '.exe' : '' - return `agent-browser-${platform()}-${arch()}${ext}` -} - -export function resolveAgentBrowserBinary(): string { - // resourcesPath preserves the case-sensitive macOS Resources path. - const bundledResourcesPath = - process.resourcesPath ?? - (process.platform === 'darwin' - ? join(app.getPath('exe'), '..', '..', 'Resources') - : join(app.getPath('exe'), '..', 'resources')) - const bundled = join(bundledResourcesPath, agentBrowserNativeName()) - if (existsSync(bundled)) { - return bundled - } - - // Bundling makes __dirname unreliable for locating development dependencies. - const nmBin = join( - app.getAppPath(), - 'node_modules', - 'agent-browser', - 'bin', - agentBrowserNativeName() - ) - if (existsSync(nmBin)) { - ensureDependencyBinaryExecutable(nmBin) - return nmBin - } - - return 'agent-browser' -} - -export function parseShellArgs(input: string): string[] { - const args: string[] = [] - let current = '' - let inDouble = false - let inSingle = false - - for (let i = 0; i < input.length; i++) { - const ch = input[i] - if (ch === '"' && !inSingle) { - inDouble = !inDouble - } else if (ch === "'" && !inDouble) { - inSingle = !inSingle - } else if (ch === ' ' && !inDouble && !inSingle) { - if (current) { - args.push(current) - current = '' - } - } else { - current += ch - } - } - if (current) { - args.push(current) - } - return args -} - -export function stripAgentBrowserTargetArgs(args: string[]): string[] { - const stripped: string[] = [] - for (let index = 0; index < args.length; index++) { - const arg = args[index] - if (arg === '--cdp' || arg === '--session') { - index++ - continue - } - if (arg.startsWith('--cdp=') || arg.startsWith('--session=')) { - continue - } - stripped.push(arg) - } - return stripped -} - -// Stale refs need a distinct code so agents can retry with a fresh snapshot. -export function classifyErrorCode(message: string): string { - if (isAgentBrowserStaleRefError(message)) { - return 'browser_stale_ref' - } - return 'browser_error' -} - -export function isAbortedNavigationError(error: unknown): boolean { - if (!error || typeof error !== 'object') { - return false - } - const { code, errno } = error as { code?: unknown; errno?: unknown } - return code === 'ERR_ABORTED' || errno === -3 -} - -export function isWebContentsLoading(wc: WebContents): boolean { - try { - return wc.isLoading() - } catch { - // The caller rechecks authoritative page registration after waiting. - return false - } -} - -export function isLoadingMainFrame(wc: WebContents): boolean { - try { - return wc.isLoadingMainFrame() - } catch { - return false - } -} - -export function waitForAbortedNavigationReplacement( - wc: WebContents, - browserPageId: string, - timeoutMs: number -): Promise { - if (!isWebContentsLoading(wc)) { - return Promise.resolve() - } - - return new Promise((resolve, reject) => { - let settled = false - let timeout: ReturnType | null = null - const finish = (error?: BrowserError): void => { - if (settled) { - return - } - settled = true - wc.removeListener('did-stop-loading', onDidStopLoading) - wc.removeListener('destroyed', onDestroyed) - if (timeout) { - clearTimeout(timeout) - } - if (error) { - reject(error) - } else { - resolve() - } - } - const onDidStopLoading = (): void => finish() - const onDestroyed = (): void => finish() - - wc.on('did-stop-loading', onDidStopLoading) - wc.on('destroyed', onDestroyed) - timeout = setTimeout( - () => - finish( - new BrowserError( - 'browser_error', - `Failed to navigate browser page ${browserPageId}: Browser navigation timed out after ${EMBEDDED_NAVIGATION_TIMEOUT_MS}ms` - ) - ), - timeoutMs - ) - timeout.unref?.() - - // Loading may finish between loadURL rejection and listener attachment. - if (!isWebContentsLoading(wc)) { - finish() - } - }) -} - -export function isTabClosedTransportError(message: string): boolean { - return /session destroyed while command|session destroyed while commands|connection refused|cdp discovery methods failed|websocket connect failed/i.test( - message - ) -} - -/** agent-browser's handshake error when Orca's CDP proxy refuses its endpoint (wrong or missing token). */ -export function isCdpProxyRejectedError(message: string): boolean { - return /websocket connect failed\b.*\b40[34]\b/i.test(message) -} - -export function pageUnavailableMessageForSession(sessionName: string): string { - const prefix = ORCA_TAB_SESSION_PREFIX - const browserPageId = sessionName.startsWith(prefix) ? sessionName.slice(prefix.length) : null - return browserPageId - ? `Browser page ${browserPageId} is no longer available` - : 'Browser tab is no longer available' -} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-state-commands.ts b/src/main/browser/agent-browser/agent-browser-bridge-state-commands.ts deleted file mode 100644 index 72e9cc0e5bc..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-state-commands.ts +++ /dev/null @@ -1,307 +0,0 @@ -import type { - BrowserCookieGetResult, - BrowserCookieSetResult, - BrowserCookieDeleteResult, - BrowserCookie, - BrowserViewportResult, - BrowserGeolocationResult, - BrowserInterceptEnableResult, - BrowserInterceptDisableResult, - BrowserCaptureStartResult, - BrowserCaptureStopResult, - BrowserConsoleResult, - BrowserNetworkLogResult -} from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' -import { parseShellArgs, stripAgentBrowserTargetArgs } from './agent-browser-bridge-process' -import { AgentBrowserBridgeInteractionCommands } from './agent-browser-bridge-interaction-commands' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' -import { - toBrowserConsoleResult, - toBrowserNetworkLogResult, - type AgentBrowserConsoleOutput, - type AgentBrowserNetworkOutput -} from './agent-browser-log-entries' -import { touchEmulationParams } from '../cdp/input/guest-touch-emulation' - -export abstract class AgentBrowserBridgeStateCommands extends AgentBrowserBridgeInteractionCommands { - async cookieGet( - _url?: string, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - return (await this.execAgentBrowser(sessionName, [ - 'cookies', - 'get' - ])) as BrowserCookieGetResult - }) - } - - async cookieSet( - cookie: Partial, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const args = ['cookies', 'set', cookie.name ?? '', cookie.value ?? ''] - if (cookie.domain) { - args.push('--domain', cookie.domain) - } - if (cookie.path) { - args.push('--path', cookie.path) - } - if (cookie.secure) { - args.push('--secure') - } - if (cookie.httpOnly) { - args.push('--httpOnly') - } - if (cookie.sameSite) { - args.push('--sameSite', cookie.sameSite) - } - if (cookie.expires != null) { - args.push('--expires', String(cookie.expires)) - } - return (await this.execAgentBrowser(sessionName, args)) as BrowserCookieSetResult - }) - } - - async cookieDelete( - name?: string, - domain?: string, - _url?: string, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const args = ['cookies', 'clear'] - if (name) { - args.push('--name', name) - } - if (domain) { - args.push('--domain', domain) - } - return (await this.execAgentBrowser(sessionName, args)) as BrowserCookieDeleteResult - }) - } - - async setViewport( - width: number, - height: number, - scale = 1, - mobile = false, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (_sessionName, target) => { - const wc = this.getWebContents(target.webContentsId) - if (!wc) { - throw new BrowserError('browser_tab_not_found', 'Tab is no longer available') - } - const dbg = wc.debugger - if (!dbg.isAttached()) { - throw new BrowserError('browser_error', 'Debugger not attached') - } - - // agent-browser lacks a mobile viewport flag; apply Orca's emulation through CDP. - await sendGuestCdpCommand(wc, 'Emulation.setDeviceMetricsOverride', { - width, - height, - deviceScaleFactor: scale, - mobile - }) - await sendGuestCdpCommand( - wc, - 'Emulation.setTouchEmulationEnabled', - touchEmulationParams(mobile) - ) - // Metrics-only resize can leave the compositor at its old size and crop remote screencasts. - await sendGuestCdpCommand(wc, 'Emulation.setVisibleSize', { width, height }).catch(() => {}) - this.browserManager.showAgentViewportInPane(target.webContentsId, { - width, - height, - deviceScaleFactor: scale, - mobile - }) - - return { - width, - height, - deviceScaleFactor: scale, - mobile - } - }) - } - - async setGeolocation( - lat: number, - lon: number, - _accuracy?: number, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - return (await this.execAgentBrowser(sessionName, [ - 'set', - 'geo', - String(lat), - String(lon) - ])) as BrowserGeolocationResult - }) - } - - async interceptEnable( - patterns?: string[], - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const urlPattern = patterns?.[0] ?? '**/*' - const args = ['network', 'route', urlPattern] - const result = (await this.execAgentBrowser( - sessionName, - args - )) as BrowserInterceptEnableResult - const session = this.sessions.get(sessionName) - if (session) { - this.pendingInterceptRestore.delete(sessionName) - session.activeInterceptPatterns = patterns ?? ['*'] - } - return result - }) - } - - async interceptDisable( - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const result = (await this.execAgentBrowser(sessionName, [ - 'network', - 'unroute' - ])) as BrowserInterceptDisableResult - const session = this.sessions.get(sessionName) - if (session) { - this.pendingInterceptRestore.delete(sessionName) - session.activeInterceptPatterns = [] - } - return result - }) - } - - async interceptList( - worktreeId?: string, - browserPageId?: string - ): Promise<{ requests: unknown[] }> { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - return (await this.execAgentBrowser(sessionName, ['network', 'requests'])) as { - requests: unknown[] - } - }) - } - - // TODO: Per-request continue/block requires agent-browser support. - - async captureStart( - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const result = (await this.execAgentBrowser(sessionName, [ - 'network', - 'har', - 'start' - ])) as BrowserCaptureStartResult - const session = this.sessions.get(sessionName) - if (session) { - session.activeCapture = true - } - return result - }) - } - - async captureStop( - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - const result = (await this.execAgentBrowser(sessionName, [ - 'network', - 'har', - 'stop' - ])) as BrowserCaptureStopResult - const session = this.sessions.get(sessionName) - if (session) { - session.activeCapture = false - } - return result - }) - } - - async consoleLog( - limit?: number, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: agent-browser's `console --json` data has this shape. - const output = (await this.execAgentBrowser(sessionName, [ - 'console' - ])) as AgentBrowserConsoleOutput - return toBrowserConsoleResult(output, limit) - }) - } - - async networkLog( - limit?: number, - worktreeId?: string, - browserPageId?: string - ): Promise { - return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: agent-browser's `network requests --json` data has this shape. - const output = (await this.execAgentBrowser(sessionName, [ - 'network', - 'requests' - ])) as AgentBrowserNetworkOutput - return toBrowserNetworkLogResult(output, limit) - }) - } - - async exec(command: string, worktreeId?: string, browserPageId?: string): Promise { - // Passthrough arguments must not override Orca's selected page or CDP proxy. - const args = stripAgentBrowserTargetArgs(parseShellArgs(command.trim())) - return this.enqueueTargetedCommand( - worktreeId, - browserPageId, - async (sessionName) => await this.execAgentBrowser(sessionName, args, { cliArgv: true }), - { elements: passthroughElementArgs(args) } - ) - } -} - -// Commands whose first operand is an element, where agent-browser reads a bare `e2` as a ref. -const ELEMENT_FIRST_COMMANDS = new Set([ - 'click', - 'dblclick', - 'hover', - 'focus', - 'check', - 'uncheck', - 'fill', - 'type', - 'select', - 'scrollintoview', - 'upload', - 'highlight', - 'download', - 'drag' -]) - -// Free text such as `keyboard type e2` is not a ref; explicit `@e2`/`ref=e2` are refs anywhere. -function passthroughElementArgs([command, ...operands]: string[]): string[] { - const explicit = operands.filter((arg) => arg.startsWith('@') || arg.startsWith('ref=')) - return command && ELEMENT_FIRST_COMMANDS.has(command) && operands[0] - ? [operands[0], ...explicit] - : explicit -} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-types.ts b/src/main/browser/agent-browser/agent-browser-bridge-types.ts deleted file mode 100644 index 8a784e0eba5..00000000000 --- a/src/main/browser/agent-browser/agent-browser-bridge-types.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { ChildProcess } from 'node:child_process' -import type { CdpWsProxy } from '../cdp/transport/cdp-ws-proxy' -import type { BrowserError } from '../browser-error' - -// Exceed agent-browser's internal navigation (30s) and default wait (25s) timeouts. -export const EXEC_TIMEOUT_MS = 90_000 -export const CONSECUTIVE_TIMEOUT_LIMIT = 3 -export const STALE_SESSION_CLOSE_TIMEOUT_MS = 3_000 -export const AGENT_BROWSER_EXIT_DRAIN_MS = 500 -// Cleanup must finish within the 20s quit barrier. -export const AGENT_BROWSER_CLEANUP_TIMEOUT_MS = 5_000 -export const AGENT_BROWSER_CLEANUP_CONCURRENCY = 4 -export const EMBEDDED_NAVIGATION_TIMEOUT_MS = 30_000 -export const AGENT_DOWNLOAD_START_TIMEOUT_MS = 10_000 -// Counted from the request, so the reply beats the CLI's 60s timeout; the download keeps going after. -export const AGENT_DOWNLOAD_REPLY_DEADLINE_MS = 50_000 -export const AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES = 8 * 1024 -export const AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES = AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES - -export type SessionState = { - proxy: CdpWsProxy - cdpEndpoint: string - initialized: boolean - consecutiveTimeouts: number - // Restore these routes after a session restart. - activeInterceptPatterns: string[] - activeCapture: boolean - // Detect idle daemon retirement from the gap between commands. - lastCommandAt: number - // Revalidate after queue delay, when the tab may have disappeared. - webContentsId: number - activeProcess: ChildProcess | null - // agent-browser keeps the `snapshot --delta` baseline in this session's daemon. - hasDeltaBaseline?: boolean -} - -export type QueuedCommand = { - execute: () => Promise - resolve: (value: unknown) => void - reject: (reason: unknown) => void -} - -export type ResolvedBrowserCommandTarget = { - browserPageId: string - webContentsId: number -} - -export type AgentBrowserCleanupOptions = { - closeTimeoutMs?: number - /** Preserve queued commands for the replacement session. */ - keepQueuedCommands?: boolean -} - -export type AgentBrowserExecOptions = { - envOverrides?: NodeJS.ProcessEnv - timeoutMs?: number - timeoutError?: BrowserError - /** The caller owns stdin, so the command goes as argv; only for Orca-authored tokens. */ - stdinText?: string - /** Send tokens as argv so global options apply; only for Orca-authored or raw CLI tokens. */ - cliArgv?: boolean -} - -export type EnqueueTargetedCommandOptions = { - ensureSession?: boolean - /** Page actions report what they caused when an agent runs them. */ - reportEffects?: boolean - // Text mutations must not fall back to a global tab from another worktree. - requireScopedTarget?: boolean - // Element arguments that may be snapshot refs. - elements?: readonly (string | undefined)[] -} - -export type AgentBrowserBridgeOptions = { - onTabsChanged?: (worktreeId?: string) => void -} diff --git a/src/main/browser/agent-browser/agent-browser-bridge.ts b/src/main/browser/agent-browser/agent-browser-bridge.ts index 64663b9b8e1..f34370fc2cb 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge.ts +++ b/src/main/browser/agent-browser/agent-browser-bridge.ts @@ -1,3 +1,310 @@ -import { AgentBrowserBridgeStateCommands } from './agent-browser-bridge-state-commands' +import type { + BrowserCookieGetResult, + BrowserCookieSetResult, + BrowserCookieDeleteResult, + BrowserCookie, + BrowserViewportResult, + BrowserGeolocationResult, + BrowserInterceptEnableResult, + BrowserInterceptDisableResult, + BrowserCaptureStartResult, + BrowserCaptureStopResult, + BrowserConsoleResult, + BrowserNetworkLogResult +} from '../../../shared/runtime-browser-contracts' +import { BrowserError } from '../browser-error' +import { + parseShellArgs, + stripAgentBrowserTargetArgs +} from './protocol/agent-browser-passthrough-arguments' +import { AgentBrowserBridgeInteractionCommands } from './commands/agent-browser-bridge-interaction-commands' +import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' +import { + toBrowserConsoleResult, + toBrowserNetworkLogResult, + type AgentBrowserConsoleOutput, + type AgentBrowserNetworkOutput +} from './observation/agent-browser-log-entries' +import { touchEmulationParams } from '../cdp/input/guest-touch-emulation' -export class AgentBrowserBridge extends AgentBrowserBridgeStateCommands {} +export class AgentBrowserBridge extends AgentBrowserBridgeInteractionCommands { + async cookieGet( + _url?: string, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + return (await this.execAgentBrowser(sessionName, [ + 'cookies', + 'get' + ])) as BrowserCookieGetResult + }) + } + + async cookieSet( + cookie: Partial, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const args = ['cookies', 'set', cookie.name ?? '', cookie.value ?? ''] + if (cookie.domain) { + args.push('--domain', cookie.domain) + } + if (cookie.path) { + args.push('--path', cookie.path) + } + if (cookie.secure) { + args.push('--secure') + } + if (cookie.httpOnly) { + args.push('--httpOnly') + } + if (cookie.sameSite) { + args.push('--sameSite', cookie.sameSite) + } + if (cookie.expires != null) { + args.push('--expires', String(cookie.expires)) + } + return (await this.execAgentBrowser(sessionName, args)) as BrowserCookieSetResult + }) + } + + async cookieDelete( + name?: string, + domain?: string, + _url?: string, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const args = ['cookies', 'clear'] + if (name) { + args.push('--name', name) + } + if (domain) { + args.push('--domain', domain) + } + return (await this.execAgentBrowser(sessionName, args)) as BrowserCookieDeleteResult + }) + } + + async setViewport( + width: number, + height: number, + scale = 1, + mobile = false, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (_sessionName, target) => { + const wc = this.getWebContents(target.webContentsId) + if (!wc) { + throw new BrowserError('browser_tab_not_found', 'Tab is no longer available') + } + const dbg = wc.debugger + if (!dbg.isAttached()) { + throw new BrowserError('browser_error', 'Debugger not attached') + } + + // agent-browser lacks a mobile viewport flag; apply Orca's emulation through CDP. + await sendGuestCdpCommand(wc, 'Emulation.setDeviceMetricsOverride', { + width, + height, + deviceScaleFactor: scale, + mobile + }) + await sendGuestCdpCommand( + wc, + 'Emulation.setTouchEmulationEnabled', + touchEmulationParams(mobile) + ) + // Metrics-only resize can leave the compositor at its old size and crop remote screencasts. + await sendGuestCdpCommand(wc, 'Emulation.setVisibleSize', { width, height }).catch(() => {}) + this.browserManager.showAgentViewportInPane(target.webContentsId, { + width, + height, + deviceScaleFactor: scale, + mobile + }) + + return { + width, + height, + deviceScaleFactor: scale, + mobile + } + }) + } + + async setGeolocation( + lat: number, + lon: number, + _accuracy?: number, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + return (await this.execAgentBrowser(sessionName, [ + 'set', + 'geo', + String(lat), + String(lon) + ])) as BrowserGeolocationResult + }) + } + + async interceptEnable( + patterns?: string[], + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const urlPattern = patterns?.[0] ?? '**/*' + const args = ['network', 'route', urlPattern] + const result = (await this.execAgentBrowser( + sessionName, + args + )) as BrowserInterceptEnableResult + const session = this.sessions.get(sessionName) + if (session) { + this.pendingInterceptRestore.delete(sessionName) + session.activeInterceptPatterns = patterns ?? ['*'] + } + return result + }) + } + + async interceptDisable( + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const result = (await this.execAgentBrowser(sessionName, [ + 'network', + 'unroute' + ])) as BrowserInterceptDisableResult + const session = this.sessions.get(sessionName) + if (session) { + this.pendingInterceptRestore.delete(sessionName) + session.activeInterceptPatterns = [] + } + return result + }) + } + + async interceptList( + worktreeId?: string, + browserPageId?: string + ): Promise<{ requests: unknown[] }> { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + return (await this.execAgentBrowser(sessionName, ['network', 'requests'])) as { + requests: unknown[] + } + }) + } + + // TODO: Per-request continue/block requires agent-browser support. + + async captureStart( + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const result = (await this.execAgentBrowser(sessionName, [ + 'network', + 'har', + 'start' + ])) as BrowserCaptureStartResult + const session = this.sessions.get(sessionName) + if (session) { + session.activeCapture = true + } + return result + }) + } + + async captureStop( + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + const result = (await this.execAgentBrowser(sessionName, [ + 'network', + 'har', + 'stop' + ])) as BrowserCaptureStopResult + const session = this.sessions.get(sessionName) + if (session) { + session.activeCapture = false + } + return result + }) + } + + async consoleLog( + limit?: number, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: agent-browser's `console --json` data has this shape. + const output = (await this.execAgentBrowser(sessionName, [ + 'console' + ])) as AgentBrowserConsoleOutput + return toBrowserConsoleResult(output, limit) + }) + } + + async networkLog( + limit?: number, + worktreeId?: string, + browserPageId?: string + ): Promise { + return this.enqueueTargetedCommand(worktreeId, browserPageId, async (sessionName) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: agent-browser's `network requests --json` data has this shape. + const output = (await this.execAgentBrowser(sessionName, [ + 'network', + 'requests' + ])) as AgentBrowserNetworkOutput + return toBrowserNetworkLogResult(output, limit) + }) + } + + async exec(command: string, worktreeId?: string, browserPageId?: string): Promise { + // Passthrough arguments must not override Orca's selected page or CDP proxy. + const args = stripAgentBrowserTargetArgs(parseShellArgs(command.trim())) + return this.enqueueTargetedCommand( + worktreeId, + browserPageId, + async (sessionName) => await this.execAgentBrowser(sessionName, args, { cliArgv: true }), + { elements: passthroughElementArgs(args) } + ) + } +} + +// Commands whose first operand is an element, where agent-browser reads a bare `e2` as a ref. +const ELEMENT_FIRST_COMMANDS = new Set([ + 'click', + 'dblclick', + 'hover', + 'focus', + 'check', + 'uncheck', + 'fill', + 'type', + 'select', + 'scrollintoview', + 'upload', + 'highlight', + 'download', + 'drag' +]) + +// Free text such as `keyboard type e2` is not a ref; explicit `@e2`/`ref=e2` are refs anywhere. +function passthroughElementArgs([command, ...operands]: string[]): string[] { + const explicit = operands.filter((arg) => arg.startsWith('@') || arg.startsWith('ref=')) + return command && ELEMENT_FIRST_COMMANDS.has(command) && operands[0] + ? [operands[0], ...explicit] + : explicit +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-action-effects.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-action-effects.ts similarity index 86% rename from src/main/browser/agent-browser/agent-browser-bridge-action-effects.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-bridge-action-effects.ts index 3da02ea5575..2486e0f09c2 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-action-effects.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-action-effects.ts @@ -1,8 +1,8 @@ -import { BrowserError } from '../browser-error' -import { AgentBrowserBridgeShutdown } from './agent-browser-bridge-shutdown' -import type { ResolvedBrowserCommandTarget } from './agent-browser-bridge-types' -import { assertRemoteCliPageAccess } from '../routing/input-ownership/remote-cli-page-admission' -import type { ActionEffectsHost } from './agent-browser-action-effects' +import { BrowserError } from '../../browser-error' +import { AgentBrowserBridgeShutdown } from '../session-lifecycle/agent-browser-bridge-shutdown' +import type { ResolvedBrowserCommandTarget } from '../session-routing/agent-browser-command-target' +import { assertRemoteCliPageAccess } from '../../routing/input-ownership/remote-cli-page-admission' +import type { ActionEffectsHost } from '../observation/agent-browser-action-effects' const EFFECTS_SNAPSHOT_TIMEOUT_MS = 5_000 diff --git a/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-expected-url.test.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-bridge-expected-url.test.ts index 05eb1ebbfc7..115de003690 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-expected-url.test.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-expected-url.test.ts @@ -1,4 +1,19 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' +import { runInRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { runWithRequestedPageUrl } from '../../cdp/input/browser-expected-page-url' +import { AgentBrowserBridge } from '../agent-browser-bridge' +import { + answerAgentBrowserCommands, + mockBrowserManager, + mockWebContents, + overrideBridgeWebContentsLookup, + resetAgentBrowserBridgeMocks +} from '../testing/agent-browser-bridge-test-harness' +import type { + ExecFileCallback, + MockWebContents +} from '../testing/agent-browser-bridge-test-harness' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = vi.hoisted(() => ({ @@ -35,20 +50,7 @@ const { CdpWsProxyMock } = vi.hoisted(() => { }) return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { runWithRequestedPageUrl } from '../cdp/input/browser-expected-page-url' -import { AgentBrowserBridge } from './agent-browser-bridge' -import { - answerAgentBrowserCommands, - mockBrowserManager, - mockWebContents, - overrideBridgeWebContentsLookup, - resetAgentBrowserBridgeMocks, - type ExecFileCallback, - type MockWebContents -} from './agent-browser-bridge-test-harness' -import type { BrowserManager } from '../browser-manager' +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-host-revocation.test.ts similarity index 94% rename from src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-bridge-host-revocation.test.ts index 4475116ab00..bf8805e261d 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-host-revocation.test.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-host-revocation.test.ts @@ -36,16 +36,16 @@ const { CdpWsProxyMock } = vi.hoisted(() => { }) return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -import { AgentBrowserBridge } from './agent-browser-bridge' -import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { AgentBrowserBridge } from '../agent-browser-bridge' +import { runInRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { mockBrowserManager, mockWebContents, overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-javascript-dialog.test.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-javascript-dialog.test.ts similarity index 87% rename from src/main/browser/agent-browser/agent-browser-bridge-javascript-dialog.test.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-bridge-javascript-dialog.test.ts index 756d1f504eb..a16dd4f862d 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-javascript-dialog.test.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-javascript-dialog.test.ts @@ -33,16 +33,16 @@ const { CdpWsProxyMock } = vi.hoisted(() => { }) return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -import { AgentBrowserBridge } from './agent-browser-bridge' -import { installBrowserJavaScriptDialogs } from '../guest-lifecycle/prompts/browser-javascript-dialogs' -import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { AgentBrowserBridge } from '../agent-browser-bridge' +import { installBrowserJavaScriptDialogs } from '../../guest-lifecycle/prompts/browser-javascript-dialogs' +import { runInRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { mockBrowserManager, overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-queue.ts b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts similarity index 90% rename from src/main/browser/agent-browser/agent-browser-bridge-queue.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts index b03111968d8..91595222056 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-queue.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-bridge-queue.ts @@ -1,17 +1,15 @@ -import type { BrowserTabSwitchResult } from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' +import type { BrowserTabSwitchResult } from '../../../../shared/runtime-browser-contracts' +import { BrowserError } from '../../browser-error' import { AgentBrowserBridgeActionEffects } from './agent-browser-bridge-action-effects' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import type { - EnqueueTargetedCommandOptions, - ResolvedBrowserCommandTarget -} from './agent-browser-bridge-types' -import { runWithRemoteCliPageAdmission } from '../routing/input-ownership/remote-cli-page-admission' -import { runWithActionEffects } from './agent-browser-action-effects' -import { getRequestedPageUrl, runExpectingPageUrl } from '../cdp/input/browser-expected-page-url' -import { AGENT_BROWSER_CLEANUP_TIMEOUT_MS } from './agent-browser-bridge-types' -import { releaseHeldPageInput } from '../cdp/input/guest-direct-key-input' -import { onBrowserJavaScriptDialogOpened } from '../guest-lifecycle/prompts/browser-javascript-dialogs' +import { ORCA_TAB_SESSION_PREFIX } from '../session-lifecycle/agent-browser-session-name' +import type { EnqueueTargetedCommandOptions } from './agent-browser-queued-command' +import type { ResolvedBrowserCommandTarget } from '../session-routing/agent-browser-command-target' +import { runWithRemoteCliPageAdmission } from '../../routing/input-ownership/remote-cli-page-admission' +import { runWithActionEffects } from '../observation/agent-browser-action-effects' +import { getRequestedPageUrl, runExpectingPageUrl } from '../../cdp/input/browser-expected-page-url' +import { AGENT_BROWSER_CLEANUP_TIMEOUT_MS } from '../session-lifecycle/agent-browser-cleanup-options' +import { releaseHeldPageInput } from '../../cdp/input/guest-direct-key-input' +import { onBrowserJavaScriptDialogOpened } from '../../guest-lifecycle/prompts/browser-javascript-dialogs' import { assertNoJavaScriptDialog, dialogAnswerHint, @@ -21,8 +19,8 @@ import { captureRemoteCliBrowserRevocation, captureRemoteCliBrowserScope, runOutsideRemoteCliBrowserScope -} from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { getActiveRpcCaller } from '../../runtime/rpc/rpc-active-caller' +} from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' export abstract class AgentBrowserBridgeQueue extends AgentBrowserBridgeActionEffects { // Serialize tab switches behind commands targeting the current tab. diff --git a/src/main/browser/agent-browser/agent-browser-dialog-errors.ts b/src/main/browser/agent-browser/command-queue/agent-browser-dialog-errors.ts similarity index 84% rename from src/main/browser/agent-browser/agent-browser-dialog-errors.ts rename to src/main/browser/agent-browser/command-queue/agent-browser-dialog-errors.ts index 8da7e150ced..0008f580d54 100644 --- a/src/main/browser/agent-browser/agent-browser-dialog-errors.ts +++ b/src/main/browser/agent-browser/command-queue/agent-browser-dialog-errors.ts @@ -1,6 +1,6 @@ -import { BrowserError } from '../browser-error' -import { getBrowserJavaScriptDialog } from '../guest-lifecycle/prompts/browser-javascript-dialogs' -import type { BrowserJavaScriptDialog } from '../../../shared/browser-javascript-dialog' +import { BrowserError } from '../../browser-error' +import { getBrowserJavaScriptDialog } from '../../guest-lifecycle/prompts/browser-javascript-dialogs' +import type { BrowserJavaScriptDialog } from '../../../../shared/browser-javascript-dialog' const DIALOG_MESSAGE_QUOTE_MAX_CHARS = 500 diff --git a/src/main/browser/agent-browser/command-queue/agent-browser-queued-command.ts b/src/main/browser/agent-browser/command-queue/agent-browser-queued-command.ts new file mode 100644 index 00000000000..0a8ba7450f0 --- /dev/null +++ b/src/main/browser/agent-browser/command-queue/agent-browser-queued-command.ts @@ -0,0 +1,15 @@ +export type QueuedCommand = { + execute: () => Promise + resolve: (value: unknown) => void + reject: (reason: unknown) => void +} + +export type EnqueueTargetedCommandOptions = { + ensureSession?: boolean + /** Page actions report what they caused when an agent runs them. */ + reportEffects?: boolean + // Text mutations must not fall back to a global tab from another worktree. + requireScopedTarget?: boolean + // Element arguments that may be snapshot refs. + elements?: readonly (string | undefined)[] +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-capture-commands.ts similarity index 87% rename from src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-capture-commands.ts index b62d85b9f58..7c69dab7046 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-capture-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-capture-commands.ts @@ -1,27 +1,30 @@ -import type { BrowserScreenshotOptions } from '../../../shared/rpc-contract/browser-observation-params' +import type { BrowserScreenshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' import { z } from 'zod' import { app, nativeImage, type WebContents } from 'electron' import type { BrowserScreenshotResult, BrowserEvalResult -} from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' +} from '../../../../shared/runtime-browser-contracts' +import { BrowserError } from '../../browser-error' import { captureFullPageScreenshot, SCREENSHOT_TIMEOUT_MS, withTimeout -} from '../cdp/commands/cdp-screenshot' +} from '../../cdp/commands/cdp-screenshot' import { agentBrowserScreenshotArgs, readAgentBrowserScreenshot -} from './agent-browser-screenshot-arguments' -import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions' -import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' +} from '../observation/agent-browser-screenshot-arguments' +import { readRasterImageDimensions } from '../../../../shared/file-preview/raster-image-dimensions' +import { acquireElectronDebugger } from '../../cdp/debugger/electron-debugger-lease' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' import { AgentBrowserBridgeUtilityCommands } from './agent-browser-bridge-page-commands' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import { captureRemoteCliBrowserWorkBound } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { ORCA_TAB_SESSION_PREFIX } from '../session-lifecycle/agent-browser-session-name' +import { captureRemoteCliBrowserWorkBound } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { + throwIfSignalAborted, + waitForPromiseWithSignal +} from '../../../../shared/abort-signal-reason' export abstract class AgentBrowserBridgeCaptureCommands extends AgentBrowserBridgeUtilityCommands { async screenshot( diff --git a/src/main/browser/agent-browser/agent-browser-bridge-core-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-core-commands.ts similarity index 88% rename from src/main/browser/agent-browser/agent-browser-bridge-core-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-core-commands.ts index 84774bde69c..82d64eadc10 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-core-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-core-commands.ts @@ -1,23 +1,23 @@ -import type { BrowserSnapshotOptions } from '../../../shared/rpc-contract/browser-observation-params' +import type { BrowserSnapshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' import type { BrowserSnapshotResult, BrowserClickResult, BrowserGotoResult, BrowserFillResult -} from '../../../shared/runtime-browser-contracts' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../../shared/clipboard-text' -import { normalizeBrowserNavigationUrl } from '../../../shared/browser-url' -import { BrowserError } from '../browser-error' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import { FILL_ELEMENT_FUNCTION } from '../cdp/input/browser-element-functions' -import { EMBEDDED_NAVIGATION_TIMEOUT_MS } from './agent-browser-bridge-types' +} from '../../../../shared/runtime-browser-contracts' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' +import { BrowserError } from '../../browser-error' +import { ORCA_TAB_SESSION_PREFIX } from '../session-lifecycle/agent-browser-session-name' +import { FILL_ELEMENT_FUNCTION } from '../../cdp/input/browser-element-functions' import { + EMBEDDED_NAVIGATION_TIMEOUT_MS, isAbortedNavigationError, waitForAbortedNavigationReplacement -} from './agent-browser-bridge-process' -import { AgentBrowserBridgeQueue } from './agent-browser-bridge-queue' -import { assertRemoteCliPageAccess } from '../routing/input-ownership/remote-cli-page-admission' -import { agentBrowserSnapshotArgs } from './agent-browser-snapshot-arguments' +} from './agent-browser-navigation-settle' +import { AgentBrowserBridgeQueue } from '../command-queue/agent-browser-bridge-queue' +import { assertRemoteCliPageAccess } from '../../routing/input-ownership/remote-cli-page-admission' +import { agentBrowserSnapshotArgs } from '../protocol/agent-browser-snapshot-arguments' export abstract class AgentBrowserBridgeCoreCommands extends AgentBrowserBridgeQueue { async snapshot( diff --git a/src/main/browser/agent-browser/agent-browser-bridge-element-calls.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-element-calls.ts similarity index 88% rename from src/main/browser/agent-browser/agent-browser-bridge-element-calls.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-element-calls.ts index cda545a3a4e..b59450ab742 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-element-calls.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-element-calls.ts @@ -1,10 +1,10 @@ import type { WebContents } from 'electron' -import { BrowserError } from '../browser-error' -import type { CapturedElement } from '../cdp/commands/cdp-element-capture' -import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page-url' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' -import { readRecord, readString } from '../cdp/input/guest-frame-input-sessions' -import { AgentBrowserBridgeExecution } from './agent-browser-bridge-execution' +import { BrowserError } from '../../browser-error' +import type { CapturedElement } from '../../cdp/commands/cdp-element-capture' +import { assertExpectedPageUrlForStep } from '../../cdp/input/browser-expected-page-url' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' +import { readRecord, readString } from '../../cdp/input/guest-frame-input-sessions' +import { AgentBrowserBridgeExecution } from '../helper-process/agent-browser-bridge-execution' export type CapturedTarget = { wc: WebContents; captured: CapturedElement } diff --git a/src/main/browser/agent-browser/agent-browser-bridge-input-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-input-commands.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-input-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-input-commands.ts index c95f79e7196..b7649baf342 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-input-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-input-commands.ts @@ -1,12 +1,12 @@ import type { BrowserSelectResult, BrowserScrollResult -} from '../../../shared/runtime-browser-contracts' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../../shared/clipboard-text' -import { iterateBrowserTextInsertionChunks } from '../../../shared/browser-text-insertion-chunks' -import { AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES } from './agent-browser-bridge-types' +} from '../../../../shared/runtime-browser-contracts' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { iterateBrowserTextInsertionChunks } from '../../../../shared/browser-text-insertion-chunks' +import { AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES } from '../protocol/agent-browser-text-argument-budget' import { AgentBrowserBridgeCoreCommands } from './agent-browser-bridge-core-commands' -import { SELECT_OPTION_TARGET_FUNCTION } from '../cdp/input/browser-element-functions' +import { SELECT_OPTION_TARGET_FUNCTION } from '../../cdp/input/browser-element-functions' export abstract class AgentBrowserBridgeInputCommands extends AgentBrowserBridgeCoreCommands { async select( diff --git a/src/main/browser/agent-browser/agent-browser-bridge-interaction-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-interaction-commands.ts similarity index 92% rename from src/main/browser/agent-browser/agent-browser-bridge-interaction-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-interaction-commands.ts index b9547e6f7d4..18018862702 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-interaction-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-interaction-commands.ts @@ -8,25 +8,25 @@ import type { BrowserClearResult, BrowserSelectAllResult, BrowserPdfResult -} from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' +} from '../../../../shared/runtime-browser-contracts' +import { BrowserError } from '../../browser-error' import { FILE_INPUT_FRAME_URL_FUNCTION, FILE_UPLOAD_TARGET_FUNCTION, FILL_ELEMENT_FUNCTION, SELECT_ALL_ELEMENT_FUNCTION -} from '../cdp/input/browser-element-functions' -import { assertUploadFilesExist } from '../cdp/input/browser-upload-files' +} from '../../cdp/input/browser-element-functions' +import { assertUploadFilesExist } from '../../cdp/input/browser-upload-files' import type { WebContents } from 'electron' -import type { CapturedElement } from '../cdp/commands/cdp-element-capture' -import { interceptFileChooser, type OpenedFileChooser } from '../cdp/input/guest-file-chooser' -import { readRecord, readString } from '../cdp/input/guest-frame-input-sessions' +import type { CapturedElement } from '../../cdp/commands/cdp-element-capture' +import { interceptFileChooser, type OpenedFileChooser } from '../../cdp/input/guest-file-chooser' +import { readRecord, readString } from '../../cdp/input/guest-frame-input-sessions' import { agentBrowserWaitArguments, type AgentBrowserWaitOptions -} from './agent-browser-wait-arguments' -import { parseCdpKeyEvent } from '../cdp/input/cdp-keyboard-us-layout' -import { readRemoteCliAdmittedPage } from '../routing/input-ownership/remote-cli-page-admission' +} from '../protocol/agent-browser-wait-arguments' +import { parseCdpKeyEvent } from '../../cdp/input/cdp-keyboard-us-layout' +import { readRemoteCliAdmittedPage } from '../../routing/input-ownership/remote-cli-page-admission' import { AgentBrowserBridgeKeyCommands } from './agent-browser-bridge-key-commands' export abstract class AgentBrowserBridgeInteractionCommands extends AgentBrowserBridgeKeyCommands { diff --git a/src/main/browser/agent-browser/agent-browser-bridge-key-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-key-commands.ts similarity index 86% rename from src/main/browser/agent-browser/agent-browser-bridge-key-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-key-commands.ts index 70f303341d1..4faf5baef24 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-key-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-key-commands.ts @@ -1,24 +1,24 @@ import type { BrowserKeypressResult, BrowserTypeResult -} from '../../../shared/runtime-browser-contracts' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../../shared/clipboard-text' -import { BrowserError } from '../browser-error' -import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease' +} from '../../../../shared/runtime-browser-contracts' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { BrowserError } from '../../browser-error' +import { acquireElectronDebugger } from '../../cdp/debugger/electron-debugger-lease' import { parseCdpKeyEvent, imeFallbackKeyEvent, typedInputSteps, type TypedInputStep -} from '../cdp/input/cdp-keyboard-us-layout' -import type { ResolvedBrowserCommandTarget } from './agent-browser-bridge-types' +} from '../../cdp/input/cdp-keyboard-us-layout' +import type { ResolvedBrowserCommandTarget } from '../session-routing/agent-browser-command-target' import { dispatchPageKeyEvents, - routePageTextInsertion, - type GuestCdpSender -} from '../cdp/input/guest-direct-key-input' -import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page-url' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' + routePageTextInsertion +} from '../../cdp/input/guest-direct-key-input' +import type { GuestSessionCdpSender } from '../../cdp/input/guest-frame-input-sessions' +import { assertExpectedPageUrlForStep } from '../../cdp/input/browser-expected-page-url' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' import { AgentBrowserBridgeCaptureCommands } from './agent-browser-bridge-capture-commands' // Bounds the events a typed run holds and how long it keeps the main loop busy. @@ -76,7 +76,7 @@ export abstract class AgentBrowserBridgeKeyCommands extends AgentBrowserBridgeCa try { releaseDebugger = acquireElectronDebugger(wc).release await this.waitForPagePaint(wc, target.webContentsId) - const send: GuestCdpSender = (method, params, sessionId) => + const send: GuestSessionCdpSender = (method, params, sessionId) => sendGuestCdpCommand(wc, method, params, sessionId) const guardFocus = (): Promise<() => void> => this.browserManager.guardUserFocusForAgentInput(target.webContentsId) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-keypress-input.test.ts similarity index 95% rename from src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-keypress-input.test.ts index 86924a5931b..5cee79cc2dc 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-keypress-input.test.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-keypress-input.test.ts @@ -42,11 +42,11 @@ const { CdpWsProxyMock } = vi.hoisted(() => { return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -import { AgentBrowserBridge } from './agent-browser-bridge' +import { AgentBrowserBridge } from '../agent-browser-bridge' import { createSucceedWith, mockBrowserManager, @@ -54,7 +54,7 @@ import { overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks, type MockWebContents -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-mouse-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-mouse-commands.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-mouse-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-mouse-commands.ts index 762d664e0d5..e5a9725efee 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-mouse-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-mouse-commands.ts @@ -1,18 +1,18 @@ -import type { BrowserMouseModifier } from '../cdp/input/cdp-pointer-targets' -import { BrowserError } from '../browser-error' +import type { BrowserMouseModifier } from '../../cdp/input/cdp-pointer-targets' +import { BrowserError } from '../../browser-error' import { normalizeCdpMouseButton, cdpPointerButtonMask, cdpMouseModifierMask, resolveMobileTouchClickPoint -} from '../cdp/input/cdp-pointer-targets' -import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease' -import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page-url' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' -import { touchEmulationParams } from '../cdp/input/guest-touch-emulation' -import { assertRemoteCliBrowserAccess } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +} from '../../cdp/input/cdp-pointer-targets' +import { acquireElectronDebugger } from '../../cdp/debugger/electron-debugger-lease' +import { assertExpectedPageUrlForStep } from '../../cdp/input/browser-expected-page-url' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' +import { touchEmulationParams } from '../../cdp/input/guest-touch-emulation' +import { assertRemoteCliBrowserAccess } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { AgentBrowserBridgePointerCommands } from './agent-browser-bridge-pointer-commands' -import { agentBrowserSetMediaArguments } from './agent-browser-set-media-arguments' +import { agentBrowserSetMediaArguments } from '../protocol/agent-browser-set-media-arguments' export abstract class AgentBrowserBridgeMouseCommands extends AgentBrowserBridgePointerCommands { async mouseClick( diff --git a/src/main/browser/agent-browser/agent-browser-bridge-navigation.test.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-navigation.test.ts similarity index 90% rename from src/main/browser/agent-browser/agent-browser-bridge-navigation.test.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-navigation.test.ts index e09992238ea..798045c7c83 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-navigation.test.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-navigation.test.ts @@ -1,4 +1,4 @@ -import type * as BrowserErrorTypes from '../browser-error' +import type * as BrowserErrorTypes from '../../browser-error' import { describe, it, expect, vi, beforeEach } from 'vitest' const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = @@ -40,10 +40,10 @@ const { CdpWsProxyMock } = vi.hoisted(() => { return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -vi.mock('../browser-error', () => ({ +vi.mock('../../browser-error', () => ({ BrowserError: class BrowserError extends Error { code: string constructor(code: string, message: string) { @@ -53,18 +53,18 @@ vi.mock('../browser-error', () => ({ } })) -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') +vi.mock('../../cdp/commands/cdp-bridge', async () => { + const { BrowserError } = await vi.importMock('../../browser-error') return { BrowserError } }) -import { AgentBrowserBridge } from './agent-browser-bridge' +import { AgentBrowserBridge } from '../agent-browser-bridge' import { mockBrowserManager, mockWebContents, overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-page-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-page-commands.ts similarity index 91% rename from src/main/browser/agent-browser/agent-browser-bridge-page-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-page-commands.ts index e70478bb3f7..96b1da212e5 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-page-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-page-commands.ts @@ -1,24 +1,23 @@ import { mkdir } from 'node:fs/promises' import path from 'node:path' -import { BrowserError } from '../browser-error' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../../shared/clipboard-text' -import { withTimeout } from '../../../shared/promise-timeout-fallback' -import { - AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES, - AGENT_DOWNLOAD_REPLY_DEADLINE_MS, - AGENT_DOWNLOAD_START_TIMEOUT_MS -} from './agent-browser-bridge-types' +import { BrowserError } from '../../browser-error' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import { AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES } from '../protocol/agent-browser-text-argument-budget' import type { BrowserBackResult, BrowserReloadResult -} from '../../../shared/runtime-browser-contracts' +} from '../../../../shared/runtime-browser-contracts' import { AgentBrowserBridgeMouseCommands } from './agent-browser-bridge-mouse-commands' import { answerBrowserJavaScriptDialog, getBrowserJavaScriptDialog -} from '../guest-lifecycle/prompts/browser-javascript-dialogs' -import { captureRemoteCliBrowserRevocation } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { ExpectedPageUrlGuard, getRequestedPageUrl } from '../cdp/input/browser-expected-page-url' +} from '../../guest-lifecycle/prompts/browser-javascript-dialogs' +import { captureRemoteCliBrowserRevocation } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { + ExpectedPageUrlGuard, + getRequestedPageUrl +} from '../../cdp/input/browser-expected-page-url' /** Keep JSON results stable across CLI payload versions. */ export type BrowserDialogAnswer = { accepted: boolean; browserPageId?: string; checkedUrl?: string } @@ -248,3 +247,8 @@ export abstract class AgentBrowserBridgeUtilityCommands extends AgentBrowserBrid }) } } + +export const AGENT_DOWNLOAD_START_TIMEOUT_MS = 10_000 + +// Counted from the request, so the reply beats the CLI's 60s timeout; the download keeps going after. +export const AGENT_DOWNLOAD_REPLY_DEADLINE_MS = 50_000 diff --git a/src/main/browser/agent-browser/agent-browser-bridge-pointer-commands.ts b/src/main/browser/agent-browser/commands/agent-browser-bridge-pointer-commands.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-pointer-commands.ts rename to src/main/browser/agent-browser/commands/agent-browser-bridge-pointer-commands.ts index c6cff4c0244..1650b6f8baa 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-pointer-commands.ts +++ b/src/main/browser/agent-browser/commands/agent-browser-bridge-pointer-commands.ts @@ -1,6 +1,6 @@ -import type { ResolvedBrowserCommandTarget } from './agent-browser-bridge-types' -import { BrowserError } from '../browser-error' -import { normalizeCdpPointerButton } from '../cdp/input/cdp-pointer-targets' +import type { ResolvedBrowserCommandTarget } from '../session-routing/agent-browser-command-target' +import { BrowserError } from '../../browser-error' +import { normalizeCdpPointerButton } from '../../cdp/input/cdp-pointer-targets' import { assertFinitePointerValues, cdpPointerStateFor, @@ -8,14 +8,14 @@ import { releaseCdpPointerButton, resolveCdpPointerReleaseButton, type CdpPointerState -} from '../cdp/input/cdp-pointer-input' -import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease' -import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page-url' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' +} from '../../cdp/input/cdp-pointer-input' +import { acquireElectronDebugger } from '../../cdp/debugger/electron-debugger-lease' +import { assertExpectedPageUrlForStep } from '../../cdp/input/browser-expected-page-url' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' import { AgentBrowserBridgeInputCommands } from './agent-browser-bridge-input-commands' -import { isEmbeddedGuest } from '../cdp/input/guest-direct-key-input' -import { enablePageFocusEmulation } from '../cdp/input/agent-input-focus-guard' -import { waitForGuestFirstPaint } from '../cdp/debugger/guest-first-paint' +import { isEmbeddedGuest } from '../../cdp/input/guest-direct-key-input' +import { enablePageFocusEmulation } from '../../cdp/input/agent-input-focus-guard' +import { waitForGuestFirstPaint } from '../../cdp/debugger/guest-first-paint' type CdpPointerEventParams = { type: 'mouseMoved' | 'mousePressed' | 'mouseReleased' | 'mouseWheel' diff --git a/src/main/browser/agent-browser/commands/agent-browser-navigation-settle.ts b/src/main/browser/agent-browser/commands/agent-browser-navigation-settle.ts new file mode 100644 index 00000000000..d1b12ee41e9 --- /dev/null +++ b/src/main/browser/agent-browser/commands/agent-browser-navigation-settle.ts @@ -0,0 +1,81 @@ +import type { WebContents } from 'electron' +import { BrowserError } from '../../browser-error' + +export function isAbortedNavigationError(error: unknown): boolean { + if (!error || typeof error !== 'object') { + return false + } + const { code, errno } = error as { code?: unknown; errno?: unknown } + return code === 'ERR_ABORTED' || errno === -3 +} + +export function isWebContentsLoading(wc: WebContents): boolean { + try { + return wc.isLoading() + } catch { + // The caller rechecks authoritative page registration after waiting. + return false + } +} + +export function isLoadingMainFrame(wc: WebContents): boolean { + try { + return wc.isLoadingMainFrame() + } catch { + return false + } +} + +export function waitForAbortedNavigationReplacement( + wc: WebContents, + browserPageId: string, + timeoutMs: number +): Promise { + if (!isWebContentsLoading(wc)) { + return Promise.resolve() + } + + return new Promise((resolve, reject) => { + let settled = false + let timeout: ReturnType | null = null + const finish = (error?: BrowserError): void => { + if (settled) { + return + } + settled = true + wc.removeListener('did-stop-loading', onDidStopLoading) + wc.removeListener('destroyed', onDestroyed) + if (timeout) { + clearTimeout(timeout) + } + if (error) { + reject(error) + } else { + resolve() + } + } + const onDidStopLoading = (): void => finish() + const onDestroyed = (): void => finish() + + wc.on('did-stop-loading', onDidStopLoading) + wc.on('destroyed', onDestroyed) + timeout = setTimeout( + () => + finish( + new BrowserError( + 'browser_error', + `Failed to navigate browser page ${browserPageId}: Browser navigation timed out after ${EMBEDDED_NAVIGATION_TIMEOUT_MS}ms` + ) + ), + timeoutMs + ) + timeout.unref?.() + + // Loading may finish between loadURL rejection and listener attachment. + if (!isWebContentsLoading(wc)) { + finish() + } + }) +} + +export const EMBEDDED_NAVIGATION_TIMEOUT_MS = 30_000 diff --git a/src/main/browser/agent-browser/helper-process/agent-browser-binary.ts b/src/main/browser/agent-browser/helper-process/agent-browser-binary.ts new file mode 100644 index 00000000000..94cbbff7f1e --- /dev/null +++ b/src/main/browser/agent-browser/helper-process/agent-browser-binary.ts @@ -0,0 +1,38 @@ +import { platform, arch } from 'node:os' +import { app } from 'electron' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { ensureDependencyBinaryExecutable } from './agent-browser-dependency-binary' + +export function agentBrowserNativeName(): string { + const ext = process.platform === 'win32' ? '.exe' : '' + return `agent-browser-${platform()}-${arch()}${ext}` +} + +export function resolveAgentBrowserBinary(): string { + // resourcesPath preserves the case-sensitive macOS Resources path. + const bundledResourcesPath = + process.resourcesPath ?? + (process.platform === 'darwin' + ? join(app.getPath('exe'), '..', '..', 'Resources') + : join(app.getPath('exe'), '..', 'resources')) + const bundled = join(bundledResourcesPath, agentBrowserNativeName()) + if (existsSync(bundled)) { + return bundled + } + + // Bundling makes __dirname unreliable for locating development dependencies. + const nmBin = join( + app.getAppPath(), + 'node_modules', + 'agent-browser', + 'bin', + agentBrowserNativeName() + ) + if (existsSync(nmBin)) { + ensureDependencyBinaryExecutable(nmBin) + return nmBin + } + + return 'agent-browser' +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-cdp-endpoint.test.ts b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-cdp-endpoint.test.ts similarity index 90% rename from src/main/browser/agent-browser/agent-browser-bridge-cdp-endpoint.test.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-bridge-cdp-endpoint.test.ts index 04c32a7cfeb..7c08b8cf623 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-cdp-endpoint.test.ts +++ b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-cdp-endpoint.test.ts @@ -1,4 +1,4 @@ -import type * as BrowserErrorTypes from '../browser-error' +import type * as BrowserErrorTypes from '../../browser-error' import { describe, it, expect, vi, beforeEach } from 'vitest' const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = @@ -44,10 +44,10 @@ const { CdpWsProxyMock, proxyStops } = vi.hoisted(() => { return { CdpWsProxyMock: Object.assign(MockClass, { instances }), proxyStops } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -vi.mock('../browser-error', () => ({ +vi.mock('../../browser-error', () => ({ BrowserError: class BrowserError extends Error { code: string constructor(code: string, message: string) { @@ -57,18 +57,18 @@ vi.mock('../browser-error', () => ({ } })) -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') +vi.mock('../../cdp/commands/cdp-bridge', async () => { + const { BrowserError } = await vi.importMock('../../browser-error') return { BrowserError } }) -import { AgentBrowserBridge } from './agent-browser-bridge' +import { AgentBrowserBridge } from '../agent-browser-bridge' import { mockBrowserManager, overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks, succeedRecordingAgentBrowserSpawns -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-execution.ts b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-execution.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-execution.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-bridge-execution.ts index 6de99f1fc7e..05c7acd9090 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-execution.ts +++ b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-execution.ts @@ -1,30 +1,29 @@ import { execFile } from 'node:child_process' import type { WebContents } from 'electron' -import { BrowserError } from '../browser-error' +import { BrowserError } from '../../browser-error' import { isCdpProxyRejectedError, isTabClosedTransportError, pageUnavailableMessageForSession -} from './agent-browser-bridge-process' -import { translateResult } from './agent-browser-bridge-result' +} from './agent-browser-command-errors' +import { translateResult } from '../protocol/agent-browser-bridge-result' import { AGENT_BROWSER_BATCH_ARGS, agentBrowserBatchInput, agentBrowserResultMintsRefs -} from './agent-browser-batch-command' -import { AgentBrowserBridgeTabs } from './agent-browser-bridge-tabs' -import { assertRemoteCliBrowserAccess } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' -import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page-url' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import { canSkipAgentBrowserSessionReset } from './agent-browser-session-reset' +} from '../protocol/agent-browser-batch-command' +import { AgentBrowserBridgeTabs } from '../session-routing/agent-browser-bridge-tabs' +import { assertRemoteCliBrowserAccess } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { assertExpectedPageUrlForStep } from '../../cdp/input/browser-expected-page-url' +import { ORCA_TAB_SESSION_PREFIX } from '../session-lifecycle/agent-browser-session-name' +import { canSkipAgentBrowserSessionReset } from '../session-lifecycle/agent-browser-session-reset' import { AGENT_BROWSER_CLEANUP_TIMEOUT_MS, - STALE_SESSION_CLOSE_TIMEOUT_MS, - type AgentBrowserCleanupOptions, - type AgentBrowserExecOptions, - type SessionState, - type ResolvedBrowserCommandTarget -} from './agent-browser-bridge-types' + type AgentBrowserCleanupOptions +} from '../session-lifecycle/agent-browser-cleanup-options' +import type { AgentBrowserExecOptions } from './agent-browser-exec-options' +import type { SessionState } from '../session-lifecycle/agent-browser-session-state' +import type { ResolvedBrowserCommandTarget } from '../session-routing/agent-browser-command-target' // These act on an element with no pointer input, so the agent cursor is shown on it first. const ELEMENT_COMMANDS_WITHOUT_POINTER = new Set(['check', 'uncheck', 'select', 'focus']) @@ -291,3 +290,5 @@ export abstract class AgentBrowserBridgeExecution extends AgentBrowserBridgeTabs return !this.getWebContents(targetWebContentsId) } } + +export const STALE_SESSION_CLOSE_TIMEOUT_MS = 3_000 diff --git a/src/main/browser/agent-browser/agent-browser-bridge-raw-process-retention.test.ts b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process-retention.test.ts similarity index 93% rename from src/main/browser/agent-browser/agent-browser-bridge-raw-process-retention.test.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process-retention.test.ts index 3bd2c98bcb0..453c60719e5 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-raw-process-retention.test.ts +++ b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process-retention.test.ts @@ -19,8 +19,8 @@ vi.mock('node:child_process', async (importOriginal) => { return { ...actual, execFile: vi.fn(actual.execFile) } }) -import { AgentBrowserBridge } from './agent-browser-bridge' -import { mockBrowserManager } from './agent-browser-bridge-test-harness' +import { AgentBrowserBridge } from '../agent-browser-bridge' +import { mockBrowserManager } from '../testing/agent-browser-bridge-test-harness' let bridge: AgentBrowserBridge diff --git a/src/main/browser/agent-browser/agent-browser-bridge-raw-process.test.ts b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.test.ts similarity index 92% rename from src/main/browser/agent-browser/agent-browser-bridge-raw-process.test.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.test.ts index 1a205e326ca..1b278c79f6b 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-raw-process.test.ts +++ b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.test.ts @@ -13,8 +13,8 @@ vi.mock('electron', () => ({ } })) -import { AgentBrowserBridge } from './agent-browser-bridge' -import { mockBrowserManager } from './agent-browser-bridge-test-harness' +import { AgentBrowserBridge } from '../agent-browser-bridge' +import { mockBrowserManager } from '../testing/agent-browser-bridge-test-harness' const PAYLOAD_BYTES = 5 * 1024 * 1024 diff --git a/src/main/browser/agent-browser/agent-browser-bridge-raw-process.ts b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.ts similarity index 87% rename from src/main/browser/agent-browser/agent-browser-bridge-raw-process.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.ts index 9b3ecb58ffa..91ad22638d2 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-raw-process.ts +++ b/src/main/browser/agent-browser/helper-process/agent-browser-bridge-raw-process.ts @@ -1,14 +1,9 @@ import { execFile, type ChildProcess } from 'node:child_process' -import { BrowserError } from '../browser-error' -import { classifyErrorCode } from './agent-browser-bridge-process' -import { parseAgentBrowserJsonOutput } from './agent-browser-batch-command' -import { AgentBrowserBridgeElementCalls } from './agent-browser-bridge-element-calls' -import { - AGENT_BROWSER_EXIT_DRAIN_MS, - CONSECUTIVE_TIMEOUT_LIMIT, - EXEC_TIMEOUT_MS, - type AgentBrowserExecOptions -} from './agent-browser-bridge-types' +import { BrowserError } from '../../browser-error' +import { classifyErrorCode } from './agent-browser-command-errors' +import { parseAgentBrowserJsonOutput } from '../protocol/agent-browser-batch-command' +import { AgentBrowserBridgeElementCalls } from '../commands/agent-browser-bridge-element-calls' +import type { AgentBrowserExecOptions } from './agent-browser-exec-options' export abstract class AgentBrowserBridgeRawProcess extends AgentBrowserBridgeElementCalls { protected abstract destroySession( @@ -118,3 +113,10 @@ export abstract class AgentBrowserBridgeRawProcess extends AgentBrowserBridgeEle }) } } + +// Exceed agent-browser's internal navigation (30s) and default wait (25s) timeouts. +export const EXEC_TIMEOUT_MS = 90_000 + +export const CONSECUTIVE_TIMEOUT_LIMIT = 3 + +export const AGENT_BROWSER_EXIT_DRAIN_MS = 500 diff --git a/src/main/browser/agent-browser/helper-process/agent-browser-command-errors.ts b/src/main/browser/agent-browser/helper-process/agent-browser-command-errors.ts new file mode 100644 index 00000000000..953336933fd --- /dev/null +++ b/src/main/browser/agent-browser/helper-process/agent-browser-command-errors.ts @@ -0,0 +1,29 @@ +import { isAgentBrowserStaleRefError } from '../protocol/agent-browser-batch-command' +import { ORCA_TAB_SESSION_PREFIX } from '../session-lifecycle/agent-browser-session-name' + +// Stale refs need a distinct code so agents can retry with a fresh snapshot. +export function classifyErrorCode(message: string): string { + if (isAgentBrowserStaleRefError(message)) { + return 'browser_stale_ref' + } + return 'browser_error' +} + +export function isTabClosedTransportError(message: string): boolean { + return /session destroyed while command|session destroyed while commands|connection refused|cdp discovery methods failed|websocket connect failed/i.test( + message + ) +} + +/** agent-browser's handshake error when Orca's CDP proxy refuses its endpoint (wrong or missing token). */ +export function isCdpProxyRejectedError(message: string): boolean { + return /websocket connect failed\b.*\b40[34]\b/i.test(message) +} + +export function pageUnavailableMessageForSession(sessionName: string): string { + const prefix = ORCA_TAB_SESSION_PREFIX + const browserPageId = sessionName.startsWith(prefix) ? sessionName.slice(prefix.length) : null + return browserPageId + ? `Browser page ${browserPageId} is no longer available` + : 'Browser tab is no longer available' +} diff --git a/src/main/browser/agent-browser/agent-browser-dependency-binary.ts b/src/main/browser/agent-browser/helper-process/agent-browser-dependency-binary.ts similarity index 100% rename from src/main/browser/agent-browser/agent-browser-dependency-binary.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-dependency-binary.ts diff --git a/src/main/browser/agent-browser/helper-process/agent-browser-exec-options.ts b/src/main/browser/agent-browser/helper-process/agent-browser-exec-options.ts new file mode 100644 index 00000000000..146ef049f51 --- /dev/null +++ b/src/main/browser/agent-browser/helper-process/agent-browser-exec-options.ts @@ -0,0 +1,11 @@ +import type { BrowserError } from '../../browser-error' + +export type AgentBrowserExecOptions = { + envOverrides?: NodeJS.ProcessEnv + timeoutMs?: number + timeoutError?: BrowserError + /** The caller owns stdin, so the command goes as argv; only for Orca-authored tokens. */ + stdinText?: string + /** Send tokens as argv so global options apply; only for Orca-authored or raw CLI tokens. */ + cliArgv?: boolean +} diff --git a/src/main/browser/agent-browser/agent-browser-process-environment.ts b/src/main/browser/agent-browser/helper-process/agent-browser-process-environment.ts similarity index 100% rename from src/main/browser/agent-browser/agent-browser-process-environment.ts rename to src/main/browser/agent-browser/helper-process/agent-browser-process-environment.ts diff --git a/src/main/browser/agent-browser/agent-browser-action-effects.test.ts b/src/main/browser/agent-browser/observation/agent-browser-action-effects.test.ts similarity index 95% rename from src/main/browser/agent-browser/agent-browser-action-effects.test.ts rename to src/main/browser/agent-browser/observation/agent-browser-action-effects.test.ts index 8f0e7cb3037..2a0c3ca96ee 100644 --- a/src/main/browser/agent-browser/agent-browser-action-effects.test.ts +++ b/src/main/browser/agent-browser/observation/agent-browser-action-effects.test.ts @@ -2,10 +2,10 @@ import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' import type { WebContents } from 'electron' import { runWithActionEffects, type ActionEffectsHost } from './agent-browser-action-effects' -import type { BrowserPageEvent } from '../guest-lifecycle/browser-page-events' -import { readBrowserActionEffects } from '../../../shared/browser-action-effects' +import type { BrowserPageEvent } from '../../guest-lifecycle/page-activity/browser-page-events' +import { readBrowserActionEffects } from '../../../../shared/browser-action-effects' -vi.mock('../routing/input-ownership/remote-cli-page-admission', () => ({ +vi.mock('../../routing/input-ownership/remote-cli-page-admission', () => ({ readRemoteCliAdmittedPage: (_id: number, read: () => Promise) => read() })) diff --git a/src/main/browser/agent-browser/agent-browser-action-effects.ts b/src/main/browser/agent-browser/observation/agent-browser-action-effects.ts similarity index 95% rename from src/main/browser/agent-browser/agent-browser-action-effects.ts rename to src/main/browser/agent-browser/observation/agent-browser-action-effects.ts index 5f4d43ac6df..2020b252744 100644 --- a/src/main/browser/agent-browser/agent-browser-action-effects.ts +++ b/src/main/browser/agent-browser/observation/agent-browser-action-effects.ts @@ -1,12 +1,12 @@ import { setTimeout as delay } from 'node:timers/promises' import type { WebContents } from 'electron' -import type { BrowserActionEffects } from '../../../shared/runtime-browser-contracts' -import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' -import { withTimeout } from '../../../shared/promise-timeout-fallback' -import type { BrowserPageEvent } from '../guest-lifecycle/browser-page-events' -import { readRemoteCliAdmittedPage } from '../routing/input-ownership/remote-cli-page-admission' +import type { BrowserActionEffects } from '../../../../shared/runtime-browser-contracts' +import { isRecord } from '../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import { withTimeout } from '../../../../shared/promise-timeout-fallback' +import type { BrowserPageEvent } from '../../guest-lifecycle/page-activity/browser-page-events' +import { readRemoteCliAdmittedPage } from '../../routing/input-ownership/remote-cli-page-admission' import { readPageChange } from './agent-browser-snapshot-delta' -import { isLoadingMainFrame } from './agent-browser-bridge-process' +import { isLoadingMainFrame } from '../commands/agent-browser-navigation-settle' // Settle like ChatGPT's browser: wait for a started navigation, then for a short DOM-quiet window. const NAVIGATION_START_GRACE_MS = 50 diff --git a/src/main/browser/agent-browser/agent-browser-log-entries.ts b/src/main/browser/agent-browser/observation/agent-browser-log-entries.ts similarity index 96% rename from src/main/browser/agent-browser/agent-browser-log-entries.ts rename to src/main/browser/agent-browser/observation/agent-browser-log-entries.ts index 034dd05ec9f..0a24db068a2 100644 --- a/src/main/browser/agent-browser/agent-browser-log-entries.ts +++ b/src/main/browser/agent-browser/observation/agent-browser-log-entries.ts @@ -3,7 +3,7 @@ import type { BrowserConsoleResult, BrowserNetworkEntry, BrowserNetworkLogResult -} from '../../../shared/runtime-browser-contracts' +} from '../../../../shared/runtime-browser-contracts' // Shapes agent-browser prints for `console --json` and `network requests --json` (0.27 and 0.41). export type AgentBrowserConsoleOutput = { messages: { type: string; text: string }[] } diff --git a/src/main/browser/agent-browser/agent-browser-screenshot-arguments.ts b/src/main/browser/agent-browser/observation/agent-browser-screenshot-arguments.ts similarity index 91% rename from src/main/browser/agent-browser/agent-browser-screenshot-arguments.ts rename to src/main/browser/agent-browser/observation/agent-browser-screenshot-arguments.ts index 3c8909da7ca..0bbd07647bf 100644 --- a/src/main/browser/agent-browser/agent-browser-screenshot-arguments.ts +++ b/src/main/browser/agent-browser/observation/agent-browser-screenshot-arguments.ts @@ -1,4 +1,4 @@ -import type { BrowserScreenshotOptions } from '../../../shared/rpc-contract/browser-observation-params' +import type { BrowserScreenshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' import { randomUUID } from 'node:crypto' import { readFile, rm } from 'node:fs/promises' import { join } from 'node:path' @@ -6,8 +6,8 @@ import { z } from 'zod' import type { BrowserScreenshotAnnotation, BrowserScreenshotResult -} from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' +} from '../../../../shared/runtime-browser-contracts' +import { BrowserError } from '../../browser-error' const Annotation: z.ZodType = z.object({ ref: z.string(), diff --git a/src/main/browser/agent-browser/agent-browser-snapshot-delta.ts b/src/main/browser/agent-browser/observation/agent-browser-snapshot-delta.ts similarity index 90% rename from src/main/browser/agent-browser/agent-browser-snapshot-delta.ts rename to src/main/browser/agent-browser/observation/agent-browser-snapshot-delta.ts index ff53c4329f1..2d9560d6361 100644 --- a/src/main/browser/agent-browser/agent-browser-snapshot-delta.ts +++ b/src/main/browser/agent-browser/observation/agent-browser-snapshot-delta.ts @@ -1,5 +1,5 @@ -import type { BrowserActionEffects } from '../../../shared/runtime-browser-contracts' -import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import type { BrowserActionEffects } from '../../../../shared/runtime-browser-contracts' +import { isRecord } from '../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' // Results travel to remote clients with a 768 KB budget; agents read them in their context. const PAGE_CHARS = 6_000 diff --git a/src/main/browser/agent-browser/agent-browser-batch-command.ts b/src/main/browser/agent-browser/protocol/agent-browser-batch-command.ts similarity index 100% rename from src/main/browser/agent-browser/agent-browser-batch-command.ts rename to src/main/browser/agent-browser/protocol/agent-browser-batch-command.ts diff --git a/src/main/browser/agent-browser/agent-browser-bridge-result.ts b/src/main/browser/agent-browser/protocol/agent-browser-bridge-result.ts similarity index 90% rename from src/main/browser/agent-browser/agent-browser-bridge-result.ts rename to src/main/browser/agent-browser/protocol/agent-browser-bridge-result.ts index 00724c37478..34634263bdc 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-result.ts +++ b/src/main/browser/agent-browser/protocol/agent-browser-bridge-result.ts @@ -1,4 +1,4 @@ -import { classifyErrorCode } from './agent-browser-bridge-process' +import { classifyErrorCode } from '../helper-process/agent-browser-command-errors' import { parseAgentBrowserJsonOutput, type AgentBrowserEnvelope diff --git a/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts new file mode 100644 index 00000000000..1ba5a18c9cc --- /dev/null +++ b/src/main/browser/agent-browser/protocol/agent-browser-passthrough-arguments.ts @@ -0,0 +1,42 @@ +export function parseShellArgs(input: string): string[] { + const args: string[] = [] + let current = '' + let inDouble = false + let inSingle = false + + for (let i = 0; i < input.length; i++) { + const ch = input[i] + if (ch === '"' && !inSingle) { + inDouble = !inDouble + } else if (ch === "'" && !inDouble) { + inSingle = !inSingle + } else if (ch === ' ' && !inDouble && !inSingle) { + if (current) { + args.push(current) + current = '' + } + } else { + current += ch + } + } + if (current) { + args.push(current) + } + return args +} + +export function stripAgentBrowserTargetArgs(args: string[]): string[] { + const stripped: string[] = [] + for (let index = 0; index < args.length; index++) { + const arg = args[index] + if (arg === '--cdp' || arg === '--session') { + index++ + continue + } + if (arg.startsWith('--cdp=') || arg.startsWith('--session=')) { + continue + } + stripped.push(arg) + } + return stripped +} diff --git a/src/main/browser/agent-browser/agent-browser-set-media-arguments.ts b/src/main/browser/agent-browser/protocol/agent-browser-set-media-arguments.ts similarity index 94% rename from src/main/browser/agent-browser/agent-browser-set-media-arguments.ts rename to src/main/browser/agent-browser/protocol/agent-browser-set-media-arguments.ts index acadc4460fa..a5c2211fe86 100644 --- a/src/main/browser/agent-browser/agent-browser-set-media-arguments.ts +++ b/src/main/browser/agent-browser/protocol/agent-browser-set-media-arguments.ts @@ -1,4 +1,4 @@ -import { BrowserError } from '../browser-error' +import { BrowserError } from '../../browser-error' // Why: agent-browser's `set media` matches the bare tokens dark/light/reduced-motion // anywhere in its args and silently ignores everything else, so map Orca's values here. diff --git a/src/main/browser/agent-browser/agent-browser-snapshot-arguments.ts b/src/main/browser/agent-browser/protocol/agent-browser-snapshot-arguments.ts similarity index 83% rename from src/main/browser/agent-browser/agent-browser-snapshot-arguments.ts rename to src/main/browser/agent-browser/protocol/agent-browser-snapshot-arguments.ts index 8d04149eb8a..dc6e4a53773 100644 --- a/src/main/browser/agent-browser/agent-browser-snapshot-arguments.ts +++ b/src/main/browser/agent-browser/protocol/agent-browser-snapshot-arguments.ts @@ -1,4 +1,4 @@ -import type { BrowserSnapshotOptions } from '../../../shared/rpc-contract/browser-observation-params' +import type { BrowserSnapshotOptions } from '../../../../shared/rpc-contract/browser-observation-params' export function agentBrowserSnapshotArgs(options: BrowserSnapshotOptions): string[] { const args = ['snapshot'] diff --git a/src/main/browser/agent-browser/protocol/agent-browser-text-argument-budget.ts b/src/main/browser/agent-browser/protocol/agent-browser-text-argument-budget.ts new file mode 100644 index 00000000000..63be91cecf7 --- /dev/null +++ b/src/main/browser/agent-browser/protocol/agent-browser-text-argument-budget.ts @@ -0,0 +1,3 @@ +export const AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES = 8 * 1024 + +export const AGENT_BROWSER_CLIPBOARD_WRITE_MAX_BYTES = AGENT_BROWSER_TEXT_ARGUMENT_MAX_BYTES diff --git a/src/main/browser/agent-browser/agent-browser-wait-arguments.ts b/src/main/browser/agent-browser/protocol/agent-browser-wait-arguments.ts similarity index 93% rename from src/main/browser/agent-browser/agent-browser-wait-arguments.ts rename to src/main/browser/agent-browser/protocol/agent-browser-wait-arguments.ts index 98b8982ab9b..c918bdc605b 100644 --- a/src/main/browser/agent-browser/agent-browser-wait-arguments.ts +++ b/src/main/browser/agent-browser/protocol/agent-browser-wait-arguments.ts @@ -1,4 +1,4 @@ -import { BROWSER_WAIT_DEFAULT_TIMEOUT_MS } from '../../../shared/browser-wait-timeout' +import { BROWSER_WAIT_DEFAULT_TIMEOUT_MS } from '../../../../shared/browser-wait-timeout' // Lets agent-browser report its own wait timeout before Orca kills the process. const WAIT_PROCESS_TIMEOUT_GRACE_MS = 5_000 diff --git a/src/main/browser/agent-browser/agent-browser-bridge-lifecycle.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-lifecycle.ts similarity index 95% rename from src/main/browser/agent-browser/agent-browser-bridge-lifecycle.ts rename to src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-lifecycle.ts index f8c442f9349..d5ba93933c4 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-lifecycle.ts +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-lifecycle.ts @@ -1,11 +1,11 @@ -import { CdpWsProxy } from '../cdp/transport/cdp-ws-proxy' -import { BrowserError } from '../browser-error' -import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep' -import { AgentBrowserBridgeRawProcess } from './agent-browser-bridge-raw-process' -import type { AgentBrowserCleanupOptions } from './agent-browser-bridge-types' -import { AGENT_BROWSER_CLEANUP_TIMEOUT_MS } from './agent-browser-bridge-types' +import { CdpWsProxy } from '../../cdp/transport/cdp-ws-proxy' +import { BrowserError } from '../../browser-error' +import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-session-name' +import { AgentBrowserBridgeRawProcess } from '../helper-process/agent-browser-bridge-raw-process' +import type { AgentBrowserCleanupOptions } from './agent-browser-cleanup-options' +import { AGENT_BROWSER_CLEANUP_TIMEOUT_MS } from './agent-browser-cleanup-options' import { waitForAgentBrowserSessionExit } from './agent-browser-session-reset' -import { runOutsideRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { runOutsideRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' export abstract class AgentBrowserBridgeLifecycle extends AgentBrowserBridgeRawProcess { async onTabClosed(webContentsId: number): Promise { diff --git a/src/main/browser/agent-browser/agent-browser-bridge-shutdown.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-shutdown.ts similarity index 84% rename from src/main/browser/agent-browser/agent-browser-bridge-shutdown.ts rename to src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-shutdown.ts index ffa3deec697..71cea05b84b 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-shutdown.ts +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-bridge-shutdown.ts @@ -1,10 +1,7 @@ -import { mapSettledWithConcurrency } from '../../../shared/map-with-concurrency' +import { mapSettledWithConcurrency } from '../../../../shared/map-with-concurrency' import { sweepOrphanedAgentBrowserSessions } from './agent-browser-orphan-sweep' import { AgentBrowserBridgeLifecycle } from './agent-browser-bridge-lifecycle' -import { - AGENT_BROWSER_CLEANUP_CONCURRENCY, - type AgentBrowserCleanupOptions -} from './agent-browser-bridge-types' +import type { AgentBrowserCleanupOptions } from './agent-browser-cleanup-options' export abstract class AgentBrowserBridgeShutdown extends AgentBrowserBridgeLifecycle { async sweepOrphanedSessions(): Promise { @@ -33,3 +30,5 @@ export abstract class AgentBrowserBridgeShutdown extends AgentBrowserBridgeLifec this.pendingInterceptRestore.clear() } } + +export const AGENT_BROWSER_CLEANUP_CONCURRENCY = 4 diff --git a/src/main/browser/agent-browser/session-lifecycle/agent-browser-cleanup-options.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-cleanup-options.ts new file mode 100644 index 00000000000..474a886ac24 --- /dev/null +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-cleanup-options.ts @@ -0,0 +1,8 @@ +// Cleanup must finish within the 20s quit barrier. +export const AGENT_BROWSER_CLEANUP_TIMEOUT_MS = 5_000 + +export type AgentBrowserCleanupOptions = { + closeTimeoutMs?: number + /** Preserve queued commands for the replacement session. */ + keepQueuedCommands?: boolean +} diff --git a/src/main/browser/agent-browser/agent-browser-orphan-sweep.test.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.test.ts similarity index 100% rename from src/main/browser/agent-browser/agent-browser-orphan-sweep.test.ts rename to src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.test.ts diff --git a/src/main/browser/agent-browser/agent-browser-orphan-sweep.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.ts similarity index 96% rename from src/main/browser/agent-browser/agent-browser-orphan-sweep.ts rename to src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.ts index f1e0b0363a8..afc84d33566 100644 --- a/src/main/browser/agent-browser/agent-browser-orphan-sweep.ts +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-orphan-sweep.ts @@ -1,6 +1,5 @@ import { runProcess } from '@orca/process-host' - -export const ORCA_TAB_SESSION_PREFIX = 'orca-tab-' +import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-session-name' const SWEEP_TIMEOUT_MS = 5_000 const SWEEP_MAX_OUTPUT_BYTES = 256 * 1024 diff --git a/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-name.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-name.ts new file mode 100644 index 00000000000..4fa59e112fa --- /dev/null +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-name.ts @@ -0,0 +1 @@ +export const ORCA_TAB_SESSION_PREFIX = 'orca-tab-' diff --git a/src/main/browser/agent-browser/agent-browser-session-reset.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-reset.ts similarity index 100% rename from src/main/browser/agent-browser/agent-browser-session-reset.ts rename to src/main/browser/agent-browser/session-lifecycle/agent-browser-session-reset.ts diff --git a/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-state.ts b/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-state.ts new file mode 100644 index 00000000000..5432accceeb --- /dev/null +++ b/src/main/browser/agent-browser/session-lifecycle/agent-browser-session-state.ts @@ -0,0 +1,19 @@ +import type { ChildProcess } from 'node:child_process' +import type { CdpWsProxy } from '../../cdp/transport/cdp-ws-proxy' + +export type SessionState = { + proxy: CdpWsProxy + cdpEndpoint: string + initialized: boolean + consecutiveTimeouts: number + // Restore these routes after a session restart. + activeInterceptPatterns: string[] + activeCapture: boolean + // Detect idle daemon retirement from the gap between commands. + lastCommandAt: number + // Revalidate after queue delay, when the tab may have disappeared. + webContentsId: number + activeProcess: ChildProcess | null + // agent-browser keeps the `snapshot --delta` baseline in this session's daemon. + hasDeltaBaseline?: boolean +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-state.ts b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-state.ts similarity index 89% rename from src/main/browser/agent-browser/agent-browser-bridge-state.ts rename to src/main/browser/agent-browser/session-routing/agent-browser-bridge-state.ts index 59fc8f539a7..2f943be6a62 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-state.ts +++ b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-state.ts @@ -1,15 +1,12 @@ import { app } from 'electron' import type { ChildProcess } from 'node:child_process' -import { BrowserError } from '../browser-error' -import type { BrowserManager } from '../browser-manager' -import type { BrowserPopupPage } from '../guest-lifecycle/manager/browser-manager-types' -import { createAgentBrowserProcessEnvironment } from './agent-browser-process-environment' -import { resolveAgentBrowserBinary } from './agent-browser-bridge-process' -import type { - AgentBrowserBridgeOptions, - QueuedCommand, - SessionState -} from './agent-browser-bridge-types' +import { BrowserError } from '../../browser-error' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' +import type { BrowserPopupPage } from '../../guest-lifecycle/popups/browser-popup-ownership' +import { createAgentBrowserProcessEnvironment } from '../helper-process/agent-browser-process-environment' +import { resolveAgentBrowserBinary } from '../helper-process/agent-browser-binary' +import type { QueuedCommand } from '../command-queue/agent-browser-queued-command' +import type { SessionState } from '../session-lifecycle/agent-browser-session-state' export abstract class AgentBrowserBridgeState { // Isolate each worktree's tab selection. @@ -152,3 +149,7 @@ export abstract class AgentBrowserBridgeState { function isSnapshotRef(element: string): boolean { return /^(?:@|ref=)?e\d+$/.test(element) } + +export type AgentBrowserBridgeOptions = { + onTabsChanged?: (worktreeId?: string) => void +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-tab-routing.test.ts b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts similarity index 91% rename from src/main/browser/agent-browser/agent-browser-bridge-tab-routing.test.ts rename to src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts index e82a65239c0..ce28eaa77df 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-tab-routing.test.ts +++ b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tab-routing.test.ts @@ -1,4 +1,4 @@ -import type * as BrowserErrorTypes from '../browser-error' +import type * as BrowserErrorTypes from '../../browser-error' import { describe, it, expect, vi, beforeEach } from 'vitest' const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } = @@ -40,10 +40,10 @@ const { CdpWsProxyMock } = vi.hoisted(() => { return { CdpWsProxyMock: Object.assign(MockClass, { instances }) } }) -vi.mock('../cdp/transport/cdp-ws-proxy', () => ({ +vi.mock('../../cdp/transport/cdp-ws-proxy', () => ({ CdpWsProxy: CdpWsProxyMock })) -vi.mock('../browser-error', () => ({ +vi.mock('../../browser-error', () => ({ BrowserError: class BrowserError extends Error { code: string constructor(code: string, message: string) { @@ -53,19 +53,19 @@ vi.mock('../browser-error', () => ({ } })) -vi.mock('../cdp/commands/cdp-bridge', async () => { - const { BrowserError } = await vi.importMock('../browser-error') +vi.mock('../../cdp/commands/cdp-bridge', async () => { + const { BrowserError } = await vi.importMock('../../browser-error') return { BrowserError } }) -import { AgentBrowserBridge } from './agent-browser-bridge' +import { AgentBrowserBridge } from '../agent-browser-bridge' import { answerAgentBrowserCommands, mockBrowserManager, mockWebContents, overrideBridgeWebContentsLookup, resetAgentBrowserBridgeMocks -} from './agent-browser-bridge-test-harness' +} from '../testing/agent-browser-bridge-test-harness' overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock) diff --git a/src/main/browser/agent-browser/agent-browser-bridge-tabs.ts b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tabs.ts similarity index 96% rename from src/main/browser/agent-browser/agent-browser-bridge-tabs.ts rename to src/main/browser/agent-browser/session-routing/agent-browser-bridge-tabs.ts index ee164547f1d..8221270d93b 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-tabs.ts +++ b/src/main/browser/agent-browser/session-routing/agent-browser-bridge-tabs.ts @@ -1,12 +1,12 @@ import type { BrowserTabInfo, BrowserTabListResult -} from '../../../shared/runtime-browser-contracts' -import { BrowserError } from '../browser-error' -import type { ResolvedBrowserCommandTarget } from './agent-browser-bridge-types' +} from '../../../../shared/runtime-browser-contracts' +import { BrowserError } from '../../browser-error' +import type { ResolvedBrowserCommandTarget } from './agent-browser-command-target' import { AgentBrowserBridgeState } from './agent-browser-bridge-state' -import { isAgentRpcCaller } from '../../runtime/rpc/rpc-caller-identity' -import { getActiveRpcCaller } from '../../runtime/rpc/rpc-active-caller' +import { isAgentRpcCaller } from '../../../runtime/rpc/rpc-caller-identity' +import { getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' export abstract class AgentBrowserBridgeTabs extends AgentBrowserBridgeState { setActiveTab(webContentsId: number, worktreeId?: string): void { @@ -119,6 +119,9 @@ export abstract class AgentBrowserBridgeTabs extends AgentBrowserBridgeState { return null } } + getRemoteTabFaviconUrl(browserPageId: string): string | null { + return this.browserManager.getBrowserPageRemoteTabFaviconUrl(browserPageId) + } onTabChanged(webContentsId: number, worktreeId?: string): void { this.selectForPerson(webContentsId, worktreeId) this.options.onTabsChanged?.(worktreeId) diff --git a/src/main/browser/agent-browser/session-routing/agent-browser-command-target.ts b/src/main/browser/agent-browser/session-routing/agent-browser-command-target.ts new file mode 100644 index 00000000000..c819b983482 --- /dev/null +++ b/src/main/browser/agent-browser/session-routing/agent-browser-command-target.ts @@ -0,0 +1,4 @@ +export type ResolvedBrowserCommandTarget = { + browserPageId: string + webContentsId: number +} diff --git a/src/main/browser/agent-browser/agent-browser-bridge-test-harness.ts b/src/main/browser/agent-browser/testing/agent-browser-bridge-test-harness.ts similarity index 97% rename from src/main/browser/agent-browser/agent-browser-bridge-test-harness.ts rename to src/main/browser/agent-browser/testing/agent-browser-bridge-test-harness.ts index 79a2463fe79..c6497e240bd 100644 --- a/src/main/browser/agent-browser/agent-browser-bridge-test-harness.ts +++ b/src/main/browser/agent-browser/testing/agent-browser-bridge-test-harness.ts @@ -1,7 +1,8 @@ import { EventEmitter } from 'node:events' -import { vi, type Mock } from 'vitest' -import type { AgentBrowserBridge } from './agent-browser-bridge' -import type { BrowserManager } from '../browser-manager' +import { vi } from 'vitest' +import type { Mock } from 'vitest' +import type { AgentBrowserBridge } from '../agent-browser-bridge' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' export type ExecFileCallback = (error: unknown, stdout?: string, stderr?: string) => void diff --git a/src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts b/src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts index 338302cac4e..b9abfcfcc93 100644 --- a/src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts +++ b/src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts @@ -67,7 +67,7 @@ class MockBrowserWindow { } vi.mock('electron', () => ({ BrowserWindow: mocks.BrowserWindow })) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getDefaultProfile: vi.fn(() => ({ id: 'default', partition: 'persist:orca-browser' })) } diff --git a/src/main/browser/backends/offscreen-browser-backend.ts b/src/main/browser/backends/offscreen-browser-backend.ts index 6c9a2b4ef2f..cc186c029a1 100644 --- a/src/main/browser/backends/offscreen-browser-backend.ts +++ b/src/main/browser/backends/offscreen-browser-backend.ts @@ -4,9 +4,9 @@ import { ORCA_BROWSER_PARTITION } from '../../../shared/constants' import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../../shared/browser-guest-web-preferences' import { mapSettledWithConcurrency } from '../../../shared/map-with-concurrency' import type { BrowserBackend, BrowserBackendCreateTab } from '../browser-backend' -import type { BrowserManager } from '../browser-manager' +import type { BrowserManager } from '../guest-lifecycle/manager/browser-manager' import type { AgentBrowserBridge } from '../agent-browser/agent-browser-bridge' -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' import { installBrowserJavaScriptDialogs } from '../guest-lifecycle/prompts/browser-javascript-dialogs' import type { ServeBrowserPageState } from '../../runtime/browser/headless/serve-browser-tab-layout' diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts deleted file mode 100644 index 29ce1b428f4..00000000000 --- a/src/main/browser/browser-manager.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { webContents } from 'electron' -import { BrowserCertificateTrustController } from './certificate-trust/browser-certificate-trust-controller' -import { BrowserManagerFinal } from './guest-lifecycle/manager/browser-manager-final' - -export class BrowserManager extends BrowserManagerFinal {} - -export const browserManager = new BrowserManager() -export const browserCertificateTrustController = new BrowserCertificateTrustController({ - resolveManagedGuestContext: (webContentsId) => - browserManager.getManagedBrowserGuestContext(webContentsId), - resolveWebContentsIdForPage: (browserPageId) => - browserManager.getGuestWebContentsId(browserPageId), - resolveWebContents: (webContentsId) => webContents.fromId(webContentsId) ?? null, - onFailureChanged: (webContentsId, failure, navigationUrl) => - browserManager.notifyCertificateFailureChanged(webContentsId, failure, navigationUrl) -}) -browserManager.setCertificateTrustController(browserCertificateTrustController) diff --git a/src/main/browser/cdp/commands/cdp-auxiliary-commands.ts b/src/main/browser/cdp/commands/cdp-auxiliary-commands.ts index 358a2909ba6..fd6a308fbb8 100644 --- a/src/main/browser/cdp/commands/cdp-auxiliary-commands.ts +++ b/src/main/browser/cdp/commands/cdp-auxiliary-commands.ts @@ -1,8 +1,8 @@ +import type { CdpTabState } from './cdp-tab-state' import type { WebContents } from 'electron' import type { BrowserCaptureStartResult, BrowserCaptureStopResult, - BrowserConsoleEntry, BrowserConsoleResult, BrowserCookie, BrowserCookieDeleteResult, @@ -12,27 +12,10 @@ import type { BrowserInterceptDisableResult, BrowserInterceptEnableResult, BrowserInterceptedRequest, - BrowserNetworkEntry, BrowserNetworkLogResult, BrowserViewportResult } from '../../../../shared/runtime-browser-contracts' -import type { CdpCommandSender, SnapshotResult } from '../snapshots/snapshot-engine' - -export type CdpTabState = { - navigationId: string | null - snapshotResult: SnapshotResult | null - debuggerAttached: boolean - debuggerDetachListener: (() => void) | null - debuggerMessageListener: ((_event: unknown, method: string, params: unknown) => void) | null - iframeSessions: Map - capturing: boolean - consoleLog: BrowserConsoleEntry[] - networkLog: BrowserNetworkEntry[] - intercepting: boolean - interceptPatterns: string[] - pausedRequests: Map - networkRequestMap: Map -} +import type { CdpCommandSender } from '../debugger/cdp-command-sender' type ActiveCdpContext = { guest: WebContents diff --git a/src/main/browser/cdp/commands/cdp-bridge-command-module.ts b/src/main/browser/cdp/commands/cdp-bridge-command-module.ts deleted file mode 100644 index 30ca2a53e7b..00000000000 --- a/src/main/browser/cdp/commands/cdp-bridge-command-module.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { WebContents } from 'electron' -import type { - BrowserScreenshotResult, - BrowserScrollResult -} from '../../../../shared/runtime-browser-contracts' -import type { CdpTabState } from './cdp-auxiliary-commands' -import type { CdpCommandSender, RefEntry } from '../snapshots/snapshot-engine' -import type { CdpBridgeState, CdpQueuedCommand } from './cdp-bridge-state' -import type { CdpDebuggerLifecycle } from './cdp-debugger-lifecycle' -import type { CdpNavigationOperations } from './cdp-navigation-operations' -import type { CdpRefResolution } from './cdp-ref-resolution' - -export type CdpScrollDirection = BrowserScrollResult extends { scrolled: infer Direction } - ? Direction - : never -export type CdpScreenshotFormat = BrowserScreenshotResult extends { format: infer Format } - ? Format - : never - -export abstract class CdpBridgeCommandModule { - constructor( - private readonly bridgeState: CdpBridgeState, - private readonly debuggerLifecycle: CdpDebuggerLifecycle, - private readonly refResolution: CdpRefResolution, - private readonly navigation: CdpNavigationOperations - ) {} - - protected get activeWebContentsId(): number | null { - return this.bridgeState.activeWebContentsId - } - - protected set activeWebContentsId(webContentsId: number | null) { - this.bridgeState.activeWebContentsId = webContentsId - } - - protected get tabState(): Map { - return this.bridgeState.tabState - } - - protected get commandQueues(): Map { - return this.bridgeState.commandQueues - } - - protected getActiveGuest(): WebContents { - return this.bridgeState.getActiveGuest() - } - - protected getRegisteredTabs(): Map { - return this.bridgeState.getRegisteredTabs() - } - - protected resolveTabId(webContentsId: number): string { - return this.bridgeState.resolveTabId(webContentsId) - } - - protected resolveTabIdSafe(webContentsId: number): string | null { - return this.bridgeState.resolveTabIdSafe(webContentsId) - } - - protected getOrCreateTabState(tabId: string): CdpTabState { - return this.bridgeState.getOrCreateTabState(tabId) - } - - protected removeDebuggerListeners(guest: WebContents, state: CdpTabState): void { - this.debuggerLifecycle.removeDebuggerListeners(guest, state) - } - - protected ensureDebuggerAttached(guest: WebContents): Promise { - return this.debuggerLifecycle.ensureDebuggerAttached(guest) - } - - protected makeCdpSender(guest: WebContents, sessionId?: string): CdpCommandSender { - return this.debuggerLifecycle.makeCdpSender(guest, sessionId) - } - - protected senderForRef(guest: WebContents, ref: RefEntry): CdpCommandSender { - return this.refResolution.senderForRef(guest, ref) - } - - protected resolveRef( - guest: WebContents, - sender: CdpCommandSender, - ref: string - ): Promise { - return this.refResolution.resolveRef(guest, sender, ref) - } - - protected scrollIntoView(sender: CdpCommandSender, backendNodeId: number): Promise { - return this.refResolution.scrollIntoView(sender, backendNodeId) - } - - protected getElementCenter( - sender: CdpCommandSender, - backendNodeId: number - ): Promise<{ cx: number; cy: number }> { - return this.refResolution.getElementCenter(sender, backendNodeId) - } - - protected getPageCoordinates( - guest: WebContents, - refEntry: RefEntry, - localCx: number, - localCy: number - ): Promise<{ cx: number; cy: number }> { - return this.refResolution.getPageCoordinates(guest, refEntry, localCx, localCy) - } - - protected getNavigationId(sender: CdpCommandSender): Promise { - return this.navigation.getNavigationId(sender) - } - - protected getPreviousHistoryEntryId(sender: CdpCommandSender): Promise { - return this.navigation.getPreviousHistoryEntryId(sender) - } - - protected waitForLoad(sender: CdpCommandSender, guest: WebContents): Promise { - return this.navigation.waitForLoad(sender, guest) - } - - protected waitForNetworkIdle( - guest: WebContents, - timeoutMs: number, - idleMs: number - ): Promise { - return this.navigation.waitForNetworkIdle(guest, timeoutMs, idleMs) - } - - protected invalidateRefMap(webContentsId: number): void { - this.bridgeState.invalidateRefMap(webContentsId) - } - - protected enqueueCommand(execute: () => Promise): Promise { - return this.bridgeState.enqueueCommand(execute) - } -} diff --git a/src/main/browser/cdp/commands/cdp-bridge-command-set.ts b/src/main/browser/cdp/commands/cdp-bridge-command-set.ts index bd159a95c42..de2f3153c11 100644 --- a/src/main/browser/cdp/commands/cdp-bridge-command-set.ts +++ b/src/main/browser/cdp/commands/cdp-bridge-command-set.ts @@ -1,8 +1,9 @@ import type { WebContents } from 'electron' -import { CdpAuxiliaryCommands, type CdpTabState } from './cdp-auxiliary-commands' -import type { CdpCommandSender } from '../snapshots/snapshot-engine' +import { CdpAuxiliaryCommands } from './cdp-auxiliary-commands' +import type { CdpTabState } from './cdp-tab-state' +import type { CdpCommandSender } from '../debugger/cdp-command-sender' import type { CdpBridgeState } from './cdp-bridge-state' -import { CdpDebuggerLifecycle } from './cdp-debugger-lifecycle' +import { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' import { CdpElementStateCommands } from './cdp-element-state-commands' import { CdpNavigationOperations } from './cdp-navigation-operations' import { CdpPageCommands } from './cdp-page-commands' @@ -23,13 +24,12 @@ export class CdpBridgeCommandSet { const debuggerLifecycle = new CdpDebuggerLifecycle(bridgeState) const navigation = new CdpNavigationOperations() const refResolution = new CdpRefResolution(bridgeState, debuggerLifecycle, navigation) - const moduleArgs = [bridgeState, debuggerLifecycle, refResolution, navigation] as const - this.elements = new CdpElementStateCommands(...moduleArgs) - this.page = new CdpPageCommands(...moduleArgs) - this.pointer = new CdpPointerCommands(...moduleArgs) - this.tabs = new CdpTabCommands(...moduleArgs) - this.textInput = new CdpTextInputCommands(...moduleArgs) + this.elements = new CdpElementStateCommands(bridgeState, debuggerLifecycle, refResolution) + this.page = new CdpPageCommands(bridgeState, debuggerLifecycle, navigation) + this.pointer = new CdpPointerCommands(bridgeState, debuggerLifecycle, refResolution) + this.tabs = new CdpTabCommands(bridgeState, debuggerLifecycle) + this.textInput = new CdpTextInputCommands(bridgeState, debuggerLifecycle, refResolution) this.auxiliary = new CdpAuxiliaryCommands({ run: ( operation: (context: { diff --git a/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts b/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts index f62703c8d7f..796522a2f81 100644 --- a/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts +++ b/src/main/browser/cdp/commands/cdp-bridge-integration.test.ts @@ -7,6 +7,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { createConnection } from 'node:net' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' +import { CdpBridge } from './cdp-bridge' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { OrcaRuntimeRpcServer } from '../../../runtime/rpc/server/runtime-rpc' +import { readRuntimeMetadata } from '../../../runtime/rpc/server/runtime-metadata' const { webContentsFromIdMock } = vi.hoisted(() => ({ webContentsFromIdMock: vi.fn() @@ -44,12 +49,6 @@ const { getWorktreeListingMocks } = vi.hoisted(() => { return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } }) -import { BrowserManager } from '../../browser-manager' -import { CdpBridge } from './cdp-bridge' -import { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import { OrcaRuntimeRpcServer } from '../../../runtime/rpc/server/runtime-rpc' -import { readRuntimeMetadata } from '../../../runtime/rpc/server/runtime-metadata' - type AXNode = { nodeId: string backendDOMNodeId?: number diff --git a/src/main/browser/cdp/commands/cdp-bridge-state.ts b/src/main/browser/cdp/commands/cdp-bridge-state.ts index 630bee7652b..4a9ab650837 100644 --- a/src/main/browser/cdp/commands/cdp-bridge-state.ts +++ b/src/main/browser/cdp/commands/cdp-bridge-state.ts @@ -1,6 +1,6 @@ import { webContents } from 'electron' import { BrowserError } from '../../browser-error' -import type { CdpTabState } from './cdp-auxiliary-commands' +import type { CdpTabState } from './cdp-tab-state' export type CdpQueuedCommand = { execute: () => Promise diff --git a/src/main/browser/cdp/commands/cdp-bridge.ts b/src/main/browser/cdp/commands/cdp-bridge.ts index c56d1f5d367..9d28918aaa3 100644 --- a/src/main/browser/cdp/commands/cdp-bridge.ts +++ b/src/main/browser/cdp/commands/cdp-bridge.ts @@ -33,10 +33,12 @@ import type { BrowserViewportResult, BrowserWaitResult } from '../../../../shared/runtime-browser-contracts' -import type { BrowserManager } from '../../browser-manager' -import type { CdpAuxiliaryCommands, CdpTabState } from './cdp-auxiliary-commands' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' +import type { CdpAuxiliaryCommands } from './cdp-auxiliary-commands' +import type { CdpTabState } from './cdp-tab-state' import { CdpBridgeCommandSet } from './cdp-bridge-command-set' -import { CdpBridgeState, type CdpQueuedCommand } from './cdp-bridge-state' +import { CdpBridgeState } from './cdp-bridge-state' +import type { CdpQueuedCommand } from './cdp-bridge-state' // Preserve existing imports; runtime code uses browser-error without loading Chromium. diff --git a/src/main/browser/cdp/commands/cdp-element-state-commands.ts b/src/main/browser/cdp/commands/cdp-element-state-commands.ts index 93948aa6006..010f6053860 100644 --- a/src/main/browser/cdp/commands/cdp-element-state-commands.ts +++ b/src/main/browser/cdp/commands/cdp-element-state-commands.ts @@ -3,17 +3,25 @@ import type { BrowserSelectResult, BrowserUploadResult } from '../../../../shared/runtime-browser-contracts' -import { CdpBridgeCommandModule } from './cdp-bridge-command-module' +import type { CdpBridgeState } from './cdp-bridge-state' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' +import type { CdpRefResolution } from './cdp-ref-resolution' + +export class CdpElementStateCommands { + constructor( + private readonly bridgeState: CdpBridgeState, + private readonly debuggerLifecycle: CdpDebuggerLifecycle, + private readonly refResolution: CdpRefResolution + ) {} -export class CdpElementStateCommands extends CdpBridgeCommandModule { uploadFile(element: string, filePaths: string[]): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) await refSender('DOM.setFileInputFiles', { files: filePaths, backendNodeId: node.backendDOMNodeId @@ -24,13 +32,13 @@ export class CdpElementStateCommands extends CdpBridgeCommandModule { } select(element: string, value: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) const { nodeId } = (await refSender('DOM.requestNode', { backendNodeId: node.backendDOMNodeId })) as { nodeId: number } @@ -75,13 +83,13 @@ export class CdpElementStateCommands extends CdpBridgeCommandModule { } check(element: string, checked: boolean): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) const { nodeId } = (await refSender('DOM.requestNode', { backendNodeId: node.backendDOMNodeId @@ -97,9 +105,12 @@ export class CdpElementStateCommands extends CdpBridgeCommandModule { })) as { result: { value: boolean } } if (currentState.value !== checked) { - await this.scrollIntoView(refSender, node.backendDOMNodeId) - const localCenter = await this.getElementCenter(refSender, node.backendDOMNodeId) - const { cx, cy } = await this.getPageCoordinates( + await this.refResolution.scrollIntoView(refSender, node.backendDOMNodeId) + const localCenter = await this.refResolution.getElementCenter( + refSender, + node.backendDOMNodeId + ) + const { cx, cy } = await this.refResolution.getPageCoordinates( guest, node, localCenter.cx, diff --git a/src/main/browser/cdp/commands/cdp-navigation-operations.ts b/src/main/browser/cdp/commands/cdp-navigation-operations.ts index e74512f3269..f63c2837d5b 100644 --- a/src/main/browser/cdp/commands/cdp-navigation-operations.ts +++ b/src/main/browser/cdp/commands/cdp-navigation-operations.ts @@ -1,6 +1,6 @@ import type { WebContents } from 'electron' import { BrowserError } from '../../browser-error' -import type { CdpCommandSender } from '../snapshots/snapshot-engine' +import type { CdpCommandSender } from '../debugger/cdp-command-sender' export class CdpNavigationOperations { async getNavigationId(sender: CdpCommandSender): Promise { diff --git a/src/main/browser/cdp/commands/cdp-page-capture-commands.ts b/src/main/browser/cdp/commands/cdp-page-capture-commands.ts index a0bd4f0e525..69521766d79 100644 --- a/src/main/browser/cdp/commands/cdp-page-capture-commands.ts +++ b/src/main/browser/cdp/commands/cdp-page-capture-commands.ts @@ -1,6 +1,7 @@ import type { WebSocket } from 'ws' import type { WebContents } from 'electron' -import { captureScreenshot, type CapturePaintHold } from './cdp-screenshot' +import { captureScreenshot } from './cdp-screenshot' +import type { CapturePaintHold } from '../debugger/guest-paint-hold' import { buildPrintToPdfOptions, CdpPdfStreamStore } from './cdp-print-to-pdf' import type { CdpClientResponseWriter } from '../transport/cdp-client-response-writer' import { readRemoteCliAdmittedPage } from '../../routing/input-ownership/remote-cli-page-admission' diff --git a/src/main/browser/cdp/commands/cdp-page-commands.ts b/src/main/browser/cdp/commands/cdp-page-commands.ts index 626f504e66b..4ed98ae5bb1 100644 --- a/src/main/browser/cdp/commands/cdp-page-commands.ts +++ b/src/main/browser/cdp/commands/cdp-page-commands.ts @@ -8,29 +8,39 @@ import type { BrowserWaitResult } from '../../../../shared/runtime-browser-contracts' import { BrowserError } from '../../browser-error' -import { - CdpBridgeCommandModule, - type CdpScreenshotFormat, - type CdpScrollDirection -} from './cdp-bridge-command-module' +import type { CdpBridgeState } from './cdp-bridge-state' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' +import type { CdpNavigationOperations } from './cdp-navigation-operations' import { buildSnapshot } from '../snapshots/snapshot-engine' -export class CdpPageCommands extends CdpBridgeCommandModule { - snapshot(): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) +type CdpScrollDirection = BrowserScrollResult extends { scrolled: infer Direction } + ? Direction + : never - const tabId = this.resolveTabId(guest.id) - const state = this.getOrCreateTabState(tabId) +type CdpScreenshotFormat = BrowserScreenshotResult extends { format: infer Format } ? Format : never + +export class CdpPageCommands { + constructor( + private readonly bridgeState: CdpBridgeState, + private readonly debuggerLifecycle: CdpDebuggerLifecycle, + private readonly navigation: CdpNavigationOperations + ) {} + + snapshot(): Promise { + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) + + const tabId = this.bridgeState.resolveTabId(guest.id) + const state = this.bridgeState.getOrCreateTabState(tabId) const result = await buildSnapshot(sender, state.iframeSessions, (sessionId) => - this.makeCdpSender(guest, sessionId) + this.debuggerLifecycle.makeCdpSender(guest, sessionId) ) state.snapshotResult = result - const navId = await this.getNavigationId(sender) + const navId = await this.navigation.getNavigationId(sender) state.navigationId = navId return { @@ -44,10 +54,10 @@ export class CdpPageCommands extends CdpBridgeCommandModule { } goto(url: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const { errorText } = (await sender('Page.navigate', { url })) as { errorText?: string @@ -57,18 +67,18 @@ export class CdpPageCommands extends CdpBridgeCommandModule { throw new BrowserError('browser_navigation_failed', `Navigation failed: ${errorText}`) } - await this.waitForLoad(sender, guest) - this.invalidateRefMap(guest.id) + await this.navigation.waitForLoad(sender, guest) + this.bridgeState.invalidateRefMap(guest.id) return { url: guest.getURL(), title: guest.getTitle() } }) } scroll(direction: CdpScrollDirection, amount?: number): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) // JS scrolling avoids focus changes and unreliable wheel delivery in Electron webviews. const expr = amount @@ -81,19 +91,19 @@ export class CdpPageCommands extends CdpBridgeCommandModule { } wait(timeoutMs: number): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - await this.ensureDebuggerAttached(guest) - await this.waitForNetworkIdle(guest, timeoutMs, 500) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + await this.debuggerLifecycle.ensureDebuggerAttached(guest) + await this.navigation.waitForNetworkIdle(guest, timeoutMs, 500) return { waited: true } }) } pdf(): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const { data } = (await sender('Page.printToPDF', { printBackground: true @@ -104,10 +114,10 @@ export class CdpPageCommands extends CdpBridgeCommandModule { } fullPageScreenshot(format: CdpScreenshotFormat): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const metrics = (await sender('Page.getLayoutMetrics')) as { cssContentSize?: { width: number; height: number } @@ -136,40 +146,40 @@ export class CdpPageCommands extends CdpBridgeCommandModule { } back(): Promise<{ url: string; title: string }> { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) await sender('Page.navigateToHistoryEntry', { - entryId: await this.getPreviousHistoryEntryId(sender) + entryId: await this.navigation.getPreviousHistoryEntryId(sender) }) - await this.waitForLoad(sender, guest) - this.invalidateRefMap(guest.id) + await this.navigation.waitForLoad(sender, guest) + this.bridgeState.invalidateRefMap(guest.id) return { url: guest.getURL(), title: guest.getTitle() } }) } reload(): Promise<{ url: string; title: string }> { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) await sender('Page.reload') - await this.waitForLoad(sender, guest) - this.invalidateRefMap(guest.id) + await this.navigation.waitForLoad(sender, guest) + this.bridgeState.invalidateRefMap(guest.id) return { url: guest.getURL(), title: guest.getTitle() } }) } screenshot(format: CdpScreenshotFormat): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const { data } = (await sender('Page.captureScreenshot', { format @@ -180,10 +190,10 @@ export class CdpPageCommands extends CdpBridgeCommandModule { } evaluate(expression: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const { result, exceptionDetails } = (await sender('Runtime.evaluate', { expression, diff --git a/src/main/browser/cdp/commands/cdp-page-navigation-commands.ts b/src/main/browser/cdp/commands/cdp-page-navigation-commands.ts index fa0edcddabb..5db6d88cf9e 100644 --- a/src/main/browser/cdp/commands/cdp-page-navigation-commands.ts +++ b/src/main/browser/cdp/commands/cdp-page-navigation-commands.ts @@ -1,8 +1,8 @@ import type { WebSocket } from 'ws' import type { WebContents } from 'electron' import type { CdpClientResponseWriter } from '../transport/cdp-client-response-writer' -import type { CdpSyntheticSessionRegistry } from './cdp-synthetic-session-registry' -import type { CdpDebuggerChannel } from './cdp-debugger-channel' +import type { CdpSyntheticSessionRegistry } from '../transport/cdp-synthetic-session-registry' +import type { CdpDebuggerChannel } from '../debugger/cdp-debugger-channel' const LIFECYCLE_PRIMING_TIMEOUT_MS = 1_000 diff --git a/src/main/browser/cdp/commands/cdp-ref-resolution.ts b/src/main/browser/cdp/commands/cdp-ref-resolution.ts index d469296379b..6528a7162f4 100644 --- a/src/main/browser/cdp/commands/cdp-ref-resolution.ts +++ b/src/main/browser/cdp/commands/cdp-ref-resolution.ts @@ -1,9 +1,10 @@ import type { WebContents } from 'electron' import { BrowserError } from '../../browser-error' -import type { CdpTabState } from './cdp-auxiliary-commands' -import type { CdpCommandSender, RefEntry } from '../snapshots/snapshot-engine' + +import type { CdpCommandSender } from '../debugger/cdp-command-sender' +import type { RefEntry } from '../snapshots/snapshot-engine' import type { CdpBridgeState } from './cdp-bridge-state' -import type { CdpDebuggerLifecycle } from './cdp-debugger-lifecycle' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' import type { CdpNavigationOperations } from './cdp-navigation-operations' export class CdpRefResolution { @@ -14,12 +15,14 @@ export class CdpRefResolution { ) {} senderForRef(guest: WebContents, ref: RefEntry): CdpCommandSender { - return ref.sessionId ? this.makeCdpSender(guest, ref.sessionId) : this.makeCdpSender(guest) + return ref.sessionId + ? this.debuggerLifecycle.makeCdpSender(guest, ref.sessionId) + : this.debuggerLifecycle.makeCdpSender(guest) } async resolveRef(guest: WebContents, sender: CdpCommandSender, ref: string): Promise { - const tabId = this.resolveTabId(guest.id) - const state = this.getOrCreateTabState(tabId) + const tabId = this.bridgeState.resolveTabId(guest.id) + const state = this.bridgeState.getOrCreateTabState(tabId) if (!state.snapshotResult) { throw new BrowserError( @@ -38,7 +41,7 @@ export class CdpRefResolution { // Child sessions have independent history; parent navigation IDs cannot validate their refs. if (!entry.sessionId) { - const currentNavId = await this.getNavigationId(sender) + const currentNavId = await this.navigation.getNavigationId(sender) if (state.navigationId && currentNavId !== state.navigationId) { state.snapshotResult = null state.navigationId = null @@ -49,7 +52,9 @@ export class CdpRefResolution { } } - const refSender = entry.sessionId ? this.makeCdpSender(guest, entry.sessionId) : sender + const refSender = entry.sessionId + ? this.debuggerLifecycle.makeCdpSender(guest, entry.sessionId) + : sender try { await refSender('DOM.describeNode', { backendNodeId: entry.backendDOMNodeId }) return entry @@ -94,9 +99,9 @@ export class CdpRefResolution { guest: WebContents, sessionId: string ): Promise<{ offsetX: number; offsetY: number }> { - const tabId = this.resolveTabId(guest.id) - const state = this.getOrCreateTabState(tabId) - const parentSender = this.makeCdpSender(guest) + const tabId = this.bridgeState.resolveTabId(guest.id) + const state = this.bridgeState.getOrCreateTabState(tabId) + const parentSender = this.debuggerLifecycle.makeCdpSender(guest) for (const [targetId, sid] of state.iframeSessions) { if (sid === sessionId) { @@ -201,20 +206,4 @@ export class CdpRefResolution { } return null } - - private resolveTabId(webContentsId: number): string { - return this.bridgeState.resolveTabId(webContentsId) - } - - private getOrCreateTabState(tabId: string): CdpTabState { - return this.bridgeState.getOrCreateTabState(tabId) - } - - private makeCdpSender(guest: WebContents, sessionId?: string): CdpCommandSender { - return this.debuggerLifecycle.makeCdpSender(guest, sessionId) - } - - private getNavigationId(sender: CdpCommandSender): Promise { - return this.navigation.getNavigationId(sender) - } } diff --git a/src/main/browser/cdp/commands/cdp-screenshot.ts b/src/main/browser/cdp/commands/cdp-screenshot.ts index 7371ce01765..f43f5c1e194 100644 --- a/src/main/browser/cdp/commands/cdp-screenshot.ts +++ b/src/main/browser/cdp/commands/cdp-screenshot.ts @@ -1,3 +1,4 @@ +import type { CapturePaintHold } from '../debugger/guest-paint-hold' import type { WebContents } from 'electron' import { sendGuestCdpCommand } from '../debugger/guest-cdp-command' import { @@ -5,9 +6,6 @@ import { readRemoteCliAdmittedPage } from '../../routing/input-ownership/remote-cli-page-admission' -/** Draws a hidden guest while a capture or agent input needs its frames; returns its release. */ -export type CapturePaintHold = () => () => void - export const SCREENSHOT_TIMEOUT_MS = 8000 // Probe offsets leave time for the original capture to finish before the deadline. const FRAME_PROBE_OFFSETS_MS = [250, 750, 1750, 3750] diff --git a/src/main/browser/cdp/commands/cdp-tab-commands.ts b/src/main/browser/cdp/commands/cdp-tab-commands.ts index 35e865b3d0a..92569ff3bc7 100644 --- a/src/main/browser/cdp/commands/cdp-tab-commands.ts +++ b/src/main/browser/cdp/commands/cdp-tab-commands.ts @@ -5,22 +5,28 @@ import type { BrowserTabSwitchResult } from '../../../../shared/runtime-browser-contracts' import { BrowserError } from '../../browser-error' -import { CdpBridgeCommandModule } from './cdp-bridge-command-module' +import type { CdpBridgeState } from './cdp-bridge-state' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' + +export class CdpTabCommands { + constructor( + private readonly bridgeState: CdpBridgeState, + private readonly debuggerLifecycle: CdpDebuggerLifecycle + ) {} -export class CdpTabCommands extends CdpBridgeCommandModule { setActiveTab(webContentsId: number): void { - this.activeWebContentsId = webContentsId + this.bridgeState.activeWebContentsId = webContentsId } getActiveWebContentsId(): number | null { - return this.activeWebContentsId + return this.bridgeState.activeWebContentsId } getActivePageId(_worktreeId?: string): string | null { - if (!this.activeWebContentsId) { + if (!this.bridgeState.activeWebContentsId) { return null } - return this.resolveTabIdSafe(this.activeWebContentsId) + return this.bridgeState.resolveTabIdSafe(this.bridgeState.activeWebContentsId) } getPageInfo( @@ -31,7 +37,7 @@ export class CdpTabCommands extends CdpBridgeCommandModule { if (!resolvedPageId) { return null } - const webContentsId = this.getRegisteredTabs().get(resolvedPageId) + const webContentsId = this.bridgeState.getRegisteredTabs().get(resolvedPageId) if (webContentsId == null) { return null } @@ -50,7 +56,7 @@ export class CdpTabCommands extends CdpBridgeCommandModule { const tabs: BrowserTabInfo[] = [] let index = 0 - for (const [tabId, wcId] of this.getRegisteredTabs()) { + for (const [tabId, wcId] of this.bridgeState.getRegisteredTabs()) { const guest = webContents.fromId(wcId) if (!guest || guest.isDestroyed()) { continue @@ -60,7 +66,7 @@ export class CdpTabCommands extends CdpBridgeCommandModule { index, url: guest.getURL(), title: guest.getTitle(), - active: wcId === this.activeWebContentsId + active: wcId === this.bridgeState.activeWebContentsId }) index++ } @@ -70,7 +76,7 @@ export class CdpTabCommands extends CdpBridgeCommandModule { tabSwitch(index: number): BrowserTabSwitchResult { // Keep indices aligned with tabList(), which skips destroyed guests. - const liveEntries = [...this.getRegisteredTabs()].filter(([_tabId, wcId]) => { + const liveEntries = [...this.bridgeState.getRegisteredTabs()].filter(([_tabId, wcId]) => { const guest = webContents.fromId(wcId) return guest && !guest.isDestroyed() }) @@ -82,31 +88,31 @@ export class CdpTabCommands extends CdpBridgeCommandModule { } const [tabId, wcId] = liveEntries[index] - if (this.activeWebContentsId !== null) { - this.invalidateRefMap(this.activeWebContentsId) + if (this.bridgeState.activeWebContentsId !== null) { + this.bridgeState.invalidateRefMap(this.bridgeState.activeWebContentsId) } - this.activeWebContentsId = wcId + this.bridgeState.activeWebContentsId = wcId return { switched: index, browserPageId: tabId } } onTabClosed(webContentsId: number): void { - if (this.activeWebContentsId === webContentsId) { - this.activeWebContentsId = null + if (this.bridgeState.activeWebContentsId === webContentsId) { + this.bridgeState.activeWebContentsId = null } - const tabId = this.resolveTabIdSafe(webContentsId) + const tabId = this.bridgeState.resolveTabIdSafe(webContentsId) if (tabId) { - const state = this.tabState.get(tabId) + const state = this.bridgeState.tabState.get(tabId) const guest = webContents.fromId(webContentsId) if (state && guest) { - this.removeDebuggerListeners(guest, state) + this.debuggerLifecycle.removeDebuggerListeners(guest, state) } - this.tabState.delete(tabId) - this.commandQueues.delete(tabId) + this.bridgeState.tabState.delete(tabId) + this.bridgeState.commandQueues.delete(tabId) } } onTabChanged(webContentsId: number): void { - this.activeWebContentsId = webContentsId + this.bridgeState.activeWebContentsId = webContentsId } } diff --git a/src/main/browser/cdp/commands/cdp-tab-state.ts b/src/main/browser/cdp/commands/cdp-tab-state.ts new file mode 100644 index 00000000000..aae922be6f8 --- /dev/null +++ b/src/main/browser/cdp/commands/cdp-tab-state.ts @@ -0,0 +1,22 @@ +import type { + BrowserConsoleEntry, + BrowserInterceptedRequest, + BrowserNetworkEntry +} from '../../../../shared/runtime-browser-contracts' +import type { SnapshotResult } from '../snapshots/snapshot-engine' + +export type CdpTabState = { + navigationId: string | null + snapshotResult: SnapshotResult | null + debuggerAttached: boolean + debuggerDetachListener: (() => void) | null + debuggerMessageListener: ((_event: unknown, method: string, params: unknown) => void) | null + iframeSessions: Map + capturing: boolean + consoleLog: BrowserConsoleEntry[] + networkLog: BrowserNetworkEntry[] + intercepting: boolean + interceptPatterns: string[] + pausedRequests: Map + networkRequestMap: Map +} diff --git a/src/main/browser/cdp/debugger/cdp-command-sender.ts b/src/main/browser/cdp/debugger/cdp-command-sender.ts new file mode 100644 index 00000000000..0cff00bc4ac --- /dev/null +++ b/src/main/browser/cdp/debugger/cdp-command-sender.ts @@ -0,0 +1,4 @@ +export type CdpCommandSender = ( + method: string, + params?: Record +) => Promise diff --git a/src/main/browser/cdp/commands/cdp-debugger-channel.ts b/src/main/browser/cdp/debugger/cdp-debugger-channel.ts similarity index 94% rename from src/main/browser/cdp/commands/cdp-debugger-channel.ts rename to src/main/browser/cdp/debugger/cdp-debugger-channel.ts index 661e2bb2c2a..80172af19f0 100644 --- a/src/main/browser/cdp/commands/cdp-debugger-channel.ts +++ b/src/main/browser/cdp/debugger/cdp-debugger-channel.ts @@ -1,12 +1,9 @@ import { WebSocket } from 'ws' import type { WebContents } from 'electron' -import { - acquireElectronDebugger, - type ElectronDebuggerLease -} from '../debugger/electron-debugger-lease' +import { acquireElectronDebugger, type ElectronDebuggerLease } from './electron-debugger-lease' import type { CdpClientResponseWriter } from '../transport/cdp-client-response-writer' -import type { CdpSyntheticSessionRegistry } from './cdp-synthetic-session-registry' -import { sendGuestCdpCommand } from '../debugger/guest-cdp-command' +import type { CdpSyntheticSessionRegistry } from '../transport/cdp-synthetic-session-registry' +import { sendGuestCdpCommand } from './guest-cdp-command' import { isOrcaFrameSessionTraffic } from '../input/guest-frame-input-sessions' export class CdpDebuggerChannel { diff --git a/src/main/browser/cdp/commands/cdp-debugger-events.ts b/src/main/browser/cdp/debugger/cdp-debugger-events.ts similarity index 98% rename from src/main/browser/cdp/commands/cdp-debugger-events.ts rename to src/main/browser/cdp/debugger/cdp-debugger-events.ts index ea44c713279..cfcfcfb9721 100644 --- a/src/main/browser/cdp/commands/cdp-debugger-events.ts +++ b/src/main/browser/cdp/debugger/cdp-debugger-events.ts @@ -1,6 +1,6 @@ import type { WebContents } from 'electron' import type { BrowserNetworkEntry } from '../../../../shared/runtime-browser-contracts' -import type { CdpTabState } from './cdp-auxiliary-commands' +import type { CdpTabState } from '../commands/cdp-tab-state' const CAPTURE_LOG_LIMIT = 1000 diff --git a/src/main/browser/cdp/commands/cdp-debugger-lifecycle.ts b/src/main/browser/cdp/debugger/cdp-debugger-lifecycle.ts similarity index 92% rename from src/main/browser/cdp/commands/cdp-debugger-lifecycle.ts rename to src/main/browser/cdp/debugger/cdp-debugger-lifecycle.ts index a7bfba9cce2..c06af7287bd 100644 --- a/src/main/browser/cdp/commands/cdp-debugger-lifecycle.ts +++ b/src/main/browser/cdp/debugger/cdp-debugger-lifecycle.ts @@ -1,10 +1,10 @@ import type { WebContents } from 'electron' import { BrowserError } from '../../browser-error' -import type { CdpTabState } from './cdp-auxiliary-commands' -import type { CdpCommandSender } from '../snapshots/snapshot-engine' -import type { CdpBridgeState } from './cdp-bridge-state' +import type { CdpTabState } from '../commands/cdp-tab-state' +import type { CdpCommandSender } from './cdp-command-sender' +import type { CdpBridgeState } from '../commands/cdp-bridge-state' import { createCdpDebuggerMessageListener } from './cdp-debugger-events' -import { sendGuestCdpCommand } from '../debugger/guest-cdp-command' +import { sendGuestCdpCommand } from './guest-cdp-command' export class CdpDebuggerLifecycle { constructor(private readonly bridgeState: CdpBridgeState) {} diff --git a/src/main/browser/cdp/debugger/guest-first-paint.ts b/src/main/browser/cdp/debugger/guest-first-paint.ts index 6d3527147bb..b76d09fdb81 100644 --- a/src/main/browser/cdp/debugger/guest-first-paint.ts +++ b/src/main/browser/cdp/debugger/guest-first-paint.ts @@ -1,7 +1,11 @@ import type { WebContents } from 'electron' -import type { CapturePaintHold } from '../commands/cdp-screenshot' -import { isEmbeddedGuest, type GuestCdpSender } from '../input/guest-direct-key-input' -import { readRecord, settleWithin } from '../input/guest-frame-input-sessions' +import type { CapturePaintHold } from './guest-paint-hold' +import { isEmbeddedGuest } from '../input/guest-direct-key-input' +import { + readRecord, + settleWithin, + type GuestSessionCdpSender +} from '../input/guest-frame-input-sessions' const PAINTED_EXPRESSION = "performance.getEntriesByType('paint').length > 0" const AWAIT_FIRST_PAINT_EXPRESSION = `new Promise((resolve) => { @@ -14,7 +18,7 @@ const AWAIT_FIRST_PAINT_EXPRESSION = `new Promise((resolve) => { const gatedDocumentByGuest = new WeakMap() // Answers the document to gate, or null. A failed or timed-out probe means a busy page. -async function unpaintedDocument(send: GuestCdpSender): Promise { +async function unpaintedDocument(send: GuestSessionCdpSender): Promise { const response = await settleWithin( send('Runtime.evaluate', { expression: `[${PAINTED_EXPRESSION}, performance.timeOrigin]`, @@ -35,7 +39,7 @@ async function unpaintedDocument(send: GuestCdpSender): Promise { */ export async function waitForGuestFirstPaint( guest: WebContents, - send: GuestCdpSender, + send: GuestSessionCdpSender, holdPaint: CapturePaintHold ): Promise { if (!isEmbeddedGuest(guest)) { diff --git a/src/main/browser/cdp/debugger/guest-paint-hold.ts b/src/main/browser/cdp/debugger/guest-paint-hold.ts new file mode 100644 index 00000000000..885a3e98a84 --- /dev/null +++ b/src/main/browser/cdp/debugger/guest-paint-hold.ts @@ -0,0 +1,2 @@ +/** Draws a hidden guest while a capture or agent input needs its frames; returns its release. */ +export type CapturePaintHold = () => () => void diff --git a/src/main/browser/cdp/input/agent-input-injection.test.ts b/src/main/browser/cdp/input/agent-input-injection.test.ts index a0e10b8b3ec..5def5b427af 100644 --- a/src/main/browser/cdp/input/agent-input-injection.test.ts +++ b/src/main/browser/cdp/input/agent-input-injection.test.ts @@ -6,9 +6,9 @@ vi.mock('electron', () => ({ })) import { isAgentInjectingInput, withAgentInputInjection } from './agent-input-injection' -import { setupGuestShortcutForwarding } from '../../guest-lifecycle/input/browser-guest-shortcut-forwarding' -import { setupGrabShortcutForwarding } from '../../guest-lifecycle/input/browser-guest-grab-shortcuts' -import { setupGuestEscapeForwarding } from '../../guest-lifecycle/input/browser-guest-escape-forwarding' +import { setupGuestShortcutForwarding } from '../../guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding' +import { setupGrabShortcutForwarding } from '../../guest-lifecycle/input/shortcuts/browser-guest-grab-shortcuts' +import { setupGuestEscapeForwarding } from '../../guest-lifecycle/input/shortcuts/browser-guest-escape-forwarding' type BeforeInputHandler = (event: Electron.Event, input: Electron.Input) => void diff --git a/src/main/browser/cdp/input/browser-text-insertion.ts b/src/main/browser/cdp/input/browser-text-insertion.ts index b5bd0d56e84..588db4df2c8 100644 --- a/src/main/browser/cdp/input/browser-text-insertion.ts +++ b/src/main/browser/cdp/input/browser-text-insertion.ts @@ -1,6 +1,6 @@ import { iterateBrowserTextInsertionChunks } from '../../../../shared/browser-text-insertion-chunks' import { yieldToEventLoop } from '../../../../shared/event-loop-yield' -import type { CdpCommandSender } from '../snapshots/snapshot-engine' +import type { CdpCommandSender } from '../debugger/cdp-command-sender' export async function insertTextThroughCdp( sender: CdpCommandSender, diff --git a/src/main/browser/cdp/commands/cdp-dom-focus-replay.ts b/src/main/browser/cdp/input/cdp-dom-focus-replay.ts similarity index 97% rename from src/main/browser/cdp/commands/cdp-dom-focus-replay.ts rename to src/main/browser/cdp/input/cdp-dom-focus-replay.ts index 45045e5fbd3..31ffed7c213 100644 --- a/src/main/browser/cdp/commands/cdp-dom-focus-replay.ts +++ b/src/main/browser/cdp/input/cdp-dom-focus-replay.ts @@ -1,8 +1,8 @@ import type { WebSocket } from 'ws' import type { WebContents } from 'electron' import type { CdpClientResponseWriter } from '../transport/cdp-client-response-writer' -import type { CdpDebuggerChannel } from './cdp-debugger-channel' -import type { TextInsertionRoute } from '../input/guest-direct-key-input' +import type { CdpDebuggerChannel } from '../debugger/cdp-debugger-channel' +import type { TextInsertionRoute } from './guest-direct-key-input' /** Replay DOM.focus before insertion because native focusing can blur the target. */ export class CdpDomFocusReplay { diff --git a/src/main/browser/cdp/commands/cdp-page-input-commands.ts b/src/main/browser/cdp/input/cdp-page-input-commands.ts similarity index 91% rename from src/main/browser/cdp/commands/cdp-page-input-commands.ts rename to src/main/browser/cdp/input/cdp-page-input-commands.ts index d69a65caf74..372d5c21991 100644 --- a/src/main/browser/cdp/commands/cdp-page-input-commands.ts +++ b/src/main/browser/cdp/input/cdp-page-input-commands.ts @@ -1,23 +1,23 @@ import type { WebSocket } from 'ws' import type { WebContents } from 'electron' import type { CdpClientResponseWriter } from '../transport/cdp-client-response-writer' -import type { CdpDebuggerChannel } from './cdp-debugger-channel' +import type { CdpDebuggerChannel } from '../debugger/cdp-debugger-channel' import type { CdpDomFocusReplay } from './cdp-dom-focus-replay' import { enablePageFocusEmulation, isFocusRoutedCdpInput, isFocusTakingCdpInput, type AgentInputFocusGuard -} from '../input/agent-input-focus-guard' +} from './agent-input-focus-guard' import { dispatchPageKeyEvent, isEmbeddedGuest, - routePageTextInsertion, - type GuestCdpSender -} from '../input/guest-direct-key-input' -import { withAgentInputInjection } from '../input/agent-input-injection' -import type { AgentPointerInput } from '../../guest-lifecycle/browser-agent-activity' -import type { CapturePaintHold } from './cdp-screenshot' + routePageTextInsertion +} from './guest-direct-key-input' +import type { GuestSessionCdpSender } from './guest-frame-input-sessions' +import { withAgentInputInjection } from './agent-input-injection' +import type { AgentPointerInput } from '../../guest-lifecycle/page-activity/browser-agent-activity' +import type { CapturePaintHold } from '../debugger/guest-paint-hold' import { waitForGuestFirstPaint } from '../debugger/guest-first-paint' /** Shows the agent's pointer at an input's point and resolves once it has landed. */ @@ -147,7 +147,7 @@ export class CdpPageInputCommands { ) } - private readonly sendRoot: GuestCdpSender = (method, params, sessionId) => + private readonly sendRoot: GuestSessionCdpSender = (method, params, sessionId) => this.debuggerChannel.sendDebuggerCommand(method, params, sessionId) // Focus awaits must not reorder pipelined key, text, or pointer events. diff --git a/src/main/browser/cdp/input/cdp-pointer-commands.ts b/src/main/browser/cdp/input/cdp-pointer-commands.ts index c59348df172..67d6e4cefd5 100644 --- a/src/main/browser/cdp/input/cdp-pointer-commands.ts +++ b/src/main/browser/cdp/input/cdp-pointer-commands.ts @@ -3,21 +3,37 @@ import type { BrowserDragResult, BrowserHoverResult } from '../../../../shared/runtime-browser-contracts' -import { CdpBridgeCommandModule } from '../commands/cdp-bridge-command-module' +import type { CdpBridgeState } from '../commands/cdp-bridge-state' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' +import type { CdpRefResolution } from '../commands/cdp-ref-resolution' + +export class CdpPointerCommands { + constructor( + private readonly bridgeState: CdpBridgeState, + private readonly debuggerLifecycle: CdpDebuggerLifecycle, + private readonly refResolution: CdpRefResolution + ) {} -export class CdpPointerCommands extends CdpBridgeCommandModule { click(element: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) - await this.scrollIntoView(refSender, node.backendDOMNodeId) - const localCenter = await this.getElementCenter(refSender, node.backendDOMNodeId) - const { cx, cy } = await this.getPageCoordinates(guest, node, localCenter.cx, localCenter.cy) + await this.refResolution.scrollIntoView(refSender, node.backendDOMNodeId) + const localCenter = await this.refResolution.getElementCenter( + refSender, + node.backendDOMNodeId + ) + const { cx, cy } = await this.refResolution.getPageCoordinates( + guest, + node, + localCenter.cx, + localCenter.cy + ) // Reveal hover-dependent targets before clicking. await sender('Input.dispatchMouseEvent', { type: 'mouseMoved', x: cx, y: cy }) @@ -41,16 +57,24 @@ export class CdpPointerCommands extends CdpBridgeCommandModule { } hover(element: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) - await this.scrollIntoView(refSender, node.backendDOMNodeId) - const localCenter = await this.getElementCenter(refSender, node.backendDOMNodeId) - const { cx, cy } = await this.getPageCoordinates(guest, node, localCenter.cx, localCenter.cy) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) + await this.refResolution.scrollIntoView(refSender, node.backendDOMNodeId) + const localCenter = await this.refResolution.getElementCenter( + refSender, + node.backendDOMNodeId + ) + const { cx, cy } = await this.refResolution.getPageCoordinates( + guest, + node, + localCenter.cx, + localCenter.cy + ) await sender('Input.dispatchMouseEvent', { type: 'mouseMoved', x: cx, y: cy }) @@ -59,21 +83,29 @@ export class CdpPointerCommands extends CdpBridgeCommandModule { } drag(fromElement: string, toElement: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const fromNode = await this.resolveRef(guest, sender, fromElement) - const toNode = await this.resolveRef(guest, sender, toElement) - const fromSender = this.senderForRef(guest, fromNode) - const toSender = this.senderForRef(guest, toNode) + const fromNode = await this.refResolution.resolveRef(guest, sender, fromElement) + const toNode = await this.refResolution.resolveRef(guest, sender, toElement) + const fromSender = this.refResolution.senderForRef(guest, fromNode) + const toSender = this.refResolution.senderForRef(guest, toNode) - await this.scrollIntoView(fromSender, fromNode.backendDOMNodeId) - const fromLocal = await this.getElementCenter(fromSender, fromNode.backendDOMNodeId) - const from = await this.getPageCoordinates(guest, fromNode, fromLocal.cx, fromLocal.cy) - const toLocal = await this.getElementCenter(toSender, toNode.backendDOMNodeId) - const to = await this.getPageCoordinates(guest, toNode, toLocal.cx, toLocal.cy) + await this.refResolution.scrollIntoView(fromSender, fromNode.backendDOMNodeId) + const fromLocal = await this.refResolution.getElementCenter( + fromSender, + fromNode.backendDOMNodeId + ) + const from = await this.refResolution.getPageCoordinates( + guest, + fromNode, + fromLocal.cx, + fromLocal.cy + ) + const toLocal = await this.refResolution.getElementCenter(toSender, toNode.backendDOMNodeId) + const to = await this.refResolution.getPageCoordinates(guest, toNode, toLocal.cx, toLocal.cy) // Intermediate drag events are required by many drag-and-drop libraries. await sender('Input.dispatchMouseEvent', { type: 'mouseMoved', x: from.cx, y: from.cy }) diff --git a/src/main/browser/cdp/input/cdp-text-input-commands.ts b/src/main/browser/cdp/input/cdp-text-input-commands.ts index 198d01b56a8..8fa20c64f77 100644 --- a/src/main/browser/cdp/input/cdp-text-input-commands.ts +++ b/src/main/browser/cdp/input/cdp-text-input-commands.ts @@ -7,17 +7,25 @@ import type { BrowserTypeResult } from '../../../../shared/runtime-browser-contracts' import { insertTextThroughCdp } from './browser-text-insertion' -import { CdpBridgeCommandModule } from '../commands/cdp-bridge-command-module' +import type { CdpBridgeState } from '../commands/cdp-bridge-state' +import type { CdpDebuggerLifecycle } from '../debugger/cdp-debugger-lifecycle' +import type { CdpRefResolution } from '../commands/cdp-ref-resolution' + +export class CdpTextInputCommands { + constructor( + private readonly bridgeState: CdpBridgeState, + private readonly debuggerLifecycle: CdpDebuggerLifecycle, + private readonly refResolution: CdpRefResolution + ) {} -export class CdpTextInputCommands extends CdpBridgeCommandModule { fill(element: string, value: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) await refSender('DOM.focus', { backendNodeId: node.backendDOMNodeId }) @@ -54,10 +62,10 @@ export class CdpTextInputCommands extends CdpBridgeCommandModule { } type(input: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) await insertTextThroughCdp(sender, input) return { typed: true } @@ -65,13 +73,13 @@ export class CdpTextInputCommands extends CdpBridgeCommandModule { } focus(element: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) await refSender('DOM.focus', { backendNodeId: node.backendDOMNodeId }) return { focused: element } @@ -79,13 +87,13 @@ export class CdpTextInputCommands extends CdpBridgeCommandModule { } clear(element: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) const { nodeId } = (await refSender('DOM.requestNode', { backendNodeId: node.backendDOMNodeId @@ -108,13 +116,13 @@ export class CdpTextInputCommands extends CdpBridgeCommandModule { } selectAll(element: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) - const node = await this.resolveRef(guest, sender, element) - const refSender = this.senderForRef(guest, node) + const node = await this.refResolution.resolveRef(guest, sender, element) + const refSender = this.refResolution.senderForRef(guest, node) await refSender('DOM.focus', { backendNodeId: node.backendDOMNodeId }) await sender('Input.dispatchKeyEvent', { @@ -133,10 +141,10 @@ export class CdpTextInputCommands extends CdpBridgeCommandModule { } keypress(key: string): Promise { - return this.enqueueCommand(async () => { - const guest = this.getActiveGuest() - const sender = this.makeCdpSender(guest) - await this.ensureDebuggerAttached(guest) + return this.bridgeState.enqueueCommand(async () => { + const guest = this.bridgeState.getActiveGuest() + const sender = this.debuggerLifecycle.makeCdpSender(guest) + await this.debuggerLifecycle.ensureDebuggerAttached(guest) const keyDef = resolveKeyDefinition(key) await sender('Input.dispatchKeyEvent', { diff --git a/src/main/browser/cdp/input/guest-direct-key-input.ts b/src/main/browser/cdp/input/guest-direct-key-input.ts index c4d0c32b6e1..01ca2355541 100644 --- a/src/main/browser/cdp/input/guest-direct-key-input.ts +++ b/src/main/browser/cdp/input/guest-direct-key-input.ts @@ -21,15 +21,13 @@ import { // Main-session CDP keys follow window focus; guest widget events protect the user's input (#20595). -export type GuestCdpSender = GuestSessionCdpSender - // Offscreen and headless pages lack a host frame tree, so CDP already targets them. export function isEmbeddedGuest(webContents: WebContents): boolean { return webContents.getType() === 'webview' } // Wait for widget input handling before callers read its effects, matching CDP behavior. -async function waitForPageToHandleInput(send: GuestCdpSender): Promise { +async function waitForPageToHandleInput(send: GuestSessionCdpSender): Promise { await settleWithin( send('Runtime.evaluate', { // MessageChannel avoids hidden-page timer throttling. @@ -73,7 +71,7 @@ const NO_FOCUS_GUARD: AgentInputFocusGuard = async () => () => {} // Restore user focus after CDP fallback; emulation keeps the page from seeing blur. async function focusGuestForCdpInput( webContents: WebContents, - send: GuestCdpSender, + send: GuestSessionCdpSender, guardFocus: AgentInputFocusGuard ): Promise<() => void> { await enablePageFocusEmulation(send) @@ -85,7 +83,7 @@ async function focusGuestForCdpInput( // Cross-site frame sessions route CDP input without borrowing user focus. async function sendToFrameSession( webContents: WebContents, - send: GuestCdpSender, + send: GuestSessionCdpSender, sessionId: string, method: string, params: Record @@ -99,7 +97,7 @@ async function sendToFrameSession( export async function dispatchPageKeyEvent( webContents: WebContents, params: Record, - send: GuestCdpSender, + send: GuestSessionCdpSender, guardFocus: AgentInputFocusGuard = NO_FOCUS_GUARD ): Promise { return await dispatchPageKeyEvents(webContents, [params], send, guardFocus) @@ -112,7 +110,7 @@ const isTabDown = (params: Record): boolean => export async function dispatchPageKeyEvents( webContents: WebContents, events: readonly Record[], - send: GuestCdpSender, + send: GuestSessionCdpSender, guardFocus: AgentInputFocusGuard = NO_FOCUS_GUARD ): Promise { let result: unknown = {} @@ -211,7 +209,7 @@ export async function releaseHeldPageInput( release: HeldInputRelease, guardFocus: AgentInputFocusGuard ): Promise { - const send: GuestCdpSender = (method, params, sessionId) => + const send: GuestSessionCdpSender = (method, params, sessionId) => sendGuestCdpCommand(webContents, method, params, sessionId) // The command's debugger lease may already have detached. const lease = acquireElectronDebugger(webContents) @@ -245,7 +243,7 @@ export type TextInsertionRoute = { export async function routePageTextInsertion( webContents: WebContents, params: Record, - send: GuestCdpSender, + send: GuestSessionCdpSender, guardFocus: AgentInputFocusGuard = NO_FOCUS_GUARD ): Promise { const sendText = (insertParams: Record): Promise => diff --git a/src/main/browser/cdp/snapshots/snapshot-cursor-interactive-elements.ts b/src/main/browser/cdp/snapshots/snapshot-cursor-interactive-elements.ts index 997e8d9dd74..2bebb5dd7cb 100644 --- a/src/main/browser/cdp/snapshots/snapshot-cursor-interactive-elements.ts +++ b/src/main/browser/cdp/snapshots/snapshot-cursor-interactive-elements.ts @@ -1,5 +1,5 @@ import type { SnapshotEntry } from './snapshot-ax-tree-walk' -import type { CdpCommandSender } from './snapshot-engine' +import type { CdpCommandSender } from '../debugger/cdp-command-sender' // Find controls omitted from the accessibility tree, such as styled div buttons. export async function findCursorInteractiveElements( diff --git a/src/main/browser/cdp/snapshots/snapshot-engine.test.ts b/src/main/browser/cdp/snapshots/snapshot-engine.test.ts index 4369966d33f..a4aaf46753d 100644 --- a/src/main/browser/cdp/snapshots/snapshot-engine.test.ts +++ b/src/main/browser/cdp/snapshots/snapshot-engine.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { buildSnapshot, type CdpCommandSender } from './snapshot-engine' +import { buildSnapshot } from './snapshot-engine' +import type { CdpCommandSender } from '../debugger/cdp-command-sender' type AXNode = { nodeId: string diff --git a/src/main/browser/cdp/snapshots/snapshot-engine.ts b/src/main/browser/cdp/snapshots/snapshot-engine.ts index c8d7090ed69..344104e8b3a 100644 --- a/src/main/browser/cdp/snapshots/snapshot-engine.ts +++ b/src/main/browser/cdp/snapshots/snapshot-engine.ts @@ -1,12 +1,8 @@ +import type { CdpCommandSender } from '../debugger/cdp-command-sender' import type { BrowserSnapshotRef } from '../../../../shared/runtime-browser-contracts' import { walkTree, type AXNode, type SnapshotEntry } from './snapshot-ax-tree-walk' import { findCursorInteractiveElements } from './snapshot-cursor-interactive-elements' -export type CdpCommandSender = ( - method: string, - params?: Record -) => Promise - export type RefEntry = { backendDOMNodeId: number role: string diff --git a/src/main/browser/cdp/commands/cdp-client-command.ts b/src/main/browser/cdp/transport/cdp-client-command.ts similarity index 100% rename from src/main/browser/cdp/commands/cdp-client-command.ts rename to src/main/browser/cdp/transport/cdp-client-command.ts diff --git a/src/main/browser/cdp/commands/cdp-synthetic-session-registry.ts b/src/main/browser/cdp/transport/cdp-synthetic-session-registry.ts similarity index 100% rename from src/main/browser/cdp/commands/cdp-synthetic-session-registry.ts rename to src/main/browser/cdp/transport/cdp-synthetic-session-registry.ts diff --git a/src/main/browser/cdp/transport/cdp-target-discovery.ts b/src/main/browser/cdp/transport/cdp-target-discovery.ts index 996432f0922..75db7c36ee1 100644 --- a/src/main/browser/cdp/transport/cdp-target-discovery.ts +++ b/src/main/browser/cdp/transport/cdp-target-discovery.ts @@ -2,7 +2,7 @@ import type { WebSocket } from 'ws' import type { ServerResponse } from 'node:http' import type { WebContents } from 'electron' import type { CdpClientResponseWriter } from './cdp-client-response-writer' -import type { CdpSyntheticSessionRegistry } from '../commands/cdp-synthetic-session-registry' +import type { CdpSyntheticSessionRegistry } from './cdp-synthetic-session-registry' export class CdpTargetDiscovery { constructor( diff --git a/src/main/browser/cdp/transport/cdp-ws-proxy.ts b/src/main/browser/cdp/transport/cdp-ws-proxy.ts index 13e2f8d2090..d0ca4f49e87 100644 --- a/src/main/browser/cdp/transport/cdp-ws-proxy.ts +++ b/src/main/browser/cdp/transport/cdp-ws-proxy.ts @@ -3,18 +3,18 @@ import { createServer, type Server } from 'node:http' import { randomBytes } from 'node:crypto' import type { WebContents } from 'electron' import { CdpClientResponseWriter } from './cdp-client-response-writer' -import { CdpSyntheticSessionRegistry } from '../commands/cdp-synthetic-session-registry' +import { CdpSyntheticSessionRegistry } from './cdp-synthetic-session-registry' import { CdpTargetDiscovery } from './cdp-target-discovery' -import { CdpDebuggerChannel } from '../commands/cdp-debugger-channel' +import { CdpDebuggerChannel } from '../debugger/cdp-debugger-channel' import { CdpPageNavigationCommands } from '../commands/cdp-page-navigation-commands' -import { CdpDomFocusReplay } from '../commands/cdp-dom-focus-replay' +import { CdpDomFocusReplay } from '../input/cdp-dom-focus-replay' import { CdpElementCapture } from '../commands/cdp-element-capture' import { CdpPageCaptureCommands } from '../commands/cdp-page-capture-commands' -import type { CapturePaintHold } from '../commands/cdp-screenshot' +import type { CapturePaintHold } from '../debugger/guest-paint-hold' import type { AgentInputFocusGuard } from '../input/agent-input-focus-guard' -import { CdpPageInputCommands, type ShowAgentPointer } from '../commands/cdp-page-input-commands' +import { CdpPageInputCommands, type ShowAgentPointer } from '../input/cdp-page-input-commands' import { admitCdpProxyRequest, verifyCdpProxyUpgrade } from './cdp-loopback-request-guard' -import { parseCdpClientCommand } from '../commands/cdp-client-command' +import { parseCdpClientCommand } from './cdp-client-command' import { assertRemoteCliPageAccess, runUnderRemoteCliPageAdmission diff --git a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.ts b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.ts index adacf4a1e07..173d5844819 100644 --- a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.ts +++ b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.ts @@ -11,7 +11,7 @@ import { closeBrowserClientHostComposition, fenceBrowserClientHostComposition } from './paired-runtime-browser-client-host-teardown' -import type { BrowserClientPageNetworkRoute } from '../../client-pages/lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' import type { BrowserClientPageAuthorityIdentity as BrowserClientHostAuthorityTransitionInput } from '../../client-pages/execution/browser-client-page-command-executor-dependencies' import { type ComposedBrowserClientNetworkRoutes, diff --git a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-route-sets.ts b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-route-sets.ts index 9482333d403..9283cc429aa 100644 --- a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-route-sets.ts +++ b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-route-sets.ts @@ -1,5 +1,5 @@ import type { BrowserClientHostLeaseAuthority } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import type { BrowserClientPageNetworkRoute } from '../../client-pages/lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' import { sameBrowserClientHostLeaseAuthority } from '../commands/browser-client-host-command-authority' export type ComposedBrowserClientNetworkRoutes = { diff --git a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime.ts b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime.ts index fb3a550c7f7..125cb2d078e 100644 --- a/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime.ts +++ b/src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime.ts @@ -25,8 +25,8 @@ import { BrowserClientFileChannelTransport } from '../file-transfers/browser-cli import { registerBrowserClientHostEnvironmentRoutes } from './browser-client-host-environment-routes' import { BrowserClientPageCommandExecutor } from '../../client-pages/execution/browser-client-page-command-executor' import { createBrowserClientPageGuestBinding } from '../../client-pages/lifecycle/browser-client-page-guest-binding' -import { browserManager } from '../../browser-manager' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { BrowserClientUploadStaging } from '../file-transfers/browser-client-upload-staging' import { executeBrowserClientPageAutomation, diff --git a/src/main/browser/client-pages/execution/browser-client-page-automation-runtime.ts b/src/main/browser/client-pages/execution/browser-client-page-automation-runtime.ts index 0a9f70fb0a8..b3b5dd90cb7 100644 --- a/src/main/browser/client-pages/execution/browser-client-page-automation-runtime.ts +++ b/src/main/browser/client-pages/execution/browser-client-page-automation-runtime.ts @@ -1,7 +1,7 @@ import type { BrowserClientAutomationMethod } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' import type { AgentBrowserBridge } from '../../agent-browser/agent-browser-bridge' -import type { BrowserGuestRegistration } from '../../guest-lifecycle/manager/browser-manager-types' -import type { BrowserManager } from '../../browser-manager' +import type { BrowserGuestRegistration } from '../../guest-lifecycle/manager/registration/browser-manager-registration' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' import { BrowserClientPageCommandError } from './browser-client-page-command-failure' import type { BrowserRoutePageGuestIdentity } from '../../routing/guest-authority/browser-route-page-authority' diff --git a/src/main/browser/client-pages/execution/browser-client-page-command-admission.ts b/src/main/browser/client-pages/execution/browser-client-page-command-admission.ts index c72a404af4d..a80377935a2 100644 --- a/src/main/browser/client-pages/execution/browser-client-page-command-admission.ts +++ b/src/main/browser/client-pages/execution/browser-client-page-command-admission.ts @@ -1,21 +1,6 @@ -import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import type { - BrowserClientPageRenderer, - BrowserClientPageRendererIdentity -} from '../lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' import { BrowserClientPageCommandError } from './browser-client-page-command-failure' -export function browserClientPageIdentity( - page: Pick, - partition: string -): BrowserClientPageRendererIdentity { - return { - partition, - browserPageId: page.browserPageId, - pageHostGeneration: page.pageHostGeneration - } -} - export function assertCurrentBrowserClientPageRenderer(renderer: BrowserClientPageRenderer): void { if ( !Number.isInteger(renderer.rendererWebContentsId) || diff --git a/src/main/browser/client-pages/execution/browser-client-page-command-executor-dependencies.ts b/src/main/browser/client-pages/execution/browser-client-page-command-executor-dependencies.ts index 48bb6dc53c3..b164589ba7a 100644 --- a/src/main/browser/client-pages/execution/browser-client-page-command-executor-dependencies.ts +++ b/src/main/browser/client-pages/execution/browser-client-page-command-executor-dependencies.ts @@ -2,10 +2,8 @@ import type { BrowserClientAutomationMethod } from '../../../../shared/browser/c import type { BrowserClientFileChannelTransport } from '../../client-hosts/file-transfers/browser-client-file-channel-transport' import type { BrowserClientPageGuestBinding } from '../lifecycle/browser-client-page-guest-binding' import type { BrowserClientUploadStaging } from '../../client-hosts/file-transfers/browser-client-upload-staging' -import type { - BrowserClientPageNetworkRoute, - BrowserClientPageRenderer -} from '../lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' import type { BrowserRouteSessionRegistry } from '../../routing/sessions/browser-route-session-registry' import type { BrowserClientPageLifecycleRegistry, diff --git a/src/main/browser/client-pages/execution/browser-client-page-command-executor.ts b/src/main/browser/client-pages/execution/browser-client-page-command-executor.ts index ac4eb302d99..34c9b6453e5 100644 --- a/src/main/browser/client-pages/execution/browser-client-page-command-executor.ts +++ b/src/main/browser/client-pages/execution/browser-client-page-command-executor.ts @@ -9,10 +9,8 @@ import { type BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' import type { BrowserClientAutomationResult as BrowserClientHostCommandResult } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' -import { - cleanupRetainedBrowserClientPage, - type BrowserClientPageRendererIdentity -} from '../lifecycle/browser-client-page-cleanup' +import { cleanupRetainedBrowserClientPage } from '../lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageRendererIdentity } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' import { assertBrowserClientPageAdmission } from '../lifecycle/browser-client-page-admission' import { createReservedBrowserClientPage } from '../lifecycle/browser-client-page-creation' import { retireSupersededExecutionHostPages } from '../lifecycle/browser-client-page-execution-host-supersession' @@ -279,7 +277,7 @@ export class BrowserClientPageCommandExecutor { private async cleanupPage( page: BrowserClientRetainedPage, - previousRendererPage?: BrowserClientPageRendererIdentity, + previousRendererPage?: Readonly, releaseUploads = true ): Promise { page.releaseAvailabilityWatch?.() diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-cleanup.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-cleanup.ts index 4d7f211c930..f0dddd8ce5b 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-cleanup.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-cleanup.ts @@ -1,47 +1,19 @@ +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' +import type { BrowserClientPageRendererIdentity } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' import type { BrowserRouteGuestLifecycleClaim } from '../../routing/guest-authority/browser-route-page-authority' import type { BrowserRouteSessionHandle } from '../../routing/sessions/browser-route-session-state' -import type { BrowserRouteProxyEndpoint } from '../../routing/sessions/browser-route-session-policy' import type { BrowserRouteWebContentsRegistry } from '../../routing/guest-authority/browser-route-webcontents-registry' -import { browserClientPageIdentity } from '../execution/browser-client-page-command-admission' +import { browserClientPageIdentity } from '../renderer/browser-client-page-renderer-contract' import type { BrowserClientRetainedPage } from './browser-client-page-retained-state' -export type BrowserClientPageNetworkRoute = { - key: string - executionHostIdentity: string - /** Pre-migration identity of the same host, so its existing partition can be adopted. */ - legacyExecutionHostIdentity: string - proxyEndpoint: BrowserRouteProxyEndpoint - release(): void | Promise -} - -export type BrowserClientPageRendererIdentity = Readonly<{ - partition: string - browserPageId: string - pageHostGeneration: number -}> - -export type BrowserClientPageRenderer = { - rendererWebContentsId: number - isCurrent(): boolean - mountPage( - page: BrowserClientPageRendererIdentity, - signal: AbortSignal - ): Promise<{ webContentsId: number }> - rekeyPage?( - previous: BrowserClientPageRendererIdentity, - next: BrowserClientPageRendererIdentity, - signal: AbortSignal - ): Promise - retirePage(page: BrowserClientPageRendererIdentity): void | Promise -} - export async function cleanupBrowserClientPage( routeWebContents: Pick, target: { guestMayExist: boolean lifecycleClaim: BrowserRouteGuestLifecycleClaim | null renderer: BrowserClientPageRenderer | null - rendererPages: readonly BrowserClientPageRendererIdentity[] + rendererPages: readonly Readonly[] routeSession: BrowserRouteSessionHandle | null route: BrowserClientPageNetworkRoute | null } @@ -94,7 +66,7 @@ export async function cleanupRetainedBrowserClientPage( }): Promise releaseUploadStaging?(): void | Promise }, - previousRendererPage?: BrowserClientPageRendererIdentity + previousRendererPage?: Readonly ): Promise { const failures: unknown[] = [] try { diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-creation.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-creation.ts index 0468d4ba519..63d6a2ce0d4 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-creation.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-creation.ts @@ -1,14 +1,12 @@ import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import { - cleanupBrowserClientPage, - type BrowserClientPageNetworkRoute as RetainedNetworkRoute, - type BrowserClientPageRenderer -} from './browser-client-page-cleanup' +import { cleanupBrowserClientPage } from './browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute as RetainedNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' import { assertBrowserClientPageCommandNotAborted, - assertCurrentBrowserClientPageRenderer, - browserClientPageIdentity + assertCurrentBrowserClientPageRenderer } from '../execution/browser-client-page-command-admission' +import { browserClientPageIdentity } from '../renderer/browser-client-page-renderer-contract' import type { BrowserClientPageAuthorityIdentity } from '../execution/browser-client-page-command-executor-dependencies' import { BrowserClientPageCommandError } from '../execution/browser-client-page-command-failure' import type { BrowserClientPageGuestBinding } from './browser-client-page-guest-binding' diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-execution-host-supersession.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-execution-host-supersession.ts index ce4b8c85650..8e552551e7e 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-execution-host-supersession.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-execution-host-supersession.ts @@ -1,4 +1,4 @@ -import type { BrowserClientPageNetworkRoute } from './browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' import type { BrowserClientRetainedPage } from './browser-client-page-retained-state' type SupersedingRoute = Pick diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-guest-binding.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-guest-binding.ts index 4e25bc771e7..638ce08d16d 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-guest-binding.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-guest-binding.ts @@ -1,4 +1,4 @@ -import type { BrowserManager } from '../../browser-manager' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' import type { BrowserRoutePageGuestIdentity } from '../../routing/guest-authority/browser-route-page-authority' export type BrowserClientPageGuestBindingInput = { diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-inventory.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-inventory.ts index 34882246c2c..a25911e50a4 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-inventory.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-inventory.ts @@ -8,7 +8,7 @@ import { type BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' import { BrowserClientPageMetadataParams } from '../../../../shared/browser/client-hosting/browser-client-page-metadata-protocol' -import type { BrowserClientPageRenderer } from './browser-client-page-cleanup' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' import { BrowserClientPageCommandError } from '../execution/browser-client-page-command-failure' import type { BrowserRouteGuestLifecycleClaim } from '../../routing/guest-authority/browser-route-page-authority' diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts index 49fc6fb7d02..be6fd057434 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-profile-binding.test.ts @@ -25,11 +25,11 @@ vi.mock('electron', () => ({ webContents: { fromId: browserMocks.webContentsFromIdMock } })) -vi.mock('../../guest-lifecycle/popups/popup-origin-bar-window', () => ({ +vi.mock('../../guest-lifecycle/popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { createBrowserClientPageGuestBinding } from './browser-client-page-guest-binding' import { resetBrowserManagerMocks, diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation.ts index 5f03d4eb3c1..e46fb501b5c 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation.ts @@ -4,9 +4,9 @@ import type { } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' import { assertBrowserClientPageCommandNotAborted, - assertCurrentBrowserClientPageRenderer, - browserClientPageIdentity + assertCurrentBrowserClientPageRenderer } from '../execution/browser-client-page-command-admission' +import { browserClientPageIdentity } from '../renderer/browser-client-page-renderer-contract' import { sameBrowserClientPageAuthority } from '../../client-hosts/commands/browser-client-host-command-authority' import { BrowserClientPageCommandError } from '../execution/browser-client-page-command-failure' import { @@ -17,7 +17,7 @@ import type { BrowserClientPageLifecycleRegistry, BrowserClientRetainedPage } from './browser-client-page-retained-state' -import type { BrowserClientPageRendererIdentity } from './browser-client-page-cleanup' +import type { BrowserClientPageRendererIdentity } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' type BrowserClientPageReconciliationContext = { pages: Map @@ -29,7 +29,7 @@ type BrowserClientPageReconciliationContext = { retirePage: (browserPageId: string, pageHostGeneration: number) => Promise cleanupPage: ( page: BrowserClientRetainedPage, - previousRendererPage?: BrowserClientPageRendererIdentity + previousRendererPage?: Readonly ) => Promise } @@ -200,7 +200,7 @@ async function failClosedRekeyedPage( context: BrowserClientPageReconciliationContext, page: BrowserClientRetainedPage, error: unknown, - previousRendererPage?: BrowserClientPageRendererIdentity + previousRendererPage?: Readonly ): Promise { page.reconciling = false page.retiring ??= context.cleanupPage(page, previousRendererPage) diff --git a/src/main/browser/client-pages/lifecycle/browser-client-page-retained-state.ts b/src/main/browser/client-pages/lifecycle/browser-client-page-retained-state.ts index 12726b4326a..4669535d9a3 100644 --- a/src/main/browser/client-pages/lifecycle/browser-client-page-retained-state.ts +++ b/src/main/browser/client-pages/lifecycle/browser-client-page-retained-state.ts @@ -1,8 +1,6 @@ import type { BrowserClientHostedPageInventory } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' -import type { - BrowserClientPageNetworkRoute, - BrowserClientPageRenderer -} from './browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from '../../network/client-routes/browser-client-page-network-route' +import type { BrowserClientPageRenderer } from '../renderer/browser-client-page-renderer-contract' import type { BrowserRouteGuestLifecycleClaim, BrowserRoutePageGuestIdentity diff --git a/src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.ts b/src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.ts index cdfaee7d68a..a4f2378b6de 100644 --- a/src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.ts +++ b/src/main/browser/client-pages/renderer/browser-client-page-renderer-bridge.ts @@ -8,7 +8,7 @@ import { type BrowserClientPageRendererReply as RendererReply, type BrowserClientPageRendererRequest as RendererRequest } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' -import type { BrowserClientPageRenderer } from '../lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageRenderer } from './browser-client-page-renderer-contract' import { readCurrentRendererFrame, readRendererReplyRequestId, diff --git a/src/main/browser/client-pages/renderer/browser-client-page-renderer-contract.ts b/src/main/browser/client-pages/renderer/browser-client-page-renderer-contract.ts new file mode 100644 index 00000000000..e0176154708 --- /dev/null +++ b/src/main/browser/client-pages/renderer/browser-client-page-renderer-contract.ts @@ -0,0 +1,28 @@ +import type { BrowserClientHostCommandEvent } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' +import type { BrowserClientPageRendererIdentity } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' + +export type BrowserClientPageRenderer = { + rendererWebContentsId: number + isCurrent(): boolean + mountPage( + page: Readonly, + signal: AbortSignal + ): Promise<{ webContentsId: number }> + rekeyPage?( + previous: Readonly, + next: Readonly, + signal: AbortSignal + ): Promise + retirePage(page: Readonly): void | Promise +} + +export function browserClientPageIdentity( + page: Pick, + partition: string +): Readonly { + return { + partition, + browserPageId: page.browserPageId, + pageHostGeneration: page.pageHostGeneration + } +} diff --git a/src/main/browser/client-pages/renderer/browser-client-page-renderer-runtime.ts b/src/main/browser/client-pages/renderer/browser-client-page-renderer-runtime.ts index 57dd5c2a4c5..776e456f414 100644 --- a/src/main/browser/client-pages/renderer/browser-client-page-renderer-runtime.ts +++ b/src/main/browser/client-pages/renderer/browser-client-page-renderer-runtime.ts @@ -1,6 +1,6 @@ import { ipcMain } from 'electron' import { BROWSER_CLIENT_PAGE_RENDERER_REPLY_CHANNEL } from '../../../../shared/browser/client-hosting/browser-client-page-renderer-protocol' -import type { BrowserClientPageRenderer } from '../lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageRenderer } from './browser-client-page-renderer-contract' import { BrowserClientPageRendererBridgeRegistry } from './browser-client-page-renderer-bridge' import type { BrowserClientPageRendererEndpoint } from './browser-client-page-renderer-reply-admission' diff --git a/src/main/browser/cookies/browser-cookie-clear-store-lifecycle.test.ts b/src/main/browser/cookies/browser-cookie-clear-store-lifecycle.test.ts index b326d033597..1dcdc264e53 100644 --- a/src/main/browser/cookies/browser-cookie-clear-store-lifecycle.test.ts +++ b/src/main/browser/cookies/browser-cookie-clear-store-lifecycle.test.ts @@ -43,7 +43,7 @@ vi.mock('../cdp/debugger/electron-debugger-lease', () => ({ acquireElectronDebugger: vi.fn(() => lease) })) -import { withCookieMutationLock } from './browser-cookie-import-clear' +import { withCookieMutationLock } from './mutation/cookie-mutation-lock' import { writeImportedCookies, type SourceCookieToWrite } from './browser-cookie-import-write' import { openCookieClearStore } from './browser-cookie-clear-store' diff --git a/src/main/browser/cookies/browser-cookie-clear-store.ts b/src/main/browser/cookies/browser-cookie-clear-store.ts index 653d36427d5..08f0a39e985 100644 --- a/src/main/browser/cookies/browser-cookie-clear-store.ts +++ b/src/main/browser/cookies/browser-cookie-clear-store.ts @@ -3,14 +3,14 @@ import { openCookieDebuggerSession, type CookieClearDebugger } from './browser-cookie-debugger-session' -import { normalizeCookieDomain } from './browser-cookie-import-policy' +import { normalizeCookieDomain } from './policy/cookie-domain' import type { CookieClearIdentity, CookieClearPartitionKey, CookieClearStore, CookieImportWriteStore, CookieJarCdpReadStore -} from './browser-cookie-import-clear' +} from './storage/cookie-store-contracts' import { restoreEveryCookieIdentity } from './browser-cookie-identity-restore' import { normalizeCookiePartitionSite } from './sources/browser-cookie-source-partition' import type { CdpCookie } from './browser-cdp-cookie' diff --git a/src/main/browser/cookies/browser-cookie-identity-restore.ts b/src/main/browser/cookies/browser-cookie-identity-restore.ts index 5febf2319bb..b5fda4cce21 100644 --- a/src/main/browser/cookies/browser-cookie-identity-restore.ts +++ b/src/main/browser/cookies/browser-cookie-identity-restore.ts @@ -1,4 +1,4 @@ -import type { CookieClearIdentity } from './browser-cookie-import-clear' +import type { CookieClearIdentity } from './storage/cookie-store-contracts' export async function restoreEveryCookieIdentity( identities: readonly CookieClearIdentity[], diff --git a/src/main/browser/cookies/browser-cookie-import-clear-atomicity.test.ts b/src/main/browser/cookies/browser-cookie-import-clear-atomicity.test.ts index 30c0ff7fec4..a40eb7f8c90 100644 --- a/src/main/browser/cookies/browser-cookie-import-clear-atomicity.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-clear-atomicity.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { CookieClearIdentity } from './browser-cookie-import-clear' +import type { CookieClearIdentity } from './storage/cookie-store-contracts' import type { ValidatedCookie } from './sources/browser-cookie-validation' vi.mock('electron', () => ({ dialog: {}, session: {} })) @@ -9,7 +9,7 @@ vi.mock('./browser-cookie-import-diagnostics', () => ({ summarizeCookieImportError: String })) -import { importValidatedCookies } from './browser-cookie-import-pipeline' +import { importValidatedCookies } from './imports/import-validated-cookies' function cookie(name: string, overrides: Partial = {}): ValidatedCookie { return { diff --git a/src/main/browser/cookies/browser-cookie-import-clear.ts b/src/main/browser/cookies/browser-cookie-import-clear.ts index 8e49a2d7845..69daa4a0456 100644 --- a/src/main/browser/cookies/browser-cookie-import-clear.ts +++ b/src/main/browser/cookies/browser-cookie-import-clear.ts @@ -1,65 +1,14 @@ -import type { Cookie, Cookies } from 'electron' +import type { Cookie } from 'electron' +import type { CookieClearIdentity, CookieClearSession } from './storage/cookie-store-contracts' +import { type ImportedDomainScope, domainIsInImportedScope } from './policy/cookie-import-scope' +import { cookieRemovalUrl } from './storage/cookie-removal-url' +import { isNonTransplantableCookieDomain } from './policy/cookie-import-exclusions' +import { normalizeCookieDomain, registrableFamily } from './policy/cookie-domain' import { mapSettledWithConcurrency } from '../../../shared/map-with-concurrency' -import type { CdpCookie } from './browser-cdp-cookie' -import type { ImportedDomainScope } from './browser-cookie-import-policy' -import { - cookieRemovalUrl, - domainIsInImportedScope, - isNonTransplantableCookieDomain, - normalizeCookieDomain, - registrableFamily -} from './browser-cookie-import-policy' +import { withCookieMutationLock } from './mutation/cookie-mutation-lock' const COOKIE_CLEAR_CONCURRENCY = 8 -export type CookieClearPartitionKey = { - topLevelSite: string - hasCrossSiteAncestor: boolean -} - -export type CookieClearIdentity = { - url: string - name: string - value: string - domain?: string - hostOnly?: boolean - path?: string - secure?: boolean - httpOnly?: boolean - sameSite: Cookie['sameSite'] - expirationDate?: number - partitionKey?: CookieClearPartitionKey -} - -export type CookieClearStore = Pick & { - snapshotClearIdentities( - cookies: readonly { cookie: Cookie; url: string }[] - ): Promise - restoreClearIdentities(identities: readonly CookieClearIdentity[]): Promise -} - -// Write through CDP identities because Electron cookies.set loses partition keys. -export type CookieImportWriteStore = Pick & { - writeCookieIdentity(identity: CookieClearIdentity): Promise -} - -// Why: cookies.get() leaves out partitionKey, so a whole-jar copy reads through CDP too. -export type CookieJarCdpReadStore = { - readAllCdpCookies(): Promise -} - -// Exclude cookies.set and bulk clearData: neither preserves this per-cookie rollback contract. -export type CookieClearSession = { - cookies: Pick - snapshotClearIdentities: CookieClearStore['snapshotClearIdentities'] - restoreClearIdentities: CookieClearStore['restoreClearIdentities'] -} - -/** Use the partition’s Electron Session as the shared lock key. */ -export type CookieMutationLockOwner = WeakKey - -const mutationLocks = new WeakMap>() - function cookieClearKey(url: string, name: string): string { return JSON.stringify([url, name]) } @@ -81,35 +30,6 @@ export function identitiesFromClearCookies( })) } -/** Hold across clear, writes, and rollback so a stale rollback cannot undo a later import. */ -export async function acquireCookieMutationLock( - owner: CookieMutationLockOwner -): Promise<() => void> { - const previous = mutationLocks.get(owner) ?? Promise.resolve() - let release!: () => void - const current = new Promise((resolve) => { - release = resolve - }) - mutationLocks.set( - owner, - previous.then(() => current) - ) - await previous - return release -} - -export async function withCookieMutationLock( - owner: CookieMutationLockOwner, - run: () => Promise -): Promise { - const release = await acquireCookieMutationLock(owner) - try { - return await run() - } finally { - release() - } -} - function removableCookieEntries( cookies: readonly Cookie[], preserveFamilies: ReadonlySet, diff --git a/src/main/browser/cookies/browser-cookie-import-concurrency.test.ts b/src/main/browser/cookies/browser-cookie-import-concurrency.test.ts index ef41ce87944..f8c6c9fe8ab 100644 --- a/src/main/browser/cookies/browser-cookie-import-concurrency.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-concurrency.test.ts @@ -43,7 +43,7 @@ vi.mock('./browser-cookie-clear-store', () => ({ dispose: () => undefined }) })) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { setPendingCookieImport: setPendingCookieImportMock, clearPendingCookieImport: clearPendingCookieImportMock @@ -56,7 +56,8 @@ vi.mock('../../../shared/windows-retry-file-operations', () => ({ copyFileWithWindowsRetry: copyFileWithWindowsRetryMock })) -import { importCookiesFromBrowser, importCookiesFromFile } from './browser-cookie-import' +import { importCookiesFromBrowser } from './browser-cookie-import' +import { importCookiesFromFile } from './imports/import-cookie-file' import { createChromiumCookieTestDatabase } from './browser-cookie-import-test-database' describe('two concurrent imports into one partition', () => { diff --git a/src/main/browser/cookies/browser-cookie-import-partition-fidelity.test.ts b/src/main/browser/cookies/browser-cookie-import-partition-fidelity.test.ts index f4259562092..e21795aca7b 100644 --- a/src/main/browser/cookies/browser-cookie-import-partition-fidelity.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-partition-fidelity.test.ts @@ -20,7 +20,7 @@ const { writeCookieIdentityMock: vi.fn() })) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { setPendingCookieImport: setPendingCookieImportMock, clearPendingCookieImport: clearPendingCookieImportMock diff --git a/src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts b/src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts index f04416f87fd..50f4e2645ac 100644 --- a/src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-partition-reland.electron.test.ts @@ -298,6 +298,7 @@ async function runFixture(mode: 'native' | 'file'): Promise { const root = mkdtempSync(join(tmpdir(), `orca-sta4300-${mode}-`)) fixtureRoots.push(root) const importPath = join(root, 'browser-cookie-import.cjs') + const importEntryPath = join(root, 'cookie-import-entry.ts') const registryStubPath = join(root, 'browser-session-registry.cjs') const resultPath = join(root, 'result.json') const fixturePath = join(root, 'main.cjs') @@ -344,6 +345,13 @@ async function runFixture(mode: 'native' | 'file'): Promise { registryStubPath, 'exports.browserSessionRegistry = { clearPendingCookieImport() {}, setPendingCookieImport() {} }\n' ) + writeFileSync( + importEntryPath, + [ + `export { importCookiesFromBrowser } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-cookie-import.ts'))}`, + `export { importCookiesFromFile } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/imports/import-cookie-file.ts'))}` + ].join('\n') + ) await buildVite({ configFile: false, logLevel: 'silent', @@ -351,8 +359,8 @@ async function runFixture(mode: 'native' | 'file'): Promise { { name: 'stub-browser-session-registry', resolveId(source, importer) { - return source === '../sessions/browser-session-registry' && - importer?.endsWith('browser-cookie-import.ts') + return source === '../../sessions/profiles/browser-session-registry' && + importer?.replaceAll('\\', '/').endsWith('/cookies/chromium/finalize-import.ts') ? registryStubPath : null } @@ -361,7 +369,7 @@ async function runFixture(mode: 'native' | 'file'): Promise { build: { emptyOutDir: false, lib: { - entry: join(process.cwd(), 'src/main/browser/cookies/browser-cookie-import.ts'), + entry: importEntryPath, formats: ['cjs'], fileName: () => 'browser-cookie-import.cjs' }, diff --git a/src/main/browser/cookies/browser-cookie-import-partition-rollback.electron.test.ts b/src/main/browser/cookies/browser-cookie-import-partition-rollback.electron.test.ts index 6da3dfcc4d4..00a05aef4f9 100644 --- a/src/main/browser/cookies/browser-cookie-import-partition-rollback.electron.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-partition-rollback.electron.test.ts @@ -149,7 +149,7 @@ async function runFixture(): Promise { [ `export { openCookieClearStore } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-cookie-clear-store.ts'))}`, `export { removeTransplantableCookies } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-cookie-import-clear.ts'))}`, - `export { importedDomainScope } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-cookie-import-policy.ts'))}` + `export { importedDomainScope } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/policy/cookie-import-scope.ts'))}` ].join('\n') ) await buildVite({ diff --git a/src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts b/src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts index 49796fce309..39c83d0126f 100644 --- a/src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts @@ -171,8 +171,8 @@ async function runFixture(): Promise { { name: 'stub-browser-session-registry', resolveId(source, importer) { - return source === '../sessions/browser-session-registry' && - importer?.endsWith('browser-cookie-import.ts') + return source === '../../sessions/profiles/browser-session-registry' && + importer?.replaceAll('\\', '/').endsWith('/cookies/chromium/finalize-import.ts') ? registryStubPath : null } diff --git a/src/main/browser/cookies/browser-cookie-import-policy.ts b/src/main/browser/cookies/browser-cookie-import-policy.ts deleted file mode 100644 index 3f60e7da276..00000000000 --- a/src/main/browser/cookies/browser-cookie-import-policy.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { isIP } from 'node:net' -import type { Cookie } from 'electron' -import { parse as parseDomain } from 'tldts' - -const GOOGLE_SOURCE_BOUND_COOKIE_NAMES = new Set([ - 'SIDCC', - '__Secure-1PSIDCC', - '__Secure-3PSIDCC', - '__Secure-STRP', - 'AEC' -]) - -export function normalizeCookieDomain(domain: string): string | null { - const candidate = domain.trim().replace(/^\.+/, '') - const isBracketedIpv6 = candidate.startsWith('[') && candidate.endsWith(']') - if (!candidate || /[/\\@?#%]/.test(candidate) || (!isBracketedIpv6 && candidate.includes(':'))) { - return null - } - try { - const parsed = new URL(`https://${candidate}/`) - const normalized = parsed.hostname.toLowerCase() - if ( - parsed.username || - parsed.password || - parsed.port || - parsed.pathname !== '/' || - parsed.search || - parsed.hash || - normalized.endsWith('.') || - normalized.includes('..') - ) { - return null - } - return normalized - } catch { - return null - } -} - -// Private suffixes keep tenants such as foo.github.io and bar.github.io in separate removal scopes. -const PUBLIC_SUFFIX_OPTIONS = { allowPrivateDomains: true } as const - -function isListedSuffix(parsed: { isIcann: boolean | null; isPrivate: boolean | null }): boolean { - return parsed.isIcann === true || parsed.isPrivate === true -} - -// Normalize before IP detection so alternate address spellings share the same removal family. -// Bare public suffixes name no family; preserving one would exempt all tenants. -export function registrableFamily(domain: string): string | null { - const host = normalizeCookieDomain(domain) - if (!host) { - return null - } - if (isIP(host)) { - return host - } - // isIP requires IPv6 addresses without brackets. - if (host.startsWith('[') && host.endsWith(']') && isIP(host.slice(1, -1)) === 6) { - return host - } - const parsed = parseDomain(host, PUBLIC_SUFFIX_OPTIONS) - if (parsed.hostname === null) { - return host - } - if (parsed.domain === null) { - return isListedSuffix(parsed) ? null : host - } - return parsed.domain -} - -export function normalizeCookieImportDomain(domain: string): string | null { - const normalized = normalizeCookieDomain(domain) - if (!normalized) { - return null - } - const parsed = parseDomain(normalized, PUBLIC_SUFFIX_OPTIONS) - if (parsed.hostname === null) { - return normalized.startsWith('[') && normalized.endsWith(']') ? normalized : null - } - if (parsed.domain === null && isListedSuffix(parsed)) { - return null - } - return normalized -} - -// Preserve device-bound Google sessions; YouTube accepts imports and stays eligible. -// Entries must be canonical lowercase ASCII registrable domains, never public suffixes. -const NON_TRANSPLANTABLE_DOMAINS = ['google.com'] as const - -export function isNonTransplantableCookieDomain(domain: string): boolean { - const normalized = normalizeCookieDomain(domain) - if (!normalized) { - return false - } - return NON_TRANSPLANTABLE_DOMAINS.some( - (root) => normalized === root || normalized.endsWith(`.${root}`) - ) -} - -export function isGoogleSourceBoundCookie(name: string, domain: string): boolean { - if (!GOOGLE_SOURCE_BOUND_COOKIE_NAMES.has(name)) { - return false - } - const normalized = normalizeCookieDomain(domain) - return normalized === 'google.com' || normalized?.endsWith('.google.com') === true -} - -function domainSuffixes(domain: string): string[] { - const labels = domain.split('.') - return labels.map((_, index) => labels.slice(index).join('.')) -} - -function importDomainAncestors(domain: string): string[] { - const parsed = parseDomain(domain, PUBLIC_SUFFIX_OPTIONS) - const boundary = parsed.hostname === null ? domain : (parsed.domain ?? domain) - const ancestors: string[] = [] - for (const suffix of domainSuffixes(domain)) { - ancestors.push(suffix) - if (suffix === boundary) { - break - } - } - return ancestors -} - -// Share removal scope across live imports, replacements, and staged replay to protect unrelated sessions. -export type ImportedDomainScope = { - exact: Set - ancestors: Set - descendantRoots: Set -} - -export function importedDomainScope(domains: readonly string[]): ImportedDomainScope { - const exact = new Set() - const ancestors = new Set() - const descendantRoots = new Set() - const seen = new Set() - for (const domain of domains) { - const candidate = normalizeCookieDomain(domain) - if (!candidate || seen.has(candidate)) { - continue - } - seen.add(candidate) - const normalized = normalizeCookieImportDomain(candidate) - if (!normalized || exact.has(normalized)) { - continue - } - exact.add(normalized) - if (normalized.includes('.')) { - descendantRoots.add(normalized) - } - for (const suffix of importDomainAncestors(normalized)) { - ancestors.add(suffix) - } - } - return { exact, ancestors, descendantRoots } -} - -// Staged rows derive hostOnly from host_key, without constructing an Electron Cookie. -export function domainIsInImportedScope( - scope: ImportedDomainScope, - domain: string, - hostOnly: boolean -): boolean { - if (scope.exact.has(domain)) { - return true - } - if (!hostOnly && scope.ancestors.has(domain)) { - return true - } - return domainSuffixes(domain).some((suffix) => scope.descendantRoots.has(suffix)) -} - -// normalizedDomain must come from normalizeCookieDomain. -export function cookieRemovalUrl(cookie: Cookie, normalizedDomain: string): string { - const url = new URL(`${cookie.secure ? 'https' : 'http'}://${normalizedDomain}/`) - url.pathname = cookie.path?.startsWith('/') ? cookie.path : '/' - return url.toString() -} diff --git a/src/main/browser/cookies/browser-cookie-import-snapshot-ownership.test.ts b/src/main/browser/cookies/browser-cookie-import-snapshot-ownership.test.ts index 5dbb04d239b..4c5ed86d74f 100644 --- a/src/main/browser/cookies/browser-cookie-import-snapshot-ownership.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-snapshot-ownership.test.ts @@ -42,7 +42,7 @@ vi.mock('electron', () => ({ vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { setPendingCookieImport: setPendingCookieImportMock, clearPendingCookieImport: clearPendingCookieImportMock @@ -102,7 +102,7 @@ import { createChromiumCookieTestDatabase, encryptMacChromiumCookie } from './browser-cookie-import-test-database' -import { acquireCookieMutationLock } from './browser-cookie-import-clear' +import { acquireCookieMutationLock } from './mutation/cookie-mutation-lock' import * as cookieDecryption from './sources/browser-cookie-decryption' const PARTITION = 'persist:test' diff --git a/src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts b/src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts index 3685cdc3e0f..6148e6aed1b 100644 --- a/src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts @@ -175,7 +175,7 @@ async function runFixture(): Promise { writeFileSync(cookieFilePath, JSON.stringify(SOURCE_COOKIES)) writeFileSync( bundleEntryPath, - `export { importCookiesFromFile } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-cookie-import.ts'))}` + `export { importCookiesFromFile } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/imports/import-cookie-file.ts'))}` ) await buildVite({ configFile: false, diff --git a/src/main/browser/cookies/browser-cookie-import-write.test.ts b/src/main/browser/cookies/browser-cookie-import-write.test.ts index c926d99a048..e7f9a6cc2b8 100644 --- a/src/main/browser/cookies/browser-cookie-import-write.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-write.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { CookieClearIdentity } from './browser-cookie-import-clear' +import type { CookieClearIdentity } from './storage/cookie-store-contracts' import type { SourcePartitionRead } from './sources/browser-cookie-source-partition' import { writeImportedCookies, type SourceCookieToWrite } from './browser-cookie-import-write' diff --git a/src/main/browser/cookies/browser-cookie-import-write.ts b/src/main/browser/cookies/browser-cookie-import-write.ts index ed00e5ff3d8..0914c939451 100644 --- a/src/main/browser/cookies/browser-cookie-import-write.ts +++ b/src/main/browser/cookies/browser-cookie-import-write.ts @@ -3,7 +3,7 @@ import type { CookieClearIdentity, CookieClearPartitionKey, CookieImportWriteStore -} from './browser-cookie-import-clear' +} from './storage/cookie-store-contracts' import type { SourcePartitionRead } from './sources/browser-cookie-source-partition' export type ImportedCookieFields = { diff --git a/src/main/browser/cookies/browser-cookie-import.comet.test.ts b/src/main/browser/cookies/browser-cookie-import.comet.test.ts index ed18b84d254..f993fb771f6 100644 --- a/src/main/browser/cookies/browser-cookie-import.comet.test.ts +++ b/src/main/browser/cookies/browser-cookie-import.comet.test.ts @@ -58,7 +58,7 @@ describe('detectInstalledBrowsers — Comet', () => { } }) - const { detectInstalledBrowsers } = await import('./browser-cookie-import') + const { detectInstalledBrowsers } = await import('./sources/browser-cookie-detection') const detected = detectInstalledBrowsers() expect(detected.find((b) => b.family === 'comet')).toBeUndefined() }) @@ -77,7 +77,7 @@ describe('detectInstalledBrowsers — Comet', () => { } }) - const { selectBrowserProfile } = await import('./browser-cookie-import') + const { selectBrowserProfile } = await import('./sources/browser-cookie-detection') const selected = selectBrowserProfile( { family: 'comet', diff --git a/src/main/browser/cookies/browser-cookie-import.test.ts b/src/main/browser/cookies/browser-cookie-import.test.ts index 7f0237d7b89..1bd8c84739a 100644 --- a/src/main/browser/cookies/browser-cookie-import.test.ts +++ b/src/main/browser/cookies/browser-cookie-import.test.ts @@ -22,7 +22,7 @@ const { writeCookieIdentityMock: vi.fn() })) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { setPendingCookieImport: setPendingCookieImportMock, clearPendingCookieImport: clearPendingCookieImportMock diff --git a/src/main/browser/cookies/browser-cookie-import.ts b/src/main/browser/cookies/browser-cookie-import.ts index 6c536c42cdc..df6a90afd72 100644 --- a/src/main/browser/cookies/browser-cookie-import.ts +++ b/src/main/browser/cookies/browser-cookie-import.ts @@ -1,39 +1,9 @@ -import type { BrowserWindow } from 'electron' import type { BrowserCookieImportResult } from '../../../shared/browser-workspace-types' -import { - detectInstalledBrowsers as detectBrowsers, - selectBrowserProfile as selectProfile -} from './sources/browser-cookie-detection' import type { DetectedBrowser } from './sources/browser-cookie-source-profiles' -import { - pickCookieFile as pickFile, - importCookiesFromFile as importFile, - type CookieImportOptions -} from './browser-cookie-import-pipeline' +import type { CookieImportOptions } from './imports/cookie-import-contracts' import { importChromiumCookies } from './chromium/import-cookies' import { importCookiesFromFirefox } from './sources/browser-cookie-firefox-import' import { importCookiesFromSafari } from './sources/browser-cookie-safari-import' -export function detectInstalledBrowsers(): DetectedBrowser[] { - return detectBrowsers() -} - -export function selectBrowserProfile( - browser: DetectedBrowser, - profileDirectory: string -): DetectedBrowser | null { - return selectProfile(browser, profileDirectory) -} - -export async function pickCookieFile(parentWindow: BrowserWindow | null): Promise { - return pickFile(parentWindow) -} - -export async function importCookiesFromFile( - filePath: string, - targetPartition: string -): Promise { - return importFile(filePath, targetPartition) -} export async function importCookiesFromBrowser( browser: DetectedBrowser, diff --git a/src/main/browser/cookies/browser-google-cookie-clear-target.test.ts b/src/main/browser/cookies/browser-google-cookie-clear-target.test.ts index f0cbbfbc5f4..d7c15e93aed 100644 --- a/src/main/browser/cookies/browser-google-cookie-clear-target.test.ts +++ b/src/main/browser/cookies/browser-google-cookie-clear-target.test.ts @@ -52,13 +52,19 @@ vi.mock('../client-hosts/lifecycle/paired-runtime-browser-client-host-runtime', getPairedRuntimeBrowserClientRouteIdentity: mocks.route })) vi.mock('./browser-cookie-import', () => ({ - importCookiesFromBrowser: mocks.import, - importCookiesFromFile: mocks.import, - pickCookieFile: mocks.pick, + importCookiesFromBrowser: mocks.import +})) +vi.mock('./imports/import-cookie-file', () => ({ + importCookiesFromFile: mocks.import +})) +vi.mock('./imports/cookie-file-picker', () => ({ + pickCookieFile: mocks.pick +})) +vi.mock('./sources/browser-cookie-detection', () => ({ detectInstalledBrowsers: mocks.detect, selectBrowserProfile: vi.fn() })) -vi.mock('../browser-manager', () => ({ browserManager: {} })) +vi.mock('../guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('./client-route/client-route-cookie-import-source-store', () => ({ recordClientRouteCookieImportSource: vi.fn() })) @@ -66,7 +72,7 @@ vi.mock('@/store/index', () => ({ useAppStore: { getState: () => importStore.get vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } })) -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' vi.mock('../client-hosts/lifecycle/paired-runtime-browser-client-host-registry', () => ({ PairedRuntimeBrowserClientHostRegistry: class { start = async () => ({}) @@ -104,7 +110,7 @@ const { captureGoogleCookieClearTarget, confirmAndClearGoogleCookies } = await v import { registerBrowserHandlers } from '../../ipc/browser/browser' import { setTrustedBrowserRendererWebContentsId } from '../../ipc/browser/browser-renderer-trust' import { importCookiesIntoClientRoutePartition } from './client-route/browser-client-route-cookie-import' -import { acquireCookieMutationLock } from './browser-cookie-import-clear' +import { acquireCookieMutationLock } from './mutation/cookie-mutation-lock' import * as bindingFile from '../routing/partitions/browser-route-partition-binding-file' const profile: BrowserSessionProfile = { diff --git a/src/main/browser/cookies/browser-google-cookie-clear-target.ts b/src/main/browser/cookies/browser-google-cookie-clear-target.ts index 66a78fec43f..e87ddb79284 100644 --- a/src/main/browser/cookies/browser-google-cookie-clear-target.ts +++ b/src/main/browser/cookies/browser-google-cookie-clear-target.ts @@ -4,7 +4,7 @@ import type { } from '../../../shared/browser-workspace-types' import type { GoogleCookieClearLocalTarget } from '../../../shared/browser-google-cookie-clear' import { bindRoutePartition } from './client-route/browser-client-route-cookie-import' -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' import { getPairedRuntimeBrowserClientRouteIdentity } from '../client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' import { clearGoogleCookiesFromPartition } from './browser-google-cookie-clear' diff --git a/src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts b/src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts index 52e36e55e1a..1efeb66c5be 100644 --- a/src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts +++ b/src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts @@ -38,8 +38,8 @@ it('clears Google paths/partitions and preserves other sites across a graceful E import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' - import { browserSessionRegistry as registry } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/sessions/browser-session-registry.ts'))} - import { loadBrowserSessionMeta, persistBrowserSessionMeta } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/sessions/browser-session-meta-store.ts'))} + import { browserSessionRegistry as registry } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/sessions/profiles/browser-session-registry.ts'))} + import { loadBrowserSessionMeta, persistBrowserSessionMeta } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/sessions/profiles/browser-session-meta-store.ts'))} import { resolveChromiumCookiesPath } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/chromium/chromium-cookie-path.ts'))} import { clearGoogleCookiesFromPartition } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/cookies/browser-google-cookie-clear.ts'))} app.setPath('userData', ${JSON.stringify(join(root, 'user-data'))}) @@ -139,11 +139,12 @@ it('clears Google paths/partitions and preserves other sites across a graceful E build.onResolve({ filter: /./ }, ({ path, importer }) => importer.endsWith('/browser-session-registry.ts') && ![ - '../cookies/staging/browser-session-cookie-staging', + '../../cookies/staging/browser-session-cookie-staging', './browser-session-meta-store', - './browser-session-persisted-profile-validation' + './browser-session-persisted-profile-validation', + '../../identity/mode/browser-retired-profile-identity-inspection' ].includes(path) && - !path.startsWith('../../../shared/') && + !path.startsWith('../../../../shared/') && !['electron', 'node:crypto', 'node:path'].includes(path) ? { path, namespace: 'registry-policy-effects' } : undefined diff --git a/src/main/browser/cookies/browser-google-cookie-clear.ts b/src/main/browser/cookies/browser-google-cookie-clear.ts index adfb4a6687f..0773288052b 100644 --- a/src/main/browser/cookies/browser-google-cookie-clear.ts +++ b/src/main/browser/cookies/browser-google-cookie-clear.ts @@ -1,13 +1,11 @@ import { BrowserError } from '../browser-error' -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' import { session, type Cookies } from 'electron' import type { GoogleCookieClearResult } from '../../../shared/browser-google-cookie-clear' -import { withCookieMutationLock } from './browser-cookie-import-clear' -import { - cookieRemovalUrl, - isNonTransplantableCookieDomain, - normalizeCookieDomain -} from './browser-cookie-import-policy' +import { withCookieMutationLock } from './mutation/cookie-mutation-lock' +import { cookieRemovalUrl } from './storage/cookie-removal-url' +import { isNonTransplantableCookieDomain } from './policy/cookie-import-exclusions' +import { normalizeCookieDomain } from './policy/cookie-domain' export async function clearGoogleCookies( target: { cookies: Pick }, diff --git a/src/main/browser/cookies/browser-partition-cookie-copy.ts b/src/main/browser/cookies/browser-partition-cookie-copy.ts index 01e36762bfc..2e1a7eff573 100644 --- a/src/main/browser/cookies/browser-partition-cookie-copy.ts +++ b/src/main/browser/cookies/browser-partition-cookie-copy.ts @@ -10,18 +10,15 @@ import { } from '../../../shared/wsl-move/wsl-move-browser-cookie-copy' import type { CdpCookie } from './browser-cdp-cookie' import { identityFromCdpCookie, openCookieClearStore } from './browser-cookie-clear-store' -import { withCookieMutationLock, type CookieClearIdentity } from './browser-cookie-import-clear' -import { - isNonTransplantableCookieDomain, - normalizeCookieDomain -} from './browser-cookie-import-policy' - -export type BrowserPartitionCookieCopyCounts = WslMoveBrowserCookieCopyCounts +import { withCookieMutationLock } from './mutation/cookie-mutation-lock' +import type { CookieClearIdentity } from './storage/cookie-store-contracts' +import { isNonTransplantableCookieDomain } from './policy/cookie-import-exclusions' +import { normalizeCookieDomain } from './policy/cookie-domain' export type BrowserPartitionCookieCopyPlan = { writes: CookieClearIdentity[] /** Skip and reject counts; the copy adds the write results. */ - counts: BrowserPartitionCookieCopyCounts + counts: WslMoveBrowserCookieCopyCounts } /** Pure: what to write from `source` into a jar that already holds `destination`. */ @@ -77,7 +74,7 @@ export function planBrowserPartitionCookieCopy( export async function copyBrowserPartitionCookies( sourcePartition: string, destinationPartition: string -): Promise { +): Promise { if (sourcePartition === destinationPartition) { throw new Error('browser_partition_cookie_copy_same_partition') } diff --git a/src/main/browser/cookies/chromium/finalize-import.ts b/src/main/browser/cookies/chromium/finalize-import.ts index 5e709b0ea61..08cfe43c1d0 100644 --- a/src/main/browser/cookies/chromium/finalize-import.ts +++ b/src/main/browser/cookies/chromium/finalize-import.ts @@ -2,7 +2,7 @@ import type { BrowserCookieImportResult, BrowserCookieImportSummary } from '../../../../shared/browser-workspace-types' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { summarizePartitionSkips } from '../browser-cookie-partition-summary' import { openCookieClearStore } from '../browser-cookie-clear-store' import { writeImportedCookies, type SourceCookieToWrite } from '../browser-cookie-import-write' diff --git a/src/main/browser/cookies/chromium/import-context.ts b/src/main/browser/cookies/chromium/import-context.ts index c45ef6f2d30..a4133c1887f 100644 --- a/src/main/browser/cookies/chromium/import-context.ts +++ b/src/main/browser/cookies/chromium/import-context.ts @@ -1,10 +1,10 @@ import type { Session } from 'electron' import type { BrowserCookieImportSummary } from '../../../../shared/browser-workspace-types' -import type { CookieImportOptions } from '../browser-cookie-import-pipeline' +import type { CookieImportOptions } from '../imports/cookie-import-contracts' import type { ImportedCookieFields, ImportWritePlanResult } from '../browser-cookie-import-write' import type { SourcePartitionRead } from '../sources/browser-cookie-source-partition' import type { ChromiumCookieSnapshot } from './chromium-cookie-snapshot' -import type { EncryptionKeyResult } from '../sources/browser-cookie-sqlite' +import type { EncryptionKeyResult } from '../sources/chromium-encryption-key-contract' import type { DetectedBrowser } from '../sources/browser-cookie-source-profiles' export type ChromiumSourceRow = Record diff --git a/src/main/browser/cookies/chromium/import-cookies.ts b/src/main/browser/cookies/chromium/import-cookies.ts index db3822bea13..c9310f07c43 100644 --- a/src/main/browser/cookies/chromium/import-cookies.ts +++ b/src/main/browser/cookies/chromium/import-cookies.ts @@ -8,8 +8,8 @@ import { summarizeCookieImportError } from '../browser-cookie-import-diagnostics' import type { DetectedBrowser } from '../sources/browser-cookie-source-profiles' -import type { CookieImportOptions } from '../browser-cookie-import-pipeline' -import { withCookieMutationLock } from '../browser-cookie-import-clear' +import type { CookieImportOptions } from '../imports/cookie-import-contracts' +import { withCookieMutationLock } from '../mutation/cookie-mutation-lock' import { prepareChromiumCookieImport } from './prepare-import' import { scanChromiumCookieRows } from './scan-source-rows' import { finalizeChromiumCookieImport } from './finalize-import' diff --git a/src/main/browser/cookies/chromium/prepare-import.ts b/src/main/browser/cookies/chromium/prepare-import.ts index 49d007c16c4..25550f67189 100644 --- a/src/main/browser/cookies/chromium/prepare-import.ts +++ b/src/main/browser/cookies/chromium/prepare-import.ts @@ -4,13 +4,13 @@ import type { BrowserCookieImportResult } from '../../../../shared/browser-works import { isGoogleSourceBoundCookie, isNonTransplantableCookieDomain -} from '../browser-cookie-import-policy' +} from '../policy/cookie-import-exclusions' import { createChromiumCookieSnapshot } from './chromium-cookie-snapshot' import { planImportWrites } from '../browser-cookie-import-write' import { readChromiumRowPartition } from '../sources/browser-cookie-source-partition' import { diag } from '../browser-cookie-import-diagnostics' import type { DetectedBrowser } from '../sources/browser-cookie-source-profiles' -import type { CookieImportOptions } from '../browser-cookie-import-pipeline' +import type { CookieImportOptions } from '../imports/cookie-import-contracts' import type { ChromiumImportContext } from './import-context' import type { Session } from 'electron' import { getEncryptionKey } from '../sources/browser-cookie-key' diff --git a/src/main/browser/cookies/chromium/scan-source-rows.ts b/src/main/browser/cookies/chromium/scan-source-rows.ts index c319814678d..020d573c2d6 100644 --- a/src/main/browser/cookies/chromium/scan-source-rows.ts +++ b/src/main/browser/cookies/chromium/scan-source-rows.ts @@ -1,11 +1,11 @@ import type { BrowserCookieImportResult } from '../../../../shared/browser-workspace-types' import { isGoogleSourceBoundCookie, - isNonTransplantableCookieDomain, - normalizeCookieImportDomain -} from '../browser-cookie-import-policy' + isNonTransplantableCookieDomain +} from '../policy/cookie-import-exclusions' +import { normalizeCookieImportDomain } from '../policy/cookie-domain' import { isExpiredImportRow } from '../browser-cookie-import-write' -import { chromiumTimestampToUnix } from '../sources/browser-cookie-sqlite' +import { chromiumTimestampToUnix } from '../sources/chromium-cookie-time' import { databaseSameSite } from '../sources/browser-cookie-validation' import { buildUndecryptableWarning, diff --git a/src/main/browser/cookies/client-route/browser-client-route-cookie-import.test.ts b/src/main/browser/cookies/client-route/browser-client-route-cookie-import.test.ts index d925afa7b4a..a3e9e62776f 100644 --- a/src/main/browser/cookies/client-route/browser-client-route-cookie-import.test.ts +++ b/src/main/browser/cookies/client-route/browser-client-route-cookie-import.test.ts @@ -28,16 +28,20 @@ const { selectBrowserProfileMock: vi.fn() })) -vi.mock('../browser-cookie-import', () => ({ +vi.mock('../sources/browser-cookie-detection', () => ({ detectInstalledBrowsers: detectInstalledBrowsersMock, - importCookiesFromBrowser: importCookiesFromBrowserMock, - importCookiesFromFile: importCookiesFromFileMock, selectBrowserProfile: selectBrowserProfileMock })) +vi.mock('../browser-cookie-import', () => ({ + importCookiesFromBrowser: importCookiesFromBrowserMock +})) +vi.mock('../imports/import-cookie-file', () => ({ + importCookiesFromFile: importCookiesFromFileMock +})) vi.mock('../../routing/partitions/browser-route-partition-binding-runtime', () => ({ currentBrowserRoutePartitionBindingStore: () => bindingStore })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getProfile: getProfileMock, requireRouteBrowserProfile: requireRouteBrowserProfileMock diff --git a/src/main/browser/cookies/client-route/browser-client-route-cookie-import.ts b/src/main/browser/cookies/client-route/browser-client-route-cookie-import.ts index a53b60cd48e..12f2dbd9e00 100644 --- a/src/main/browser/cookies/client-route/browser-client-route-cookie-import.ts +++ b/src/main/browser/cookies/client-route/browser-client-route-cookie-import.ts @@ -6,18 +6,15 @@ import { browserCookieImportFailure, type BrowserCookieImportFailure } from '../../../../shared/browser-cookie-import-failure-copy' -import { - detectInstalledBrowsers, - importCookiesFromBrowser, - importCookiesFromFile, - selectBrowserProfile -} from '../browser-cookie-import' +import { detectInstalledBrowsers, selectBrowserProfile } from '../sources/browser-cookie-detection' +import { importCookiesFromBrowser } from '../browser-cookie-import' +import { importCookiesFromFile } from '../imports/import-cookie-file' import type { DetectedBrowser } from '../sources/browser-cookie-source-profiles' import { recordClientRouteCookieImportSource } from './client-route-cookie-import-source-store' import { currentBrowserRoutePartitionBindingStore } from '../../routing/partitions/browser-route-partition-binding-runtime' import { resolveBrowserRoutePartitionBinding } from '../../routing/partitions/browser-route-partition-migration' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { getPairedRuntimeBrowserClientRouteIdentity } from '../../client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' type ClientRouteCookieImportTarget = { diff --git a/src/main/browser/cookies/imports/cookie-file-picker.ts b/src/main/browser/cookies/imports/cookie-file-picker.ts new file mode 100644 index 00000000000..42a479476a5 --- /dev/null +++ b/src/main/browser/cookies/imports/cookie-file-picker.ts @@ -0,0 +1,22 @@ +import { translateMain } from '../../../i18n/main-i18n' +import { dialog, type BrowserWindow } from 'electron' + +// Main owns the file picker so a compromised renderer cannot request arbitrary file reads. +export async function pickCookieFile(parentWindow: BrowserWindow | null): Promise { + const opts = { + title: translateMain('native.dialog.importCookies', 'Import Cookies'), + filters: [ + { name: translateMain('native.dialog.cookieFiles', 'Cookie Files'), extensions: ['json'] }, + { name: translateMain('native.dialog.allFiles', 'All Files'), extensions: ['*'] } + ], + properties: ['openFile' as const] + } + const result = parentWindow + ? await dialog.showOpenDialog(parentWindow, opts) + : await dialog.showOpenDialog(opts) + + if (result.canceled || result.filePaths.length === 0) { + return null + } + return result.filePaths[0] +} diff --git a/src/main/browser/cookies/imports/cookie-import-contracts.ts b/src/main/browser/cookies/imports/cookie-import-contracts.ts new file mode 100644 index 00000000000..089d80a8471 --- /dev/null +++ b/src/main/browser/cookies/imports/cookie-import-contracts.ts @@ -0,0 +1,16 @@ +import type { CookieClearStore, CookieImportWriteStore } from '../storage/cookie-store-contracts' + +export type CookieImportSessionStore = CookieClearStore & + CookieImportWriteStore & { dispose: () => void } + +export type CookieImportTarget = { + partition: string + // Reuse the Electron Session as the lock key across import paths; a fresh adapter would not serialize. + mutationLockOwner: object + openWriteStore: () => CookieImportSessionStore + flushStore?: () => Promise +} + +export type CookieImportOptions = { + canReportPartitionSkippedCookies?: boolean +} diff --git a/src/main/browser/cookies/imports/import-cookie-file.ts b/src/main/browser/cookies/imports/import-cookie-file.ts new file mode 100644 index 00000000000..63f6bada220 --- /dev/null +++ b/src/main/browser/cookies/imports/import-cookie-file.ts @@ -0,0 +1,58 @@ +import { browserCookieImportFailure } from '../../../../shared/browser-cookie-import-failure-copy' +import type { BrowserCookieImportResult } from '../../../../shared/browser-workspace-types' +import { readFile } from 'node:fs/promises' +import { + validateCookieEntry, + type RawCookieEntry, + type ValidatedCookie +} from '../sources/browser-cookie-validation' +import { cookieImportTarget } from '../storage/browser-cookie-session-target' +import { importValidatedCookies } from './import-validated-cookies' + +export async function importCookiesFromFile( + filePath: string, + targetPartition: string +): Promise { + let rawContent: string + try { + rawContent = await readFile(filePath, 'utf-8') + } catch { + return browserCookieImportFailure('fileUnreadable') + } + + let parsed: unknown + try { + parsed = JSON.parse(rawContent) + } catch { + return browserCookieImportFailure('fileInvalidJson') + } + + if (!Array.isArray(parsed)) { + return browserCookieImportFailure('fileNotArray') + } + + if (parsed.length === 0) { + return browserCookieImportFailure('fileEmpty') + } + + const validated: ValidatedCookie[] = [] + let skipped = 0 + for (const entry of parsed) { + if (typeof entry !== 'object' || entry === null) { + skipped++ + continue + } + const cookie = validateCookieEntry(entry as RawCookieEntry) + if (cookie) { + validated.push(cookie) + } else { + skipped++ + } + } + + if (validated.length === 0) { + return browserCookieImportFailure('fileNoValidCookies', { count: skipped }) + } + + return importValidatedCookies(validated, parsed.length, cookieImportTarget(targetPartition)) +} diff --git a/src/main/browser/cookies/browser-cookie-import-pipeline.ts b/src/main/browser/cookies/imports/import-validated-cookies.ts similarity index 50% rename from src/main/browser/cookies/browser-cookie-import-pipeline.ts rename to src/main/browser/cookies/imports/import-validated-cookies.ts index b99a857c56b..9dac6de22cb 100644 --- a/src/main/browser/cookies/browser-cookie-import-pipeline.ts +++ b/src/main/browser/cookies/imports/import-validated-cookies.ts @@ -1,60 +1,23 @@ -import { translateMain } from '../../i18n/main-i18n' -import { dialog, session, type BrowserWindow } from 'electron' -import { summarizePartitionSkips } from './browser-cookie-partition-summary' -import { browserCookieImportFailure } from '../../../shared/browser-cookie-import-failure-copy' +import { summarizePartitionSkips } from '../browser-cookie-partition-summary' import type { BrowserCookieImportResult, BrowserCookieImportSummary -} from '../../../shared/browser-workspace-types' +} from '../../../../shared/browser-workspace-types' import { isGoogleSourceBoundCookie, - isNonTransplantableCookieDomain, - normalizeCookieImportDomain -} from './browser-cookie-import-policy' -import { - acquireCookieMutationLock, - type CookieClearStore, - type CookieImportWriteStore -} from './browser-cookie-import-clear' -import { openCookieClearStore } from './browser-cookie-clear-store' + isNonTransplantableCookieDomain +} from '../policy/cookie-import-exclusions' +import { normalizeCookieImportDomain } from '../policy/cookie-domain' +import { acquireCookieMutationLock } from '../mutation/cookie-mutation-lock' import { emptyImportWritePhase, planImportWrites, writeImportedCookies, type ImportWritePhase -} from './browser-cookie-import-write' -import { readFile } from 'node:fs/promises' -import { diag } from './browser-cookie-import-diagnostics' -import { - validateCookieEntry, - type RawCookieEntry, - type ValidatedCookie -} from './sources/browser-cookie-validation' - -export type CookieImportSessionStore = CookieClearStore & - CookieImportWriteStore & { dispose: () => void } - -export type CookieImportTarget = { - partition: string - // Reuse the Electron Session as the lock key across import paths; a fresh adapter would not serialize. - mutationLockOwner: object - openWriteStore: () => CookieImportSessionStore - flushStore?: () => Promise -} - -export type CookieImportOptions = { - canReportPartitionSkippedCookies?: boolean -} - -export function cookieImportTarget(targetPartition: string): CookieImportTarget { - const targetSession = session.fromPartition(targetPartition) - return { - partition: targetPartition, - mutationLockOwner: targetSession, - openWriteStore: () => openCookieClearStore(targetSession), - flushStore: () => targetSession.cookies.flushStore() - } -} +} from '../browser-cookie-import-write' +import { diag } from '../browser-cookie-import-diagnostics' +import type { ValidatedCookie } from '../sources/browser-cookie-validation' +import type { CookieImportTarget, CookieImportOptions } from './cookie-import-contracts' export async function importValidatedCookies( cookies: ValidatedCookie[], @@ -145,71 +108,3 @@ export async function importValidatedCookies( return { ok: true, profileId: '', summary } } - -// Main owns the file picker so a compromised renderer cannot request arbitrary file reads. -export async function pickCookieFile(parentWindow: BrowserWindow | null): Promise { - const opts = { - title: translateMain('native.dialog.importCookies', 'Import Cookies'), - filters: [ - { name: translateMain('native.dialog.cookieFiles', 'Cookie Files'), extensions: ['json'] }, - { name: translateMain('native.dialog.allFiles', 'All Files'), extensions: ['*'] } - ], - properties: ['openFile' as const] - } - const result = parentWindow - ? await dialog.showOpenDialog(parentWindow, opts) - : await dialog.showOpenDialog(opts) - - if (result.canceled || result.filePaths.length === 0) { - return null - } - return result.filePaths[0] -} - -export async function importCookiesFromFile( - filePath: string, - targetPartition: string -): Promise { - let rawContent: string - try { - rawContent = await readFile(filePath, 'utf-8') - } catch { - return browserCookieImportFailure('fileUnreadable') - } - - let parsed: unknown - try { - parsed = JSON.parse(rawContent) - } catch { - return browserCookieImportFailure('fileInvalidJson') - } - - if (!Array.isArray(parsed)) { - return browserCookieImportFailure('fileNotArray') - } - - if (parsed.length === 0) { - return browserCookieImportFailure('fileEmpty') - } - - const validated: ValidatedCookie[] = [] - let skipped = 0 - for (const entry of parsed) { - if (typeof entry !== 'object' || entry === null) { - skipped++ - continue - } - const cookie = validateCookieEntry(entry as RawCookieEntry) - if (cookie) { - validated.push(cookie) - } else { - skipped++ - } - } - - if (validated.length === 0) { - return browserCookieImportFailure('fileNoValidCookies', { count: skipped }) - } - - return importValidatedCookies(validated, parsed.length, cookieImportTarget(targetPartition)) -} diff --git a/src/main/browser/cookies/mutation/cookie-mutation-lock.ts b/src/main/browser/cookies/mutation/cookie-mutation-lock.ts new file mode 100644 index 00000000000..6631e15eabc --- /dev/null +++ b/src/main/browser/cookies/mutation/cookie-mutation-lock.ts @@ -0,0 +1,33 @@ +/** Use the partition’s Electron Session as the shared lock key. */ +export type CookieMutationLockOwner = WeakKey + +const mutationLocks = new WeakMap>() + +/** Hold across clear, writes, and rollback so a stale rollback cannot undo a later import. */ +export async function acquireCookieMutationLock( + owner: CookieMutationLockOwner +): Promise<() => void> { + const previous = mutationLocks.get(owner) ?? Promise.resolve() + let release!: () => void + const current = new Promise((resolve) => { + release = resolve + }) + mutationLocks.set( + owner, + previous.then(() => current) + ) + await previous + return release +} + +export async function withCookieMutationLock( + owner: CookieMutationLockOwner, + run: () => Promise +): Promise { + const release = await acquireCookieMutationLock(owner) + try { + return await run() + } finally { + release() + } +} diff --git a/src/main/browser/cookies/policy/cookie-domain.ts b/src/main/browser/cookies/policy/cookie-domain.ts new file mode 100644 index 00000000000..f920510dc3a --- /dev/null +++ b/src/main/browser/cookies/policy/cookie-domain.ts @@ -0,0 +1,75 @@ +import { isIP } from 'node:net' +import { parse as parseDomain } from 'tldts' + +export function normalizeCookieDomain(domain: string): string | null { + const candidate = domain.trim().replace(/^\.+/, '') + const isBracketedIpv6 = candidate.startsWith('[') && candidate.endsWith(']') + if (!candidate || /[/\\@?#%]/.test(candidate) || (!isBracketedIpv6 && candidate.includes(':'))) { + return null + } + try { + const parsed = new URL(`https://${candidate}/`) + const normalized = parsed.hostname.toLowerCase() + if ( + parsed.username || + parsed.password || + parsed.port || + parsed.pathname !== '/' || + parsed.search || + parsed.hash || + normalized.endsWith('.') || + normalized.includes('..') + ) { + return null + } + return normalized + } catch { + return null + } +} + +// Private suffixes keep tenants such as foo.github.io and bar.github.io in separate removal scopes. +export const PUBLIC_SUFFIX_OPTIONS = { allowPrivateDomains: true } as const + +function isListedSuffix(parsed: { isIcann: boolean | null; isPrivate: boolean | null }): boolean { + return parsed.isIcann === true || parsed.isPrivate === true +} + +// Normalize before IP detection so alternate address spellings share the same removal family. +// Bare public suffixes name no family; preserving one would exempt all tenants. +export function registrableFamily(domain: string): string | null { + const host = normalizeCookieDomain(domain) + if (!host) { + return null + } + if (isIP(host)) { + return host + } + // isIP requires IPv6 addresses without brackets. + if (host.startsWith('[') && host.endsWith(']') && isIP(host.slice(1, -1)) === 6) { + return host + } + const parsed = parseDomain(host, PUBLIC_SUFFIX_OPTIONS) + if (parsed.hostname === null) { + return host + } + if (parsed.domain === null) { + return isListedSuffix(parsed) ? null : host + } + return parsed.domain +} + +export function normalizeCookieImportDomain(domain: string): string | null { + const normalized = normalizeCookieDomain(domain) + if (!normalized) { + return null + } + const parsed = parseDomain(normalized, PUBLIC_SUFFIX_OPTIONS) + if (parsed.hostname === null) { + return normalized.startsWith('[') && normalized.endsWith(']') ? normalized : null + } + if (parsed.domain === null && isListedSuffix(parsed)) { + return null + } + return normalized +} diff --git a/src/main/browser/cookies/policy/cookie-import-exclusions.ts b/src/main/browser/cookies/policy/cookie-import-exclusions.ts new file mode 100644 index 00000000000..10c72ac283c --- /dev/null +++ b/src/main/browser/cookies/policy/cookie-import-exclusions.ts @@ -0,0 +1,31 @@ +import { normalizeCookieDomain } from './cookie-domain' + +const GOOGLE_SOURCE_BOUND_COOKIE_NAMES = new Set([ + 'SIDCC', + '__Secure-1PSIDCC', + '__Secure-3PSIDCC', + '__Secure-STRP', + 'AEC' +]) + +// Preserve device-bound Google sessions; YouTube accepts imports and stays eligible. +// Entries must be canonical lowercase ASCII registrable domains, never public suffixes. +const NON_TRANSPLANTABLE_DOMAINS = ['google.com'] as const + +export function isNonTransplantableCookieDomain(domain: string): boolean { + const normalized = normalizeCookieDomain(domain) + if (!normalized) { + return false + } + return NON_TRANSPLANTABLE_DOMAINS.some( + (root) => normalized === root || normalized.endsWith(`.${root}`) + ) +} + +export function isGoogleSourceBoundCookie(name: string, domain: string): boolean { + if (!GOOGLE_SOURCE_BOUND_COOKIE_NAMES.has(name)) { + return false + } + const normalized = normalizeCookieDomain(domain) + return normalized === 'google.com' || normalized?.endsWith('.google.com') === true +} diff --git a/src/main/browser/cookies/policy/cookie-import-scope.ts b/src/main/browser/cookies/policy/cookie-import-scope.ts new file mode 100644 index 00000000000..da07b547ca6 --- /dev/null +++ b/src/main/browser/cookies/policy/cookie-import-scope.ts @@ -0,0 +1,72 @@ +import { parse as parseDomain } from 'tldts' +import { + PUBLIC_SUFFIX_OPTIONS, + normalizeCookieDomain, + normalizeCookieImportDomain +} from './cookie-domain' + +function domainSuffixes(domain: string): string[] { + const labels = domain.split('.') + return labels.map((_, index) => labels.slice(index).join('.')) +} + +function importDomainAncestors(domain: string): string[] { + const parsed = parseDomain(domain, PUBLIC_SUFFIX_OPTIONS) + const boundary = parsed.hostname === null ? domain : (parsed.domain ?? domain) + const ancestors: string[] = [] + for (const suffix of domainSuffixes(domain)) { + ancestors.push(suffix) + if (suffix === boundary) { + break + } + } + return ancestors +} + +// Share removal scope across live imports, replacements, and staged replay to protect unrelated sessions. +export type ImportedDomainScope = { + exact: Set + ancestors: Set + descendantRoots: Set +} + +export function importedDomainScope(domains: readonly string[]): ImportedDomainScope { + const exact = new Set() + const ancestors = new Set() + const descendantRoots = new Set() + const seen = new Set() + for (const domain of domains) { + const candidate = normalizeCookieDomain(domain) + if (!candidate || seen.has(candidate)) { + continue + } + seen.add(candidate) + const normalized = normalizeCookieImportDomain(candidate) + if (!normalized || exact.has(normalized)) { + continue + } + exact.add(normalized) + if (normalized.includes('.')) { + descendantRoots.add(normalized) + } + for (const suffix of importDomainAncestors(normalized)) { + ancestors.add(suffix) + } + } + return { exact, ancestors, descendantRoots } +} + +// Staged rows derive hostOnly from host_key, without constructing an Electron Cookie. +export function domainIsInImportedScope( + scope: ImportedDomainScope, + domain: string, + hostOnly: boolean +): boolean { + if (scope.exact.has(domain)) { + return true + } + if (!hostOnly && scope.ancestors.has(domain)) { + return true + } + return domainSuffixes(domain).some((suffix) => scope.descendantRoots.has(suffix)) +} diff --git a/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts b/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts index 5c19a557d95..50955cb3be3 100644 --- a/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts +++ b/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts @@ -1,7 +1,7 @@ import { createCipheriv, createHash, randomBytes } from 'node:crypto' import { describe, expect, it } from 'vitest' import { decryptCookieValueRaw } from './browser-cookie-decryption' -import type { EncryptionKeyResult } from './browser-cookie-sqlite' +import type { EncryptionKeyResult } from './chromium-encryption-key-contract' const HOST_KEY = '.example.com' const cbcKey = randomBytes(16) diff --git a/src/main/browser/cookies/sources/browser-cookie-decryption.ts b/src/main/browser/cookies/sources/browser-cookie-decryption.ts index 3b6fe682da5..ecf341d3763 100644 --- a/src/main/browser/cookies/sources/browser-cookie-decryption.ts +++ b/src/main/browser/cookies/sources/browser-cookie-decryption.ts @@ -1,6 +1,6 @@ import { createDecipheriv, createHash } from 'node:crypto' import type { BrowserCookieImportSummary } from '../../../../shared/browser-workspace-types' -import type { EncryptionKeyResult } from './browser-cookie-sqlite' +import type { EncryptionKeyResult } from './chromium-encryption-key-contract' // The fallback heuristic treats 8 nonprintable bytes in a 32-byte prefix as a host hash. const CHROMIUM_COOKIE_HMAC_LEN = 32 diff --git a/src/main/browser/cookies/sources/browser-cookie-firefox-import.ts b/src/main/browser/cookies/sources/browser-cookie-firefox-import.ts index 3a6bee5a5f3..a4bab1a28ee 100644 --- a/src/main/browser/cookies/sources/browser-cookie-firefox-import.ts +++ b/src/main/browser/cookies/sources/browser-cookie-firefox-import.ts @@ -5,11 +5,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { BrowserCookieImportResult } from '../../../../shared/browser-workspace-types' import { readFirefoxRowPartition } from './browser-cookie-source-partition' -import { - importValidatedCookies, - cookieImportTarget, - type CookieImportOptions -} from '../browser-cookie-import-pipeline' +import { importValidatedCookies } from '../imports/import-validated-cookies' +import { cookieImportTarget } from '../storage/browser-cookie-session-target' +import type { CookieImportOptions } from '../imports/cookie-import-contracts' import { databaseSameSite, deriveUrl, type ValidatedCookie } from './browser-cookie-validation' import type { DetectedBrowser } from './browser-cookie-source-profiles' import { diag } from '../browser-cookie-import-diagnostics' diff --git a/src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts b/src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts index 081b8442acb..76316e69c56 100644 --- a/src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts +++ b/src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts @@ -28,7 +28,7 @@ vi.mock('node:crypto', async (importOriginal) => { createDecipherivMock.mockImplementation(original.createDecipheriv) return { ...original, createDecipheriv: createDecipherivMock } }) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { setPendingCookieImport: setPendingCookieImportMock, clearPendingCookieImport: clearPendingCookieImportMock diff --git a/src/main/browser/cookies/sources/browser-cookie-key.ts b/src/main/browser/cookies/sources/browser-cookie-key.ts index 515bc0b1cc8..d239ded80df 100644 --- a/src/main/browser/cookies/sources/browser-cookie-key.ts +++ b/src/main/browser/cookies/sources/browser-cookie-key.ts @@ -9,7 +9,7 @@ import { browserRootPath, type DetectedBrowser } from './browser-cookie-source-profiles' -import type { EncryptionKeyResult } from './browser-cookie-sqlite' +import type { EncryptionKeyResult } from './chromium-encryption-key-contract' import type { LinuxCookieKeyFailure } from '../../../../shared/browser-workspace-types' const PBKDF2_ITERATIONS = 1003 diff --git a/src/main/browser/cookies/sources/browser-cookie-safari-import.ts b/src/main/browser/cookies/sources/browser-cookie-safari-import.ts index 6949769ea44..771638ac96e 100644 --- a/src/main/browser/cookies/sources/browser-cookie-safari-import.ts +++ b/src/main/browser/cookies/sources/browser-cookie-safari-import.ts @@ -2,7 +2,8 @@ import { readFileSync } from 'node:fs' import { browserCookieImportFailure } from '../../../../shared/browser-cookie-import-failure-copy' import type { BrowserCookieImportResult } from '../../../../shared/browser-workspace-types' import { decodeSafariBinaryCookies } from './browser-cookie-safari-parser' -import { importValidatedCookies, cookieImportTarget } from '../browser-cookie-import-pipeline' +import { importValidatedCookies } from '../imports/import-validated-cookies' +import { cookieImportTarget } from '../storage/browser-cookie-session-target' import type { DetectedBrowser } from './browser-cookie-source-profiles' import { diag } from '../browser-cookie-import-diagnostics' import { isMacPrivacyDenial } from './browser-cookie-macos-privacy-denial' diff --git a/src/main/browser/cookies/sources/browser-cookie-source-partition.ts b/src/main/browser/cookies/sources/browser-cookie-source-partition.ts index 36d52441f2a..2ed6dc30f22 100644 --- a/src/main/browser/cookies/sources/browser-cookie-source-partition.ts +++ b/src/main/browser/cookies/sources/browser-cookie-source-partition.ts @@ -1,4 +1,4 @@ -import type { CookieClearPartitionKey } from '../browser-cookie-import-clear' +import type { CookieClearPartitionKey } from '../storage/cookie-store-contracts' // Skip unreadable partition identities; an unpartitioned fallback would lose the site’s session. export type SourcePartitionRead = diff --git a/src/main/browser/cookies/sources/browser-cookie-validation.ts b/src/main/browser/cookies/sources/browser-cookie-validation.ts index 77feef35e81..26156f3a7a9 100644 --- a/src/main/browser/cookies/sources/browser-cookie-validation.ts +++ b/src/main/browser/cookies/sources/browser-cookie-validation.ts @@ -1,4 +1,4 @@ -import { normalizeCookieDomain } from '../browser-cookie-import-policy' +import { normalizeCookieDomain } from '../policy/cookie-domain' import { readJsonCookiePartition, type SourcePartitionRead diff --git a/src/main/browser/cookies/sources/browser-cookie-sqlite.ts b/src/main/browser/cookies/sources/chromium-cookie-time.ts similarity index 61% rename from src/main/browser/cookies/sources/browser-cookie-sqlite.ts rename to src/main/browser/cookies/sources/chromium-cookie-time.ts index 6ab9699998b..3b84a36cef2 100644 --- a/src/main/browser/cookies/sources/browser-cookie-sqlite.ts +++ b/src/main/browser/cookies/sources/chromium-cookie-time.ts @@ -1,5 +1,3 @@ -import type { LinuxCookieKeyFailure } from '../../../../shared/browser-workspace-types' - const CHROMIUM_EPOCH_OFFSET = 11644473600n export function chromiumTimestampToUnix(chromiumTs: bigint | number | string): number { @@ -19,12 +17,3 @@ export function chromiumTimestampToUnix(chromiumTs: bigint | number | string): n return 0 } } - -export type EncryptionKeyResult = - | { - mode: 'aes-128-cbc' - keysByVersion: Partial> - keyringUnavailable?: boolean - keyringFailure?: LinuxCookieKeyFailure - } - | { mode: 'aes-256-gcm'; key: Buffer } diff --git a/src/main/browser/cookies/sources/chromium-encryption-key-contract.ts b/src/main/browser/cookies/sources/chromium-encryption-key-contract.ts new file mode 100644 index 00000000000..dbbe9042843 --- /dev/null +++ b/src/main/browser/cookies/sources/chromium-encryption-key-contract.ts @@ -0,0 +1,10 @@ +import type { LinuxCookieKeyFailure } from '../../../../shared/browser-workspace-types' + +export type EncryptionKeyResult = + | { + mode: 'aes-128-cbc' + keysByVersion: Partial> + keyringUnavailable?: boolean + keyringFailure?: LinuxCookieKeyFailure + } + | { mode: 'aes-256-gcm'; key: Buffer } diff --git a/src/main/browser/cookies/staging/browser-cookie-staged-import.ts b/src/main/browser/cookies/staging/browser-cookie-staged-import.ts index 427e522ab3c..955988f0641 100644 --- a/src/main/browser/cookies/staging/browser-cookie-staged-import.ts +++ b/src/main/browser/cookies/staging/browser-cookie-staged-import.ts @@ -1,12 +1,8 @@ import { DatabaseSync } from 'node:sqlite' -import type { ImportedDomainScope } from '../browser-cookie-import-policy' -import { - domainIsInImportedScope, - importedDomainScope, - isNonTransplantableCookieDomain, - normalizeCookieDomain, - normalizeCookieImportDomain -} from '../browser-cookie-import-policy' +import type { ImportedDomainScope } from '../policy/cookie-import-scope' +import { domainIsInImportedScope, importedDomainScope } from '../policy/cookie-import-scope' +import { isNonTransplantableCookieDomain } from '../policy/cookie-import-exclusions' +import { normalizeCookieDomain, normalizeCookieImportDomain } from '../policy/cookie-domain' const IMPORT_SCOPE_TABLE = 'orca_cookie_import_scope' const IMPORT_SCOPE_FORMAT_VERSION = 1 diff --git a/src/main/browser/cookies/staging/browser-session-cookie-staging.scoped.test.ts b/src/main/browser/cookies/staging/browser-session-cookie-staging.scoped.test.ts index 1f953256ee8..be8e458f196 100644 --- a/src/main/browser/cookies/staging/browser-session-cookie-staging.scoped.test.ts +++ b/src/main/browser/cookies/staging/browser-session-cookie-staging.scoped.test.ts @@ -22,7 +22,7 @@ vi.mock('electron', () => ({ app: { getPath: appGetPathMock }, session: { fromPartition: sessionFromPartitionMock } })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { clearPendingCookieImport: clearPendingCookieImportMock } })) vi.mock('../browser-cookie-clear-store', () => ({ @@ -40,7 +40,7 @@ import { import { loadBrowserSessionMeta, persistBrowserSessionMeta -} from '../../sessions/browser-session-meta-store' +} from '../../sessions/profiles/browser-session-meta-store' const PARTITION = 'persist:test' diff --git a/src/main/browser/cookies/staging/browser-session-cookie-staging.test.ts b/src/main/browser/cookies/staging/browser-session-cookie-staging.test.ts index 2726728df8c..de360c27126 100644 --- a/src/main/browser/cookies/staging/browser-session-cookie-staging.test.ts +++ b/src/main/browser/cookies/staging/browser-session-cookie-staging.test.ts @@ -11,7 +11,7 @@ import { applyPendingBrowserCookieImports } from './browser-session-cookie-stagi import { loadBrowserSessionMeta, persistBrowserSessionMeta -} from '../../sessions/browser-session-meta-store' +} from '../../sessions/profiles/browser-session-meta-store' const defaultPartition = 'persist:orca-browser-default' const routePartition = `persist:orca-browser-v1-${'c'.repeat(64)}` diff --git a/src/main/browser/cookies/staging/browser-session-cookie-staging.ts b/src/main/browser/cookies/staging/browser-session-cookie-staging.ts index f5a40ce5614..853beb565fc 100644 --- a/src/main/browser/cookies/staging/browser-session-cookie-staging.ts +++ b/src/main/browser/cookies/staging/browser-session-cookie-staging.ts @@ -5,8 +5,8 @@ import { loadBrowserSessionMeta, persistBrowserSessionMeta, type PendingBrowserCookieImport -} from '../../sessions/browser-session-meta-store' -import { isValidPersistedBrowserSessionProfile } from '../../sessions/browser-session-persisted-profile-validation' +} from '../../sessions/profiles/browser-session-meta-store' +import { isValidPersistedBrowserSessionProfile } from '../../sessions/profiles/browser-session-persisted-profile-validation' import { renameFileWithWindowsRetry } from '../../../../shared/windows-retry-file-operations' import { applyScopedStagedCookieImport, diff --git a/src/main/browser/cookies/storage/browser-cookie-session-target.ts b/src/main/browser/cookies/storage/browser-cookie-session-target.ts new file mode 100644 index 00000000000..ad8cfc8ce65 --- /dev/null +++ b/src/main/browser/cookies/storage/browser-cookie-session-target.ts @@ -0,0 +1,13 @@ +import { session } from 'electron' +import { openCookieClearStore } from '../browser-cookie-clear-store' +import type { CookieImportTarget } from '../imports/cookie-import-contracts' + +export function cookieImportTarget(targetPartition: string): CookieImportTarget { + const targetSession = session.fromPartition(targetPartition) + return { + partition: targetPartition, + mutationLockOwner: targetSession, + openWriteStore: () => openCookieClearStore(targetSession), + flushStore: () => targetSession.cookies.flushStore() + } +} diff --git a/src/main/browser/cookies/storage/cookie-removal-url.ts b/src/main/browser/cookies/storage/cookie-removal-url.ts new file mode 100644 index 00000000000..e17dfe6fe1e --- /dev/null +++ b/src/main/browser/cookies/storage/cookie-removal-url.ts @@ -0,0 +1,8 @@ +import type { Cookie } from 'electron' + +// normalizedDomain must come from normalizeCookieDomain. +export function cookieRemovalUrl(cookie: Cookie, normalizedDomain: string): string { + const url = new URL(`${cookie.secure ? 'https' : 'http'}://${normalizedDomain}/`) + url.pathname = cookie.path?.startsWith('/') ? cookie.path : '/' + return url.toString() +} diff --git a/src/main/browser/cookies/storage/cookie-store-contracts.ts b/src/main/browser/cookies/storage/cookie-store-contracts.ts new file mode 100644 index 00000000000..0e808cfbdd3 --- /dev/null +++ b/src/main/browser/cookies/storage/cookie-store-contracts.ts @@ -0,0 +1,45 @@ +import type { Cookie, Cookies } from 'electron' +import type { CdpCookie } from '../browser-cdp-cookie' + +export type CookieClearPartitionKey = { + topLevelSite: string + hasCrossSiteAncestor: boolean +} + +export type CookieClearIdentity = { + url: string + name: string + value: string + domain?: string + hostOnly?: boolean + path?: string + secure?: boolean + httpOnly?: boolean + sameSite: Cookie['sameSite'] + expirationDate?: number + partitionKey?: CookieClearPartitionKey +} + +export type CookieClearStore = Pick & { + snapshotClearIdentities( + cookies: readonly { cookie: Cookie; url: string }[] + ): Promise + restoreClearIdentities(identities: readonly CookieClearIdentity[]): Promise +} + +// Write through CDP identities because Electron cookies.set loses partition keys. +export type CookieImportWriteStore = Pick & { + writeCookieIdentity(identity: CookieClearIdentity): Promise +} + +// Why: cookies.get() leaves out partitionKey, so a whole-jar copy reads through CDP too. +export type CookieJarCdpReadStore = { + readAllCdpCookies(): Promise +} + +// Exclude cookies.set and bulk clearData: neither preserves this per-cookie rollback contract. +export type CookieClearSession = { + cookies: Pick + snapshotClearIdentities: CookieClearStore['snapshotClearIdentities'] + restoreClearIdentities: CookieClearStore['restoreClearIdentities'] +} diff --git a/src/main/browser/desktop-browser-bridge/remote-cli-driven-workspaces.ts b/src/main/browser/desktop-browser-bridge/remote-cli-driven-workspaces.ts index 4bd313e042a..d01bebcdb5f 100644 --- a/src/main/browser/desktop-browser-bridge/remote-cli-driven-workspaces.ts +++ b/src/main/browser/desktop-browser-bridge/remote-cli-driven-workspaces.ts @@ -1,7 +1,7 @@ // SSH-driven workspaces lose programmatic clipboard reads until quit; user paste still works. import { webContents } from 'electron' import { parseChromeExtensionUrl } from '../../../shared/browser/extensions/browser-extension-url' -import { browserManager } from '../browser-manager' +import { browserManager } from '../guest-lifecycle/manager/browser-manager' const drivenWorkspaceIds = new Set() diff --git a/src/main/browser/document-preview/doc-preview-file-reader.ts b/src/main/browser/document-preview/doc-preview-file-reader.ts index 457b19e8eef..69597092c42 100644 --- a/src/main/browser/document-preview/doc-preview-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-file-reader.ts @@ -20,6 +20,7 @@ import { } from './doc-preview-grant-registry' import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/runtime-environment-registry-root' import { readDocPreviewTerminalFile } from './doc-preview-terminal-file-reader' +import type { RuntimeDocPreviewReadParams } from './doc-preview-runtime-read-contract' const DOC_PREVIEW_READ_TIMEOUT_MS = 15_000 // Why: under files.readDocPreviewChunk's 512 KiB cap, and a multiple of 3 so its base64 has no padding. @@ -109,14 +110,6 @@ function toOutcome(source: PreviewFileBytes, contentType: string): DocPreviewRea : UNSUPPORTED_ASSET_OUTCOME } -export type RuntimeDocPreviewReadParams = { - worktree: string - relativePath: string - entryRelativePath: string - implicitRootRelativePath: string | null - authorizedRootRelativePaths: string[] -} - async function readRuntimeDocPreviewFile( environmentId: string, params: RuntimeDocPreviewReadParams diff --git a/src/main/browser/document-preview/doc-preview-protocol.ts b/src/main/browser/document-preview/doc-preview-protocol.ts index f57b7089bbd..afee86c27e8 100644 --- a/src/main/browser/document-preview/doc-preview-protocol.ts +++ b/src/main/browser/document-preview/doc-preview-protocol.ts @@ -4,7 +4,7 @@ import { DOC_PREVIEW_SCHEME, parseDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme' -import { installBrowserSessionPartitionPolicies } from '../sessions/browser-session-partition-policies' +import { installBrowserSessionPartitionPolicies } from '../sessions/partition-policies/browser-session-partition-policies' import { readDocPreviewFile } from './doc-preview-file-reader' import { publishDocPreviewFailure } from './doc-preview-failure-notice' import { getDocPreviewGrant } from './doc-preview-grant-registry' diff --git a/src/main/browser/document-preview/doc-preview-runtime-read-contract.ts b/src/main/browser/document-preview/doc-preview-runtime-read-contract.ts new file mode 100644 index 00000000000..fcccc32afd0 --- /dev/null +++ b/src/main/browser/document-preview/doc-preview-runtime-read-contract.ts @@ -0,0 +1,7 @@ +export type RuntimeDocPreviewReadParams = { + worktree: string + relativePath: string + entryRelativePath: string + implicitRootRelativePath: string | null + authorizedRootRelativePaths: string[] +} diff --git a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts index 47862cf864f..3e024512e7b 100644 --- a/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts +++ b/src/main/browser/document-preview/doc-preview-terminal-file-reader.ts @@ -8,7 +8,7 @@ import { toRuntimeWorktreeRelativePath, type DocPreviewGrant } from './doc-preview-grant-registry' -import type { RuntimeDocPreviewReadParams } from './doc-preview-file-reader' +import type { RuntimeDocPreviewReadParams } from './doc-preview-runtime-read-contract' import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' const TIMEOUT_MS = 15_000 diff --git a/src/main/browser/downloads/browser-session-download-policy.ts b/src/main/browser/downloads/browser-session-download-policy.ts new file mode 100644 index 00000000000..09f69a5c171 --- /dev/null +++ b/src/main/browser/downloads/browser-session-download-policy.ts @@ -0,0 +1,29 @@ +import { browserManager } from '../guest-lifecycle/manager/browser-manager' +import { isRemoteCliDrivenGuest } from '../desktop-browser-bridge/remote-cli-driven-workspaces' +import { noticeDocPreviewDownloadBlocked } from '../document-preview/doc-preview-download-block-notice' + +export const handleWillDownload = ( + event: Electron.Event, + item: Electron.DownloadItem, + webContents: Electron.WebContents +): void => { + // Prevent SSH-driven pages from writing host-chosen files into desktop Downloads. + if (isRemoteCliDrivenGuest(webContents.id)) { + event.preventDefault() + console.info('[desktop-browser-bridge] refused a download from a page an SSH host drives') + return + } + browserManager.handleGuestWillDownload({ guestWebContentsId: webContents.id, item }) +} + +// will-download omits the partition; attach each partition's selected policy to its session. +export const handleDeniedWillDownload = ( + event: Electron.Event, + _item: Electron.DownloadItem, + webContents: Electron.WebContents +): void => { + event.preventDefault() + noticeDocPreviewDownloadBlocked(webContents) +} + +export type BrowserPartitionDownloadPolicy = 'route' | 'deny' diff --git a/src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.test.ts b/src/main/browser/electron-fixtures/popup-identity-electron-probe.test.ts similarity index 95% rename from src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.test.ts rename to src/main/browser/electron-fixtures/popup-identity-electron-probe.test.ts index 698ecd932fa..609f2d65897 100644 --- a/src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.test.ts +++ b/src/main/browser/electron-fixtures/popup-identity-electron-probe.test.ts @@ -12,7 +12,7 @@ vi.mock('@orca/process-host', () => ({ spawnProcess: mocks.spawn })) vi.mock('playwright', () => ({ chromium: { connectOverCDP: vi.fn(async () => ({ close: mocks.closeBrowser })) } })) -vi.mock('../../identity/browser-session-ua-cdp-collector', () => ({ +vi.mock('../identity/wire-probes/browser-session-ua-cdp-collector', () => ({ waitForBrowserCdpEndpoint: vi.fn(async () => undefined) })) diff --git a/src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts b/src/main/browser/electron-fixtures/popup-identity-electron-probe.ts similarity index 94% rename from src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts rename to src/main/browser/electron-fixtures/popup-identity-electron-probe.ts index a775b3e50af..6fc29438a1a 100644 --- a/src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts +++ b/src/main/browser/electron-fixtures/popup-identity-electron-probe.ts @@ -6,8 +6,8 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { chromium } from 'playwright' import { build } from 'vite' -import { waitForBrowserCdpEndpoint } from '../../identity/browser-session-ua-cdp-collector' -import { resolveElectronProbeLaunch } from '../../electron-fixtures/electron-probe-display-launch' +import { waitForBrowserCdpEndpoint } from '../identity/wire-probes/browser-session-ua-cdp-collector' +import { resolveElectronProbeLaunch } from './electron-probe-display-launch' export function createPopupIdentityProbeRoot(): string { return mkdtempSync(join(tmpdir(), 'orca-popup-identity-')) diff --git a/src/main/browser/extensions/actions/browser-extension-popup-host.ts b/src/main/browser/extensions/actions/browser-extension-popup-host.ts index 7c5dd37d6f9..d2a32d6ebf4 100644 --- a/src/main/browser/extensions/actions/browser-extension-popup-host.ts +++ b/src/main/browser/extensions/actions/browser-extension-popup-host.ts @@ -4,7 +4,7 @@ import { getChromeExtensionOrigin, isSameExtensionNavigation } from '../../../../shared/browser/extensions/browser-extension-url' -import { allowPageUnload } from '../../guest-lifecycle/browser-guest-unload-policy' +import { allowPageUnload } from '../../guest-lifecycle/navigation/browser-guest-unload-policy' import { BrowserExtensionApiError } from '../api-runtime/browser-extension-namespace-registry' import { BROWSER_EXTENSION_POPUP_MAX, diff --git a/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts b/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts index 84bcd4fa363..3059c59b0bf 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar-electron-fixture.ts @@ -2,8 +2,8 @@ import { app, BaseWindow, BrowserWindow, protocol, ipcMain, session } from 'elec import { renameSync, writeFileSync } from 'node:fs' import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' -import { browserManager } from '../../browser-manager' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' import { attachBrowserExtensionsToProfileSession } from '../profile-sessions/browser-extension-session-loader' diff --git a/src/main/browser/extensions/actions/browser-extension-toolbar-pins.ts b/src/main/browser/extensions/actions/browser-extension-toolbar-pins.ts index 9db27cadca2..086cfd53b50 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar-pins.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar-pins.ts @@ -1,4 +1,4 @@ -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { withExtensionEnabled, withoutExtension diff --git a/src/main/browser/extensions/actions/browser-extension-toolbar.ts b/src/main/browser/extensions/actions/browser-extension-toolbar.ts index c7546303b53..eb0bb73c23a 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar.ts @@ -1,5 +1,5 @@ import { webContents } from 'electron' -import { noteBrowserExtensionUserGesture } from '../api/permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import type { BrowserExtensionActionResult } from '../../../../shared/browser/extensions/browser-extension-types' import { BROWSER_EXTENSION_POPUP_REQUEST_CHANNEL, @@ -9,7 +9,7 @@ import { type BrowserExtensionToolbarAction, type BrowserExtensionToolbarState } from '../../../../shared/browser/extensions/browser-extension-toolbar-types' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent, getBrowserExtensionProfileIdForSession diff --git a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts index 713e2e3ea4a..c1a882d765d 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-api-host.test.ts @@ -52,7 +52,7 @@ vi.mock('electron', async () => { } } }) -vi.mock('../../browser-manager', () => ({ browserManager: {} })) +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('../../../ipc/browser/browser-tab-registration-wait', () => ({ waitForTabRegistration: vi.fn() })) diff --git a/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts b/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts index e119ea1b9a0..32e8638c2c9 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-electron-fixture.ts @@ -3,8 +3,8 @@ import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' -import { browserManager } from '../../browser-manager' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from './browser-extension-api-scheme' import { attachBrowserExtensionsToProfileSession } from '../profile-sessions/browser-extension-session-loader' diff --git a/src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts b/src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts index cff175f71bb..4e55897c27a 100644 --- a/src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts +++ b/src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts @@ -9,7 +9,7 @@ vi.mock('electron', () => ({ ipcMain: { removeHandler: vi.fn(), handle: vi.fn() }, webFrameMain: { fromId: vi.fn() } })) -vi.mock('../../browser-manager', () => ({ browserManager: {} })) +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('../../../ipc/browser/browser-tab-registration-wait', () => ({ waitForTabRegistration: vi.fn() })) diff --git a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts index 9c6d2083c11..0b5419b68ba 100644 --- a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts +++ b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts @@ -39,7 +39,7 @@ vi.mock('electron', () => ({ fromId: (processId: number, routingId: number) => mocks.frames.get(`${processId}:${routingId}`) } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getWebContentsIdByTabId: () => new Map(), getGuestWebContentsId: (id: string) => (id === 'gesture-page' ? 700 : null) @@ -70,7 +70,7 @@ await import('./permissions') const { getBrowserExtensionProfileStateStore } = await import('../profile-storage/browser-extension-profile-state-store') const menuHost = await import('../context-menus/browser-extension-context-menu-host') -const webRequest = await import('../browser-extension-web-request') +const webRequest = await import('../requests/browser-extension-web-request-observer') const { setBrowserExtensionSupportEnabled } = await import('../browser-extension-support') const contexts = await import('../api-runtime/browser-extension-contexts') const eventDispatch = await import('../api-runtime/browser-extension-event-dispatch') diff --git a/src/main/browser/extensions/api/commands.ts b/src/main/browser/extensions/api/commands.ts index 2d360905381..c44acd3552b 100644 --- a/src/main/browser/extensions/api/commands.ts +++ b/src/main/browser/extensions/api/commands.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { KEYBINDING_DEFINITIONS, keybindingMatchesAction } from '../../../../shared/keybindings' import { isAgentInjectingInput } from '../../cdp/input/agent-input-injection' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent, getBrowserExtensionProfileIdForSession @@ -22,7 +22,7 @@ import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' import { runBrowserExtensionToolbarAction } from '../actions/browser-extension-toolbar' -import { noteBrowserExtensionUserGesture } from './permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' function isOrcaShortcut(input: Electron.Input): boolean { const overrides = browserManager.getKeybindingOverrides() diff --git a/src/main/browser/extensions/api/cookies.ts b/src/main/browser/extensions/api/cookies.ts index 92e5d49c716..d28b9ca95f3 100644 --- a/src/main/browser/extensions/api/cookies.ts +++ b/src/main/browser/extensions/api/cookies.ts @@ -9,7 +9,7 @@ import { } from '../api-runtime/browser-extension-namespace-registry' import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' import { listBrowserExtensionTabs } from '../tabs-and-windows/browser-extension-tab-model' -import { browserExtensionHostPatternsInSession } from './permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' /** Each extension session has one cookie store; Chrome names the regular store "0". */ const STORE_ID = '0' diff --git a/src/main/browser/extensions/api/declarative-net-request-test-match.ts b/src/main/browser/extensions/api/declarative-net-request-test-match.ts index 4b8dd84c158..564602f9bd9 100644 --- a/src/main/browser/extensions/api/declarative-net-request-test-match.ts +++ b/src/main/browser/extensions/api/declarative-net-request-test-match.ts @@ -1,9 +1,15 @@ import { z } from 'zod' import { createDnrRequestState } from '../declarative-net-request/request-state' import { DnrEngine } from '../declarative-net-request/engine' -import type { DnrHostAccess } from '../declarative-net-request/extension-matcher' -import { compareActions, type DnrRequestAction } from '../declarative-net-request/ruleset-matcher' -import { DNR_REQUEST_METHODS, DNR_RESOURCE_TYPES } from '../declarative-net-request/rule-types' +import type { DnrHostAccess } from '../declarative-net-request/matching/extension-matcher' +import { + compareActions, + type DnrRequestAction +} from '../declarative-net-request/matching/ruleset-matcher' +import { + DNR_REQUEST_METHODS, + DNR_RESOURCE_TYPES +} from '../declarative-net-request/rule-compilation/rule-types' import { BrowserExtensionApiError } from '../api-runtime/browser-extension-namespace-registry' import type { DnrExtensionRules } from '../declarative-net-request/session/browser-extension-dnr-extension-rules' import { DNR_ERRORS } from '../declarative-net-request/session/browser-extension-dnr-limits' diff --git a/src/main/browser/extensions/api/declarative-net-request.ts b/src/main/browser/extensions/api/declarative-net-request.ts index 010fef4770f..beaeba5e2a6 100644 --- a/src/main/browser/extensions/api/declarative-net-request.ts +++ b/src/main/browser/extensions/api/declarative-net-request.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { isDnrRegexSupported } from '../declarative-net-request/regex-filter' +import { isDnrRegexSupported } from '../declarative-net-request/regex/regex-filter' import { hasBrowserExtensionActiveTab } from '../permissions/browser-extension-active-tab' import { DnrApiError, diff --git a/src/main/browser/extensions/api/downloads.test.ts b/src/main/browser/extensions/api/downloads.test.ts index 6a5131f32fc..ebc9613d1ef 100644 --- a/src/main/browser/extensions/api/downloads.test.ts +++ b/src/main/browser/extensions/api/downloads.test.ts @@ -15,7 +15,7 @@ const mocks = vi.hoisted(() => { vi.mock('electron', () => ({ webContents: { fromId: () => undefined } })) vi.mock('./downloads-save-as', () => ({ chooseDownloadSavePath: mocks.chooseSavePath })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getTabIdForWebContentsId: () => 'tab-1', requestDownloadFilename: mocks.requestDownloadFilename, diff --git a/src/main/browser/extensions/api/downloads.ts b/src/main/browser/extensions/api/downloads.ts index eb8342ea774..c8b551732b2 100644 --- a/src/main/browser/extensions/api/downloads.ts +++ b/src/main/browser/extensions/api/downloads.ts @@ -4,7 +4,7 @@ import { getChromeExtensionOrigin, parseChromeExtensionUrl } from '../../../../shared/browser/extensions/browser-extension-url' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' import { getBrowserExtensionContextSignal } from '../api-runtime/browser-extension-context-lifetime' import { getHostSessionState } from '../api-runtime/browser-extension-contexts' diff --git a/src/main/browser/extensions/api/management.test.ts b/src/main/browser/extensions/api/management.test.ts index e16e2e09e3d..5ad72c91ec4 100644 --- a/src/main/browser/extensions/api/management.test.ts +++ b/src/main/browser/extensions/api/management.test.ts @@ -13,7 +13,7 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getEnabledExtensionIds: () => [...mocks.enabled] } })) vi.mock('../installation/browser-extension-install-store', () => ({ @@ -25,7 +25,9 @@ vi.mock('../browser-extension-management', () => ({ vi.mock('../installation/browser-extension-list-changes', () => ({ notifyBrowserExtensionListChanged: mocks.notify })) -vi.mock('./permissions', () => ({ hasBrowserExtensionUserGesture: () => mocks.gesture })) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + hasBrowserExtensionUserGesture: () => mocks.gesture +})) const registry = await import('../api-runtime/browser-extension-namespace-registry') const { registerManagementNamespace } = await import('./management') diff --git a/src/main/browser/extensions/api/management.ts b/src/main/browser/extensions/api/management.ts index 22dbc257e1d..086676b213b 100644 --- a/src/main/browser/extensions/api/management.ts +++ b/src/main/browser/extensions/api/management.ts @@ -2,7 +2,7 @@ import { z } from 'zod' import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' import type { InstalledBrowserExtension } from '../../../../shared/browser/extensions/browser-extension-types' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { getBrowserExtensionInstallStore } from '../installation/browser-extension-install-store' import { notifyBrowserExtensionListChanged } from '../installation/browser-extension-list-changes' import { setBrowserExtensionEnabled } from '../browser-extension-management' @@ -12,7 +12,7 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { hasBrowserExtensionUserGesture } from './permissions' +import { hasBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' /** * chrome.management for extensions that declare "management": Orca's installed list as the diff --git a/src/main/browser/extensions/api/notifications.test.ts b/src/main/browser/extensions/api/notifications.test.ts index 1f305468c42..4443dcd4b8b 100644 --- a/src/main/browser/extensions/api/notifications.test.ts +++ b/src/main/browser/extensions/api/notifications.test.ts @@ -31,13 +31,16 @@ vi.mock('../../../window/foreground-activation-policy', () => ({ isBackgroundLaunch: () => mocks.background })) vi.mock('../api-runtime/browser-extension-api-host', () => ({ emitBrowserExtensionEvent: vi.fn() })) -vi.mock('./permissions', () => ({ noteBrowserExtensionUserGesture: vi.fn() })) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + noteBrowserExtensionUserGesture: vi.fn() +})) const { registerNotificationsNamespace } = await import('./notifications') const { getBrowserExtensionNamespace } = await import('../api-runtime/browser-extension-namespace-registry') const { emitBrowserExtensionEvent } = await import('../api-runtime/browser-extension-api-host') -const { noteBrowserExtensionUserGesture } = await import('./permissions') +const { noteBrowserExtensionUserGesture } = + await import('../permissions/browser-extension-user-gesture') registerNotificationsNamespace() const extension = { id: 'a'.repeat(32), path: join('/ext', 'root') } diff --git a/src/main/browser/extensions/api/notifications.ts b/src/main/browser/extensions/api/notifications.ts index 067c8546ed3..e397022f9a5 100644 --- a/src/main/browser/extensions/api/notifications.ts +++ b/src/main/browser/extensions/api/notifications.ts @@ -14,7 +14,7 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { noteBrowserExtensionUserGesture } from './permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' const optionsSchema = z .object({ diff --git a/src/main/browser/extensions/api/permissions.ts b/src/main/browser/extensions/api/permissions.ts index 79154866d1f..d575757ce9e 100644 --- a/src/main/browser/extensions/api/permissions.ts +++ b/src/main/browser/extensions/api/permissions.ts @@ -1,3 +1,5 @@ +import { readBrowserExtensionProfileGrants } from '../permissions/browser-extension-session-permissions' +import { hasBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import { z } from 'zod' import { emitBrowserExtensionEvent, @@ -11,7 +13,6 @@ import { type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' import { - browserExtensionHostPatterns, containsBrowserExtensionPermissions, effectiveBrowserExtensionPermissions, planBrowserExtensionPermissionRemoval, @@ -25,10 +26,8 @@ import { getBrowserExtensionProfileStateStore } from '../profile-storage/browser import { getHostSessionState } from '../api-runtime/browser-extension-contexts' import { getBrowserExtensionContextSignal } from '../api-runtime/browser-extension-context-lifetime' import { getDnrSessionRuntime } from '../declarative-net-request/session/browser-extension-dnr-session' -import { observeBrowserExtensionWebRequests } from '../browser-extension-web-request' +import { observeBrowserExtensionWebRequests } from '../requests/browser-extension-web-request-observer' -const USER_GESTURE_WINDOW_MS = 5_000 -const recentGestures = new WeakMap() const pendingRequests = new Set() const permissionsSchema = z @@ -40,51 +39,6 @@ function gestureKey(profileId: string, extensionId: string): string { return `${profileId}\n${extensionId}` } -/** - * Chrome lets permissions.request run only inside a user gesture. Orca records the gestures it - * delivers to an extension (menu click, command, notification click, toolbar click). - */ -export function noteBrowserExtensionUserGesture( - session: Electron.Session, - extensionId: string -): void { - const state = getHostSessionState(session) - if (!state) { - return - } - const signal = getBrowserExtensionContextSignal(state, extensionId) - recentGestures.set(signal, Date.now()) -} - -export function hasBrowserExtensionUserGesture(caller: BrowserExtensionCaller): boolean { - if (caller.userGesture === true) { - return true - } - const state = getHostSessionState(caller.session) - if (!state) { - return false - } - const signal = getBrowserExtensionContextSignal(state, caller.extension.id) - const at = recentGestures.get(signal) - return at !== undefined && !signal.aborted && Date.now() - at <= USER_GESTURE_WINDOW_MS -} - -function readGrants(profileId: string, extensionId: string) { - return getBrowserExtensionProfileStateStore().read(profileId, extensionId) -} - -/** Manifest host patterns plus origins the user granted in this session's profile. */ -export function browserExtensionHostPatternsInSession( - extension: Electron.Extension, - session: Electron.Session -): string[] { - const profileId = getBrowserExtensionProfileIdForSession(session) - const grants = profileId - ? readGrants(profileId, extension.id) - : { grantedPermissions: [], grantedOrigins: [] } - return browserExtensionHostPatterns(extension.manifest, grants) -} - function emitChange( caller: BrowserExtensionCaller, event: 'onAdded' | 'onRemoved', @@ -108,7 +62,7 @@ async function request( const { extension, browserProfileId } = caller const plan = planBrowserExtensionPermissionRequest( extension.manifest, - readGrants(browserProfileId, extension.id), + readBrowserExtensionProfileGrants(browserProfileId, extension.id), wanted ) if (plan.kind === 'invalid') { @@ -161,7 +115,7 @@ async function remove( const { extension, browserProfileId } = caller const plan = planBrowserExtensionPermissionRemoval( extension.manifest, - readGrants(browserProfileId, extension.id), + readBrowserExtensionProfileGrants(browserProfileId, extension.id), wanted ) if (plan.kind === 'invalid') { @@ -178,21 +132,23 @@ async function remove( export function registerPermissionsNamespace(): void { setBrowserExtensionGrantedPermissionsLookup((extension, session) => { const profileId = getBrowserExtensionProfileIdForSession(session) - return profileId ? readGrants(profileId, extension.id).grantedPermissions : [] + return profileId + ? readBrowserExtensionProfileGrants(profileId, extension.id).grantedPermissions + : [] }) registerBrowserExtensionNamespace('permissions', { methods: { contains: defineBrowserExtensionMethod(z.tuple([permissionsSchema]), (caller, wanted) => containsBrowserExtensionPermissions( caller.extension.manifest, - readGrants(caller.browserProfileId, caller.extension.id), + readBrowserExtensionProfileGrants(caller.browserProfileId, caller.extension.id), wanted ) ), getAll: defineBrowserExtensionMethod(z.tuple([]), (caller) => effectiveBrowserExtensionPermissions( caller.extension.manifest, - readGrants(caller.browserProfileId, caller.extension.id) + readBrowserExtensionProfileGrants(caller.browserProfileId, caller.extension.id) ) ), request: defineBrowserExtensionMethod(z.tuple([permissionsSchema]), request), diff --git a/src/main/browser/extensions/api/runtime.ts b/src/main/browser/extensions/api/runtime.ts index 0c7d9c29919..4b0f8d16974 100644 --- a/src/main/browser/extensions/api/runtime.ts +++ b/src/main/browser/extensions/api/runtime.ts @@ -1,31 +1,9 @@ +import { openBrowserExtensionOptionsPage } from '../tabs-and-windows/browser-extension-options-page' import { z } from 'zod' -import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' import { - BrowserExtensionApiError, defineBrowserExtensionMethod, registerBrowserExtensionNamespace } from '../api-runtime/browser-extension-namespace-registry' -import { openBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' - -function optionsPagePath(extension: Electron.Extension): string | null { - const manifest: { options_ui?: { page?: unknown }; options_page?: unknown } = - extension.manifest ?? {} - const page = manifest.options_ui?.page ?? manifest.options_page - return typeof page === 'string' && page.length > 0 ? page : null -} - -/** Opens the extension's options page as an Orca tab in the given browser profile. */ -export async function openBrowserExtensionOptionsPage( - browserProfileId: string, - extension: Electron.Extension -): Promise { - const page = optionsPagePath(extension) - if (!page) { - throw new BrowserExtensionApiError('This extension has no options page') - } - const url = new URL(page.replace(/^\/+/, ''), `${getChromeExtensionOrigin(extension.id)}/`) - await openBrowserExtensionTab(browserProfileId, url.toString(), true) -} /** Only what Electron leaves unimplemented (lifecycle events: runtime-lifecycle); the rest is native. */ export function registerRuntimeNamespace(): void { diff --git a/src/main/browser/extensions/api/storage-sync.ts b/src/main/browser/extensions/api/storage-sync.ts index 16fc39273c2..17862c39604 100644 --- a/src/main/browser/extensions/api/storage-sync.ts +++ b/src/main/browser/extensions/api/storage-sync.ts @@ -6,10 +6,8 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { - getBrowserExtensionSyncStorageStore, - type BrowserExtensionSyncItems -} from '../profile-storage/browser-extension-sync-storage-store' +import { getBrowserExtensionSyncStorageStore } from '../profile-storage/browser-extension-sync-storage-store' +import type { BrowserExtensionProfileDocumentItems } from '../profile-storage/browser-extension-profile-document-store' /** * Electron disables chrome.storage.sync ("not available in this instance of Chrome"), so Orca @@ -50,7 +48,7 @@ function itemBytes(key: string, value: unknown): number { return Buffer.byteLength(key) + Buffer.byteLength(JSON.stringify(value)) } -function bytesInUse(items: BrowserExtensionSyncItems, keys: string[]): number { +function bytesInUse(items: BrowserExtensionProfileDocumentItems, keys: string[]): number { return keys.reduce( (total, key) => (Object.hasOwn(items, key) ? total + itemBytes(key, items[key]) : total), 0 @@ -65,15 +63,15 @@ function sameValue(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right) } -function readItems(caller: BrowserExtensionCaller): BrowserExtensionSyncItems { +function readItems(caller: BrowserExtensionCaller): BrowserExtensionProfileDocumentItems { return getBrowserExtensionSyncStorageStore().read(caller.browserProfileId, caller.extension.id) } /** Saves `next`; returns and announces the changes for every key whose value differs. */ function commit( caller: BrowserExtensionCaller, - current: BrowserExtensionSyncItems, - next: BrowserExtensionSyncItems, + current: BrowserExtensionProfileDocumentItems, + next: BrowserExtensionProfileDocumentItems, keys: Iterable ): StorageChanges { const changes: StorageChanges = {} @@ -103,7 +101,7 @@ function commit( function get( caller: BrowserExtensionCaller, keys: z.infer -): BrowserExtensionSyncItems { +): BrowserExtensionProfileDocumentItems { const items = readItems(caller) if (keys == null) { return { ...items } @@ -113,7 +111,7 @@ function get( [keys].flat().flatMap((key) => (Object.hasOwn(items, key) ? [[key, items[key]]] : [])) ) } - const result: BrowserExtensionSyncItems = {} + const result: BrowserExtensionProfileDocumentItems = {} for (const [key, fallback] of Object.entries(keys)) { const value = Object.hasOwn(items, key) ? items[key] : toStoredValue(fallback) if (value !== undefined) { @@ -123,7 +121,10 @@ function get( return result } -function set(caller: BrowserExtensionCaller, input: BrowserExtensionSyncItems): StorageChanges { +function set( + caller: BrowserExtensionCaller, + input: BrowserExtensionProfileDocumentItems +): StorageChanges { const current = readItems(caller) const next = { ...current } let total = bytesInUse(current, Object.keys(current)) diff --git a/src/main/browser/extensions/api/tabs-capture.test.ts b/src/main/browser/extensions/api/tabs-capture.test.ts index df386f80fd7..d009b5637e7 100644 --- a/src/main/browser/extensions/api/tabs-capture.test.ts +++ b/src/main/browser/extensions/api/tabs-capture.test.ts @@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => { vi.mock('electron', () => ({ webFrameMain: { fromId: vi.fn() } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { holdPaintForCapture: mocks.holdPaint } })) @@ -28,7 +28,7 @@ vi.mock('../tabs-and-windows/browser-extension-window-model', () => ({ WINDOW_ID_CURRENT: -2, getBrowserExtensionWindow: (id: number) => (mocks.windows.has(id) ? {} : null) })) -vi.mock('./permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: () => mocks.hostPatterns })) vi.mock('../permissions/browser-extension-active-tab', () => ({ diff --git a/src/main/browser/extensions/api/tabs-capture.ts b/src/main/browser/extensions/api/tabs-capture.ts index 0b5386de259..70ab5e02b5d 100644 --- a/src/main/browser/extensions/api/tabs-capture.ts +++ b/src/main/browser/extensions/api/tabs-capture.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { consumeBrowserExtensionCaptureQuota } from '../api-runtime/browser-extension-capture-quota' import { parseChromeExtensionUrl } from '../../../../shared/browser/extensions/browser-extension-url' import { isChromeWebStoreUrl } from '../../../../shared/browser/extensions/browser-extension-webstore' @@ -17,7 +17,7 @@ import { WINDOW_ID_CURRENT, getBrowserExtensionWindow } from '../tabs-and-windows/browser-extension-window-model' -import { browserExtensionHostPatternsInSession } from './permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' // Chrome's default JPEG quality for tabs.captureVisibleTab. const DEFAULT_JPEG_QUALITY = 90 diff --git a/src/main/browser/extensions/api/tabs.ts b/src/main/browser/extensions/api/tabs.ts index 04d1e8f34f9..b69233ca4d3 100644 --- a/src/main/browser/extensions/api/tabs.ts +++ b/src/main/browser/extensions/api/tabs.ts @@ -1,6 +1,7 @@ /// +import { requireOpenableUrl } from '../tabs-and-windows/browser-extension-requested-navigation' + import { z } from 'zod' -import { resolveBrowserExtensionRequestedUrl } from '../../../../shared/browser/extensions/browser-extension-url' import { BrowserExtensionApiError, defineBrowserExtensionMethod, @@ -76,22 +77,6 @@ const updatePropertiesSchema = z .partial() .loose() -/** Resolves an extension-requested URL through Orca's rules; extension pages must be loaded in `sess`. */ -export function requireOpenableUrl( - caller: BrowserExtensionCaller, - rawUrl: string | undefined, - sess: Electron.Session -): string { - const resolved = resolveBrowserExtensionRequestedUrl(rawUrl, caller.extension.id) - if ( - !resolved || - (resolved.kind === 'extension' && !sess.extensions.getExtension(resolved.extensionId)) - ) { - throw new BrowserExtensionApiError(`Cannot open URL: ${rawUrl ?? ''}`) - } - return resolved.url -} - async function createTab( caller: BrowserExtensionCaller, url: string, diff --git a/src/main/browser/extensions/api/web-navigation.ts b/src/main/browser/extensions/api/web-navigation.ts index 50959520698..d9b28b16b79 100644 --- a/src/main/browser/extensions/api/web-navigation.ts +++ b/src/main/browser/extensions/api/web-navigation.ts @@ -1,4 +1,9 @@ /// +import { + chromeFrameId, + chromeFrameDocument +} from '../tabs-and-windows/browser-extension-frame-projection' + import { webFrameMain } from 'electron' import { z } from 'zod' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' @@ -19,32 +24,6 @@ import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' -/** - * Chrome frame ids: 0 for a tab's main frame, the frame-tree-node id otherwise. Electron's own - * content-script `sender.frameId` uses the same numbering, so tabs.sendMessage targets line up. - */ -export function chromeFrameId(frame: Electron.WebFrameMain): number { - return frame.parent ? frame.frameTreeNodeId : 0 -} - -function chromeParentFrameId(frame: Electron.WebFrameMain): number { - return frame.parent ? chromeFrameId(frame.parent) : -1 -} - -/** Chrome's frame fields; `documentId` is left out where the document does not exist yet. */ -export function chromeFrameDocument(frame: Electron.WebFrameMain, withDocument: boolean) { - return { - frameId: chromeFrameId(frame), - parentFrameId: chromeParentFrameId(frame), - ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) } : {}), - ...(frame.parent - ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent.frameTreeNodeId) } - : {}), - frameType: frame.parent ? ('sub_frame' as const) : ('outermost_frame' as const), - documentLifecycle: 'active' as const - } -} - function frameDetails( tabId: number, frame: Electron.WebFrameMain, diff --git a/src/main/browser/extensions/api/windows.ts b/src/main/browser/extensions/api/windows.ts index dec336d5512..dcf3834777f 100644 --- a/src/main/browser/extensions/api/windows.ts +++ b/src/main/browser/extensions/api/windows.ts @@ -21,7 +21,7 @@ import { presentBrowserExtensionWindow, type BrowserExtensionWindowEntry } from '../tabs-and-windows/browser-extension-window-model' -import { requireOpenableUrl } from './tabs' +import { requireOpenableUrl } from '../tabs-and-windows/browser-extension-requested-navigation' const windowIdSchema = z.number().int() const queryOptionsSchema = z diff --git a/src/main/browser/extensions/browser-extension-management.test.ts b/src/main/browser/extensions/browser-extension-management.test.ts index 356326785cd..76cb80c9de7 100644 --- a/src/main/browser/extensions/browser-extension-management.test.ts +++ b/src/main/browser/extensions/browser-extension-management.test.ts @@ -16,14 +16,16 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getEnabledExtensionIds: () => [], updateEnabledExtensionIds: vi.fn(), getProfile: () => ({ id: 'default' }) } })) -vi.mock('./api/runtime', () => ({ openBrowserExtensionOptionsPage: vi.fn() })) +vi.mock('./tabs-and-windows/browser-extension-options-page', () => ({ + openBrowserExtensionOptionsPage: vi.fn() +})) vi.mock('./installation/browser-extension-install-store', () => ({ getBrowserExtensionInstallStore: () => mocks.store })) diff --git a/src/main/browser/extensions/browser-extension-management.ts b/src/main/browser/extensions/browser-extension-management.ts index c6ef6cfdec6..dbd4c9e178d 100644 --- a/src/main/browser/extensions/browser-extension-management.ts +++ b/src/main/browser/extensions/browser-extension-management.ts @@ -4,8 +4,8 @@ import type { BrowserExtensionListResult, InstalledBrowserExtension } from '../../../shared/browser/extensions/browser-extension-types' -import { browserSessionRegistry } from '../sessions/browser-session-registry' -import { openBrowserExtensionOptionsPage } from './api/runtime' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' +import { openBrowserExtensionOptionsPage } from './tabs-and-windows/browser-extension-options-page' import { getBrowserExtensionInstallStore } from './installation/browser-extension-install-store' import { reloadBrowserExtensionWhereEnabled } from './profile-sessions/browser-extension-profile-reload' import { @@ -32,7 +32,7 @@ import { } from './profile-sessions/browser-extension-load-errors' import { notifyBrowserExtensionListChanged } from './installation/browser-extension-list-changes' import { reviewHeldBrowserExtensionUpdate } from './web-store/browser-extension-webstore-updater' -import { withBrowserExtensionLock } from './installation/browser-extension-webstore-install' +import { withBrowserExtensionLock } from './installation/browser-extension-mutation-lock' import { isBrowserExtensionSupportEnabled } from './browser-extension-support' import { withExtensionEnabled, diff --git a/src/main/browser/extensions/browser-extension-startup.ts b/src/main/browser/extensions/browser-extension-startup.ts index 340d29d7245..d388a50d1e7 100644 --- a/src/main/browser/extensions/browser-extension-startup.ts +++ b/src/main/browser/extensions/browser-extension-startup.ts @@ -10,14 +10,14 @@ import { isBrowserExtensionSupportEnabled, setBrowserExtensionSupportEnabled } from './browser-extension-support' -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' import { attachBrowserExtensionsToProfileSession, detachBrowserExtensionsFromAllProfileSessions } from './profile-sessions/browser-extension-session-loader' import { notifyBrowserExtensionActionsChanged } from './actions/browser-extension-action-registry' import { registerBrowserExtensionNamespaces } from './register-browser-extension-namespaces' -import { observeBrowserExtensionTabLifecycle } from './api/tabs-lifecycle' +import { observeBrowserExtensionTabLifecycle } from './tabs-and-windows/browser-extension-tab-lifecycle' import { observeBrowserExtensionWebNavigation } from './api/web-navigation' import { observeBrowserExtensionCommands } from './api/commands' import { observeBrowserExtensionDnrContents } from './declarative-net-request/session/browser-extension-dnr-contents' diff --git a/src/main/browser/extensions/browser-extension-web-request.ts b/src/main/browser/extensions/browser-extension-web-request.ts deleted file mode 100644 index 43df3da9131..00000000000 --- a/src/main/browser/extensions/browser-extension-web-request.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { CHROME_WEB_STORE_ORIGIN } from '../../../shared/browser/extensions/browser-extension-webstore' -import { - installBrowserSessionHeadersReceived, - installBrowserSessionRequestLifecycle, - removeBrowserSessionHeadersReceived, - removeBrowserSessionRequestLifecycle -} from '../sessions/requests/browser-session-request-decisions' -import { - setBrowserSessionWebRequestObserver, - type ObservedWebRequestDetails, - type ObservedWebRequestEvent -} from '../sessions/requests/browser-session-web-request-observer' -import { chromeFrameDocument } from './api/web-navigation' -import { browserExtensionHostPatternsInSession } from './api/permissions' -import { - emitBrowserExtensionEvent, - getBrowserExtensionProfileIdForSession -} from './api-runtime/browser-extension-api-host' -import { browserExtensionEventHasListener } from './api-runtime/browser-extension-contexts' -import { matchesExtensionMatchPattern } from './permissions/browser-extension-match-pattern' -import { extensionHasPermission } from './api-runtime/browser-extension-namespace-registry' -import { hasBrowserExtensionHostPermission } from './permissions/browser-extension-permission-grants' -import { canExtensionAccessRequest } from './permissions/browser-extension-request-host-access' -import { resolveBrowserExtensionTab } from './tabs-and-windows/browser-extension-tab-model' - -/** - * chrome.webRequest, observed rather than blocking. Electron 43 delivers no webRequest events to - * MV3 workers, and Orca's own session handlers switch Electron's extension webRequest off anyway, - * so Orca forwards what its handlers see. MV3 store extensions cannot block requests in Chrome - * either (webRequestBlocking is policy-only), so nothing they could do is lost. - */ - -type ChromeResourceType = - | 'main_frame' - | 'sub_frame' - | 'stylesheet' - | 'script' - | 'image' - | 'font' - | 'object' - | 'xmlhttprequest' - | 'ping' - | 'csp_report' - | 'media' - | 'websocket' - | 'other' - -const CHROME_RESOURCE_TYPES = new Map([ - ['mainFrame', 'main_frame'], - ['subFrame', 'sub_frame'], - ['stylesheet', 'stylesheet'], - ['script', 'script'], - ['image', 'image'], - ['font', 'font'], - ['object', 'object'], - ['xhr', 'xmlhttprequest'], - ['ping', 'ping'], - ['cspReport', 'csp_report'], - ['media', 'media'], - ['webSocket', 'websocket'] -]) - -/** Electron's resourceType → Chrome's, shared by webRequest and declarativeNetRequest. */ -export function chromeResourceType(resourceType: string): ChromeResourceType { - return CHROME_RESOURCE_TYPES.get(resourceType) ?? 'other' -} - -// Chrome hides these unless a listener asks for 'extraHeaders'. -const HIDDEN_REQUEST_HEADERS = new Set(['accept-language', 'accept-encoding', 'referer', 'cookie']) -const HIDDEN_RESPONSE_HEADERS = new Set(['set-cookie']) - -export type ChromeWebRequestDetails = { - requestId: string - url: string - method: string - frameId: number - parentFrameId: number - tabId: number - windowId: number - type: string - timeStamp: number - frameType?: 'outermost_frame' | 'sub_frame' - documentId?: string - parentDocumentId?: string - documentLifecycle?: 'active' - requestHeaders?: { name: string; value: string }[] - responseHeaders?: { name: string; value: string }[] - statusCode?: number - statusLine?: string - fromCache?: boolean - ip?: string - redirectUrl?: string - error?: string -} - -function requestHeaderList(headers: Record): { name: string; value: string }[] { - return Object.entries(headers) - .filter(([name]) => !HIDDEN_REQUEST_HEADERS.has(name.toLowerCase())) - .map(([name, value]) => ({ name, value })) -} - -function responseHeaderList(headers: Record): { name: string; value: string }[] { - return Object.entries(headers) - .filter(([name]) => !HIDDEN_RESPONSE_HEADERS.has(name.toLowerCase())) - .flatMap(([name, values]) => values.map((value) => ({ name, value }))) -} - -type WebRequestFrameFields = Pick< - ChromeWebRequestDetails, - | 'frameId' - | 'parentFrameId' - | 'frameType' - | 'documentId' - | 'parentDocumentId' - | 'documentLifecycle' -> - -/** A navigation request has no document yet; any other request belongs to its frame's current one. */ -function frameFields(details: ObservedWebRequestDetails): WebRequestFrameFields { - if (details.resourceType === 'mainFrame') { - return { - frameId: 0, - parentFrameId: -1, - frameType: 'outermost_frame', - documentLifecycle: 'active' - } - } - const frame = details.frame && !details.frame.isDestroyed() ? details.frame : null - return frame - ? chromeFrameDocument(frame, details.resourceType !== 'subFrame') - : { frameId: 0, parentFrameId: -1 } -} - -export function toChromeWebRequestDetails( - details: ObservedWebRequestDetails, - tab: { tabId: number; windowId: number }, - frame: WebRequestFrameFields -): ChromeWebRequestDetails { - const type = chromeResourceType(details.resourceType) - return { - requestId: String(details.id), - url: details.url, - method: details.method, - ...frame, - ...tab, - type, - timeStamp: details.timestamp, - ...(details.requestHeaders - ? { requestHeaders: requestHeaderList(details.requestHeaders) } - : {}), - ...(details.responseHeaders - ? { responseHeaders: responseHeaderList(details.responseHeaders) } - : {}), - ...(details.statusCode !== undefined ? { statusCode: details.statusCode } : {}), - ...(details.statusLine !== undefined ? { statusLine: details.statusLine } : {}), - ...(details.fromCache !== undefined ? { fromCache: details.fromCache } : {}), - ...(details.ip ? { ip: details.ip } : {}), - ...(details.redirectURL ? { redirectUrl: details.redirectURL } : {}), - ...(details.error ? { error: details.error } : {}) - } -} - -/** Main-side pre-filter against one listener's chrome.webRequest.RequestFilter. */ -export function webRequestFilterMatches( - filter: unknown, - details: ChromeWebRequestDetails -): boolean { - if (filter === null || typeof filter !== 'object') { - return true - } - const fields = new Map(Object.entries(filter)) - const urls = fields.get('urls') - if ( - Array.isArray(urls) && - !urls.some( - (pattern) => typeof pattern === 'string' && matchesExtensionMatchPattern(pattern, details.url) - ) - ) { - return false - } - const types = fields.get('types') - if (Array.isArray(types) && !types.includes(details.type)) { - return false - } - const tabId = fields.get('tabId') - const windowId = fields.get('windowId') - return ( - (typeof tabId !== 'number' || tabId === details.tabId) && - (typeof windowId !== 'number' || windowId === details.windowId) - ) -} - -const WEB_URL = /^(?:https?|wss?):/i - -/** WebRequestPermissions::HideRequest: requests extensions never see or act on. */ -export function isRequestHiddenFromExtensions(details: { - url: string - webContentsId?: number - initiatorOrigin?: string -}): boolean { - if (!WEB_URL.test(details.url)) { - return true - } - // Orca's own main-process requests carry neither a webContents nor an initiator. - if (details.webContentsId === undefined && details.initiatorOrigin === undefined) { - return true - } - return ( - details.url.startsWith(`${CHROME_WEB_STORE_ORIGIN}/`) || - details.url.startsWith('https://chrome.google.com/webstore') - ) -} - -function forward( - session: Electron.Session, - event: ObservedWebRequestEvent, - details: ObservedWebRequestDetails -): void { - if ( - isRequestHiddenFromExtensions(details) || - !getBrowserExtensionProfileIdForSession(session) || - !browserExtensionEventHasListener(session, 'webRequest', event) - ) { - return - } - const entry = - details.webContentsId === undefined ? null : resolveBrowserExtensionTab(details.webContentsId) - const chromeDetails = toChromeWebRequestDetails( - details, - entry ? { tabId: entry.contents.id, windowId: entry.windowId } : { tabId: -1, windowId: -1 }, - frameFields(details) - ) - const request = { - url: details.url, - initiator: details.initiatorOrigin ?? null, - tabId: chromeDetails.tabId, - type: chromeDetails.type - } - emitBrowserExtensionEvent( - { session }, - 'webRequest', - event, - (extension) => { - const patterns = browserExtensionHostPatternsInSession(extension, session) - return canExtensionAccessRequest(extension.id, request, (url) => - hasBrowserExtensionHostPermission(patterns, url) - ) - ? [chromeDetails] - : null - }, - (filter) => webRequestFilterMatches(filter, chromeDetails) - ) -} - -const observedSessions = new WeakSet() -const watchedSessions = new WeakSet() -const OBSERVE_ALL = { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] } - -/** The events Orca does not otherwise handle, installed once a webRequest extension loads. */ -function observeRemainingEvents(session: Electron.Session): void { - if (observedSessions.has(session)) { - return - } - observedSessions.add(session) - const { webRequest } = session - webRequest.onSendHeaders(OBSERVE_ALL, (details) => forward(session, 'onSendHeaders', details)) - installBrowserSessionHeadersReceived(session) - webRequest.onResponseStarted(OBSERVE_ALL, (details) => - forward(session, 'onResponseStarted', details) - ) - webRequest.onBeforeRedirect(OBSERVE_ALL, (details) => - forward(session, 'onBeforeRedirect', details) - ) - installBrowserSessionRequestLifecycle(session) -} - -export function observeBrowserExtensionWebRequests(session: Electron.Session): void { - const maybeObserve = (extension: Electron.Extension): void => { - if (extensionHasPermission(extension, 'webRequest', session)) { - observeRemainingEvents(session) - } - } - if (!watchedSessions.has(session)) { - watchedSessions.add(session) - session.extensions.on('extension-ready', (_event, extension) => maybeObserve(extension)) - } - session.extensions.getAllExtensions().forEach(maybeObserve) -} - -/** Extensions turned off: hand the session's request path back to Orca's own handlers alone. */ -export function stopObservingBrowserExtensionWebRequests(session: Electron.Session): void { - removeBrowserSessionHeadersReceived(session) - removeBrowserSessionRequestLifecycle(session) - if (!observedSessions.delete(session)) { - return - } - const { webRequest } = session - webRequest.onSendHeaders(null) - webRequest.onResponseStarted(null) - webRequest.onBeforeRedirect(null) -} - -export function installBrowserExtensionWebRequestForwarding(): void { - setBrowserSessionWebRequestObserver(forward) -} diff --git a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts index ee17628fa2e..47ef817d418 100644 --- a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts +++ b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts @@ -7,8 +7,12 @@ const mocks = vi.hoisted(() => ({ })) const VAULT = 'a'.repeat(32) -vi.mock('../api/web-navigation', () => ({ chromeFrameId: () => 0 })) -vi.mock('../api/permissions', () => ({ noteBrowserExtensionUserGesture: vi.fn() })) +vi.mock('../tabs-and-windows/browser-extension-frame-projection', () => ({ + chromeFrameId: () => 0 +})) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + noteBrowserExtensionUserGesture: vi.fn() +})) vi.mock('../api-runtime/browser-extension-api-host', () => ({ emitBrowserExtensionEvent: mocks.emit, getBrowserExtensionProfileIdForSession: () => 'default' @@ -37,7 +41,6 @@ vi.mock('../tabs-and-windows/browser-extension-tab-model', () => ({ resolveBrowserExtensionTab: () => null, describeBrowserExtensionTab: vi.fn() })) - import { createContextMenuItem } from './browser-extension-context-menu-model' import * as menuHost from './browser-extension-context-menu-host' diff --git a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts index 4e748f9d52c..892d6d346a7 100644 --- a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts +++ b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts @@ -4,8 +4,8 @@ import type { BrowserExtensionContextMenuGroup, BrowserExtensionContextMenuPayload } from '../../../../shared/browser/extensions/browser-extension-context-menu-types' -import { chromeFrameId } from '../api/web-navigation' -import { noteBrowserExtensionUserGesture } from '../api/permissions' +import { chromeFrameId } from '../tabs-and-windows/browser-extension-frame-projection' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import { emitBrowserExtensionEvent, getBrowserExtensionProfileIdForSession diff --git a/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts b/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts index 7d1b9380cba..11daab5e627 100644 --- a/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts +++ b/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest' import { createDnrRequestState } from './request-state' import { DnrEngine } from './engine' -import { applyDnrRequestHeaderActions } from './header-modification' +import { applyDnrRequestHeaderActions } from './header-actions/header-modification' import type { DnrRequestInfo } from './request-context' -import type { DnrRule } from './rule-types' -import { buildDnrRuleset } from './ruleset-builder' +import type { DnrRule } from './rule-compilation/rule-types' +import { buildDnrRuleset } from './rule-compilation/ruleset-builder' const OLD = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' const NEW = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' diff --git a/src/main/browser/extensions/declarative-net-request/engine.test.ts b/src/main/browser/extensions/declarative-net-request/engine.test.ts index 7caf03bf64a..cea3c2e0cc5 100644 --- a/src/main/browser/extensions/declarative-net-request/engine.test.ts +++ b/src/main/browser/extensions/declarative-net-request/engine.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest' import { createDnrRequestState } from './request-state' import { DnrEngine, type DnrEvaluateOptions } from './engine' import type { DnrRequestInfo } from './request-context' -import type { DnrRule, DnrRulesetSource } from './rule-types' -import { buildDnrRuleset } from './ruleset-builder' +import type { DnrRule, DnrRulesetSource } from './rule-compilation/rule-types' +import { buildDnrRuleset } from './rule-compilation/ruleset-builder' const OLD = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' diff --git a/src/main/browser/extensions/declarative-net-request/engine.ts b/src/main/browser/extensions/declarative-net-request/engine.ts index 4e7bb97ac82..66431fb0d7e 100644 --- a/src/main/browser/extensions/declarative-net-request/engine.ts +++ b/src/main/browser/extensions/declarative-net-request/engine.ts @@ -2,8 +2,8 @@ import { DnrExtensionMatcher, type DnrFrameAllowState, type DnrHostAccess -} from './extension-matcher' -import { sameDomainOrHost } from './domain-matching' +} from './matching/extension-matcher' +import { sameDomainOrHost } from './matching/domain-matching' import { createDnrRequestContext, dnrOriginHost, @@ -11,8 +11,8 @@ import { type DnrRequestInfo, type DnrResponseHeaders } from './request-context' -import { DnrCandidatePostings } from './candidate-postings' -import type { DnrRulesetIndex } from './ruleset-index' +import { DnrCandidatePostings } from './indexing/candidate-postings' +import type { DnrRulesetIndex } from './indexing/ruleset-index' import { crossExtensionRank, emptyDnrEvaluation, @@ -25,8 +25,8 @@ import { DnrRulesetMatcher, type DnrRequestAction, type DnrStage -} from './ruleset-matcher' -import type { DnrRulesetSource } from './rule-types' +} from './matching/ruleset-matcher' +import type { DnrRulesetSource } from './rule-compilation/rule-types' // RulesetManager (ruleset_manager.cc) plus the per-request bookkeeping WebRequestInfo keeps // between stages (see request-state.ts). diff --git a/src/main/browser/extensions/declarative-net-request/header-modification.ts b/src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/header-modification.ts rename to src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts index a6591cb454f..e9f11134eab 100644 --- a/src/main/browser/extensions/declarative-net-request/header-modification.ts +++ b/src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts @@ -1,5 +1,5 @@ import { REQUEST_HEADER_APPEND_DELIMITERS, type DnrHeaderModification } from './header-rules' -import type { DnrRequestAction } from './ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' // Applies modifyHeaders actions the way web_request_api_helpers.cc does // (ModifyRequestHeadersForAction, ModifyResponseHeadersForAction, DNRHeaderAction). diff --git a/src/main/browser/extensions/declarative-net-request/header-rules.ts b/src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts similarity index 94% rename from src/main/browser/extensions/declarative-net-request/header-rules.ts rename to src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts index c3c9ec95050..090f01a21f3 100644 --- a/src/main/browser/extensions/declarative-net-request/header-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts @@ -1,6 +1,10 @@ -import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import type { DnrHeaderInfo, DnrHeaderOperation, DnrModifyHeaderInfo } from './rule-types' -import { toLowerAscii } from './url-text' +import { dnrRuleProblem, type DnrRuleProblem } from '../rule-compilation/parse-errors' +import type { + DnrHeaderInfo, + DnrHeaderOperation, + DnrModifyHeaderInfo +} from '../rule-compilation/rule-types' +import { toLowerAscii } from '../matching/url-text' // Header validation from indexed_rule.cc (ValidateHeadersForModification, // ValidateResponseHeadersForMatching) and the request-header append allowlist with each diff --git a/src/main/browser/extensions/declarative-net-request/candidate-postings.ts b/src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/candidate-postings.ts rename to src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts index 56a141cf882..040249be382 100644 --- a/src/main/browser/extensions/declarative-net-request/candidate-postings.ts +++ b/src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts @@ -1,4 +1,4 @@ -import type { DnrRequestContext } from './request-context' +import type { DnrRequestContext } from '../request-context' import type { DnrRulePartition, DnrRulesetIndex } from './ruleset-index' // Engine-wide inverted index over every attached ruleset: n-gram id or domain -> the partitions diff --git a/src/main/browser/extensions/declarative-net-request/ngram-dictionary.ts b/src/main/browser/extensions/declarative-net-request/indexing/ngram-dictionary.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/ngram-dictionary.ts rename to src/main/browser/extensions/declarative-net-request/indexing/ngram-dictionary.ts diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-index.ts b/src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts similarity index 96% rename from src/main/browser/extensions/declarative-net-request/ruleset-index.ts rename to src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts index 93200a76ef4..d022f52d441 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-index.ts +++ b/src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts @@ -1,8 +1,8 @@ -import { hostLabelSuffixes, type DnrDomainList } from './domain-matching' -import type { DnrIndexedRule } from './indexed-rule' +import { hostLabelSuffixes, type DnrDomainList } from '../matching/domain-matching' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' import { dnrNgramDictionary, patternNgrams } from './ngram-dictionary' -import type { DnrRequestContext } from './request-context' -import { toLowerAscii } from './url-text' +import type { DnrRequestContext } from '../request-context' +import { toLowerAscii } from '../matching/url-text' // One url_pattern_index (url_pattern_index.cc UrlPatternIndexBuilder): rules keyed by a 5-gram // of their filter. Rules without one are keyed by an included request or initiator domain, diff --git a/src/main/browser/extensions/declarative-net-request/domain-matching.ts b/src/main/browser/extensions/declarative-net-request/matching/domain-matching.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/domain-matching.ts rename to src/main/browser/extensions/declarative-net-request/matching/domain-matching.ts diff --git a/src/main/browser/extensions/declarative-net-request/extension-matcher.ts b/src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/extension-matcher.ts rename to src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts index da2b2371b35..8e38a49a07c 100644 --- a/src/main/browser/extensions/declarative-net-request/extension-matcher.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts @@ -1,4 +1,4 @@ -import type { DnrRequestContext } from './request-context' +import type { DnrRequestContext } from '../request-context' import { compareActions, isAllowAction, diff --git a/src/main/browser/extensions/declarative-net-request/rule-matching.ts b/src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts similarity index 95% rename from src/main/browser/extensions/declarative-net-request/rule-matching.ts rename to src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts index 5ec676d9cfa..fea70d5dd5e 100644 --- a/src/main/browser/extensions/declarative-net-request/rule-matching.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts @@ -1,7 +1,7 @@ import { hostMatchesDomainLists } from './domain-matching' -import type { DnrHeaderCondition } from './header-rules' -import type { DnrIndexedRule } from './indexed-rule' -import type { DnrRequestContext } from './request-context' +import type { DnrHeaderCondition } from '../header-actions/header-rules' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' +import type { DnrRequestContext } from '../request-context' // Per-rule checks from url_pattern_index.cc (DoesRuleFlagsMatch, DoesOriginMatchInitiatorDomainList, // DoesURLMatchRequestDomainList) and request_params.cc DoEmbedderConditionsMatch. diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts b/src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts similarity index 92% rename from src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts rename to src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts index 8cf3f82bf9e..3d49c2f2c51 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts @@ -1,13 +1,17 @@ -import type { DnrHeaderModification } from './header-rules' -import type { DnrIndexedRule } from './indexed-rule' -import { transformDnrUrl, upgradeDnrUrl } from './redirect-url' -import { applyRegexSubstitution } from './regex-filter' -import { isCollapsibleType, type DnrRequestContext } from './request-context' -import { ELEMENT_TYPE } from './rule-flags' +import type { DnrHeaderModification } from '../header-actions/header-rules' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' +import { transformDnrUrl, upgradeDnrUrl } from '../redirect-actions/redirect-url' +import { applyRegexSubstitution } from '../regex/regex-filter' +import { isCollapsibleType, type DnrRequestContext } from '../request-context' +import { ELEMENT_TYPE } from '../rule-compilation/rule-flags' import { regexRuleMetadataMatches, urlRuleMatches } from './rule-matching' -import { compareRulePriority, type DnrRulePartition, type DnrRulesetIndex } from './ruleset-index' -import type { DnrRulesetSource } from './rule-types' -import { dnrPublicRulesetId, dnrRulesetOrdinal } from './rule-types' +import { + compareRulePriority, + type DnrRulePartition, + type DnrRulesetIndex +} from '../indexing/ruleset-index' +import type { DnrRulesetSource } from '../rule-compilation/rule-types' +import { dnrPublicRulesetId, dnrRulesetOrdinal } from '../rule-compilation/rule-types' // One ruleset's matcher: ruleset_matcher.cc, extension_url_pattern_index_matcher.cc, // regex_rules_matcher.cc and ruleset_matcher_base.cc. diff --git a/src/main/browser/extensions/declarative-net-request/url-pattern.test.ts b/src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-pattern.test.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts diff --git a/src/main/browser/extensions/declarative-net-request/url-pattern.ts b/src/main/browser/extensions/declarative-net-request/matching/url-pattern.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-pattern.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-pattern.ts diff --git a/src/main/browser/extensions/declarative-net-request/url-text.ts b/src/main/browser/extensions/declarative-net-request/matching/url-text.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-text.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-text.ts diff --git a/src/main/browser/extensions/declarative-net-request/redirect-url.test.ts b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts similarity index 94% rename from src/main/browser/extensions/declarative-net-request/redirect-url.test.ts rename to src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts index cdadd533660..bb32dd224b4 100644 --- a/src/main/browser/extensions/declarative-net-request/redirect-url.test.ts +++ b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' -import { sameDomainOrHost } from './domain-matching' +import { sameDomainOrHost } from '../matching/domain-matching' import { parseDnrRedirect, transformDnrUrl } from './redirect-url' -import { isDnrRuleProblem } from './parse-errors' -import type { DnrUrlTransform } from './rule-types' +import { isDnrRuleProblem } from '../rule-compilation/parse-errors' +import type { DnrUrlTransform } from '../rule-compilation/rule-types' function transform(url: string, spec: DnrUrlTransform): string | null { const parsed = parseDnrRedirect({ transform: spec }, 1, 'ext') diff --git a/src/main/browser/extensions/declarative-net-request/redirect-url.ts b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/redirect-url.ts rename to src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts index be584833a37..e3087ffdd7f 100644 --- a/src/main/browser/extensions/declarative-net-request/redirect-url.ts +++ b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts @@ -1,5 +1,5 @@ -import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import type { DnrRedirect, DnrUrlTransform } from './rule-types' +import { dnrRuleProblem, type DnrRuleProblem } from '../rule-compilation/parse-errors' +import type { DnrRedirect, DnrUrlTransform } from '../rule-compilation/rule-types' // Redirect parsing (indexed_rule.cc ParseRedirect/ValidateTransform, flat_ruleset_indexer.cc // BuildTransformOffset) and application (ruleset_matcher_base.cc GetTransformedURL, diff --git a/src/main/browser/extensions/declarative-net-request/regex-char-set.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-char-set.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-char-set.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-char-set.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-filter.test.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-filter.test.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-filter.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-filter.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-filter.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-filter.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-piece.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-piece.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-piece.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-piece.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-repetition.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-repetition.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-repetition.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-repetition.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-translation.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-translation.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-translation.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-translation.ts diff --git a/src/main/browser/extensions/declarative-net-request/request-context.ts b/src/main/browser/extensions/declarative-net-request/request-context.ts index 9e878bfe10e..5a01843437f 100644 --- a/src/main/browser/extensions/declarative-net-request/request-context.ts +++ b/src/main/browser/extensions/declarative-net-request/request-context.ts @@ -1,9 +1,9 @@ -import { hostLabelSuffixes, sameDomainOrHost } from './domain-matching' -import { dnrNgramDictionary } from './ngram-dictionary' -import { ELEMENT_TYPE, requestMethodBit, resourceTypeBit } from './rule-flags' -import type { DnrResourceType } from './rule-types' -import type { DnrUrlText } from './url-pattern' -import { dnrUrlHost, dnrUrlText, toLowerAscii } from './url-text' +import { hostLabelSuffixes, sameDomainOrHost } from './matching/domain-matching' +import { dnrNgramDictionary } from './indexing/ngram-dictionary' +import { ELEMENT_TYPE, requestMethodBit, resourceTypeBit } from './rule-compilation/rule-flags' +import type { DnrResourceType } from './rule-compilation/rule-types' +import type { DnrUrlText } from './matching/url-pattern' +import { dnrUrlHost, dnrUrlText, toLowerAscii } from './matching/url-text' // Everything a rule looks at for one request, computed once and shared by every ruleset // (request_params.cc RequestParams). diff --git a/src/main/browser/extensions/declarative-net-request/request-state.ts b/src/main/browser/extensions/declarative-net-request/request-state.ts index 2b17dc9e628..f29eb39df77 100644 --- a/src/main/browser/extensions/declarative-net-request/request-state.ts +++ b/src/main/browser/extensions/declarative-net-request/request-state.ts @@ -1,4 +1,4 @@ -import { compareActions, isAllowAction, type DnrRequestAction } from './ruleset-matcher' +import { compareActions, isAllowAction, type DnrRequestAction } from './matching/ruleset-matcher' // What WebRequestInfo carries for one request between onBeforeRequest and onHeadersReceived // (dnr_actions, max_priority_allow_action), and the event router's merge between the stages diff --git a/src/main/browser/extensions/declarative-net-request/indexed-rule.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts similarity index 96% rename from src/main/browser/extensions/declarative-net-request/indexed-rule.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts index 0e8898e6599..b935d4f1872 100644 --- a/src/main/browser/extensions/declarative-net-request/indexed-rule.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts @@ -3,10 +3,10 @@ import { parseResponseHeaderConditions, type DnrHeaderCondition, type DnrHeaderModification -} from './header-rules' +} from '../header-actions/header-rules' import { dnrRuleProblem, isDnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import { parseDnrRedirect, type DnrRedirectSpec } from './redirect-url' -import { isValidRegexSubstitution, translateDnrRegex } from './regex-filter' +import { parseDnrRedirect, type DnrRedirectSpec } from '../redirect-actions/redirect-url' +import { isValidRegexSubstitution, translateDnrRegex } from '../regex/regex-filter' import { emptyConditionListProblem, parseRuleConditionFields, @@ -14,8 +14,8 @@ import { } from './rule-conditions' import { indexedRulePriority } from './rule-flags' import type { DnrActionType, DnrRule } from './rule-types' -import { DnrUrlPatternMatcher, parseUrlFilter } from './url-pattern' -import { isAsciiText, toLowerAscii } from './url-text' +import { DnrUrlPatternMatcher, parseUrlFilter } from '../matching/url-pattern' +import { isAsciiText, toLowerAscii } from '../matching/url-text' // IndexedRule::CreateIndexedRule (indexed_rule.cc). Checks run in Chromium's order so the // first problem reported is the one Chrome would report. diff --git a/src/main/browser/extensions/declarative-net-request/parse-errors.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/parse-errors.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/parse-errors.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/parse-errors.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-conditions.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts similarity index 97% rename from src/main/browser/extensions/declarative-net-request/rule-conditions.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts index df1506dc306..fc44fcc1e8e 100644 --- a/src/main/browser/extensions/declarative-net-request/rule-conditions.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts @@ -1,4 +1,4 @@ -import { DnrDomainList } from './domain-matching' +import { DnrDomainList } from '../matching/domain-matching' import { dnrRuleProblem, isDnrRuleProblem, type DnrRuleProblem } from './parse-errors' import { ELEMENT_TYPE, @@ -9,7 +9,7 @@ import { ruleMethodBit } from './rule-flags' import type { DnrRule } from './rule-types' -import { isAsciiText, toLowerAscii } from './url-text' +import { isAsciiText, toLowerAscii } from '../matching/url-text' // Condition parsing steps of IndexedRule::CreateIndexedRule (indexed_rule.cc): // ComputeRequestMethods, ComputeElementTypes, CanonicalizeDomains and tab ids. diff --git a/src/main/browser/extensions/declarative-net-request/rule-flags.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-flags.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-flags.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-flags.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-schema.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-schema.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-schema.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-schema.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-types.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-types.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-types.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-types.ts diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-builder.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/ruleset-builder.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts index 33fd81070ea..4705a27f540 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-builder.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts @@ -2,7 +2,7 @@ import { createIndexedRule } from './indexed-rule' import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' import { readDnrRuleJson } from './rule-schema' import type { DnrRulesetSource } from './rule-types' -import { DnrRulesetIndex } from './ruleset-index' +import { DnrRulesetIndex } from '../indexing/ruleset-index' // RulesetSource::IndexRules (ruleset_source.cc). Static rulesets skip bad rules with warnings; // updateDynamicRules / updateSessionRules reject the whole update on the first bad rule. diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts index 9581670859c..e4edf987e07 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts @@ -1,6 +1,6 @@ import type { DnrEngine } from '../engine' -import { readDnrRuleJson } from '../rule-schema' -import type { DnrRule, DnrRulesetSource } from '../rule-types' +import { readDnrRuleJson } from '../rule-compilation/rule-schema' +import type { DnrRule, DnrRulesetSource } from '../rule-compilation/rule-types' import { DNR_API_CONSTANTS, DNR_ERRORS, diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts index f132f16584b..4a04c618c1a 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { DnrEngine } from '../engine' import { createDnrRequestState } from '../request-state' -import { buildDnrRuleset } from '../ruleset-builder' +import { buildDnrRuleset } from '../rule-compilation/ruleset-builder' import { DnrFrameTracker } from './browser-extension-dnr-frames' const EXT = 'f'.repeat(32) diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts index e607c45d0a4..8e203a098e3 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts @@ -1,5 +1,5 @@ import type { DnrEngine, DnrFrameCommit } from '../engine' -import type { DnrFrameAllowState } from '../extension-matcher' +import type { DnrFrameAllowState } from '../matching/extension-matcher' import type { DnrResponseHeaders } from '../request-context' /** What a frame's navigation request carried, which its committed document is matched with. */ diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts index f2dce544d0d..f0c34c3e39c 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts @@ -1,4 +1,4 @@ -import type { DnrRule } from '../rule-types' +import type { DnrRule } from '../rule-compilation/rule-types' /** chrome.declarativeNetRequest constants (declarative_net_request.webidl, Chromium 150). */ export const DNR_API_CONSTANTS = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts index 2df5534cedd..3c6f6baeb01 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' import { DnrMatchedRules } from './browser-extension-dnr-matched-rules' const EXT = 'e'.repeat(32) diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts index 7d1245cf3a0..1a1d93ba192 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts @@ -1,4 +1,4 @@ -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' /** getMatchedRules' MatchedRuleInfo. */ export type DnrMatchedRuleInfo = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts index 0fec7e7570e..61945867460 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts @@ -37,7 +37,7 @@ const { attachBrowserExtensionDnr, getDnrSessionRuntime } = await import('./browser-extension-dnr-session') const { observeBrowserExtensionDnrContents } = await import('./browser-extension-dnr-contents') await import('../../actions/browser-extension-action-registry') -await import('../../browser-extension-web-request') +await import('../../requests/browser-extension-web-request-observer') const BLOCKER = 'c'.repeat(32) const PAGE = 'https://site.example' diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts index 76fd9ef456b..77c4ec418db 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts @@ -1,15 +1,18 @@ import type { BrowserSessionRequestDecider } from '../../../sessions/requests/browser-session-request-decisions' import { createDnrRequestState, type DnrRequestState } from '../request-state' import type { DnrEvaluateOptions } from '../engine' -import { applyDnrRequestHeaderActions, applyDnrResponseHeaderActions } from '../header-modification' +import { + applyDnrRequestHeaderActions, + applyDnrResponseHeaderActions +} from '../header-actions/header-modification' import type { DnrRequestInfo, DnrResponseHeaders } from '../request-context' -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' import { getDnrSessionRuntime, type DnrSessionRuntime } from './browser-extension-dnr-session' import { extensionHasPermission } from '../../api-runtime/browser-extension-namespace-registry' import { chromeResourceType, isRequestHiddenFromExtensions -} from '../../browser-extension-web-request' +} from '../../requests/browser-extension-request-classification' type RequestDetails = { id: number diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts index 294812e4037..2eb66ca91ec 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts @@ -1,8 +1,11 @@ import { readFile } from 'node:fs/promises' import { isAbsolute, relative, resolve } from 'node:path' -import { buildDnrRulesetInSlices, type DnrInvalidRulePolicy } from '../ruleset-builder' -import type { DnrRulesetIndex } from '../ruleset-index' -import type { DnrRulesetSource } from '../rule-types' +import { + buildDnrRulesetInSlices, + type DnrInvalidRulePolicy +} from '../rule-compilation/ruleset-builder' +import type { DnrRulesetIndex } from '../indexing/ruleset-index' +import type { DnrRulesetSource } from '../rule-compilation/rule-types' /** One manifest declarative_net_request.rule_resources entry. */ export type DnrManifestRuleset = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts index df9c0fea925..a3560b0bf83 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts @@ -1,6 +1,6 @@ import { app } from 'electron' import { z } from 'zod' -import { BrowserExtensionSyncStorageStore } from '../../profile-storage/browser-extension-sync-storage-store' +import { BrowserExtensionProfileDocumentStore } from '../../profile-storage/browser-extension-profile-document-store' import { getBrowserExtensionProfileDataDirectory } from '../../profile-storage/browser-extension-profile-data-directory' /** @@ -19,11 +19,11 @@ const dnrStateSchema = z.object({ export type BrowserExtensionDnrState = z.infer -let store: BrowserExtensionSyncStorageStore | null = null +let store: BrowserExtensionProfileDocumentStore | null = null -export function getBrowserExtensionDnrStore(): BrowserExtensionSyncStorageStore { +export function getBrowserExtensionDnrStore(): BrowserExtensionProfileDocumentStore { if (!store) { - const created = new BrowserExtensionSyncStorageStore( + const created = new BrowserExtensionProfileDocumentStore( getBrowserExtensionProfileDataDirectory(), 'declarative-net-request' ) diff --git a/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts b/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts new file mode 100644 index 00000000000..41d9d6215a9 --- /dev/null +++ b/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts @@ -0,0 +1,27 @@ +const busyExtensionIds = new Set() + +export class BrowserExtensionBusyError extends Error { + constructor() { + super('This extension is already being installed or removed') + } +} + +/** Serializes install, update and uninstall of one extension id. */ +export async function withBrowserExtensionLock( + extensionId: string, + action: () => Promise +): Promise { + if (busyExtensionIds.has(extensionId)) { + throw new BrowserExtensionBusyError() + } + busyExtensionIds.add(extensionId) + try { + return await action() + } finally { + busyExtensionIds.delete(extensionId) + } +} + +export function isBrowserExtensionBusy(extensionId: string): boolean { + return busyExtensionIds.has(extensionId) +} diff --git a/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts b/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts index 72a6e9aa4fa..54374209dba 100644 --- a/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts +++ b/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts @@ -8,6 +8,7 @@ import { extensionIdFromPublicKey, type VerifiedCrx } from './browser-extension- import { generateCrxTestKey, type CrxTestKey } from './browser-extension-crx-fixture' import type * as InstallStoreModule from './browser-extension-install-store' import type * as InstallModule from './browser-extension-webstore-install' +import type * as MutationLockModule from './browser-extension-mutation-lock' const state = vi.hoisted(() => { const enabled: Record = {} @@ -21,12 +22,14 @@ const state = vi.hoisted(() => { }) vi.mock('electron', () => ({ app: { getPath: () => state.userData, on: vi.fn() } })) -vi.mock('../api/runtime', () => ({ openBrowserExtensionOptionsPage: vi.fn() })) +vi.mock('../tabs-and-windows/browser-extension-options-page', () => ({ + openBrowserExtensionOptionsPage: vi.fn() +})) vi.mock('../web-store/browser-extension-webstore-updater', () => ({ reviewHeldBrowserExtensionUpdate: vi.fn() })) vi.mock('../browser-extension-support', () => ({ isBrowserExtensionSupportEnabled: () => true })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { listProfiles: () => [{ id: 'default' }, { id: 'work' }], getProfile: (id: string) => ({ id }), @@ -50,6 +53,7 @@ vi.mock('../profile-sessions/browser-extension-session-loader', () => ({ let key: CrxTestKey let extensionId: string let install: typeof InstallModule +let mutationLock: typeof MutationLockModule let installStore: typeof InstallStoreModule beforeAll(() => { @@ -64,6 +68,7 @@ beforeEach(async () => { state.load.mockImplementation(async () => ({})) vi.resetModules() install = await import('./browser-extension-webstore-install') + mutationLock = await import('./browser-extension-mutation-lock') installStore = await import('./browser-extension-install-store') }) afterEach(() => { @@ -111,7 +116,7 @@ describe('store installs', () => { await vi.waitFor(() => expect(state.load).toHaveBeenCalledWith('work', first)) try { await expect( - install.withBrowserExtensionLock(extensionId, () => + mutationLock.withBrowserExtensionLock(extensionId, () => install.commitStagedWebStoreExtension(staged, null) ) ).rejects.toThrow('already being installed') diff --git a/src/main/browser/extensions/installation/browser-extension-webstore-install.ts b/src/main/browser/extensions/installation/browser-extension-webstore-install.ts index 2ed352f13db..7d58552bba7 100644 --- a/src/main/browser/extensions/installation/browser-extension-webstore-install.ts +++ b/src/main/browser/extensions/installation/browser-extension-webstore-install.ts @@ -3,7 +3,7 @@ import { rename, rm, writeFile } from 'node:fs/promises' import { isAbsolute, join, relative, resolve } from 'node:path' import type { InstalledBrowserExtension } from '../../../../shared/browser/extensions/browser-extension-types' import { BROWSER_EXTENSION_ORIGINAL_MANIFEST_FILE } from '../../../../shared/browser/extensions/browser-extension-worker-api' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { readBrowserExtensionArchive, writeBrowserExtensionArchive @@ -36,33 +36,6 @@ import { const VERSION_PATTERN = /^\d+(\.\d+){0,3}$/ const STAGING_PREFIX = '.staging-' -const busyExtensionIds = new Set() - -export class BrowserExtensionBusyError extends Error { - constructor() { - super('This extension is already being installed or removed') - } -} - -/** Serializes install, update and uninstall of one extension id. */ -export async function withBrowserExtensionLock( - extensionId: string, - action: () => Promise -): Promise { - if (busyExtensionIds.has(extensionId)) { - throw new BrowserExtensionBusyError() - } - busyExtensionIds.add(extensionId) - try { - return await action() - } finally { - busyExtensionIds.delete(extensionId) - } -} - -export function isBrowserExtensionBusy(extensionId: string): boolean { - return busyExtensionIds.has(extensionId) -} export type StagedWebStoreExtension = { extensionId: string diff --git a/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts b/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts index 4e6731291cf..81d752dfed8 100644 --- a/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts +++ b/src/main/browser/extensions/native-messaging/browser-extension-native-messaging-electron-fixture.ts @@ -3,7 +3,7 @@ import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' import { attachBrowserExtensionsToProfileSession } from '../profile-sessions/browser-extension-session-loader' diff --git a/src/main/browser/extensions/permissions/browser-extension-permission-prompt.ts b/src/main/browser/extensions/permissions/browser-extension-permission-prompt.ts index 7edc3516abb..980fe4d8a59 100644 --- a/src/main/browser/extensions/permissions/browser-extension-permission-prompt.ts +++ b/src/main/browser/extensions/permissions/browser-extension-permission-prompt.ts @@ -1,4 +1,4 @@ -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { requestBrowserExtensionInstallPrompt } from './browser-extension-install-prompt' import { getBrowserExtensionInstallStore } from '../installation/browser-extension-install-store' import { readBrowserExtensionIconDataUrl } from '../installation/browser-extension-manifest' diff --git a/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts b/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts index be7c935dcad..ab5cf2b08c4 100644 --- a/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts +++ b/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts @@ -1,4 +1,4 @@ -import type { DnrHostAccess } from '../declarative-net-request/extension-matcher' +import type { DnrHostAccess } from '../declarative-net-request/matching/extension-matcher' import { browserExtensionActiveTabCovers } from './browser-extension-active-tab' import { matchesExtensionMatchPattern } from './browser-extension-match-pattern' import { manifestPermissionSets } from './browser-extension-permission-grants' diff --git a/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts b/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts new file mode 100644 index 00000000000..750309bcd88 --- /dev/null +++ b/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts @@ -0,0 +1,19 @@ +import { getBrowserExtensionProfileIdForSession } from '../api-runtime/browser-extension-api-host' +import { browserExtensionHostPatterns } from './browser-extension-permission-grants' +import { getBrowserExtensionProfileStateStore } from '../profile-storage/browser-extension-profile-state-store' + +export function readBrowserExtensionProfileGrants(profileId: string, extensionId: string) { + return getBrowserExtensionProfileStateStore().read(profileId, extensionId) +} + +/** Manifest host patterns plus origins the user granted in this session's profile. */ +export function browserExtensionHostPatternsInSession( + extension: Electron.Extension, + session: Electron.Session +): string[] { + const profileId = getBrowserExtensionProfileIdForSession(session) + const grants = profileId + ? readBrowserExtensionProfileGrants(profileId, extension.id) + : { grantedPermissions: [], grantedOrigins: [] } + return browserExtensionHostPatterns(extension.manifest, grants) +} diff --git a/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts b/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts index f074bd911d4..7d5a96a61f0 100644 --- a/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts +++ b/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts @@ -10,7 +10,7 @@ import { } from '../../../../shared/browser/extensions/browser-extension-webstore' import type * as PromptModule from './browser-extension-install-prompt' import type * as ServiceModule from '../web-store/browser-extension-webstore-service' -import type * as InstallModule from '../installation/browser-extension-webstore-install' +import type * as MutationLockModule from '../installation/browser-extension-mutation-lock' const state = vi.hoisted(() => ({ userData: '', @@ -22,8 +22,8 @@ vi.mock('electron', () => ({ app: { getPath: () => state.userData }, webContents: { fromId: () => null } })) -vi.mock('../../browser-manager', () => ({ browserManager: {} })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getProfile: () => ({ label: 'Work' }), getEnabledExtensionIds: () => [], @@ -65,7 +65,7 @@ const renderers: EventEmitter[] = [] const installs: Promise[] = [] let service: typeof ServiceModule let prompt: typeof PromptModule -let install: typeof InstallModule +let mutationLock: typeof MutationLockModule function renderer() { const contents = Object.assign(new EventEmitter(), { @@ -138,7 +138,7 @@ beforeEach(async () => { vi.resetModules() service = await import('../web-store/browser-extension-webstore-service') prompt = await import('./browser-extension-install-prompt') - install = await import('../installation/browser-extension-webstore-install') + mutationLock = await import('../installation/browser-extension-mutation-lock') }) afterEach(async () => { @@ -155,14 +155,14 @@ describe('Settings extension install prompt lifetime', () => { const pending = start(contents) const request = await requested(contents) expect(stagedFolders()).toHaveLength(1) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(true) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(true) contents.emit('did-navigate', {}, 'file:///orca/index.html', 200, 'OK') - await vi.waitFor(() => expect(install.isBrowserExtensionBusy(extensionId)).toBe(false)) + await vi.waitFor(() => expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false)) await expect(pending).resolves.toEqual({ status: 'cancelled' }) expect(stagedFolders()).toEqual([]) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false) expect( prompt.respondToBrowserExtensionInstallPrompt(asContents(contents), { requestId: request.requestId, @@ -181,6 +181,6 @@ describe('Settings extension install prompt lifetime', () => { accepted: true }) await expect(retry).resolves.toEqual({ status: 'installed', name: 'Vault' }) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false) }) }) diff --git a/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts b/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts new file mode 100644 index 00000000000..e0abfe450e3 --- /dev/null +++ b/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts @@ -0,0 +1,36 @@ +import type { BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' +import { getHostSessionState } from '../api-runtime/browser-extension-contexts' +import { getBrowserExtensionContextSignal } from '../api-runtime/browser-extension-context-lifetime' + +const USER_GESTURE_WINDOW_MS = 5_000 + +const recentGestures = new WeakMap() + +/** + * Chrome lets permissions.request run only inside a user gesture. Orca records the gestures it + * delivers to an extension (menu click, command, notification click, toolbar click). + */ +export function noteBrowserExtensionUserGesture( + session: Electron.Session, + extensionId: string +): void { + const state = getHostSessionState(session) + if (!state) { + return + } + const signal = getBrowserExtensionContextSignal(state, extensionId) + recentGestures.set(signal, Date.now()) +} + +export function hasBrowserExtensionUserGesture(caller: BrowserExtensionCaller): boolean { + if (caller.userGesture === true) { + return true + } + const state = getHostSessionState(caller.session) + if (!state) { + return false + } + const signal = getBrowserExtensionContextSignal(state, caller.extension.id) + const at = recentGestures.get(signal) + return at !== undefined && !signal.aborted && Date.now() - at <= USER_GESTURE_WINDOW_MS +} diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts b/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts index 725643418a1..37f7d63079c 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-lifecycle-electron-fixture.ts @@ -2,7 +2,7 @@ import { app, BaseWindow, protocol, session } from 'electron' import { renameSync, writeFileSync } from 'node:fs' import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' import { attachBrowserExtensionsToProfileSession } from './browser-extension-session-loader' diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.test.ts b/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.test.ts index acc72a39a5b..edc3894f409 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.test.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.test.ts @@ -9,7 +9,7 @@ const mocks = vi.hoisted(() => ({ load: vi.fn(async (_profileId: string): Promise => ({})) })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { listProfiles: () => [...mocks.enabled.keys()].map((id) => ({ id })), getEnabledExtensionIds: (profileId: string) => mocks.enabled.get(profileId) ?? [] diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.ts b/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.ts index 109ed28a60d..9ee4ab472f8 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-profile-reload.ts @@ -1,5 +1,5 @@ import type { InstalledBrowserExtension } from '../../../../shared/browser/extensions/browser-extension-types' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { prepareBrowserExtensionDirectory } from '../installation/browser-extension-load-directory' import { getBrowserExtensionSessionForProfile, diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts index 62e6027932e..40637eefdfc 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts @@ -22,7 +22,7 @@ let attachHook: AttachHook | null = null vi.mock('electron', () => ({ webContents: { fromId: (id: number) => ({ session: mocks.sessionByTabId.get(id) }) } })) -vi.mock('../../sessions/browser-session-registry', () => ({ +vi.mock('../../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { updateEnabledExtensionIds: mocks.updateEnabled, updatePinnedExtensionIds: mocks.updatePinned, @@ -30,7 +30,7 @@ vi.mock('../../sessions/browser-session-registry', () => ({ getPinnedExtensionIds: () => [] } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { setUnownedDownloadOwnerResolver: vi.fn() } })) vi.mock('../api/cookies', () => ({ observeBrowserExtensionCookieChanges: vi.fn() })) @@ -59,7 +59,7 @@ vi.mock('./browser-extension-session-loader', () => ({ attachHook = hooks } })) -vi.mock('../browser-extension-web-request', () => ({ +vi.mock('../requests/browser-extension-web-request-observer', () => ({ installBrowserExtensionWebRequestForwarding: vi.fn(), observeBrowserExtensionWebRequests: vi.fn(), stopObservingBrowserExtensionWebRequests: vi.fn() diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts index 6addfc642d1..e9a62eeb5c6 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts @@ -1,7 +1,7 @@ -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { webContents } from 'electron' import { parseChromeExtensionUrl } from '../../../../shared/browser/extensions/browser-extension-url' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { observeBrowserExtensionCookieChanges } from '../api/cookies' import { observeBrowserExtensionActionSession } from '../actions/browser-extension-action-registry' import { revokeBrowserExtensionActiveTabInSession } from '../permissions/browser-extension-active-tab' @@ -22,7 +22,7 @@ import { installBrowserExtensionWebRequestForwarding, observeBrowserExtensionWebRequests, stopObservingBrowserExtensionWebRequests -} from '../browser-extension-web-request' +} from '../requests/browser-extension-web-request-observer' // Why once: a session outlives the experimental setting being switched off and on again. const servedSessions = new WeakSet() diff --git a/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts b/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts index 235dbeef7b7..c88feafc4f5 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts @@ -51,7 +51,9 @@ const { } = await import('./browser-extension-data-removal') const { getBrowserExtensionProfileStateStore } = await import('./browser-extension-profile-state-store') -const { BrowserExtensionSyncStorageStore, getBrowserExtensionSyncStorageStore } = +const { BrowserExtensionProfileDocumentStore } = + await import('./browser-extension-profile-document-store') +const { getBrowserExtensionSyncStorageStore } = await import('./browser-extension-sync-storage-store') const { getBrowserExtensionInstallStore } = await import('../installation/browser-extension-install-store') @@ -112,7 +114,7 @@ describe('removeUninstalledBrowserExtensionData', () => { expect(Object.keys(states.readProfile('work'))).toEqual([OTHER]) expect(states.read('home', ID).grantedPermissions).toEqual(['tabs']) expect( - new BrowserExtensionSyncStorageStore(getBrowserExtensionProfileDataDirectory()).read( + new BrowserExtensionProfileDocumentStore(getBrowserExtensionProfileDataDirectory()).read( 'work', ID ) diff --git a/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts b/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts index 114b22ae2b8..3634015a353 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-persistence-electron-fixture.ts @@ -3,8 +3,8 @@ import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' -import { browserManager } from '../../browser-manager' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' import { BROWSER_EXTENSION_API_CUSTOM_SCHEME } from '../api-runtime/browser-extension-api-scheme' import { diff --git a/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts b/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts new file mode 100644 index 00000000000..9a1f6a8b0bb --- /dev/null +++ b/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts @@ -0,0 +1,158 @@ +import { mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { isChromeExtensionId } from '../../../../shared/browser/extensions/browser-extension-url' +import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' + +const SYNC_STORAGE_DIRECTORY = 'sync-storage' + +const PERSIST_DELAY_MS = 250 + +export type BrowserExtensionProfileDocumentItems = Record + +function isItems(value: unknown): value is BrowserExtensionProfileDocumentItems { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +export class BrowserExtensionProfileDocumentStore { + /** Profile → extension → items. */ + private readonly cache = new Map>() + /** Profile → extensions whose items are not on disk yet. */ + private readonly dirty = new Map>() + private timer: NodeJS.Timeout | null = null + + constructor( + private readonly rootDirectory: string, + /** declarativeNetRequest state reuses this store under its own directory. */ + private readonly directoryName = SYNC_STORAGE_DIRECTORY + ) {} + + read(profileId: string, extensionId: string): BrowserExtensionProfileDocumentItems { + let byExtension = this.cache.get(profileId) + if (!byExtension) { + byExtension = new Map() + this.cache.set(profileId, byExtension) + } + let items = byExtension.get(extensionId) + if (!items) { + items = this.load(profileId, extensionId) + byExtension.set(extensionId, items) + } + return items + } + + write(profileId: string, extensionId: string, items: BrowserExtensionProfileDocumentItems): void { + this.read(profileId, extensionId) + this.cache.get(profileId)?.set(extensionId, items) + const dirty = this.dirty.get(profileId) ?? new Set() + dirty.add(extensionId) + this.dirty.set(profileId, dirty) + this.schedulePersist() + } + + forgetExtension(extensionId: string): void { + for (const byExtension of this.cache.values()) { + byExtension.delete(extensionId) + } + for (const dirty of this.dirty.values()) { + dirty.delete(extensionId) + } + let profileDirectories: string[] + try { + profileDirectories = readdirSync(join(this.rootDirectory, this.directoryName)) + } catch { + return + } + for (const directory of profileDirectories) { + rmSync(join(this.rootDirectory, this.directoryName, directory, this.fileName(extensionId)), { + force: true + }) + } + } + + forgetProfileExtension(profileId: string, extensionId: string): void { + this.cache.get(profileId)?.delete(extensionId) + this.dirty.get(profileId)?.delete(extensionId) + rmSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), { force: true }) + } + + /** Drops one profile's items of every extension not in `extensionIds`. */ + forgetExtensionsExcept(profileId: string, extensionIds: ReadonlySet): void { + const cached = this.cache.get(profileId) + for (const extensionId of cached?.keys() ?? []) { + if (!extensionIds.has(extensionId)) { + cached?.delete(extensionId) + this.dirty.get(profileId)?.delete(extensionId) + } + } + let files: string[] + try { + files = readdirSync(this.profileDirectory(profileId)) + } catch { + return + } + for (const file of files) { + const extensionId = file.replace(/\.json$/, '') + if (isChromeExtensionId(extensionId) && !extensionIds.has(extensionId)) { + rmSync(join(this.profileDirectory(profileId), file), { force: true }) + } + } + } + + forgetProfile(profileId: string): void { + this.cache.delete(profileId) + this.dirty.delete(profileId) + rmSync(this.profileDirectory(profileId), { recursive: true, force: true }) + } + + flush(): void { + if (this.timer) { + clearTimeout(this.timer) + this.timer = null + } + for (const [profileId, extensionIds] of this.dirty) { + const directory = this.profileDirectory(profileId) + mkdirSync(directory, { recursive: true }) + for (const extensionId of extensionIds) { + const target = join(directory, this.fileName(extensionId)) + const items = this.cache.get(profileId)?.get(extensionId) ?? {} + writeFileDurableSync(durableWriteTempPath(target), target, JSON.stringify(items)) + extensionIds.delete(extensionId) + } + this.dirty.delete(profileId) + } + } + + // Why debounce: extensions often write settings key by key in a burst. + private schedulePersist(): void { + if (this.timer) { + return + } + this.timer = setTimeout(() => { + this.timer = null + try { + this.flush() + } catch (error) { + console.warn('[browser-extensions] Could not save extension sync storage:', error) + } + }, PERSIST_DELAY_MS) + } + + private load(profileId: string, extensionId: string): BrowserExtensionProfileDocumentItems { + try { + const raw: unknown = JSON.parse( + readFileSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), 'utf8') + ) + return isItems(raw) ? raw : {} + } catch { + return {} + } + } + + private profileDirectory(profileId: string): string { + return join(this.rootDirectory, this.directoryName, encodeURIComponent(profileId)) + } + + private fileName(extensionId: string): string { + return `${encodeURIComponent(extensionId)}.json` + } +} diff --git a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts index 4b87e80c204..fd00df7b1f4 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts @@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => tmpdir(), on: vi.fn() } })) -const { BrowserExtensionSyncStorageStore } = await import('./browser-extension-sync-storage-store') +const { BrowserExtensionProfileDocumentStore } = + await import('./browser-extension-profile-document-store') const EXTENSION = 'a'.repeat(32) const OTHER = 'b'.repeat(32) @@ -18,34 +19,34 @@ afterEach(() => { rmSync(root, { recursive: true, force: true }) }) -describe('BrowserExtensionSyncStorageStore', () => { +describe('BrowserExtensionProfileDocumentStore', () => { it('keeps each profile and extension apart and survives a restart', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) store.write('default', EXTENSION, { theme: { dark: true }, list: [1, 'two'] }) store.write('work', EXTENSION, { theme: 'light' }) store.flush() - const reopened = new BrowserExtensionSyncStorageStore(root) + const reopened = new BrowserExtensionProfileDocumentStore(root) expect(reopened.read('default', EXTENSION)).toEqual({ theme: { dark: true }, list: [1, 'two'] }) expect(reopened.read('work', EXTENSION)).toEqual({ theme: 'light' }) expect(reopened.read('default', OTHER)).toEqual({}) }) it('retries acknowledged writes after a failed flush', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) store.write('default', EXTENSION, { token: 'saved after recovery' }) writeFileSync(join(root, 'sync-storage'), 'blocks the storage directory') expect(() => store.flush()).toThrow() rmSync(join(root, 'sync-storage')) store.flush() - expect(new BrowserExtensionSyncStorageStore(root).read('default', EXTENSION)).toEqual({ + expect(new BrowserExtensionProfileDocumentStore(root).read('default', EXTENSION)).toEqual({ token: 'saved after recovery' }) }) it('forgets a removed extension in every profile and a deleted profile entirely', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) for (const profile of ['default', 'work']) { store.write(profile, EXTENSION, { kept: profile }) store.write(profile, OTHER, { kept: profile }) @@ -58,7 +59,7 @@ describe('BrowserExtensionSyncStorageStore', () => { store.flush() expect(store.read('default', EXTENSION)).toEqual({}) - const reopened = new BrowserExtensionSyncStorageStore(root) + const reopened = new BrowserExtensionProfileDocumentStore(root) expect(reopened.read('default', EXTENSION)).toEqual({}) expect(reopened.read('default', OTHER)).toEqual({ kept: 'default' }) expect(reopened.read('work', OTHER)).toEqual({}) diff --git a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts index 441a023ffd1..569bdd6b60c 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts @@ -1,173 +1,19 @@ +import { BrowserExtensionProfileDocumentStore } from './browser-extension-profile-document-store' import { app } from 'electron' -import { mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { isChromeExtensionId } from '../../../../shared/browser/extensions/browser-extension-url' -import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' import { getBrowserExtensionProfileDataDirectory } from './browser-extension-profile-data-directory' -const SYNC_STORAGE_DIRECTORY = 'sync-storage' -const PERSIST_DELAY_MS = 250 - -export type BrowserExtensionSyncItems = Record - -function isItems(value: unknown): value is BrowserExtensionSyncItems { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} +let syncStorageStore: BrowserExtensionProfileDocumentStore | null = null /** * chrome.storage.sync items per browser profile and extension, kept on this machine the way * Chrome keeps them for a user who is not signed in. One file per extension, so a write rewrites * only that extension's items (up to 100 KB). */ -export class BrowserExtensionSyncStorageStore { - /** Profile → extension → items. */ - private readonly cache = new Map>() - /** Profile → extensions whose items are not on disk yet. */ - private readonly dirty = new Map>() - private timer: NodeJS.Timeout | null = null - - constructor( - private readonly rootDirectory: string, - /** declarativeNetRequest state reuses this store under its own directory. */ - private readonly directoryName = SYNC_STORAGE_DIRECTORY - ) {} - - read(profileId: string, extensionId: string): BrowserExtensionSyncItems { - let byExtension = this.cache.get(profileId) - if (!byExtension) { - byExtension = new Map() - this.cache.set(profileId, byExtension) - } - let items = byExtension.get(extensionId) - if (!items) { - items = this.load(profileId, extensionId) - byExtension.set(extensionId, items) - } - return items - } - - write(profileId: string, extensionId: string, items: BrowserExtensionSyncItems): void { - this.read(profileId, extensionId) - this.cache.get(profileId)?.set(extensionId, items) - const dirty = this.dirty.get(profileId) ?? new Set() - dirty.add(extensionId) - this.dirty.set(profileId, dirty) - this.schedulePersist() - } - - forgetExtension(extensionId: string): void { - for (const byExtension of this.cache.values()) { - byExtension.delete(extensionId) - } - for (const dirty of this.dirty.values()) { - dirty.delete(extensionId) - } - let profileDirectories: string[] - try { - profileDirectories = readdirSync(join(this.rootDirectory, this.directoryName)) - } catch { - return - } - for (const directory of profileDirectories) { - rmSync(join(this.rootDirectory, this.directoryName, directory, this.fileName(extensionId)), { - force: true - }) - } - } - - forgetProfileExtension(profileId: string, extensionId: string): void { - this.cache.get(profileId)?.delete(extensionId) - this.dirty.get(profileId)?.delete(extensionId) - rmSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), { force: true }) - } - - /** Drops one profile's items of every extension not in `extensionIds`. */ - forgetExtensionsExcept(profileId: string, extensionIds: ReadonlySet): void { - const cached = this.cache.get(profileId) - for (const extensionId of cached?.keys() ?? []) { - if (!extensionIds.has(extensionId)) { - cached?.delete(extensionId) - this.dirty.get(profileId)?.delete(extensionId) - } - } - let files: string[] - try { - files = readdirSync(this.profileDirectory(profileId)) - } catch { - return - } - for (const file of files) { - const extensionId = file.replace(/\.json$/, '') - if (isChromeExtensionId(extensionId) && !extensionIds.has(extensionId)) { - rmSync(join(this.profileDirectory(profileId), file), { force: true }) - } - } - } - - forgetProfile(profileId: string): void { - this.cache.delete(profileId) - this.dirty.delete(profileId) - rmSync(this.profileDirectory(profileId), { recursive: true, force: true }) - } - - flush(): void { - if (this.timer) { - clearTimeout(this.timer) - this.timer = null - } - for (const [profileId, extensionIds] of this.dirty) { - const directory = this.profileDirectory(profileId) - mkdirSync(directory, { recursive: true }) - for (const extensionId of extensionIds) { - const target = join(directory, this.fileName(extensionId)) - const items = this.cache.get(profileId)?.get(extensionId) ?? {} - writeFileDurableSync(durableWriteTempPath(target), target, JSON.stringify(items)) - extensionIds.delete(extensionId) - } - this.dirty.delete(profileId) - } - } - - // Why debounce: extensions often write settings key by key in a burst. - private schedulePersist(): void { - if (this.timer) { - return - } - this.timer = setTimeout(() => { - this.timer = null - try { - this.flush() - } catch (error) { - console.warn('[browser-extensions] Could not save extension sync storage:', error) - } - }, PERSIST_DELAY_MS) - } - - private load(profileId: string, extensionId: string): BrowserExtensionSyncItems { - try { - const raw: unknown = JSON.parse( - readFileSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), 'utf8') - ) - return isItems(raw) ? raw : {} - } catch { - return {} - } - } - - private profileDirectory(profileId: string): string { - return join(this.rootDirectory, this.directoryName, encodeURIComponent(profileId)) - } - - private fileName(extensionId: string): string { - return `${encodeURIComponent(extensionId)}.json` - } -} - -let syncStorageStore: BrowserExtensionSyncStorageStore | null = null - -export function getBrowserExtensionSyncStorageStore(): BrowserExtensionSyncStorageStore { +export function getBrowserExtensionSyncStorageStore(): BrowserExtensionProfileDocumentStore { if (!syncStorageStore) { - const store = new BrowserExtensionSyncStorageStore(getBrowserExtensionProfileDataDirectory()) + const store = new BrowserExtensionProfileDocumentStore( + getBrowserExtensionProfileDataDirectory() + ) app.on('will-quit', () => store.flush()) syncStorageStore = store } diff --git a/src/main/browser/extensions/requests/browser-extension-request-classification.ts b/src/main/browser/extensions/requests/browser-extension-request-classification.ts new file mode 100644 index 00000000000..1d974b43e40 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-request-classification.ts @@ -0,0 +1,57 @@ +import { CHROME_WEB_STORE_ORIGIN } from '../../../../shared/browser/extensions/browser-extension-webstore' + +type ChromeResourceType = + | 'main_frame' + | 'sub_frame' + | 'stylesheet' + | 'script' + | 'image' + | 'font' + | 'object' + | 'xmlhttprequest' + | 'ping' + | 'csp_report' + | 'media' + | 'websocket' + | 'other' + +const CHROME_RESOURCE_TYPES = new Map([ + ['mainFrame', 'main_frame'], + ['subFrame', 'sub_frame'], + ['stylesheet', 'stylesheet'], + ['script', 'script'], + ['image', 'image'], + ['font', 'font'], + ['object', 'object'], + ['xhr', 'xmlhttprequest'], + ['ping', 'ping'], + ['cspReport', 'csp_report'], + ['media', 'media'], + ['webSocket', 'websocket'] +]) + +/** Electron's resourceType → Chrome's, shared by webRequest and declarativeNetRequest. */ +export function chromeResourceType(resourceType: string): ChromeResourceType { + return CHROME_RESOURCE_TYPES.get(resourceType) ?? 'other' +} + +const WEB_URL = /^(?:https?|wss?):/i + +/** WebRequestPermissions::HideRequest: requests extensions never see or act on. */ +export function isRequestHiddenFromExtensions(details: { + url: string + webContentsId?: number + initiatorOrigin?: string +}): boolean { + if (!WEB_URL.test(details.url)) { + return true + } + // Orca's own main-process requests carry neither a webContents nor an initiator. + if (details.webContentsId === undefined && details.initiatorOrigin === undefined) { + return true + } + return ( + details.url.startsWith(`${CHROME_WEB_STORE_ORIGIN}/`) || + details.url.startsWith('https://chrome.google.com/webstore') + ) +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-details.ts b/src/main/browser/extensions/requests/browser-extension-web-request-details.ts new file mode 100644 index 00000000000..90964d4ab29 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-details.ts @@ -0,0 +1,101 @@ +import { chromeResourceType } from './browser-extension-request-classification' +import type { ObservedWebRequestDetails } from '../../sessions/requests/browser-session-web-request-observer' +import { chromeFrameDocument } from '../tabs-and-windows/browser-extension-frame-projection' + +// Chrome hides these unless a listener asks for 'extraHeaders'. +const HIDDEN_REQUEST_HEADERS = new Set(['accept-language', 'accept-encoding', 'referer', 'cookie']) + +const HIDDEN_RESPONSE_HEADERS = new Set(['set-cookie']) + +export type ChromeWebRequestDetails = { + requestId: string + url: string + method: string + frameId: number + parentFrameId: number + tabId: number + windowId: number + type: string + timeStamp: number + frameType?: 'outermost_frame' | 'sub_frame' + documentId?: string + parentDocumentId?: string + documentLifecycle?: 'active' + requestHeaders?: { name: string; value: string }[] + responseHeaders?: { name: string; value: string }[] + statusCode?: number + statusLine?: string + fromCache?: boolean + ip?: string + redirectUrl?: string + error?: string +} + +function requestHeaderList(headers: Record): { name: string; value: string }[] { + return Object.entries(headers) + .filter(([name]) => !HIDDEN_REQUEST_HEADERS.has(name.toLowerCase())) + .map(([name, value]) => ({ name, value })) +} + +function responseHeaderList(headers: Record): { name: string; value: string }[] { + return Object.entries(headers) + .filter(([name]) => !HIDDEN_RESPONSE_HEADERS.has(name.toLowerCase())) + .flatMap(([name, values]) => values.map((value) => ({ name, value }))) +} + +type WebRequestFrameFields = Pick< + ChromeWebRequestDetails, + | 'frameId' + | 'parentFrameId' + | 'frameType' + | 'documentId' + | 'parentDocumentId' + | 'documentLifecycle' +> + +/** A navigation request has no document yet; any other request belongs to its frame's current one. */ +export function browserExtensionRequestFrameFields( + details: ObservedWebRequestDetails +): WebRequestFrameFields { + if (details.resourceType === 'mainFrame') { + return { + frameId: 0, + parentFrameId: -1, + frameType: 'outermost_frame', + documentLifecycle: 'active' + } + } + const frame = details.frame && !details.frame.isDestroyed() ? details.frame : null + return frame + ? chromeFrameDocument(frame, details.resourceType !== 'subFrame') + : { frameId: 0, parentFrameId: -1 } +} + +export function toChromeWebRequestDetails( + details: ObservedWebRequestDetails, + tab: { tabId: number; windowId: number }, + frame: WebRequestFrameFields +): ChromeWebRequestDetails { + const type = chromeResourceType(details.resourceType) + return { + requestId: String(details.id), + url: details.url, + method: details.method, + ...frame, + ...tab, + type, + timeStamp: details.timestamp, + ...(details.requestHeaders + ? { requestHeaders: requestHeaderList(details.requestHeaders) } + : {}), + ...(details.responseHeaders + ? { responseHeaders: responseHeaderList(details.responseHeaders) } + : {}), + ...(details.statusCode !== undefined ? { statusCode: details.statusCode } : {}), + ...(details.statusLine !== undefined ? { statusLine: details.statusLine } : {}), + ...(details.fromCache !== undefined ? { fromCache: details.fromCache } : {}), + ...(details.ip ? { ip: details.ip } : {}), + ...(details.redirectURL ? { redirectUrl: details.redirectURL } : {}), + ...(details.error ? { error: details.error } : {}) + } +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts b/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts new file mode 100644 index 00000000000..fdce0232e65 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts @@ -0,0 +1,32 @@ +import type { ChromeWebRequestDetails } from './browser-extension-web-request-details' +import { matchesExtensionMatchPattern } from '../permissions/browser-extension-match-pattern' + +/** Main-side pre-filter against one listener's chrome.webRequest.RequestFilter. */ +export function webRequestFilterMatches( + filter: unknown, + details: ChromeWebRequestDetails +): boolean { + if (filter === null || typeof filter !== 'object') { + return true + } + const fields = new Map(Object.entries(filter)) + const urls = fields.get('urls') + if ( + Array.isArray(urls) && + !urls.some( + (pattern) => typeof pattern === 'string' && matchesExtensionMatchPattern(pattern, details.url) + ) + ) { + return false + } + const types = fields.get('types') + if (Array.isArray(types) && !types.includes(details.type)) { + return false + } + const tabId = fields.get('tabId') + const windowId = fields.get('windowId') + return ( + (typeof tabId !== 'number' || tabId === details.tabId) && + (typeof windowId !== 'number' || windowId === details.windowId) + ) +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts b/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts new file mode 100644 index 00000000000..bd47fdd2ae8 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts @@ -0,0 +1,127 @@ +import { webRequestFilterMatches } from './browser-extension-web-request-filter' +import { + browserExtensionRequestFrameFields, + toChromeWebRequestDetails +} from './browser-extension-web-request-details' +import { isRequestHiddenFromExtensions } from './browser-extension-request-classification' +import { + installBrowserSessionHeadersReceived, + installBrowserSessionRequestLifecycle, + removeBrowserSessionHeadersReceived, + removeBrowserSessionRequestLifecycle +} from '../../sessions/requests/browser-session-request-decisions' +import { + setBrowserSessionWebRequestObserver, + type ObservedWebRequestDetails, + type ObservedWebRequestEvent +} from '../../sessions/requests/browser-session-web-request-observer' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' +import { + emitBrowserExtensionEvent, + getBrowserExtensionProfileIdForSession +} from '../api-runtime/browser-extension-api-host' +import { browserExtensionEventHasListener } from '../api-runtime/browser-extension-contexts' +import { extensionHasPermission } from '../api-runtime/browser-extension-namespace-registry' +import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' +import { canExtensionAccessRequest } from '../permissions/browser-extension-request-host-access' +import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' + +/** + * chrome.webRequest, observed rather than blocking. Electron 43 delivers no webRequest events to + * MV3 workers, and Orca's own session handlers switch Electron's extension webRequest off anyway, + * so Orca forwards what its handlers see. MV3 store extensions cannot block requests in Chrome + * either (webRequestBlocking is policy-only), so nothing they could do is lost. + */ + +function forward( + session: Electron.Session, + event: ObservedWebRequestEvent, + details: ObservedWebRequestDetails +): void { + if ( + isRequestHiddenFromExtensions(details) || + !getBrowserExtensionProfileIdForSession(session) || + !browserExtensionEventHasListener(session, 'webRequest', event) + ) { + return + } + const entry = + details.webContentsId === undefined ? null : resolveBrowserExtensionTab(details.webContentsId) + const chromeDetails = toChromeWebRequestDetails( + details, + entry ? { tabId: entry.contents.id, windowId: entry.windowId } : { tabId: -1, windowId: -1 }, + browserExtensionRequestFrameFields(details) + ) + const request = { + url: details.url, + initiator: details.initiatorOrigin ?? null, + tabId: chromeDetails.tabId, + type: chromeDetails.type + } + emitBrowserExtensionEvent( + { session }, + 'webRequest', + event, + (extension) => { + const patterns = browserExtensionHostPatternsInSession(extension, session) + return canExtensionAccessRequest(extension.id, request, (url) => + hasBrowserExtensionHostPermission(patterns, url) + ) + ? [chromeDetails] + : null + }, + (filter) => webRequestFilterMatches(filter, chromeDetails) + ) +} + +const observedSessions = new WeakSet() +const watchedSessions = new WeakSet() +const OBSERVE_ALL = { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] } + +/** The events Orca does not otherwise handle, installed once a webRequest extension loads. */ +function observeRemainingEvents(session: Electron.Session): void { + if (observedSessions.has(session)) { + return + } + observedSessions.add(session) + const { webRequest } = session + webRequest.onSendHeaders(OBSERVE_ALL, (details) => forward(session, 'onSendHeaders', details)) + installBrowserSessionHeadersReceived(session) + webRequest.onResponseStarted(OBSERVE_ALL, (details) => + forward(session, 'onResponseStarted', details) + ) + webRequest.onBeforeRedirect(OBSERVE_ALL, (details) => + forward(session, 'onBeforeRedirect', details) + ) + installBrowserSessionRequestLifecycle(session) +} + +export function observeBrowserExtensionWebRequests(session: Electron.Session): void { + const maybeObserve = (extension: Electron.Extension): void => { + if (extensionHasPermission(extension, 'webRequest', session)) { + observeRemainingEvents(session) + } + } + if (!watchedSessions.has(session)) { + watchedSessions.add(session) + session.extensions.on('extension-ready', (_event, extension) => maybeObserve(extension)) + } + session.extensions.getAllExtensions().forEach(maybeObserve) +} + +/** Extensions turned off: hand the session's request path back to Orca's own handlers alone. */ +export function stopObservingBrowserExtensionWebRequests(session: Electron.Session): void { + removeBrowserSessionHeadersReceived(session) + removeBrowserSessionRequestLifecycle(session) + if (!observedSessions.delete(session)) { + return + } + const { webRequest } = session + webRequest.onSendHeaders(null) + webRequest.onResponseStarted(null) + webRequest.onBeforeRedirect(null) +} + +export function installBrowserExtensionWebRequestForwarding(): void { + setBrowserSessionWebRequestObserver(forward) +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts index 318f8fbe940..482e93828e4 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts @@ -39,7 +39,7 @@ const mocks = vi.hoisted(() => { vi.mock('electron', () => ({ webContents: { fromId: (id: number) => mocks.guests.get(id) } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getGuestWebContentsId: (pageId: string) => [...mocks.pageByGuest].find(([, page]) => page === pageId)?.[0] ?? null, @@ -99,7 +99,7 @@ vi.mock('./browser-extension-window-model', () => ({ presentBrowserExtensionWindow: vi.fn() })) vi.mock('../api/tabs-capture', () => ({ captureVisibleTabMethod: {} })) -vi.mock('../api/permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: (_extension: unknown, sess: unknown) => sess === mocks.sessions.default ? mocks.grantedOrigins : [] })) @@ -109,7 +109,7 @@ const discardedTabs = await import('./browser-extension-discarded-tabs') const { recordActiveBrowserPage } = await import('./browser-extension-tab-model') const { registerTabsNamespace } = await import('../api/tabs') const { announceRegisteredBrowserExtensionTab, observeBrowserExtensionTabLifecycle } = - await import('../api/tabs-lifecycle') + await import('./browser-extension-tab-lifecycle') await import('../../../../preload/browser-extension-document-targets') function page(id: string, workspaceId: string, overrides: Partial = {}): BrowserPage { diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts index e4ca181f621..55c2cb90743 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.ts @@ -2,7 +2,7 @@ import { webContents } from 'electron' import type { Store } from '../../../persistence/loading-store/store' import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' import { getBrowserExtensionProfile, diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts new file mode 100644 index 00000000000..58732fa864f --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts @@ -0,0 +1,27 @@ +import { getBrowserExtensionDocumentId } from './browser-extension-document-ids' + +/** + * Chrome frame ids: 0 for a tab's main frame, the frame-tree-node id otherwise. Electron's own + * content-script `sender.frameId` uses the same numbering, so tabs.sendMessage targets line up. + */ +export function chromeFrameId(frame: Electron.WebFrameMain): number { + return frame.parent ? frame.frameTreeNodeId : 0 +} + +function chromeParentFrameId(frame: Electron.WebFrameMain): number { + return frame.parent ? chromeFrameId(frame.parent) : -1 +} + +/** Chrome's frame fields; `documentId` is left out where the document does not exist yet. */ +export function chromeFrameDocument(frame: Electron.WebFrameMain, withDocument: boolean) { + return { + frameId: chromeFrameId(frame), + parentFrameId: chromeParentFrameId(frame), + ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) } : {}), + ...(frame.parent + ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent.frameTreeNodeId) } + : {}), + frameType: frame.parent ? ('sub_frame' as const) : ('outermost_frame' as const), + documentLifecycle: 'active' as const + } +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts new file mode 100644 index 00000000000..541ab745a2f --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts @@ -0,0 +1,23 @@ +import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' +import { BrowserExtensionApiError } from '../api-runtime/browser-extension-namespace-registry' +import { openBrowserExtensionTab } from './browser-extension-tab-model' + +function optionsPagePath(extension: Electron.Extension): string | null { + const manifest: { options_ui?: { page?: unknown }; options_page?: unknown } = + extension.manifest ?? {} + const page = manifest.options_ui?.page ?? manifest.options_page + return typeof page === 'string' && page.length > 0 ? page : null +} + +/** Opens the extension's options page as an Orca tab in the given browser profile. */ +export async function openBrowserExtensionOptionsPage( + browserProfileId: string, + extension: Electron.Extension +): Promise { + const page = optionsPagePath(extension) + if (!page) { + throw new BrowserExtensionApiError('This extension has no options page') + } + const url = new URL(page.replace(/^\/+/, ''), `${getChromeExtensionOrigin(extension.id)}/`) + await openBrowserExtensionTab(browserProfileId, url.toString(), true) +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts new file mode 100644 index 00000000000..912591a34be --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts @@ -0,0 +1,21 @@ +import { resolveBrowserExtensionRequestedUrl } from '../../../../shared/browser/extensions/browser-extension-url' +import { + BrowserExtensionApiError, + type BrowserExtensionCaller +} from '../api-runtime/browser-extension-namespace-registry' + +/** Resolves an extension-requested URL through Orca's rules; extension pages must be loaded in `sess`. */ +export function requireOpenableUrl( + caller: BrowserExtensionCaller, + rawUrl: string | undefined, + sess: Electron.Session +): string { + const resolved = resolveBrowserExtensionRequestedUrl(rawUrl, caller.extension.id) + if ( + !resolved || + (resolved.kind === 'extension' && !sess.extensions.getExtension(resolved.extensionId)) + ) { + throw new BrowserExtensionApiError(`Cannot open URL: ${rawUrl ?? ''}`) + } + return resolved.url +} diff --git a/src/main/browser/extensions/api/tabs-lifecycle.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts similarity index 97% rename from src/main/browser/extensions/api/tabs-lifecycle.ts rename to src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts index afbeb6c8ff4..1a1ad109e1a 100644 --- a/src/main/browser/extensions/api/tabs-lifecycle.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts @@ -1,6 +1,6 @@ /// import { webContents } from 'electron' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { emitBrowserExtensionEvent, getBrowserExtensionProfileIdForSession @@ -11,14 +11,14 @@ import { emitDiscardedBrowserTabRemoved, noteBrowserPageGuestGone, takeDiscardedBrowserTabId -} from '../tabs-and-windows/browser-extension-discarded-tabs' +} from './browser-extension-discarded-tabs' import { isBrowserExtensionSupportEnabled } from '../browser-extension-support' import { canExtensionSeeTabUrl, describeBrowserExtensionTab, replaceActivatedBrowserTabId, resolveBrowserExtensionTab -} from '../tabs-and-windows/browser-extension-tab-model' +} from './browser-extension-tab-model' /** Tabs announced through onCreated or onReplaced, with their window, so onRemoved matches them. */ const announcedTabWindowIds = new Map() diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.test.ts index 301ea11e2fe..dd92338bfe7 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.test.ts @@ -17,7 +17,7 @@ vi.mock('electron', () => ({ } } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getGuestWebContentsId: (pageId: string) => mocks.pages.get(pageId)?.id ?? null, getWebContentsIdByTabId: () => diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts index 9cdc971f5e2..cbe3e122894 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts @@ -1,7 +1,7 @@ /// import { webContents } from 'electron' import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { createBrowserTabInRenderer } from '../../../runtime/browser/tabs/browser-tab-renderer-create' import { closeBrowserTabInRenderer } from '../../../runtime/browser/tabs/browser-tab-renderer-close' import { activateBrowserTabInRenderer } from '../../../runtime/browser/tabs/browser-tab-renderer-activate' @@ -13,7 +13,7 @@ import { type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' -import { browserExtensionHostPatternsInSession } from '../api/permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' import { closeBrowserExtensionPopup } from '../actions/browser-extension-popup-host' import { hasBrowserExtensionActiveTab } from '../permissions/browser-extension-active-tab' import { diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts index 7c82b7a10a8..a7e885bbd1d 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts @@ -68,7 +68,7 @@ vi.mock('electron', () => ({ } } })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getWebContentsIdByTabId: () => { mocks.counts.registries += 1 @@ -90,7 +90,7 @@ vi.mock('../permissions/browser-extension-active-tab', () => ({ hasBrowserExtensionActiveTab: (_extensionId: string, tabId: number) => mocks.activeGrants.has(tabId) })) -vi.mock('../api/permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: () => mocks.hostPatterns })) vi.mock('../api/tabs-capture', () => ({ captureVisibleTabMethod: {} })) diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.test.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.test.ts index b3185ea7dd5..7f140a2fe39 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.test.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ ipcMain: { handle: vi.fn(), removeHandler: vi.fn() } })) -vi.mock('../../browser-manager', () => ({ browserManager: {} })) +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('../api-runtime/browser-extension-api-host', () => ({ getBrowserExtensionProfileIdForSession: vi.fn() })) diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.ts index 8a5f97fca45..4ef9add7351 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-bridge-host.ts @@ -5,7 +5,7 @@ import { isChromeWebStoreUrl, type ChromeWebStoreReply } from '../../../../shared/browser/extensions/browser-extension-webstore' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { getBrowserExtensionProfileIdForSession } from '../api-runtime/browser-extension-api-host' import { getBrowserExtensionInstallStore } from '../installation/browser-extension-install-store' import { toChromeWebStoreExtensionInfo } from './browser-extension-webstore-events' diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-events.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-events.ts index 8aa04bef278..7792a4074fd 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-events.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-events.ts @@ -5,7 +5,7 @@ import { isChromeWebStoreUrl } from '../../../../shared/browser/extensions/browser-extension-webstore' import { getBrowserExtensionProfileIdForSession } from '../api-runtime/browser-extension-api-host' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' /** The subset of chrome.management.ExtensionInfo the store page reads. */ export function toChromeWebStoreExtensionInfo( diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts index 2e209ad717f..1052b409ed7 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts @@ -4,8 +4,8 @@ import { parseChromeWebStoreExtensionInput, type BrowserExtensionWebStoreInstallResult } from '../../../../shared/browser/extensions/browser-extension-webstore' -import { browserManager } from '../../browser-manager' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { getBrowserExtensionInstallStore } from '../installation/browser-extension-install-store' import { requestBrowserExtensionInstallPrompt } from '../permissions/browser-extension-install-prompt' import { removeBrowserExtension } from '../browser-extension-management' @@ -26,10 +26,12 @@ import { import { commitStagedWebStoreExtension, discardStagedWebStoreExtension, - isBrowserExtensionBusy, - stageWebStoreExtension, - withBrowserExtensionLock + stageWebStoreExtension } from '../installation/browser-extension-webstore-install' +import { + isBrowserExtensionBusy, + withBrowserExtensionLock +} from '../installation/browser-extension-mutation-lock' import { ChromeWebStoreInstallFlow, InvalidIconUrlError, diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts index d2d55516bd5..dc36c26bdff 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts @@ -22,7 +22,7 @@ vi.mock('./browser-extension-webstore-download', async (importOriginal) => ({ ...(await importOriginal()), downloadWebStoreCrx: mocks.download })) -vi.mock('../installation/browser-extension-webstore-install', () => ({ +vi.mock('../installation/browser-extension-mutation-lock', () => ({ withBrowserExtensionLock: (_id: string, action: () => Promise) => action(), isBrowserExtensionBusy: () => false })) diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts index 5ffee7341c2..127282b88f6 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts @@ -24,11 +24,13 @@ import { downloadWebStoreCrx, isAllowedCrxDownloadUrl } from './browser-extensio import { commitStagedWebStoreExtension, discardStagedWebStoreExtension, - isBrowserExtensionBusy, stageWebStoreExtension, - withBrowserExtensionLock, type StagedWebStoreExtension } from '../installation/browser-extension-webstore-install' +import { + isBrowserExtensionBusy, + withBrowserExtensionLock +} from '../installation/browser-extension-mutation-lock' /** * Background updates for store installs. Request shape follows electron-chrome-web-store's diff --git a/src/main/browser/guest-lifecycle/browser-event-origin.ts b/src/main/browser/guest-lifecycle/browser-event-origin.ts new file mode 100644 index 00000000000..4bbe595369c --- /dev/null +++ b/src/main/browser/guest-lifecycle/browser-event-origin.ts @@ -0,0 +1,11 @@ +import { normalizeExternalBrowserUrl } from '../../../shared/browser-url' + +export function safeOrigin(rawUrl: string): string { + const external = normalizeExternalBrowserUrl(rawUrl) + const urlToParse = external ?? rawUrl + try { + return new URL(urlToParse).origin + } catch { + return external ?? 'unknown' + } +} diff --git a/src/main/browser/guest-lifecycle/browser-guest-devtools-close-shortcut.ts b/src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-close-shortcut.ts similarity index 95% rename from src/main/browser/guest-lifecycle/browser-guest-devtools-close-shortcut.ts rename to src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-close-shortcut.ts index 462253477d2..7d07a5fef51 100644 --- a/src/main/browser/guest-lifecycle/browser-guest-devtools-close-shortcut.ts +++ b/src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-close-shortcut.ts @@ -1,5 +1,5 @@ -import { keybindingMatchesAction } from '../../../shared/keybindings/matching' -import type { KeybindingInput, KeybindingOverrides } from '../../../shared/keybindings/types' +import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' +import type { KeybindingInput, KeybindingOverrides } from '../../../../shared/keybindings/types' /** Cmd/Ctrl+W in a page's DevTools, docked or in their own window, closes DevTools, not the tab. */ export function installGuestDevToolsCloseShortcut(args: { diff --git a/src/main/browser/guest-lifecycle/browser-guest-devtools-dock.test.ts b/src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.test.ts similarity index 100% rename from src/main/browser/guest-lifecycle/browser-guest-devtools-dock.test.ts rename to src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.test.ts diff --git a/src/main/browser/guest-lifecycle/browser-guest-devtools-dock.ts b/src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.ts similarity index 99% rename from src/main/browser/guest-lifecycle/browser-guest-devtools-dock.ts rename to src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.ts index 9318a4fdc6e..7fc70935add 100644 --- a/src/main/browser/guest-lifecycle/browser-guest-devtools-dock.ts +++ b/src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.ts @@ -1,5 +1,5 @@ import { BrowserWindow, WebContentsView } from 'electron' -import type { BrowserDevToolsDockBounds } from '../../../shared/browser-devtools-dock' +import type { BrowserDevToolsDockBounds } from '../../../../shared/browser-devtools-dock' type DevToolsOpenOperation = { isCurrent: () => boolean diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts b/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts index 876220a3d62..dcdb1765262 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts +++ b/src/main/browser/guest-lifecycle/input/browser-guest-context-menu.ts @@ -6,7 +6,7 @@ import { } from '../../../../shared/browser-url' import type { BrowserContextMenuRequestedEvent } from '../../../../shared/browser-guest-events' import { readContextMenuSpelling } from '../../../window/editable-context-menu' -import { readGuestNavigationState } from '../browser-guest-navigation-state' +import { readGuestNavigationState } from '../navigation/browser-guest-navigation-state' import type { ResolveRenderer } from '../browser-guest-renderer-target' import { buildBrowserExtensionPageContextMenu } from '../../extensions/context-menus/browser-extension-context-menu-host' diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-escape-forwarding.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-escape-forwarding.ts similarity index 94% rename from src/main/browser/guest-lifecycle/input/browser-guest-escape-forwarding.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-escape-forwarding.ts index a736ea12e3c..3156e186d66 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-escape-forwarding.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-escape-forwarding.ts @@ -1,4 +1,4 @@ -import { isAgentInjectingInput } from '../../cdp/input/agent-input-injection' +import { isAgentInjectingInput } from '../../../cdp/input/agent-input-injection' type GuestEscapeTarget = { browserPageId: string; renderer: Electron.WebContents } diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-grab-shortcuts.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-grab-shortcuts.ts similarity index 89% rename from src/main/browser/guest-lifecycle/input/browser-guest-grab-shortcuts.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-grab-shortcuts.ts index f78e67a3253..7281473c4f0 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-grab-shortcuts.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-grab-shortcuts.ts @@ -1,7 +1,7 @@ -import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' -import type { KeybindingOverrides } from '../../../../shared/keybindings/types' -import { isAgentInjectingInput } from '../../cdp/input/agent-input-injection' -import type { ResolveRenderer } from '../browser-guest-renderer-target' +import { keybindingMatchesAction } from '../../../../../shared/keybindings/matching' +import type { KeybindingOverrides } from '../../../../../shared/keybindings/types' +import { isAgentInjectingInput } from '../../../cdp/input/agent-input-injection' +import type { ResolveRenderer } from '../../browser-guest-renderer-target' // Guests swallow renderer shortcuts; keep normal copy when editing or text is selected. export function setupGrabShortcutForwarding(args: { diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-dispatch.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts similarity index 93% rename from src/main/browser/guest-lifecycle/input/browser-guest-shortcut-dispatch.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts index ee469fc0ac0..ab1da348d42 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-dispatch.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-dispatch.ts @@ -1,14 +1,14 @@ import { resolveWindowShortcutAction, type WindowShortcutInput -} from '../../../../shared/window-shortcut-policy' -import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' -import type { KeybindingOverrides } from '../../../../shared/keybindings/types' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' -import type { BrowserPageZoomDirection } from '../../../../shared/browser-page-zoom' -import type { BrowserFindTarget } from '../../../../shared/browser-find-source' -import type { BrowserPageTabShortcut } from '../../../../shared/browser-page-command-target' -import type { ResolveRenderer } from '../browser-guest-renderer-target' +} from '../../../../../shared/window-shortcut-policy' +import { keybindingMatchesAction } from '../../../../../shared/keybindings/matching' +import type { KeybindingOverrides } from '../../../../../shared/keybindings/types' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../shared/constants' +import type { BrowserPageZoomDirection } from '../../../../../shared/browser-page-zoom' +import type { BrowserFindTarget } from '../../../../../shared/browser-find-source' +import type { BrowserPageTabShortcut } from '../../../../../shared/browser-page-command-target' +import type { ResolveRenderer } from '../../browser-guest-renderer-target' import { matchesGuestTabShortcut } from './browser-guest-tab-shortcut' export type ShouldForwardDictationShortcut = () => boolean diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-forwarding.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.ts similarity index 90% rename from src/main/browser/guest-lifecycle/input/browser-guest-shortcut-forwarding.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.ts index 99dde606a90..a51f774436b 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-forwarding.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding.ts @@ -1,18 +1,18 @@ -import { isAgentInjectingInput } from '../../cdp/input/agent-input-injection' +import { isAgentInjectingInput } from '../../../cdp/input/agent-input-injection' import { isRecentTabSwitcherCommitRelease, matchesRecentTabSwitcherChord, nativeZoomCommandMatchesKeybindings, resolveWindowShortcutAction -} from '../../../../shared/window-shortcut-policy' -import type { KeybindingOverrides } from '../../../../shared/keybindings/types' -import type { BrowserPageZoomDirection } from '../../../../shared/browser-page-zoom' +} from '../../../../../shared/window-shortcut-policy' +import type { KeybindingOverrides } from '../../../../../shared/keybindings/types' +import type { BrowserPageZoomDirection } from '../../../../../shared/browser-page-zoom' import { ModifierDoubleTapDetector, toModifierDoubleTapEvent -} from '../../../../shared/modifier-double-tap-detector' -import type { ResolveRenderer } from '../browser-guest-renderer-target' -import { consumeRecentGuestWheelZoom } from './browser-guest-wheel-zoom' +} from '../../../../../shared/modifier-double-tap-detector' +import type { ResolveRenderer } from '../../browser-guest-renderer-target' +import { consumeRecentGuestWheelZoom } from '../browser-guest-wheel-zoom' import { forwardGuestShortcutInput, type GuestShortcutForwardContext, diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-plugin-frame.test.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-plugin-frame.test.ts similarity index 100% rename from src/main/browser/guest-lifecycle/input/browser-guest-shortcut-plugin-frame.test.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-plugin-frame.test.ts diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-precedence.test.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-precedence.test.ts similarity index 90% rename from src/main/browser/guest-lifecycle/input/browser-guest-shortcut-precedence.test.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-precedence.test.ts index 435c2669805..1e86c4e3398 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-shortcut-precedence.test.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-precedence.test.ts @@ -15,10 +15,10 @@ vi.mock('electron', async () => { }) import { BrowserWindow } from 'electron' -import { findKeybindingConflicts } from '../../../../shared/keybindings/formatting' -import { isKeybindingInterceptedByMainProcess } from '../../../../shared/keybindings/effective' -import { KEYBINDING_DEFINITIONS } from '../../../../shared/keybindings/definitions' -import type { KeybindingOverrides } from '../../../../shared/keybindings/types' +import { findKeybindingConflicts } from '../../../../../shared/keybindings/formatting' +import { isKeybindingInterceptedByMainProcess } from '../../../../../shared/keybindings/effective' +import { KEYBINDING_DEFINITIONS } from '../../../../../shared/keybindings/definitions' +import type { KeybindingOverrides } from '../../../../../shared/keybindings/types' import { setupGuestShortcutForwarding } from './browser-guest-shortcut-forwarding' const CHORD = 'Mod+Alt+Shift+1' diff --git a/src/main/browser/guest-lifecycle/input/browser-guest-tab-shortcut.ts b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-tab-shortcut.ts similarity index 69% rename from src/main/browser/guest-lifecycle/input/browser-guest-tab-shortcut.ts rename to src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-tab-shortcut.ts index 6a142b022c3..99db5e67d89 100644 --- a/src/main/browser/guest-lifecycle/input/browser-guest-tab-shortcut.ts +++ b/src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-tab-shortcut.ts @@ -1,7 +1,10 @@ -import { KEYBINDING_DEFINITIONS } from '../../../../shared/keybindings/definitions' -import { keybindingMatchesAction } from '../../../../shared/keybindings/matching' -import type { KeybindingActionId, KeybindingOverrides } from '../../../../shared/keybindings/types' -import type { WindowShortcutInput } from '../../../../shared/window-shortcut-policy' +import { KEYBINDING_DEFINITIONS } from '../../../../../shared/keybindings/definitions' +import { keybindingMatchesAction } from '../../../../../shared/keybindings/matching' +import type { + KeybindingActionId, + KeybindingOverrides +} from '../../../../../shared/keybindings/types' +import type { WindowShortcutInput } from '../../../../../shared/window-shortcut-policy' // Why: neither acts on a page (open-markdown has no app-wide owner, rename only renames terminal and // chat tabs), so claiming them would only take the chord from the page. diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-bindings.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-bindings.ts index 5e4bb955f01..df201f6595b 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-bindings.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-bindings.ts @@ -1,10 +1,10 @@ import { resolveRendererWebContents } from '../browser-guest-renderer-target' import { setupGuestContextMenu } from '../input/browser-guest-context-menu' -import { setupGrabShortcutForwarding } from '../input/browser-guest-grab-shortcuts' +import { setupGrabShortcutForwarding } from '../input/shortcuts/browser-guest-grab-shortcuts' import { setupGuestMouseWheelZoomForwarding } from '../input/browser-guest-wheel-zoom' -import { setupGuestShortcutForwarding } from '../input/browser-guest-shortcut-forwarding' +import { setupGuestShortcutForwarding } from '../input/shortcuts/browser-guest-shortcut-forwarding' import { setupGuestTargetUrlForwarding } from '../input/browser-guest-target-url' -import { BrowserManagerGrab } from './browser-manager-grab' +import { BrowserManagerGrab } from './grab/browser-manager-grab' export abstract class BrowserManagerBindings extends BrowserManagerGrab { protected setupContextMenu(browserTabId: string, guest: Electron.WebContents): void { diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-event-forwarding.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-event-forwarding.ts index 2ef00abea55..497fbdfbc83 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-event-forwarding.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-event-forwarding.ts @@ -4,7 +4,10 @@ import type { } from '../../../../shared/browser-guest-events' import { redactKagiSessionToken } from '../../../../shared/browser-url' import { BrowserManagerBindings } from './browser-manager-bindings' -import type { PendingPermissionEvent, PendingPopupEvent } from './browser-manager-types' + +export type PendingPermissionEvent = Omit + +export type PendingPopupEvent = Omit export abstract class BrowserManagerEventForwarding extends BrowserManagerBindings { protected forwardOrQueueGuestLoadFailure( diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts index 3986d0beaef..e12c6c44fd5 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts @@ -35,11 +35,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' +import { browserManager } from './browser-manager' import { rendererPublicationThrottle } from '../../../window/renderer-publication-throttle' import { rendererWebContentsId, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts index 384b1dc9938..39148d307f6 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-queries.ts @@ -5,8 +5,9 @@ import type { } from '../../../../shared/browser-workspace-types' import type { ManagedBrowserGuestContext } from '../../certificate-trust/browser-certificate-challenge' import { redactKagiSessionToken } from '../../../../shared/browser-url' -import { safeOrigin, type BrowserPopupPage } from './browser-manager-types' -import { BrowserManagerRegistration } from './browser-manager-registration' +import { safeOrigin } from '../browser-event-origin' +import type { BrowserPopupPage } from '../popups/browser-popup-ownership' +import { BrowserManagerRegistration } from './registration/browser-manager-registration' import { isBrowserRouteGuestPopup, listBrowserRouteGuestPopups @@ -112,6 +113,13 @@ export abstract class BrowserManagerQueries extends BrowserManagerRegistration { : (this.loadErrorsByGuestId.get(webContentsId) ?? null) } + getBrowserPageRemoteTabFaviconUrl(browserPageId: string): string | null { + const webContentsId = this.webContentsIdByTabId.get(browserPageId) + return webContentsId === undefined + ? null + : (this.remoteTabFaviconUrlByGuestId.get(webContentsId) ?? null) + } + getBrowserPageCertificateFailure(browserPageId: string): BrowserCertificateFailure | null { return this.certificateTrustController?.getFailure(browserPageId) ?? null } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts index c911e349849..70c46275235 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-state.ts @@ -1,31 +1,30 @@ import { BrowserGrabSessionController } from '../../element-grab/browser-grab-session-controller' import type { BrowserCertificateTrustController } from '../../certificate-trust/browser-certificate-trust-controller' -import type { BrowserSiteDisplayController } from '../../site-settings/browser-site-display-controller' -import { - createPageInitiatedTabBudget, - type PageInitiatedTabBudget -} from '../popups/browser-page-initiated-tab-budget' +import type { BrowserSiteDisplayController } from '../../site-settings/display/browser-site-display-controller' +import { createPageInitiatedTabBudget } from '../popups/browser-page-initiated-tab-budget' +import type { PageInitiatedTabBudget } from '../popups/browser-page-initiated-tab-budget' import type { KeybindingOverrides } from '../../../../shared/keybindings/types' import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' import { resolveBrowserRouteGuestPopupOpener } from '../../routing/guest-authority/browser-route-guest-popup-ownership' import type { BrowserPagePromptTarget } from '../prompts/browser-page-prompts' -import type { - ActiveDownload, - CdpUserAgentOverrideState, - PendingMainFrameNavigation, - PendingPermissionEvent, - PendingPopupEvent, - BrowserGuestPolicy, - BrowserManagerLoadError, - PopupOwnerContext -} from './browser-manager-types' +import type { ActiveDownload } from './downloads/browser-active-download' +import type { CdpUserAgentOverrideState } from './navigation/browser-user-agent-override-state' +import type { PendingMainFrameNavigation } from './navigation/browser-main-frame-navigation' +import type { PendingPermissionEvent, PendingPopupEvent } from './browser-manager-event-forwarding' +import type { BrowserGuestPolicy } from './registration/browser-guest-policy-profile' +import type { PopupOwnerContext } from '../popups/browser-popup-ownership' import type { BrowserDownloadFinishedEvent, BrowserDownloadProgressEvent } from '../../../../shared/browser-guest-events' import type { BrowserGrabCancelReason } from '../../../../shared/browser-grab-types' -import { BrowserManagerViewportScrollState } from './browser-manager-viewport-scroll-state' -import { BrowserGuestDevToolsDock } from '../browser-guest-devtools-dock' +import { BrowserManagerViewportScrollState } from './viewport/browser-manager-viewport-scroll-state' +import { BrowserGuestDevToolsDock } from '../devtools/browser-guest-devtools-dock' + +export type BrowserManagerSettings = { + keybindings?: KeybindingOverrides + mobileEmulatorEnabled?: boolean +} /** A link a headless serve page asked to open as an Orca tab beside it. */ export type OffscreenBrowserTabOpenRequest = { @@ -60,7 +59,7 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt ): BrowserLoadError protected abstract forwardOrQueueGuestLoadFailure( guestWebContentsId: number, - loadError: BrowserManagerLoadError + loadError: BrowserLoadError ): void protected abstract forwardOrQueuePermissionDenied( guestWebContentsId: number, @@ -133,12 +132,7 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt activate?: boolean ): boolean - protected settingsResolver: - | (() => { - keybindings?: KeybindingOverrides - mobileEmulatorEnabled?: boolean - }) - | null = null + protected settingsResolver: (() => BrowserManagerSettings) | null = null protected readonly webContentsIdByTabId = new Map() protected readonly tabIdByWebContentsId = new Map() protected readonly popupOwnerContextByGuestId = new Map() @@ -170,6 +164,8 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt protected readonly loadErrorsByGuestId = new Map() // Restore the optimistically hidden error if navigation aborts. protected readonly clearedLoadErrorsByGuestId = new Map() + // Offscreen pages have no renderer to hold their icon for session-tab rows. + protected readonly remoteTabFaviconUrlByGuestId = new Map() protected browserGuestStateChangedListener: ((worktreeId: string) => void) | null = null protected offscreenTabOpener: ((request: OffscreenBrowserTabOpenRequest) => void) | null = null protected certificateTrustController: BrowserCertificateTrustController | null = null @@ -218,12 +214,7 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt return this.settingsResolver?.().keybindings } - setSettingsResolver( - resolver: () => { - keybindings?: KeybindingOverrides - mobileEmulatorEnabled?: boolean - } - ): void { + setSettingsResolver(resolver: () => BrowserManagerSettings): void { this.settingsResolver = resolver } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts index bdb7bebaa6b..6729d982e76 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-test-harness.ts @@ -1,5 +1,5 @@ import { vi, type Mock } from 'vitest' -import { browserManager } from '../../browser-manager' +import { browserManager } from './browser-manager' export const rendererWebContentsId = 5001 export const guestBaseUserAgent = 'Mozilla/5.0 (Test) Chrome/140.0.0.0' diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-types.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-types.ts deleted file mode 100644 index 17aee26bb7e..00000000000 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-types.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { normalizeExternalBrowserUrl } from '../../../../shared/browser-url' -import type { CdpUserAgentMetadata } from '../../identity/browser-tab-identity' -import type { - BrowserDownloadFinishedEvent, - BrowserDownloadProgressEvent, - BrowserPermissionDeniedEvent, - BrowserPopupEvent -} from '../../../../shared/browser-guest-events' -import type { - BrowserGrabCancelReason, - BrowserGrabPayload, - BrowserGrabRect, - BrowserGrabResult, - BrowserGrabScreenshot -} from '../../../../shared/browser-grab-types' -import type { BrowserClientDownloadRoute } from '../../client-hosts/file-transfers/browser-client-download-relay' -import type { BrowserLoadError } from '../../../../shared/browser-workspace-types' -import type { KeybindingOverrides } from '../../../../shared/keybindings/types' - -export function isChromiumInternalErrorUrl(url: string): boolean { - return url.startsWith('chrome-error://') -} - -export type BrowserGuestRegistration = { - browserPageId?: string - browserTabId?: string - workspaceId?: string - worktreeId?: string - sessionProfileId?: string | null - webContentsId: number - rendererWebContentsId: number -} - -export type PendingPermissionEvent = Omit -export type PendingPopupEvent = Omit -export type BrowserDownloadDoneState = 'completed' | 'cancelled' | 'interrupted' -export type PopupOwnerContext = { - browserTabId: string - rootGuestWebContentsId: number -} -/** A live popup window an agent can drive, owned by the tab whose page opened its chain. */ -export type BrowserPopupPage = { - browserPageId: string - webContentsId: number - openerBrowserPageId: string -} - -/** Document guests render one grant and report only to its host; browsing policies do not apply. */ -export type BrowserGuestPolicy = - | { profile: 'browsing' } - | { profile: 'workspace-doc'; host: Electron.WebContents } - -export const BROWSING_GUEST_POLICY: BrowserGuestPolicy = { profile: 'browsing' } - -export type PendingMainFrameNavigation = { - currentUrl: string - supersededUrls: string[] -} - -/** An empty userAgent clears the CDP override. */ -export type CdpUserAgentOverride = { - userAgent: string - userAgentMetadata?: CdpUserAgentMetadata -} - -export type CdpUserAgentOverrideOperation = { - sequence: number - override: CdpUserAgentOverride -} - -export type CdpUserAgentOverrideState = { - confirmed: CdpUserAgentOverrideOperation | null - nextSequence: number - pending: CdpUserAgentOverrideOperation[] -} - -export const SAFE_POPUP_WINDOW_OPTIONS = { - alwaysOnTop: false, - closable: true, - focusable: true, - frame: true, - fullscreen: false, - kiosk: false, - modal: false, - movable: true, - opacity: 1, - show: true, - simpleFullscreen: false, - skipTaskbar: false, - titleBarStyle: 'default', - transparent: false, - // Apply isolation before createWindow so features and opener inheritance cannot weaken it. - webPreferences: { - allowRunningInsecureContent: false, - contextIsolation: true, - nodeIntegration: false, - nodeIntegrationInSubFrames: false, - sandbox: true, - webviewTag: false - } -} satisfies Electron.BrowserWindowConstructorOptions - -export type ActiveDownload = { - downloadId: string - guestWebContentsId: number - browserTabId: string | null - rendererWebContentsId: number | null - origin: string - filename: string - totalBytes: number | null - mimeType: string | null - item: Electron.DownloadItem - savePath: string - reservationKey: string | null - clientRoute: BrowserClientDownloadRoute | null - remoteDestination: BrowserDownloadFinishedEvent['remoteDestination'] - receivedBytes: number - transientState: BrowserDownloadProgressEvent['state'] - terminalEvent: BrowserDownloadFinishedEvent | null - startedSent: boolean - cleanup: (() => void) | null - onFinished: ((event: BrowserDownloadFinishedEvent) => void) | null -} - -export function safeOrigin(rawUrl: string): string { - const external = normalizeExternalBrowserUrl(rawUrl) - const urlToParse = external ?? rawUrl - try { - return new URL(urlToParse).origin - } catch { - return external ?? 'unknown' - } -} - -export type BrowserManagerSettings = { - keybindings?: KeybindingOverrides - mobileEmulatorEnabled?: boolean -} - -export type BrowserManagerLoadError = Pick< - BrowserLoadError, - 'code' | 'description' | 'validatedUrl' -> - -export type BrowserManagerGrabTypes = { - cancelReason: BrowserGrabCancelReason - payload: BrowserGrabPayload - rect: BrowserGrabRect - result: BrowserGrabResult - screenshot: BrowserGrabScreenshot -} diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts index e058fa84f13..90e6bafedd9 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager-visibility.ts @@ -9,8 +9,8 @@ import { BrowserAgentActivity, type AgentCommandLease, type AgentPointerInput -} from '../browser-agent-activity' -import { BrowserPageEvents, type BrowserPageEvent } from '../browser-page-events' +} from '../page-activity/browser-agent-activity' +import { BrowserPageEvents, type BrowserPageEvent } from '../page-activity/browser-page-events' import { BrowserPageInputCredit } from '../../routing/input-ownership/browser-page-input-credit' import { browserPopupPageId } from '../popups/browser-popup-page-id' import type { RpcCallerIdentity } from '../../../runtime/rpc/rpc-caller-identity' diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-final.ts b/src/main/browser/guest-lifecycle/manager/browser-manager.ts similarity index 69% rename from src/main/browser/guest-lifecycle/manager/browser-manager-final.ts rename to src/main/browser/guest-lifecycle/manager/browser-manager.ts index 93f265db28a..acb3a3bfa71 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-final.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager.ts @@ -1,10 +1,12 @@ +import { webContents } from 'electron' +import { BrowserCertificateTrustController } from '../../certificate-trust/browser-certificate-trust-controller' import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import { BrowserManagerEventForwarding } from './browser-manager-event-forwarding' type OpenLinkInTab = (url: string, activate: boolean) => void -export abstract class BrowserManagerFinal extends BrowserManagerEventForwarding { +export class BrowserManager extends BrowserManagerEventForwarding { protected openLinkInOrcaTab(browserTabId: string, rawUrl: string, activate?: boolean): boolean { const renderer = this.resolveRendererForBrowserTab(browserTabId) const open: OpenLinkInTab | null = renderer @@ -48,3 +50,15 @@ export abstract class BrowserManagerFinal extends BrowserManagerEventForwarding }) } } + +export const browserManager = new BrowserManager() +export const browserCertificateTrustController = new BrowserCertificateTrustController({ + resolveManagedGuestContext: (webContentsId) => + browserManager.getManagedBrowserGuestContext(webContentsId), + resolveWebContentsIdForPage: (browserPageId) => + browserManager.getGuestWebContentsId(browserPageId), + resolveWebContents: (webContentsId) => webContents.fromId(webContentsId) ?? null, + onFailureChanged: (webContentsId, failure, navigationUrl) => + browserManager.notifyCertificateFailureChanged(webContentsId, failure, navigationUrl) +}) +browserManager.setCertificateTrustController(browserCertificateTrustController) diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-devtools-retirement.test.ts b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-devtools-retirement.test.ts rename to src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts index 02dd26afe42..365734a9ce4 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-devtools-retirement.test.ts +++ b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts @@ -1,5 +1,6 @@ import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { BrowserManager } from '../browser-manager' type DevToolsHost = EventEmitter & { isDestroyed: () => boolean } type HeldDevToolsView = { release: () => void; destroyed: boolean } @@ -45,12 +46,10 @@ vi.mock('electron', () => { webContents: { fromId: (id: number) => native.byId.get(id) } } }) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: vi.fn() })) -import { BrowserManager } from '../../browser-manager' - function createGuest(id: number) { let destroyed = false let opened = false diff --git a/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools.ts b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools.ts new file mode 100644 index 00000000000..c627f72c0c8 --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools.ts @@ -0,0 +1,121 @@ +import { webContents } from 'electron' +import { BrowserManagerDownloadLifecycle } from '../downloads/browser-manager-download-lifecycle' +import type { BrowserDevToolsDockBounds } from '../../../../../shared/browser-devtools-dock' + +export abstract class BrowserManagerDevTools extends BrowserManagerDownloadLifecycle { + async openDevTools( + browserTabId: string, + inspectAt?: { x: number; y: number }, + options?: { detach?: boolean } + ): Promise { + const guest = this.resolveDevToolsGuest(browserTabId) + if (!guest) { + return false + } + const renderer = this.resolveRendererForBrowserTab(browserTabId) + const operation = this.devToolsDock.beginOpen( + guest, + () => + this.webContentsIdByTabId.get(browserTabId) === guest.id && + !this.offscreenGuestIds.has(guest.id) && + (!renderer || + (this.resolveRendererForBrowserTab(browserTabId) === renderer && !renderer.isDestroyed())) + ) + const notify = (docked: boolean): void => { + const currentGuestId = this.webContentsIdByTabId.get(browserTabId) + if ( + renderer && + !renderer.isDestroyed() && + (currentGuestId === undefined || + currentGuestId === guest.id || + (!docked && !this.devToolsDock.isDocked(currentGuestId))) + ) { + renderer.send('browser:devToolsDockChanged', { browserPageId: browserTabId, docked }) + } + } + try { + let docked = false + if (!options?.detach && renderer) { + docked = await this.devToolsDock.open(guest, () => notify(false), operation) + if (!operation.isCurrent()) { + return false + } + } + if (!docked && !(await this.devToolsDock.openDetached(guest, operation))) { + return false + } + if (!operation.isCurrent()) { + return false + } + if (docked) { + notify(true) + } + if (!operation.isCurrent()) { + return false + } + if (inspectAt) { + // Open first: inspectElement alone opens Electron's own DevTools and bypasses the dock. + guest.inspectElement(inspectAt.x, inspectAt.y) + } + return true + } finally { + operation.finish() + } + } + + closeDevTools(browserTabId: string): void { + const guest = this.resolveDevToolsGuest(browserTabId) + if (guest) { + this.closeGuestDevTools(guest) + } + } + + /** Toggles the page DevTools of `focused` (the page or its DevTools); false if it is neither. */ + toggleDevToolsOfFocusedPage(focused: Electron.WebContents): boolean { + for (const [browserTabId, guestId] of this.webContentsIdByTabId) { + const guest = webContents.fromId(guestId) + if (!guest || guest.isDestroyed()) { + continue + } + if (guest !== focused && guest.devToolsWebContents !== focused) { + continue + } + if ( + this.devToolsDock.isOpening(guest.id) || + this.devToolsDock.isDocked(guest.id) || + guest.isDevToolsOpened() + ) { + this.closeGuestDevTools(guest) + } else { + void this.openDevTools(browserTabId) + } + return true + } + return false + } + + setDevToolsDockBounds( + browserTabId: string, + bounds: BrowserDevToolsDockBounds | null, + snapshot: boolean + ): Promise { + const guestId = this.webContentsIdByTabId.get(browserTabId) + return guestId === undefined + ? Promise.resolve(null) + : this.devToolsDock.setBounds(guestId, bounds, snapshot) + } + + private resolveDevToolsGuest(browserTabId: string): Electron.WebContents | null { + const webContentsId = this.webContentsIdByTabId.get(browserTabId) + if (!webContentsId) { + return null + } + const guest = webContents.fromId(webContentsId) + if (!guest || guest.isDestroyed()) { + this.unregisterGuest(browserTabId) + return null + } + // Offscreen DevTools would open on the server desktop without a route back to the client. + return this.offscreenGuestIds.has(webContentsId) ? null : guest + } +} diff --git a/src/main/browser/guest-lifecycle/manager/downloads/browser-active-download.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-active-download.ts new file mode 100644 index 00000000000..def72c555b5 --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-active-download.ts @@ -0,0 +1,29 @@ +import type { + BrowserDownloadFinishedEvent, + BrowserDownloadProgressEvent +} from '../../../../../shared/browser-guest-events' +import type { BrowserClientDownloadRoute } from '../../../client-hosts/file-transfers/browser-client-download-relay' + +export type BrowserDownloadDoneState = 'completed' | 'cancelled' | 'interrupted' + +export type ActiveDownload = { + downloadId: string + guestWebContentsId: number + browserTabId: string | null + rendererWebContentsId: number | null + origin: string + filename: string + totalBytes: number | null + mimeType: string | null + item: Electron.DownloadItem + savePath: string + reservationKey: string | null + clientRoute: BrowserClientDownloadRoute | null + remoteDestination: BrowserDownloadFinishedEvent['remoteDestination'] + receivedBytes: number + transientState: BrowserDownloadProgressEvent['state'] + terminalEvent: BrowserDownloadFinishedEvent | null + startedSent: boolean + cleanup: (() => void) | null + onFinished: ((event: BrowserDownloadFinishedEvent) => void) | null +} diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-client-hosted-downloads.test.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts similarity index 90% rename from src/main/browser/guest-lifecycle/manager/browser-manager-client-hosted-downloads.test.ts rename to src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts index 356ed144eda..eed58334674 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-client-hosted-downloads.test.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts @@ -25,31 +25,31 @@ vi.mock('electron', () => ({ webContents: { fromId: browserMocks.webContentsFromIdMock } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) import { mkdtemp, readdir, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' -import { browserManager } from '../../browser-manager' -import { BrowserClientDownloadRelay } from '../../client-hosts/file-transfers/browser-client-download-relay' -import { BrowserClientFileChannelTransport } from '../../client-hosts/file-transfers/browser-client-file-channel-transport' -import type { BrowserClientHostedPageInventory } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' +import { browserManager } from '../browser-manager' +import { BrowserClientDownloadRelay } from '../../../client-hosts/file-transfers/browser-client-download-relay' +import { BrowserClientFileChannelTransport } from '../../../client-hosts/file-transfers/browser-client-file-channel-transport' +import type { BrowserClientHostedPageInventory } from '../../../../../shared/browser/client-hosting/browser-client-host-protocol' import { registerBrowserClientDownloadRouter, resetBrowserClientDownloadRouting, setBrowserClientRouteWebContentsProbe -} from '../../client-hosts/file-transfers/browser-client-download-routing' -import { createBrowserClientPageGuestBinding } from '../../client-pages/lifecycle/browser-client-page-guest-binding' -import { resetBrowserRouteGuestPopupOwnership } from '../../routing/guest-authority/browser-route-guest-popup-ownership' +} from '../../../client-hosts/file-transfers/browser-client-download-routing' +import { createBrowserClientPageGuestBinding } from '../../../client-pages/lifecycle/browser-client-page-guest-binding' +import { resetBrowserRouteGuestPopupOwnership } from '../../../routing/guest-authority/browser-route-guest-popup-ownership' import { createDownloadItem, getDownloadItemEventHandler, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const GUEST_WEB_CONTENTS_ID = 6100 const SERVER_GUEST_WEB_CONTENTS_ID = 6103 diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-downloads.test.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-destroyed-guest-downloads.test.ts similarity index 92% rename from src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-downloads.test.ts rename to src/main/browser/guest-lifecycle/manager/downloads/browser-manager-destroyed-guest-downloads.test.ts index 0adb36484f0..4ef4a966756 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-downloads.test.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-destroyed-guest-downloads.test.ts @@ -10,15 +10,15 @@ vi.mock('electron', () => ({ screen: { getCursorScreenPoint: () => ({ x: 0, y: 0 }) }, webContents: { fromId: (id: number) => mocks.contents.get(id) ?? null } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: vi.fn() })) import { DestroyedGuestTestContents, DestroyedGuestTestManager -} from './browser-manager-destroyed-guest-test-fixture' -import { createDownloadItem, getDownloadItemEventHandler } from './browser-manager-test-harness' +} from '../registration/browser-manager-destroyed-guest-test-fixture' +import { createDownloadItem, getDownloadItemEventHandler } from '../browser-manager-test-harness' const event = { preventDefault: () => {}, defaultPrevented: false } const manager = new DestroyedGuestTestManager() diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-download-creation.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-creation.ts similarity index 94% rename from src/main/browser/guest-lifecycle/manager/browser-manager-download-creation.ts rename to src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-creation.ts index 6dd64a7a7f6..887ee604cfe 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-download-creation.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-creation.ts @@ -1,15 +1,12 @@ import { randomUUID } from 'node:crypto' import path from 'node:path' -import { BrowserError } from '../../browser-error' -import { browserDownloadDestinationReservations } from '../../downloads/browser-download-destination' -import { routeBrowserClientDownload } from '../../client-hosts/file-transfers/browser-client-download-routing' -import { - safeOrigin, - type ActiveDownload, - type BrowserDownloadDoneState -} from './browser-manager-types' -import type { BrowserDownloadFinishedEvent } from '../../../../shared/browser-guest-events' -import { BrowserManagerQueries } from './browser-manager-queries' +import { BrowserError } from '../../../browser-error' +import { browserDownloadDestinationReservations } from '../../../downloads/browser-download-destination' +import { routeBrowserClientDownload } from '../../../client-hosts/file-transfers/browser-client-download-routing' +import { safeOrigin } from '../../browser-event-origin' +import type { ActiveDownload, BrowserDownloadDoneState } from './browser-active-download' +import type { BrowserDownloadFinishedEvent } from '../../../../../shared/browser-guest-events' +import { BrowserManagerQueries } from '../browser-manager-queries' export type BrowserDownloadClaim = { started: Promise diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-download-lifecycle.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-lifecycle.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-download-lifecycle.ts rename to src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-lifecycle.ts index e48443d38be..55ab6c69530 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-download-lifecycle.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-download-lifecycle.ts @@ -1,10 +1,10 @@ -import { browserDownloadDestinationReservations } from '../../downloads/browser-download-destination' +import { browserDownloadDestinationReservations } from '../../../downloads/browser-download-destination' import type { BrowserDownloadFinishedEvent, BrowserDownloadProgressEvent, BrowserDownloadRequestedEvent -} from '../../../../shared/browser-guest-events' -import type { ActiveDownload } from './browser-manager-types' +} from '../../../../../shared/browser-guest-events' +import type { ActiveDownload } from './browser-active-download' import { BrowserManagerDownloadCreation } from './browser-manager-download-creation' export abstract class BrowserManagerDownloadLifecycle extends BrowserManagerDownloadCreation { diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-downloads.test.ts b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-downloads.test.ts similarity index 95% rename from src/main/browser/guest-lifecycle/manager/browser-manager-downloads.test.ts rename to src/main/browser/guest-lifecycle/manager/downloads/browser-manager-downloads.test.ts index 752e92b147f..5534a0914fc 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-downloads.test.ts +++ b/src/main/browser/guest-lifecycle/manager/downloads/browser-manager-downloads.test.ts @@ -36,19 +36,19 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' -import { browserDownloadDestinationReservations } from '../../downloads/browser-download-destination' +import { browserManager } from '../browser-manager' +import { browserDownloadDestinationReservations } from '../../../downloads/browser-download-destination' import { createDownloadItem, getDownloadItemEventHandler, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-capture.test.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-capture.test.ts similarity index 96% rename from src/main/browser/guest-lifecycle/manager/browser-manager-grab-capture.test.ts rename to src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-capture.test.ts index 09d3c27d182..499c71244a2 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-capture.test.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-capture.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { GRAB_BUDGET } from '../../../../shared/browser-grab-types' +import { GRAB_BUDGET } from '../../../../../shared/browser-grab-types' const grabMocks = vi.hoisted(() => ({ webContentsFromIdMock: vi.fn(), @@ -24,7 +24,7 @@ vi.mock('electron', () => ({ webContents: { fromId: grabMocks.webContentsFromIdMock } })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { resetGrabTestEnvironment } from './browser-manager-grab-test-harness' const { guestCapturePageMock, guestExecuteJavaScriptMock } = grabMocks diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-mode.test.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-mode.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-grab-mode.test.ts rename to src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-mode.test.ts index 387021b26f8..6aa573a26ca 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-mode.test.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-mode.test.ts @@ -23,7 +23,7 @@ vi.mock('electron', () => ({ webContents: { fromId: grabMocks.webContentsFromIdMock } })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { GRAB_RENDERER_WEB_CONTENTS_ID, resetGrabTestEnvironment diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-selection.test.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-selection.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-grab-selection.test.ts rename to src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-selection.test.ts index b0add27c895..1c2c5c5a651 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-selection.test.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-selection.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserGrabPayload } from '../../../../shared/browser-grab-types' +import type { BrowserGrabPayload } from '../../../../../shared/browser-grab-types' const grabMocks = vi.hoisted(() => ({ webContentsFromIdMock: vi.fn(), @@ -24,7 +24,7 @@ vi.mock('electron', () => ({ webContents: { fromId: grabMocks.webContentsFromIdMock } })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { GRAB_GUEST_WEB_CONTENTS_ID, GRAB_RENDERER_WEB_CONTENTS_ID, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-test-harness.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-grab-test-harness.ts rename to src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts index 84adc2d8fb0..6cbc482dcf4 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-grab-test-harness.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-test-harness.ts @@ -1,5 +1,5 @@ import { vi, type Mock } from 'vitest' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' export const GRAB_RENDERER_WEB_CONTENTS_ID = 5001 export const GRAB_GUEST_WEB_CONTENTS_ID = 101 diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-grab.ts b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab.ts similarity index 88% rename from src/main/browser/guest-lifecycle/manager/browser-manager-grab.ts rename to src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab.ts index ef1a5e2a70b..fd090508dfc 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-grab.ts +++ b/src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab.ts @@ -1,19 +1,19 @@ import { webContents } from 'electron' -import { buildGuestOverlayScript } from '../../element-grab/grab-guest-script' -import { clampGrabPayload } from '../../element-grab/browser-grab-payload' -import { captureSelectionScreenshot as captureGrabSelectionScreenshot } from '../../element-grab/browser-grab-screenshot' +import { buildGuestOverlayScript } from '../../../element-grab/grab-guest-script' +import { clampGrabPayload } from '../../../element-grab/browser-grab-payload' +import { captureSelectionScreenshot as captureGrabSelectionScreenshot } from '../../../element-grab/browser-grab-screenshot' import { getWorkspaceDocPageGuest, readDocPreviewGuestDocumentUrl -} from '../../document-preview/doc-preview-guest-policy' +} from '../../../document-preview/doc-preview-guest-policy' import type { BrowserGrabCancelReason, BrowserGrabResult, BrowserGrabRect, BrowserGrabPayload, BrowserGrabScreenshot -} from '../../../../shared/browser-grab-types' -import { BrowserManagerViewport } from './browser-manager-viewport' +} from '../../../../../shared/browser-grab-types' +import { BrowserManagerViewport } from '../viewport/browser-manager-viewport' export abstract class BrowserManagerGrab extends BrowserManagerViewport { /** Authorize tools for browsing and document guests; documents stay outside browsing maps. */ diff --git a/src/main/browser/guest-lifecycle/manager/navigation/browser-main-frame-navigation.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-main-frame-navigation.ts new file mode 100644 index 00000000000..bc5a828c8ad --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-main-frame-navigation.ts @@ -0,0 +1,8 @@ +export function isChromiumInternalErrorUrl(url: string): boolean { + return url.startsWith('chrome-error://') +} + +export type PendingMainFrameNavigation = { + currentUrl: string + supersededUrls: string[] +} diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-auth-user-agent.test.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-auth-user-agent.test.ts similarity index 94% rename from src/main/browser/guest-lifecycle/manager/browser-manager-auth-user-agent.test.ts rename to src/main/browser/guest-lifecycle/manager/navigation/browser-manager-auth-user-agent.test.ts index 49739d5e20c..5c533dbb08f 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-auth-user-agent.test.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-auth-user-agent.test.ts @@ -37,11 +37,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -vi.mock('../../identity/browser-process-user-agent', () => ({ +vi.mock('../../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: browserMocks.processUserAgentMode, userAgent: browserMocks.processUserAgent, @@ -52,21 +52,21 @@ vi.mock('../../identity/browser-process-user-agent', () => ({ }) })) -vi.mock('../../identity/browser-tab-identity', async (importOriginal) => +vi.mock('../../../identity/browser-tab-identity', async (importOriginal) => ( - await import('./browser-manager-desktop-ua-metadata-test-fixture') + await import('../viewport/browser-manager-desktop-ua-metadata-test-fixture') ).withPinnedDesktopUserAgentMetadata(await importOriginal()) ) -import { browserManager } from '../../browser-manager' -import { googleAuthUserAgent } from '../../identity/browser-google-auth-ua' +import { browserManager } from '../browser-manager' +import { googleAuthUserAgent } from '../../../identity/browser-google-auth-ua' import { guestBaseUserAgent, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' -import { pinnedDesktopUserAgentMetadata as desktopMetadata } from './browser-manager-desktop-ua-metadata-test-fixture' +} from '../browser-manager-test-harness' +import { pinnedDesktopUserAgentMetadata as desktopMetadata } from '../viewport/browser-manager-desktop-ua-metadata-test-fixture' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-navigation-policy.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts similarity index 79% rename from src/main/browser/guest-lifecycle/manager/browser-manager-guest-navigation-policy.ts rename to src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts index a8ae2b74d31..cf70c4ee0bc 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-navigation-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-guest-navigation-policy.ts @@ -1,16 +1,21 @@ import { normalizeBrowserNavigationUrl, toSecureCertificateEndpoint -} from '../../../../shared/browser-url' -import { isChromiumInternalErrorUrl } from './browser-manager-types' -import { watchDecisionBlockedMainFrames } from '../../sessions/requests/browser-session-request-decisions' +} from '../../../../../shared/browser-url' +import { isChromiumInternalErrorUrl } from './browser-main-frame-navigation' +import { watchDecisionBlockedMainFrames } from '../../../sessions/requests/browser-session-request-decisions' import { BrowserManagerGuestPopupPolicy, isLocalFileLinkFromLocalPage -} from './browser-manager-guest-popup-policy' -import { allowPageUnload } from '../browser-guest-unload-policy' -import { initiatingFrameUrl } from '../prompts/browser-external-app-launch' -import { isSameExtensionNavigation } from '../../../../shared/browser/extensions/browser-extension-url' +} from '../popups/browser-manager-guest-popup-policy' +import { allowPageUnload } from '../../navigation/browser-guest-unload-policy' +import { initiatingFrameUrl } from '../../prompts/browser-external-app-launch' +import { isSameExtensionNavigation } from '../../../../../shared/browser/extensions/browser-extension-url' +import { + browserNavigationLeavesFaviconOrigin, + pickDisplayableFaviconUrl, + remoteTabFaviconUrl +} from '../../../../../shared/browser/browser-favicon-url' export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManagerGuestPopupPolicy { protected installGuestNavigationPolicy(guest: Electron.WebContents): () => void { @@ -118,6 +123,10 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager if (!isMainFrame || isChromiumInternalErrorUrl(url)) { return } + // Like the tab strip: a load that fails on the new origin never commits to clear it. + if (!isInPlace && browserNavigationLeavesFaviconOrigin(guest.getURL(), url)) { + this.remoteTabFaviconUrlByGuestId.delete(guest.id) + } // getURL() still names the committed document; UA writers need the in-flight target. this.startPendingNavigation(guest.id, url) void this.presentTabIdentityAtNavigationStart(guest, url, isInPlace) @@ -138,6 +147,10 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager let publishedUrl: string | null = null const didNavigateHandler = (_event: Electron.Event, url: string): void => { + // A redirect can still land on another origin. + if (browserNavigationLeavesFaviconOrigin(publishedUrl, url)) { + this.remoteTabFaviconUrlByGuestId.delete(guest.id) + } publishedUrl = guest.getURL() this.pendingNavigationByGuestId.delete(guest.id) // Committing makes the hidden error obsolete; a later abort must not restore it. @@ -164,11 +177,30 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager } } + // Renderer webviews keep their own icon. An offscreen page's icon arriving publishes; later + // swaps (animated or status icons) ride the page's next publish instead of one per frame. + const faviconUpdatedHandler = (_event: Electron.Event, favicons: string[]): void => { + if (!this.offscreenGuestIds.has(guest.id)) { + return + } + const next = remoteTabFaviconUrl(pickDisplayableFaviconUrl(favicons)) + const hadIcon = this.remoteTabFaviconUrlByGuestId.has(guest.id) + if (next) { + this.remoteTabFaviconUrlByGuestId.set(guest.id, next) + } else { + this.remoteTabFaviconUrlByGuestId.delete(guest.id) + } + if (next && !hadIcon) { + this.notifyBrowserGuestStateChanged(guest.id) + } + } + guest.on('will-navigate', willNavigateHandler) guest.on('will-redirect', willRedirectHandler) guest.on('did-start-navigation', didStartNavigationHandler) guest.on('did-navigate', didNavigateHandler) guest.on('did-navigate-in-page', didNavigateInPageHandler) + guest.on('page-favicon-updated', faviconUpdatedHandler) guest.on('did-fail-load', didFailLoadHandler) // Why emit: an extension-blocked guest main frame commits no error page, so Electron reports // nothing; every did-fail-load reader (this policy, the pane, webNavigation) needs the failure. @@ -201,6 +233,7 @@ export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManager guest.off('did-start-navigation', didStartNavigationHandler) guest.off('did-navigate', didNavigateHandler) guest.off('did-navigate-in-page', didNavigateInPageHandler) + guest.off('page-favicon-updated', faviconUpdatedHandler) guest.off('did-fail-load', didFailLoadHandler) guest.off('will-prevent-unload', allowPageUnload) } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-load-failure-replay.test.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts similarity index 96% rename from src/main/browser/guest-lifecycle/manager/browser-manager-load-failure-replay.test.ts rename to src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts index 78c3a34b642..b18c3456761 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-load-failure-replay.test.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts @@ -35,24 +35,24 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -vi.mock('../../identity/browser-process-user-agent', () => ({ +vi.mock('../../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: 'Mozilla/5.0 (Test) Chrome/140.0.0.0' }) })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { guestUaMethods, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-navigation.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-navigation.ts similarity index 79% rename from src/main/browser/guest-lifecycle/manager/browser-manager-navigation.ts rename to src/main/browser/guest-lifecycle/manager/navigation/browser-manager-navigation.ts index bd8bd6b3ee8..994cb64fc0c 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-navigation.ts +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-manager-navigation.ts @@ -1,23 +1,18 @@ -import { - openPopupWithOriginBar, - type PopupChildWindowOptions -} from '../popups/popup-origin-bar-window' -import { getBrowserProcessUserAgentIdentity } from '../../identity/browser-process-user-agent' -import type { BrowserSessionRequestUserAgentResolver } from '../../identity/browser-session-ua' -import { isGoogleAuthUrl } from '../../identity/browser-google-auth-ua' +import { getBrowserProcessUserAgentIdentity } from '../../../identity/browser-process-user-agent' +import type { BrowserSessionRequestUserAgentResolver } from '../../../identity/requests/browser-session-ua' +import { isGoogleAuthUrl } from '../../../identity/browser-google-auth-ua' import { desktopUserAgentMetadata, googleAuthTabIdentity, - resolveBrowserTabIdentity, - type BrowserTabIdentity -} from '../../identity/browser-tab-identity' -import { - safeOrigin, - type CdpUserAgentOverride, - type CdpUserAgentOverrideOperation, - type CdpUserAgentOverrideState -} from './browser-manager-types' -import { BrowserManagerVisibility } from './browser-manager-visibility' + resolveBrowserTabIdentity +} from '../../../identity/browser-tab-identity' +import type { BrowserTabIdentity } from '../../../identity/browser-tab-identity' +import type { + CdpUserAgentOverride, + CdpUserAgentOverrideOperation, + CdpUserAgentOverrideState +} from './browser-user-agent-override-state' +import { BrowserManagerVisibility } from '../browser-manager-visibility' export abstract class BrowserManagerNavigation extends BrowserManagerVisibility { resolveBrowserGuestRequestUserAgent( @@ -246,51 +241,4 @@ export abstract class BrowserManagerNavigation extends BrowserManagerVisibility protected resolveTabNavigationUrl(guest: Electron.WebContents): string { return this.pendingNavigationByGuestId.get(guest.id)?.currentUrl ?? guest.getURL() } - - reportRouteGuestPopupBlocked(input: { openerWebContentsId: number; url: string }): void { - this.forwardOrQueuePopupEvent(input.openerWebContentsId, { - origin: safeOrigin(input.url), - action: 'blocked' - }) - } - - protected createPopupChildWindowWithOriginBar( - openerGuest: Electron.WebContents, - targetUrl: string, - options: PopupChildWindowOptions - ): Electron.WebContents { - const popup = openPopupWithOriginBar(options, targetUrl, (contents) => { - if (openerGuest.isDestroyed() || contents.session !== openerGuest.session) { - return false - } - const owner = this.resolvePopupOwnerContext(openerGuest.id) - if (!owner) { - return false - } - this.attachGuestPolicies(contents, owner) - return true - }) - const opened = Boolean(options.webContents || options.nativeWindow) - this.forwardOrQueuePopupEvent(openerGuest.id, { - origin: safeOrigin(targetUrl), - action: opened ? 'opened-in-orca' : 'blocked' - }) - const ownerTabId = this.resolveBrowserTabIdForGuestWebContentsId(openerGuest.id) - if (opened && ownerTabId) { - this.pageEvents.emit(ownerTabId, { - kind: 'popup', - action: 'window', - origin: safeOrigin(targetUrl) - }) - } - // Close session-bearing popups with their owning guest to avoid orphan windows. - const closePopupWithOpener = (): void => popup.close() - openerGuest.once('destroyed', closePopupWithOpener) - popup.onClosed(() => { - if (!openerGuest.isDestroyed()) { - openerGuest.off('destroyed', closePopupWithOpener) - } - }) - return popup.contentWebContents - } } diff --git a/src/main/browser/guest-lifecycle/manager/navigation/browser-user-agent-override-state.ts b/src/main/browser/guest-lifecycle/manager/navigation/browser-user-agent-override-state.ts new file mode 100644 index 00000000000..c70cfd785c2 --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/navigation/browser-user-agent-override-state.ts @@ -0,0 +1,18 @@ +import type { CdpUserAgentMetadata } from '../../../identity/browser-tab-identity' + +/** An empty userAgent clears the CDP override. */ +export type CdpUserAgentOverride = { + userAgent: string + userAgentMetadata?: CdpUserAgentMetadata +} + +export type CdpUserAgentOverrideOperation = { + sequence: number + override: CdpUserAgentOverride +} + +export type CdpUserAgentOverrideState = { + confirmed: CdpUserAgentOverrideOperation | null + nextSequence: number + pending: CdpUserAgentOverrideOperation[] +} diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-popup-policy.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts similarity index 73% rename from src/main/browser/guest-lifecycle/manager/browser-manager-guest-popup-policy.ts rename to src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts index 311b9f24102..fabb14072b9 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-popup-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-guest-popup-policy.ts @@ -1,24 +1,26 @@ import { shell } from 'electron' -import { normalizeExternalBrowserUrl, redactKagiSessionToken } from '../../../../shared/browser-url' -import { trackBrowserGuestInputGesture } from '../input/browser-guest-input-gesture' +import { + normalizeExternalBrowserUrl, + redactKagiSessionToken +} from '../../../../../shared/browser-url' +import { trackBrowserGuestInputGesture } from '../../input/browser-guest-input-gesture' import { isNewBrowserTabPopupIntent, isBrowserTabPopupRequest, normalizeBrowserPopupUrl -} from '../popups/browser-popup-new-tab-intent' -import { SAFE_POPUP_WINDOW_OPTIONS, safeOrigin } from './browser-manager-types' -import { - openPopupWithOriginBar, - type PopupChildWindowOptions -} from '../popups/popup-origin-bar-window' -import { BrowserManagerNavigation } from './browser-manager-navigation' +} from '../../popups/browser-popup-new-tab-intent' +import { SAFE_POPUP_WINDOW_OPTIONS } from '../../popups/presentation/browser-popup-window-policy' +import { safeOrigin } from '../../browser-event-origin' +import { openPopupWithOriginBar } from '../../popups/presentation/popup-origin-bar-window' +import type { PopupChildWindowOptions } from '../../popups/presentation/browser-popup-window-contract' +import { BrowserManagerNavigation } from '../navigation/browser-manager-navigation' import { allowNativeBrowserPopup, discardBrowserPopupContents, isNativeBrowserPopupRequest -} from '../popups/browser-popup-native-window' -import { isBrowserRouteGuestPopup } from '../../routing/guest-authority/browser-route-guest-popup-ownership' -import { requestBrowserExternalAppLaunch } from '../prompts/browser-external-app-launch' +} from '../../popups/presentation/browser-popup-native-window' +import { isBrowserRouteGuestPopup } from '../../../routing/guest-authority/browser-route-guest-popup-ownership' +import { requestBrowserExternalAppLaunch } from '../../prompts/browser-external-app-launch' export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavigation { protected installGuestPopupPolicy(guest: Electron.WebContents): () => void { @@ -179,6 +181,53 @@ export abstract class BrowserManagerGuestPopupPolicy extends BrowserManagerNavig } return openPopupWithOriginBar(options, url, () => false).contentWebContents } + + reportRouteGuestPopupBlocked(input: { openerWebContentsId: number; url: string }): void { + this.forwardOrQueuePopupEvent(input.openerWebContentsId, { + origin: safeOrigin(input.url), + action: 'blocked' + }) + } + + protected createPopupChildWindowWithOriginBar( + openerGuest: Electron.WebContents, + targetUrl: string, + options: PopupChildWindowOptions + ): Electron.WebContents { + const popup = openPopupWithOriginBar(options, targetUrl, (contents) => { + if (openerGuest.isDestroyed() || contents.session !== openerGuest.session) { + return false + } + const owner = this.resolvePopupOwnerContext(openerGuest.id) + if (!owner) { + return false + } + this.attachGuestPolicies(contents, owner) + return true + }) + const opened = Boolean(options.webContents || options.nativeWindow) + this.forwardOrQueuePopupEvent(openerGuest.id, { + origin: safeOrigin(targetUrl), + action: opened ? 'opened-in-orca' : 'blocked' + }) + const ownerTabId = this.resolveBrowserTabIdForGuestWebContentsId(openerGuest.id) + if (opened && ownerTabId) { + this.pageEvents.emit(ownerTabId, { + kind: 'popup', + action: 'window', + origin: safeOrigin(targetUrl) + }) + } + // Close session-bearing popups with their owning guest to avoid orphan windows. + const closePopupWithOpener = (): void => popup.close() + openerGuest.once('destroyed', closePopupWithOpener) + popup.onClosed(() => { + if (!openerGuest.isDestroyed()) { + openerGuest.off('destroyed', closePopupWithOpener) + } + }) + return popup.contentWebContents + } } // Web pages must not reach the filesystem; only a local page may link to local files. diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-popup-child.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-popup-child.test.ts rename to src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts index f0c40cf4396..ad6a10d0c9c 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-popup-child.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts @@ -25,18 +25,18 @@ vi.mock('electron', () => ({ webContents: { fromId: browserMocks.webContentsFromIdMock } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { createDownloadItem, getDownloadItemEventHandler, rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-popup-routing.test.ts b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-popup-routing.test.ts rename to src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts index 89be3a19358..49f30d15008 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-popup-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts @@ -37,20 +37,20 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' +import { browserManager } from '../browser-manager' import { MAX_PAGE_INITIATED_TABS_PER_WINDOW, PAGE_INITIATED_TAB_WINDOW_MS -} from '../popups/browser-page-initiated-tab-budget' +} from '../../popups/browser-page-initiated-tab-budget' import { rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-guest-policy-profile.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-guest-policy-profile.ts new file mode 100644 index 00000000000..d04776c1236 --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-guest-policy-profile.ts @@ -0,0 +1,6 @@ +/** Document guests render one grant and report only to its host; browsing policies do not apply. */ +export type BrowserGuestPolicy = + | { profile: 'browsing' } + | { profile: 'workspace-doc'; host: Electron.WebContents } + +export const BROWSING_GUEST_POLICY: BrowserGuestPolicy = { profile: 'browsing' } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-test-fixture.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-test-fixture.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts index 8b48bcdc677..c830c844a27 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest-test-fixture.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest-test-fixture.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'node:events' import type { WebContents } from 'electron' -import { BrowserManager } from '../../browser-manager' +import { BrowserManager } from '../browser-manager' const session = { getUserAgent: () => 'Chrome/140.0.0.0' } diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest.test.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest.test.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest.test.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest.test.ts index 71e84165f3d..0d9fc8b44a5 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-destroyed-guest.test.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest.test.ts @@ -10,7 +10,7 @@ vi.mock('electron', () => ({ screen: { getCursorScreenPoint: () => ({ x: 0, y: 0 }) }, webContents: { fromId: (id: number) => mocks.guests.get(id) ?? null } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: vi.fn() })) diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-cleanup.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts similarity index 92% rename from src/main/browser/guest-lifecycle/manager/browser-manager-guest-cleanup.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts index 6a0da4591b9..c0812f2fa58 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-cleanup.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-cleanup.ts @@ -1,4 +1,4 @@ -import { BrowserManagerGuestNavigationPolicy } from './browser-manager-guest-navigation-policy' +import { BrowserManagerGuestNavigationPolicy } from '../navigation/browser-manager-guest-navigation-policy' export abstract class BrowserManagerGuestCleanup extends BrowserManagerGuestNavigationPolicy { protected retireStaleGuestWebContents(previousWebContentsId: number): void { @@ -37,6 +37,7 @@ export abstract class BrowserManagerGuestCleanup extends BrowserManagerGuestNavi this.pendingLoadFailuresByGuestId.delete(guestWebContentsId) this.loadErrorsByGuestId.delete(guestWebContentsId) this.clearedLoadErrorsByGuestId.delete(guestWebContentsId) + this.remoteTabFaviconUrlByGuestId.delete(guestWebContentsId) this.pendingPermissionEventsByGuestId.delete(guestWebContentsId) this.pendingPopupEventsByGuestId.delete(guestWebContentsId) this.cancelPendingDownloadsForGuest(guestWebContentsId) diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts similarity index 86% rename from src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts index d7e32846420..1c527c71636 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts @@ -1,17 +1,15 @@ -import { - BROWSING_GUEST_POLICY, - type BrowserGuestPolicy, - type PopupOwnerContext -} from './browser-manager-types' +import { BROWSING_GUEST_POLICY } from './browser-guest-policy-profile' +import type { BrowserGuestPolicy } from './browser-guest-policy-profile' +import type { PopupOwnerContext } from '../../popups/browser-popup-ownership' import { BrowserManagerGuestCleanup } from './browser-manager-guest-cleanup' -import { allowPageUnload } from '../browser-guest-unload-policy' +import { allowPageUnload } from '../../navigation/browser-guest-unload-policy' import { installDocPreviewGuestPolicy, readDocPreviewGuestBoundGrantId -} from '../../document-preview/doc-preview-guest-policy' -import { getDocPreviewGrant } from '../../document-preview/doc-preview-grant-registry' -import { setupGuestEscapeForwarding } from '../input/browser-guest-escape-forwarding' -import { installGuestDevToolsCloseShortcut } from '../browser-guest-devtools-close-shortcut' +} from '../../../document-preview/doc-preview-guest-policy' +import { getDocPreviewGrant } from '../../../document-preview/doc-preview-grant-registry' +import { setupGuestEscapeForwarding } from '../../input/shortcuts/browser-guest-escape-forwarding' +import { installGuestDevToolsCloseShortcut } from '../../devtools/browser-guest-devtools-close-shortcut' export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestCleanup { attachGuestPolicies( diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-unload.test.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-unload.test.ts similarity index 92% rename from src/main/browser/guest-lifecycle/manager/browser-manager-guest-unload.test.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-unload.test.ts index 9ddec33241b..2387905ff6c 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-guest-unload.test.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-unload.test.ts @@ -1,4 +1,6 @@ import { afterEach, expect, it, vi } from 'vitest' +import { BrowserManager } from '../browser-manager' +import { DestroyedGuestTestContents } from './browser-manager-destroyed-guest-test-fixture' vi.mock('electron', () => ({ app: { getPath: () => '/downloads' }, @@ -9,13 +11,10 @@ vi.mock('electron', () => ({ screen: { getCursorScreenPoint: () => ({ x: 0, y: 0 }) }, webContents: { fromId: () => null } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: vi.fn() })) -import { BrowserManager } from '../../browser-manager' -import { DestroyedGuestTestContents } from './browser-manager-destroyed-guest-test-fixture' - const manager = new BrowserManager() /** Electron leaves only when will-prevent-unload is prevented. */ diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-page-prompt-routing.test.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts similarity index 95% rename from src/main/browser/guest-lifecycle/manager/browser-manager-page-prompt-routing.test.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts index 577dc363b83..35d74509c88 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-page-prompt-routing.test.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts @@ -37,18 +37,18 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' -import { respondToBrowserPagePrompt } from '../prompts/browser-page-prompts' -import { handleBrowserGuestLogin } from '../prompts/browser-http-auth-prompt' +import { browserManager } from '../browser-manager' +import { respondToBrowserPagePrompt } from '../../prompts/browser-page-prompts' +import { handleBrowserGuestLogin } from '../../prompts/browser-http-auth-prompt' import { rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' const { guestOffMock, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-registration.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts similarity index 95% rename from src/main/browser/guest-lifecycle/manager/browser-manager-registration.ts rename to src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts index 09cf3311f24..918f9afe91b 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-registration.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-registration.ts @@ -1,12 +1,21 @@ import { webContents } from 'electron' -import { browserDownloadDestinationReservations } from '../../downloads/browser-download-destination' -import { isWorkspaceDocPageId } from '../../document-preview/doc-preview-guest-policy' -import type { BrowserGuestRegistration } from './browser-manager-types' +import { browserDownloadDestinationReservations } from '../../../downloads/browser-download-destination' +import { isWorkspaceDocPageId } from '../../../document-preview/doc-preview-guest-policy' import { BrowserManagerGuestPolicy } from './browser-manager-guest-policy' import { cancelBrowserPagePrompts, showBrowserPagePromptsAwaitingRegistration -} from '../prompts/browser-page-prompts' +} from '../../prompts/browser-page-prompts' + +export type BrowserGuestRegistration = { + browserPageId?: string + browserTabId?: string + workspaceId?: string + worktreeId?: string + sessionProfileId?: string | null + webContentsId: number + rendererWebContentsId: number +} export abstract class BrowserManagerRegistration extends BrowserManagerGuestPolicy { registerGuest( diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts index 594cdf2c4be..d7416a6e025 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-annotation-bridge.test.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts @@ -25,17 +25,17 @@ vi.mock('electron', () => ({ webContents: { fromId: browserMocks.webContentsFromIdMock } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -import { browserManager } from '../../browser-manager' -import type { BrowserAnnotationViewportBridgeOptions } from '../../../../shared/browser-annotation-viewport-bridge' +import { browserManager } from '../browser-manager' +import type { BrowserAnnotationViewportBridgeOptions } from '../../../../../shared/browser-annotation-viewport-bridge' import { rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' import { createViewportGuestFactory, flushViewportOps diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-desktop-ua-metadata-test-fixture.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-desktop-ua-metadata-test-fixture.ts similarity index 83% rename from src/main/browser/guest-lifecycle/manager/browser-manager-desktop-ua-metadata-test-fixture.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-desktop-ua-metadata-test-fixture.ts index e55f8420711..ce841f1528c 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-desktop-ua-metadata-test-fixture.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-desktop-ua-metadata-test-fixture.ts @@ -1,4 +1,4 @@ -import type { CdpUserAgentMetadata } from '../../identity/browser-tab-identity' +import type { CdpUserAgentMetadata } from '../../../identity/browser-tab-identity' // Pinned host client hints so expectations do not depend on the CI platform. export const pinnedDesktopUserAgentMetadata: CdpUserAgentMetadata = { diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-tab-identity.test.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts similarity index 96% rename from src/main/browser/guest-lifecycle/manager/browser-manager-tab-identity.test.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts index 2bbb517cbaf..d57e0a5ef31 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-tab-identity.test.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts @@ -26,10 +26,10 @@ vi.mock('electron', () => ({ screen: { getCursorScreenPoint: mocks.screenGetCursorScreenPointMock }, webContents: { fromId: mocks.webContentsFromIdMock } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: mocks.openPopupWithOriginBarMock })) -vi.mock('../../identity/browser-process-user-agent', () => ({ +vi.mock('../../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: mocks.processUserAgentMode, userAgent: mocks.processUserAgent, @@ -40,9 +40,9 @@ vi.mock('../../identity/browser-process-user-agent', () => ({ }) })) -import { browserManager } from '../../browser-manager' -import { googleAuthUserAgent } from '../../identity/browser-google-auth-ua' -import { resetBrowserManagerMocks, resetBrowserManagerState } from './browser-manager-test-harness' +import { browserManager } from '../browser-manager' +import { googleAuthUserAgent } from '../../../identity/browser-google-auth-ua' +import { resetBrowserManagerMocks, resetBrowserManagerState } from '../browser-manager-test-harness' import { createViewportGuestFactory, flushViewportOps, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-override.test.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-viewport-override.test.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts index a1fce6bbb21..f87967a35ca 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-override.test.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts @@ -38,11 +38,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) -vi.mock('../../identity/browser-process-user-agent', () => ({ +vi.mock('../../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: browserMocks.processUserAgentMode, userAgent: browserMocks.processUserAgent, @@ -53,19 +53,19 @@ vi.mock('../../identity/browser-process-user-agent', () => ({ }) })) -vi.mock('../../identity/browser-tab-identity', async (importOriginal) => +vi.mock('../../../identity/browser-tab-identity', async (importOriginal) => ( await import('./browser-manager-desktop-ua-metadata-test-fixture') ).withPinnedDesktopUserAgentMetadata(await importOriginal()) ) -import { browserManager } from '../../browser-manager' -import { googleAuthUserAgent } from '../../identity/browser-google-auth-ua' +import { browserManager } from '../browser-manager' +import { googleAuthUserAgent } from '../../../identity/browser-google-auth-ua' import { rendererWebContentsId, resetBrowserManagerMocks, resetBrowserManagerState -} from './browser-manager-test-harness' +} from '../browser-manager-test-harness' import { pinnedDesktopUserAgentMetadata as desktopMetadata } from './browser-manager-desktop-ua-metadata-test-fixture' import { createViewportGuestFactory, diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-ownership.test.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-ownership.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/manager/browser-manager-viewport-ownership.test.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-ownership.test.ts index 1e374114c72..60d21990759 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-ownership.test.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-ownership.test.ts @@ -26,11 +26,11 @@ vi.mock('electron', () => ({ screen: { getCursorScreenPoint: mocks.screenGetCursorScreenPointMock }, webContents: { fromId: mocks.webContentsFromIdMock } })) -vi.mock('../popups/popup-origin-bar-window', () => ({ +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: mocks.openPopupWithOriginBarMock })) -vi.mock('../../identity/browser-process-user-agent', () => ({ +vi.mock('../../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: mocks.processUserAgentMode, userAgent: mocks.processUserAgent, @@ -41,8 +41,8 @@ vi.mock('../../identity/browser-process-user-agent', () => ({ }) })) -import { browserManager } from '../../browser-manager' -import { resetBrowserManagerMocks, resetBrowserManagerState } from './browser-manager-test-harness' +import { browserManager } from '../browser-manager' +import { resetBrowserManagerMocks, resetBrowserManagerState } from '../browser-manager-test-harness' import { createViewportGuestFactory, GUEST_CLEAN_UA diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-scroll-state.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-scroll-state.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-viewport-scroll-state.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-scroll-state.ts index 75679964a0b..d6fa68568e9 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-scroll-state.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-scroll-state.ts @@ -2,7 +2,7 @@ import { webContents } from 'electron' import type { BrowserViewportOverride, BrowserViewportScrollState -} from '../../../../shared/browser-workspace-types' +} from '../../../../../shared/browser-workspace-types' type ViewportPresetState = { guestWebContentsId: number diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-test-fixtures.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts similarity index 98% rename from src/main/browser/guest-lifecycle/manager/browser-manager-viewport-test-fixtures.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts index 80474805203..0a40c69e6be 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport-test-fixtures.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-test-fixtures.ts @@ -1,5 +1,5 @@ import { vi } from 'vitest' -import type { BrowserManagerMocks } from './browser-manager-test-harness' +import type { BrowserManagerMocks } from '../browser-manager-test-harness' export const GUEST_ELECTRON_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) orca/1.0.0 Chrome/134.0.0.0 Electron/30.0.0 Safari/537.36' diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport.ts b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport.ts similarity index 62% rename from src/main/browser/guest-lifecycle/manager/browser-manager-viewport.ts rename to src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport.ts index e837c5f1878..2322a599fe9 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager-viewport.ts +++ b/src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport.ts @@ -1,133 +1,16 @@ import { webContents } from 'electron' import { BROWSER_ANNOTATION_VIEWPORT_BRIDGE_WORLD_ID, - buildBrowserAnnotationViewportBridgeScript, - type BrowserAnnotationViewportBridgeOptions -} from '../../../../shared/browser-annotation-viewport-bridge' -import type { BrowserViewportOverride } from '../../../../shared/browser-workspace-types' -import { BROWSER_AGENT_VIEWPORT_CHANNEL } from '../../../../shared/browser-agent-activity-contract' -import { BrowserManagerDownloadLifecycle } from './browser-manager-download-lifecycle' -import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' -import { touchEmulationParams } from '../../cdp/input/guest-touch-emulation' -import type { BrowserDevToolsDockBounds } from '../../../../shared/browser-devtools-dock' - -export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifecycle { - async openDevTools( - browserTabId: string, - inspectAt?: { x: number; y: number }, - options?: { detach?: boolean } - ): Promise { - const guest = this.resolveDevToolsGuest(browserTabId) - if (!guest) { - return false - } - const renderer = this.resolveRendererForBrowserTab(browserTabId) - const operation = this.devToolsDock.beginOpen( - guest, - () => - this.webContentsIdByTabId.get(browserTabId) === guest.id && - !this.offscreenGuestIds.has(guest.id) && - (!renderer || - (this.resolveRendererForBrowserTab(browserTabId) === renderer && !renderer.isDestroyed())) - ) - const notify = (docked: boolean): void => { - const currentGuestId = this.webContentsIdByTabId.get(browserTabId) - if ( - renderer && - !renderer.isDestroyed() && - (currentGuestId === undefined || - currentGuestId === guest.id || - (!docked && !this.devToolsDock.isDocked(currentGuestId))) - ) { - renderer.send('browser:devToolsDockChanged', { browserPageId: browserTabId, docked }) - } - } - try { - let docked = false - if (!options?.detach && renderer) { - docked = await this.devToolsDock.open(guest, () => notify(false), operation) - if (!operation.isCurrent()) { - return false - } - } - if (!docked && !(await this.devToolsDock.openDetached(guest, operation))) { - return false - } - if (!operation.isCurrent()) { - return false - } - if (docked) { - notify(true) - } - if (!operation.isCurrent()) { - return false - } - if (inspectAt) { - // Open first: inspectElement alone opens Electron's own DevTools and bypasses the dock. - guest.inspectElement(inspectAt.x, inspectAt.y) - } - return true - } finally { - operation.finish() - } - } - - closeDevTools(browserTabId: string): void { - const guest = this.resolveDevToolsGuest(browserTabId) - if (guest) { - this.closeGuestDevTools(guest) - } - } - - /** Toggles the page DevTools of `focused` (the page or its DevTools); false if it is neither. */ - toggleDevToolsOfFocusedPage(focused: Electron.WebContents): boolean { - for (const [browserTabId, guestId] of this.webContentsIdByTabId) { - const guest = webContents.fromId(guestId) - if (!guest || guest.isDestroyed()) { - continue - } - if (guest !== focused && guest.devToolsWebContents !== focused) { - continue - } - if ( - this.devToolsDock.isOpening(guest.id) || - this.devToolsDock.isDocked(guest.id) || - guest.isDevToolsOpened() - ) { - this.closeGuestDevTools(guest) - } else { - void this.openDevTools(browserTabId) - } - return true - } - return false - } - - setDevToolsDockBounds( - browserTabId: string, - bounds: BrowserDevToolsDockBounds | null, - snapshot: boolean - ): Promise { - const guestId = this.webContentsIdByTabId.get(browserTabId) - return guestId === undefined - ? Promise.resolve(null) - : this.devToolsDock.setBounds(guestId, bounds, snapshot) - } - - private resolveDevToolsGuest(browserTabId: string): Electron.WebContents | null { - const webContentsId = this.webContentsIdByTabId.get(browserTabId) - if (!webContentsId) { - return null - } - const guest = webContents.fromId(webContentsId) - if (!guest || guest.isDestroyed()) { - this.unregisterGuest(browserTabId) - return null - } - // Offscreen DevTools would open on the server desktop without a route back to the client. - return this.offscreenGuestIds.has(webContentsId) ? null : guest - } + buildBrowserAnnotationViewportBridgeScript +} from '../../../../../shared/browser-annotation-viewport-bridge' +import type { BrowserAnnotationViewportBridgeOptions } from '../../../../../shared/browser-annotation-viewport-bridge' +import type { BrowserViewportOverride } from '../../../../../shared/browser-workspace-types' +import { BROWSER_AGENT_VIEWPORT_CHANNEL } from '../../../../../shared/browser-agent-activity-contract' +import { sendGuestCdpCommand } from '../../../cdp/debugger/guest-cdp-command' +import { touchEmulationParams } from '../../../cdp/input/guest-touch-emulation' +import { BrowserManagerDevTools } from '../devtools/browser-manager-devtools' +export abstract class BrowserManagerViewport extends BrowserManagerDevTools { /** Sizes the pane's page box to an agent's viewport as a preset does: wider pages scroll, not crop. */ showAgentViewportInPane(guestWebContentsId: number, override: BrowserViewportOverride): void { const browserPageId = this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId) diff --git a/src/main/browser/guest-lifecycle/browser-guest-navigation-state.ts b/src/main/browser/guest-lifecycle/navigation/browser-guest-navigation-state.ts similarity index 100% rename from src/main/browser/guest-lifecycle/browser-guest-navigation-state.ts rename to src/main/browser/guest-lifecycle/navigation/browser-guest-navigation-state.ts diff --git a/src/main/browser/guest-lifecycle/browser-guest-unload-policy.ts b/src/main/browser/guest-lifecycle/navigation/browser-guest-unload-policy.ts similarity index 100% rename from src/main/browser/guest-lifecycle/browser-guest-unload-policy.ts rename to src/main/browser/guest-lifecycle/navigation/browser-guest-unload-policy.ts diff --git a/src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts b/src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts index 68ba6447e3c..ab0613f7975 100644 --- a/src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts +++ b/src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts @@ -7,7 +7,7 @@ import { buildPopupIdentityProbe, createPopupIdentityProbeRoot, launchPopupIdentityProbe -} from '../popups/popup-identity-electron-probe' +} from '../../electron-fixtures/popup-identity-electron-probe' const root = createPopupIdentityProbeRoot() let probe: Awaited> diff --git a/src/main/browser/guest-lifecycle/browser-agent-activity.test.ts b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts similarity index 96% rename from src/main/browser/guest-lifecycle/browser-agent-activity.test.ts rename to src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts index fef10a5e24e..8a2148e204f 100644 --- a/src/main/browser/guest-lifecycle/browser-agent-activity.test.ts +++ b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.test.ts @@ -21,14 +21,14 @@ vi.mock('electron', () => ({ })) import { BrowserAgentActivity } from './browser-agent-activity' -import { runWithActiveRpcCaller } from '../../runtime/rpc/rpc-active-caller' -import { runInRemoteCliBrowserScope } from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +import { runWithActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' +import { runInRemoteCliBrowserScope } from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' import { BROWSER_AGENT_ACTIVITY_CHANNEL, BROWSER_AGENT_CURSOR_ARRIVED_CHANNEL, BROWSER_AGENT_CURSOR_CHANNEL, type BrowserAgentCursorEvent -} from '../../../shared/browser-agent-activity-contract' +} from '../../../../shared/browser-agent-activity-contract' const PAGE = 'page-1' diff --git a/src/main/browser/guest-lifecycle/browser-agent-activity.ts b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts similarity index 95% rename from src/main/browser/guest-lifecycle/browser-agent-activity.ts rename to src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts index 58226190cc6..b698b215aab 100644 --- a/src/main/browser/guest-lifecycle/browser-agent-activity.ts +++ b/src/main/browser/guest-lifecycle/page-activity/browser-agent-activity.ts @@ -1,19 +1,19 @@ import { BrowserWindow, ipcMain, type WebContents } from 'electron' -import { isResourceWindowVisible } from '../../window/resource-view-admission' -import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command' -import { isAgentRpcCaller } from '../../runtime/rpc/rpc-caller-identity' +import { isResourceWindowVisible } from '../../../window/resource-view-admission' +import { sendGuestCdpCommand } from '../../cdp/debugger/guest-cdp-command' +import { isAgentRpcCaller } from '../../../runtime/rpc/rpc-caller-identity' import { BROWSER_AGENT_ACTIVITY_CHANNEL, BROWSER_AGENT_CURSOR_ARRIVED_CHANNEL, BROWSER_AGENT_CURSOR_CHANNEL, type BrowserAgentActivityEvent, type BrowserAgentCursorEvent -} from '../../../shared/browser-agent-activity-contract' -import { getActiveRpcCaller } from '../../runtime/rpc/rpc-active-caller' +} from '../../../../shared/browser-agent-activity-contract' +import { getActiveRpcCaller } from '../../../runtime/rpc/rpc-active-caller' import { remoteCliBrowserScopeController, type RemoteCliBrowserController -} from '../../runtime/desktop-browser-bridge/remote-cli-browser-scope' +} from '../../../runtime/desktop-browser-bridge/remote-cli-browser-scope' // Spans an agent's thinking between steps; a finished, failed or disconnected agent clears within it. const ACTIVITY_IDLE_MS = 20_000 diff --git a/src/main/browser/guest-lifecycle/browser-page-events.ts b/src/main/browser/guest-lifecycle/page-activity/browser-page-events.ts similarity index 91% rename from src/main/browser/guest-lifecycle/browser-page-events.ts rename to src/main/browser/guest-lifecycle/page-activity/browser-page-events.ts index d5e5ba1dade..a0f77094ef1 100644 --- a/src/main/browser/guest-lifecycle/browser-page-events.ts +++ b/src/main/browser/guest-lifecycle/page-activity/browser-page-events.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'node:events' -import type { BrowserPopupEvent } from '../../../shared/browser-guest-events' +import type { BrowserPopupEvent } from '../../../../shared/browser-guest-events' /** Facts the browser manager resolves to their owning page: a tab it asked for, a popup outcome, a download. */ export type BrowserPageEvent = diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-ownership.ts b/src/main/browser/guest-lifecycle/popups/browser-popup-ownership.ts new file mode 100644 index 00000000000..b5798f76fe4 --- /dev/null +++ b/src/main/browser/guest-lifecycle/popups/browser-popup-ownership.ts @@ -0,0 +1,11 @@ +export type PopupOwnerContext = { + browserTabId: string + rootGuestWebContentsId: number +} + +/** A live popup window an agent can drive, owned by the tab whose page opened its chain. */ +export type BrowserPopupPage = { + browserPageId: string + webContentsId: number + openerBrowserPageId: string +} diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts similarity index 98% rename from src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts index 215e4f79bec..23e1e1ce48d 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-adapter-compatibility.electron.test.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts @@ -11,7 +11,7 @@ import { snapshots, status } from './browser-popup-compatibility-cdp-fixture' -import { waitForHiddenFrameInput } from '../../electron-fixtures/hidden-frame-input-readiness-fixture' +import { waitForHiddenFrameInput } from '../../../electron-fixtures/hidden-frame-input-readiness-fixture' enablePopupAdapterProbe() setPopupFixtureEvidenceName('adapter-electron-evidence.json') diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-adapter-probe-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-probe-fixture.ts similarity index 94% rename from src/main/browser/guest-lifecycle/popups/browser-popup-adapter-probe-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-probe-fixture.ts index e28bdf0e9f4..bd50bc01288 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-adapter-probe-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-probe-fixture.ts @@ -1,6 +1,8 @@ -import { app, BrowserWindow, type Session, type WebContents } from 'electron' -import { openPopupWithOriginBar, type PopupChildWindowOptions } from './popup-origin-bar-window' -import { allowNativeBrowserPopup } from './browser-popup-native-window' +import { app, BrowserWindow } from 'electron' +import type { Session, WebContents } from 'electron' +import { openPopupWithOriginBar } from '../presentation/popup-origin-bar-window' +import type { PopupChildWindowOptions } from '../presentation/browser-popup-window-contract' +import { allowNativeBrowserPopup } from '../presentation/browser-popup-native-window' export class BrowserPopupAdapterProbeFixture { readonly events: Record[] = [] diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-background-cdp-probe.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts similarity index 98% rename from src/main/browser/guest-lifecycle/popups/browser-popup-background-cdp-probe.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts index c83e5af6baf..ae5ef8b84aa 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-background-cdp-probe.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-cdp-probe.ts @@ -2,7 +2,7 @@ import { mkdirSync } from 'node:fs' import { join } from 'node:path' import type { Page } from 'playwright' import { expect } from 'vitest' -import { waitForHiddenFrameInput } from '../../electron-fixtures/hidden-frame-input-readiness-fixture' +import { waitForHiddenFrameInput } from '../../../electron-fixtures/hidden-frame-input-readiness-fixture' import { artifactDir, browser, diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/browser-popup-background-compatibility.electron.test.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-cdp-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts similarity index 96% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-cdp-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts index 5aa844dc767..b52c38e018e 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-cdp-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-cdp-fixture.ts @@ -9,13 +9,13 @@ import { join } from 'node:path' import { chromium, type Browser, type Page } from 'playwright' import { afterAll, afterEach, beforeAll, expect, vi } from 'vitest' import { build as buildVite } from 'vite' -import { waitForBrowserCdpEndpoint } from '../../identity/browser-session-ua-cdp-collector' +import { waitForBrowserCdpEndpoint } from '../../../identity/wire-probes/browser-session-ua-cdp-collector' import { popupFixtureHtml } from './browser-popup-compatibility-page-fixture' -import { resolveElectronProbeLaunch } from '../../electron-fixtures/electron-probe-display-launch' +import { resolveElectronProbeLaunch } from '../../../electron-fixtures/electron-probe-display-launch' import { HIDDEN_RENDERER_FIRST_FRAME_TIMEOUT_MS, startHiddenRendererFrameCapture -} from '../../electron-fixtures/hidden-renderer-frame-capture-fixture' +} from '../../../electron-fixtures/hidden-renderer-frame-capture-fixture' // Hidden renderer startup and CDP events can exceed the default one-second poll on CI. vi.setConfig({ expect: { poll: { timeout: 10_000 } } }) @@ -132,7 +132,7 @@ beforeAll(async () => { lib: { entry: join( process.cwd(), - 'src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-electron-fixture.ts' + 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts' ), formats: ['cjs'], fileName: () => 'main.cjs' diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts similarity index 95% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-electron-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts index b9d9e12b33f..4f8a7f81e70 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts @@ -8,11 +8,11 @@ import { type WebContents } from 'electron' import { writeFileSync } from 'node:fs' -import { renameFileWithWindowsRetry } from '../../../../shared/windows-retry-file-operations' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { renameFileWithWindowsRetry } from '../../../../../shared/windows-retry-file-operations' +import { applyBackgroundActivationPolicy } from '../../../../window/foreground-activation-policy' import { BrowserPopupCompatibilityManager } from './browser-popup-compatibility-manager-fixture' -import { BrowserRouteWebContentsRegistry } from '../../routing/guest-authority/browser-route-webcontents-registry' -import { initializeBrowserProcessUserAgent } from '../../identity/browser-process-user-agent' +import { BrowserRouteWebContentsRegistry } from '../../../routing/guest-authority/browser-route-webcontents-registry' +import { initializeBrowserProcessUserAgent } from '../../../identity/browser-process-user-agent' import { BrowserPopupNativeFixture, popupFixtureContentSecurity as contentSecurity @@ -20,7 +20,7 @@ import { import type { BrowserRouteGuestLifecycleClaim, BrowserRoutePageGuestIdentity -} from '../../routing/guest-authority/browser-route-page-authority' +} from '../../../routing/guest-authority/browser-route-page-authority' import { BrowserPopupAdapterProbeFixture } from './browser-popup-adapter-probe-fixture' const origin = process.env.ORCA_POPUP_FIXTURE_ORIGIN diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-manager-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts similarity index 92% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-manager-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts index 2e65b3f2cd7..81389d6d001 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-manager-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-manager-fixture.ts @@ -1,6 +1,6 @@ import type { WebContents } from 'electron' -import { BrowserManager } from '../../browser-manager' -import type { PopupChildWindowOptions } from './popup-origin-bar-window' +import { BrowserManager } from '../../manager/browser-manager' +import type { PopupChildWindowOptions } from '../presentation/browser-popup-window-contract' import { popupFixtureContentSecurity as contentSecurity } from './browser-popup-native-electron-fixture' export class BrowserPopupCompatibilityManager extends BrowserManager { diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-page-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-page-fixture.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-page-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-page-fixture.ts diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-status.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility-status.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/browser-popup-compatibility.electron.test.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts similarity index 99% rename from src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts index fdbd1bf3974..21d121df45d 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-native-compatibility.electron.test.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts @@ -14,7 +14,7 @@ import { status, setPopupFixtureEvidenceName } from './browser-popup-compatibility-cdp-fixture' -import { waitForHiddenFrameInput } from '../../electron-fixtures/hidden-frame-input-readiness-fixture' +import { waitForHiddenFrameInput } from '../../../electron-fixtures/hidden-frame-input-readiness-fixture' setPopupFixtureEvidenceName('native-electron-evidence.json') diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-native-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-electron-fixture.ts similarity index 97% rename from src/main/browser/guest-lifecycle/popups/browser-popup-native-electron-fixture.ts rename to src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-electron-fixture.ts index e5ce1690dc8..5b5e37de450 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-native-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-electron-fixture.ts @@ -6,7 +6,7 @@ import { type Session, type WebContents } from 'electron' -import { resolveBrowserRouteGuestPopupOpener } from '../../routing/guest-authority/browser-route-guest-popup-ownership' +import { resolveBrowserRouteGuestPopupOpener } from '../../../routing/guest-authority/browser-route-guest-popup-ownership' export class BrowserPopupNativeFixture { readonly presentationCalls: string[] = [] diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-native-window.test.ts b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.test.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/browser-popup-native-window.test.ts rename to src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.test.ts diff --git a/src/main/browser/guest-lifecycle/popups/browser-popup-native-window.ts b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts similarity index 97% rename from src/main/browser/guest-lifecycle/popups/browser-popup-native-window.ts rename to src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts index 742c4cec958..e1819fe2907 100644 --- a/src/main/browser/guest-lifecycle/popups/browser-popup-native-window.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-native-window.ts @@ -1,6 +1,7 @@ -import { app, type BrowserWindow, type WebContents } from 'electron' -import { isBackgroundLaunch } from '../../../window/foreground-activation-policy' -import type { PopupChildWindowOptions, PopupOriginBarWindow } from './popup-origin-bar-window' +import { app } from 'electron' +import type { BrowserWindow, WebContents } from 'electron' +import { isBackgroundLaunch } from '../../../../window/foreground-activation-policy' +import type { PopupChildWindowOptions, PopupOriginBarWindow } from './browser-popup-window-contract' import { isNativeBrowserPopupWindow, markNativeBrowserPopupWindow diff --git a/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-contract.ts b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-contract.ts new file mode 100644 index 00000000000..7216ab75a0a --- /dev/null +++ b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-contract.ts @@ -0,0 +1,13 @@ +// Electron supplies an untyped webContents option; adopting it preserves OAuth opener/session state. +export type PopupChildWindowOptions = Electron.BrowserWindowConstructorOptions & { + webContents?: Electron.WebContents + nativeWindow?: Electron.BrowserWindow + // Cmd/Ctrl+Shift-click supplies no page; only GET requests can be reloaded by URL. + loadInitialUrl?: boolean +} + +export type PopupOriginBarWindow = { + contentWebContents: Electron.WebContents + close: () => void + onClosed: (listener: () => void) => void +} diff --git a/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-policy.ts b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-policy.ts new file mode 100644 index 00000000000..58b67251f2b --- /dev/null +++ b/src/main/browser/guest-lifecycle/popups/presentation/browser-popup-window-policy.ts @@ -0,0 +1,25 @@ +export const SAFE_POPUP_WINDOW_OPTIONS = { + alwaysOnTop: false, + closable: true, + focusable: true, + frame: true, + fullscreen: false, + kiosk: false, + modal: false, + movable: true, + opacity: 1, + show: true, + simpleFullscreen: false, + skipTaskbar: false, + titleBarStyle: 'default', + transparent: false, + // Apply isolation before createWindow so features and opener inheritance cannot weaken it. + webPreferences: { + allowRunningInsecureContent: false, + contextIsolation: true, + nodeIntegration: false, + nodeIntegrationInSubFrames: false, + sandbox: true, + webviewTag: false + } +} satisfies Electron.BrowserWindowConstructorOptions diff --git a/src/main/browser/guest-lifecycle/popups/native-browser-popup-windows.ts b/src/main/browser/guest-lifecycle/popups/presentation/native-browser-popup-windows.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/native-browser-popup-windows.ts rename to src/main/browser/guest-lifecycle/popups/presentation/native-browser-popup-windows.ts diff --git a/src/main/browser/guest-lifecycle/popups/popup-committed-origin.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-committed-origin.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/popup-committed-origin.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-committed-origin.ts diff --git a/src/main/browser/guest-lifecycle/popups/popup-origin-bar-window.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts similarity index 93% rename from src/main/browser/guest-lifecycle/popups/popup-origin-bar-window.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts index ec39bb41850..81f78d715d8 100644 --- a/src/main/browser/guest-lifecycle/popups/popup-origin-bar-window.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-bar-window.ts @@ -1,25 +1,12 @@ import { BaseWindow, WebContentsView } from 'electron' -import { isBackgroundLaunch } from '../../../window/foreground-activation-policy' +import { isBackgroundLaunch } from '../../../../window/foreground-activation-policy' import { discardBrowserPopupContents, prepareNativeBrowserPopup } from './browser-popup-native-window' import { MIN_POPUP_CONTENT_HEIGHT, MIN_POPUP_CONTENT_WIDTH } from './popup-window-minimum-size' import { describeCommittedPopupOrigin } from './popup-committed-origin' - -// Electron supplies an untyped webContents option; adopting it preserves OAuth opener/session state. -export type PopupChildWindowOptions = Electron.BrowserWindowConstructorOptions & { - webContents?: Electron.WebContents - nativeWindow?: Electron.BrowserWindow - // Cmd/Ctrl+Shift-click supplies no page; only GET requests can be reloaded by URL. - loadInitialUrl?: boolean -} - -export type PopupOriginBarWindow = { - contentWebContents: Electron.WebContents - close: () => void - onClosed: (listener: () => void) => void -} +import type { PopupChildWindowOptions, PopupOriginBarWindow } from './browser-popup-window-contract' export const POPUP_ORIGIN_BAR_HEIGHT = 34 diff --git a/src/main/browser/guest-lifecycle/popups/popup-origin-chrome-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts similarity index 98% rename from src/main/browser/guest-lifecycle/popups/popup-origin-chrome-electron-fixture.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts index 56413d267cd..68cff07d9fa 100644 --- a/src/main/browser/guest-lifecycle/popups/popup-origin-chrome-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts @@ -3,7 +3,7 @@ import { mkdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { openPopupWithOriginBar } from './popup-origin-bar-window' import { prepareNativeBrowserPopup } from './browser-popup-native-window' -import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' +import { applyBackgroundActivationPolicy } from '../../../../window/foreground-activation-policy' if (process.env.ORCA_BACKGROUND_LAUNCH !== '1') { throw new Error('Popup identity probes require a background launch') diff --git a/src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts similarity index 97% rename from src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts index ac066495f8b..e5f39c79b3b 100644 --- a/src/main/browser/guest-lifecycle/popups/popup-origin-chrome.electron.test.ts +++ b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts @@ -7,11 +7,11 @@ import { buildPopupIdentityProbe, createPopupIdentityProbeRoot, launchPopupIdentityProbe -} from './popup-identity-electron-probe' +} from '../../../electron-fixtures/popup-identity-electron-probe' import { HIDDEN_RENDERER_FIRST_FRAME_TIMEOUT_MS, startHiddenRendererFrameCapture -} from '../../electron-fixtures/hidden-renderer-frame-capture-fixture' +} from '../../../electron-fixtures/hidden-renderer-frame-capture-fixture' type OriginProbeWindow = Window & { originProbeChild?: Window } @@ -120,7 +120,7 @@ beforeAll(async () => { root, join( process.cwd(), - 'src/main/browser/guest-lifecycle/popups/popup-origin-chrome-electron-fixture.ts' + 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome-electron-fixture.ts' ), 'main.cjs' ) diff --git a/src/main/browser/guest-lifecycle/popups/popup-origin-description.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-origin-description.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/popup-origin-description.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-origin-description.ts diff --git a/src/main/browser/guest-lifecycle/popups/popup-window-minimum-size.ts b/src/main/browser/guest-lifecycle/popups/presentation/popup-window-minimum-size.ts similarity index 100% rename from src/main/browser/guest-lifecycle/popups/popup-window-minimum-size.ts rename to src/main/browser/guest-lifecycle/popups/presentation/popup-window-minimum-size.ts diff --git a/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.test.ts b/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.test.ts index 40a23839520..fb2d1851e7c 100644 --- a/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.test.ts +++ b/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.test.ts @@ -5,7 +5,7 @@ const mocks = vi.hoisted(() => ({ resolvePagePromptTarget: vi.fn() })) -vi.mock('../../browser-manager', () => ({ +vi.mock('../manager/browser-manager', () => ({ browserManager: { resolvePagePromptTarget: mocks.resolvePagePromptTarget } diff --git a/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.ts b/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.ts index 3fb0fc86d34..ded16763245 100644 --- a/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.ts +++ b/src/main/browser/guest-lifecycle/prompts/browser-http-auth-prompt.ts @@ -1,5 +1,5 @@ import type { BrowserHttpAuthCredentials } from '../../../../shared/browser-http-auth' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../manager/browser-manager' import { browserPagePromptOrigin, openBrowserPagePrompt } from './browser-page-prompts' function parseCredentials(value: unknown): BrowserHttpAuthCredentials | undefined { diff --git a/src/main/browser/identity/browser-google-auth-ua.ts b/src/main/browser/identity/browser-google-auth-ua.ts index 8cf2b98c2b3..c3ff7b15231 100644 --- a/src/main/browser/identity/browser-google-auth-ua.ts +++ b/src/main/browser/identity/browser-google-auth-ua.ts @@ -27,23 +27,3 @@ export function shouldUseGoogleAuthIdentity( export function googleAuthUserAgent(): string { return getBrowserProcessUserAgentIdentity().electronUserAgent } - -export function stripClientHints(headers: Record): void { - for (const key of Object.keys(headers)) { - if (key.toLowerCase().startsWith('sec-ch-ua')) { - delete headers[key] - } - } -} - -// Replace case-insensitively to avoid duplicate User-Agent headers. -export function setUserAgentHeader(headers: Record, value: string): void { - const existing = Object.keys(headers).find((key) => key.toLowerCase() === 'user-agent') - headers[existing ?? 'User-Agent'] = value -} - -// The outgoing UA identifies auth-document requests even across hosts. -export function currentUserAgent(headers: Record): string | undefined { - const existing = Object.keys(headers).find((key) => key.toLowerCase() === 'user-agent') - return existing ? headers[existing] : undefined -} diff --git a/src/main/browser/identity/browser-identity-mode-record.ts b/src/main/browser/identity/mode/browser-identity-mode-record.ts similarity index 97% rename from src/main/browser/identity/browser-identity-mode-record.ts rename to src/main/browser/identity/mode/browser-identity-mode-record.ts index 0c865cfe357..fa1b5e72bc2 100644 --- a/src/main/browser/identity/browser-identity-mode-record.ts +++ b/src/main/browser/identity/mode/browser-identity-mode-record.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' -import type { BrowserUserAgentMode } from '../../../shared/browser-user-agent-mode' +import type { BrowserUserAgentMode } from '../../../../shared/browser-user-agent-mode' /** Read synchronously before Electron ready: worker identity uses a process-global default. */ export const BROWSER_IDENTITY_MODE_FILE = 'browser-identity-mode.json' diff --git a/src/main/browser/identity/browser-identity-mode-store.test.ts b/src/main/browser/identity/mode/browser-identity-mode-store.test.ts similarity index 97% rename from src/main/browser/identity/browser-identity-mode-store.test.ts rename to src/main/browser/identity/mode/browser-identity-mode-store.test.ts index 8441ba91d8d..aa44f8cbc8f 100644 --- a/src/main/browser/identity/browser-identity-mode-store.test.ts +++ b/src/main/browser/identity/mode/browser-identity-mode-store.test.ts @@ -2,11 +2,11 @@ import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as DurableFileWrite from '../../filesystem/durable-file-write' +import type * as DurableFileWrite from '../../../filesystem/durable-file-write' const mocks = vi.hoisted(() => ({ failWrite: false })) -vi.mock('../../filesystem/durable-file-write', async (importOriginal) => { +vi.mock('../../../filesystem/durable-file-write', async (importOriginal) => { const actual = await importOriginal() return { ...actual, diff --git a/src/main/browser/identity/browser-identity-mode-store.ts b/src/main/browser/identity/mode/browser-identity-mode-store.ts similarity index 98% rename from src/main/browser/identity/browser-identity-mode-store.ts rename to src/main/browser/identity/mode/browser-identity-mode-store.ts index 38f8302248e..9814a140036 100644 --- a/src/main/browser/identity/browser-identity-mode-store.ts +++ b/src/main/browser/identity/mode/browser-identity-mode-store.ts @@ -1,12 +1,12 @@ import { randomUUID } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' -import { durableWriteTempPath, writeFileDurableSync } from '../../filesystem/durable-file-write' +import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' import type { BrowserIdentityModeSetResult, BrowserIdentityModeSnapshot, BrowserIdentityModeStatus, BrowserUserAgentMode -} from '../../../shared/browser-user-agent-mode' +} from '../../../../shared/browser-user-agent-mode' import { BROWSER_IDENTITY_MODE_VERSION, browserIdentityModeRecordPath, diff --git a/src/main/browser/sessions/browser-session-user-agent-migration-inspection.test.ts b/src/main/browser/identity/mode/browser-retired-profile-identity-inspection.test.ts similarity index 96% rename from src/main/browser/sessions/browser-session-user-agent-migration-inspection.test.ts rename to src/main/browser/identity/mode/browser-retired-profile-identity-inspection.test.ts index c1ce0338538..eb050a91f96 100644 --- a/src/main/browser/sessions/browser-session-user-agent-migration-inspection.test.ts +++ b/src/main/browser/identity/mode/browser-retired-profile-identity-inspection.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { getOrcaProfileBrowserSessionPartition } from '../../../shared/orca-profiles' -import { inspectRetiredBrowserSessionProfileUserAgentModes } from './browser-session-persisted-profile-validation' +import { getOrcaProfileBrowserSessionPartition } from '../../../../shared/orca-profiles' +import { inspectRetiredBrowserSessionProfileUserAgentModes } from './browser-retired-profile-identity-inspection' const ORCA_PROFILE_ID = 'local-default' const PROFILE_ID = '11111111-1111-4111-8111-111111111111' diff --git a/src/main/browser/identity/mode/browser-retired-profile-identity-inspection.ts b/src/main/browser/identity/mode/browser-retired-profile-identity-inspection.ts new file mode 100644 index 00000000000..4d472cd5ff8 --- /dev/null +++ b/src/main/browser/identity/mode/browser-retired-profile-identity-inspection.ts @@ -0,0 +1,39 @@ +import { isValidPersistedBrowserSessionProfile } from '../../sessions/profiles/browser-session-persisted-profile-validation' + +type PersistedProfileWithUserAgentMode = Record & { + readonly userAgentMode: unknown +} + +export function inspectRetiredBrowserSessionProfileUserAgentModes( + profiles: readonly unknown[], + activeOrcaProfileId: string +): { noticePending: boolean; degraded: boolean } { + let noticePending = false + let degraded = false + for (const profile of profiles) { + // Invalid profiles without a retired choice must not trigger a migration notice. + if (!isRecord(profile) || !hasPersistedProfileUserAgentMode(profile)) { + continue + } + noticePending = true + const mode = profile.userAgentMode + // Unknown modes and unhydratable profiles make the retired choice uninspectable. + if ( + (mode !== 'clean' && mode !== 'native') || + !isValidPersistedBrowserSessionProfile(profile, activeOrcaProfileId) + ) { + degraded = true + } + } + return { noticePending, degraded } +} + +function hasPersistedProfileUserAgentMode( + profile: Record +): profile is PersistedProfileWithUserAgentMode { + return Object.hasOwn(profile, 'userAgentMode') +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} diff --git a/src/main/browser/identity/browser-session-ua.ts b/src/main/browser/identity/requests/browser-session-ua.ts similarity index 59% rename from src/main/browser/identity/browser-session-ua.ts rename to src/main/browser/identity/requests/browser-session-ua.ts index 70152f28640..c55ceb2ad14 100644 --- a/src/main/browser/identity/browser-session-ua.ts +++ b/src/main/browser/identity/requests/browser-session-ua.ts @@ -1,17 +1,15 @@ import type { Session } from 'electron' -import type { BrowserTabIdentity, UserAgentMetadata } from './browser-tab-identity' - -import { getBrowserProcessUserAgentIdentity } from './browser-process-user-agent' -import { decideBrowserSessionRequestHeaders } from '../sessions/requests/browser-session-request-decisions' -import { reportBrowserSessionWebRequest } from '../sessions/requests/browser-session-web-request-observer' - +import type { BrowserTabIdentity } from '../browser-tab-identity' +import { getBrowserProcessUserAgentIdentity } from '../browser-process-user-agent' +import { decideBrowserSessionRequestHeaders } from '../../sessions/requests/browser-session-request-decisions' +import { reportBrowserSessionWebRequest } from '../../sessions/requests/browser-session-web-request-observer' import { currentUserAgent, - googleAuthUserAgent, setUserAgentHeader, - shouldUseGoogleAuthIdentity, - stripClientHints -} from './browser-google-auth-ua' + stripClientHints, + applyUserAgentMetadataHeaders +} from './browser-user-agent-request-headers' +import { googleAuthUserAgent, shouldUseGoogleAuthIdentity } from '../browser-google-auth-ua' export type BrowserSessionRequestUserAgentResolver = (args: { session: Session @@ -23,44 +21,6 @@ export type BrowserSessionRequestUserAgentResolver = (args: { effectiveUserAgent?: string }) => BrowserTabIdentity | undefined -function quoteClientHint(value: string): string { - return `"${value.replace(/["\\]/g, '\\$&')}"` -} - -function formatClientHintBrands(brands: { brand: string; version: string }[]): string { - return brands - .map(({ brand, version }) => `${quoteClientHint(brand)};v=${quoteClientHint(version)}`) - .join(', ') -} - -function applyUserAgentMetadataHeaders( - headers: Record, - metadata: UserAgentMetadata -): void { - const values: Record = { - 'sec-ch-ua': formatClientHintBrands(metadata.brands), - 'sec-ch-ua-full-version-list': formatClientHintBrands(metadata.fullVersionList), - 'sec-ch-ua-full-version': quoteClientHint(metadata.fullVersion), - 'sec-ch-ua-platform': quoteClientHint(metadata.platform), - 'sec-ch-ua-platform-version': quoteClientHint(metadata.platformVersion), - 'sec-ch-ua-arch': quoteClientHint(metadata.architecture), - 'sec-ch-ua-model': quoteClientHint(metadata.model), - 'sec-ch-ua-mobile': metadata.mobile ? '?1' : '?0' - } - for (const key of Object.keys(headers)) { - const lowerKey = key.toLowerCase() - if (!lowerKey.startsWith('sec-ch-ua')) { - continue - } - const value = values[lowerKey] - if (value === undefined) { - delete headers[key] - } else { - headers[key] = value - } - } -} - // Rewrite only hints Chromium emitted; desktop hints remain browser-owned. export function installBrowserSessionUserAgentPolicy( sess: Session, diff --git a/src/main/browser/identity/requests/browser-user-agent-request-headers.ts b/src/main/browser/identity/requests/browser-user-agent-request-headers.ts new file mode 100644 index 00000000000..84bd8d5be61 --- /dev/null +++ b/src/main/browser/identity/requests/browser-user-agent-request-headers.ts @@ -0,0 +1,59 @@ +import type { UserAgentMetadata } from '../browser-tab-identity' + +export function stripClientHints(headers: Record): void { + for (const key of Object.keys(headers)) { + if (key.toLowerCase().startsWith('sec-ch-ua')) { + delete headers[key] + } + } +} + +// Replace case-insensitively to avoid duplicate User-Agent headers. +export function setUserAgentHeader(headers: Record, value: string): void { + const existing = Object.keys(headers).find((key) => key.toLowerCase() === 'user-agent') + headers[existing ?? 'User-Agent'] = value +} + +// The outgoing UA identifies auth-document requests even across hosts. +export function currentUserAgent(headers: Record): string | undefined { + const existing = Object.keys(headers).find((key) => key.toLowerCase() === 'user-agent') + return existing ? headers[existing] : undefined +} + +function quoteClientHint(value: string): string { + return `"${value.replace(/["\\]/g, '\\$&')}"` +} + +function formatClientHintBrands(brands: { brand: string; version: string }[]): string { + return brands + .map(({ brand, version }) => `${quoteClientHint(brand)};v=${quoteClientHint(version)}`) + .join(', ') +} + +export function applyUserAgentMetadataHeaders( + headers: Record, + metadata: UserAgentMetadata +): void { + const values: Record = { + 'sec-ch-ua': formatClientHintBrands(metadata.brands), + 'sec-ch-ua-full-version-list': formatClientHintBrands(metadata.fullVersionList), + 'sec-ch-ua-full-version': quoteClientHint(metadata.fullVersion), + 'sec-ch-ua-platform': quoteClientHint(metadata.platform), + 'sec-ch-ua-platform-version': quoteClientHint(metadata.platformVersion), + 'sec-ch-ua-arch': quoteClientHint(metadata.architecture), + 'sec-ch-ua-model': quoteClientHint(metadata.model), + 'sec-ch-ua-mobile': metadata.mobile ? '?1' : '?0' + } + for (const key of Object.keys(headers)) { + const lowerKey = key.toLowerCase() + if (!lowerKey.startsWith('sec-ch-ua')) { + continue + } + const value = values[lowerKey] + if (value === undefined) { + delete headers[key] + } else { + headers[key] = value + } + } +} diff --git a/src/main/browser/identity/browser-session-ua-cdp-collector.ts b/src/main/browser/identity/wire-probes/browser-session-ua-cdp-collector.ts similarity index 98% rename from src/main/browser/identity/browser-session-ua-cdp-collector.ts rename to src/main/browser/identity/wire-probes/browser-session-ua-cdp-collector.ts index 42049c2d123..7ab6387f8b7 100644 --- a/src/main/browser/identity/browser-session-ua-cdp-collector.ts +++ b/src/main/browser/identity/wire-probes/browser-session-ua-cdp-collector.ts @@ -1,6 +1,6 @@ import WebSocket from 'ws' -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' -import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' +import { isRecord } from '../../../../shared/agent-status/child-work/agent-status-child-work-value-guards' export type BrowserSessionUaCdpRequest = Readonly<{ targetType: string diff --git a/src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts similarity index 99% rename from src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts rename to src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts index f6b230fd8c3..d5b3e0c58f9 100644 --- a/src/main/browser/identity/browser-session-ua-wire-identity-cross-context.electron.test.ts +++ b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts @@ -33,7 +33,7 @@ beforeAll(async () => { 'src/main/browser/identity/browser-process-user-agent.ts', processIdentityModulePath ), - buildModule('src/main/browser/identity/browser-session-ua.ts', exceptionModulePath) + buildModule('src/main/browser/identity/requests/browser-session-ua.ts', exceptionModulePath) ]) }) diff --git a/src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts similarity index 99% rename from src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts rename to src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts index e2043149ef8..e3d42272402 100644 --- a/src/main/browser/identity/browser-session-ua-wire-identity.electron.test.ts +++ b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts @@ -33,7 +33,7 @@ beforeAll(async () => { 'src/main/browser/identity/browser-process-user-agent.ts', processIdentityModulePath ), - buildModule('src/main/browser/identity/browser-session-ua.ts', exceptionModulePath) + buildModule('src/main/browser/identity/requests/browser-session-ua.ts', exceptionModulePath) ]) }) diff --git a/src/main/browser/identity/browser-session-ua-wire-probe-server.ts b/src/main/browser/identity/wire-probes/browser-session-ua-wire-probe-server.ts similarity index 99% rename from src/main/browser/identity/browser-session-ua-wire-probe-server.ts rename to src/main/browser/identity/wire-probes/browser-session-ua-wire-probe-server.ts index 5f1625f89e9..b6045fa2ea7 100644 --- a/src/main/browser/identity/browser-session-ua-wire-probe-server.ts +++ b/src/main/browser/identity/wire-probes/browser-session-ua-wire-probe-server.ts @@ -10,7 +10,7 @@ import type { Duplex } from 'node:stream' import { LOCAL_HTTPS_TEST_CERTIFICATE, LOCAL_HTTPS_TEST_PRIVATE_KEY -} from '../electron-fixtures/browser-local-https-test-certificate' +} from '../../electron-fixtures/browser-local-https-test-certificate' export type WireProbeReceipt = Readonly<{ protocol: 'http' | 'https' | 'ws' | 'wss' diff --git a/src/main/browser/network/client-routes/browser-client-network-route-registry.ts b/src/main/browser/network/client-routes/browser-client-network-route-registry.ts index 8bc5455aad2..f474f3fefd2 100644 --- a/src/main/browser/network/client-routes/browser-client-network-route-registry.ts +++ b/src/main/browser/network/client-routes/browser-client-network-route-registry.ts @@ -1,6 +1,6 @@ import type { BrowserHostLeaseAuthority } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' import type { BrowserNetworkExecutionHost } from '../../../../shared/browser/client-hosting/browser-network-execution-host' -import type { BrowserClientPageNetworkRoute } from '../../client-pages/lifecycle/browser-client-page-cleanup' +import type { BrowserClientPageNetworkRoute } from './browser-client-page-network-route' import { assertBrowserClientNetworkRouteAddress, sameBrowserClientNetworkRouteAddress diff --git a/src/main/browser/network/client-routes/browser-client-page-network-route.ts b/src/main/browser/network/client-routes/browser-client-page-network-route.ts new file mode 100644 index 00000000000..7de7789e114 --- /dev/null +++ b/src/main/browser/network/client-routes/browser-client-page-network-route.ts @@ -0,0 +1,10 @@ +import type { BrowserRouteProxyEndpoint } from '../../routing/sessions/browser-route-session-policy' + +export type BrowserClientPageNetworkRoute = { + key: string + executionHostIdentity: string + /** Pre-migration identity of the same host, so its existing partition can be adopted. */ + legacyExecutionHostIdentity: string + proxyEndpoint: BrowserRouteProxyEndpoint + release(): void | Promise +} diff --git a/src/main/browser/routing/guest-authority/browser-route-guest-popups.test.ts b/src/main/browser/routing/guest-authority/browser-route-guest-popups.test.ts index d18e0e84c19..98b6c8a0509 100644 --- a/src/main/browser/routing/guest-authority/browser-route-guest-popups.test.ts +++ b/src/main/browser/routing/guest-authority/browser-route-guest-popups.test.ts @@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const popupMocks = vi.hoisted(() => ({ openPopupWithOriginBar: vi.fn() })) -vi.mock('../../guest-lifecycle/popups/popup-origin-bar-window', () => ({ +vi.mock('../../guest-lifecycle/popups/presentation/popup-origin-bar-window', () => ({ openPopupWithOriginBar: popupMocks.openPopupWithOriginBar })) diff --git a/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts b/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts index 34871c7b514..f77a9f5877a 100644 --- a/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts +++ b/src/main/browser/routing/guest-authority/browser-route-guest-popups.ts @@ -5,27 +5,21 @@ import { normalizeBrowserPopupUrl } from '../../guest-lifecycle/popups/browser-popup-new-tab-intent' import { enforceBrowserRouteWebRtcPolicy } from '../../network/egress/browser-route-webrtc-policy' -import { - trackBrowserGuestInputGesture, - type BrowserGuestInputGesture -} from '../../guest-lifecycle/input/browser-guest-input-gesture' +import { trackBrowserGuestInputGesture } from '../../guest-lifecycle/input/browser-guest-input-gesture' +import type { BrowserGuestInputGesture } from '../../guest-lifecycle/input/browser-guest-input-gesture' import { registerBrowserRouteGuestPopup, releaseBrowserRouteGuestPopup } from './browser-route-guest-popup-ownership' -import { - ROUTE_POPUP_WINDOW_OPTIONS, - type BrowserRouteGuestPopupWindow -} from './browser-route-guest-popup-window-options' -import { - openPopupWithOriginBar, - type PopupChildWindowOptions -} from '../../guest-lifecycle/popups/popup-origin-bar-window' +import { ROUTE_POPUP_WINDOW_OPTIONS } from './browser-route-guest-popup-window-options' +import type { BrowserRouteGuestPopupWindow } from './browser-route-guest-popup-window-options' +import { openPopupWithOriginBar } from '../../guest-lifecycle/popups/presentation/popup-origin-bar-window' +import type { PopupChildWindowOptions } from '../../guest-lifecycle/popups/presentation/browser-popup-window-contract' import { allowNativeBrowserPopup, isNativeBrowserPopupRequest -} from '../../guest-lifecycle/popups/browser-popup-native-window' -import { allowPageUnload } from '../../guest-lifecycle/browser-guest-unload-policy' +} from '../../guest-lifecycle/popups/presentation/browser-popup-native-window' +import { allowPageUnload } from '../../guest-lifecycle/navigation/browser-guest-unload-policy' export const MAX_BROWSER_ROUTE_GUEST_POPUPS = 4 diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-partitions.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-partitions.ts index 64057090412..f21edb8afd3 100644 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-partitions.ts +++ b/src/main/browser/routing/local-host-partitions/local-ssh-browser-partitions.ts @@ -19,7 +19,7 @@ import { type BrowserRouteProxyEndpoint } from '../sessions/browser-route-session-policy' import { enforceBrowserRouteWebRtcPolicy } from '../../network/egress/browser-route-webrtc-policy' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { closeLocalSshBrowserRouteForTarget, probeLocalSshBrowserRouteForwarding, diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-profile-retirement.test.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-profile-retirement.test.ts index 108a0729592..5f18eccd026 100644 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-profile-retirement.test.ts +++ b/src/main/browser/routing/local-host-partitions/local-ssh-browser-profile-retirement.test.ts @@ -60,13 +60,13 @@ vi.mock('../../cookies/staging/browser-session-cookie-staging', () => ({ applyPendingBrowserCookieImports() {}, clearPendingBrowserCookieImport() {} })) -vi.mock('../../sessions/browser-session-partition-policies', () => ({ +vi.mock('../../sessions/partition-policies/browser-session-partition-policies', () => ({ installBrowserSessionPartitionPolicies: state.policy, clearBrowserSessionPartitionPolicies: state.clearPolicy, forgetBrowserSessionPartitionConfiguration() {}, retireBrowserSessionUserAgentPolicy() {} })) -vi.mock('../../sessions/browser-session-proxy', () => ({ +vi.mock('../../sessions/proxy/browser-session-proxy', () => ({ invalidateBrowserSessionProxyApplication() {} })) vi.mock('../../../network/proxy-settings', () => ({ async retireProxySessionApplication() {} })) @@ -80,13 +80,15 @@ vi.mock('../../extensions/profile-sessions/browser-extension-session-loader', () vi.mock('../../../persistence/loading-store/user-data-path', () => ({ getCanonicalUserDataPath: () => state.directory })) -vi.mock('../../identity/browser-identity-mode-store', () => ({ +vi.mock('../../identity/mode/browser-identity-mode-store', () => ({ async markBrowserIdentityMigrationNoticePending() {} })) -vi.mock('../../site-settings/browser-site-permission-store', () => ({ +vi.mock('../../site-settings/permissions/browser-site-permission-store', () => ({ forgetBrowserSitePermissions() {} })) -vi.mock('../../site-settings/browser-site-display-store', () => ({ forgetBrowserSiteDisplay() {} })) +vi.mock('../../site-settings/display/browser-site-display-store', () => ({ + forgetBrowserSiteDisplay() {} +})) vi.mock('../../network/egress/browser-route-webrtc-policy', () => ({ enforceBrowserRouteWebRtcPolicy() {} })) @@ -97,7 +99,7 @@ vi.mock('./local-ssh-browser-route', () => ({ })) import { session } from 'electron' -import { browserSessionRegistry as registry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry as registry } from '../../sessions/profiles/browser-session-registry' import { configureBrowserRoutePartitionBindingsForOrcaProfile, currentBrowserRoutePartitionBindingStore diff --git a/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.test.ts b/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.test.ts index 8948b0ed6fb..4a68741c1ba 100644 --- a/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.test.ts +++ b/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.test.ts @@ -15,11 +15,11 @@ vi.mock('electron', () => ({ app: { getPath: () => mocks.userData }, session: { fromPartition: mocks.fromPartition } })) -vi.mock('../../sessions/browser-session-partition-policies', () => ({ +vi.mock('../../sessions/partition-policies/browser-session-partition-policies', () => ({ installBrowserSessionPartitionPolicies: vi.fn(async () => {}), clearBrowserSessionPartitionPolicies: mocks.clearPolicies })) -vi.mock('../../sessions/browser-session-profile-retirement', () => ({ +vi.mock('../../sessions/profiles/browser-session-profile-retirement', () => ({ retireDeletedBrowserSessionProfile: vi.fn(async () => {}), retireFailedBrowserSessionProfile: vi.fn(async () => {}) })) diff --git a/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.ts b/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.ts index c875e5d978d..85f56a779ed 100644 --- a/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.ts +++ b/src/main/browser/routing/partitions/browser-route-partition-storage-dependencies.ts @@ -9,7 +9,7 @@ import { currentBrowserRoutePartitionBindingStore, routePartitionDataRoot } from './browser-route-partition-binding-runtime' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { browserRoutePartitionPendingDeletesPath, queueBrowserRoutePartitionDirectoryDelete diff --git a/src/main/browser/routing/sessions/browser-route-session-runtime.ts b/src/main/browser/routing/sessions/browser-route-session-runtime.ts index 50d092027ce..7373196f7f9 100644 --- a/src/main/browser/routing/sessions/browser-route-session-runtime.ts +++ b/src/main/browser/routing/sessions/browser-route-session-runtime.ts @@ -9,14 +9,14 @@ import { } from '../partitions/browser-route-partition-binding-runtime' import { releaseEvictedBrowserRoutePartitionStorage } from '../partitions/browser-route-partition-storage-dependencies' import { isBrowserRouteGuestPopup } from '../guest-authority/browser-route-guest-popup-ownership' -import { browserManager } from '../../browser-manager' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { isBrowserRoutePartitionRetainedByAnyOwner, registerBrowserRoutePartitionRetentionProbe } from '../partitions/browser-route-partition-retention' import { BrowserRouteSessionRegistry } from './browser-route-session-registry' import { BrowserRouteWebContentsRegistry } from '../guest-authority/browser-route-webcontents-registry' -import { browserSessionRegistry } from '../../sessions/browser-session-registry' +import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' const routeWebContentsRegistryRef: { current: BrowserRouteWebContentsRegistry | null diff --git a/src/main/browser/routing/sessions/browser-session-route-policies.ts b/src/main/browser/routing/sessions/browser-session-route-policies.ts index 77063069f5b..aa4dc37b78c 100644 --- a/src/main/browser/routing/sessions/browser-session-route-policies.ts +++ b/src/main/browser/routing/sessions/browser-session-route-policies.ts @@ -4,7 +4,7 @@ import { isBrowserRoutePartition } from '../partitions/browser-route-identity' import { clearBrowserSessionPartitionPolicies, installBrowserSessionPartitionPolicies -} from '../../sessions/browser-session-partition-policies' +} from '../../sessions/partition-policies/browser-session-partition-policies' export function installBrowserRoutePartitionPolicies( profile: BrowserSessionProfile, diff --git a/src/main/browser/sessions/browser-session-partition-policies.ts b/src/main/browser/sessions/browser-session-partition-policies.ts deleted file mode 100644 index 0d956f78e0c..00000000000 --- a/src/main/browser/sessions/browser-session-partition-policies.ts +++ /dev/null @@ -1,319 +0,0 @@ -import { session } from 'electron' -import type { Session } from 'electron' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' -import { browserManager } from '../browser-manager' -import { clearProxySessionCredentials } from '../../network/proxy-settings' -import { - applyProxyToBrowserSession, - invalidateBrowserSessionProxyApplication -} from './browser-session-proxy' -import { - hasSystemMediaAccess, - requestSystemMediaAccess -} from '../site-settings/browser-media-access' -import { isAutoGrantedBrowserSessionPermission } from '../site-settings/browser-session-permission-policy' -import { - answerBrowserLocalNetworkCheck, - browserSitePermissionRequestingOrigin, - browserSitePermissionsFor, - decideBrowserSitePermissions, - isBrowserSitePermissionAllowed, - savedBrowserSitePermissions, - sessionBrowserSitePermissions -} from '../site-settings/browser-site-permission-prompt' -import { installBrowserSessionUserAgentPolicy } from '../identity/browser-session-ua' -import { getBrowserProcessUserAgentIdentity } from '../identity/browser-process-user-agent' -import { - allowsBrowserWebAuthnPermission, - clearBrowserWebAuthnAccessHandlers, - installBrowserWebAuthnAccessHandlers -} from '../webauthn/browser-webauthn-access' -import { noticeDocPreviewDownloadBlocked } from '../document-preview/doc-preview-download-block-notice' -import { isRemoteCliDrivenGuest } from '../desktop-browser-bridge/remote-cli-driven-workspaces' - -const configuredPartitions = new Set() -const userAgentPolicyDisposerBySession = new WeakMap void>() - -export function retireBrowserSessionUserAgentPolicy(sess: Session): void { - const dispose = userAgentPolicyDisposerBySession.get(sess) - if (!dispose) { - return - } - userAgentPolicyDisposerBySession.delete(sess) - dispose() -} - -function configureBrowserSessionUserAgentPolicy(sess: Session, installExceptions: boolean): void { - sess.setUserAgent(getBrowserProcessUserAgentIdentity().userAgent) - if (!installExceptions) { - retireBrowserSessionUserAgentPolicy(sess) - return - } - if (userAgentPolicyDisposerBySession.has(sess)) { - return - } - userAgentPolicyDisposerBySession.set( - sess, - installBrowserSessionUserAgentPolicy(sess, (request) => - browserManager.resolveBrowserGuestRequestUserAgent(request) - ) - ) -} - -// SSH-driven pages must not read the desktop clipboard. -function deniesRemoteCliDrivenClipboardRead(permission: string, webContentsId?: number): boolean { - return permission === 'clipboard-read' && isRemoteCliDrivenGuest(webContentsId) -} - -/** Drop only the installer memo; retired-session guards remain fail-closed. */ -export function forgetBrowserSessionPartitionConfiguration(partition: string): void { - configuredPartitions.delete(partition) -} -const handleWillDownload = ( - event: Electron.Event, - item: Electron.DownloadItem, - webContents: Electron.WebContents -): void => { - // Prevent SSH-driven pages from writing host-chosen files into desktop Downloads. - if (isRemoteCliDrivenGuest(webContents.id)) { - event.preventDefault() - console.info('[desktop-browser-bridge] refused a download from a page an SSH host drives') - return - } - browserManager.handleGuestWillDownload({ guestWebContentsId: webContents.id, item }) -} - -// will-download omits the partition; attach each partition's selected policy to its session. -const handleDeniedWillDownload = ( - event: Electron.Event, - _item: Electron.DownloadItem, - webContents: Electron.WebContents -): void => { - event.preventDefault() - noticeDocPreviewDownloadBlocked(webContents) -} - -type RestrictedFileSystemAccessListener = ( - event: Electron.Event, - details: Electron.FileSystemAccessRestrictedDetails, - callback: (action: 'allow' | 'deny' | 'tryAgain') => void -) => void - -// Chromium waits for an answer on blocklisted system folders; without one the page hangs. -const denyRestrictedFileSystemAccess: RestrictedFileSystemAccessListener = ( - _event, - _details, - callback -) => callback('deny') - -const handleRestrictedFileSystemAccess: RestrictedFileSystemAccessListener = ( - _event, - details, - callback -) => { - callback('deny') - if (details.webContents) { - browserManager.notifyPermissionDenied({ - guestWebContentsId: details.webContents.id, - permission: 'fileSystem', - rawUrl: details.origin - }) - } -} - -function resolvePermissionNoticeUrl( - webContents: Electron.WebContents, - details: Electron.PermissionRequest | undefined -): string { - const requestingUrl = details?.requestingUrl - if (!requestingUrl) { - return webContents.getURL() - } - try { - return new URL(requestingUrl).origin === 'null' ? '' : requestingUrl - } catch { - return '' - } -} - -export type BrowserPartitionDownloadPolicy = 'route' | 'deny' -export type BrowserPartitionPermissionPolicy = 'browser' | 'deny' - -// Keep async so initialization errors reach callers through the returned promise. -export async function installBrowserSessionPartitionPolicies( - profile: BrowserSessionProfile, - options: { - downloads?: BrowserPartitionDownloadPolicy - permissions?: BrowserPartitionPermissionPolicy - applyAppWideProxy?: boolean - /** Off where another machine can script pages and reuse their stored file handles. */ - fileSystemAccess?: boolean - userAgentExceptions?: boolean - /** Session-only answers are not persisted to a browser profile. */ - sitePermissions?: 'saved' | 'session' - } = {} -): Promise { - const { partition } = profile - const sess = session.fromPartition(partition) - configureBrowserSessionUserAgentPolicy(sess, options.userAgentExceptions !== false) - // Route partitions own a SOCKS policy that the app proxy must not overwrite. - const proxyReady = ( - options.applyAppWideProxy === false ? Promise.resolve() : applyProxyToBrowserSession(sess) - ).catch((error: unknown) => { - clearProxySessionCredentials(sess) - throw error - }) - if (configuredPartitions.has(partition)) { - return proxyReady - } - - browserManager.installCertificateRequestGuard(sess) - if (options?.permissions === 'deny') { - sess.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false)) - sess.setPermissionCheckHandler(() => false) - clearBrowserWebAuthnAccessHandlers(sess) - } else { - // Electron answers every File System Access grant here, overriding Chromium's own; - // the user's pick or drop is the consent, and handles a site stores keep their access. - const grantsFileSystem = options.fileSystemAccess !== false - const isAutoGranted = (permission: string): boolean => - isAutoGrantedBrowserSessionPermission(permission) || - (grantsFileSystem && permission === 'fileSystem') - const siteMemory = - options.sitePermissions === 'session' - ? sessionBrowserSitePermissions(partition) - : savedBrowserSitePermissions(profile.id) - sess.setPermissionRequestHandler((webContents, permission, callback, details) => { - if ( - permission === 'openExternal' && - browserManager.requestExternalAppLaunch( - webContents, - 'externalURL' in details ? details.externalURL : undefined, - () => resolvePermissionNoticeUrl(webContents, details) || null - ) - ) { - // Orca launches approved apps itself; deny Chromium's duplicate launch. - callback(false) - return - } - // Capture the requesting URL before async handling; opaque frames have no named site. - const rawUrl = resolvePermissionNoticeUrl(webContents, details) - const notifyDenied = (): void => - browserManager.notifyPermissionDenied({ - guestWebContentsId: webContents.id, - permission, - rawUrl - }) - if (deniesRemoteCliDrivenClipboardRead(permission, webContents.id)) { - notifyDenied() - callback(false) - return - } - const mediaRequest = 'mediaTypes' in details ? details : undefined - const sitePermissions = browserSitePermissionsFor(permission, mediaRequest?.mediaTypes) - if (!sitePermissions) { - const allowed = isAutoGranted(permission) - if (!allowed) { - notifyDenied() - } - callback(allowed) - return - } - const decide = async (): Promise => { - const allowed = await decideBrowserSitePermissions({ - requester: webContents, - frameOrigin: sitePermissions.includes('notifications') - ? browserSitePermissionRequestingOrigin(webContents, details) - : null, - memory: siteMemory, - permissions: sitePermissions - }) - if (!allowed || permission !== 'media') { - return allowed - } - // macOS also gates camera and mic per app; distinguish OS refusal from a site decision. - const granted = await requestSystemMediaAccess(mediaRequest) - if (!granted) { - notifyDenied() - } - return granted - } - void decide().then(callback, (error: unknown) => { - console.error('[permissions] Browser site permission failed:', error) - callback(false) - }) - }) - sess.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { - if (deniesRemoteCliDrivenClipboardRead(permission, webContents?.id)) { - return false - } - if (allowsBrowserWebAuthnPermission(permission, details)) { - return true - } - const sitePermissions = browserSitePermissionsFor( - permission, - details?.mediaType ? [details.mediaType] : undefined - ) - if (sitePermissions) { - const source = { - // Service-worker checks have no WebContents; use their requesting origin. - pageUrl: webContents?.getURL() ?? requestingOrigin, - // Checks supply the frame's inherited origin. - frameOrigin: requestingOrigin - } - if (sitePermissions.includes('local-network')) { - return answerBrowserLocalNetworkCheck({ - requester: webContents, - source, - memory: siteMemory - }) - } - return ( - isBrowserSitePermissionAllowed({ - source, - memory: siteMemory, - permissions: sitePermissions - }) && - (permission !== 'media' || hasSystemMediaAccess(details?.mediaType)) - ) - } - return isAutoGranted(permission) - }) - installBrowserWebAuthnAccessHandlers(sess) - } - sess.setDisplayMediaRequestHandler((_request, callback) => { - callback({ video: undefined, audio: undefined }) - }) - sess.removeListener('will-download', handleWillDownload) - sess.removeListener('will-download', handleDeniedWillDownload) - sess.on( - 'will-download', - options?.downloads === 'deny' ? handleDeniedWillDownload : handleWillDownload - ) - sess.removeListener('file-system-access-restricted', denyRestrictedFileSystemAccess) - sess.removeListener('file-system-access-restricted', handleRestrictedFileSystemAccess) - sess.on( - 'file-system-access-restricted', - options?.permissions === 'deny' - ? denyRestrictedFileSystemAccess - : handleRestrictedFileSystemAccess - ) - configuredPartitions.add(partition) - return proxyReady -} - -export function clearBrowserSessionPartitionPolicies(partition: string, sess: Session): void { - // Electron Sessions outlive removed partitions; release their callbacks and listeners. - invalidateBrowserSessionProxyApplication(sess) - retireBrowserSessionUserAgentPolicy(sess) - configuredPartitions.delete(partition) - browserManager.removeCertificateRequestGuard(sess) - sess.removeListener('will-download', handleWillDownload) - sess.removeListener('will-download', handleDeniedWillDownload) - sess.removeListener('file-system-access-restricted', denyRestrictedFileSystemAccess) - sess.removeListener('file-system-access-restricted', handleRestrictedFileSystemAccess) - clearBrowserWebAuthnAccessHandlers(sess) - sess.setPermissionRequestHandler(null) - sess.setPermissionCheckHandler(null) - sess.setDisplayMediaRequestHandler(null) -} diff --git a/src/main/browser/sessions/browser-session-persisted-profile-validation.ts b/src/main/browser/sessions/browser-session-persisted-profile-validation.ts deleted file mode 100644 index 3370a9b9e5a..00000000000 --- a/src/main/browser/sessions/browser-session-persisted-profile-validation.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { getOrcaProfileBrowserSessionPartition } from '../../../shared/orca-profiles' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' - -const BROWSER_SESSION_PROFILE_ID_RE = - /^[\da-f-]{8}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{12}$/ - -type PersistedProfileWithUserAgentMode = Record & { - readonly userAgentMode: unknown -} - -// Persisted metadata must not add arbitrary partitions to the webview allowlist. -export function isValidPersistedBrowserSessionProfile( - profile: unknown, - activeOrcaProfileId: string -): profile is BrowserSessionProfile { - if (!profile || typeof profile !== 'object') { - return false - } - const candidate = profile as Partial - return ( - candidate.id !== 'default' && - candidate.scope !== 'default' && - typeof candidate.id === 'string' && - typeof candidate.partition === 'string' && - typeof candidate.label === 'string' && - isProfileOwnedSessionPartition(candidate.id, candidate.partition, activeOrcaProfileId) - ) -} - -export function inspectRetiredBrowserSessionProfileUserAgentModes( - profiles: readonly unknown[], - activeOrcaProfileId: string -): { noticePending: boolean; degraded: boolean } { - let noticePending = false - let degraded = false - for (const profile of profiles) { - // Invalid profiles without a retired choice must not trigger a migration notice. - if (!isRecord(profile) || !hasPersistedProfileUserAgentMode(profile)) { - continue - } - noticePending = true - const mode = profile.userAgentMode - // Unknown modes and unhydratable profiles make the retired choice uninspectable. - if ( - (mode !== 'clean' && mode !== 'native') || - !isValidPersistedBrowserSessionProfile(profile, activeOrcaProfileId) - ) { - degraded = true - } - } - return { noticePending, degraded } -} - -function hasPersistedProfileUserAgentMode( - profile: Record -): profile is PersistedProfileWithUserAgentMode { - return Object.hasOwn(profile, 'userAgentMode') -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isProfileOwnedSessionPartition( - profileId: string, - partition: string, - activeOrcaProfileId: string -): boolean { - return ( - BROWSER_SESSION_PROFILE_ID_RE.test(profileId) && - partition === getOrcaProfileBrowserSessionPartition(activeOrcaProfileId, profileId) - ) -} diff --git a/src/main/browser/sessions/browser-session-startup.ts b/src/main/browser/sessions/browser-session-startup.ts index aeec760ff1d..e831064fd3d 100644 --- a/src/main/browser/sessions/browser-session-startup.ts +++ b/src/main/browser/sessions/browser-session-startup.ts @@ -1,9 +1,9 @@ -import { browserSessionRegistry } from './browser-session-registry' -import type { BrowserSessionRegistryProfileOptions } from './browser-session-registry' +import { browserSessionRegistry } from './profiles/browser-session-registry' +import type { BrowserSessionRegistryProfileOptions } from './profiles/browser-session-registry' import { collectOrphanedBrowserRoutePartitionStorage } from '../routing/partitions/browser-route-partition-storage-runtime' import { configureRouteSessionsForOrcaProfile } from '../routing/sessions/browser-route-session-runtime' -import { configureBrowserSitePermissionStore } from '../site-settings/browser-site-permission-store' -import { configureBrowserSiteDisplayStore } from '../site-settings/browser-site-display-store' +import { configureBrowserSitePermissionStore } from '../site-settings/permissions/browser-site-permission-store' +import { configureBrowserSiteDisplayStore } from '../site-settings/display/browser-site-display-store' import { configureBrowserExtensionProfileDataDirectory } from '../extensions/profile-storage/browser-extension-profile-data-directory' import { configurePairedRuntimeBrowserClientHostsForOrcaProfile } from '../client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' import { configureBrowserPasswordVaults } from '../../browser-passwords/browser-password-vaults' diff --git a/src/main/browser/sessions/browser-session-partition-policies.test.ts b/src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts similarity index 93% rename from src/main/browser/sessions/browser-session-partition-policies.test.ts rename to src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts index 1baf0531735..0653d3e0b38 100644 --- a/src/main/browser/sessions/browser-session-partition-policies.test.ts +++ b/src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' const mocks = vi.hoisted(() => ({ handleGuestWillDownload: vi.fn(), @@ -74,10 +74,10 @@ vi.mock('electron', () => ({ } } })) -vi.mock('../desktop-browser-bridge/remote-cli-driven-workspaces', () => ({ +vi.mock('../../desktop-browser-bridge/remote-cli-driven-workspaces', () => ({ isRemoteCliDrivenGuest: mocks.isRemoteCliDrivenGuest })) -vi.mock('../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { handleGuestWillDownload: mocks.handleGuestWillDownload, installCertificateRequestGuard: vi.fn(), @@ -87,20 +87,20 @@ vi.mock('../browser-manager', () => ({ resolvePagePromptTarget: mocks.resolvePagePromptTarget } })) -vi.mock('../document-preview/doc-preview-download-block-notice', () => ({ +vi.mock('../../document-preview/doc-preview-download-block-notice', () => ({ noticeDocPreviewDownloadBlocked: mocks.noticeDocPreviewDownloadBlocked })) -vi.mock('../site-settings/browser-media-access', () => ({ +vi.mock('../../site-settings/permissions/browser-media-access', () => ({ hasSystemMediaAccess: () => false, requestSystemMediaAccess: async () => false })) -vi.mock('../identity/browser-session-ua', () => ({ +vi.mock('../../identity/requests/browser-session-ua', () => ({ installBrowserSessionUserAgentPolicy: vi.fn(() => vi.fn()) })) -vi.mock('../identity/browser-process-user-agent', () => ({ +vi.mock('../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: 'Mozilla/5.0 Orca' }) })) -vi.mock('../webauthn/browser-webauthn-access', () => ({ +vi.mock('../../webauthn/browser-webauthn-access', () => ({ allowsBrowserWebAuthnPermission: () => false, clearBrowserWebAuthnAccessHandlers: mocks.clearBrowserWebAuthnAccessHandlers, installBrowserWebAuthnAccessHandlers: mocks.installBrowserWebAuthnAccessHandlers @@ -147,7 +147,7 @@ describe('partition permission policy', () => { it('denies clipboard reads only to pages an SSH host has driven (#29145)', async () => { mocks.isRemoteCliDrivenGuest.mockImplementation((id?: number) => id === 7) const install = await loadInstaller() - const store = await import('../site-settings/browser-site-permission-store') + const store = await import('../../site-settings/permissions/browser-site-permission-store') store.configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) store.setBrowserSitePermissionDecisions( 'persist:browsing-2', @@ -193,7 +193,7 @@ describe('partition permission policy', () => { it("answers a notification from a frame with an inherited origin as the frame's real site", async () => { const install = await loadInstaller() - const store = await import('../site-settings/browser-site-permission-store') + const store = await import('../../site-settings/permissions/browser-site-permission-store') store.configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) store.setBrowserSitePermissionDecisions( 'persist:browsing-frames', @@ -253,10 +253,10 @@ describe('partition permission policy', () => { it('asks when a page checks local network access, since Electron never requests it', async () => { const install = await loadInstaller() - const store = await import('../site-settings/browser-site-permission-store') + const store = await import('../../site-settings/permissions/browser-site-permission-store') store.configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) const { respondToBrowserPagePrompt } = - await import('../guest-lifecycle/prompts/browser-page-prompts') + await import('../../guest-lifecycle/prompts/browser-page-prompts') const send = vi.fn() // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: prompts only read id, isDestroyed, send and subscribe to the window's lifecycle events. const renderer = { @@ -305,7 +305,7 @@ describe('partition permission policy', () => { it("keeps a paired server's pages off this computer's saved answers for the same profile id", async () => { const install = await loadInstaller() - const store = await import('../site-settings/browser-site-permission-store') + const store = await import('../../site-settings/permissions/browser-site-permission-store') store.configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) store.setBrowserSitePermissionDecisions('default', 'https://a.test', ['clipboard'], 'allow') const desktop = { ...profileFor('persist:desktop-default'), id: 'default' } @@ -330,10 +330,11 @@ describe('partition permission policy', () => { it("keeps a paired partition's answers after its last page closes and it reopens", async () => { const install = await loadInstaller() const policies = await import('./browser-session-partition-policies') - const prompts = await import('../site-settings/browser-site-permission-prompt') + const permissionMemory = + await import('../../site-settings/permissions/browser-site-permission-memory') const paired = profileFor('persist:paired-work') install(paired, { sitePermissions: 'session' }) - prompts + permissionMemory .sessionBrowserSitePermissions('persist:paired-work') .set('https://a.test', ['clipboard'], 'allow') const sess = sessionsByPartition.get('persist:paired-work') @@ -362,7 +363,7 @@ describe('partition permission policy', () => { it('gives browsing pages File System Access but keeps it from pages another machine can script', async () => { const install = await loadInstaller() const { installBrowserRoutePartitionPolicies } = - await import('../routing/sessions/browser-session-route-policies') + await import('../../routing/sessions/browser-session-route-policies') const routed = `persist:orca-browser-v1-${'a'.repeat(64)}` install(profileFor('persist:browsing-5')) void installBrowserRoutePartitionPolicies(profileFor('persist:browsing-5'), routed) diff --git a/src/main/browser/sessions/partition-policies/browser-session-partition-policies.ts b/src/main/browser/sessions/partition-policies/browser-session-partition-policies.ts new file mode 100644 index 00000000000..749645d2bc5 --- /dev/null +++ b/src/main/browser/sessions/partition-policies/browser-session-partition-policies.ts @@ -0,0 +1,126 @@ +import { session, type Session } from 'electron' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import { clearProxySessionCredentials } from '../../../network/proxy-settings' +import { + applyProxyToBrowserSession, + invalidateBrowserSessionProxyApplication +} from '../proxy/browser-session-proxy' +import { installBrowserSessionUserAgentPolicy } from '../../identity/requests/browser-session-ua' +import { getBrowserProcessUserAgentIdentity } from '../../identity/browser-process-user-agent' +import { clearBrowserWebAuthnAccessHandlers } from '../../webauthn/browser-webauthn-access' +import { + handleWillDownload, + handleDeniedWillDownload, + type BrowserPartitionDownloadPolicy +} from '../../downloads/browser-session-download-policy' +import { + denyRestrictedFileSystemAccess, + handleRestrictedFileSystemAccess, + installBrowserSessionPermissionHandlers, + type BrowserSessionPermissionOptions +} from '../../site-settings/permissions/browser-session-permission-handlers' + +const configuredPartitions = new Set() +const userAgentPolicyDisposerBySession = new WeakMap void>() + +export function retireBrowserSessionUserAgentPolicy(sess: Session): void { + const dispose = userAgentPolicyDisposerBySession.get(sess) + if (!dispose) { + return + } + userAgentPolicyDisposerBySession.delete(sess) + dispose() +} + +function configureBrowserSessionUserAgentPolicy(sess: Session, installExceptions: boolean): void { + sess.setUserAgent(getBrowserProcessUserAgentIdentity().userAgent) + if (!installExceptions) { + retireBrowserSessionUserAgentPolicy(sess) + return + } + if (userAgentPolicyDisposerBySession.has(sess)) { + return + } + userAgentPolicyDisposerBySession.set( + sess, + installBrowserSessionUserAgentPolicy(sess, (request) => + browserManager.resolveBrowserGuestRequestUserAgent(request) + ) + ) +} + +/** Drop only the installer memo; retired-session guards remain fail-closed. */ +export function forgetBrowserSessionPartitionConfiguration(partition: string): void { + configuredPartitions.delete(partition) +} +export type BrowserPartitionPermissionPolicy = 'browser' | 'deny' + +// Keep async so initialization errors reach callers through the returned promise. +export async function installBrowserSessionPartitionPolicies( + profile: BrowserSessionProfile, + options: BrowserSessionPermissionOptions & { + downloads?: BrowserPartitionDownloadPolicy + permissions?: BrowserPartitionPermissionPolicy + applyAppWideProxy?: boolean + userAgentExceptions?: boolean + } = {} +): Promise { + const { partition } = profile + const sess = session.fromPartition(partition) + configureBrowserSessionUserAgentPolicy(sess, options.userAgentExceptions !== false) + // Route partitions own a SOCKS policy that the app proxy must not overwrite. + const proxyReady = ( + options.applyAppWideProxy === false ? Promise.resolve() : applyProxyToBrowserSession(sess) + ).catch((error: unknown) => { + clearProxySessionCredentials(sess) + throw error + }) + if (configuredPartitions.has(partition)) { + return proxyReady + } + + browserManager.installCertificateRequestGuard(sess) + if (options?.permissions === 'deny') { + sess.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false)) + sess.setPermissionCheckHandler(() => false) + clearBrowserWebAuthnAccessHandlers(sess) + } else { + installBrowserSessionPermissionHandlers(sess, profile, options) + } + sess.setDisplayMediaRequestHandler((_request, callback) => { + callback({ video: undefined, audio: undefined }) + }) + sess.removeListener('will-download', handleWillDownload) + sess.removeListener('will-download', handleDeniedWillDownload) + sess.on( + 'will-download', + options?.downloads === 'deny' ? handleDeniedWillDownload : handleWillDownload + ) + sess.removeListener('file-system-access-restricted', denyRestrictedFileSystemAccess) + sess.removeListener('file-system-access-restricted', handleRestrictedFileSystemAccess) + sess.on( + 'file-system-access-restricted', + options?.permissions === 'deny' + ? denyRestrictedFileSystemAccess + : handleRestrictedFileSystemAccess + ) + configuredPartitions.add(partition) + return proxyReady +} + +export function clearBrowserSessionPartitionPolicies(partition: string, sess: Session): void { + // Electron Sessions outlive removed partitions; release their callbacks and listeners. + invalidateBrowserSessionProxyApplication(sess) + retireBrowserSessionUserAgentPolicy(sess) + configuredPartitions.delete(partition) + browserManager.removeCertificateRequestGuard(sess) + sess.removeListener('will-download', handleWillDownload) + sess.removeListener('will-download', handleDeniedWillDownload) + sess.removeListener('file-system-access-restricted', denyRestrictedFileSystemAccess) + sess.removeListener('file-system-access-restricted', handleRestrictedFileSystemAccess) + clearBrowserWebAuthnAccessHandlers(sess) + sess.setPermissionRequestHandler(null) + sess.setPermissionCheckHandler(null) + sess.setDisplayMediaRequestHandler(null) +} diff --git a/src/main/browser/sessions/browser-session-partition-proxy-install.test.ts b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts similarity index 93% rename from src/main/browser/sessions/browser-session-partition-proxy-install.test.ts rename to src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts index 5b618fd1f17..58e39a1df16 100644 --- a/src/main/browser/sessions/browser-session-partition-proxy-install.test.ts +++ b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts @@ -33,7 +33,7 @@ vi.mock('electron', () => ({ fromPartition: fromPartitionMock } })) -vi.mock('../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { installCertificateRequestGuard: vi.fn(), removeCertificateRequestGuard: vi.fn(), @@ -41,14 +41,14 @@ vi.mock('../browser-manager', () => ({ handleGuestWillDownload: vi.fn() } })) -vi.mock('../site-settings/browser-media-access', () => ({ +vi.mock('../../site-settings/permissions/browser-media-access', () => ({ hasSystemMediaAccess: vi.fn(() => false), requestSystemMediaAccess: vi.fn(async () => false) })) -vi.mock('../identity/browser-session-ua', () => ({ +vi.mock('../../identity/requests/browser-session-ua', () => ({ installBrowserSessionUserAgentPolicy: vi.fn(() => vi.fn()) })) -vi.mock('../identity/browser-process-user-agent', () => ({ +vi.mock('../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => { if (identityState.unavailable) { throw new Error('Browser process user agent is not initialized') @@ -59,7 +59,7 @@ vi.mock('../identity/browser-process-user-agent', () => ({ } } })) -vi.mock('../webauthn/browser-webauthn-access', () => ({ +vi.mock('../../webauthn/browser-webauthn-access', () => ({ allowsBrowserWebAuthnPermission: vi.fn(() => false), clearBrowserWebAuthnAccessHandlers: vi.fn(), installBrowserWebAuthnAccessHandlers: vi.fn() @@ -73,8 +73,8 @@ import { import { applyBrowserSessionProxies, setBrowserNetworkProxySettingsResolver -} from './browser-session-proxy' -import { handleElectronProxyLogin } from '../../network/electron-proxy-credentials' +} from '../proxy/browser-session-proxy' +import { handleElectronProxyLogin } from '../../../network/electron-proxy-credentials' let partitionCounter = 0 function nextProfile() { diff --git a/src/main/browser/sessions/browser-managed-session-profiles.ts b/src/main/browser/sessions/profiles/browser-managed-session-profiles.ts similarity index 85% rename from src/main/browser/sessions/browser-managed-session-profiles.ts rename to src/main/browser/sessions/profiles/browser-managed-session-profiles.ts index 2fabeb8dccc..32cf1b627d3 100644 --- a/src/main/browser/sessions/browser-managed-session-profiles.ts +++ b/src/main/browser/sessions/profiles/browser-managed-session-profiles.ts @@ -1,10 +1,10 @@ -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' import { isManagedBrowserProfileOf, managedBrowserProfileOwnerKey, type ManagedBrowserProfileOwner -} from '../../../shared/browser-profile-scope' -import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe' +} from '../../../../shared/browser-profile-scope' +import { InFlightPromiseDedupe } from '../../../../shared/in-flight-promise-dedupe' import { browserSessionRegistry } from './browser-session-registry' const creations = new InFlightPromiseDedupe() diff --git a/src/main/browser/sessions/browser-profile-owned-stores.ts b/src/main/browser/sessions/profiles/browser-profile-owned-stores.ts similarity index 58% rename from src/main/browser/sessions/browser-profile-owned-stores.ts rename to src/main/browser/sessions/profiles/browser-profile-owned-stores.ts index 3e38bcef5e4..6068b7b5a46 100644 --- a/src/main/browser/sessions/browser-profile-owned-stores.ts +++ b/src/main/browser/sessions/profiles/browser-profile-owned-stores.ts @@ -1,6 +1,6 @@ -import { forgetBrowserPasswordVault } from '../../browser-passwords/browser-password-vaults' -import { forgetBrowserSiteDisplay } from '../site-settings/browser-site-display-store' -import { forgetBrowserSitePermissions } from '../site-settings/browser-site-permission-store' +import { forgetBrowserPasswordVault } from '../../../browser-passwords/browser-password-vaults' +import { forgetBrowserSiteDisplay } from '../../site-settings/display/browser-site-display-store' +import { forgetBrowserSitePermissions } from '../../site-settings/permissions/browser-site-permission-store' /** Drops everything Orca stores per browser profile outside its Chromium partition. */ export function forgetBrowserProfileOwnedStores(profileId: string): boolean { diff --git a/src/main/browser/sessions/browser-session-meta-store.test.ts b/src/main/browser/sessions/profiles/browser-session-meta-store.test.ts similarity index 100% rename from src/main/browser/sessions/browser-session-meta-store.test.ts rename to src/main/browser/sessions/profiles/browser-session-meta-store.test.ts diff --git a/src/main/browser/sessions/browser-session-meta-store.ts b/src/main/browser/sessions/profiles/browser-session-meta-store.ts similarity index 98% rename from src/main/browser/sessions/browser-session-meta-store.ts rename to src/main/browser/sessions/profiles/browser-session-meta-store.ts index 404fb314c7e..7eff071d38d 100644 --- a/src/main/browser/sessions/browser-session-meta-store.ts +++ b/src/main/browser/sessions/profiles/browser-session-meta-store.ts @@ -1,6 +1,6 @@ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' import { dirname } from 'node:path' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' export type PendingBrowserCookieImport = | string diff --git a/src/main/browser/sessions/profiles/browser-session-persisted-profile-validation.ts b/src/main/browser/sessions/profiles/browser-session-persisted-profile-validation.ts new file mode 100644 index 00000000000..fe3b281a8e3 --- /dev/null +++ b/src/main/browser/sessions/profiles/browser-session-persisted-profile-validation.ts @@ -0,0 +1,35 @@ +import { getOrcaProfileBrowserSessionPartition } from '../../../../shared/orca-profiles' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' + +const BROWSER_SESSION_PROFILE_ID_RE = + /^[\da-f-]{8}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{4}-[\da-f-]{12}$/ + +// Persisted metadata must not add arbitrary partitions to the webview allowlist. +export function isValidPersistedBrowserSessionProfile( + profile: unknown, + activeOrcaProfileId: string +): profile is BrowserSessionProfile { + if (!profile || typeof profile !== 'object') { + return false + } + const candidate = profile as Partial + return ( + candidate.id !== 'default' && + candidate.scope !== 'default' && + typeof candidate.id === 'string' && + typeof candidate.partition === 'string' && + typeof candidate.label === 'string' && + isProfileOwnedSessionPartition(candidate.id, candidate.partition, activeOrcaProfileId) + ) +} + +function isProfileOwnedSessionPartition( + profileId: string, + partition: string, + activeOrcaProfileId: string +): boolean { + return ( + BROWSER_SESSION_PROFILE_ID_RE.test(profileId) && + partition === getOrcaProfileBrowserSessionPartition(activeOrcaProfileId, profileId) + ) +} diff --git a/src/main/browser/sessions/browser-session-profile-retirement.ts b/src/main/browser/sessions/profiles/browser-session-profile-retirement.ts similarity index 82% rename from src/main/browser/sessions/browser-session-profile-retirement.ts rename to src/main/browser/sessions/profiles/browser-session-profile-retirement.ts index df6323873f5..2af4dabd7ab 100644 --- a/src/main/browser/sessions/browser-session-profile-retirement.ts +++ b/src/main/browser/sessions/profiles/browser-session-profile-retirement.ts @@ -1,14 +1,14 @@ import { session, type Session } from 'electron' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' -import { retireProxySessionApplication } from '../../network/proxy-settings' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' +import { retireProxySessionApplication } from '../../../network/proxy-settings' import { clearBrowserSessionPartitionPolicies, forgetBrowserSessionPartitionConfiguration, retireBrowserSessionUserAgentPolicy -} from './browser-session-partition-policies' -import { invalidateBrowserSessionProxyApplication } from './browser-session-proxy' -import { cancelBrowserWebAuthnAccountRequestsForSession } from '../webauthn/browser-webauthn-account-picker' -import { detachBrowserExtensionsFromProfileSession } from '../extensions/profile-sessions/browser-extension-session-loader' +} from '../partition-policies/browser-session-partition-policies' +import { invalidateBrowserSessionProxyApplication } from '../proxy/browser-session-proxy' +import { cancelBrowserWebAuthnAccountRequestsForSession } from '../../webauthn/browser-webauthn-account-picker' +import { detachBrowserExtensionsFromProfileSession } from '../../extensions/profile-sessions/browser-extension-session-loader' export async function retireFailedBrowserSessionProfile( partition: string, diff --git a/src/main/browser/sessions/browser-session-registry-identity.persistence.test.ts b/src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts similarity index 95% rename from src/main/browser/sessions/browser-session-registry-identity.persistence.test.ts rename to src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts index afbb6c3b613..2e5bc3ae600 100644 --- a/src/main/browser/sessions/browser-session-registry-identity.persistence.test.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts @@ -31,7 +31,7 @@ describe('BrowserSessionRegistry retired identity data', () => { installModuleMocks(fsState) const { browserSessionRegistry } = await import('./browser-session-registry') - const identity = await import('../identity/browser-identity-mode-store') + const identity = await import('../../identity/mode/browser-identity-mode-store') browserSessionRegistry.initializeBrowserSessionsFromPersistedState() expect(identity.getBrowserIdentityMigrationNotice()).toEqual({ degraded: false }) diff --git a/src/main/browser/sessions/browser-session-registry-persistence-test-fixture.ts b/src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts similarity index 92% rename from src/main/browser/sessions/browser-session-registry-persistence-test-fixture.ts rename to src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts index bc72e60ce44..c5bc57018db 100644 --- a/src/main/browser/sessions/browser-session-registry-persistence-test-fixture.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts @@ -130,7 +130,7 @@ export function installModuleMocks( }) })) - vi.doMock('../browser-manager', () => ({ + vi.doMock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { notifyPermissionDenied: browserManagerNotifyPermissionDeniedMock, handleGuestWillDownload: browserManagerHandleGuestWillDownloadMock, @@ -139,24 +139,24 @@ export function installModuleMocks( resolvePagePromptTarget: vi.fn(() => null) } })) - vi.doMock('../site-settings/browser-media-access', () => ({ + vi.doMock('../../site-settings/permissions/browser-media-access', () => ({ hasSystemMediaAccess: vi.fn(() => true), requestSystemMediaAccess: requestSystemMediaAccessMock })) - vi.doMock('../identity/browser-session-ua', () => ({ + vi.doMock('../../identity/requests/browser-session-ua', () => ({ installBrowserSessionUserAgentPolicy: installBrowserSessionUserAgentPolicyMock })) - vi.doMock('../identity/browser-process-user-agent', () => ({ + vi.doMock('../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: CLEAN_USER_AGENT }) })) - vi.doMock('../../persistence/loading-store/user-data-path', () => ({ + vi.doMock('../../../persistence/loading-store/user-data-path', () => ({ getCanonicalUserDataPath: () => USER_DATA })) // Model legacy unmarked stages; real SQLite merges have separate file-backed coverage. - vi.doMock('../cookies/staging/browser-cookie-staged-import', () => ({ + vi.doMock('../../cookies/staging/browser-cookie-staged-import', () => ({ SCOPED_COOKIE_IMPORT_FORMAT: 'scoped-v1', InvalidStagedCookieImportError: class extends Error {}, isPermanentStagedCookieImportFailure: vi.fn(() => false), @@ -178,11 +178,11 @@ export function installModuleMocks( fsState.files.set(targetKey, value) } }) - vi.doMock('../../../shared/windows-retry-file-operations', async (importOriginal) => ({ + vi.doMock('../../../../shared/windows-retry-file-operations', async (importOriginal) => ({ ...(await importOriginal>()), renameFileWithWindowsRetry: renameFileWithWindowsRetryMock })) - vi.doMock('../../codex-accounts/fs-utils', () => ({ + vi.doMock('../../../codex-accounts/fs-utils', () => ({ renameFileWithWindowsRetry: renameFileWithWindowsRetryMock, writeFileAtomically: vi.fn((pathValue: string, data: string) => { const key = fsKey(pathValue) diff --git a/src/main/browser/sessions/browser-session-registry-startup-metadata.test.ts b/src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts similarity index 95% rename from src/main/browser/sessions/browser-session-registry-startup-metadata.test.ts rename to src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts index 840eeb2fe95..5d8abc958d8 100644 --- a/src/main/browser/sessions/browser-session-registry-startup-metadata.test.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { DEFAULT_LOCAL_ORCA_PROFILE_ID, getOrcaProfileBrowserSessionPartition -} from '../../../shared/orca-profiles' +} from '../../../../shared/orca-profiles' import { createFsState, installModuleMocks, @@ -37,7 +37,7 @@ describe('browser profile startup metadata reads', () => { seedMeta(fsState, { profiles, enabledExtensionIdsByProfileId }) installModuleMocks(fsState) const attachExtensions = vi.fn() - vi.doMock('../extensions/profile-sessions/browser-extension-session-loader', () => ({ + vi.doMock('../../extensions/profile-sessions/browser-extension-session-loader', () => ({ attachBrowserExtensionsToProfileSession: attachExtensions })) const { browserSessionRegistry } = await import('./browser-session-registry') diff --git a/src/main/browser/sessions/browser-session-registry.test.ts b/src/main/browser/sessions/profiles/browser-session-registry.test.ts similarity index 93% rename from src/main/browser/sessions/browser-session-registry.test.ts rename to src/main/browser/sessions/profiles/browser-session-registry.test.ts index dab6d3985df..23c38b85923 100644 --- a/src/main/browser/sessions/browser-session-registry.test.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry.test.ts @@ -31,12 +31,12 @@ vi.mock('electron', () => ({ })) // Extension loading and cleanup have their own tests (browser-extension-session-loader.test.ts). -vi.mock('../extensions/profile-sessions/browser-extension-session-loader', () => ({ +vi.mock('../../extensions/profile-sessions/browser-extension-session-loader', () => ({ attachBrowserExtensionsToProfileSession: () => {}, detachBrowserExtensionsFromProfileSession: async () => {} })) -vi.mock('../identity/browser-process-user-agent', () => ({ +vi.mock('../../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: processUserAgentMode.value, userAgent: 'Mozilla/5.0 Chrome/150.0.0.0 Safari/537.36', @@ -44,7 +44,7 @@ vi.mock('../identity/browser-process-user-agent', () => ({ }) })) -vi.mock('../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { notifyPermissionDenied: vi.fn(), handleGuestWillDownload: vi.fn(), @@ -54,7 +54,7 @@ vi.mock('../browser-manager', () => ({ } })) -vi.mock('../../browser-passwords/browser-password-vaults', () => ({ +vi.mock('../../../browser-passwords/browser-password-vaults', () => ({ forgetBrowserPasswordVault: forgetBrowserPasswordVaultMock })) @@ -68,11 +68,11 @@ import { configureBrowserSitePermissionStore, listBrowserSitePermissions, setBrowserSitePermissionDecisions -} from '../site-settings/browser-site-permission-store' -import { setBrowserNetworkProxySettingsResolver } from './browser-session-proxy' -import { handleElectronProxyLogin } from '../../network/electron-proxy-credentials' -import { applyProxySettingsToSession } from '../../network/proxy-settings' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../shared/orca-profiles' +} from '../../site-settings/permissions/browser-site-permission-store' +import { setBrowserNetworkProxySettingsResolver } from '../proxy/browser-session-proxy' +import { handleElectronProxyLogin } from '../../../network/electron-proxy-credentials' +import { applyProxySettingsToSession } from '../../../network/proxy-settings' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../../shared/orca-profiles' describe('BrowserSessionRegistry', () => { let profileDirectory: string diff --git a/src/main/browser/sessions/browser-session-registry.ts b/src/main/browser/sessions/profiles/browser-session-registry.ts similarity index 92% rename from src/main/browser/sessions/browser-session-registry.ts rename to src/main/browser/sessions/profiles/browser-session-registry.ts index 1c5ebdbfd24..3b9bde71fde 100644 --- a/src/main/browser/sessions/browser-session-registry.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry.ts @@ -1,20 +1,20 @@ import { app, session } from 'electron' import { randomUUID } from 'node:crypto' import { join } from 'node:path' -import { ORCA_BROWSER_PARTITION } from '../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import { DEFAULT_LOCAL_ORCA_PROFILE_ID, getOrcaProfileBrowserDefaultPartition, getOrcaProfileBrowserSessionPartition -} from '../../../shared/orca-profiles' +} from '../../../../shared/orca-profiles' import type { BrowserSessionProfile, BrowserSessionProfileScope -} from '../../../shared/browser-workspace-types' +} from '../../../../shared/browser-workspace-types' import { applyPendingBrowserCookieImports, clearPendingBrowserCookieImport -} from '../cookies/staging/browser-session-cookie-staging' +} from '../../cookies/staging/browser-session-cookie-staging' import { BROWSER_SESSION_META_FILE_NAME, forgetBrowserSessionProfileMeta, @@ -22,23 +22,21 @@ import { persistBrowserSessionMeta } from './browser-session-meta-store' import type { BrowserSessionMeta } from './browser-session-meta-store' -import { installBrowserSessionPartitionPolicies } from './browser-session-partition-policies' -import { - isValidPersistedBrowserSessionProfile, - inspectRetiredBrowserSessionProfileUserAgentModes -} from './browser-session-persisted-profile-validation' +import { installBrowserSessionPartitionPolicies } from '../partition-policies/browser-session-partition-policies' +import { isValidPersistedBrowserSessionProfile } from './browser-session-persisted-profile-validation' +import { inspectRetiredBrowserSessionProfileUserAgentModes } from '../../identity/mode/browser-retired-profile-identity-inspection' import { clearBrowserRoutePartitionPolicies, installBrowserRoutePartitionPolicies -} from '../routing/sessions/browser-session-route-policies' +} from '../../routing/sessions/browser-session-route-policies' import { retireDeletedBrowserSessionProfile, retireFailedBrowserSessionProfile } from './browser-session-profile-retirement' -import { getCanonicalUserDataPath } from '../../persistence/loading-store/user-data-path' -import { markBrowserIdentityMigrationNoticePending } from '../identity/browser-identity-mode-store' +import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path' +import { markBrowserIdentityMigrationNoticePending } from '../../identity/mode/browser-identity-mode-store' import { forgetBrowserProfileOwnedStores } from './browser-profile-owned-stores' -import { attachBrowserExtensionsToProfileSession } from '../extensions/profile-sessions/browser-extension-session-loader' +import { attachBrowserExtensionsToProfileSession } from '../../extensions/profile-sessions/browser-extension-session-loader' type ExtensionIdListKey = 'enabledExtensionIdsByProfileId' | 'pinnedExtensionIdsByProfileId' type ExtensionIdListUpdate = (byProfile: Record) => Record diff --git a/src/main/browser/sessions/browser-session-proxy.test.ts b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts similarity index 98% rename from src/main/browser/sessions/browser-session-proxy.test.ts rename to src/main/browser/sessions/proxy/browser-session-proxy.test.ts index 3ac81726ceb..7f5a406d072 100644 --- a/src/main/browser/sessions/browser-session-proxy.test.ts +++ b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts @@ -36,8 +36,8 @@ import { import { applyProxySettingsToSession, releaseProxySessionApplication -} from '../../network/proxy-settings' -import type { NetworkProxySettings } from '../../../shared/network-proxy' +} from '../../../network/proxy-settings' +import type { NetworkProxySettings } from '../../../../shared/network-proxy' const PROFILES = [ { diff --git a/src/main/browser/sessions/browser-session-proxy.ts b/src/main/browser/sessions/proxy/browser-session-proxy.ts similarity index 90% rename from src/main/browser/sessions/browser-session-proxy.ts rename to src/main/browser/sessions/proxy/browser-session-proxy.ts index a9b241b878a..e3b1cc6a2cf 100644 --- a/src/main/browser/sessions/browser-session-proxy.ts +++ b/src/main/browser/sessions/proxy/browser-session-proxy.ts @@ -1,14 +1,14 @@ import { session, type Session } from 'electron' -import type { BrowserSessionProfile } from '../../../shared/browser-workspace-types' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' import { applyProxySettingsToSession, awaitProxySessionApplication -} from '../../network/proxy-settings' -import type { NetworkProxySettings } from '../../../shared/network-proxy' +} from '../../../network/proxy-settings' +import type { NetworkProxySettings } from '../../../../shared/network-proxy' import { readNetworkProxySettings, setNetworkProxySettingsSource -} from '../network/execution-routes/browser-network-proxy-settings-source' +} from '../../network/execution-routes/browser-network-proxy-settings-source' let proxyPolicyGeneration = 0 // Stop stale readiness loops before a removed partition's queued proxy release. diff --git a/src/main/browser/site-settings/browser-session-permission-policy.ts b/src/main/browser/site-settings/browser-session-permission-policy.ts deleted file mode 100644 index a2b6b3f9c46..00000000000 --- a/src/main/browser/site-settings/browser-session-permission-policy.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Site prompts live in browser-site-permission-prompt.ts; other unlisted permissions are denied. -const AUTO_GRANTED_BROWSER_PERMISSIONS = new Set([ - 'fullscreen', - 'clipboard-sanitized-write', - // Chromium requests this even though Electron's permission union omits it. - 'persistent-storage', - // Chromium still requires user activation for pointer lock. - 'pointerLock', - // Match Orca's unpartitioned third-party cookie policy; request and check must agree. - // This also grants unpartitioned localStorage/IndexedDB handles, unlike ambient globals. - // Revisit if partitioning becomes configurable: Electron does not persist a STORAGE_ACCESS grant. - 'storage-access' -]) -// Top-level storage access requires Related Website Sets, which Orca does not supply. - -export function isAutoGrantedBrowserSessionPermission(permission: string): boolean { - return AUTO_GRANTED_BROWSER_PERMISSIONS.has(permission) -} diff --git a/src/main/browser/site-settings/browser-site-display-controller.test.ts b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts similarity index 98% rename from src/main/browser/site-settings/browser-site-display-controller.test.ts rename to src/main/browser/site-settings/display/browser-site-display-controller.test.ts index 5d5501fbebf..9f304231229 100644 --- a/src/main/browser/site-settings/browser-site-display-controller.test.ts +++ b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts @@ -3,11 +3,11 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' import { browserPageZoomLevelToPercent, normalizeBrowserPageZoomLevel -} from '../../../shared/browser-page-zoom' +} from '../../../../shared/browser-page-zoom' import { BrowserSiteDisplayController } from './browser-site-display-controller' import { configureBrowserSiteDisplayStore, diff --git a/src/main/browser/site-settings/browser-site-display-controller.ts b/src/main/browser/site-settings/display/browser-site-display-controller.ts similarity index 96% rename from src/main/browser/site-settings/browser-site-display-controller.ts rename to src/main/browser/site-settings/display/browser-site-display-controller.ts index f53fcd47836..2d98e61d879 100644 --- a/src/main/browser/site-settings/browser-site-display-controller.ts +++ b/src/main/browser/site-settings/display/browser-site-display-controller.ts @@ -1,21 +1,21 @@ import { acquireElectronDebugger, type ElectronDebuggerLease -} from '../cdp/debugger/electron-debugger-lease' +} from '../../cdp/debugger/electron-debugger-lease' import { getBrowserSiteDisplay, updateBrowserSiteDisplay } from './browser-site-display-store' import { browserSiteDisplayKey, type BrowserPageSiteDisplay, type BrowserSiteColorScheme -} from '../../../shared/browser-site-display' +} from '../../../../shared/browser-site-display' import { DEFAULT_BROWSER_PAGE_ZOOM_LEVEL, nextBrowserPageZoomLevel, normalizeBrowserPageZoomLevel, type BrowserPageZoomDirection -} from '../../../shared/browser-page-zoom' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import { errorMessage } from '../../../shared/error-message' +} from '../../../../shared/browser-page-zoom' +import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' +import { errorMessage } from '../../../../shared/error-message' type TrackedGuest = { guest: Electron.WebContents diff --git a/src/main/browser/site-settings/browser-site-display-store.ts b/src/main/browser/site-settings/display/browser-site-display-store.ts similarity index 86% rename from src/main/browser/site-settings/browser-site-display-store.ts rename to src/main/browser/site-settings/display/browser-site-display-store.ts index 983d774ad2c..52cdca4a405 100644 --- a/src/main/browser/site-settings/browser-site-display-store.ts +++ b/src/main/browser/site-settings/display/browser-site-display-store.ts @@ -1,9 +1,9 @@ import { isBrowserSiteColorScheme, type BrowserSiteDisplay -} from '../../../shared/browser-site-display' -import { normalizeBrowserPageZoomLevel } from '../../../shared/browser-page-zoom' -import { createBrowserProfileSiteStore } from './browser-profile-site-store' +} from '../../../../shared/browser-site-display' +import { normalizeBrowserPageZoomLevel } from '../../../../shared/browser-page-zoom' +import { createBrowserProfileSiteStore } from '../browser-profile-site-store' function parseSiteDisplay(value: unknown): BrowserSiteDisplay | null { if (!value || typeof value !== 'object') { diff --git a/src/main/browser/site-settings/browser-media-access.ts b/src/main/browser/site-settings/permissions/browser-media-access.ts similarity index 100% rename from src/main/browser/site-settings/browser-media-access.ts rename to src/main/browser/site-settings/permissions/browser-media-access.ts diff --git a/src/main/browser/site-settings/permissions/browser-session-permission-handlers.ts b/src/main/browser/site-settings/permissions/browser-session-permission-handlers.ts new file mode 100644 index 00000000000..46a12c32879 --- /dev/null +++ b/src/main/browser/site-settings/permissions/browser-session-permission-handlers.ts @@ -0,0 +1,193 @@ +import { isRemoteCliDrivenGuest } from '../../desktop-browser-bridge/remote-cli-driven-workspaces' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' +import type { Session } from 'electron' +import type { BrowserSessionProfile } from '../../../../shared/browser-workspace-types' +import { hasSystemMediaAccess, requestSystemMediaAccess } from './browser-media-access' +import { + isAutoGrantedBrowserSessionPermission, + browserSitePermissionsFor +} from './browser-session-permission-policy' +import { + answerBrowserLocalNetworkCheck, + browserSitePermissionRequestingOrigin, + decideBrowserSitePermissions, + isBrowserSitePermissionAllowed +} from './browser-site-permission-prompt' +import { + savedBrowserSitePermissions, + sessionBrowserSitePermissions +} from './browser-site-permission-memory' +import { + allowsBrowserWebAuthnPermission, + installBrowserWebAuthnAccessHandlers +} from '../../webauthn/browser-webauthn-access' + +// SSH-driven pages must not read the desktop clipboard. +function deniesRemoteCliDrivenClipboardRead(permission: string, webContentsId?: number): boolean { + return permission === 'clipboard-read' && isRemoteCliDrivenGuest(webContentsId) +} + +type RestrictedFileSystemAccessListener = ( + event: Electron.Event, + details: Electron.FileSystemAccessRestrictedDetails, + callback: (action: 'allow' | 'deny' | 'tryAgain') => void +) => void + +// Chromium waits for an answer on blocklisted system folders; without one the page hangs. +export const denyRestrictedFileSystemAccess: RestrictedFileSystemAccessListener = ( + _event, + _details, + callback +) => callback('deny') + +export const handleRestrictedFileSystemAccess: RestrictedFileSystemAccessListener = ( + _event, + details, + callback +) => { + callback('deny') + if (details.webContents) { + browserManager.notifyPermissionDenied({ + guestWebContentsId: details.webContents.id, + permission: 'fileSystem', + rawUrl: details.origin + }) + } +} + +function resolvePermissionNoticeUrl( + webContents: Electron.WebContents, + details: Electron.PermissionRequest | undefined +): string { + const requestingUrl = details?.requestingUrl + if (!requestingUrl) { + return webContents.getURL() + } + try { + return new URL(requestingUrl).origin === 'null' ? '' : requestingUrl + } catch { + return '' + } +} + +export type BrowserSessionPermissionOptions = { + /** Off where another machine can script pages and reuse their stored file handles. */ + fileSystemAccess?: boolean + /** Session-only answers are not persisted to a browser profile. */ + sitePermissions?: 'saved' | 'session' +} + +export function installBrowserSessionPermissionHandlers( + sess: Session, + profile: BrowserSessionProfile, + options: BrowserSessionPermissionOptions +): void { + const { partition } = profile + // Electron answers every File System Access grant here, overriding Chromium's own; + // the user's pick or drop is the consent, and handles a site stores keep their access. + const grantsFileSystem = options.fileSystemAccess !== false + const isAutoGranted = (permission: string): boolean => + isAutoGrantedBrowserSessionPermission(permission) || + (grantsFileSystem && permission === 'fileSystem') + const siteMemory = + options.sitePermissions === 'session' + ? sessionBrowserSitePermissions(partition) + : savedBrowserSitePermissions(profile.id) + sess.setPermissionRequestHandler((webContents, permission, callback, details) => { + if ( + permission === 'openExternal' && + browserManager.requestExternalAppLaunch( + webContents, + 'externalURL' in details ? details.externalURL : undefined, + () => resolvePermissionNoticeUrl(webContents, details) || null + ) + ) { + // Orca launches approved apps itself; deny Chromium's duplicate launch. + callback(false) + return + } + // Capture the requesting URL before async handling; opaque frames have no named site. + const rawUrl = resolvePermissionNoticeUrl(webContents, details) + const notifyDenied = (): void => + browserManager.notifyPermissionDenied({ + guestWebContentsId: webContents.id, + permission, + rawUrl + }) + if (deniesRemoteCliDrivenClipboardRead(permission, webContents.id)) { + notifyDenied() + callback(false) + return + } + const mediaRequest = 'mediaTypes' in details ? details : undefined + const sitePermissions = browserSitePermissionsFor(permission, mediaRequest?.mediaTypes) + if (!sitePermissions) { + const allowed = isAutoGranted(permission) + if (!allowed) { + notifyDenied() + } + callback(allowed) + return + } + const decide = async (): Promise => { + const allowed = await decideBrowserSitePermissions({ + requester: webContents, + frameOrigin: sitePermissions.includes('notifications') + ? browserSitePermissionRequestingOrigin(webContents, details) + : null, + memory: siteMemory, + permissions: sitePermissions + }) + if (!allowed || permission !== 'media') { + return allowed + } + // macOS also gates camera and mic per app; distinguish OS refusal from a site decision. + const granted = await requestSystemMediaAccess(mediaRequest) + if (!granted) { + notifyDenied() + } + return granted + } + void decide().then(callback, (error: unknown) => { + console.error('[permissions] Browser site permission failed:', error) + callback(false) + }) + }) + sess.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => { + if (deniesRemoteCliDrivenClipboardRead(permission, webContents?.id)) { + return false + } + if (allowsBrowserWebAuthnPermission(permission, details)) { + return true + } + const sitePermissions = browserSitePermissionsFor( + permission, + details?.mediaType ? [details.mediaType] : undefined + ) + if (sitePermissions) { + const source = { + // Service-worker checks have no WebContents; use their requesting origin. + pageUrl: webContents?.getURL() ?? requestingOrigin, + // Checks supply the frame's inherited origin. + frameOrigin: requestingOrigin + } + if (sitePermissions.includes('local-network')) { + return answerBrowserLocalNetworkCheck({ + requester: webContents, + source, + memory: siteMemory + }) + } + return ( + isBrowserSitePermissionAllowed({ + source, + memory: siteMemory, + permissions: sitePermissions + }) && + (permission !== 'media' || hasSystemMediaAccess(details?.mediaType)) + ) + } + return isAutoGranted(permission) + }) + installBrowserWebAuthnAccessHandlers(sess) +} diff --git a/src/main/browser/site-settings/permissions/browser-session-permission-policy.ts b/src/main/browser/site-settings/permissions/browser-session-permission-policy.ts new file mode 100644 index 00000000000..ea8b107292c --- /dev/null +++ b/src/main/browser/site-settings/permissions/browser-session-permission-policy.ts @@ -0,0 +1,56 @@ +import { + type BrowserSitePermission, + BROWSER_SITE_PERMISSIONS +} from '../../../../shared/browser-site-permission' + +// Site prompts live in browser-site-permission-prompt.ts; other unlisted permissions are denied. +const AUTO_GRANTED_BROWSER_PERMISSIONS = new Set([ + 'fullscreen', + 'clipboard-sanitized-write', + // Chromium requests this even though Electron's permission union omits it. + 'persistent-storage', + // Chromium still requires user activation for pointer lock. + 'pointerLock', + // Match Orca's unpartitioned third-party cookie policy; request and check must agree. + // This also grants unpartitioned localStorage/IndexedDB handles, unlike ambient globals. + // Revisit if partitioning becomes configurable: Electron does not persist a STORAGE_ACCESS grant. + 'storage-access' +]) +// Top-level storage access requires Related Website Sets, which Orca does not supply. + +export function isAutoGrantedBrowserSessionPermission(permission: string): boolean { + return AUTO_GRANTED_BROWSER_PERMISSIONS.has(permission) +} + +const SITE_PERMISSION_BY_ELECTRON_PERMISSION: Partial> = { + geolocation: 'location', + notifications: 'notifications', + 'clipboard-read': 'clipboard', + midi: 'midi', + midiSysex: 'midi', + 'window-management': 'window-management', + 'idle-detection': 'idle-detection', + // Chromium 150 asks loopback-network for 127.0.0.1; local-network-access is the legacy name. + 'local-network-access': 'local-network', + 'local-network': 'local-network', + 'loopback-network': 'local-network' +} + +const SITE_PERMISSION_BY_MEDIA_TYPE: Partial> = { + video: 'camera', + audio: 'microphone' +} + +/** Null means no site prompt applies; an empty device list must not grant media access. */ +export function browserSitePermissionsFor( + permission: string, + mediaTypes: readonly string[] | undefined +): BrowserSitePermission[] | null { + if (permission === 'media') { + const requested = new Set((mediaTypes ?? []).map((type) => SITE_PERMISSION_BY_MEDIA_TYPE[type])) + // Preserve camera-before-microphone prompt order regardless of Chromium's order. + return BROWSER_SITE_PERMISSIONS.filter((sitePermission) => requested.has(sitePermission)) + } + const sitePermission = SITE_PERMISSION_BY_ELECTRON_PERMISSION[permission] + return sitePermission ? [sitePermission] : null +} diff --git a/src/main/browser/site-settings/permissions/browser-site-permission-memory.ts b/src/main/browser/site-settings/permissions/browser-site-permission-memory.ts new file mode 100644 index 00000000000..a333478018b --- /dev/null +++ b/src/main/browser/site-settings/permissions/browser-site-permission-memory.ts @@ -0,0 +1,46 @@ +import type { + BrowserSitePermission, + BrowserSitePermissionDecision +} from '../../../../shared/browser-site-permission' +import { + getBrowserSitePermissionDecision, + setBrowserSitePermissionDecisions +} from './browser-site-permission-store' + +export type BrowserSitePermissionMemory = { + get(origin: string, permission: BrowserSitePermission): BrowserSitePermissionDecision | undefined + set( + origin: string, + permissions: readonly BrowserSitePermission[], + decision: BrowserSitePermissionDecision + ): void +} + +export function savedBrowserSitePermissions(profileId: string): BrowserSitePermissionMemory { + return { + get: (origin, permission) => getBrowserSitePermissionDecision(profileId, origin, permission), + set: (origin, permissions, decision) => + setBrowserSitePermissionDecisions(profileId, origin, permissions, decision) + } +} + +const sessionMemories = new Map() + +// Partition-scoped answers survive page closure until quit without entering local profile settings. +export function sessionBrowserSitePermissions(partition: string): BrowserSitePermissionMemory { + const existing = sessionMemories.get(partition) + if (existing) { + return existing + } + const decisions = new Map() + const memory: BrowserSitePermissionMemory = { + get: (origin, permission) => decisions.get(`${origin} ${permission}`), + set: (origin, permissions, decision) => { + for (const permission of permissions) { + decisions.set(`${origin} ${permission}`, decision) + } + } + } + sessionMemories.set(partition, memory) + return memory +} diff --git a/src/main/browser/site-settings/browser-site-permission-prompt.test.ts b/src/main/browser/site-settings/permissions/browser-site-permission-prompt.test.ts similarity index 94% rename from src/main/browser/site-settings/browser-site-permission-prompt.test.ts rename to src/main/browser/site-settings/permissions/browser-site-permission-prompt.test.ts index f7c2c0d1526..0691af0f37f 100644 --- a/src/main/browser/site-settings/browser-site-permission-prompt.test.ts +++ b/src/main/browser/site-settings/permissions/browser-site-permission-prompt.test.ts @@ -8,25 +8,27 @@ const mocks = vi.hoisted(() => ({ resolvePagePromptTarget: vi.fn() })) -vi.mock('../browser-manager', () => ({ +vi.mock('../../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { resolvePagePromptTarget: mocks.resolvePagePromptTarget } })) -import type { BrowserPagePromptRequest } from '../../../shared/browser-page-prompt' -import type { BrowserSitePermission } from '../../../shared/browser-site-permission' +import type { BrowserPagePromptRequest } from '../../../../shared/browser-page-prompt' +import type { BrowserSitePermission } from '../../../../shared/browser-site-permission' import { BROWSER_PAGE_PROMPT_TIMEOUT_MS, respondToBrowserPagePrompt -} from '../guest-lifecycle/prompts/browser-page-prompts' +} from '../../guest-lifecycle/prompts/browser-page-prompts' import { decideBrowserSitePermissions, - isBrowserSitePermissionAllowed, + isBrowserSitePermissionAllowed +} from './browser-site-permission-prompt' +import { savedBrowserSitePermissions, sessionBrowserSitePermissions, type BrowserSitePermissionMemory -} from './browser-site-permission-prompt' +} from './browser-site-permission-memory' import { configureBrowserSitePermissionStore, listBrowserSitePermissions diff --git a/src/main/browser/site-settings/browser-site-permission-prompt.ts b/src/main/browser/site-settings/permissions/browser-site-permission-prompt.ts similarity index 60% rename from src/main/browser/site-settings/browser-site-permission-prompt.ts rename to src/main/browser/site-settings/permissions/browser-site-permission-prompt.ts index 7d131e64d4d..3d6ee17287e 100644 --- a/src/main/browser/site-settings/browser-site-permission-prompt.ts +++ b/src/main/browser/site-settings/permissions/browser-site-permission-prompt.ts @@ -1,91 +1,15 @@ import { - BROWSER_SITE_PERMISSIONS, BROWSER_SITE_PERMISSION_LOCAL_FILES_ORIGIN, isBrowserSitePermissionDecision, - type BrowserSitePermission, - type BrowserSitePermissionDecision -} from '../../../shared/browser-site-permission' -import { isEligibleLocalCertificateHost } from '../../../shared/browser-url' -import { browserManager } from '../browser-manager' + type BrowserSitePermission +} from '../../../../shared/browser-site-permission' +import { isEligibleLocalCertificateHost } from '../../../../shared/browser-url' +import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserPagePromptOrigin, openBrowserPagePrompt -} from '../guest-lifecycle/prompts/browser-page-prompts' -import { - getBrowserSitePermissionDecision, - setBrowserSitePermissionDecisions -} from './browser-site-permission-store' - -const SITE_PERMISSION_BY_ELECTRON_PERMISSION: Partial> = { - geolocation: 'location', - notifications: 'notifications', - 'clipboard-read': 'clipboard', - midi: 'midi', - midiSysex: 'midi', - 'window-management': 'window-management', - 'idle-detection': 'idle-detection', - // Chromium 150 asks loopback-network for 127.0.0.1; local-network-access is the legacy name. - 'local-network-access': 'local-network', - 'local-network': 'local-network', - 'loopback-network': 'local-network' -} - -const SITE_PERMISSION_BY_MEDIA_TYPE: Partial> = { - video: 'camera', - audio: 'microphone' -} - -/** Null means no site prompt applies; an empty device list must not grant media access. */ -export function browserSitePermissionsFor( - permission: string, - mediaTypes: readonly string[] | undefined -): BrowserSitePermission[] | null { - if (permission === 'media') { - const requested = new Set((mediaTypes ?? []).map((type) => SITE_PERMISSION_BY_MEDIA_TYPE[type])) - // Preserve camera-before-microphone prompt order regardless of Chromium's order. - return BROWSER_SITE_PERMISSIONS.filter((sitePermission) => requested.has(sitePermission)) - } - const sitePermission = SITE_PERMISSION_BY_ELECTRON_PERMISSION[permission] - return sitePermission ? [sitePermission] : null -} - -export type BrowserSitePermissionMemory = { - get(origin: string, permission: BrowserSitePermission): BrowserSitePermissionDecision | undefined - set( - origin: string, - permissions: readonly BrowserSitePermission[], - decision: BrowserSitePermissionDecision - ): void -} - -export function savedBrowserSitePermissions(profileId: string): BrowserSitePermissionMemory { - return { - get: (origin, permission) => getBrowserSitePermissionDecision(profileId, origin, permission), - set: (origin, permissions, decision) => - setBrowserSitePermissionDecisions(profileId, origin, permissions, decision) - } -} - -const sessionMemories = new Map() - -// Partition-scoped answers survive page closure until quit without entering local profile settings. -export function sessionBrowserSitePermissions(partition: string): BrowserSitePermissionMemory { - const existing = sessionMemories.get(partition) - if (existing) { - return existing - } - const decisions = new Map() - const memory: BrowserSitePermissionMemory = { - get: (origin, permission) => decisions.get(`${origin} ${permission}`), - set: (origin, permissions, decision) => { - for (const permission of permissions) { - decisions.set(`${origin} ${permission}`, decision) - } - } - } - sessionMemories.set(partition, memory) - return memory -} +} from '../../guest-lifecycle/prompts/browser-page-prompts' +import type { BrowserSitePermissionMemory } from './browser-site-permission-memory' /** Returns null for opaque sites; local files share one permission origin. */ export function browserSitePermissionOrigin(rawUrl: string | null): string | null { diff --git a/src/main/browser/site-settings/browser-site-permission-store.ts b/src/main/browser/site-settings/permissions/browser-site-permission-store.ts similarity index 94% rename from src/main/browser/site-settings/browser-site-permission-store.ts rename to src/main/browser/site-settings/permissions/browser-site-permission-store.ts index 160236d90f9..2eeca975764 100644 --- a/src/main/browser/site-settings/browser-site-permission-store.ts +++ b/src/main/browser/site-settings/permissions/browser-site-permission-store.ts @@ -4,8 +4,8 @@ import { type BrowserSitePermission, type BrowserSitePermissionDecision, type BrowserSitePermissionEntry -} from '../../../shared/browser-site-permission' -import { createBrowserProfileSiteStore } from './browser-profile-site-store' +} from '../../../../shared/browser-site-permission' +import { createBrowserProfileSiteStore } from '../browser-profile-site-store' export const BROWSER_SITE_PERMISSIONS_FILE_NAME = 'browser-site-permissions.json' diff --git a/src/main/browser/webauthn/browser-webauthn-account-picker.test.ts b/src/main/browser/webauthn/browser-webauthn-account-picker.test.ts index 9285ca1134d..95dcbe9213a 100644 --- a/src/main/browser/webauthn/browser-webauthn-account-picker.test.ts +++ b/src/main/browser/webauthn/browser-webauthn-account-picker.test.ts @@ -10,7 +10,7 @@ vi.mock('electron', () => ({ webContents: { fromFrame: fromFrameMock } })) -vi.mock('../browser-manager', () => ({ +vi.mock('../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getRendererContextForGuest: getRendererContextForGuestMock } })) import { diff --git a/src/main/browser/webauthn/browser-webauthn-account-picker.ts b/src/main/browser/webauthn/browser-webauthn-account-picker.ts index 746f0c6f233..afae754772f 100644 --- a/src/main/browser/webauthn/browser-webauthn-account-picker.ts +++ b/src/main/browser/webauthn/browser-webauthn-account-picker.ts @@ -6,7 +6,7 @@ import type { BrowserWebAuthnAccountRequest, BrowserWebAuthnAccountResponse } from '../../../shared/browser-webauthn-account' -import { browserManager } from '../browser-manager' +import { browserManager } from '../guest-lifecycle/manager/browser-manager' export const BROWSER_WEBAUTHN_ACCOUNT_PICKER_TIMEOUT_MS = 60_000 diff --git a/src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts b/src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts index cf1ae2f497e..b631c2479f3 100644 --- a/src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts +++ b/src/main/browser/webauthn/browser-webauthn-profile-delete.test.ts @@ -26,7 +26,7 @@ vi.mock('electron', () => ({ vi.mock('../../browser-passwords/browser-password-vaults', () => ({ forgetBrowserPasswordVault: () => true })) -vi.mock('../browser-manager', () => ({ +vi.mock('../guest-lifecycle/manager/browser-manager', () => ({ browserManager: { getRendererContextForGuest: getRendererContextForGuestMock, handleGuestWillDownload: vi.fn(), @@ -46,7 +46,7 @@ vi.mock('../identity/browser-process-user-agent', () => ({ getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: 'Mozilla/5.0 Test' }) })) -import { browserSessionRegistry } from '../sessions/browser-session-registry' +import { browserSessionRegistry } from '../sessions/profiles/browser-session-registry' import { cancelAllBrowserWebAuthnAccountRequests, respondToBrowserWebAuthnAccountRequest diff --git a/src/main/claude/agent-view/agent-view-binding-plan.ts b/src/main/claude/agent-view/agent-view-binding-plan.ts index 8a34d0b7a0a..fc71b051c6d 100644 --- a/src/main/claude/agent-view/agent-view-binding-plan.ts +++ b/src/main/claude/agent-view/agent-view-binding-plan.ts @@ -1,5 +1,5 @@ -import type { HooksConfig } from '../../agent-hooks/installer-utils' -import { isPlainObject } from '../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' +import { isPlainObject } from '../../agent-hooks/installation/configuration/hooks-json-read' import { claudeAgentViewChord, serializeClaudeAgentViewBindings } from './agent-view-keybindings' import { CLAUDE_AGENT_VIEW_COMMAND, diff --git a/src/main/claude/agent-view/agent-view-config.ts b/src/main/claude/agent-view/agent-view-config.ts index 0845be6f5a4..e34d0f6140c 100644 --- a/src/main/claude/agent-view/agent-view-config.ts +++ b/src/main/claude/agent-view/agent-view-config.ts @@ -1,7 +1,7 @@ import { dirname, join } from 'node:path' import { readFile } from 'node:fs/promises' -import { parseHooksJsonText } from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +import { parseHooksJsonText } from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { parseClaudeAgentViewBindings, serializeClaudeAgentViewBindings diff --git a/src/main/claude/agent-view/agent-view-install.ts b/src/main/claude/agent-view/agent-view-install.ts index 191a6855a18..29190bf2665 100644 --- a/src/main/claude/agent-view/agent-view-install.ts +++ b/src/main/claude/agent-view/agent-view-install.ts @@ -11,13 +11,14 @@ import { existsSync, rmSync } from 'node:fs' import { randomUUID } from 'node:crypto' import { readFile, rm } from 'node:fs/promises' import type { SFTPWrapper } from 'ssh2' -import { writeHooksJson, type HooksConfig } from '../../agent-hooks/installer-utils' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJson, parseHooksJsonText, readHooksJsonWithRaw -} from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +} from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { claudeAgentViewChord, parseClaudeAgentViewBindings, @@ -25,10 +26,10 @@ import { } from './agent-view-keybindings' import { readHooksJsonRemote, - readTextFileRemote, - writeHooksJsonRemote, - renamePlain -} from '../../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../../agent-hooks/installation/configuration/hooks-json-remote' +import { readTextFileRemote } from '../../agent-hooks/installation/remote/hook-text-files-remote' +import { renamePlain } from '../../agent-hooks/installation/remote/hook-sftp-operations' import { CLAUDE_AGENT_VIEW_PLUGIN } from '../../../shared/claude-agent-view' // Called only after the user opts in; a surviving marker remembers deletions and edited chords. diff --git a/src/main/claude/agent-view/agent-view-keybindings.ts b/src/main/claude/agent-view/agent-view-keybindings.ts index ef312e99687..198ccfb5fbc 100644 --- a/src/main/claude/agent-view/agent-view-keybindings.ts +++ b/src/main/claude/agent-view/agent-view-keybindings.ts @@ -1,6 +1,6 @@ import { applyEdits, modify, parse, type ParseError } from 'jsonc-parser' -import type { HooksConfig } from '../../agent-hooks/installer-utils' -import { isPlainObject } from '../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' +import { isPlainObject } from '../../agent-hooks/installation/configuration/hooks-json-read' import { CLAUDE_AGENT_VIEW_COMMAND, CLAUDE_AGENT_VIEW_SHORTCUTS, diff --git a/src/main/claude/agent-view/agent-view-plugin.ts b/src/main/claude/agent-view/agent-view-plugin.ts index aa8bf84b186..23ab9ce7dae 100644 --- a/src/main/claude/agent-view/agent-view-plugin.ts +++ b/src/main/claude/agent-view/agent-view-plugin.ts @@ -1,7 +1,8 @@ import { join } from 'node:path' import { createHash } from 'node:crypto' -import { writeHooksJson, writeManagedScript } from '../../agent-hooks/installer-utils' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../../agent-hooks/installation/scripts/managed-hook-script-write' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { CLAUDE_AGENT_VIEW_PLUGIN } from '../../../shared/claude-agent-view' import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from './agent-view-mod-source' diff --git a/src/main/claude/claude-background-wake-retention.test.ts b/src/main/claude/claude-background-wake-retention.test.ts index 6fd4c15f9bf..1cb8b52af79 100644 --- a/src/main/claude/claude-background-wake-retention.test.ts +++ b/src/main/claude/claude-background-wake-retention.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentJournalSubmission } from '../../shared/agent-session/journal/agent-session-journal-types' import { structuredRunningChildWork } from '../../shared/agent-status/child-work/agent-child-work-listing' -import type { AgentHookServer } from '../agent-hooks/server' +import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { StructuredAgentSessionJournalProjections } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection' import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' diff --git a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts b/src/main/claude/claude-child-work-producer-harness.test-fixture.ts index 6ff7f13ae09..68009ae669c 100644 --- a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts +++ b/src/main/claude/claude-child-work-producer-harness.test-fixture.ts @@ -8,7 +8,7 @@ import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child import type { AgentChildWorkReconcileOutcome } from '../../shared/agent-status/child-work/agent-status-child-work-evidence-admission' import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' diff --git a/src/main/claude/claude-hook-decision-script.ts b/src/main/claude/claude-hook-decision-script.ts index 458c37b9c26..22a13224148 100644 --- a/src/main/claude/claude-hook-decision-script.ts +++ b/src/main/claude/claude-hook-decision-script.ts @@ -1,4 +1,4 @@ -import { CLAUDE_PRE_TOOL_USE_DECISION } from '../agent-hooks/agent-tool-plugin-hooks' +import { CLAUDE_PRE_TOOL_USE_DECISION } from '../agent-hooks/tool-events/agent-tool-plugin-hooks' /** * Lets Claude Code's PreToolUse hook print Orca's answer (plugins' `agent.tool.before`) instead of diff --git a/src/main/claude/claude-hook-event-versions.test.ts b/src/main/claude/claude-hook-event-versions.test.ts index 3556395417a..40e414b5188 100644 --- a/src/main/claude/claude-hook-event-versions.test.ts +++ b/src/main/claude/claude-hook-event-versions.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import { readManagedHookDetectionResult } from '../agent-hooks/managed-hook-detection-commands' +import { readManagedHookDetectionResult } from '../agent-hooks/installation/managed-hook-detection-commands' import { getClaudeManagedHookPlan } from './claude-managed-hook-events' vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) diff --git a/src/main/claude/claude-managed-hook-events.ts b/src/main/claude/claude-managed-hook-events.ts index c219e38bf7c..9894f5b4227 100644 --- a/src/main/claude/claude-managed-hook-events.ts +++ b/src/main/claude/claude-managed-hook-events.ts @@ -1,4 +1,4 @@ -import type { HookDefinition } from '../agent-hooks/installer-utils' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { claudeKnowsHookEvent, claudeKnowsStatusLine, diff --git a/src/main/claude/claude-status-line-windows.test.ts b/src/main/claude/claude-status-line-windows.test.ts index ed162281f09..95fdf8313d1 100644 --- a/src/main/claude/claude-status-line-windows.test.ts +++ b/src/main/claude/claude-status-line-windows.test.ts @@ -19,7 +19,7 @@ vi.mock('os', async (importOriginal) => { return { ...actual, homedir: homedirMock.mockImplementation(actual.homedir) } }) -import { findGitBash } from '../agent-hooks/windows-git-bash-path.test-fixture' +import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture' import { ClaudeHookService } from './hook-service' import { getManagedCommand } from './hook-settings' diff --git a/src/main/claude/claude-subagent-permission-request.test.ts b/src/main/claude/claude-subagent-permission-request.test.ts index d0d9ed4ee12..59dd7c9b91e 100644 --- a/src/main/claude/claude-subagent-permission-request.test.ts +++ b/src/main/claude/claude-subagent-permission-request.test.ts @@ -13,7 +13,7 @@ import type { } from '../../shared/agent-session/journal/agent-session-journal-types' import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' import type { AgentStatusStructuredSessionSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { StructuredAgentSessionCurrentWork } from '../native-chat/agent-session-wire/observations/structured-agent-session-current-work' diff --git a/src/main/claude/hook-script.ts b/src/main/claude/hook-script.ts index 5761f5a9bbe..a12c2812f2e 100644 --- a/src/main/claude/hook-script.ts +++ b/src/main/claude/hook-script.ts @@ -1,10 +1,10 @@ -import { buildHookProcessCapture } from '../agent-hooks/hook-process-capture' +import { buildHookProcessCapture } from '../agent-hooks/installation/scripts/hook-process-capture' import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installer-utils' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' import { buildPosixAgentHookPostCommand, buildPosixHookMetadataCacheLines -} from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixScrubSafeEnvRestoreLines, buildWindowsScrubSafeEnvRestoreLines @@ -12,17 +12,17 @@ import { import { buildPosixCursorReplayGuardLines, buildWindowsCursorReplayGuardLines -} from '../agent-hooks/cursor-replay-guard' +} from '../agent-hooks/installation/scripts/cursor-replay-guard' import { buildPosixGrokReplayGuardLines, buildWindowsGrokReplayGuardLines -} from '../agent-hooks/grok-replay-guard' +} from '../agent-hooks/installation/scripts/grok-replay-guard' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines, POSIX_HOOK_STDIN_EXEC -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildPosixClaudeDecisionModeLines, buildPosixClaudeDecisionPreludeLines, @@ -31,7 +31,7 @@ import { import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/claude-background-job-guard' +} from '../agent-hooks/installation/scripts/claude-background-job-guard' export function getManagedScript( target: 'local' | 'posix' = 'local', diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts index 0917a1e5548..f0f71b33051 100644 --- a/src/main/claude/hook-service.test.ts +++ b/src/main/claude/hook-service.test.ts @@ -17,7 +17,8 @@ vi.mock('../pty/shell-startup/git-bash', async (importOriginal) => ({ })) import type { SFTPWrapper } from 'ssh2' -import { createManagedCommandMatcher, WINDOWS_CMD_SAFE_PATH } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { WINDOWS_CMD_SAFE_PATH } from '../agent-hooks/installation/commands/windows-hook-command' import { ClaudeHookService } from './hook-service' import { CLAUDE_EVENTS } from './claude-managed-hook-events' import { getWindowsManagedLifecycleHook, OPENCLAUDE_HOOK_SETTINGS } from './hook-settings' diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index f105a43645c..87ea9b9191a 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -10,18 +10,16 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildManagedCommandHook, - readHooksJson, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' +import { buildManagedCommandHook } from '../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { getManagedScript } from './hook-script' import { removeClaudeAgentViewRemote, diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hook-settings.ts index edfc429d4b8..acd9a23acaa 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hook-settings.ts @@ -2,24 +2,26 @@ import { homedir } from 'node:os' import { basename, extname, join, win32 } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - isPlainObject, - isSafeUnicodeWindowsBatchHookPath, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, - withPreviousManagedAsync, - wrapWindowsPowerShellEncodedCommand, type HookCommandConfig, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands, + withPreviousManagedAsync +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { isSafeUnicodeWindowsBatchHookPath } from '../agent-hooks/installation/commands/windows-hook-command' +import { wrapWindowsPowerShellEncodedCommand } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' -import { getWindowsNativeHookAgent } from '../agent-hooks/windows-native-hook-executable' +import { getWindowsNativeHookAgent } from '../agent-hooks/installation/commands/windows-native-hook-executable' import { wrapRuntimeHomeHookCommand, wrapRuntimeHomePosixHookCommand -} from '../agent-hooks/runtime-home-hook-command' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/commands/runtime-home-hook-command' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import type { ClaudeManagedHookPlan } from './claude-managed-hook-events' export type ClaudeCompatibleHookSettings = { diff --git a/src/main/claude/statusline-install.ts b/src/main/claude/statusline-install.ts index bb4f6ed1b06..30d793113f2 100644 --- a/src/main/claude/statusline-install.ts +++ b/src/main/claude/statusline-install.ts @@ -1,5 +1,6 @@ import { existsSync, rmSync, writeFileSync } from 'node:fs' -import { writeManagedScript, type HooksConfig } from '../agent-hooks/installer-utils' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { getManagedStatusLineCommand, getManagedStatusLineScript } from './statusline-script' import { applyManagedStatusLine, diff --git a/src/main/claude/statusline-script.ts b/src/main/claude/statusline-script.ts index 0d392c5e47a..0d11d0e4344 100644 --- a/src/main/claude/statusline-script.ts +++ b/src/main/claude/statusline-script.ts @@ -1,14 +1,14 @@ import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/claude-background-job-guard' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { WINDOWS_HOOK_STDIN_READER } from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/claude-background-job-guard' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { WINDOWS_HOOK_STDIN_READER } from '../agent-hooks/installation/scripts/hook-stdin-contract' import { CLAUDE_STATUSLINE_MIN_POST_INTERVAL_SECONDS, CLAUDE_STATUSLINE_PATHNAME } from '../../shared/claude-statusline-rate-limits' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { getManagedCommand } from './hook-settings' const STATUSLINE_CLEANUP_LABEL = 'orca_statusline_cleanup' diff --git a/src/main/claude/theme-sync/claude-code-theme-ownership.ts b/src/main/claude/theme-sync/claude-code-theme-ownership.ts index c3c241a29fb..7c173455db6 100644 --- a/src/main/claude/theme-sync/claude-code-theme-ownership.ts +++ b/src/main/claude/theme-sync/claude-code-theme-ownership.ts @@ -2,9 +2,12 @@ import { readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' -import { isPlainObject, parseHooksJsonText } from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' -import { withManagedHookInstallLock } from '../../agent-hooks/managed-hook-install-lock' +import { + isPlainObject, + parseHooksJsonText +} from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' +import { withManagedHookInstallLock } from '../../agent-hooks/installation/locking/managed-hook-install-lock' /** What Orca replaced in one config dir's settings.json, so turning the sync off can put it back. */ export type ClaudeThemeOwnership = { diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.ts b/src/main/claude/theme-sync/claude-code-theme-sync.ts index 7b4233a2d8f..4bd63ebf552 100644 --- a/src/main/claude/theme-sync/claude-code-theme-sync.ts +++ b/src/main/claude/theme-sync/claude-code-theme-sync.ts @@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto' import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' -import { readHooksJson } from '../../agent-hooks/hooks-json-read' -import { writeHooksJson } from '../../agent-hooks/installer-utils' +import { readHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' import { defaultClaudeConfigDir } from '../claude-config-dir-pin' import { listClaudeProfileHomesAsync } from '../../claude-accounts/claude-profile-homes' import { diff --git a/src/main/claude/windows-hook-files.test.ts b/src/main/claude/windows-hook-files.test.ts index c2a6f5aa7f2..2a79cdb3fcf 100644 --- a/src/main/claude/windows-hook-files.test.ts +++ b/src/main/claude/windows-hook-files.test.ts @@ -3,8 +3,9 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import type * as osModule from 'node:os' import { join } from 'node:path' -import * as refresh from '../agent-hooks/managed-hook-script-refresh' -import { readHooksJson, writeHooksJson } from '../agent-hooks/installer-utils' +import * as refresh from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' import { ClaudeHookService } from './hook-service' import { getWindowsManagedLifecycleHook } from './hook-settings' import { getWindowsClaudeHookEntry, getWindowsClaudeHookPayloadPath } from './windows-hook-files' diff --git a/src/main/claude/windows-hook-files.ts b/src/main/claude/windows-hook-files.ts index 64291fb2f14..7b7c9620cf2 100644 --- a/src/main/claude/windows-hook-files.ts +++ b/src/main/claude/windows-hook-files.ts @@ -2,22 +2,22 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { writeManagedScript } from '../agent-hooks/installer-utils' -import { getLockedExecutableAsidePath } from '../agent-hooks/locked-executable-rename' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { getLockedExecutableAsidePath } from '../agent-hooks/installation/scripts/locked-executable-rename' import { refreshManagedScriptIfPresent, restoreManagedScript, scriptStillExists -} from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { buildWindowsHookEnvironmentGuardLines, WINDOWS_HOOK_STDIN_DRAIN_COMMAND -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { resolveBundledWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME -} from '../agent-hooks/windows-native-hook-executable' -import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../agent-hooks/claude-background-job-guard' +} from '../agent-hooks/installation/commands/windows-native-hook-executable' +import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../agent-hooks/installation/scripts/claude-background-job-guard' const PAYLOAD_FILE_NAME = 'claude-hook-impl.cmd' diff --git a/src/main/claude/windows-native-hook-registration.test.ts b/src/main/claude/windows-native-hook-registration.test.ts index 05cccc35a89..c62b41fcc4a 100644 --- a/src/main/claude/windows-native-hook-registration.test.ts +++ b/src/main/claude/windows-native-hook-registration.test.ts @@ -6,7 +6,7 @@ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import type * as NativeHookExecutableModule from '../agent-hooks/windows-native-hook-executable' +import type * as NativeHookExecutableModule from '../agent-hooks/installation/commands/windows-native-hook-executable' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) @@ -14,21 +14,26 @@ const { bundledHook } = vi.hoisted(() => { const bundledHook: { path: string | null } = { path: null } return { bundledHook } }) -vi.mock('../agent-hooks/windows-native-hook-executable', async (importOriginal) => ({ - ...(await importOriginal()), - resolveBundledWindowsNativeHookExecutable: () => bundledHook.path -})) +vi.mock( + '../agent-hooks/installation/commands/windows-native-hook-executable', + async (importOriginal) => ({ + ...(await importOriginal()), + resolveBundledWindowsNativeHookExecutable: () => bundledHook.path + }) +) import { createManagedCommandMatcher, - removeManagedCommands, - type HookCommandConfig, - type HookDefinition -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import type { + HookCommandConfig, + HookDefinition +} from '../agent-hooks/installation/configuration/hook-config-schema' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from '../agent-hooks/windows-native-hook-exe.test-fixture' +} from '../agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture' import { ClaudeHookService } from './hook-service' const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' } diff --git a/src/main/cli/appimage-generation-lease.ts b/src/main/cli/appimage-generation-lease.ts index fc705102c06..4918e1be8cd 100644 --- a/src/main/cli/appimage-generation-lease.ts +++ b/src/main/cli/appimage-generation-lease.ts @@ -4,7 +4,10 @@ import { readFileSync, unlinkSync } from 'node:fs' import { lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' import type { ProcessLivenessVerdict } from '../daemon/endpoint/identity/daemon-incarnation-evidence-types' -import { parseLinuxStartTicks, readBootIdentity } from '../agent-hooks/managed-hook-owner-identity' +import { + parseLinuxStartTicks, + readBootIdentity +} from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveAppImageGenerationOfExecutable, type AppImageGenerationLocation diff --git a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts b/src/main/codex-accounts/service-hook-trust-test-fixtures.ts index 63eeeea6137..76ca11f09a8 100644 --- a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts +++ b/src/main/codex-accounts/service-hook-trust-test-fixtures.ts @@ -8,7 +8,8 @@ export type CanonicalHookTrustFixture = { } export async function createCanonicalHookTrustFixture(): Promise { - const { MANAGED_HOOK_TIMEOUT_SECONDS } = await import('../agent-hooks/installer-utils') + const { MANAGED_HOOK_TIMEOUT_SECONDS } = + await import('../agent-hooks/installation/configuration/hook-config-schema') const [, { getCodexManagedHookInstallMaterial }] = await Promise.all([ import('../codex/hooks/installation/hook-service'), import('../codex/hooks/definitions/codex-hook-definition') diff --git a/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts b/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts index 63fc919ba0b..045623c71d9 100644 --- a/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts +++ b/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts @@ -113,7 +113,7 @@ const { upsertHookTrustEntries, upsertProjectTrustLevel } = await import('../../trust/toml/config-toml-trust') const { writeCodexTrustGrantLedgerHome, getCodexTrustGrantLedgerPath } = await import('../../trust/grants/codex-trust-grant-ledger') -await import('../../../agent-hooks/hooks-json-read') +await import('../../../agent-hooks/installation/configuration/hooks-json-read') const { MAX_AGENT_STATE_FILE_BYTES } = await import('../agent-state-file-reader') const { observeCodexSettingsBaseline } = await import('../settings/config-settings-baseline') const { snapshotCodexRuntimeSettingsBaseline } = diff --git a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts index ecc491e75a2..6f8dd5a232f 100644 --- a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts +++ b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts @@ -3,8 +3,8 @@ import { join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { parseWslUncPath } from '../../../../shared/wsl-paths' -import { withManagedHookInstallLock } from '../../../agent-hooks/managed-hook-install-lock' -import { readManagedHookHostIdentity } from '../../../agent-hooks/managed-hook-owner-identity' +import { withManagedHookInstallLock } from '../../../agent-hooks/installation/locking/managed-hook-install-lock' +import { readManagedHookHostIdentity } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveCodexCommand } from '../../../codex-cli/command' import type { ChildProcessHandle } from '@orca/process-host/process-spec' import { diff --git a/src/main/codex/hooks/definitions/codex-hook-definition.ts b/src/main/codex/hooks/definitions/codex-hook-definition.ts index 52055bbebe5..f59c2790cf1 100644 --- a/src/main/codex/hooks/definitions/codex-hook-definition.ts +++ b/src/main/codex/hooks/definitions/codex-hook-definition.ts @@ -2,13 +2,13 @@ import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument- import { join } from 'node:path' import { buildManagedCommandHook, - getSharedManagedScriptPath, MANAGED_HOOK_TIMEOUT_SECONDS, - writeHooksJson, type HookCommandConfig, type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/hook-stdin-contract' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { getSharedManagedScriptPath } from '../../../agent-hooks/installation/scripts/managed-hook-script-path' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/installation/scripts/hook-stdin-contract' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/codex/hooks/definitions/codex-hook-identity.ts b/src/main/codex/hooks/definitions/codex-hook-identity.ts index e3c3050fe18..89e3e5a7a90 100644 --- a/src/main/codex/hooks/definitions/codex-hook-identity.ts +++ b/src/main/codex/hooks/definitions/codex-hook-identity.ts @@ -1,4 +1,7 @@ -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import type { CodexEventLabel, CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { normalizeCodexHookTimeoutSec } from '../../trust/identity/codex-trust-identity' diff --git a/src/main/codex/hooks/definitions/codex-hook-script.ts b/src/main/codex/hooks/definitions/codex-hook-script.ts index 67db071b491..0ef1d101c4b 100644 --- a/src/main/codex/hooks/definitions/codex-hook-script.ts +++ b/src/main/codex/hooks/definitions/codex-hook-script.ts @@ -1,14 +1,14 @@ import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../../../agent-hooks/claude-background-job-guard' -import { buildPosixAgentHookPostCommand } from '../../../agent-hooks/hook-post-command' +} from '../../../agent-hooks/installation/scripts/claude-background-job-guard' +import { buildPosixAgentHookPostCommand } from '../../../agent-hooks/installation/scripts/hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../../../agent-hooks/hook-stdin-contract' -import { buildWindowsAgentHookCurlPostCommand } from '../../../agent-hooks/installer-utils' +} from '../../../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildWindowsAgentHookCurlPostCommand } from '../../../agent-hooks/installation/commands/windows-agent-hook-post-command' export function getManagedScript(target: 'local' | 'posix' = 'local'): string { if (target === 'local' && process.platform === 'win32') { diff --git a/src/main/codex/hooks/installation/codex-hook-local-install.ts b/src/main/codex/hooks/installation/codex-hook-local-install.ts index 12ee59f8246..3f95b4ff1ea 100644 --- a/src/main/codex/hooks/installation/codex-hook-local-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-local-install.ts @@ -2,11 +2,11 @@ import { mkdirSync } from 'node:fs' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - writeManagedScript, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { syncSystemConfigIntoManagedCodexHome } from '../../configuration/settings/codex-config-mirror' import { upsertHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { getExplicitHomeCodexHookSourcePath as getCodexExplicitHomeHookSourcePath } from '../../trust/identity/codex-trust-identity' diff --git a/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts b/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts index 344e99597c6..251bdca2462 100644 --- a/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts +++ b/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts @@ -3,8 +3,8 @@ import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-liste import { createManagedCommandMatcher, removeManagedCommands -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { syncSystemConfigIntoManagedCodexHome } from '../../configuration/settings/codex-config-mirror' import { upsertHookTrustEntries } from '../../trust/toml/config-toml-trust' import { diff --git a/src/main/codex/hooks/installation/codex-hook-remote-install.ts b/src/main/codex/hooks/installation/codex-hook-remote-install.ts index 68b2ebf5153..c726d8ac979 100644 --- a/src/main/codex/hooks/installation/codex-hook-remote-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-remote-install.ts @@ -2,17 +2,19 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import { readHooksJsonRemote, + writeHooksJsonRemote +} from '../../../agent-hooks/installation/configuration/hooks-json-remote' +import { readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../../../agent-hooks/installer-utils-remote' +} from '../../../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../../../agent-hooks/installation/scripts/managed-script-write-remote' import { assertLoadableHookTrustConfig, type CodexTrustEntry diff --git a/src/main/codex/hooks/installation/codex-hook-service-implementation.ts b/src/main/codex/hooks/installation/codex-hook-service-implementation.ts index 184572b6ad5..d5dd7450e25 100644 --- a/src/main/codex/hooks/installation/codex-hook-service-implementation.ts +++ b/src/main/codex/hooks/installation/codex-hook-service-implementation.ts @@ -3,8 +3,8 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { dedupeInFlightRun } from '../../../runtime/concurrency/in-flight-run-dedupe' -import { refreshManagedScriptIfPresent } from '../../../agent-hooks/managed-hook-script-refresh' -import { writeManagedScript } from '../../../agent-hooks/installer-utils' +import { refreshManagedScriptIfPresent } from '../../../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' import { getOrcaManagedCodexHomePath } from '../../configuration/homes/codex-home-paths' import { getManagedScriptPath } from '../definitions/codex-hook-definition' import { buildCodexHookCommand as getManagedCommand } from '../definitions/codex-hook-command-form' diff --git a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts index 191f6eec09f..d4d224e3ba2 100644 --- a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts +++ b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts @@ -2,11 +2,11 @@ import { win32 as pathWin32 } from 'node:path' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - writeManagedScript, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { upsertHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import '../../trust/identity/codex-trust-identity' import { @@ -17,8 +17,11 @@ import { writeCodexHooksJson } from '../definitions/codex-hook-definition' import { grantManagedCodexHookTrust } from '../../trust/grants/codex-hook-trust-grant' -import type { CodexManagedTrustGrantPlan } from '../../trust/grants/codex-managed-trust-grant-plan' -import { removeSelfComputedTrustBeforeGrant } from '../../trust/grants/codex-managed-trust-grant-plan' + +import { + type CodexManagedTrustGrantPlan, + removeSelfComputedTrustBeforeGrant +} from '../../trust/grants/codex-managed-trust-grant-plan' import { getManagedScript } from '../definitions/codex-hook-script' import { removeStaleWslRuntimeManagedHookTrustEntries, diff --git a/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts b/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts index e2980e1d5ba..ae8bbc6942c 100644 --- a/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts +++ b/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import '../../trust/toml/config-toml-trust' import { upsertHookTrustContent as upsertHookTrustEntriesInContent } from '../../trust/toml/config-toml-hook-trust-edit' import { setupCodexHookHomes } from './hook-service-test-harness' diff --git a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts index 54e32c9ae62..165e88a18eb 100644 --- a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts +++ b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' import { parse as parseToml } from 'smol-toml' -import type * as InstallerUtils from '../../../agent-hooks/installer-utils' +import type * as HooksJsonWrite from '../../../agent-hooks/installation/configuration/hooks-json-write' import type * as TrustDerivation from '../../trust/hooks/codex-hook-trust-derivation' import { setupCodexHookHomes } from './hook-service-test-harness' @@ -30,16 +30,19 @@ vi.mock('../../trust/hooks/codex-hook-trust-derivation', async (importOriginal) ...(await importOriginal()), ...codex })) -vi.mock('../../../agent-hooks/installer-utils', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeHooksJson: (...args: Parameters) => { - hooks.beforeHooksJsonWrite?.() - return actual.writeHooksJson(...args) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-write', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeHooksJson: (...args: Parameters) => { + hooks.beforeHooksJsonWrite?.() + return actual.writeHooksJson(...args) + } } } -}) +) import './hook-service' import { CodexHookService } from './codex-hook-service-implementation' diff --git a/src/main/codex/hooks/installation/hook-service-test-harness.ts b/src/main/codex/hooks/installation/hook-service-test-harness.ts index 496cf8ec739..ee984f10fe7 100644 --- a/src/main/codex/hooks/installation/hook-service-test-harness.ts +++ b/src/main/codex/hooks/installation/hook-service-test-harness.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, vi, type Mock } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { createManagedCommandMatcher } from '../../../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' import '../../trust/toml/config-toml-trust' import { getExplicitHomeCodexHookSourcePath as getCodexExplicitHomeHookSourcePath, diff --git a/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts b/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts index 09ef1380984..476fbbefabe 100644 --- a/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts +++ b/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts @@ -4,8 +4,8 @@ import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../../../agent-hooks/installer-utils' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/hook-stdin-contract' +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/installation/scripts/hook-stdin-contract' import { readHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { computeCodexTrustKey as computeTrustKey, diff --git a/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts b/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts index 4429a772652..cc8b82168b3 100644 --- a/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts @@ -12,7 +12,7 @@ import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as HashLookup from '../../trust/hooks/codex-hook-hash-lookup' -import type { HookDefinition } from '../../../agent-hooks/installer-utils' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' const mocks = vi.hoisted(() => { const hashes: Record = {} diff --git a/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts b/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts index fc83fcf865b..6443640bd10 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts @@ -2,12 +2,12 @@ import { existsSync, readFileSync, unlinkSync } from 'node:fs' import { join } from 'node:path' import { hookDefinitionHasManagedCommand, - removeManagedCommands, - writeHooksJson -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' -import { findManagedTomlBlocks } from '../../../agent-hooks/managed-toml-ownership' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' +import { findManagedTomlBlocks } from '../../../agent-hooks/installation/configuration/managed-toml-ownership' import type { CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { writeTomlConfigAtomically as writeConfigAtomically } from '../../configuration/toml/config-toml-atomic-write' import { diff --git a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts index 0c497633f92..4b1f1ae6cff 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts @@ -13,8 +13,8 @@ import { import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import type * as CodexCommand from '../../../codex-cli/command' import type * as TrustDerivation from '../../trust/hooks/codex-hook-trust-derivation' import type * as RealHomeInstall from './codex-real-home-hook-install' diff --git a/src/main/codex/hooks/reconciliation/codex-hook-status.ts b/src/main/codex/hooks/reconciliation/codex-hook-status.ts index f1664f3e121..06eeca77cad 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-status.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-status.ts @@ -3,8 +3,8 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' -import '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { assertLoadableHookTrustConfig, isCodexConfigTomlRefusedError, diff --git a/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts index 6ad455a589c..711eee6b1cf 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import { setupCodexHookHomes } from '../installation/hook-service-test-harness' const { getPathMock, homedirMock } = vi.hoisted(() => ({ diff --git a/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts index 353dcf39a4c..96cfaed3939 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts @@ -39,7 +39,7 @@ vi.mock('../../trust/hooks/codex-hook-trust-derivation', async (importOriginal) import { MANAGED_AGENT_HOOK_INSTALLERS, MANAGED_AGENT_HOOK_REMOVERS -} from '../../../agent-hooks/managed-agent-hook-registry' +} from '../../../agent-hooks/installation/managed-agent-hook-registry' import { _internals, startCodexHooks } from './codex-hook-reconcile' import { _internals as lookupInternals } from '../../trust/hooks/codex-hook-hash-lookup' import { diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts index 88c0ee5fc2b..bb17c069df0 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts @@ -16,10 +16,10 @@ import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' -import type * as InstallerUtils from '../../../agent-hooks/installer-utils' +import type * as HooksJsonWrite from '../../../agent-hooks/installation/configuration/hooks-json-write' import type * as RealHomeHooksJson from './codex-real-home-hooks-json' -import type { HookDefinition } from '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' const mocks = vi.hoisted(() => { const state: { beforeHooksJsonGuard: (() => void) | null; hooksJsonWrites: number } = { @@ -33,16 +33,19 @@ vi.mock('node:os', async () => ({ ...(await vi.importActual('node:os')), homedir: mocks.homedir })) -vi.mock('../../../agent-hooks/installer-utils', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeHooksJson: (...args: Parameters) => { - mocks.hooksJsonWrites += 1 - return actual.writeHooksJson(...args) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-write', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeHooksJson: (...args: Parameters) => { + mocks.hooksJsonWrites += 1 + return actual.writeHooksJson(...args) + } } } -}) +) vi.mock('./codex-real-home-hooks-json', async (importOriginal) => { const actual = await importOriginal() diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts index 8f6eef97edd..f8ad4cb850b 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts @@ -1,8 +1,8 @@ -import { - removeManagedCommands, - type HookCommandConfig, - type HookDefinition -} from '../../../agent-hooks/installer-utils' +import { removeManagedCommands } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { buildCodexManagedHook, CODEX_EVENT_LABEL, diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts index 92938886c0a..503aa57799b 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts @@ -1,11 +1,9 @@ -import { - createManagedCommandMatcher, - type HookDefinition, - writeHooksJson, - writeManagedScript -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' import { assertHooksJsonGeneration, backupRealHomeHooksJsonOnce, diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts index 35b255287c7..9f8900b1f31 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts @@ -1,11 +1,11 @@ import { createManagedCommandMatcher, - removeManagedCommands, - writeHooksJson, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' import { assertHooksJsonGeneration } from './codex-real-home-hooks-json' import { getCodexManagedScriptFileName } from '../definitions/codex-hook-identity' import { diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts index 124c95c41c4..5f6055509cb 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts @@ -1,9 +1,12 @@ import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { writeFileAtomically } from '../../../codex-accounts/fs-utils' -import type { HooksConfig } from '../../../agent-hooks/installer-utils' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' -import { isPlainObject, readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' +import { + isPlainObject, + readHooksJsonWithRaw +} from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getSystemCodexHomePath } from '../../configuration/homes/codex-home-paths' import '../../trust/toml/config-toml-trust' import { diff --git a/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts b/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts index c9faebb0f30..b11e147f7dc 100644 --- a/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts +++ b/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts @@ -1,5 +1,4 @@ -import '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { CODEX_EVENT_NAME_BY_LABEL } from '../../hooks/definitions/codex-hook-identity' import { readHookTrustBlocks, diff --git a/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts b/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts index 287c7c59cbd..7ab93794078 100644 --- a/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts +++ b/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts @@ -1,8 +1,8 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, type HooksConfig -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { readHookTrustEntries, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-hook-system-trust.ts b/src/main/codex/trust/hooks/codex-hook-system-trust.ts index 2103407e789..3b1fa79cef5 100644 --- a/src/main/codex/trust/hooks/codex-hook-system-trust.ts +++ b/src/main/codex/trust/hooks/codex-hook-system-trust.ts @@ -1,4 +1,4 @@ -import type { HookDefinition } from '../../../agent-hooks/installer-utils' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts b/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts index fd2bbb7d9c3..b136d9fb63a 100644 --- a/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts +++ b/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts @@ -2,7 +2,7 @@ import { win32 as pathWin32 } from 'node:path' import { MANAGED_HOOK_TIMEOUT_SECONDS, type HookDefinition -} from '../../../agent-hooks/installer-utils' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, removeHookTrustEntries, diff --git a/src/main/codex/trust/hooks/codex-hook-trust-memo.ts b/src/main/codex/trust/hooks/codex-hook-trust-memo.ts index 549a9c8972e..26b38cea96f 100644 --- a/src/main/codex/trust/hooks/codex-hook-trust-memo.ts +++ b/src/main/codex/trust/hooks/codex-hook-trust-memo.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { normalizeRuntimePathForComparison as codexBinaryKey } from '../../../../shared/cross-platform-path' import { writeFileAtomically } from '../../../codex-accounts/fs-utils' -import { isPlainObject } from '../../../agent-hooks/hooks-json-read' +import { isPlainObject } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getOrcaUserDataPath } from '../../configuration/homes/codex-home-paths' import type { CodexHookAnswer, CodexHookHashes } from './codex-hook-trust-derivation' import { CODEX_MANAGED_EVENT_LABELS } from '../../hooks/definitions/codex-hook-definition' diff --git a/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts b/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts index bbcc8f06357..ace0fc3c6c2 100644 --- a/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts +++ b/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' -import { removeManagedCommands, type HookDefinition } from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' +import { removeManagedCommands } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { writeLoadableHookTrustConfig, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts index e46c5b389b7..72f5d9175a6 100644 --- a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts +++ b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts @@ -3,7 +3,10 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, upsertHookTrustEntries, diff --git a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts index e922a9ecffc..a8d89b172c4 100644 --- a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts +++ b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts @@ -1,4 +1,7 @@ -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { createCodexHookTrustEntry } from '../../hooks/definitions/codex-hook-identity' import { moveHookTrustEntries, type CodexTrustEntry } from '../toml/config-toml-trust' import { computeCodexTrustKey as computeTrustKey } from '../identity/codex-trust-identity' diff --git a/src/main/codex/trust/hooks/hook-trust-promotion.ts b/src/main/codex/trust/hooks/hook-trust-promotion.ts index a03c2e2e4e2..99b38d56e01 100644 --- a/src/main/codex/trust/hooks/hook-trust-promotion.ts +++ b/src/main/codex/trust/hooks/hook-trust-promotion.ts @@ -1,11 +1,9 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' -import { - createManagedCommandMatcher, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/codex/trust/toml/config-toml-hook-trust-read.ts b/src/main/codex/trust/toml/config-toml-hook-trust-read.ts index f9b2779b8c9..fa56aacb4ff 100644 --- a/src/main/codex/trust/toml/config-toml-hook-trust-read.ts +++ b/src/main/codex/trust/toml/config-toml-hook-trust-read.ts @@ -1,5 +1,5 @@ import { parse as parseToml } from 'smol-toml' -import { isPlainObject } from '../../../agent-hooks/hooks-json-read' +import { isPlainObject } from '../../../agent-hooks/installation/configuration/hooks-json-read' import type { CodexHookTrustState } from './config-toml-trust' import { normalizeCodexHookTrustLookupKey } from '../identity/codex-trust-identity' import { findAllHookTrustBlocks } from './config-toml-hook-trust-blocks' diff --git a/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts b/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts index 6d65c82ff22..2a6fdbb1850 100644 --- a/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts +++ b/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts @@ -4,7 +4,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { SFTPWrapper } from 'ssh2' import type * as SmolToml from 'smol-toml' -import type * as InstallerUtilsRemote from '../../../agent-hooks/installer-utils-remote' +import type * as RemoteHooksJson from '../../../agent-hooks/installation/configuration/hooks-json-remote' +import type * as RemoteHookTextFiles from '../../../agent-hooks/installation/remote/hook-text-files-remote' +import type * as ManagedScriptWriteRemote from '../../../agent-hooks/installation/scripts/managed-script-write-remote' const mocks = vi.hoisted(() => { const state: { @@ -28,23 +30,46 @@ vi.mock('smol-toml', async (importOriginal) => { } }) -vi.mock('../../../agent-hooks/installer-utils-remote', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readHooksJsonRemote: async (_sftp: SFTPWrapper, path: string) => - JSON.parse(mocks.remoteFiles.get(path) ?? '{}'), - readTextFileRemote: async (_sftp: SFTPWrapper, path: string) => - mocks.remoteFiles.get(path) ?? null, - writeHooksJsonRemote: async (_sftp: SFTPWrapper, path: string, config: unknown) => { - mocks.remoteFiles.set(path, JSON.stringify(config)) - }, - writeManagedScriptRemote: async () => {}, - writeTextFileRemoteAtomic: async (_sftp: SFTPWrapper, path: string, content: string) => { - mocks.remoteFiles.set(path, content) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readHooksJsonRemote: async (_sftp: SFTPWrapper, path: string) => + JSON.parse(mocks.remoteFiles.get(path) ?? '{}'), + writeHooksJsonRemote: async (_sftp: SFTPWrapper, path: string, config: unknown) => { + mocks.remoteFiles.set(path, JSON.stringify(config)) + } } } -}) +) + +vi.mock( + '../../../agent-hooks/installation/remote/hook-text-files-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readTextFileRemote: async (_sftp: SFTPWrapper, path: string) => + mocks.remoteFiles.get(path) ?? null, + writeTextFileRemoteAtomic: async (_sftp: SFTPWrapper, path: string, content: string) => { + mocks.remoteFiles.set(path, content) + } + } + } +) + +vi.mock( + '../../../agent-hooks/installation/scripts/managed-script-write-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeManagedScriptRemote: async () => {} + } + } +) import { isCodexConfigTomlRefusedError, diff --git a/src/main/command-code/command-code-managed-script.ts b/src/main/command-code/command-code-managed-script.ts index c7da611a1b8..34a41d97fa1 100644 --- a/src/main/command-code/command-code-managed-script.ts +++ b/src/main/command-code/command-code-managed-script.ts @@ -1,10 +1,11 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installer-utils' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { ORCA_AGENT_HOOKS_DISABLED_ENV } from '../../shared/agent-hook-listener/transport/agent-hook-suppression-env' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' export type CommandCodeManagedScriptTarget = 'local' | 'posix' @@ -15,6 +16,7 @@ export function buildCommandCodeManagedScript( return [ '@echo off', 'setlocal', + `if "%${ORCA_AGENT_HOOKS_DISABLED_ENV}%"=="1" exit /b 0`, 'if "%ORCA_AGENT_HOOK_PORT%"=="" if defined ORCA_AGENT_HOOK_ENDPOINT if exist "%ORCA_AGENT_HOOK_ENDPOINT%" call "%ORCA_AGENT_HOOK_ENDPOINT%" 2>nul', 'if "%ORCA_AGENT_HOOK_TOKEN%"=="" if not "%ORCA_AGENT_HOOK_PORT%"=="" call :sourceEndpointByPort', ...buildWindowsHookEnvironmentGuardLines(), @@ -42,18 +44,22 @@ export function buildCommandCodeManagedScript( return [ '#!/bin/sh', ...buildPosixHookPayloadCapture(), + `if [ "\${${ORCA_AGENT_HOOKS_DISABLED_ENV}:-}" = 1 ]; then exit 0; fi`, ...buildPosixHookSpoolLines('command-code'), '__orca_read_ancestor_var() {', ' __orca_name="$1"', ' __orca_pid="${PPID:-}"', ' while [ -n "$__orca_pid" ] && [ "$__orca_pid" != "0" ] && [ "$__orca_pid" != "1" ]; do', - ' __orca_value=""', + ' __orca_env=""', ' if [ -r "/proc/$__orca_pid/environ" ]; then', - ' __orca_value=$(tr "\\000" "\\n" < "/proc/$__orca_pid/environ" 2>/dev/null | sed -n "s/^${__orca_name}=//p" | head -n 1)', + ' __orca_env=$(tr "\\000" "\\n" < "/proc/$__orca_pid/environ" 2>/dev/null)', ' fi', - ' if [ -z "$__orca_value" ]; then', - ' __orca_value=$(ps eww -p "$__orca_pid" -o command= 2>/dev/null | tr " " "\\n" | sed -n "s/^${__orca_name}=//p" | head -n 1)', + ' if [ -z "$__orca_env" ]; then', + ' __orca_env=$(ps eww -p "$__orca_pid" -o command= 2>/dev/null | tr " " "\\n")', ' fi', + // A scrubbed hook may recover identity, but must never cross a background launch. + ` if printf '%s\\n' "$__orca_env" | grep -qx '${ORCA_AGENT_HOOKS_DISABLED_ENV}=1'; then return 1; fi`, + ' __orca_value=$(printf "%s\\n" "$__orca_env" | sed -n "s/^${__orca_name}=//p" | head -n 1)', ' if [ -n "$__orca_value" ]; then', ' printf "%s\\n" "$__orca_value"', ' return 0', diff --git a/src/main/command-code/hook-service.test.ts b/src/main/command-code/hook-service.test.ts index 6dbfd741d5c..3127607b844 100644 --- a/src/main/command-code/hook-service.test.ts +++ b/src/main/command-code/hook-service.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { spawn } from 'node:child_process' +import { spawnProcess } from '@orca/process-host' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' import { tmpdir } from 'node:os' @@ -35,6 +36,80 @@ describe('CommandCodeHookService', () => { const itPosix = process.platform === 'win32' ? it.skip : it + itPosix( + 'stops identity recovery at a background ancestor even when the hook env is scrubbed', + async () => { + new CommandCodeHookService().install() + const requests: string[] = [] + const server = createServer((req, res) => { + let body = '' + req.setEncoding('utf8') + req.on('data', (chunk) => (body += chunk)) + req.on('end', () => { + requests.push(new URLSearchParams(body).get('paneKey') ?? '') + res.writeHead(204).end() + }) + }) + const ancestor = join(homeDir, 'ancestor.cjs') + writeFileSync( + ancestor, + `const { spawn } = require('node:child_process') +const [hook, disabled, stage] = process.argv.slice(2) +const env = { PATH: process.env.PATH, HOME: process.env.HOME } +const child = stage === 'ancestor' + ? spawn(process.execPath, [__filename, hook, disabled, 'background'], { + env: { ...env, ORCA_AGENT_HOOKS_DISABLED: disabled }, + stdio: ['ignore', 'inherit', 'inherit'] + }) + : spawn('/bin/sh', [hook], { env, stdio: ['pipe', 'inherit', 'inherit'] }) +if (stage !== 'ancestor') child.stdin.end(JSON.stringify({ hook_event_name: 'Stop' })) +child.on('error', error => { throw error }) +child.on('close', code => { process.exitCode = code ?? 1 }) +` + ) + try { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() as AddressInfo + const run = async (disabled: string) => { + const child = spawnProcess({ + program: process.execPath, + args: [ + ancestor, + join(homeDir, '.orca', 'agent-hooks', 'command-code-hook.sh'), + disabled, + 'ancestor' + ], + env: { + ...process.env, + HOME: homeDir, + ORCA_AGENT_HOOKS_DISABLED: '0', + ORCA_AGENT_HOOK_PORT: String(address.port), + ORCA_AGENT_HOOK_TOKEN: 'test-token', + ORCA_PANE_KEY: 'recovered-tab:leaf', + ORCA_TAB_ID: 'recovered-tab', + ORCA_WORKTREE_ID: 'folder-workspace', + ORCA_AGENT_LAUNCH_TOKEN: 'parent-launch' + }, + stdio: ['ignore', 'ignore', 'pipe'] + }) + let stderr = '' + child.stderr?.on('data', (chunk) => (stderr += chunk)) + const code = await new Promise((resolve, reject) => { + child.on('error', reject) + child.on('close', resolve) + }) + expect(code, stderr).toBe(0) + } + await run('0') + expect(requests).toEqual(['recovered-tab:leaf']) + await run('1') + expect(requests).toEqual(['recovered-tab:leaf']) + } finally { + await new Promise((resolve) => server.close(() => resolve())) + } + } + ) + itPosix('does not let stale endpoint files clobber recovered connection fields', async () => { new CommandCodeHookService().install() diff --git a/src/main/command-code/hook-service.ts b/src/main/command-code/hook-service.ts index 773eec52cab..ec0f628d160 100644 --- a/src/main/command-code/hook-service.ts +++ b/src/main/command-code/hook-service.ts @@ -7,22 +7,24 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildCommandCodeManagedScript } from './command-code-managed-script' const COMMAND_CODE_EVENTS = [ diff --git a/src/main/copilot/copilot-managed-hook-definitions.ts b/src/main/copilot/copilot-managed-hook-definitions.ts index 2e5d183b3d2..d1b9f419c31 100644 --- a/src/main/copilot/copilot-managed-hook-definitions.ts +++ b/src/main/copilot/copilot-managed-hook-definitions.ts @@ -1,10 +1,8 @@ -import { - wrapPosixHookCommand, - wrapWindowsHookCommand, - type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { getWindowsSystem32Path } from '../agent-hooks/windows-powershell-hook-launcher' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { getWindowsSystem32Path } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' // VS Code-compatible PascalCase names reuse the hook server's event normalization. export const COPILOT_EVENTS = [ diff --git a/src/main/copilot/copilot-managed-script.ts b/src/main/copilot/copilot-managed-script.ts index 8cd108d8409..30e6d491a9c 100644 --- a/src/main/copilot/copilot-managed-script.ts +++ b/src/main/copilot/copilot-managed-script.ts @@ -1,13 +1,11 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath -} from '../agent-hooks/installer-utils' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' export function getManagedScriptFileName(): string { return process.platform === 'win32' ? 'copilot-hook.cmd' : 'copilot-hook.sh' diff --git a/src/main/copilot/copilot-remote-hook-install.ts b/src/main/copilot/copilot-remote-hook-install.ts index ece725e0f02..2ddf1168674 100644 --- a/src/main/copilot/copilot-remote-hook-install.ts +++ b/src/main/copilot/copilot-remote-hook-install.ts @@ -2,15 +2,15 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - wrapPosixHookCommand, - type HookDefinition -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { COPILOT_EVENTS } from './copilot-managed-hook-definitions' import { getManagedScript } from './copilot-managed-script' diff --git a/src/main/copilot/hook-service.test.ts b/src/main/copilot/hook-service.test.ts index 35c5c97ef49..b4e09d6d560 100644 --- a/src/main/copilot/hook-service.test.ts +++ b/src/main/copilot/hook-service.test.ts @@ -3,7 +3,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' -import { readHooksJson, wrapWindowsHookCommand } from '../agent-hooks/installer-utils' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' import { COPILOT_EVENTS, getManagedCommand } from './copilot-managed-hook-definitions' import { CopilotHookService } from './hook-service' diff --git a/src/main/copilot/hook-service.ts b/src/main/copilot/hook-service.ts index 4ddabb67e76..5a1bba6e225 100644 --- a/src/main/copilot/hook-service.ts +++ b/src/main/copilot/hook-service.ts @@ -8,12 +8,12 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - readHooksJson, - removeManagedCommands, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { COPILOT_EVENTS, definitionHasCurrentCommand, diff --git a/src/main/cursor/hook-script.ts b/src/main/cursor/hook-script.ts index bad25d52af8..c6fdceb1cd4 100644 --- a/src/main/cursor/hook-script.ts +++ b/src/main/cursor/hook-script.ts @@ -1,19 +1,17 @@ -import { - buildWindowsAgentHookPostCommand, - wrapPosixHookCommand, - buildWindowsHookPowerShellCommand, - wrapWindowsPowerShellEncodedCommand -} from '../agent-hooks/installer-utils' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { buildWindowsHookPowerShellCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import { wrapWindowsPowerShellEncodedCommand } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildPosixGrokReplayGuardLines, buildWindowsGrokReplayGuardLines -} from '../agent-hooks/grok-replay-guard' +} from '../agent-hooks/installation/scripts/grok-replay-guard' import { quoteStartupArg } from '../../shared/agent-launch/startup/tui-agent-startup-shell' import { getCursorHookResponse, type CursorEvent } from './hook-events' diff --git a/src/main/cursor/hook-service.test.ts b/src/main/cursor/hook-service.test.ts index 9de920e7b73..9146476186b 100644 --- a/src/main/cursor/hook-service.test.ts +++ b/src/main/cursor/hook-service.test.ts @@ -6,7 +6,7 @@ import { dirname, join } from 'node:path' import { spawnSync } from 'node:child_process' import { createServer, type Server } from 'node:http' import { runProcess } from '@orca/process-host' -import { findGitBash } from '../agent-hooks/windows-git-bash-path.test-fixture' +import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture' const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() diff --git a/src/main/cursor/hook-service.ts b/src/main/cursor/hook-service.ts index e96c479db32..5264cdaae8d 100644 --- a/src/main/cursor/hook-service.ts +++ b/src/main/cursor/hook-service.ts @@ -7,20 +7,22 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandDefinition, - createManagedCommandMatcher, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { CURSOR_EVENTS } from './hook-events' import { getManagedCommand, getManagedScript, getPosixManagedCommand } from './hook-script' diff --git a/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts b/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts index b9100133950..50bd696425c 100644 --- a/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts +++ b/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts @@ -1,7 +1,7 @@ import { parseLinuxStartTicks, readBootIdentity -} from '../../../agent-hooks/managed-hook-owner-identity' +} from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { commandLineMatchesDaemon } from './daemon-pid-identity' import { startTimesWithinTolerance } from './daemon-process-start-time' import { diff --git a/src/main/daemon/endpoint/identity/daemon-ready-identity.ts b/src/main/daemon/endpoint/identity/daemon-ready-identity.ts index fc1c6238ed8..519783894d7 100644 --- a/src/main/daemon/endpoint/identity/daemon-ready-identity.ts +++ b/src/main/daemon/endpoint/identity/daemon-ready-identity.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { parseLinuxStartTicks, readBootIdentity -} from '../../../agent-hooks/managed-hook-owner-identity' +} from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' /** Self-reported identity avoids relying on launcher PIDs that may belong to wrappers. */ export type DaemonReadyIdentity = { diff --git a/src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts b/src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts index fefda820cf3..3e979f46ca4 100644 --- a/src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts +++ b/src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts @@ -3,7 +3,7 @@ import { createHash } from 'node:crypto' import { lstatSync, mkdirSync } from 'node:fs' import { posix } from 'node:path' import { unixSocketPathFits } from '../../../../shared/unix-socket-path-limit' -import { hasErrorCode } from '../identity/daemon-process-inspection' +import { errnoCodeOrUnknown } from '../../../../shared/errno-code' import { PRIVATE_DIR_MODE } from './daemon-private-file-modes' // Keep the fallback path independent of user-directory length. @@ -35,7 +35,7 @@ export function ensureOwnedPrivateDir(dir: string, uid: number): void { try { mkdirSync(dir, { mode: PRIVATE_DIR_MODE }) } catch (error) { - if (!hasErrorCode(error, 'EEXIST')) { + if (errnoCodeOrUnknown(error) !== 'EEXIST') { throw error } } diff --git a/src/main/daemon/executable-host/linux/daemon-host-image.ts b/src/main/daemon/executable-host/linux/daemon-host-image.ts index 3e74561fe5b..5639f590eb5 100644 --- a/src/main/daemon/executable-host/linux/daemon-host-image.ts +++ b/src/main/daemon/executable-host/linux/daemon-host-image.ts @@ -2,7 +2,7 @@ // Probe proc metadata rather than traversing potentially wedged FUSE mounts. import { lstatSync, readFileSync, readlinkSync } from 'node:fs' import type { ParsedDaemonPid } from '../../endpoint/identity/daemon-pid-file-parse' -import { parseLinuxStartTicks } from '../../../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { isFuseMountPoint } from './daemon-appimage-launch' import { appImageEphemeralRootOf } from '../../../../shared/appimage-ephemeral-root' diff --git a/src/main/daemon/health/daemon-liveness-report.ts b/src/main/daemon/health/daemon-liveness-report.ts index 059f03ca7be..6d8e03f6481 100644 --- a/src/main/daemon/health/daemon-liveness-report.ts +++ b/src/main/daemon/health/daemon-liveness-report.ts @@ -1,5 +1,5 @@ /** Only positive death proof earns exited; lazy respawn leaves a gap until the next terminal. */ -import { parseLinuxStartTicks } from '../../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../agent-hooks/installation/locking/managed-hook-owner-identity' import { checkDaemonHealthWithCoverage, type DaemonHealthCheck } from './daemon-health' import { inspectProcessLiveness, diff --git a/src/main/devin/hook-config-json.ts b/src/main/devin/hook-config-json.ts index 12f15ed9678..c02db189629 100644 --- a/src/main/devin/hook-config-json.ts +++ b/src/main/devin/hook-config-json.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' -import { isPlainObject, type HooksConfig } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' /** Devin documents config.json as JSONC; stock JSON.parse rejects comments. */ export function readDevinHooksConfig(configPath: string): HooksConfig | null { diff --git a/src/main/devin/hook-service.ts b/src/main/devin/hook-service.ts index 1df8db33575..117a9c552fd 100644 --- a/src/main/devin/hook-service.ts +++ b/src/main/devin/hook-service.ts @@ -3,23 +3,19 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { - readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyDevinManagedHooks, DEVIN_EVENTS, diff --git a/src/main/devin/hook-settings.ts b/src/main/devin/hook-settings.ts index d77c93e44a5..3ce2693b522 100644 --- a/src/main/devin/hook-settings.ts +++ b/src/main/devin/hook-settings.ts @@ -2,14 +2,16 @@ import { homedir } from 'node:os' import { join } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const DEVIN_SCRIPT_BASE = 'devin-hook' diff --git a/src/main/droid/hook-service.ts b/src/main/droid/hook-service.ts index ed51a9bd834..19698a6f15e 100644 --- a/src/main/droid/hook-service.ts +++ b/src/main/droid/hook-service.ts @@ -7,30 +7,32 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' // SessionStart clears prompt/tool caches on resume before the next user prompt. const DROID_EVENTS = [ diff --git a/src/main/dsh/hook-service.ts b/src/main/dsh/hook-service.ts index 3d40f6f2a6a..e36fcf4198a 100644 --- a/src/main/dsh/hook-service.ts +++ b/src/main/dsh/hook-service.ts @@ -7,23 +7,21 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixScrubSafeEnvRestoreLines, buildWindowsScrubSafeEnvRestoreLines diff --git a/src/main/dsh/hook-settings.ts b/src/main/dsh/hook-settings.ts index f4e71aad5b4..6304c05e353 100644 --- a/src/main/dsh/hook-settings.ts +++ b/src/main/dsh/hook-settings.ts @@ -2,13 +2,13 @@ import { homedir } from 'node:os' import { join, posix as pathPosix } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { readManagedHookEventsFromJson } from '../agent-hooks/managed-hooks-json-events' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { readManagedHookEventsFromJson } from '../agent-hooks/installation/configuration/managed-hooks-json-events' const DSH_SCRIPT_BASE = 'dsh-hook' diff --git a/src/main/ephemeral-vm/failed-start-cleanup.ts b/src/main/ephemeral-vm/failed-start-cleanup.ts index 878f59cebf9..7a1eaf9921d 100644 --- a/src/main/ephemeral-vm/failed-start-cleanup.ts +++ b/src/main/ephemeral-vm/failed-start-cleanup.ts @@ -1,3 +1,4 @@ +import { toEphemeralVmRuntimeRecipeSnapshot } from '../../shared/ephemeral-vm-recipe-timeouts' import { getEphemeralVmRecipeResultConnection, type EphemeralVmRecipeResult @@ -23,6 +24,7 @@ import { type FailedStart = { context: EphemeralVmRecipeContext recipeResult: EphemeralVmRecipeResult + createdAt?: number } export async function cleanupFailedEphemeralVmStart( @@ -39,8 +41,9 @@ export async function cleanupFailedEphemeralVmStart( const recovery: EphemeralVmRuntimeRecord = { id: start.context.instanceId ?? start.context.recipeId, recipeId: args.recipe.id, - recipe: args.recipe, + recipe: toEphemeralVmRuntimeRecipeSnapshot(args.recipe), ...(args.repoId ? { repoId: args.repoId } : {}), + ...(args.repoPath ? { repoPath: args.repoPath } : {}), ...(args.projectId ? { projectId: args.projectId } : {}), ...(args.workspaceId ? { workspaceId: args.workspaceId } : {}), ...(args.workspaceName ? { workspaceName: args.workspaceName } : {}), @@ -50,7 +53,7 @@ export async function cleanupFailedEphemeralVmStart( ...(args.recipe.destroyDisabled ? { cleanupDisabled: true } : {}), cleanupLastAttemptAt: now, ...toCleanupLastErrorFields(cleanupError), - createdAt: now, + createdAt: start.createdAt ?? now, updatedAt: now, recipeResult: start.recipeResult } diff --git a/src/main/ephemeral-vm/recipe-runner.test.ts b/src/main/ephemeral-vm/recipe-runner.test.ts index e74989ba620..0a6ac8abafb 100644 --- a/src/main/ephemeral-vm/recipe-runner.test.ts +++ b/src/main/ephemeral-vm/recipe-runner.test.ts @@ -8,7 +8,8 @@ import { getEphemeralVmRecipeResultProjectRoot } from '../../shared/ephemeral-vm import { runEphemeralVmRecipeCleanup, runEphemeralVmRecipeResume, - runEphemeralVmRecipeStart + runEphemeralVmRecipeStart, + runEphemeralVmRecipeSuspend } from '../../shared/ephemeral-vm-recipe-runner' import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' @@ -277,4 +278,70 @@ describe('runEphemeralVmRecipeSuspend and runEphemeralVmRecipeResume', () => { }) } }) + + it.skipIf(process.platform === 'win32')( + 'stops a suspend that outlives its timeout and reports the timeout code', + async () => { + const repoPath = makeRepo() + const suspendPath = join(repoPath, 'suspend.js') + writeFileSync(suspendPath, 'setTimeout(() => {}, 30_000)\n') + + const result = await runEphemeralVmRecipeSuspend({ + repoPath, + recipe: { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: 'unused', + suspend: nodeCommand(suspendPath), + resume: 'unused', + timeoutSeconds: { suspend: 1 } + }, + context: { recipeId: 'cloud-sandbox', repoPath, instanceId: 'orca-test-instance' }, + recipeResult: { + schemaVersion: 1, + pairingCode: makePairingCode(), + projectRoot: '/workspace/repo' + } + }) + + expect(result).toMatchObject({ + ok: false, + skipped: false, + timedOut: true, + errorCode: 'recipeTimedOut', + errorParams: { mode: 'suspend', timeout: '1s', timeoutSeconds: 1 }, + error: + 'The recipe suspend step did not finish within 1s, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.' + }) + } + ) + + it('reports a failed resume exit through the failure catalog', async () => { + const repoPath = makeRepo() + const resumePath = join(repoPath, 'resume.js') + writeFileSync(resumePath, 'process.exit(3)\n') + + const result = await runEphemeralVmRecipeResume({ + repoPath, + recipe: { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: 'unused', + resume: nodeCommand(resumePath) + }, + context: { recipeId: 'cloud-sandbox', repoPath, instanceId: 'orca-test-instance' }, + recipeResult: { + schemaVersion: 1, + pairingCode: makePairingCode(), + projectRoot: '/workspace/repo' + } + }) + + expect(result).toMatchObject({ + ok: false, + error: 'Resume exited with code 3.', + errorCode: 'resumeExited', + errorParams: { exitCode: 3 } + }) + }) }) diff --git a/src/main/ephemeral-vm/recipe-vm-wake-pairings.ts b/src/main/ephemeral-vm/recipe-vm-wake-pairings.ts index e9d5573a973..9a011c077af 100644 --- a/src/main/ephemeral-vm/recipe-vm-wake-pairings.ts +++ b/src/main/ephemeral-vm/recipe-vm-wake-pairings.ts @@ -1,15 +1,30 @@ -/** The pairing revision each recipe VM wake left its server on, by environment. A request that - * waited for a wake is held to exactly that pairing, not to whatever is current after it. */ -const wakePairings = new Map() +/** The pairing revision a recipe VM wake left its server on. A request that waited for a wake is + * held to exactly that pairing, not to whatever is current after it. */ +export type RecipeVmWake = { readonly pairingRevision: number } -export function noteRecipeVmWakePairing(environmentId: string, pairingRevision: number): void { - wakePairings.set(environmentId, pairingRevision) +const wakes = new Map() + +/** `restartedServer`: a resume that kept its pairing still restarted the server, so it reads as a + * new wake; otherwise a wake that left the pairing as it was reads as no wake. */ +export function noteRecipeVmWakePairing( + environmentId: string, + pairingRevision: number, + restartedServer = false +): void { + if (!restartedServer && wakes.get(environmentId)?.pairingRevision === pairingRevision) { + return + } + wakes.set(environmentId, { pairingRevision }) +} + +export function latestRecipeVmWake(environmentId: string): RecipeVmWake | undefined { + return wakes.get(environmentId) } export function recipeVmWakePairing(environmentId: string): number | undefined { - return wakePairings.get(environmentId) + return wakes.get(environmentId)?.pairingRevision } export function forgetRecipeVmWakePairingsForTests(): void { - wakePairings.clear() + wakes.clear() } diff --git a/src/main/ephemeral-vm/runtime-attachment.ts b/src/main/ephemeral-vm/runtime-attachment.ts index 682b2bc596a..ed39f1b6570 100644 --- a/src/main/ephemeral-vm/runtime-attachment.ts +++ b/src/main/ephemeral-vm/runtime-attachment.ts @@ -15,6 +15,10 @@ export function attachEphemeralVmRuntimeToWorkspace(args: { if (!runtime) { throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) } + if (!runtime.recipeResult) { + // Write-ahead rows have no VM details to attach; they must stay destroyable as they are. + throw new Error(`Ephemeral VM runtime never finished provisioning: ${args.runtimeId}`) + } if (['cleanup_pending', 'cleanup_failed', 'cleaned'].includes(runtime.status)) { throw new Error(`Cannot attach cleaned ephemeral VM runtime: ${args.runtimeId}`) } diff --git a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts index 8b561bb4692..957bf90b87b 100644 --- a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts +++ b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts @@ -1,82 +1,225 @@ +import { toEphemeralVmRuntimeRecipeSnapshot } from '../../shared/ephemeral-vm-recipe-timeouts' import { randomUUID } from 'node:crypto' import { assertEphemeralVmRuntimeCheckoutModeCanPersist } from '../../shared/ephemeral-vm-runtime-feature-store' import { getEphemeralVmRecipeResultConnection } from '../../shared/ephemeral-vm-recipes' import { listEphemeralVmRuntimes, removeEphemeralVmRuntime, + updateEphemeralVmRuntimeStatus, upsertEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { + ephemeralVmFailure, + ephemeralVmFailureFromError, + pickEphemeralVmFailureCode, + type EphemeralVmFailure +} from '../../shared/ephemeral-vm-failure-copy' +import type { EphemeralVmRecipeStartFailure } from '../../shared/ephemeral-vm-recipe-runner' import type { ProvisionEphemeralVmRuntimeArgs, ProvisionEphemeralVmRuntimeResult } from './runtime-service' import { cleanupFailedEphemeralVmStart } from './failed-start-cleanup' -export type EphemeralVmCompatibilityPersistence = { +export type EphemeralVmWriteAhead = { instanceId: string createdAt: number + /** Set once the create command's process started; before that no VM can exist. */ + launched: boolean } -export function prepareEphemeralVmCompatibilityPersistence( +// Creates owned by this process; any other `provisioning` record was orphaned by a crash or quit. +const liveProvisionInstanceIds = new Set() + +export function isEphemeralVmProvisionLive(instanceId: string): boolean { + return liveProvisionInstanceIds.has(instanceId) +} + +/** Persist the `provisioning` record before spawning create so a crash cannot leak an untracked VM. */ +export function beginEphemeralVmProvisioning( args: ProvisionEphemeralVmRuntimeArgs -): EphemeralVmCompatibilityPersistence | null { - if (!args.recipe.checkoutMode) { - return null - } - listEphemeralVmRuntimes(args.userDataPath) - const compatibility = { +): EphemeralVmWriteAhead { + const writeAhead: EphemeralVmWriteAhead = { instanceId: `orca-${randomUUID()}`, - createdAt: args.now ?? Date.now() + createdAt: args.now ?? Date.now(), + launched: false } - assertEphemeralVmRuntimeCheckoutModeCanPersist(args.userDataPath, { - id: compatibility.instanceId, - recipeId: args.recipe.id, - createdAt: compatibility.createdAt, - checkoutMode: args.recipe.checkoutMode + if (args.recipe.checkoutMode) { + assertEphemeralVmRuntimeCheckoutModeCanPersist(args.userDataPath, { + id: writeAhead.instanceId, + recipeId: args.recipe.id, + createdAt: writeAhead.createdAt, + checkoutMode: args.recipe.checkoutMode + }) + } + upsertEphemeralVmRuntime(args.userDataPath, { + ...baseRuntimeRecord(args, writeAhead), + status: 'provisioning', + updatedAt: writeAhead.createdAt }) - return compatibility + liveProvisionInstanceIds.add(writeAhead.instanceId) + return writeAhead +} + +export function endEphemeralVmProvisioning( + args: ProvisionEphemeralVmRuntimeArgs, + writeAhead: EphemeralVmWriteAhead, + error?: unknown +): void { + liveProvisionInstanceIds.delete(writeAhead.instanceId) + if (error === undefined) { + return + } + try { + const record = findRuntime(args.userDataPath, writeAhead.instanceId) + if (record?.status === 'provisioning' && !writeAhead.launched) { + removeEphemeralVmRuntime(args.userDataPath, record.id) + } else if (record?.status === 'provisioning') { + markProvisionFailed(args.userDataPath, record.id, ephemeralVmFailureFromError(error)) + } + } catch { + // Why: surface the original provisioning error; startup reconciliation retries the flip. + } +} + +export async function persistFailedEphemeralVmStart( + args: ProvisionEphemeralVmRuntimeArgs, + writeAhead: EphemeralVmWriteAhead, + start: EphemeralVmRecipeStartFailure +): Promise { + if (!start.recipeResult && !writeAhead.launched) { + // Why: create never ran (validation failed or it was cancelled first), so no VM can exist. + removeIfPresent(args.userDataPath, writeAhead.instanceId) + return + } + if (!start.recipeResult) { + // Why: create may have allocated resources before failing; keep the row so the user can destroy it. + markProvisionFailed(args.userDataPath, writeAhead.instanceId, { + error: start.error, + ...pickEphemeralVmFailureCode(start) + }) + return + } + const cleaned = await cleanupFailedEphemeralVmStart(args, { + context: start.context, + recipeResult: start.recipeResult, + createdAt: writeAhead.createdAt + }) + if (cleaned) { + removeIfPresent(args.userDataPath, writeAhead.instanceId) + } } export async function persistProvisionedEphemeralVmRuntime( args: ProvisionEphemeralVmRuntimeArgs, start: Extract['start'], - compatibility: EphemeralVmCompatibilityPersistence | null + writeAhead: EphemeralVmWriteAhead ): Promise { - const now = compatibility?.createdAt ?? args.now ?? Date.now() const connection = getEphemeralVmRecipeResultConnection(start.result) try { return upsertEphemeralVmRuntime(args.userDataPath, { - id: start.context.instanceId ?? start.context.recipeId, - recipeId: args.recipe.id, - recipe: args.recipe, - ...(args.repoId ? { repoId: args.repoId } : {}), - ...(args.projectId ? { projectId: args.projectId } : {}), - ...(args.workspaceId ? { workspaceId: args.workspaceId } : {}), - ...(args.workspaceName ? { workspaceName: args.workspaceName } : {}), + ...baseRuntimeRecord(args, writeAhead), status: 'running', connectionMode: connection.type, - cleanupStatus: args.recipe.destroyDisabled ? 'disabled' : 'not_started', - ...(args.recipe.destroyDisabled ? { cleanupDisabled: true } : {}), - createdAt: now, - updatedAt: now, + updatedAt: args.now ?? Date.now(), recipeResult: start.result }) } catch (error) { - if (compatibility) { + if (args.recipe.checkoutMode) { const cleaned = await cleanupFailedEphemeralVmStart(args, { context: start.context, - recipeResult: start.result + recipeResult: start.result, + createdAt: writeAhead.createdAt }) - if ( - cleaned && - listEphemeralVmRuntimes(args.userDataPath).some( - (runtime) => runtime.id === compatibility.instanceId - ) - ) { - removeEphemeralVmRuntime(args.userDataPath, compatibility.instanceId) + if (cleaned) { + removeIfPresent(args.userDataPath, writeAhead.instanceId) } } throw error } } + +/** Flip `provisioning` records with no live create in this process to `failed` so Settings offers Destroy. */ +export function reconcileInterruptedEphemeralVmProvisions( + userDataPath: string, + now = Date.now() +): EphemeralVmRuntimeRecord[] { + return listEphemeralVmRuntimes(userDataPath) + .filter( + (runtime) => runtime.status === 'provisioning' && !isEphemeralVmProvisionLive(runtime.id) + ) + .map((runtime) => + markProvisionFailed(userDataPath, runtime.id, ephemeralVmFailure('provisionInterrupted'), now) + ) +} + +export function reconcileInterruptedEphemeralVmProvisionsOnStartup(userDataPath: string): void { + try { + reconcileInterruptedEphemeralVmProvisions(userDataPath) + } catch (error) { + console.warn('[ephemeral-vm] Could not reconcile interrupted provisions:', error) + } +} + +/** Tracked VMs must go through Destroy; only result-less write-ahead rows can be dropped by hand. */ +export function forgetInterruptedEphemeralVmProvision( + userDataPath: string, + runtimeId: string +): void { + const runtime = findRuntime(userDataPath, runtimeId) + if (!runtime) { + return + } + if ( + runtime.recipeResult || + runtime.status === 'cleanup_pending' || + (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) + ) { + throw new Error(`Ephemeral VM runtime must be destroyed, not removed: ${runtimeId}`) + } + removeEphemeralVmRuntime(userDataPath, runtimeId) +} + +function markProvisionFailed( + userDataPath: string, + runtimeId: string, + failure: EphemeralVmFailure, + now = Date.now() +): EphemeralVmRuntimeRecord { + // cleanupLastError is the row's displayed error, which older builds also render. + return updateEphemeralVmRuntimeStatus(userDataPath, runtimeId, { + status: 'failed', + cleanupLastError: failure, + updatedAt: now + }) +} + +function baseRuntimeRecord( + args: ProvisionEphemeralVmRuntimeArgs, + writeAhead: EphemeralVmWriteAhead +): Omit { + return { + id: writeAhead.instanceId, + recipeId: args.recipe.id, + recipe: toEphemeralVmRuntimeRecipeSnapshot(args.recipe), + ...(args.repoId ? { repoId: args.repoId } : {}), + ...(args.repoPath ? { repoPath: args.repoPath } : {}), + ...(args.projectId ? { projectId: args.projectId } : {}), + ...(args.workspaceId ? { workspaceId: args.workspaceId } : {}), + ...(args.workspaceName ? { workspaceName: args.workspaceName } : {}), + cleanupStatus: args.recipe.destroyDisabled ? 'disabled' : 'not_started', + ...(args.recipe.destroyDisabled ? { cleanupDisabled: true } : {}), + createdAt: writeAhead.createdAt + } +} + +function findRuntime(userDataPath: string, id: string): EphemeralVmRuntimeRecord | undefined { + return listEphemeralVmRuntimes(userDataPath).find((runtime) => runtime.id === id) +} + +function removeIfPresent(userDataPath: string, id: string): void { + if (findRuntime(userDataPath, id)) { + removeEphemeralVmRuntime(userDataPath, id) + } +} diff --git a/src/main/ephemeral-vm/runtime-recipe-timeouts.test.ts b/src/main/ephemeral-vm/runtime-recipe-timeouts.test.ts new file mode 100644 index 00000000000..994ff5d5bb2 --- /dev/null +++ b/src/main/ephemeral-vm/runtime-recipe-timeouts.test.ts @@ -0,0 +1,111 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { getEphemeralVmRuntimeStorePath } from '../../shared/ephemeral-vm-runtime-store' +import { RollbackEphemeralVmRuntimeStoreSchema } from '../../shared/ephemeral-vm-runtimes' +import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import type { Store } from '../persistence/loading-store/store' +import { provisionEphemeralVmRuntime } from './runtime-service' +import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' + +const hooks = vi.hoisted(() => { + const recipes: OrcaVmRecipe[] = [] + return { recipes } +}) +vi.mock('../workspace-hooks/hooks', () => ({ + loadHooks: () => ({ scripts: {}, environmentRecipes: hooks.recipes }) +})) + +const tempDirs: string[] = [] +afterEach(() => { + for (const root of tempDirs.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +function makeDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)) + tempDirs.push(dir) + return dir +} + +describe('recipe timeoutSeconds and persisted runtimes', () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + beforeEach(() => { + // Isolate from platform ACL behavior, which secure-file tests cover. + Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) + }) + afterEach(() => { + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + }) + + it('persists a runtime whose recipe sets timeoutSeconds in a shape older builds still read', async () => { + const userDataPath = makeDir('orca-vm-timeouts-user-data-') + const repoPath = makeDir('orca-vm-timeouts-repo-') + const startPath = join(repoPath, 'start.js') + const pairingCode = encodePairingOffer({ + v: PAIRING_OFFER_VERSION, + endpoint: 'wss://sandbox.example.com', + deviceToken: 'token', + publicKeyB64: 'public-key' + }) + writeFileSync( + startPath, + `console.log(JSON.stringify({ schemaVersion: 1, pairingCode: ${JSON.stringify(pairingCode)}, projectRoot: '/workspace/repo' }))\n` + ) + const recipe: OrcaVmRecipe = { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: `"${process.execPath}" "${startPath}"`, + destroy: './destroy.sh', + timeoutSeconds: { create: 1_800, destroy: 120 } + } + + const provisioned = await provisionEphemeralVmRuntime({ + userDataPath, + repoPath, + recipe, + repoId: 'repo-1', + now: 1_000 + }) + + expect(provisioned.ok).toBe(true) + if (!provisioned.ok) { + return + } + expect(provisioned.runtime.recipe).not.toHaveProperty('timeoutSeconds') + // The strict recipe schema is shared with older builds, so the file must parse without the new field. + const onDisk = JSON.parse(readFileSync(getEphemeralVmRuntimeStorePath(userDataPath), 'utf8')) + expect(RollbackEphemeralVmRuntimeStoreSchema.safeParse(onDisk).success).toBe(true) + + // Later lifecycle calls take the repo's current limit on top of the snapshotted commands. + hooks.recipes = [ + { ...recipe, destroy: './changed-destroy.sh', timeoutSeconds: { destroy: 60 } } + ] + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: getRuntimeRecipeContext only reads getRepo from the store. + const store = { + getRepo: () => ({ id: 'repo-1', path: repoPath, kind: 'git' }) + } as unknown as Store + const context = getRuntimeRecipeContext(store, userDataPath, provisioned.runtime.id) + expect(context.recipe).toMatchObject({ + destroy: './destroy.sh', + timeoutSeconds: { destroy: 60 } + }) + + // A different recipe that later took the same id does not impose its limits. + hooks.recipes = [{ ...recipe, create: './other-create.sh', timeoutSeconds: { destroy: 5 } }] + expect( + getRuntimeRecipeContext(store, userDataPath, provisioned.runtime.id).recipe + ).not.toHaveProperty('timeoutSeconds') + + hooks.recipes = [] + expect( + getRuntimeRecipeContext(store, userDataPath, provisioned.runtime.id).recipe + ).not.toHaveProperty('timeoutSeconds') + }) +}) diff --git a/src/main/ephemeral-vm/runtime-resume-pairing.test.ts b/src/main/ephemeral-vm/runtime-resume-pairing.test.ts new file mode 100644 index 00000000000..8fe94cfd5d8 --- /dev/null +++ b/src/main/ephemeral-vm/runtime-resume-pairing.test.ts @@ -0,0 +1,214 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairing/paired-runtime-connection' +import { + addEnvironmentFromPairingCode, + listEnvironments, + resolveEnvironmentPairingOffer, + updateEnvironmentFromPairingCode +} from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error' +import { DeviceRegistry } from '../runtime/rpc/server/pairing/device-registry' +import { applyResumedRuntimePairing } from './runtime-resume-pairing' + +const hostKey = Buffer.alloc(32, 7).toString('base64') +const rotatedHostKey = Buffer.alloc(32, 9).toString('base64') +const unpaddedHostKey = Buffer.alloc(32, 7).toString('base64url') + +/** Stands in for the VM's server: its state dir survives suspend, and each boot prints a startup offer. */ +function bootVm(serverDataPath: string, endpoint: string, publicKeyB64 = hostKey): string { + const offer = new DeviceRegistry(serverDataPath).getOrCreatePendingDevice('CLI', 'runtime') + return encodePairingOffer({ v: 2, endpoint, deviceToken: offer.token, publicKeyB64 }) +} + +/** The server's answer to a saved token, as the desktop's connection would see it. */ +function serverAuth(serverDataPath: string) { + return async (connection: PairedRuntimeConnection): Promise => { + if (!new DeviceRegistry(serverDataPath).validateToken(connection.credential.deviceToken)) { + throw new RemoteRuntimeClientError('unauthorized', 'rejected', { + pairingStage: 'access-grant' + }) + } + } +} + +/** The desktop connecting with its saved token, which marks that device row as used. */ +function connect(serverDataPath: string, desktopDataPath: string, environmentId: string): void { + const registry = new DeviceRegistry(serverDataPath) + const { deviceToken } = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + const device = registry.validateToken(deviceToken) + if (!device) { + throw new Error('saved device token was rejected') + } + registry.updateLastSeen(device.deviceId) + registry.flushPendingLastSeen() +} + +describe('resuming a recipe VM server', () => { + let desktopDataPath: string + let serverDataPath: string + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + + beforeEach(() => { + // Why: store contents are under test; secure-file tests cover Windows ACLs. + Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) + desktopDataPath = mkdtempSync(join(tmpdir(), 'orca-resume-desktop-')) + serverDataPath = mkdtempSync(join(tmpdir(), 'orca-resume-server-')) + }) + afterEach(() => { + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + rmSync(desktopDataPath, { recursive: true, force: true }) + rmSync(serverDataPath, { recursive: true, force: true }) + }) + + function provision(): string { + const environment = addEnvironmentFromPairingCode(desktopDataPath, { + name: 'Cloud workspace', + pairingCode: bootVm(serverDataPath, 'wss://vm-0.example/runtime'), + source: 'ephemeral-vm' + }) + connect(serverDataPath, desktopDataPath, environment.id) + return environment.id + } + + function resume(environmentId: string, pairingCode: string, invalidateTransport = vi.fn()) { + return applyResumedRuntimePairing({ + userDataPath: desktopDataPath, + environmentId, + pairingCode, + invalidateTransport, + probeSavedPairing: serverAuth(serverDataPath) + }) + } + + it('keeps the device rows flat and the original token across 20 suspend/resume cycles', async () => { + const environmentId = provision() + const original = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + const before = listEnvironments(desktopDataPath)[0]! + const invalidateTransport = vi.fn() + + for (let cycle = 1; cycle <= 20; cycle++) { + const endpoint = `wss://vm-${cycle}.example/runtime` + const outcome = await resume( + environmentId, + bootVm(serverDataPath, endpoint), + invalidateTransport + ) + expect(outcome).toMatchObject({ reusedPairing: true, endpointChanged: true }) + expect(invalidateTransport).toHaveBeenCalledTimes(cycle) + connect(serverDataPath, desktopDataPath, environmentId) + expect(resolveEnvironmentPairingOffer(desktopDataPath, environmentId)).toMatchObject({ + endpoint, + deviceToken: original.deviceToken + }) + } + + // The paired device plus the one unused startup offer each boot re-advertises. + expect(new DeviceRegistry(serverDataPath).listDevices()).toHaveLength(2) + expect(listEnvironments(desktopDataPath)).toHaveLength(1) + expect(listEnvironments(desktopDataPath)[0]!.pairingRevision).toBe(before.pairingRevision) + }) + + it('grows one device row per resume when every resume re-pairs (previous behaviour)', () => { + const environmentId = provision() + for (let cycle = 1; cycle <= 20; cycle++) { + updateEnvironmentFromPairingCode(desktopDataPath, environmentId, { + pairingCode: bootVm(serverDataPath, `wss://vm-${cycle}.example/runtime`) + }) + connect(serverDataPath, desktopDataPath, environmentId) + } + expect(new DeviceRegistry(serverDataPath).listDevices()).toHaveLength(21) + }) + + it('leaves the store untouched but still drops the transport when nothing moved', async () => { + const environmentId = provision() + const before = listEnvironments(desktopDataPath)[0]! + const invalidateTransport = vi.fn() + const outcome = await resume( + environmentId, + bootVm(serverDataPath, 'wss://vm-0.example/runtime'), + invalidateTransport + ) + expect(outcome).toMatchObject({ reusedPairing: true, endpointChanged: false }) + expect(listEnvironments(desktopDataPath)[0]).toEqual(before) + expect(invalidateTransport).toHaveBeenCalledWith(environmentId) + }) + + it('re-pairs from the fresh code when the host key changed, without asking the server', async () => { + const environmentId = provision() + const original = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + rmSync(serverDataPath, { recursive: true, force: true }) + serverDataPath = mkdtempSync(join(tmpdir(), 'orca-resume-server-')) + const probeSavedPairing = vi.fn() + + const outcome = await applyResumedRuntimePairing({ + userDataPath: desktopDataPath, + environmentId, + pairingCode: bootVm(serverDataPath, 'wss://rebuilt.example/runtime', rotatedHostKey), + invalidateTransport: vi.fn(), + probeSavedPairing + }) + + expect(outcome.reusedPairing).toBe(false) + expect(probeSavedPairing).not.toHaveBeenCalled() + const next = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + expect(next.deviceToken).not.toBe(original.deviceToken) + expect(next.publicKeyB64).toBe(rotatedHostKey) + connect(serverDataPath, desktopDataPath, environmentId) + expect(listEnvironments(desktopDataPath)).toHaveLength(1) + }) + + it('re-pairs from the fresh code when the server kept its key but lost the saved device', async () => { + const environmentId = provision() + const savedKeySpelling = resolveEnvironmentPairingOffer( + desktopDataPath, + environmentId + ).publicKeyB64 + const original = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + const before = listEnvironments(desktopDataPath)[0]! + rmSync(serverDataPath, { recursive: true, force: true }) + serverDataPath = mkdtempSync(join(tmpdir(), 'orca-resume-server-')) + const invalidateTransport = vi.fn() + + const outcome = await resume( + environmentId, + // The same key, printed unpadded and URL-safe. + bootVm(serverDataPath, 'wss://vm-1.example/runtime', unpaddedHostKey), + invalidateTransport + ) + + expect(outcome.reusedPairing).toBe(false) + const next = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + expect(next.deviceToken).not.toBe(original.deviceToken) + expect(next.publicKeyB64).toBe(savedKeySpelling) + expect(listEnvironments(desktopDataPath)[0]!.pairingRevision).not.toBe(before.pairingRevision) + // Only once, after the probe: reconnecting earlier would dial with the rejected token. + expect(invalidateTransport).toHaveBeenCalledTimes(1) + connect(serverDataPath, desktopDataPath, environmentId) + }) + + it('keeps the saved pairing when the server cannot be reached to check it', async () => { + const environmentId = provision() + const original = resolveEnvironmentPairingOffer(desktopDataPath, environmentId) + const outcome = await applyResumedRuntimePairing({ + userDataPath: desktopDataPath, + environmentId, + pairingCode: bootVm(serverDataPath, 'wss://vm-1.example/runtime'), + invalidateTransport: vi.fn(), + probeSavedPairing: async () => { + throw new RemoteRuntimeClientError('runtime_unavailable', 'unreachable', { + pairingStage: 'connect' + }) + } + }) + expect(outcome.reusedPairing).toBe(true) + expect(resolveEnvironmentPairingOffer(desktopDataPath, environmentId).deviceToken).toBe( + original.deviceToken + ) + }) +}) diff --git a/src/main/ephemeral-vm/runtime-resume-pairing.ts b/src/main/ephemeral-vm/runtime-resume-pairing.ts new file mode 100644 index 00000000000..dc42d772cfd --- /dev/null +++ b/src/main/ephemeral-vm/runtime-resume-pairing.ts @@ -0,0 +1,77 @@ +import { refreshEnvironmentFromResumePairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-resume-pairing' +import { + getPreferredPairedRuntimeConnection, + type KnownRuntimeEnvironment +} from '../../shared/remote-runtime/host-catalog/runtime-environments' +import type { PairedRuntimeConnection } from '../../shared/remote-runtime/pairing/paired-runtime-connection' +import { sendRemoteRuntimeRequest } from '../../shared/remote-runtime/remote-runtime-client' +import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../shared/electron-remote-runtime-client-capabilities' + +const SAVED_PAIRING_PROBE_TIMEOUT_MS = 10_000 + +export type ResumedRuntimePairingOutcome = { + environment: KnownRuntimeEnvironment + reusedPairing: boolean + endpointChanged: boolean +} + +/** + * Points a resumed recipe VM's server environment at its new endpoint. Keeps the saved device + * token while the host key is unchanged and the server still accepts it; otherwise re-pairs from + * the resume's fresh code. + */ +export async function applyResumedRuntimePairing(args: { + userDataPath: string + environmentId: string + pairingCode: string + invalidateTransport: (environmentId: string) => unknown + probeSavedPairing?: (connection: PairedRuntimeConnection) => Promise + now?: number +}): Promise { + const { repairFromFreshOffer, ...refreshed } = refreshEnvironmentFromResumePairingCode( + args.userDataPath, + args.environmentId, + { pairingCode: args.pairingCode, now: args.now } + ) + const outcome = refreshed.reusedPairing + ? await confirmSavedPairing(refreshed, repairFromFreshOffer, args.probeSavedPairing) + : refreshed + // Why also on an unchanged endpoint: the VM restarted, so any open socket is already dead. + // Why after the probe: reconnecting first would dial with a token about to be replaced. + void args.invalidateTransport(args.environmentId) + return outcome +} + +async function confirmSavedPairing( + refreshed: ResumedRuntimePairingOutcome, + repairFromFreshOffer: () => KnownRuntimeEnvironment, + probe: (connection: PairedRuntimeConnection) => Promise = probeSavedPairing +): Promise { + try { + await probe(getPreferredPairedRuntimeConnection(refreshed.environment)) + return refreshed + } catch (error) { + // Only a rejected token falls back; an unreachable server would fail the fresh pairing too. + if (!(error instanceof RemoteRuntimeClientError) || error.code !== 'unauthorized') { + return refreshed + } + // The server kept its key but lost the saved device (e.g. its device list was reset). + return { ...refreshed, environment: repairFromFreshOffer(), reusedPairing: false } + } +} + +async function probeSavedPairing(connection: PairedRuntimeConnection): Promise { + const response = await sendRemoteRuntimeRequest( + connection, + 'status.get', + undefined, + SAVED_PAIRING_PROBE_TIMEOUT_MS, + undefined, + undefined, + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES + ) + if (!response.ok && response.error.code === 'unauthorized') { + throw new RemoteRuntimeClientError('unauthorized', response.error.message) + } +} diff --git a/src/main/ephemeral-vm/runtime-service.test.ts b/src/main/ephemeral-vm/runtime-service.test.ts index d65a7fa99b3..8b0eb7b74a9 100644 --- a/src/main/ephemeral-vm/runtime-service.test.ts +++ b/src/main/ephemeral-vm/runtime-service.test.ts @@ -217,7 +217,42 @@ describe('ephemeral VM runtime service', () => { expect(readFileSync(countPath, 'utf8')).toBe('xx') }) - it('does not persist a runtime when recipe output cannot be parsed', async () => { + it('keeps no record when create is cancelled before its script starts', async () => { + const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') + const repoPath = makeDir('orca-ephemeral-vm-service-repo-') + const startedPath = join(repoPath, 'started.txt') + const startPath = join(repoPath, 'start.js') + writeFileSync(startPath, `require('fs').writeFileSync(${JSON.stringify(startedPath)}, 'x')\n`) + const controller = new AbortController() + controller.abort() + + const provisioned = await provisionEphemeralVmRuntime({ + userDataPath, + repoPath, + recipe: { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: nodeCommand(startPath) }, + signal: controller.signal + }) + + expect(provisioned).toMatchObject({ ok: false, start: { exitCode: null } }) + expect(existsSync(startedPath)).toBe(false) + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) + }) + + it('keeps no record when create fails validation before its script starts', async () => { + const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') + const missingRepoPath = join(makeDir('orca-ephemeral-vm-service-repo-'), 'missing') + + await expect( + provisionEphemeralVmRuntime({ + userDataPath, + repoPath: missingRepoPath, + recipe: { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: 'unused' } + }) + ).rejects.toThrow() + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) + }) + + it('keeps a result-less failed record when recipe output cannot be parsed', async () => { const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') const repoPath = makeDir('orca-ephemeral-vm-service-repo-') const startPath = join(repoPath, 'start.js') @@ -230,7 +265,8 @@ describe('ephemeral VM runtime service', () => { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: nodeCommand(startPath) - } + }, + now: 1_000 }) expect(provisioned).toMatchObject({ @@ -239,7 +275,138 @@ describe('ephemeral VM runtime service', () => { error: 'Recipe stdout must be one JSON object.' } }) - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) + const runtimes = listEphemeralVmRuntimes(userDataPath) + expect(runtimes).toEqual([ + expect.objectContaining({ + id: provisioned.start.context.instanceId, + status: 'failed', + cleanupLastError: 'Recipe stdout must be one JSON object.', + createdAt: 1_000 + }) + ]) + expect(runtimes[0]).not.toHaveProperty('recipeResult') + }) + + it('keeps a timed-out create destroyable by its instance id', async () => { + const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') + const repoPath = makeDir('orca-ephemeral-vm-service-repo-') + const startPath = join(repoPath, 'start.js') + writeFileSync(startPath, 'setInterval(() => {}, 1000)') + const recipe: OrcaVmRecipe = { + id: 'slow-sandbox', + name: 'Slow Sandbox', + create: nodeCommand(startPath), + destroy: nodeCommand(startPath), + timeoutSeconds: { create: 1 } + } + + const provisioned = await provisionEphemeralVmRuntime({ + userDataPath, + repoPath, + recipe, + now: 1_000 + }) + + expect(provisioned).toMatchObject({ ok: false, start: { errorCode: 'recipeTimedOut' } }) + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ + expect.objectContaining({ + id: provisioned.start.context.instanceId, + status: 'failed', + cleanupStatus: 'not_started', + cleanupLastErrorCode: 'recipeTimedOut', + recipe: expect.not.objectContaining({ timeoutSeconds: expect.anything() }) + }) + ]) + }) + + it('reconciles a create interrupted by a crash into a destroyable failed record', async () => { + const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') + const repoPath = makeDir('orca-ephemeral-vm-service-repo-') + const startPath = join(repoPath, 'start.js') + const destroyPath = join(repoPath, 'destroy.js') + const spawnedPath = join(repoPath, 'create-spawned.txt') + const payloadPath = join(repoPath, 'destroy-payload.json') + writeFileSync( + startPath, + [ + `require('fs').writeFileSync(${JSON.stringify(spawnedPath)}, process.env.ORCA_VM_INSTANCE_ID)`, + 'setInterval(() => {}, 1000)' + ].join('\n') + ) + writeFileSync( + destroyPath, + [ + "let input = ''", + "process.stdin.on('data', (chunk) => { input += chunk })", + `process.stdin.on('end', () => require('fs').writeFileSync(${JSON.stringify(payloadPath)}, input))` + ].join('\n') + ) + const recipe: OrcaVmRecipe = { + id: 'slow-sandbox', + name: 'Slow Sandbox', + create: nodeCommand(startPath), + destroy: nodeCommand(destroyPath) + } + const controller = new AbortController() + const provisioning = provisionEphemeralVmRuntime({ + userDataPath, + repoPath, + recipe, + repoId: 'repo-1', + workspaceName: 'Slow VM', + now: 1_000, + signal: controller.signal + }) + await vi.waitFor(() => expect(existsSync(spawnedPath)).toBe(true), { timeout: 10_000 }) + const instanceId = readFileSync(spawnedPath, 'utf8') + + // Persisted before create returned, and invisible to older builds' store schema. + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ + expect.objectContaining({ id: instanceId, status: 'provisioning', repoId: 'repo-1' }) + ]) + expect( + JSON.parse(readFileSync(getEphemeralVmRuntimeStorePath(userDataPath), 'utf8')).runtimes + ).toEqual([]) + const { reconcileInterruptedEphemeralVmProvisions: reconcileInSameProcess } = + await import('./runtime-provisioning-persistence') + expect(reconcileInSameProcess(userDataPath)).toEqual([]) + + // A relaunch has no record of the in-flight create. + vi.resetModules() + const { reconcileInterruptedEphemeralVmProvisions } = + await import('./runtime-provisioning-persistence') + const reconciled = reconcileInterruptedEphemeralVmProvisions(userDataPath, 5_000) + controller.abort() + await provisioning + + expect(reconciled).toEqual([ + { + id: instanceId, + recipeId: 'slow-sandbox', + recipe, + repoId: 'repo-1', + repoPath, + workspaceName: 'Slow VM', + status: 'failed', + cleanupStatus: 'not_started', + cleanupLastError: + 'Orca stopped while this VM was being created. Destroy it to release any provider resources.', + cleanupLastErrorCode: 'provisionInterrupted', + createdAt: 1_000, + updatedAt: 5_000 + } + ]) + + const cleanup = await cleanupEphemeralVmRuntime({ + userDataPath, + repoPath, + recipe, + runtimeId: instanceId + }) + expect(cleanup).toMatchObject({ ok: true, runtime: { status: 'cleaned' } }) + const payload = JSON.parse(readFileSync(payloadPath, 'utf8')) + expect(payload).toMatchObject({ mode: 'destroy', instanceId, recipeId: 'slow-sandbox' }) + expect(payload).not.toHaveProperty('recipeResult') }) it('rejects an unwritable feature store before a checkout-mode recipe creates resources', async () => { diff --git a/src/main/ephemeral-vm/runtime-service.ts b/src/main/ephemeral-vm/runtime-service.ts index 5a94f2ec621..4eba637eea1 100644 --- a/src/main/ephemeral-vm/runtime-service.ts +++ b/src/main/ephemeral-vm/runtime-service.ts @@ -13,10 +13,12 @@ import { type EphemeralVmRecipeStartFailure, type EphemeralVmRecipeStartSuccess } from '../../shared/ephemeral-vm-recipe-runner' -import { cleanupFailedEphemeralVmStart } from './failed-start-cleanup' import { - persistProvisionedEphemeralVmRuntime, - prepareEphemeralVmCompatibilityPersistence + beginEphemeralVmProvisioning, + endEphemeralVmProvisioning, + isEphemeralVmProvisionLive, + persistFailedEphemeralVmStart, + persistProvisionedEphemeralVmRuntime } from './runtime-provisioning-persistence' import { getProvisionedRootResumeIntegrityError } from './resume-integrity' import { runControlledEphemeralVmRuntimeCleanup } from './runtime-cleanup-control' @@ -105,38 +107,41 @@ export type ResumeEphemeralVmRuntimeResult = export async function provisionEphemeralVmRuntime( args: ProvisionEphemeralVmRuntimeArgs ): Promise { - const compatibility = prepareEphemeralVmCompatibilityPersistence(args) - const start = await runEphemeralVmRecipeStart({ - repoPath: args.repoPath, - recipe: args.recipe, - context: { - projectId: args.projectId, - workspaceId: args.workspaceId, - workspaceName: args.workspaceName, - repoUrl: args.repoUrl, - branch: args.branch, - ref: args.ref, - expectedRefHead: args.expectedRefHead, - orcaVersion: args.orcaVersion, - ...(compatibility ? { instanceId: compatibility.instanceId } : {}) - }, - signal: args.signal, - onStdout: args.onStdout, - onStderr: args.onStderr - }) - if (!start.ok) { - if (start.recipeResult) { - await cleanupFailedEphemeralVmStart(args, { - context: start.context, - recipeResult: start.recipeResult - }) + const writeAhead = beginEphemeralVmProvisioning(args) + try { + const start = await runEphemeralVmRecipeStart({ + repoPath: args.repoPath, + recipe: args.recipe, + context: { + projectId: args.projectId, + workspaceId: args.workspaceId, + workspaceName: args.workspaceName, + repoUrl: args.repoUrl, + branch: args.branch, + ref: args.ref, + expectedRefHead: args.expectedRefHead, + orcaVersion: args.orcaVersion, + instanceId: writeAhead.instanceId + }, + signal: args.signal, + onSpawn: () => { + writeAhead.launched = true + }, + onStdout: args.onStdout, + onStderr: args.onStderr + }) + if (!start.ok) { + await persistFailedEphemeralVmStart(args, writeAhead, start) + endEphemeralVmProvisioning(args, writeAhead) + return { ok: false, start } } - return { ok: false, start } + const runtime = await persistProvisionedEphemeralVmRuntime(args, start, writeAhead) + endEphemeralVmProvisioning(args, writeAhead) + return { ok: true, start, runtime } + } catch (error) { + endEphemeralVmProvisioning(args, writeAhead, error) + throw error } - - const runtime = await persistProvisionedEphemeralVmRuntime(args, start, compatibility) - - return { ok: true, start, runtime } } export function cleanupEphemeralVmRuntime( @@ -159,6 +164,9 @@ async function cleanupEphemeralVmRuntimeOnce( if (!existing) { throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) } + if (existing.status === 'provisioning' && isEphemeralVmProvisionLive(existing.id)) { + throw new Error(`Ephemeral VM runtime is still provisioning: ${existing.id}`) + } if (existing.status === 'cleaned') { return { ok: true, @@ -216,6 +224,9 @@ export async function suspendEphemeralVmRuntime( if (!existing) { throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) } + if (!existing.recipeResult) { + throw new Error(`Ephemeral VM runtime never finished provisioning: ${args.runtimeId}`) + } const suspend = await runEphemeralVmRecipeSuspend({ repoPath: args.repoPath, recipe: args.recipe, @@ -250,6 +261,9 @@ export async function resumeEphemeralVmRuntime( if (!existing) { throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) } + if (!existing.recipeResult) { + throw new Error(`Ephemeral VM runtime never finished provisioning: ${args.runtimeId}`) + } const resume = await runEphemeralVmRecipeResume({ repoPath: args.repoPath, recipe: args.recipe, diff --git a/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts b/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts index 7eb5d73dd65..baeb576e45a 100644 --- a/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts +++ b/src/main/ephemeral-vm/workspace-resume-user-disconnect.test.ts @@ -14,9 +14,11 @@ const mocks = vi.hoisted(() => ({ vi.mock('electron', () => ({ app: { getPath: () => '/user-data' } })) vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({ - findWorkspaceEphemeralVmRuntime: () => ({ id: 'vm-1', status: 'suspended', repoId: 'repo-1' }), updateEphemeralVmRuntimeStatus: mocks.updateStatus })) +vi.mock('../../shared/ephemeral-vm-workspace-runtime', () => ({ + findWorkspaceEphemeralVmRuntime: () => ({ id: 'vm-1', status: 'suspended', repoId: 'repo-1' }) +})) vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({ resolveEnvironment: () => ({ id: 'env-vm', pairingRevision: 9, createdAt: 0 }), updateEnvironmentFromPairingCode: vi.fn() @@ -26,7 +28,7 @@ vi.mock('../../shared/ephemeral-vm-recipes', () => ({ getEphemeralVmRecipeResultPairingCode: () => null })) vi.mock('../ipc/ephemeral-vm-recipe-context', () => ({ - getRuntimeRecipeContext: () => ({ repo: { repo: { path: '/repo' } }, recipe: {} }) + getRuntimeRecipeContext: () => ({ repoPath: '/repo', recipe: {} }) })) vi.mock('../ipc/runtime-environments/runtime-environments', () => ({ invalidateRuntimeEnvironmentTransport: vi.fn() diff --git a/src/main/ephemeral-vm/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index fe7e645ee6d..e17f536eb93 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -1,21 +1,17 @@ import { app } from 'electron' import type { Store } from '../persistence/loading-store/store' -import { - findWorkspaceEphemeralVmRuntime, - updateEphemeralVmRuntimeStatus -} from '../../shared/ephemeral-vm-runtime-store' +import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' +import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-workspace-runtime' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import { getEphemeralVmRecipeResultConnection, getEphemeralVmRecipeResultPairingCode } from '../../shared/ephemeral-vm-recipes' -import { - resolveEnvironment, - updateEnvironmentFromPairingCode -} from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' import { resumeEphemeralVmRuntime } from './runtime-service' import { connectRuntimeOwnedSshTarget, refreshRuntimeOwnedSshTarget } from './runtime-ssh' import { noteRecipeVmWakePairing } from './recipe-vm-wake-pairings' +import { applyResumedRuntimePairing } from './runtime-resume-pairing' import { getRuntimeOwnedSshTargetId } from '../ssh/targets/ssh-target-runtime-ownership' import { isSshUserDisconnected, @@ -42,13 +38,16 @@ export async function resumeEphemeralVmWorkspace( const recipeContext = getRuntimeRecipeContext(store, userDataPath, runtime.id) const result = await resumeEphemeralVmRuntime({ userDataPath, - repoPath: recipeContext.repo.repo.path, + repoPath: recipeContext.repoPath, recipe: recipeContext.recipe, runtimeId: runtime.id }) if (!result.ok) { throw new Error(result.error) } + if (!result.runtime.recipeResult) { + return result.runtime + } const connection = getEphemeralVmRecipeResultConnection(result.runtime.recipeResult) // SSH servers use their target and have no pairing to refresh. if (!result.skipped && connection.type !== 'ssh' && runtime.runtimeEnvironmentId) { @@ -56,11 +55,17 @@ export async function resumeEphemeralVmWorkspace( if (!pairingCode) { throw new Error('Resume result did not include an Orca Server pairing code.') } - const repaired = updateEnvironmentFromPairingCode(userDataPath, runtime.runtimeEnvironmentId, { - pairingCode + const { environment } = await applyResumedRuntimePairing({ + userDataPath, + environmentId: runtime.runtimeEnvironmentId, + pairingCode, + invalidateTransport: invalidateRuntimeEnvironmentTransport }) - noteRecipeVmWakePairing(repaired.id, repaired.pairingRevision ?? repaired.createdAt) - invalidateRuntimeEnvironmentTransport(runtime.runtimeEnvironmentId) + noteRecipeVmWakePairing( + environment.id, + environment.pairingRevision ?? environment.createdAt, + true + ) } // Suspend tore down the runtime-owned SSH transport, so an SSH VM reconnects even when its // recipe had no resume step to run. diff --git a/src/main/ephemeral-vm/workspace-suspend.ts b/src/main/ephemeral-vm/workspace-suspend.ts index 32c58a61f6f..7b79aa813f5 100644 --- a/src/main/ephemeral-vm/workspace-suspend.ts +++ b/src/main/ephemeral-vm/workspace-suspend.ts @@ -1,6 +1,6 @@ import { app } from 'electron' import type { Store } from '../persistence/loading-store/store' -import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store' +import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-workspace-runtime' import { suspendEphemeralVmRuntime } from './runtime-service' import { disconnectRuntimeOwnedSshTarget } from './runtime-ssh' import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' @@ -17,7 +17,7 @@ export async function suspendEphemeralVmWorkspace( const recipeContext = getRuntimeRecipeContext(store, userDataPath, runtime.id) const result = await suspendEphemeralVmRuntime({ userDataPath, - repoPath: recipeContext.repo.repo.path, + repoPath: recipeContext.repoPath, recipe: recipeContext.recipe, runtimeId: runtime.id }) diff --git a/src/main/external-conversations/external-conversation-cancel.test.ts b/src/main/external-conversations/external-conversation-cancel.test.ts index 38f93088f53..adbba524b56 100644 --- a/src/main/external-conversations/external-conversation-cancel.test.ts +++ b/src/main/external-conversations/external-conversation-cancel.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { ConversationEvent } from './external-conversation-events' import type { ConversationKey } from './external-conversation-types' import { diff --git a/src/main/external-conversations/external-conversation-events.ts b/src/main/external-conversations/external-conversation-events.ts index 20066bc110e..47573ddd9ef 100644 --- a/src/main/external-conversations/external-conversation-events.ts +++ b/src/main/external-conversations/external-conversation-events.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import { agentMainAgentVerdict } from '../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { PendingPrompt } from '../../shared/agent-status/contracts/agent-pending-prompt' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/external-conversations/external-conversation-links.ts b/src/main/external-conversations/external-conversation-links.ts index cdb6cbb3b10..6b79d4863d9 100644 --- a/src/main/external-conversations/external-conversation-links.ts +++ b/src/main/external-conversations/external-conversation-links.ts @@ -12,7 +12,7 @@ import { import { normalizeAgentProviderSession } from '../../shared/agent-session/lifecycle/agent-session-resume' import { readAllWorktreeMetaForHost } from '../persistence/host-qualified-worktree-meta' import { folderWorkspaceKey } from '../../shared/workspace-scope' -import type { AgentPaneWorkspace } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../agent-hooks/observations/agent-transition-detector' import { readWorkspaceRecord, writeWorkspaceRecord, diff --git a/src/main/external-conversations/external-conversation-prompts.test.ts b/src/main/external-conversations/external-conversation-prompts.test.ts index fbad128ef09..996f8e57154 100644 --- a/src/main/external-conversations/external-conversation-prompts.test.ts +++ b/src/main/external-conversations/external-conversation-prompts.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import { AGENT_DONE_QUIET_MS, diff --git a/src/main/external-conversations/external-conversation-seam.test-fixture.ts b/src/main/external-conversations/external-conversation-seam.test-fixture.ts index e594e6cb4b7..dbb72d8b2d6 100644 --- a/src/main/external-conversations/external-conversation-seam.test-fixture.ts +++ b/src/main/external-conversations/external-conversation-seam.test-fixture.ts @@ -1,6 +1,6 @@ import type { GlobalSettings } from '../../shared/global-settings-types' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db' import { DeliveryReceipts } from './external-conversation-delivery-receipts' import { ExternalConversationSeam } from './external-conversation-seam' diff --git a/src/main/external-conversations/external-conversation-seam.ts b/src/main/external-conversations/external-conversation-seam.ts index 13262ccb78b..ec15f8050ed 100644 --- a/src/main/external-conversations/external-conversation-seam.ts +++ b/src/main/external-conversations/external-conversation-seam.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { PendingPrompt } from '../../shared/agent-status/contracts/agent-pending-prompt' import type { AgentStatusHooksSettings } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/external-conversations/external-conversation-start.ts b/src/main/external-conversations/external-conversation-start.ts index eb3f3de6f70..86a6edcf787 100644 --- a/src/main/external-conversations/external-conversation-start.ts +++ b/src/main/external-conversations/external-conversation-start.ts @@ -9,7 +9,7 @@ import { executeAgentLaunch } from '../agent-launch/agent-launch-executor' import { agentPaneWorkspace, type AgentPaneWorkspace -} from '../agent-hooks/agent-transition-detector' +} from '../agent-hooks/observations/agent-transition-detector' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { resolveUnlaunchedIntent } from '../runtime/rpc/methods/agent-launch/agent-launch-intent-resolution' import { agentLaunchSurfaceFactory } from '../runtime/rpc/methods/agent-launch/agent-launch-surfaces' diff --git a/src/main/external-conversations/external-conversation.test-fixture.ts b/src/main/external-conversations/external-conversation.test-fixture.ts index 5475606b7ab..6cf09de158b 100644 --- a/src/main/external-conversations/external-conversation.test-fixture.ts +++ b/src/main/external-conversations/external-conversation.test-fixture.ts @@ -8,7 +8,7 @@ import type { Repo } from '../../shared/repo-types' import type { PtyLivenessVerdict } from '../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import type { RuntimeTerminalSend } from '../../shared/runtime-terminal-send-contract' import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' -import type { AgentPaneWorkspace } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../agent-hooks/observations/agent-transition-detector' import type { LaunchedAgentForeground } from '../runtime/terminal/wait/launched-agent-foreground' import type { ExternalConversationLinkStore } from './external-conversation-links' diff --git a/src/main/external-conversations/external-conversations-install.ts b/src/main/external-conversations/external-conversations-install.ts index 23a5c9dca00..b8daa142a97 100644 --- a/src/main/external-conversations/external-conversations-install.ts +++ b/src/main/external-conversations/external-conversations-install.ts @@ -1,5 +1,5 @@ import type { GlobalSettings } from '../../shared/global-settings-types' -import type { AgentTransitionDetector } from '../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../agent-hooks/observations/agent-transition-detector' import type { RuntimeWorktreeLifecycleEvent } from '../runtime/workspaces/lifecycle/worktree-lifecycle-event' import { DeliveryReceipts, type DeliveryReceiptDb } from './external-conversation-delivery-receipts' import type { ExternalConversationLinkStore } from './external-conversation-links' diff --git a/src/main/gemini/hook-service.ts b/src/main/gemini/hook-service.ts index 347f41b295f..7735667a9e1 100644 --- a/src/main/gemini/hook-service.ts +++ b/src/main/gemini/hook-service.ts @@ -7,30 +7,32 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath, MANAGED_HOOK_TIMEOUT_MILLISECONDS, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' // Gemini has no permission-prompt hook, so approvals cannot produce an Orca waiting state. // Gemini uses BeforeTool; remove stale Claude-style PreToolUse registrations below. diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts index 8dcd75701bc..45a2f92aca0 100644 --- a/src/main/github/body-image-read-adapters.test.ts +++ b/src/main/github/body-image-read-adapters.test.ts @@ -15,7 +15,6 @@ vi.mock('./project-view/internals', () => ({ projectGhExecOptions: () => ({}), runGraphql: mocks.graphql })) -import { getPRMetadata } from './pull-request-file-data' import { getWorkItemDetailsBySlug } from './project-view/work-item-details' const body = @@ -31,51 +30,6 @@ beforeEach(() => { mocks.graphql.mockReset() }) -it('gets PR metadata images in its existing uncached full-media read', async () => { - mocks.exec.mockResolvedValueOnce({ - stdout: JSON.stringify({ body, body_html: html, head: { sha: 'head' } }) - }) - const metadata = await getPRMetadata('/repo', 7, { owner: 'acme', repo: 'widgets' }) - expect(metadata).toMatchObject({ body, headSha: 'head', bodyImageUrls: expectedMap }) - expect(mocks.exec).toHaveBeenCalledTimes(1) - expect(mocks.exec.mock.calls[0][0]).toEqual([ - 'api', - '-H', - 'Accept: application/vnd.github.full+json', - 'repos/acme/widgets/pulls/7' - ]) -}) - -it.each(['issue', 'pr'] as const)( - 'gets slug %s body and comment images in one existing read', - async (type) => { - mocks.graphql.mockResolvedValueOnce({ - ok: true, - data: { - repository: { - [type === 'issue' ? 'issue' : 'pullRequest']: { - id: 'ITEM', - body, - bodyHTML: html, - comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } - } - } - } - }) - const result = await getWorkItemDetailsBySlug({ - owner: 'acme', - repo: 'widgets', - number: 7, - type - }) - expect(result.ok && result.details.body).toBe(body) - expect(result.ok && result.details.bodyImageUrls).toEqual(expectedMap) - expect(result.ok && result.details.comments[0].bodyImageUrls).toEqual(expectedMap) - expect(mocks.graphql).toHaveBeenCalledTimes(1) - expect(mocks.exec).not.toHaveBeenCalled() - } -) - it.each(['issue', 'pr'] as const)( 'recovers available slug %s data without trusting failed HTML', async (type) => { diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/body-image-urls.test.ts index a9cb4b32f46..07ee91dac34 100644 --- a/src/main/github/body-image-urls.test.ts +++ b/src/main/github/body-image-urls.test.ts @@ -1,7 +1,6 @@ import type * as HtmlParser from 'hast-util-from-html-isomorphic' -import type { Root, RootContent } from 'hast' import { describe, expect, it, vi } from 'vitest' -const traversal = vi.hoisted(() => ({ enabled: false, parses: 0, children: 0, fail: false })) +const traversal = vi.hoisted(() => ({ fail: false })) vi.mock('hast-util-from-html-isomorphic', async (load) => { const actual = await load() return { @@ -10,27 +9,7 @@ vi.mock('hast-util-from-html-isomorphic', async (load) => { if (traversal.fail) { throw new Error('Optional image HTML could not be parsed') } - const tree = actual.fromHtmlIsomorphic(...args) - if (!traversal.enabled) { - return tree - } - traversal.parses++ - const pending: (Root | RootContent)[] = [tree] - while (pending.length) { - const node = pending.pop()! - if (!('children' in node)) { - continue - } - const children = node.children - pending.push(...children) - Object.defineProperty(node, 'children', { - get: () => { - traversal.children++ - return children - } - }) - } - return tree + return actual.fromHtmlIsomorphic(...args) } } }) @@ -41,24 +20,6 @@ const signed = 'https://private-user-images.githubusercontent.com/1/2-ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST&download=1' describe('GitHub body image sources', () => { - it.each([ - { body: `![shot](${original})`, html: true }, - { body: true, html: `` } - ])('ignores unusable optional representations ($body, $html)', ({ body, html }) => { - expect(githubBodyImageUrls(body, html)).toBeUndefined() - }) - - it('skips HTML parsing when the Markdown has no attachment candidates', () => { - traversal.enabled = true - traversal.parses = 0 - try { - expect(githubBodyImageUrls('A plain comment', ``)).toBeUndefined() - expect(traversal.parses).toBe(0) - } finally { - traversal.enabled = false - } - }) - it('leaves the optional map absent if HTML extraction fails', () => { traversal.fail = true try { @@ -85,54 +46,4 @@ describe('GitHub body image sources', () => { ) ).toBeUndefined() }) - - it('bounds candidate validation and indexed lookups at N and 10N', () => { - for (const n of [100, 1000]) { - const ids = Array.from( - { length: n }, - (_, i) => `ce11040a-fb66-4289-927f-${String(i).padStart(12, '0')}` - ) - const body = ids - .map((id) => `![shot](https://github.com/user-attachments/assets/${id})`) - .join('\n') - const html = ids - .map( - (id) => - `` - ) - .join('\n') - traversal.enabled = true - traversal.parses = 0 - traversal.children = 0 - const pathname = vi.spyOn(URL.prototype, 'pathname', 'get') - const originalGet = Map.prototype.get - let lookups = 0 - Map.prototype.get = function (this: Map, key: unknown) { - if (typeof key === 'string' && key.startsWith('ce11040a-')) { - lookups++ - } - return originalGet.call(this, key) - } - try { - const result = githubBodyImageUrls(body, html) - expect(Object.keys(result ?? {})).toHaveLength(n) - // Each candidate and original is checked once, then each original gets one indexed lookup. - expect(pathname.mock.calls.length).toBeLessThanOrEqual(3 * n) - expect(lookups).toBe(n) - expect(traversal.parses).toBe(1) - expect(traversal.children).toBeLessThanOrEqual(n + 1) - expect( - result?.[ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-000000000000' - ] - ).toBe( - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-000000000000.png?jwt=TEST' - ) - } finally { - traversal.enabled = false - Map.prototype.get = originalGet - pathname.mockRestore() - } - } - }) }) diff --git a/src/main/github/issue-comment-image.test.ts b/src/main/github/issue-comment-image.test.ts deleted file mode 100644 index c22f437bd88..00000000000 --- a/src/main/github/issue-comment-image.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ exec: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: mocks.exec, - acquire: async () => {}, - release: () => {}, - classifyGhError: () => ({ type: 'unknown' }) -})) -vi.mock('./github-api-repository', () => ({ - resolveGitHubRepoExecution: async () => ({ - ownerRepo: { owner: 'acme', repo: 'widgets' }, - ghOptions: {} - }) -})) -import { addIssueComment } from './issue-comment' -import { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' - -it('returns signed display sources immediately after posting the original Markdown', async () => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - mocks.exec.mockResolvedValue({ - stdout: JSON.stringify({ - id: 1, - user: null, - body, - body_html: - '' - }) - }) - const result = await addIssueComment('/repo', 42, body) - expect(mocks.exec.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') - expect(mocks.exec.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) - expect(result.ok && result.comment.body).toBe(body) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) -}) - -it.each(['review', 'reply'])( - 'returns paired image sources immediately for %s posts', - async (kind) => { - mocks.exec.mockClear() - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - mocks.exec.mockResolvedValue({ - stdout: JSON.stringify({ - id: 1, - body, - user: null, - body_html: - '' - }) - }) - const result = - kind === 'review' - ? await addPRReviewComment({ - repoPath: '/repo', - prNumber: 7, - body, - commitId: 'head', - path: 'file.ts', - line: 1 - }) - : await addPRReviewCommentReply('/repo', 7, 1, body) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - expect(mocks.exec.mock.calls[0][0]).toContain( - 'body=![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - ) - } -) diff --git a/src/main/github/project-view/body-image-mutations.test.ts b/src/main/github/project-view/body-image-mutations.test.ts index 53c0925b77f..2230f380082 100644 --- a/src/main/github/project-view/body-image-mutations.test.ts +++ b/src/main/github/project-view/body-image-mutations.test.ts @@ -47,8 +47,6 @@ vi.mock('./internals', () => ({ })) import { updateIssueBySlug } from './mutations' -import { updatePullRequestBySlug } from './pull-request-mutation' -import { addIssueCommentBySlug } from './issue-comment-mutations' describe('Project accepted body representations', () => { beforeEach(() => { @@ -61,51 +59,6 @@ describe('Project accepted body representations', () => { runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} }) }) - it.each([updateIssueBySlug, updatePullRequestBySlug])( - 'returns paired image sources after a body edit', - async (update) => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - runRestMock.mockResolvedValueOnce({ - ok: true, - data: { - body, - body_html: - '' - } - }) - const result = await update({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) - expect(result).toEqual({ - ok: true, - bodyImageUrls: { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - } - }) - expect(runRestMock.mock.calls[0][0]).toContain(`body=${body}`) - expect(runRestMock.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') - } - ) - - it('returns the paired source for a newly posted Project comment', async () => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - runRestMock.mockResolvedValueOnce({ - ok: true, - data: { - id: 1, - body, - body_html: - '' - } - }) - const result = await addIssueCommentBySlug({ owner: 'acme', repo: 'widgets', number: 12, body }) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - }) - it('does not attach a Project issue map from a different accepted body snapshot', async () => { const body = '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' @@ -122,20 +75,6 @@ describe('Project accepted body representations', () => { ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) }) - it('keeps an accepted PR body save successful without an optional representation', async () => { - runRestMock.mockResolvedValueOnce({ ok: true, data: null }) - await expect( - updatePullRequestBySlug({ - owner: 'acme', - repo: 'widgets', - number: 12, - updates: { - body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - } - }) - ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) - }) - it.each([null, true])( 'finishes a Project compound save with unusable optional HTML (%s)', async (html) => { diff --git a/src/main/grok/grok-hook-backup-cleanup.ts b/src/main/grok/grok-hook-backup-cleanup.ts index 1e908564b89..9eb808b1ba2 100644 --- a/src/main/grok/grok-hook-backup-cleanup.ts +++ b/src/main/grok/grok-hook-backup-cleanup.ts @@ -1,6 +1,7 @@ import { lstatSync, rmSync, writeFileSync } from 'node:fs' import { lstat, rm, writeFile } from 'node:fs/promises' -import { readHooksJsonWithRaw, type HooksConfig } from '../agent-hooks/installer-utils' +import { readHooksJsonWithRaw } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' import { readGrokHookConfigSnapshot } from './grok-hook-config-file' diff --git a/src/main/grok/grok-hook-config-cleanup.ts b/src/main/grok/grok-hook-config-cleanup.ts index bdb770c421d..bda9a9f2ac7 100644 --- a/src/main/grok/grok-hook-config-cleanup.ts +++ b/src/main/grok/grok-hook-config-cleanup.ts @@ -1,9 +1,9 @@ import { createManagedCommandMatcher, hookDefinitionHasManagedCommand, - removeManagedCommands, - type HooksConfig -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' export type GrokHookConfigCleanup = { config: HooksConfig diff --git a/src/main/grok/grok-hook-config-file.ts b/src/main/grok/grok-hook-config-file.ts index 975b9834938..86ca41c7212 100644 --- a/src/main/grok/grok-hook-config-file.ts +++ b/src/main/grok/grok-hook-config-file.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { constants } from 'node:fs' import { copyFile, lstat, open, readFile, realpath, rename, rm, stat } from 'node:fs/promises' -import { parseHooksJsonText } from '../agent-hooks/hooks-json-read' -import type { HooksConfig } from '../agent-hooks/installer-utils' +import { parseHooksJsonText } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' export type AsyncGrokHookConfigSnapshot = { raw: string | null diff --git a/src/main/grok/grok-hook-config.ts b/src/main/grok/grok-hook-config.ts index e20a860b7ad..39c4a5a4dcc 100644 --- a/src/main/grok/grok-hook-config.ts +++ b/src/main/grok/grok-hook-config.ts @@ -1,10 +1,12 @@ import { buildManagedCommandHook, - createManagedCommandMatcher, - removeManagedCommands, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' export const GROK_TOOL_EVENT_MATCHER = '.*' diff --git a/src/main/grok/grok-hook-remote-install.ts b/src/main/grok/grok-hook-remote-install.ts index d8e6b1af698..02d115fd0dc 100644 --- a/src/main/grok/grok-hook-remote-install.ts +++ b/src/main/grok/grok-hook-remote-install.ts @@ -1,12 +1,12 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { wrapPosixHookCommand } from '../agent-hooks/installer-utils' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildInstalledGrokConfig } from './grok-hook-config' import { GROK_HOME_ENVELOPE_MAX_LENGTH } from './windows-grok-hook-script' diff --git a/src/main/grok/grok-hook-script.ts b/src/main/grok/grok-hook-script.ts index 411e250960e..92c8c19424f 100644 --- a/src/main/grok/grok-hook-script.ts +++ b/src/main/grok/grok-hook-script.ts @@ -1,11 +1,12 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { getSharedManagedScriptPath, wrapPosixHookCommand } from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, POSIX_HOOK_JSON_STDIN -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildWindowsGrokHookScript, GROK_HOME_ENVELOPE_MAX_LENGTH diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index ff008c35df4..a9a5e7b9bfe 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -8,11 +8,11 @@ import type { import { resolveGrokHomeDir } from '../../shared/grok-session-paths' import { readHooksJson, - readHooksJsonWithRaw, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + readHooksJsonWithRaw +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' import { removeGrokHookBackupEntries, diff --git a/src/main/grok/windows-grok-hook-script.ts b/src/main/grok/windows-grok-hook-script.ts index ddcbfa5e5f4..0be96de50ca 100644 --- a/src/main/grok/windows-grok-hook-script.ts +++ b/src/main/grok/windows-grok-hook-script.ts @@ -1,5 +1,5 @@ -import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installer-utils' -import { buildWindowsHookEnvironmentGuardLines } from '../agent-hooks/hook-stdin-contract' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { buildWindowsHookEnvironmentGuardLines } from '../agent-hooks/installation/scripts/hook-stdin-contract' /** Matches the envelope length cap used by the POSIX grok-hook branch. */ export const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096 diff --git a/src/main/grok/windows-hook-launcher-chain.test.ts b/src/main/grok/windows-hook-launcher-chain.test.ts index 104c360a39d..9002d7e4eec 100644 --- a/src/main/grok/windows-hook-launcher-chain.test.ts +++ b/src/main/grok/windows-hook-launcher-chain.test.ts @@ -17,7 +17,8 @@ vi.mock('os', async () => { }) import { getManagedCommandForTests, GrokHookService } from './hook-service' -import { wrapWindowsHookCommand, type HooksConfig } from '../agent-hooks/installer-utils' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { buildInstalledGrokConfig } from './grok-hook-config' const GROK_EVENT_NAMES = [ diff --git a/src/main/hermes/hermes-config-comment-boundaries.test.ts b/src/main/hermes/hermes-config-comment-boundaries.test.ts index 2a8abd0af21..32493acb4e0 100644 --- a/src/main/hermes/hermes-config-comment-boundaries.test.ts +++ b/src/main/hermes/hermes-config-comment-boundaries.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { parseDocument } from 'yaml' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' import { disablePlugin, enablePlugin, diff --git a/src/main/hermes/hermes-config-remote-adapter.test.ts b/src/main/hermes/hermes-config-remote-adapter.test.ts index 226b93aa525..57f47e2db5f 100644 --- a/src/main/hermes/hermes-config-remote-adapter.test.ts +++ b/src/main/hermes/hermes-config-remote-adapter.test.ts @@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSyn import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' import { HermesHookService } from './hook-service' describe('Hermes remote installer through a local filesystem adapter (no SSH)', () => { diff --git a/src/main/hermes/hermes-home-filesystem.ts b/src/main/hermes/hermes-home-filesystem.ts index d4daa431c8f..09f18c55dc7 100644 --- a/src/main/hermes/hermes-home-filesystem.ts +++ b/src/main/hermes/hermes-home-filesystem.ts @@ -1,11 +1,10 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import type { ConfigParseResult, HermesConfig } from './hermes-config-yaml' -import { parseHermesConfig } from './hermes-config-yaml' +import { type ConfigParseResult, type HermesConfig, parseHermesConfig } from './hermes-config-yaml' import { getHermesHome } from './hermes-default-home' -import { resolveHooksJsonWritePath } from '../agent-hooks/hook-config-write-path' -import { writeHooksJson } from '../agent-hooks/installer-utils' +import { resolveHooksJsonWritePath } from '../agent-hooks/installation/configuration/hook-config-write-path' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' import { HERMES_PLUGIN_MARKER, HERMES_PLUGIN_NAME, diff --git a/src/main/hermes/hook-service.ts b/src/main/hermes/hook-service.ts index 9296c297f05..e4712303670 100644 --- a/src/main/hermes/hook-service.ts +++ b/src/main/hermes/hook-service.ts @@ -9,9 +9,10 @@ import { listRemoteDirectory, readTextFileRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' -import type { HermesConfig } from './hermes-config-yaml' +} from '../agent-hooks/installation/remote/hook-text-files-remote' + import { + type HermesConfig, disablePlugin, enablePlugin, getConfigEnablement, diff --git a/src/main/host/electron-browser-commands.ts b/src/main/host/electron-browser-commands.ts index 4fdd74b4969..ae3a0858879 100644 --- a/src/main/host/electron-browser-commands.ts +++ b/src/main/host/electron-browser-commands.ts @@ -1,9 +1,9 @@ import { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' import { setRuntimeBrowserCommandsFactory } from '../runtime/browser/installation/runtime-browser-commands-factory' import { setBrowserHostClientProfileResolver } from '../runtime/browser-host/profiles/browser-host-client-profile-metadata' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { setManagedBrowserProfileDeleter } from '../runtime/browser-host/profiles/managed-browser-profile-removal' -import { deleteManagedBrowserProfile } from '../browser/sessions/browser-managed-session-profiles' +import { deleteManagedBrowserProfile } from '../browser/sessions/profiles/browser-managed-session-profiles' /** Importing this desktop factory loads the Chromium browser cluster. */ export function installElectronBrowserCommands(): void { diff --git a/src/main/host/native-chat-visual-guest-theme.test.ts b/src/main/host/native-chat-visual-guest-theme.test.ts index a3dd2e7ca48..da4fe5cd0d2 100644 --- a/src/main/host/native-chat-visual-guest-theme.test.ts +++ b/src/main/host/native-chat-visual-guest-theme.test.ts @@ -4,11 +4,11 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { BrowserWindow, IpcMainEvent } from 'electron' -import type * as SiteDisplayController from '../browser/site-settings/browser-site-display-controller' +import type * as SiteDisplayController from '../browser/site-settings/display/browser-site-display-controller' import { configureBrowserSiteDisplayStore, updateBrowserSiteDisplay -} from '../browser/site-settings/browser-site-display-store' +} from '../browser/site-settings/display/browser-site-display-store' import { NATIVE_CHAT_VISUAL_GUEST_THEME_PUBLISH as PUBLISH, NATIVE_CHAT_VISUAL_GUEST_THEME_READ as READ @@ -36,10 +36,10 @@ vi.mock('../native-chat/native-chat-scratch-folder', () => ({ vi.mock('../native-chat/native-chat-visual-guest-location', () => ({ isNativeChatVisualGuestLocation: classify })) -vi.mock('../browser/site-settings/browser-site-display-controller', () => ({ +vi.mock('../browser/site-settings/display/browser-site-display-controller', () => ({ browserSiteDisplayController: display })) -vi.mock('../browser/sessions/browser-session-registry', () => ({ +vi.mock('../browser/sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { profileIdForSession: profileForSession } })) vi.mock('../browser/routing/local-host-partitions/local-ssh-browser-partitions', () => ({ @@ -48,7 +48,7 @@ vi.mock('../browser/routing/local-host-partitions/local-ssh-browser-partitions', import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme' const { BrowserSiteDisplayController } = await vi.importActual( - '../browser/site-settings/browser-site-display-controller' + '../browser/site-settings/display/browser-site-display-controller' ) function contents(id: number, hostWebContents: EventEmitter | null = null) { diff --git a/src/main/host/native-chat-visual-guest-theme.ts b/src/main/host/native-chat-visual-guest-theme.ts index b155ac10cc4..944ff287bcc 100644 --- a/src/main/host/native-chat-visual-guest-theme.ts +++ b/src/main/host/native-chat-visual-guest-theme.ts @@ -9,9 +9,9 @@ import { } from '../../shared/native-chat/native-chat-visual-shell' import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' import { nativeChatScratchRootFor } from '../native-chat/native-chat-scratch-folder' -import { browserSiteDisplayController } from '../browser/site-settings/browser-site-display-controller' +import { browserSiteDisplayController } from '../browser/site-settings/display/browser-site-display-controller' import { isNativeChatVisualGuestLocation } from '../native-chat/native-chat-visual-guest-location' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { localSshBrowserProfileIdForSession } from '../browser/routing/local-host-partitions/local-ssh-browser-partitions' /** Install before the host loads: an unanswered synchronous preload request blocks its guest. */ diff --git a/src/main/ipc/agent-hooks.test.ts b/src/main/ipc/agent-hooks.test.ts index fcce63080a8..d0c28dd513f 100644 --- a/src/main/ipc/agent-hooks.test.ts +++ b/src/main/ipc/agent-hooks.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentHookServerModule from '../agent-hooks/server' +import type * as AgentHookServerModule from '../agent-hooks/server/agent-hook-server' import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' // Renderer dismissals must evict persisted status as well as the live row. @@ -36,9 +36,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../agent-hooks/server', async () => { +vi.mock('../agent-hooks/server/agent-hook-server', async () => { // Use the real pane-key validator so invalid-input coverage tracks its constraints. - const actual = await vi.importActual('../agent-hooks/server') + const actual = await vi.importActual( + '../agent-hooks/server/agent-hook-server' + ) return { ...actual, agentHookServer: { @@ -55,7 +57,7 @@ vi.mock('../agent-hooks/server', async () => { } }) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => ({ +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => ({ clearMigrationUnsupportedPtysByTabPrefix, clearMigrationUnsupportedPtysForPaneKey, getMigrationUnsupportedPtySnapshot: vi.fn(() => []) diff --git a/src/main/ipc/agent-hooks.ts b/src/main/ipc/agent-hooks.ts index 4bc8d1f18bd..20f770fd93e 100644 --- a/src/main/ipc/agent-hooks.ts +++ b/src/main/ipc/agent-hooks.ts @@ -5,8 +5,8 @@ import type { } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' -import { agentHookServer } from '../agent-hooks/server' -import { getMigrationUnsupportedPtySnapshot } from '../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { getMigrationUnsupportedPtySnapshot } from '../agent-hooks/observations/migration-unsupported-pty-state' import { registerAgentPaneAuthorityIpcHandlers } from './agent-pane-authority-ipc' import { registerAgentStatusRowTeardownIpcHandlers } from './agent-status-row-teardown-ipc' import { createAgentPaneAuthorityOwnership } from './agent-pane-authority-ownership' diff --git a/src/main/ipc/agent-pane-authority-ipc.ts b/src/main/ipc/agent-pane-authority-ipc.ts index 7c967178b23..4670017e32e 100644 --- a/src/main/ipc/agent-pane-authority-ipc.ts +++ b/src/main/ipc/agent-pane-authority-ipc.ts @@ -1,8 +1,8 @@ import { ipcMain } from 'electron' import { isStablePaneId } from '../../shared/workspace-layout/stable-pane-id' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isValidPaneKey } from '../agent-hooks/server/server-status-identity' -import { clearMigrationUnsupportedPtysForPaneKey } from '../agent-hooks/migration-unsupported-pty-state' +import { clearMigrationUnsupportedPtysForPaneKey } from '../agent-hooks/observations/migration-unsupported-pty-state' const MAX_PTY_ID_LENGTH = 512 diff --git a/src/main/ipc/agent-pane-retirement-ipc.test.ts b/src/main/ipc/agent-pane-retirement-ipc.test.ts index ab46d02fef4..a2db1dd1bec 100644 --- a/src/main/ipc/agent-pane-retirement-ipc.test.ts +++ b/src/main/ipc/agent-pane-retirement-ipc.test.ts @@ -12,13 +12,13 @@ vi.mock('electron', () => ({ on: (name: string, callback: (...args: unknown[]) => void) => mocks.handlers.set(name, callback) } })) -vi.mock('../agent-hooks/server', () => ({ +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { retirePaneAuthority: mocks.retire } })) vi.mock('../agent-hooks/server/server-status-identity', () => ({ isValidPaneKey: (key: string) => key.includes(':') })) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => ({ +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => ({ clearMigrationUnsupportedPtysForPaneKey: mocks.clear })) import { registerAgentPaneAuthorityIpcHandlers } from './agent-pane-authority-ipc' diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index ab2338b0300..264f44a3dc2 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -1,12 +1,12 @@ import { ipcMain } from 'electron' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isValidPaneKey } from '../agent-hooks/server/server-status-identity' import type { AgentStatusCacheIdentity } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import { parseLegacyNumericPaneKey } from '../../shared/workspace-layout/stable-pane-id' import { clearMigrationUnsupportedPtysByTabPrefix, clearMigrationUnsupportedPtysForPaneKey -} from '../agent-hooks/migration-unsupported-pty-state' +} from '../agent-hooks/observations/migration-unsupported-pty-state' import { isValidAgentStatusDropTabId } from './agent-status-ipc-boundary' /** Dismissal preserves live pane caches; confirmed exits must clear latches that could revive a stale working row. */ diff --git a/src/main/ipc/ai-vault/ai-vault.ts b/src/main/ipc/ai-vault/ai-vault.ts index 007e0cb9188..303166c2cf8 100644 --- a/src/main/ipc/ai-vault/ai-vault.ts +++ b/src/main/ipc/ai-vault/ai-vault.ts @@ -117,7 +117,8 @@ async function listAiVaultSessions( ? [...new Set(scopePaths)].sort() : scopePaths, executionHostScope, - includeAntigravityIdeSessions: args?.includeAntigravityIdeSessions === true + includeAntigravityIdeSessions: args?.includeAntigravityIdeSessions === true, + ...(args?.scopeOnly === true ? { scopeOnly: true } : {}) }) const depth = requestedAiVaultSessionDepth(args) const afterFingerprint = @@ -260,9 +261,7 @@ export function registerAiVaultHandlers(options: AiVaultHandlerOptions = {}): vo const controller = listCancellations.begin(event, requestToken) try { await handlerOptions.ensureStructuredSessionOwnership?.() - const result = await listAiVaultSessions(args, { - signal: controller?.signal - }) + const result = await listAiVaultSessions(args, { signal: controller?.signal }) return projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT) } catch (error) { // Expected cancellation is a result so Electron does not log rejected IPC as an error. diff --git a/src/main/ipc/browser/browser-client-host-cookie-import-ipc.ts b/src/main/ipc/browser/browser-client-host-cookie-import-ipc.ts index 3dc2a7afc52..c32676c1686 100644 --- a/src/main/ipc/browser/browser-client-host-cookie-import-ipc.ts +++ b/src/main/ipc/browser/browser-client-host-cookie-import-ipc.ts @@ -6,7 +6,7 @@ import { importCookiesIntoClientRoutePartition } from '../../browser/cookies/client-route/browser-client-route-cookie-import' import { clientRouteCookieImportSources } from '../../browser/cookies/client-route/client-route-cookie-import-source-store' -import { pickCookieFile } from '../../browser/cookies/browser-cookie-import' +import { pickCookieFile } from '../../browser/cookies/imports/cookie-file-picker' import { isTrustedBrowserRenderer } from './browser-renderer-trust' export function registerClientHostCookieImportHandlers(): void { diff --git a/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts b/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts index 052d8a86508..734d9d7cb0b 100644 --- a/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts +++ b/src/main/ipc/browser/browser-client-page-metadata-ipc.test.ts @@ -14,7 +14,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../browser/browser-manager', () => ({ browserManager: {} })) +vi.mock('../../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('./browser-renderer-trust', () => ({ isTrustedBrowserRenderer: (sender: unknown) => mocks.isTrusted(sender) diff --git a/src/main/ipc/browser/browser-extension-context-menu.ts b/src/main/ipc/browser/browser-extension-context-menu.ts index 75e54771123..2b11e4accdd 100644 --- a/src/main/ipc/browser/browser-extension-context-menu.ts +++ b/src/main/ipc/browser/browser-extension-context-menu.ts @@ -2,7 +2,7 @@ import { ipcMain } from 'electron' import { z } from 'zod' import type { BrowserExtensionContextMenuPayload } from '../../../shared/browser/extensions/browser-extension-context-menu-types' import { isChromeExtensionId } from '../../../shared/browser/extensions/browser-extension-url' -import { browserManager } from '../../browser/browser-manager' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' import { buildBrowserExtensionActionContextMenu, runBrowserExtensionContextMenuClick diff --git a/src/main/ipc/browser/browser-grab-ipc.ts b/src/main/ipc/browser/browser-grab-ipc.ts index 7801e9da424..8641b3221f4 100644 --- a/src/main/ipc/browser/browser-grab-ipc.ts +++ b/src/main/ipc/browser/browser-grab-ipc.ts @@ -1,5 +1,5 @@ import { ipcMain } from 'electron' -import { browserManager } from '../../browser/browser-manager' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' import { onDocPreviewGrantRevoked } from '../../browser/document-preview/doc-preview-grant-registry' import { isTrustedBrowserRenderer } from './browser-renderer-trust' import { waitForNextTabRegistration } from './browser-tab-registration-wait' diff --git a/src/main/ipc/browser/browser-guest-view-ipc.ts b/src/main/ipc/browser/browser-guest-view-ipc.ts index 5a5f28a7e73..8a74f492ed5 100644 --- a/src/main/ipc/browser/browser-guest-view-ipc.ts +++ b/src/main/ipc/browser/browser-guest-view-ipc.ts @@ -1,6 +1,6 @@ import { ipcMain, webContents, type IpcMainInvokeEvent } from 'electron' -import { browserManager } from '../../browser/browser-manager' -import { browserSiteDisplayController } from '../../browser/site-settings/browser-site-display-controller' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' +import { browserSiteDisplayController } from '../../browser/site-settings/display/browser-site-display-controller' import { isBrowserPageZoomDirection } from '../../../shared/browser-page-zoom' import { publishBrowserClientPageMetadata } from '../../browser/client-pages/renderer/browser-client-page-metadata-transport' import { diff --git a/src/main/ipc/browser/browser-passwords-ipc-request.ts b/src/main/ipc/browser/browser-passwords-ipc-request.ts index 6fb68a40947..3b04fcf8929 100644 --- a/src/main/ipc/browser/browser-passwords-ipc-request.ts +++ b/src/main/ipc/browser/browser-passwords-ipc-request.ts @@ -1,5 +1,5 @@ import { ipcMain, type IpcMainInvokeEvent } from 'electron' -import { browserSessionRegistry } from '../../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../../browser/sessions/profiles/browser-session-registry' import type { BrowserPasswordStore } from '../../browser-passwords/browser-password-store' import { browserPasswordVaultFor } from '../../browser-passwords/browser-password-vault-access' import { isTrustedBrowserRenderer } from './browser-renderer-trust' diff --git a/src/main/ipc/browser/browser-session-profile-ipc.test.ts b/src/main/ipc/browser/browser-session-profile-ipc.test.ts index b28a889b31c..39d8ad1876f 100644 --- a/src/main/ipc/browser/browser-session-profile-ipc.test.ts +++ b/src/main/ipc/browser/browser-session-profile-ipc.test.ts @@ -16,7 +16,7 @@ const { setBrowserIdentityModeMock: vi.fn(async () => ({ ok: true })) })) -vi.mock('../../browser/identity/browser-identity-mode-store', () => ({ +vi.mock('../../browser/identity/mode/browser-identity-mode-store', () => ({ setBrowserIdentityMode: setBrowserIdentityModeMock, getBrowserIdentityModeStatus: vi.fn(() => ({ identity: {}, migrationNotice: null })) })) @@ -28,14 +28,14 @@ vi.mock('electron', () => ({ webContents: { fromId: vi.fn() } })) -vi.mock('../../browser/browser-manager', () => ({ +vi.mock('../../browser/guest-lifecycle/manager/browser-manager', () => ({ browserCertificateTrustController: { proceed: vi.fn() }, browserManager: { getWebContentsIdByTabId: vi.fn(() => new Map()) } })) -vi.mock('../../browser/sessions/browser-session-registry', () => ({ +vi.mock('../../browser/sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { createProfile: createProfileMock } @@ -45,13 +45,19 @@ vi.mock('../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host getPairedRuntimeBrowserClientRouteIdentity: routeIdentityMock })) -vi.mock('../../browser/cookies/browser-cookie-import', () => ({ +vi.mock('../../browser/cookies/sources/browser-cookie-detection', () => ({ detectInstalledBrowsers: detectBrowsersMock, - importCookiesFromBrowser: vi.fn(), - importCookiesFromFile: vi.fn(), - pickCookieFile: vi.fn(), selectBrowserProfile: vi.fn() })) +vi.mock('../../browser/cookies/browser-cookie-import', () => ({ + importCookiesFromBrowser: vi.fn() +})) +vi.mock('../../browser/cookies/imports/import-cookie-file', () => ({ + importCookiesFromFile: vi.fn() +})) +vi.mock('../../browser/cookies/imports/cookie-file-picker', () => ({ + pickCookieFile: vi.fn() +})) import { registerBrowserHandlers } from './browser' import { setTrustedBrowserRendererWebContentsId } from './browser-renderer-trust' diff --git a/src/main/ipc/browser/browser-session-profile-ipc.ts b/src/main/ipc/browser/browser-session-profile-ipc.ts index 96bb9af1b60..e6d7b471d68 100644 --- a/src/main/ipc/browser/browser-session-profile-ipc.ts +++ b/src/main/ipc/browser/browser-session-profile-ipc.ts @@ -3,31 +3,31 @@ import { browserCookieImportFailure } from '../../../shared/browser-cookie-impor import { registerGoogleCookieClearHandlers } from './browser-google-cookie-clear-ipc' import { registerClientHostCookieImportHandlers } from './browser-client-host-cookie-import-ipc' import { BrowserWindow, ipcMain } from 'electron' -import { browserSessionRegistry } from '../../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../../browser/sessions/profiles/browser-session-registry' import { getPairedRuntimeBrowserClientRouteIdentity } from '../../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' import { isTrustedBrowserRenderer } from './browser-renderer-trust' +import { pickCookieFile } from '../../browser/cookies/imports/cookie-file-picker' +import { importCookiesFromFile } from '../../browser/cookies/imports/import-cookie-file' import { - pickCookieFile, - importCookiesFromFile, detectInstalledBrowsers, - selectBrowserProfile, - importCookiesFromBrowser -} from '../../browser/cookies/browser-cookie-import' + selectBrowserProfile +} from '../../browser/cookies/sources/browser-cookie-detection' +import { importCookiesFromBrowser } from '../../browser/cookies/browser-cookie-import' import type { BrowserCookieImportResult, BrowserSessionProfile, BrowserSessionProfileScope } from '../../../shared/browser-workspace-types' import type { ManagedBrowserProfileOwner } from '../../../shared/browser-profile-scope' -import { ensureManagedBrowserProfile } from '../../browser/sessions/browser-managed-session-profiles' +import { ensureManagedBrowserProfile } from '../../browser/sessions/profiles/browser-managed-session-profiles' import { getBrowserIdentityModeStatus, setBrowserIdentityMode -} from '../../browser/identity/browser-identity-mode-store' +} from '../../browser/identity/mode/browser-identity-mode-store' import { listBrowserSitePermissions, setBrowserSitePermissionDecisions -} from '../../browser/site-settings/browser-site-permission-store' +} from '../../browser/site-settings/permissions/browser-site-permission-store' import { isBrowserSitePermission, isBrowserSitePermissionDecision, diff --git a/src/main/ipc/browser/browser-tab-registration-wait.ts b/src/main/ipc/browser/browser-tab-registration-wait.ts index 7aa9cfdf1da..f62c820132a 100644 --- a/src/main/ipc/browser/browser-tab-registration-wait.ts +++ b/src/main/ipc/browser/browser-tab-registration-wait.ts @@ -1,5 +1,5 @@ import { webContents } from 'electron' -import { browserManager } from '../../browser/browser-manager' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' import { onWorkspaceDocGuestRegistered } from '../../browser/document-preview/doc-preview-guest-policy' // CLI commands wait for mounted guest registration; multiple startup callers may wait on one page. diff --git a/src/main/ipc/browser/browser.test.ts b/src/main/ipc/browser/browser.test.ts index 54d7ddeb3f8..516bbca61c6 100644 --- a/src/main/ipc/browser/browser.test.ts +++ b/src/main/ipc/browser/browser.test.ts @@ -48,7 +48,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../browser/browser-manager', () => ({ +vi.mock('../../browser/guest-lifecycle/manager/browser-manager', () => ({ browserCertificateTrustController: { proceed: proceedCertificateMock }, diff --git a/src/main/ipc/browser/browser.ts b/src/main/ipc/browser/browser.ts index de5ad39ab89..67a9132d84b 100644 --- a/src/main/ipc/browser/browser.ts +++ b/src/main/ipc/browser/browser.ts @@ -1,5 +1,8 @@ import { ipcMain, webContents } from 'electron' -import { browserCertificateTrustController, browserManager } from '../../browser/browser-manager' +import { + browserCertificateTrustController, + browserManager +} from '../../browser/guest-lifecycle/manager/browser-manager' import type { AgentBrowserBridge } from '../../browser/agent-browser/agent-browser-bridge' import { isWorkspaceDocPageId } from '../../browser/document-preview/doc-preview-guest-policy' import { isTrustedBrowserRenderer } from './browser-renderer-trust' @@ -26,7 +29,7 @@ import type { } from '../../../shared/browser-page-prompt' import { respondToBrowserPagePrompt } from '../../browser/guest-lifecycle/prompts/browser-page-prompts' import { recordActiveBrowserPage } from '../../browser/extensions/tabs-and-windows/browser-extension-tab-model' -import { announceRegisteredBrowserExtensionTab } from '../../browser/extensions/api/tabs-lifecycle' +import { announceRegisteredBrowserExtensionTab } from '../../browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle' import { registerBrowserExtensionHandlers } from './browser-extensions' import { registerBrowserExtensionContextMenuHandlers } from './browser-extension-context-menu' import { diff --git a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts index 3d3e6ab5689..3d49028eb70 100644 --- a/src/main/ipc/browser/desktop-browser-bridge-wiring.ts +++ b/src/main/ipc/browser/desktop-browser-bridge-wiring.ts @@ -16,7 +16,7 @@ import { } from '../../../shared/remote-runtime/host-catalog/runtime-environments' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' import { isRemoteCliControlAllowed } from '../../../shared/ssh-remote-cli-control' -import { browserManager } from '../../browser/browser-manager' +import { browserManager } from '../../browser/guest-lifecycle/manager/browser-manager' import { DesktopBrowserBridgeManager, type DesktopBrowserBridgeCandidate diff --git a/src/main/ipc/doc-preview-grant-ipc.ts b/src/main/ipc/doc-preview-grant-ipc.ts index 063ad916545..7231d7722f6 100644 --- a/src/main/ipc/doc-preview-grant-ipc.ts +++ b/src/main/ipc/doc-preview-grant-ipc.ts @@ -6,7 +6,7 @@ import { DOC_PREVIEW_MINT_GRANT_CHANNEL, DOC_PREVIEW_REVOKE_GRANT_CHANNEL } from '../../shared/document-preview/doc-preview-scheme' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { reportDocPreviewLinkClick } from '../browser/document-preview/doc-preview-guest-policy' import { authorizeDocPreviewDirectory, diff --git a/src/main/ipc/ephemeral-vm-recipe-context.ts b/src/main/ipc/ephemeral-vm-recipe-context.ts index 20442fb7826..3990f9827bf 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -96,32 +96,49 @@ export function getRuntimeRecipeContext( runtimeId: string ): { runtime: EphemeralVmRuntimeRecord - repo: Extract + repoPath: string recipe: OrcaVmRecipe } { const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId) if (!runtime) { throw new EphemeralVmFailureError(ephemeralVmFailure('runtimeNotFound', { runtimeId })) } - if (!runtime.repoId) { - throw new EphemeralVmFailureError(ephemeralVmFailure('runtimeRepoMissing', { runtimeId })) - } - const repo = getRecipeRepo(store, runtime.repoId) - if (!repo.ok) { - throw new EphemeralVmFailureError(repo.failure) - } - // Legacy runtimes lack snapshots; never substitute a newer same-ID plugin recipe for their repo-owned recipe. - const recipe = - runtime.recipe ?? - (loadHooks(repo.repo.path)?.environmentRecipes ?? []).find( - (entry) => entry.id === runtime.recipeId + const repo = runtime.repoId ? getRecipeRepo(store, runtime.repoId) : null + if (!repo?.ok) { + // Why: a re-added or removed repo must not strand the VM; the snapshot plus recorded checkout + // path are everything destroy needs (stablyai/orca#17293). Only trust the path while it still + // holds the same recipe, so a different checkout later placed there can't run its scripts. + const fallback = runtime.recipe && runtime.repoPath ? runtime.recipe : null + if (fallback && runtime.repoPath) { + const sameRecipe = (loadHooks(runtime.repoPath)?.environmentRecipes ?? []).some( + (entry) => entry.id === fallback.id && entry.create === fallback.create + ) + if (sameRecipe) { + return { runtime, repoPath: runtime.repoPath, recipe: fallback } + } + } + throw new EphemeralVmFailureError( + repo ? repo.failure : ephemeralVmFailure('runtimeRepoMissing', { runtimeId }) ) + } + const repoRecipe = (loadHooks(repo.repo.path)?.environmentRecipes ?? []).find( + (entry) => entry.id === runtime.recipeId + ) + // Legacy runtimes lack snapshots; never substitute a newer same-ID plugin recipe for their repo-owned recipe. + // Snapshots never persist timeoutSeconds, so take the repo's current limits (lifecycle commands stay + // snapshotted). Only when the repo recipe has the same create command, so a different recipe that + // later took this id (e.g. a repo recipe shadowing a plugin one) cannot impose its limits. + const limits = + repoRecipe?.timeoutSeconds && repoRecipe.create === runtime.recipe?.create + ? { timeoutSeconds: repoRecipe.timeoutSeconds } + : {} + const recipe = runtime.recipe ? { ...runtime.recipe, ...limits } : repoRecipe if (!recipe) { throw new EphemeralVmFailureError( ephemeralVmFailure('recipeNotFound', { recipeId: runtime.recipeId }) ) } - return { runtime, repo, recipe } + return { runtime, repoPath: repo.repo.path, recipe } } export function resolveRecipeForRepo( diff --git a/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts b/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts index 7b1f6e6b2e5..37645f8f1d0 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts @@ -220,3 +220,187 @@ it("retires a recipe server's session partition once its VM is destroyed (#33805 expect(removeEnvironmentMock).toHaveBeenCalledWith(userDataPath, 'env-recipe') expect(removeWorkspaceSessionHost).toHaveBeenCalledWith('runtime:env-recipe') }) + +it('destroys from the recorded snapshot and repo path when the repo id no longer resolves (#17293)', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-handler-')) + const repoPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-repo-')) + tempDirs.push(userDataPath, repoPath) + getPathMock.mockReturnValue(userDataPath) + const destroyedPath = join(repoPath, 'destroyed.txt') + writeFileSync( + join(repoPath, 'destroy.js'), + `require('fs').writeFileSync(${JSON.stringify(destroyedPath)}, process.cwd())` + ) + const recipe = { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: './create.sh', + destroy: `"${process.execPath}" destroy.js` + } + // The checkout still defines the recipe the VM was created from. + writeFileSync( + join(repoPath, 'orca.yaml'), + [ + 'environmentRecipes:', + ' - id: cloud-sandbox', + ' name: Cloud Sandbox', + ' create: ./create.sh' + ].join('\n') + ) + upsertEphemeralVmRuntime(userDataPath, { + id: 'runtime-stale-repo', + recipeId: 'cloud-sandbox', + recipe, + repoId: 'removed-repo', + repoPath, + status: 'cleanup_failed', + cleanupStatus: 'failed', + createdAt: 1, + updatedAt: 1, + recipeResult: { + schemaVersion: 1, + connection: { type: 'orca-server', pairingCode: 'unused', projectRoot: '/workspace/repo' } + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these cleanup paths only read getRepo from the store. + registerEphemeralVmRuntimeHandlers({ getRepo: vi.fn(() => undefined) } as never) + + await expect( + handlers.get('ephemeralVm:getCleanupCommand')?.(null, { runtimeId: 'runtime-stale-repo' }) + ).resolves.toMatchObject({ command: expect.stringContaining('destroy.js') }) + + await expect( + handlers.get('ephemeralVm:cleanup')?.(null, { runtimeId: 'runtime-stale-repo' }) + ).resolves.toMatchObject({ status: 'cleaned', cleanupStatus: 'succeeded' }) + expect(existsSync(destroyedPath)).toBe(true) +}) + +it('refuses the recorded repo path once a different checkout sits there', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-handler-')) + const repoPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-repo-')) + tempDirs.push(userDataPath, repoPath) + getPathMock.mockReturnValue(userDataPath) + const ranPath = join(repoPath, 'ran.txt') + writeFileSync( + join(repoPath, 'destroy.js'), + `require('fs').writeFileSync(${JSON.stringify(ranPath)}, 'x')` + ) + writeFileSync( + join(repoPath, 'orca.yaml'), + [ + 'environmentRecipes:', + ' - id: cloud-sandbox', + ' name: Other', + ' create: ./other.sh' + ].join('\n') + ) + upsertEphemeralVmRuntime(userDataPath, { + id: 'runtime-moved-repo', + recipeId: 'cloud-sandbox', + recipe: { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: './create.sh', + destroy: `"${process.execPath}" destroy.js` + }, + repoId: 'removed-repo', + repoPath, + status: 'running', + cleanupStatus: 'not_started', + createdAt: 1, + updatedAt: 1, + recipeResult: { + schemaVersion: 1, + connection: { type: 'orca-server', pairingCode: 'unused', projectRoot: '/workspace/repo' } + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these cleanup paths only read getRepo from the store. + registerEphemeralVmRuntimeHandlers({ getRepo: vi.fn(() => undefined) } as never) + + await expect( + handlers.get('ephemeralVm:cleanup')?.(null, { runtimeId: 'runtime-moved-repo' }) + ).resolves.toMatchObject({ status: 'cleanup_failed', cleanupLastErrorCode: 'repoNotFound' }) + expect(existsSync(ranPath)).toBe(false) +}) + +it('still refuses cleanup when the repo id is stale and no repo path was recorded', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-handler-')) + tempDirs.push(userDataPath) + getPathMock.mockReturnValue(userDataPath) + upsertEphemeralVmRuntime(userDataPath, { + id: 'runtime-legacy-stale-repo', + recipeId: 'cloud-sandbox', + recipe: { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: 'unused', destroy: 'unused' }, + repoId: 'removed-repo', + status: 'running', + cleanupStatus: 'not_started', + createdAt: 1, + updatedAt: 1, + recipeResult: { + schemaVersion: 1, + connection: { type: 'orca-server', pairingCode: 'unused', projectRoot: '/workspace/repo' } + } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these cleanup paths only read getRepo from the store. + registerEphemeralVmRuntimeHandlers({ getRepo: vi.fn(() => undefined) } as never) + + await expect( + handlers.get('ephemeralVm:cleanup')?.(null, { runtimeId: 'runtime-legacy-stale-repo' }) + ).resolves.toMatchObject({ status: 'cleanup_failed', cleanupLastErrorCode: 'repoNotFound' }) +}) + +it( + "applies the repo recipe's destroy timeout to a snapshot persisted without timeouts", + async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-handler-')) + const repoPath = mkdtempSync(join(tmpdir(), 'orca-vm-runtime-repo-')) + tempDirs.push(userDataPath, repoPath) + getPathMock.mockReturnValue(userDataPath) + writeFileSync(join(repoPath, 'destroy.js'), 'setInterval(() => {}, 1000)') + writeFileSync( + join(repoPath, 'orca.yaml'), + [ + 'environmentRecipes:', + ' - id: cloud-sandbox', + ' name: Cloud Sandbox', + ' create: unused', + ' timeoutSeconds:', + ' destroy: 1' + ].join('\n') + ) + upsertEphemeralVmRuntime(userDataPath, { + id: 'runtime-timeout', + recipeId: 'cloud-sandbox', + recipe: { + id: 'cloud-sandbox', + name: 'Cloud Sandbox', + create: 'unused', + destroy: `"${process.execPath}" destroy.js` + }, + repoId: 'repo-1', + status: 'running', + cleanupStatus: 'not_started', + createdAt: 1, + updatedAt: 1, + recipeResult: { + schemaVersion: 1, + connection: { type: 'orca-server', pairingCode: 'unused', projectRoot: '/workspace/repo' } + } + }) + registerEphemeralVmRuntimeHandlers({ + getRepo: vi.fn(() => ({ + id: 'repo-1', + path: repoPath, + displayName: 'Repo', + badgeColor: '#000', + addedAt: 0 + })) + } as never) + + await expect( + handlers.get('ephemeralVm:cleanup')?.(null, { runtimeId: 'runtime-timeout' }) + ).resolves.toMatchObject({ status: 'cleanup_failed', cleanupLastErrorCode: 'recipeTimedOut' }) + }, + // The destroy step must hit its 1s recipe timeout and then be force-stopped. + 15_000 +) diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index bbe0f63b377..95240974d55 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -22,6 +22,10 @@ import { import { invalidateRuntimeEnvironmentTransport } from './runtime-environments/runtime-environments' import { retireRemovedRuntimeEnvironment } from './runtime-environments/runtime-environment-removal-cleanup' import { attachEphemeralVmRuntimeToWorkspace } from '../ephemeral-vm/runtime-attachment' +import { + forgetInterruptedEphemeralVmProvision, + isEphemeralVmProvisionLive +} from '../ephemeral-vm/runtime-provisioning-persistence' export type EphemeralVmCleanupCommandResult = { runtimeId: string @@ -36,6 +40,7 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { ipcMain.removeHandler('ephemeralVm:listRuntimes') ipcMain.removeHandler('ephemeralVm:cleanup') ipcMain.removeHandler('ephemeralVm:stopCleanup') + ipcMain.removeHandler('ephemeralVm:forgetRuntime') ipcMain.removeHandler('ephemeralVm:getCleanupCommand') ipcMain.handle('ephemeralVm:listRuntimes', (): EphemeralVmRuntimeRecord[] => { @@ -63,8 +68,9 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { if (!runtime) { throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) } - if (!runtime.repoId) { - throw new Error(`Ephemeral VM runtime has no repo id: ${args.runtimeId}`) + if (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) { + // Why: don't mark a create in flight as cleanup_failed; its own outcome settles the row. + throw new Error(`Ephemeral VM runtime is still provisioning: ${runtime.id}`) } let result if (runtime.cleanupStatus === 'succeeded') { @@ -88,7 +94,7 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { } result = await cleanupEphemeralVmRuntime({ userDataPath, - repoPath: resolved.repo.repo.path, + repoPath: resolved.repoPath, recipe: resolved.recipe, runtimeId: runtime.id }) @@ -148,6 +154,10 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { } ) + ipcMain.handle('ephemeralVm:forgetRuntime', (_event, args: { runtimeId: string }): void => { + forgetInterruptedEphemeralVmProvision(app.getPath('userData'), args.runtimeId) + }) + ipcMain.handle( 'ephemeralVm:getCleanupCommand', async (_event, args: { runtimeId: string }): Promise => { @@ -161,7 +171,7 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { projectId: resolved.runtime.projectId, workspaceId: resolved.runtime.workspaceId, workspaceName: resolved.runtime.workspaceName, - repoPath: resolved.repo.repo.path + repoPath: resolved.repoPath }, recipeResult: resolved.runtime.recipeResult }) diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 18826b2d674..e322668b02e 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -13,7 +13,10 @@ import { getProvisionedRootRecipeRepoUrl } from '../../shared/ephemeral-vm-recip // Import the Node-only doctor directly so browser consumers of the barrel do not bundle fs/path. import { doctorEphemeralVmRecipe } from '../../shared/ephemeral-vm-recipe-doctor' import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' -import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import { + requireEphemeralVmRecipeResult, + type EphemeralVmProvisionedRuntimeRecord +} from '../../shared/ephemeral-vm-runtimes' import { addEnvironmentFromPairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-store' import { redactRuntimeEnvironment, @@ -24,6 +27,7 @@ import { provisionEphemeralVmRuntime } from '../ephemeral-vm/runtime-service' import { connectRuntimeOwnedSshTarget } from '../ephemeral-vm/runtime-ssh' +import { reconcileInterruptedEphemeralVmProvisionsOnStartup } from '../ephemeral-vm/runtime-provisioning-persistence' import { getRecipeRepo, listRecipeCatalog, @@ -48,7 +52,7 @@ export type EphemeralVmProvisionIpcResult = | { ok: true connectionType: 'orca-server' - runtime: EphemeralVmRuntimeRecord + runtime: EphemeralVmProvisionedRuntimeRecord environment: PublicKnownRuntimeEnvironment stderr: string warnings: EphemeralVmRecipeResultWarning[] @@ -56,7 +60,7 @@ export type EphemeralVmProvisionIpcResult = | { ok: true connectionType: 'ssh' - runtime: EphemeralVmRuntimeRecord + runtime: EphemeralVmProvisionedRuntimeRecord sshTargetId: string /** The managed Orca server the host runs; its workspace lives there. */ environmentId?: string @@ -77,6 +81,7 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin ipcMain.removeHandler('ephemeralVm:provision') ipcMain.removeHandler('ephemeralVm:cancelProvision') registerEphemeralVmRuntimeHandlers(store) + reconcileInterruptedEphemeralVmProvisionsOnStartup(app.getPath('userData')) ipcMain.handle('ephemeralVm:listRecipes', async (_event, args: { repoId: string }) => { return listRecipes(store, args.repoId, await getApprovedPluginVmRecipes(pluginService)) @@ -209,13 +214,11 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin runtimeId: result.runtime.id, connection }) - const runtime = updateEphemeralVmRuntimeStatus( - app.getPath('userData'), - result.runtime.id, - { + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { sshTargetId: ssh.targetId, runtimeEnvironmentId: ssh.environmentId - } + }) ) return { ok: true, @@ -264,9 +267,11 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) } } - const runtime = updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { - runtimeEnvironmentId: environment.id - }) + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { + runtimeEnvironmentId: environment.id + }) + ) return { ok: true, connectionType: 'orca-server', diff --git a/src/main/ipc/pty-claude-agent-view-readiness.test.ts b/src/main/ipc/pty-claude-agent-view-readiness.test.ts index 8a3fcfe6a53..0247392ffbe 100644 --- a/src/main/ipc/pty-claude-agent-view-readiness.test.ts +++ b/src/main/ipc/pty-claude-agent-view-readiness.test.ts @@ -18,7 +18,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -42,7 +42,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts index 620ca2bcb3f..b46881130cb 100644 --- a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts +++ b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts @@ -21,7 +21,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -45,7 +45,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts index bc7f682dc22..d5139e457ab 100644 --- a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts +++ b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts @@ -24,7 +24,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -48,7 +48,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/delivery/attached-pty-size.ts b/src/main/ipc/pty/delivery/attached-pty-size.ts index 14816e28fa9..2277d3fa79a 100644 --- a/src/main/ipc/pty/delivery/attached-pty-size.ts +++ b/src/main/ipc/pty/delivery/attached-pty-size.ts @@ -24,6 +24,17 @@ export function shouldSeedPreAttachPtySize(args: { } /** Attach does not resize the PTY; prefer proven provider/cached geometry over the pane request. */ +function resolveAttachedPtySize(args: { + result: Pick + cachedBeforeAttach: PtyGrid | undefined +}): PtyGrid | undefined { + return ( + positiveGrid(args.result.attachedGrid?.cols, args.result.attachedGrid?.rows) ?? + positiveGrid(args.result.snapshotCols, args.result.snapshotRows) ?? + positiveGrid(args.cachedBeforeAttach?.cols, args.cachedBeforeAttach?.rows) + ) +} + export function resolveCommittedPtySize(args: { result: Pick requested: PtyGrid @@ -32,12 +43,7 @@ export function resolveCommittedPtySize(args: { if (args.result.isReattach !== true) { return args.requested } - return ( - positiveGrid(args.result.attachedGrid?.cols, args.result.attachedGrid?.rows) ?? - positiveGrid(args.result.snapshotCols, args.result.snapshotRows) ?? - positiveGrid(args.cachedBeforeAttach?.cols, args.cachedBeforeAttach?.rows) ?? - args.requested - ) + return resolveAttachedPtySize(args) ?? args.requested } type HeadlessReflow = ((ptyId: string, cols: number, rows: number) => void) | undefined @@ -70,3 +76,22 @@ export function commitAttachedPtySize(args: { reflowHeadlessTerminalToCommittedGrid({ ...args, committedSize }) return committedSize } + +/** A rendererless attach has no pane request, so commit only geometry the attach proved. */ +export function commitRuntimeAttachedPtySize( + result: PtySpawnResult, + reflowHeadlessTerminalToPtyGrid: HeadlessReflow +): void { + const committedSize = resolveAttachedPtySize({ + result, + cachedBeforeAttach: ptySizes.get(result.id) + }) + if (committedSize) { + ptySizes.set(result.id, committedSize) + reflowHeadlessTerminalToCommittedGrid({ + result, + committedSize, + reflowHeadlessTerminalToPtyGrid + }) + } +} diff --git a/src/main/ipc/pty/host-env/assembly.ts b/src/main/ipc/pty/host-env/assembly.ts index 127ed52945f..8fbb59ecc82 100644 --- a/src/main/ipc/pty/host-env/assembly.ts +++ b/src/main/ipc/pty/host-env/assembly.ts @@ -8,8 +8,8 @@ import { import { applyTerminalGitCredentialPromptGuard } from '../../../../shared/shell/launch/terminal-git-credential-guard' import { ensureOpenCodeStartupPromptForLaunch } from '../../../opencode/opencode-startup-prompt-installer' import { mimoCodeHookService } from '../../../mimo/hook-service' -import { agentHookServer } from '../../../agent-hooks/server' -import { wslHookRelayManager } from '../../../agent-hooks/wsl-hook-relay-manager' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { wslHookRelayManager } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { wslInteropHealthMonitor } from '../../../wsl/execution/wsl-interop-health' import { piTitlebarExtensionService } from '../../../pi/titlebar-extension-service' import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' diff --git a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts index 658c0a4b087..daa8444df1d 100644 --- a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts +++ b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts @@ -9,10 +9,10 @@ const fixture = vi.hoisted(() => ({ userData: '', guestOverlay: '' })) vi.mock('../../../../shared/app-environment', () => ({ getAppEnvironment: () => ({ getPath: () => fixture.userData, onWillQuit: vi.fn() }) })) -vi.mock('../../../agent-hooks/server', () => ({ +vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { buildPtyEnv: () => ({ ORCA_AGENT_HOOK_PORT: '12345' }) } })) -vi.mock('../../../agent-hooks/wsl-hook-relay-manager', () => ({ +vi.mock('../../../agent-hooks/wsl-relay/wsl-hook-relay-manager', () => ({ wslHookRelayManager: { ensureForDistro: vi.fn(), getGuestEndpointFilePath: () => '/guest/endpoint.json', diff --git a/src/main/ipc/pty/host-env/saved-resume-admission.ts b/src/main/ipc/pty/host-env/saved-resume-admission.ts index 1db28b59d9d..a96c8a5548b 100644 --- a/src/main/ipc/pty/host-env/saved-resume-admission.ts +++ b/src/main/ipc/pty/host-env/saved-resume-admission.ts @@ -15,7 +15,7 @@ import { agentSessionLeasePossiblyWriting, listStructuredProviderSessionOwnership } from '../../../native-chat/agent-session-wire/host/structured-provider-session-ownership' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { diff --git a/src/main/ipc/pty/host-env/spawn-env-keys.ts b/src/main/ipc/pty/host-env/spawn-env-keys.ts index a4cbe0489e5..53e60eccc0c 100644 --- a/src/main/ipc/pty/host-env/spawn-env-keys.ts +++ b/src/main/ipc/pty/host-env/spawn-env-keys.ts @@ -1,5 +1,9 @@ import { ORCA_AGENT_SESSION_ID_ENV } from '../../../../shared/agent-session/lifecycle/agent-session-caller-env' import { ORCA_STRUCTURED_SESSION_ENV } from '../../../../shared/structured-session-marker' +import { + ORCA_SCRUB_SAFE_LAUNCH_ENV, + ORCA_SCRUB_SAFE_PANE_ENV +} from '../../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' export const AGENT_HOOK_RUNTIME_ENV_KEYS = [ 'ORCA_AGENT_HOOK_PORT', @@ -12,6 +16,16 @@ export const AGENT_HOOK_RUNTIME_ENV_KEYS = [ 'ORCA_CLAUDE_AGENT_STATUS_SETTINGS' ] as const +export const AGENT_PANE_HOOK_ENV_KEYS = [ + 'ORCA_PANE_KEY', + 'ORCA_TAB_ID', + 'ORCA_WORKTREE_ID', + 'ORCA_AGENT_LAUNCH_TOKEN', + ORCA_SCRUB_SAFE_PANE_ENV, + ORCA_SCRUB_SAFE_LAUNCH_ENV, + ...AGENT_HOOK_RUNTIME_ENV_KEYS +] as const + // Inherited Claude child stamps make an independent pane act as the launching session's child. export const CLAUDE_CHILD_SESSION_STAMP_ENV_KEYS = [ 'CLAUDECODE', diff --git a/src/main/ipc/pty/ipc/write.ts b/src/main/ipc/pty/ipc/write.ts index 30e67581775..99d03f47301 100644 --- a/src/main/ipc/pty/ipc/write.ts +++ b/src/main/ipc/pty/ipc/write.ts @@ -3,6 +3,7 @@ import { getPtyIpc } from '../pty-host-bindings' import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' import { createPtyWriteInput } from './write-input' import { installPtyTerminalAttentionIpcHandler } from './terminal-attention' +import { observeTerminalUserInput } from '../../../telemetry/protected-milestones' export function installPtyWriteIpcHandlers(deps: { mainWindow?: PtyRendererDelivery @@ -22,6 +23,13 @@ export function installPtyWriteIpcHandlers(deps: { // Input from every client lands here; agent sleep reads it back with who else is viewing. installPtyTerminalAttentionIpcHandler(deps) + ipcMain.removeAllListeners('pty:noteUserInput') + ipcMain.on('pty:noteUserInput', (event) => { + if (isPtyWriteEventFromMainWindow(event)) { + observeTerminalUserInput() + } + }) + ipcMain.on('pty:write', (event, args: unknown) => { if (!isPtyWriteEventFromMainWindow(event) || !isPtyWritePayload(args)) { return diff --git a/src/main/ipc/pty/pane/complete-pane-adoption.ts b/src/main/ipc/pty/pane/complete-pane-adoption.ts index a2d1059cf14..baed9d5cd85 100644 --- a/src/main/ipc/pty/pane/complete-pane-adoption.ts +++ b/src/main/ipc/pty/pane/complete-pane-adoption.ts @@ -21,8 +21,8 @@ import { } from './agent-session-owners' import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore' import { admitProviderReattachLaunchIdentity } from './launch-authority' -import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-hook-relay-reattach' -import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' +import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import '../spawn-outcome' import { provenSpawnResponse } from '../../../../shared/terminal/pty/lifecycle/terminal-spawn-response' import { ptySizes } from '../delivery/visibility-state' diff --git a/src/main/ipc/pty/pane/resume-launch-identity.ts b/src/main/ipc/pty/pane/resume-launch-identity.ts index fb7645125ce..34603b6057a 100644 --- a/src/main/ipc/pty/pane/resume-launch-identity.ts +++ b/src/main/ipc/pty/pane/resume-launch-identity.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { isResumableTuiAgent, normalizeAgentProviderSession diff --git a/src/main/ipc/pty/provider/bind-listeners.ts b/src/main/ipc/pty/provider/bind-listeners.ts index b8813dba24e..a9934a91fcc 100644 --- a/src/main/ipc/pty/provider/bind-listeners.ts +++ b/src/main/ipc/pty/provider/bind-listeners.ts @@ -1,5 +1,5 @@ import { isCurrentPtyExit, ptyOwnership } from './ownership-state' -import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import { localBackgroundStreamUnsub, localDataUnsub, diff --git a/src/main/ipc/pty/provider/local-configure.ts b/src/main/ipc/pty/provider/local-configure.ts index 9e9dc71a9ab..0126e7d6053 100644 --- a/src/main/ipc/pty/provider/local-configure.ts +++ b/src/main/ipc/pty/provider/local-configure.ts @@ -26,7 +26,7 @@ import { localProvider } from './registry' import { clearProviderPtyState } from './state-cleanup' import { visibleRendererPtys } from '../delivery/visibility-state' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { awaitExplicitAgentPluginGuestReadiness } from '../../../agent-hooks/wsl-agent-plugin-readiness' +import { awaitExplicitAgentPluginGuestReadiness } from '../../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness' import { prepareAntigravityAccountForLaunch } from '../../../antigravity/native-account-launch' export function configureLocalPtyProvider(args: { diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 304e615ce49..59a9b1bfbe3 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -3,8 +3,8 @@ import { unregisterPty } from '../../../memory/pty-registry' import { forgetCodexPaneAccount } from '../../../codex/configuration/homes/codex-pane-account-registry' import { openCodeHookService } from '../../../opencode/hook-service' import { piTitlebarExtensionService } from '../../../pi/titlebar-extension-service' -import { agentHookServer } from '../../../agent-hooks/server' -import { clearMigrationUnsupportedPty } from '../../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPty } from '../../../agent-hooks/observations/migration-unsupported-pty-state' import { clearNativeWindowsConptyPty } from '../../../runtime/terminal/output/terminal-model-query-authority' import { clearHiddenRendererPtyDeliveryState, diff --git a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts index 7022d13def6..17b5a04200b 100644 --- a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts +++ b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts @@ -24,7 +24,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -48,7 +48,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts index b048a49e775..631df8b569e 100644 --- a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts +++ b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts @@ -17,7 +17,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -41,7 +41,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts index c528fb4adc1..5079597303f 100644 --- a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts +++ b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts index da3ff0c83fe..44f80f22199 100644 --- a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts +++ b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => @@ -48,7 +48,7 @@ vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => vi.mock('../../codex/history/index/codex-state-db-backfill-recovery', () => import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock()) ) -vi.mock('../../agent-hooks/wsl-agent-plugin-readiness', () => ({ +vi.mock('../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness', () => ({ awaitExplicitAgentPluginGuestReadiness: vi.fn(async () => true) })) diff --git a/src/main/ipc/pty/pty-ipc-provider-fixtures.ts b/src/main/ipc/pty/pty-ipc-provider-fixtures.ts index bf744f6187b..1b9b89c307b 100644 --- a/src/main/ipc/pty/pty-ipc-provider-fixtures.ts +++ b/src/main/ipc/pty/pty-ipc-provider-fixtures.ts @@ -257,6 +257,7 @@ export function createPtyIpcProviderFixtures(ctx: { mainWindow: unknown }) { createPreAllocatedTerminalHandle: vi.fn(() => 'term_recovered'), registerPreAllocatedHandleForPty: vi.fn(), registerPty: vi.fn(), + reflowHeadlessTerminalToPtyGrid: vi.fn(), ...runtimeOverrides } registerPtyHandlers(mainWindow as never, runtime as never) diff --git a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts index 10594388c61..42cbace177e 100644 --- a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts +++ b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts @@ -16,7 +16,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -40,7 +40,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-pane-restart-replace.test.ts b/src/main/ipc/pty/pty-pane-restart-replace.test.ts index 16b851d9ba9..025d9c87195 100644 --- a/src/main/ipc/pty/pty-pane-restart-replace.test.ts +++ b/src/main/ipc/pty/pty-pane-restart-replace.test.ts @@ -20,7 +20,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -44,7 +44,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts index 1b8e8b59a22..a519ac4c3f2 100644 --- a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts +++ b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts index 5a6fb9eca9f..afe9e6f188b 100644 --- a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts +++ b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts index 159ca4d5809..0e3c9c93970 100644 --- a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts +++ b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts index cbf3378f656..374fcd7c691 100644 --- a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts +++ b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts @@ -17,7 +17,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -44,7 +44,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts index 6d69d721072..91dbd5afd6b 100644 --- a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts +++ b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts @@ -21,7 +21,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -45,7 +45,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-write-ipc-validation.test.ts b/src/main/ipc/pty/pty-write-ipc-validation.test.ts index 6766181cba9..56c13db1847 100644 --- a/src/main/ipc/pty/pty-write-ipc-validation.test.ts +++ b/src/main/ipc/pty/pty-write-ipc-validation.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it, vi } from 'vitest' -import { spawnMock } from './pty-ipc-mock-registry' +import { onMock, spawnMock } from './pty-ipc-mock-registry' import { setupPtyIpcSuite } from './pty-ipc-test-harness' import { registerPtyHandlers } from './register-handlers' +import { bindSession } from '../../telemetry/protected-milestones' vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock())) vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock())) @@ -15,7 +16,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +40,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => @@ -59,6 +60,28 @@ describe('registerPtyHandlers', () => { getPtyWriteListener } = setupPtyIpcSuite() + it('admits a terminal user activity observation only from the main window', () => { + const captured: string[] = [] + const settings = { telemetry: { protectedMilestones: { installCohort: 'existing' } } } + const store = { getSettings: () => settings, updateSettings: () => undefined } + bindSession( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture supplies all store methods read by milestone capture. + store as never, + (name) => captured.push(name), + () => true + ) + registerPtyHandlers(mainWindow as never) + const listener = onMock.mock.calls.find(([name]) => name === 'pty:noteUserInput')?.[1] + if (!listener) { + throw new Error('missing terminal user input listener') + } + + listener(foreignWindowIpcEvent) + expect(captured).toEqual([]) + listener(mainWindowIpcEvent) + expect(captured).toEqual(['meaningful_activity_day']) + }) + it('rejects malformed and cross-window pty write IPC before provider writes', async () => { const mockProc = createMockProc() spawnMock.mockReturnValue(mockProc.proc) diff --git a/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts b/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts new file mode 100644 index 00000000000..0560479dd33 --- /dev/null +++ b/src/main/ipc/pty/runtime/attach-hermes-mailbox.test.ts @@ -0,0 +1,119 @@ +import '../../../runtime/rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { settledWriteStub } from '../../../providers/settled-pty-write-stub' +import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import { createRootDispatch } from '../../../runtime/orchestration/db/root-dispatch-test-fixture' +import { + createRuntime, + PANE_KEY, + PTY_ID, + TERMINAL_HANDLE +} from '../../../runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness' +import { ptySizes } from '../delivery/visibility-state' +import { getLocalPtyProvider, setLocalPtyProvider } from '../provider/registry' +import { attachPtyFromRuntimeController, getSizeFromRuntimeController } from './operations' +import type { PtyRuntimeControllerDeps } from './controller-deps' + +const originalProvider = getLocalPtyProvider() + +afterEach(() => { + setLocalPtyProvider(originalProvider) + ptySizes.delete(PTY_ID) + vi.useRealTimers() +}) + +describe('mail to a Hermes terminal attached without a renderer', () => { + it.each([ + ['status', '─ ready │ grok 4.7 │ 150k tokens\r\n❯', true], + ['reply', '─ ready │ grok 4.7 │ 150k tokens\r\n❯', true], + ['draft', '─ ready │ grok 4.7 │ 150k tokens\r\n❯ unsent draft', false], + ['busy', '─ thinking │ grok 4.7 │ 150k tokens\r\n❯ Ctrl+C to interrupt…', false] + ] as const)( + 'handles %s mail after attach without submitting a draft or busy composer', + async (kind, screen, ready) => { + vi.useFakeTimers() + const db = new OrchestrationDb(':memory:') + try { + const { runtime } = createRuntime(db, { headless: true, launchAgent: 'hermes' }) + const write = vi.fn((_id: string, data: string) => { + if (data.includes('You have')) { + runtime.onPtyData( + PTY_ID, + '\x1b]1;✓ Run Orca dispatched worker …\x07\x1b]2;✓ Run Orca dispatched worker … · grok-4.7 · ~/workspace\x07', + Date.now() + ) + } + return true + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach reads only this provider's attach method. + const provider = { + attach: async () => ({ + id: PTY_ID, + isReattach: true, + snapshot: screen, + snapshotCols: 120, + snapshotRows: 40 + }) + } as unknown as IPtyProvider + setLocalPtyProvider(provider) + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: () => true, + getForegroundProcess: async () => 'hermes', + getSize: getSizeFromRuntimeController + }) + const run = db.createRun({ + objective: 'wake attached worker', + coordinatorHandle: 'term_coordinator', + coordinatorPaneKey: 'coordinator:leaf' + }) + const task = db.createTask({ spec: 'Wait for guidance', runId: run.id }) + const dispatch = createRootDispatch(db, task.id, TERMINAL_HANDLE, PANE_KEY) + const mailbox = `dispatch:${dispatch.id}` + const message = + kind === 'reply' + ? db.answerQuestion({ + messageId: db.createQuestion({ + runId: run.id, + dispatchId: dispatch.id, + askerHandle: TERMINAL_HANDLE, + question: 'Ready?' + }).message.id, + runId: run.id, + consumerGeneration: run.consumer_generation, + body: 'Continue' + }).message + : db.insertMessage({ + from: 'term_coordinator', + to: mailbox, + subject: 'Continue', + runId: run.id + }) + + // Only attach and restored output: no renderer spawn or resize populates the size cache. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach needs runtime; its delivery callbacks are optional. + const deps = { runtime } as unknown as PtyRuntimeControllerDeps + expect(await attachPtyFromRuntimeController(deps, PTY_ID)).toBe(true) + expect(ptySizes.get(PTY_ID)).toEqual({ cols: 120, rows: 40 }) + await runtime.serializeMainTerminalBuffer(PTY_ID) + runtime.notifyMessageArrived(mailbox, 'status') + await vi.advanceTimersByTimeAsync(1000) + + if (ready) { + expect(write.mock.calls.map(([, data]) => data)).toEqual([ + expect.stringContaining('You have 1 orchestration message'), + '\r' + ]) + expect(db.getMessageById(message.id)?.delivered_at).toEqual(expect.any(String)) + } else { + expect(write).not.toHaveBeenCalled() + expect(db.getMessageById(message.id)?.delivered_at).toBeNull() + } + } finally { + db.close() + } + } + ) +}) diff --git a/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts b/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts new file mode 100644 index 00000000000..3dab1eea59c --- /dev/null +++ b/src/main/ipc/pty/runtime/attach-quiet-agent-mailbox.test.ts @@ -0,0 +1,111 @@ +import '../../../runtime/rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { settledWriteStub } from '../../../providers/settled-pty-write-stub' +import type { IPtyProvider } from '../../../providers/pty-provider-contract' +import { OrchestrationDb } from '../../../runtime/orchestration/db/orchestration-db' +import { createRootDispatch } from '../../../runtime/orchestration/db/root-dispatch-test-fixture' +import { + createRuntime, + PANE_KEY, + PTY_ID, + TERMINAL_HANDLE +} from '../../../runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-test-harness' +import { ptySizes } from '../delivery/visibility-state' +import { getLocalPtyProvider, setLocalPtyProvider } from '../provider/registry' +import { attachPtyFromRuntimeController, getSizeFromRuntimeController } from './operations' +import type { PtyRuntimeControllerDeps } from './controller-deps' + +const originalProvider = getLocalPtyProvider() + +afterEach(() => { + setLocalPtyProvider(originalProvider) + ptySizes.delete(PTY_ID) + vi.useRealTimers() +}) + +const HERMES_READY = + '\x1b]2;\u2713 Coordinate dispatched worker \u2026 \u00b7 gpt-6.1-sol \u00b7 ~/ws\x07' + + '\u2500 ready \u2502 gpt 6.1 sol \u2502 7k/500k \u2502 4m 45s\r\n\u276f' +const RULE = '\u2500'.repeat(40) +const CLINE_READY = `${RULE}\r\n\u276f What can I do for you?\r\n${RULE}\r\n\u25cb Plan \u25cf Act (Tab)` + +async function mailAfterQuietAttach( + agent: 'hermes' | 'cline', + snapshot: string, + afterAttach: (runtime: ReturnType['runtime']) => Promise +): Promise<{ writes: string[]; delivered: boolean }> { + vi.useFakeTimers() + const db = new OrchestrationDb(':memory:') + try { + const { runtime } = createRuntime(db, { headless: true, launchAgent: agent }) + const write = vi.fn((_id: string, _data: string) => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach reads only this provider's attach method. + const provider = { + attach: async () => ({ + id: PTY_ID, + isReattach: true, + snapshot, + snapshotCols: 120, + snapshotRows: 40 + }) + } as unknown as IPtyProvider + setLocalPtyProvider(provider) + runtime.setPtyController({ + write, + writeWithSettlement: settledWriteStub(write), + kill: () => true, + getForegroundProcess: async () => agent, + getSize: getSizeFromRuntimeController + }) + const run = db.createRun({ + objective: 'wake quiet worker', + coordinatorHandle: 'term_coordinator', + coordinatorPaneKey: 'coordinator:leaf' + }) + const task = db.createTask({ spec: 'Wait for guidance', runId: run.id }) + const dispatch = createRootDispatch(db, task.id, TERMINAL_HANDLE, PANE_KEY) + const mailbox = `dispatch:${dispatch.id}` + const message = db.insertMessage({ + from: 'term_coordinator', + to: mailbox, + subject: 'Continue', + runId: run.id + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: attach needs runtime; its delivery callbacks are optional. + const deps = { runtime } as unknown as PtyRuntimeControllerDeps + expect(await attachPtyFromRuntimeController(deps, PTY_ID)).toBe(true) + await runtime.serializeMainTerminalBuffer(PTY_ID) + await afterAttach(runtime) + runtime.notifyMessageArrived(mailbox, 'status') + await vi.advanceTimersByTimeAsync(60_000) + return { + writes: write.mock.calls.map(([, data]) => data), + delivered: typeof db.getMessageById(message.id)?.delivered_at === 'string' + } + } finally { + db.close() + } +} + +describe('mail to a quiet idle agent after a runtime restart', () => { + // Real Hermes 0.23 writes its OSC title only on a state change, so a worker idle before the + // restart sends no title after reattach; only its ready screen and seeded title are known. + it('types and submits the pointer to Hermes without a fresh title', async () => { + expect(await mailAfterQuietAttach('hermes', HERMES_READY, async () => {})).toEqual({ + writes: [expect.stringContaining('You have 1 orchestration message'), '\r'], + delivered: true + }) + }) + + // A quiet-gated ready rule must still settle once a redraw soon after attach has gone quiet. + it('submits to Cline once its ready screen is quiet after a redraw', async () => { + const result = await mailAfterQuietAttach('cline', CLINE_READY, async (runtime) => { + await vi.advanceTimersByTimeAsync(2_000) + runtime.onPtyData(PTY_ID, '\x1b[H', Date.now()) + }) + expect(result).toEqual({ + writes: [expect.stringContaining('You have 1 orchestration message'), '\r'], + delivered: true + }) + }) +}) diff --git a/src/main/ipc/pty/runtime/operations.ts b/src/main/ipc/pty/runtime/operations.ts index 3c8907d9218..2c8d627c2d8 100644 --- a/src/main/ipc/pty/runtime/operations.ts +++ b/src/main/ipc/pty/runtime/operations.ts @@ -5,9 +5,8 @@ import { LocalPtyProvider } from '../../../providers/local-pty/local-pty-provide import { ptyOwnership } from '../provider/ownership-state' import { isRendererViewShowingPty, ptySizes } from '../delivery/visibility-state' import { isHiddenRendererPty } from '../delivery/pty-hidden-delivery-gate' -import { seedTerminalRestoreRecordsFromSpawnResult } from '../pane/agent-session-owners' -import { seedHeadlessTerminalFromSpawnResult } from '../pane/terminal-spawn-restore' import { hideRuntimeOwnedRendererDelivery } from './spawn-hidden-delivery' +import { seedAttachedRuntimeTerminal } from './seed-attached-runtime-terminal' import { rendererSerializerReadiness } from '../pane/serializer-state' import { getProviderForPty, localProvider, resolvePtyExecutionHost } from '../provider/registry' import { inspectPtyProviderProcess } from '../../../providers/pty-process-inspection' @@ -138,6 +137,7 @@ export async function attachPtyFromRuntimeController( } try { const sequenceBeforeProviderAttach = deps.runtime?.getPtyOutputSequence?.(ptyId) ?? 0 + const sizeBeforeAttach = ptySizes.get(ptyId) const attachResult = await provider.attach(ptyId) if (attachResult?.providerSequence) { deps.runtime?.synchronizePtyOutputSequenceFromProvider?.( @@ -147,9 +147,7 @@ export async function attachPtyFromRuntimeController( ) } if (attachResult) { - // A restarted runtime has never seen this screen; an idle agent may print nothing after attach. - seedHeadlessTerminalFromSpawnResult(deps.runtime, attachResult, null) - seedTerminalRestoreRecordsFromSpawnResult(deps.runtime, attachResult) + seedAttachedRuntimeTerminal(deps.runtime, attachResult, sizeBeforeAttach) } deps.syncPtyBackgroundedDelivery?.(ptyId, 'main-attach') return true diff --git a/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts b/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts new file mode 100644 index 00000000000..e60f68e1f56 --- /dev/null +++ b/src/main/ipc/pty/runtime/seed-attached-runtime-terminal.ts @@ -0,0 +1,25 @@ +import type { PtySpawnResult } from '../../../providers/pty-provider-contract' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { commitRuntimeAttachedPtySize, type PtyGrid } from '../delivery/attached-pty-size' +import { ptySizes } from '../delivery/visibility-state' +import { seedTerminalRestoreRecordsFromSpawnResult } from '../pane/agent-session-owners' +import { seedHeadlessTerminalFromSpawnResult } from '../pane/terminal-spawn-restore' + +/** Commit the attached grid, then seed the screen a restarted runtime has never seen. */ +export function seedAttachedRuntimeTerminal( + runtime: OrcaRuntimeService | undefined, + result: PtySpawnResult, + sizeBeforeAttach: PtyGrid | undefined +): void { + const sizeNow = ptySizes.get(result.id) + // Identity, not dimensions: A→B→A publishes a new entry that still measures A. + const resizeLanded = sizeNow !== undefined && sizeNow !== sizeBeforeAttach + if (!resizeLanded) { + commitRuntimeAttachedPtySize(result, runtime?.reflowHeadlessTerminalToPtyGrid.bind(runtime)) + } + seedHeadlessTerminalFromSpawnResult(runtime, result, null) + seedTerminalRestoreRecordsFromSpawnResult(runtime, result) + if (resizeLanded && sizeNow) { + runtime?.resizeHeadlessTerminalToPtyGrid(result.id, sizeNow.cols, sizeNow.rows) + } +} diff --git a/src/main/ipc/pty/spawn-begin.ts b/src/main/ipc/pty/spawn-begin.ts index 81449867661..bce2c924b93 100644 --- a/src/main/ipc/pty/spawn-begin.ts +++ b/src/main/ipc/pty/spawn-begin.ts @@ -10,7 +10,7 @@ import { ptyOwnership, ptyIncarnationById } from './provider/ownership-state' import { attachOnlyViewOf } from './pane/attach-only-view' import { pendingRuntimePaneCreatesByOwnerKey } from './pane/spawn-reservation' import { getConnectionExecutionHostId } from '../../../shared/execution-host' -import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-hook-relay-reattach' +import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' export async function beginPtySpawn( ctx: PtySpawnOperationState, diff --git a/src/main/ipc/pty/spawn-commit-publication.ts b/src/main/ipc/pty/spawn-commit-publication.ts index 20c78142206..e7ea0595e92 100644 --- a/src/main/ipc/pty/spawn-commit-publication.ts +++ b/src/main/ipc/pty/spawn-commit-publication.ts @@ -1,5 +1,5 @@ -import { agentHookServer } from '../../agent-hooks/server' -import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { registerPty } from '../../memory/pty-registry' import type { PtySpawnResult } from '../../providers/pty-provider-contract' import { diff --git a/src/main/ipc/pty/spawn-execute.ts b/src/main/ipc/pty/spawn-execute.ts index be3d9dffb4d..fe9fd40396a 100644 --- a/src/main/ipc/pty/spawn-execute.ts +++ b/src/main/ipc/pty/spawn-execute.ts @@ -1,6 +1,6 @@ import type { PtySpawnResult } from '../../providers/pty-provider-contract' import { ptyIncarnationById } from './provider/ownership-state' -import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-hook-relay-reattach' +import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' import { noteWslDistroWoken, noteWslDistrosRunning @@ -29,7 +29,7 @@ import { failPtySpawnExecute } from './spawn-execute-failure' import type { PtySpawnOperationState, PtySpawnExecutionFacts } from './spawn-operation-state' import { excludeReplacedPaneOwner } from './pane/replaced-pane-owner' import { attachViewWithoutOwner } from './pane/attach-only-view' -import { wslBridgePtyPresence } from '../../agent-hooks/wsl-bridge-pty-presence' +import { wslBridgePtyPresence } from '../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import { isWslTerminalSpawn } from './wsl-terminal-spawn' export async function executePtySpawn( diff --git a/src/main/ipc/pty/spawn-host-env.ts b/src/main/ipc/pty/spawn-host-env.ts index f6d26aa7dc3..34f34419955 100644 --- a/src/main/ipc/pty/spawn-host-env.ts +++ b/src/main/ipc/pty/spawn-host-env.ts @@ -8,7 +8,7 @@ import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' import { addWslEnvKeys } from '../../../shared/wsl-env' import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-agent-plugin-readiness' +import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness' import { ensureCodexStateDbBackfillRecoveryStarted } from '../../codex/history/index/codex-state-db-backfill-recovery' import type { CodexSessionResumePreparation } from '../../codex/history/resume/codex-session-resume-home' import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' diff --git a/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts b/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts index 8e6847dac3b..ca610dc9592 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-federated-read-routing.test.ts @@ -4,6 +4,11 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + createSharedControlTestServer, + closeSharedControlTestServers +} from '../../../shared/remote-runtime/control/remote-runtime-shared-control-test-server' +import type { sendRemoteRuntimeRequestWithStatusPreflight as StatusPreflight } from '../../../shared/remote-runtime/remote-runtime-client' import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/protocol-version' import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' @@ -41,6 +46,10 @@ vi.mock('./runtime-environment-request-connections', async () => { import { callRuntimeEnvironment } from './runtime-environment-transport-routing' import { resetSharedControlSupport } from './runtime-environment-shared-control-support' +const actual = await vi.importActual<{ + sendRemoteRuntimeRequestWithStatusPreflight: typeof StatusPreflight +}>('../../../shared/remote-runtime/remote-runtime-client') + describe('federated read RPC transport routing', () => { let userDataPath: string let environmentId: string @@ -62,7 +71,8 @@ describe('federated read RPC transport routing', () => { sendRemoteRuntimeSharedControlRequestMock.mockReset() }) - afterEach(() => { + afterEach(async () => { + await closeSharedControlTestServers() resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) @@ -196,25 +206,22 @@ describe('federated read RPC transport routing', () => { }) it('refuses a runtime-pinned one-shot mutation when its socket reaches a restarted host', async () => { - markEnvironmentUsed(userDataPath, environmentId, { runtimeId: 'runtime-proven' }) - const mutationSent = vi.fn() + const server = await createSharedControlTestServer({ + resultForRequest: (method) => + method === 'status.get' ? { runtimeId: 'runtime-restarted', capabilities: [] } : {} + }) + const paired = addEnvironmentFromPairingCode(userDataPath, { + name: 'Restarted host', + pairingCode: encodePairingOffer(server.offer) + }) + markEnvironmentUsed(userDataPath, paired.id, { runtimeId: 'runtime-proven' }) sendRemoteRuntimeRequestWithStatusPreflightMock.mockImplementation( - async (_connection, method, _params, _timeoutMs, validateStatus) => { - validateStatus({ - id: 'status', - ok: true, - result: { capabilities: [] }, - _meta: { runtimeId: 'runtime-restarted' } - }) - mutationSent(method) - return { id: method, ok: true, result: {}, _meta: { runtimeId: 'runtime-restarted' } } - } + actual.sendRemoteRuntimeRequestWithStatusPreflight ) - await expect( callRuntimeEnvironment( userDataPath, - environmentId, + paired.id, 'orchestration.federationRelease', { dispatchId: 'dispatch-1' }, 15_000, @@ -223,8 +230,9 @@ describe('federated read RPC transport routing', () => { { expectedEnvironmentRuntimeId: 'runtime-proven' } ) ).resolves.toMatchObject({ ok: false, error: { code: 'runtime_environment_changed' } }) - expect(mutationSent).not.toHaveBeenCalled() - expect(sendRemoteRuntimeRequestMock).not.toHaveBeenCalled() + expect( + server.requests.filter((request) => request.method === 'orchestration.federationRelease') + ).toEqual([]) }) it('falls back to one-shot with the envelope when shared control is unavailable', async () => { diff --git a/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts b/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts new file mode 100644 index 00000000000..5ce10cfd948 --- /dev/null +++ b/src/main/ipc/runtime-environments/runtime-environment-prompt-telemetry.test.ts @@ -0,0 +1,106 @@ +import { randomUUID } from 'node:crypto' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { decodeRuntimeEnvironmentSubscriptionEvents } from './runtime-environment-subscription-events' +import { + cleanupTelemetryClientTest, + setupTelemetryClientTest, + type TelemetryClientTestState +} from '../../telemetry/client-test-harness' + +let state: TelemetryClientTestState +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-08T23:58:00Z')) + state = setupTelemetryClientTest({ + optedIn: true, + installId: '00000000-0000-4000-8000-000000000000', + existedBeforeTelemetryRelease: false, + protectedMilestones: { installCohort: 'fresh' } + }) +}) +afterEach(() => { + cleanupTelemetryClientTest(state.envStash) + vi.useRealTimers() +}) + +const prompt = (client: 'desktop' | 'mobile' = 'desktop') => ({ + type: 'structuredChatPromptAccepted', + id: randomUUID(), + agent_kind: 'codex', + client +}) +const frame = (result: unknown) => ({ + type: 'response' as const, + response: { id: 'events-1', ok: true as const, result, _meta: { runtimeId: 'remote-runtime' } } +}) +const cursor = () => state.settings.telemetry?.protectedMilestones +const captured = (name: string) => + state.mock.capture.mock.calls.map(([event]) => event).filter((event) => event.event === name) + +it('consumes live accepted observations in desktop main once, without exposing their IDs to analytics', () => { + const delivered: unknown[] = [] + let current = false + const observe = decodeRuntimeEnvironmentSubscriptionEvents( + 'runtime.clientEvents.subscribe', + (event) => delivered.push(event), + () => current + ) + const event = prompt() + observe(frame(event)) + expect(cursor()).toEqual({ installCohort: 'fresh' }) + current = true + observe(frame(event)) + expect(cursor()).toEqual({ + installCohort: 'fresh', + firstAgentInteractionDay: 20_765, + meaningfulActivityDay: 20_765 + }) + expect(captured('first_agent_interaction')[0].properties).toMatchObject({ + source: 'native_chat', + agent_kind: 'codex' + }) + expect(captured('meaningful_activity_day')[0].properties.trigger).toBe('native_chat') + expect(delivered).toEqual([frame(event)]) + expect(JSON.stringify(state.mock.capture.mock.calls)).not.toContain(event.id) + + vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) + observe(frame(event)) + expect(cursor()?.meaningfulActivityDay).toBe(20_765) + observe(frame(prompt('mobile'))) + expect(cursor()?.meaningfulActivityDay).toBe(20_766) + expect(captured('meaningful_activity_day').map((entry) => entry.properties.trigger)).toEqual([ + 'native_chat', + 'mobile_chat' + ]) +}) + +it('drops opted-out observations permanently and rejects unbounded or content-bearing facts', () => { + const observe = decodeRuntimeEnvironmentSubscriptionEvents( + 'runtime.clientEvents.subscribe', + () => {}, + () => true + ) + const event = prompt('mobile') + state.settings.telemetry!.optedIn = false + observe(frame(event)) + expect(cursor()).toEqual({ installCohort: 'fresh' }) + state.settings.telemetry!.optedIn = true + observe(frame(event)) + observe(frame({ ...prompt(), body: 'private prompt must never reach analytics' })) + observe(frame({ ...prompt(), agent_kind: 'arbitrary-agent-name' })) + const wrongMethod = decodeRuntimeEnvironmentSubscriptionEvents( + 'agentSession.subscribe', + () => {}, + () => true + ) + wrongMethod(frame(prompt())) + expect(cursor()).toEqual({ installCohort: 'fresh' }) + + observe(frame(prompt('mobile'))) + expect(cursor()).toEqual({ + installCohort: 'fresh', + firstAgentInteractionDay: 20_765, + meaningfulActivityDay: 20_765 + }) + expect(captured('first_agent_interaction')[0].properties.source).toBe('mobile_chat') +}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts b/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts index 7d089afaed2..6e3c5b7f1bb 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.test.ts @@ -162,6 +162,28 @@ describe('a request to a recipe VM environment', () => { }) }) + // A resume that kept its saved pairing leaves the revision as it was; it is still a new wake. + it('reports a wake that kept the pairing an earlier wake made', async () => { + recordVm('suspended') + forgetRecipeVmWakePairingsForTests() + noteRecipeVmWakePairing(VM_ENVIRONMENT.id, 7) + holdOpen.mockImplementationOnce(async () => { + noteRecipeVmWakePairing(VM_ENVIRONMENT.id, 7, true) + return 'up' + }) + await expect(prepareRecipeVm(userDataPath, VM_ENVIRONMENT, 'wake')).resolves.toEqual({ + wokenPairingRevision: 7 + }) + // Without a server restart, a wake that kept the pairing reads as no wake, as before. + holdOpen.mockImplementationOnce(async () => { + noteRecipeVmWakePairing(VM_ENVIRONMENT.id, 7) + return 'up' + }) + await expect(prepareRecipeVm(userDataPath, VM_ENVIRONMENT, 'wake')).resolves.toEqual({ + wokenPairingRevision: null + }) + }) + it('cancels an open the user disconnected while it waited, without stopping the wake', async () => { recordVm('suspended') holdOpen.mockImplementationOnce(async () => { diff --git a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts b/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts index cc2350099c0..f906a8612f9 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-recipe-vm-wake.ts @@ -17,7 +17,7 @@ import { type RecipeVmWakeIntent } from '../../../shared/remote-runtime/recipe-vm-wake' import { getRecipeVmWaker } from '../../runtime/workspaces/sleep/recipe-vm-waker-registry' -import { recipeVmWakePairing } from '../../ephemeral-vm/recipe-vm-wake-pairings' +import { latestRecipeVmWake } from '../../ephemeral-vm/recipe-vm-wake-pairings' import { isRuntimeEnvironmentManuallyDisconnected, runtimeEnvironmentManualDisconnectCount, @@ -93,7 +93,7 @@ export async function prepareRecipeVm( runtimeEnvironmentManualDisconnectReason(environment.id) ) } - const pairingBefore = recipeVmWakePairing(environment.id) + const wakeBefore = latestRecipeVmWake(environment.id) const disconnectsBefore = runtimeEnvironmentManualDisconnectCount(environment.id) const opening = await waker.holdOpen(vm.workspaceId, vm.recordSuspended, holdMs, signal) if (opening !== 'up') { @@ -106,9 +106,9 @@ export async function prepareRecipeVm( runtimeEnvironmentManualDisconnectReason(environment.id) ) } - // A wake that ran while this request waited re-paired the server onto this exact pairing. - const wokenPairing = recipeVmWakePairing(environment.id) - return { wokenPairingRevision: wokenPairing !== pairingBefore ? (wokenPairing ?? null) : null } + // A wake that ran while this request waited left the server on this exact pairing. + const woken = latestRecipeVmWake(environment.id) + return { wokenPairingRevision: woken !== wakeBefore ? (woken?.pairingRevision ?? null) : null } } const state = waker.state(vm.workspaceId, vm.recordSuspended) if (state !== 'up') { diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts b/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts index 20a166e2a77..27bb8ce01af 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts @@ -1,3 +1,5 @@ +import { RemoteRuntimeSharedControlConnection } from '../../../shared/remote-runtime/control/remote-runtime-shared-control-connection' +import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import { afterEach, describe, expect, it, vi } from 'vitest' import { closeSharedControlTestServers, @@ -28,6 +30,7 @@ import { getRemoteRuntimeSharedControlAnsweredAt } from './runtime-environment-s const ENVIRONMENT_ID = 'standing-intent-test' afterEach(async () => { + vi.restoreAllMocks() closeRemoteRuntimeRequestConnection(ENVIRONMENT_ID) clearRuntimeEnvironmentManualDisconnect(ENVIRONMENT_ID) resetRuntimeEnvironmentCapabilityEvidence() @@ -168,6 +171,50 @@ describe('runtime environment shared-control connection cache', () => { } ) + it('does not dispatch create after the preflight socket is replaced', async () => { + const closed = Promise.withResolvers() + const server = await createSharedControlTestServer({ + onClientClose: () => closed.resolve(), + resultForRequest: (method) => (method === 'status.get' ? { runtimeId: 'runtime-a' } : {}) + }) + const original = RemoteRuntimeSharedControlConnection.prototype.request + vi.spyOn(RemoteRuntimeSharedControlConnection.prototype, 'request').mockImplementation( + function ( + this: RemoteRuntimeSharedControlConnection, + ...args: Parameters + ): Promise> { + const invoke = original.bind(this) + const response = invoke(...args) + if (args[0] !== 'status.get') { + return response + } + return response.then(async (status) => { + server.closeClients() + await closed.promise + this.reconnectNow() + return status + }) + } + ) + await expect( + sendRemoteRuntimeSharedControlRequestOnRuntime( + ENVIRONMENT_ID, + server.pairing, + { + method: 'agentSession.create', + params: { + forkFrom: { sessionId: 'child', throughItemId: 'legacy:opencode:source:reply-1' } + }, + timeoutMs: 1000 + }, + 'runtime-a' + ) + ).resolves.toBeNull() + expect(server.requests.filter((request) => request.method === 'agentSession.create')).toEqual( + [] + ) + }) + it('sends the prepared request on the runtime-pinned shared socket', async () => { const server = await createSharedControlTestServer({ resultForRequest: (method) => (method === 'status.get' ? { runtimeId: 'runtime-a' } : {}) diff --git a/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts b/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts index 035ea30ce40..3a6ea4b428f 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-subscription-events.ts @@ -19,6 +19,7 @@ export function decodeRuntimeEnvironmentSubscriptionEvents( event !== null && 'type' in event && (event.type === 'structuredChatMessageDispatch' || + event.type === 'structuredChatPromptAccepted' || event.type === 'structuredChatAgentStart') && recordRemoteStructuredChatTelemetry(event) ) { diff --git a/src/main/ipc/settings-delayed-response.test.ts b/src/main/ipc/settings-delayed-response.test.ts index b9fede4b633..e8aeaec8e63 100644 --- a/src/main/ipc/settings-delayed-response.test.ts +++ b/src/main/ipc/settings-delayed-response.test.ts @@ -33,21 +33,21 @@ vi.mock('../ssh/config/ssh-config-parser', () => ({ sshConfigHostsToTargets: () => [] })) vi.mock('../ghostty/index', () => ({ previewGhosttyImport: vi.fn() })) -vi.mock('../warp-themes', () => ({ previewWarpThemeImport: vi.fn() })) +vi.mock('../warp-themes/index', () => ({ previewWarpThemeImport: vi.fn() })) vi.mock('../network/proxy-settings', () => ({ applyElectronProxySettings: applyElectronProxySettingsMock })) -vi.mock('../browser/sessions/browser-session-proxy', () => ({ +vi.mock('../browser/sessions/proxy/browser-session-proxy', () => ({ applyBrowserSessionProxies: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../browser/sessions/browser-session-registry', () => ({ +vi.mock('../browser/sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { listProfiles: vi.fn(() => []) } })) vi.mock('../window/desktop-integration/app-icon', () => ({ applyAppIcon: vi.fn() })) vi.mock('../ai-vault-search/session-search-enablement', () => ({ applySessionSearchSettingsChange: vi.fn() })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) vi.mock('../workspaces/creation/worktree-root-preparation', () => ({ diff --git a/src/main/ipc/settings-ipc-test-fixture.ts b/src/main/ipc/settings-ipc-test-fixture.ts index 8dcedbbbdba..94d2b9b04f4 100644 --- a/src/main/ipc/settings-ipc-test-fixture.ts +++ b/src/main/ipc/settings-ipc-test-fixture.ts @@ -55,7 +55,7 @@ vi.mock('../ghostty/index', () => ({ previewGhosttyImport: previewGhosttyImportMock })) -vi.mock('../warp-themes', () => ({ +vi.mock('../warp-themes/index', () => ({ previewWarpThemeImport: previewWarpThemeImportMock })) @@ -63,11 +63,11 @@ vi.mock('../network/proxy-settings', () => ({ applyElectronProxySettings: applyElectronProxySettingsMock })) -vi.mock('../browser/sessions/browser-session-proxy', () => ({ +vi.mock('../browser/sessions/proxy/browser-session-proxy', () => ({ applyBrowserSessionProxies: applyBrowserSessionProxiesMock })) -vi.mock('../browser/sessions/browser-session-registry', () => ({ +vi.mock('../browser/sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { listProfiles: listProfilesMock } })) @@ -81,7 +81,7 @@ vi.mock('../ai-vault-search/session-search-enablement', () => ({ vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index 23a634561fe..d5cd6411e85 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -14,13 +14,13 @@ import { track } from '../telemetry/client' import { SETTINGS_CHANGED_WHITELIST, type SettingsChangedKey } from '../../shared/telemetry-events' import type { AgentAwakeService } from '../power/agent-awake-service' import { sanitizeFloatingWorkspaceDirectorySetting } from './floating-workspace-directory' -import { applyAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' +import { applyAgentStatusHooksEnabled } from '../agent-hooks/installation/managed-agent-hook-controls' import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { recordManagedHookInstallFailure } from '../agent-hooks/install-telemetry' +import { recordManagedHookInstallFailure } from '../agent-hooks/installation/install-telemetry' import { applyElectronProxySettings } from '../network/proxy-settings' -import { applyBrowserSessionProxies } from '../browser/sessions/browser-session-proxy' +import { applyBrowserSessionProxies } from '../browser/sessions/proxy/browser-session-proxy' import { applyProxyToElectronUpdaterSession } from '../updater/lifecycle/electron-updater-proxy-session' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { sanitizeNetworkSettings } from './network-settings-sanitization' import { normalizeAppIconId } from '../../shared/app-icon' import { normalizeUiLanguage } from '../../shared/ui-language' diff --git a/src/main/ipc/telemetry-protected-milestone-admission.test.ts b/src/main/ipc/telemetry-protected-milestone-admission.test.ts new file mode 100644 index 00000000000..b592431459f --- /dev/null +++ b/src/main/ipc/telemetry-protected-milestone-admission.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it, vi } from 'vitest' +import type { Store } from '../persistence/loading-store/store' + +const { handleMock, trackMock } = vi.hoisted(() => ({ + handleMock: vi.fn(), + trackMock: vi.fn(() => true) +})) + +vi.mock('electron', () => ({ + BrowserWindow: { fromWebContents: vi.fn() }, + ipcMain: { handle: handleMock } +})) +vi.mock('../telemetry/client', () => ({ + hasTrackedAgentDashboardActiveToday: vi.fn(() => false), + persistBannerAcknowledgeWithoutEmitting: vi.fn(), + setOptIn: vi.fn(), + track: trackMock +})) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../telemetry/onboarding-cohort-classifier', () => ({ + getOnboardingCohortAtEmit: () => ({}) +})) + +import { registerTelemetryHandlers } from './telemetry' + +describe('renderer telemetry admission', () => { + it('cannot forge protected milestones but still forwards their source events', () => { + const store: Partial = {} + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the track handler never reads the store. + registerTelemetryHandlers(store as Store) + const [, trackHandler] = handleMock.mock.calls.find( + ([channel]) => channel === 'telemetry:track' + )! + const sender = { sender: {} } + + expect( + trackHandler(sender, 'first_agent_interaction', { + source: 'orca_send', + agent_kind: 'codex', + install_cohort: 'fresh' + }) + ).toBe(false) + expect( + trackHandler(sender, 'meaningful_activity_day', { + trigger: 'orca_send', + install_cohort: 'fresh' + }) + ).toBe(false) + expect( + trackHandler(sender, 'native_chat_prompt_submitted', { + agent_kind: 'codex', + runtime: 'local', + client: 'desktop' + }) + ).toBe(false) + expect(trackMock).not.toHaveBeenCalled() + + const send = { agent_kind: 'codex', launch_source: 'sidebar', request_kind: 'followup' } + expect(trackHandler(sender, 'agent_prompt_sent', send)).toBe(true) + expect(trackMock).toHaveBeenCalledWith('agent_prompt_sent', send) + }) +}) diff --git a/src/main/ipc/telemetry.ts b/src/main/ipc/telemetry.ts index f093a434105..ceb99489cd9 100644 --- a/src/main/ipc/telemetry.ts +++ b/src/main/ipc/telemetry.ts @@ -30,6 +30,9 @@ const MAIN_OWNED_TELEMETRY_EVENTS = new Set([ 'daemon_pty_cwd_readable', 'star_nag_outcome', 'feature_interaction_usage_bucket_reached', + 'first_agent_interaction', + 'meaningful_activity_day', + 'native_chat_prompt_submitted', 'plugin_installed', 'ssh_remote_runtime_resolved', 'ssh_host_server_decided', diff --git a/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts b/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts index 0a6fca7614b..d6105a76212 100644 --- a/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts +++ b/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts @@ -8,7 +8,7 @@ import { } from '../../../../shared/worktree/id' import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import { isWslUncPath } from '../../../../shared/wsl-paths' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { Store } from '../../../persistence/loading-store/store' import type { NativeLocalWorktreeMetadataScanExpectation } from '../../../persistence/tracking-repos/missing-local-worktree-metadata-pruning' import { pruneWorkspaceCleanupScanSnapshots } from '../../../workspaces/cleanup/workspace-cleanup-scan-snapshot' diff --git a/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts b/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts index 205185384df..52c34f3fb7c 100644 --- a/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts +++ b/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts @@ -10,7 +10,7 @@ import type { DetectedWorktree } from '../../../../shared/worktree/types' import { isFolderRepo } from '../../../../shared/repo-kind' import { projectWorktreeLineageWithHostPeers } from '../../../workspaces/catalog/worktree-lineage-host-peers' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { pruneWorkspaceCleanupScanSnapshots } from '../../../workspaces/cleanup/workspace-cleanup-scan-snapshot' import { pruneWorkspaceSpaceAnalysisSnapshots } from '../../../workspaces/space-analysis/workspace-space-analysis-snapshot' import { findExactRepoOwner, hasConflictingStoredWorktreeOwner } from './worktree-host-ownership' diff --git a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts index 37284349024..21c66b863ac 100644 --- a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts +++ b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts @@ -10,7 +10,7 @@ import { writeWorktreeSortOrder, type WorktreeSortOrderRequest } from '../../../persistence/worktree-sort-order-write' -import { readBranchRenameFailureOutputForDisplay } from '../../../agent-hooks/branch-rename-failure-output' +import { readBranchRenameFailureOutputForDisplay } from '../../../agent-hooks/first-work/branch-rename-failure-output' import { normalizeLinkedWorkItemFields } from '../ipc-context-schemas' import { isRemovedFolderWorkspaceInstance } from '../../../workspaces/catalog/folder-workspace-meta-presence' import { resolveWorktreeMetaOwner } from '../../../persistence/host-qualified-worktree-meta' diff --git a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts index e4c9fd02783..b5bfea14861 100644 --- a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts +++ b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts @@ -3,12 +3,12 @@ import { getLocalPtyProvider } from '../../pty/provider/registry' import { clearProviderPtyState } from '../../pty/provider/state-cleanup' import { killAllProcessesForWorktree } from '../../../runtime/workspaces/removal/worktree-teardown' import type { Store } from '../../../persistence/loading-store/store' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' + import type { Repo } from '../../../../shared/repo-types' import { hasWorktreeRemovalRepoOwnerOnOtherHost } from '../../../workspaces/removal/worktree-removal-repo-owner' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { removeWorktreeMetaRow } from '../../../persistence/host-qualified-worktree-meta' import { pruneWorktreePRRefreshAliases } from '../../../github/pr-refresh-coordinator' import { diff --git a/src/main/ipc/wsl/wsl-move-driver-wiring.ts b/src/main/ipc/wsl/wsl-move-driver-wiring.ts index b66817c2556..68ed583e056 100644 --- a/src/main/ipc/wsl/wsl-move-driver-wiring.ts +++ b/src/main/ipc/wsl/wsl-move-driver-wiring.ts @@ -13,7 +13,7 @@ import { WSL_MOVE_PROGRESS_CHANNEL, type WslMoveProgressEvent } from '../../../shared/wsl-move/wsl-move-driver-types' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { getDaemonHistoryDir } from '../../daemon/launch/daemon-launch-paths' import { countInProcessFallbackTerminals, diff --git a/src/main/jcode/hook-config.ts b/src/main/jcode/hook-config.ts index f1c121fca2a..2a3c97c2041 100644 --- a/src/main/jcode/hook-config.ts +++ b/src/main/jcode/hook-config.ts @@ -11,7 +11,7 @@ import { parseTomlKeyPath, parseTomlTableHeaderPath } from '../codex/configuration/toml/config-toml-key-path' -import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' import { appendJcodeHookCommand, removeJcodeHookCommand, diff --git a/src/main/jcode/hook-service.ts b/src/main/jcode/hook-service.ts index 62cd0d1e905..6297afcb36b 100644 --- a/src/main/jcode/hook-service.ts +++ b/src/main/jcode/hook-service.ts @@ -5,23 +5,21 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookPostCommand, - createManagedCommandMatcher, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildWindowsHookEnvironmentGuardLines, POSIX_HOOK_STDIN_DRAIN_COMMAND, WINDOWS_HOOK_STDIN_DRAIN_COMMAND -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { applyJcodeManagedHooks, parseJcodeHooksTable, diff --git a/src/main/kimi/hook-service.ts b/src/main/kimi/hook-service.ts index 19a138a683f..c039cdc0920 100644 --- a/src/main/kimi/hook-service.ts +++ b/src/main/kimi/hook-service.ts @@ -18,26 +18,24 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyManagedKimiHooks, KIMI_HOOK_EVENTS, diff --git a/src/main/kimi/kimi-hook-config-toml.ts b/src/main/kimi/kimi-hook-config-toml.ts index 64653ac100e..b9e274050f5 100644 --- a/src/main/kimi/kimi-hook-config-toml.ts +++ b/src/main/kimi/kimi-hook-config-toml.ts @@ -1,6 +1,6 @@ // Preserve user TOML while managing marker blocks and positively recognized Orca hook tables. -import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installation/configuration/hook-config-schema' import { findManagedTomlBlocks, findRecognizedManagedTables, @@ -8,7 +8,7 @@ import { type ManagedTomlMarkers, type ManagedTomlRegion, type RecognizedManagedTable -} from '../agent-hooks/managed-toml-ownership' +} from '../agent-hooks/installation/configuration/managed-toml-ownership' export const KIMI_HOOK_EVENTS = [ 'SessionStart', diff --git a/src/main/kiro/hook-service.test.ts b/src/main/kiro/hook-service.test.ts index 19282c9b7bc..89e5e79092d 100644 --- a/src/main/kiro/hook-service.test.ts +++ b/src/main/kiro/hook-service.test.ts @@ -2,8 +2,8 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { KiroHookService } from './hook-service' import { getKiroManagedCommandMatcher, KIRO_HOOK_EVENTS } from './hook-settings' diff --git a/src/main/kiro/hook-service.ts b/src/main/kiro/hook-service.ts index f6975f02b04..ad62f8c3be8 100644 --- a/src/main/kiro/hook-service.ts +++ b/src/main/kiro/hook-service.ts @@ -7,25 +7,23 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - isPlainObject, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' import { listRemoteDirectory, readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyManagedKiroHooks, getKiroAgentsDir, diff --git a/src/main/kiro/hook-settings.ts b/src/main/kiro/hook-settings.ts index 8741ce87548..9af41894665 100644 --- a/src/main/kiro/hook-settings.ts +++ b/src/main/kiro/hook-settings.ts @@ -2,16 +2,18 @@ import { join, posix as pathPosix } from 'node:path' import { resolveKiroHomeDir } from '../../shared/kiro-home' import { createManagedCommandMatcher, - getSharedManagedScriptPath, hookDefinitionHasManagedCommand, - isPlainObject, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { MANAGED_HOOK_TIMEOUT_MILLISECONDS, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const KIRO_SCRIPT_BASE = 'kiro-hook' diff --git a/src/main/kiro/standalone-hook-settings.ts b/src/main/kiro/standalone-hook-settings.ts index a4e6daa9f9e..b1f78964147 100644 --- a/src/main/kiro/standalone-hook-settings.ts +++ b/src/main/kiro/standalone-hook-settings.ts @@ -1,6 +1,6 @@ import { join, posix as pathPosix } from 'node:path' import { resolveKiroHomeDir } from '../../shared/kiro-home' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { buildKiroListHook, getKiroManagedCommandMatcher, diff --git a/src/main/kiro/standalone-hooks.ts b/src/main/kiro/standalone-hooks.ts index 3c17a7106c9..f7bd127e555 100644 --- a/src/main/kiro/standalone-hooks.ts +++ b/src/main/kiro/standalone-hooks.ts @@ -4,9 +4,13 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { parseHooksJsonText, readHooksJsonWithRaw } from '../agent-hooks/hooks-json-read' -import { writeHooksJson } from '../agent-hooks/installer-utils' -import { readTextFileRemote, writeHooksJsonRemote } from '../agent-hooks/installer-utils-remote' +import { + parseHooksJsonText, + readHooksJsonWithRaw +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' import { buildKiroStandaloneHooksFile, getKiroStandaloneHooksFileConflict, diff --git a/src/main/managed-server/activation/orcad-exited-own-fence.test.ts b/src/main/managed-server/activation/orcad-exited-own-fence.test.ts index ac11f8bbd2c..61fa46ae2b0 100644 --- a/src/main/managed-server/activation/orcad-exited-own-fence.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-fence.test.ts @@ -202,20 +202,6 @@ describe.skipIf(process.platform === 'win32')('the held fence token record', () expect(held(store)).toContain('t-lost') }) - it('drops a token whose lock was never taken', async () => { - const { fence, store, options } = hostWithFence('t-foreign', []) - utimesSync(fence, new Date(), new Date()) - expect( - await withOrcadActivationLock( - options, - async () => 'ran', - () => 'held', - 't-busy' - ) - ).toBe('held') - expect(held(store)).not.toContain('t-busy') - }, 20_000) - it('never lets an unwritable record fail a fence operation', async () => { const { home, store, options } = hostWithFence('unused', []) rmSync(join(home, '.orca-remote'), { recursive: true }) diff --git a/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts b/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts index 30e2b4005ac..c05929b38ad 100644 --- a/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-install-lock.test.ts @@ -84,13 +84,6 @@ function versionDirWithLock(owner: string, heldToken: string) { describe.skipIf(process.platform === 'win32')( 'an install lock this desktop’s exited process left', () => { - it('never writes to the lock while proving its holder exited', async () => { - const { lock, proof } = versionDirWithLock('t-exited', 't-exited') - const before = statSync(lock).mtimeMs - await expect(proof.find(lock)).resolves.toBe('t-exited') - expect(statSync(lock).mtimeMs).toBe(before) - }) - // A successor replacing the proven-exited lock must never be aged or stolen. it('leaves a successor that replaced the lock after the proof alone', async () => { const { lock, store, proof, acquire } = versionDirWithLock('t-exited', 't-exited') diff --git a/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts b/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts index 2e33ab43be0..17c329bf1c0 100644 --- a/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts +++ b/src/main/managed-server/activation/orcad-exited-own-lock-windows.test.ts @@ -53,36 +53,10 @@ function find(guardsStateMutation: boolean): Promise { return findExitedOwnLockToken(target, lockDir, { baseDir, guardsStateMutation }) } -const checkOps = (): string[] => remote.commands.filter((c) => c.includes('fence-exited-owner')) - describe('reclaiming this desktop’s exited lock on a Windows host', () => { - it('asks the host script about exited holders only', async () => { - hold({ token: 't-exited', pid: EXITED_PID }, { token: 't-live', pid: process.pid }) - remote.reply = 'EXITED_OWNER t-exited\n' - await expect(find(true)).resolves.toBe('t-exited') - const [op] = checkOps() - expect(op).toContain('t-exited') - expect(op).not.toContain('t-live') - expect(op).toMatch(/fence-exited-owner"? "?[^ ]*\.install-lock"? "?1"?/u) - }) - it('ignores an answer naming a token it did not offer', async () => { hold({ token: 't-exited', pid: EXITED_PID }) remote.reply = 'EXITED_OWNER t-foreign\n' await expect(find(false)).resolves.toBeNull() }) - - it('falls back to the stale window when the check would not fit cmd.exe', async () => { - hold({ token: 't-exited', pid: EXITED_PID }) - remote.reply = 'EXITED_OWNER t-exited\n' - const deep = `C:/Users/me/${'nested-folder/'.repeat(200)}.orca-remote` - const target = { conn: unusedOrcadHostTransport(), host } - await expect( - findExitedOwnLockToken(target, `${deep}/.install-lock`, { - baseDir: deep, - guardsStateMutation: true - }) - ).resolves.toBeNull() - expect(remote.commands).toEqual([]) - }) }) diff --git a/src/main/managed-server/install/pinned-runtime-host-target.test.ts b/src/main/managed-server/install/pinned-runtime-host-target.test.ts deleted file mode 100644 index c2f5b5c45ee..00000000000 --- a/src/main/managed-server/install/pinned-runtime-host-target.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { pinnedRuntimeTargetForHost } from './pinned-runtime-host-target' - -describe('pinned runtime host target', () => { - it('names the runtime a host can run by glibc alone', () => { - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 28 } }) - ).toBe('linux-x64-glibc') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 27 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 12 } }) - ).toBeNull() - expect( - pinnedRuntimeTargetForHost({ target: 'linux-arm64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBeNull() - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: null })).toBe( - 'linux-x64-glibc' - ) - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-musl', glibc: null })).toBe( - 'linux-x64-musl' - ) - }) -}) diff --git a/src/main/menu/app-menu-selection-item.ts b/src/main/menu/app-menu-selection-item.ts index 5034d120ce1..b2ea8d1bf12 100644 --- a/src/main/menu/app-menu-selection-item.ts +++ b/src/main/menu/app-menu-selection-item.ts @@ -1,5 +1,5 @@ import { BrowserWindow, Menu, webContents } from 'electron' -import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/native-browser-popup-windows' +import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/presentation/native-browser-popup-windows' export type AppMenuSelectionAction = 'copy' | 'select-all' diff --git a/src/main/muse/hook-config-json.ts b/src/main/muse/hook-config-json.ts index 31c14832d1f..cc32c7f86e0 100644 --- a/src/main/muse/hook-config-json.ts +++ b/src/main/muse/hook-config-json.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' // Muse strips nonstandard environment variables from managed hooks unless allowlisted. export const MUSE_MANAGED_HOOK_ENV_VARS = [ diff --git a/src/main/muse/hook-service.ts b/src/main/muse/hook-service.ts index e4440b7247a..71c67033071 100644 --- a/src/main/muse/hook-service.ts +++ b/src/main/muse/hook-service.ts @@ -6,23 +6,21 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildMuseManagedHooksFile, getMuseConfigPath, diff --git a/src/main/muse/hook-settings.ts b/src/main/muse/hook-settings.ts index c85c1950e5f..d59edb81971 100644 --- a/src/main/muse/hook-settings.ts +++ b/src/main/muse/hook-settings.ts @@ -3,14 +3,14 @@ import { join } from 'node:path' import { readFile } from 'node:fs/promises' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { readManagedHookEventsFromJson } from '../agent-hooks/managed-hooks-json-events' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { readManagedHookEventsFromJson } from '../agent-hooks/installation/configuration/managed-hooks-json-events' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { parseMuseSettingsText } from './hook-config-json' const MUSE_SCRIPT_BASE = 'muse-hook' diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts index 6dcd96506f6..b53123fa52e 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts @@ -1,40 +1,52 @@ -import { mkdtempSync } from 'node:fs' -import * as fsPromises from 'node:fs/promises' +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' +import { afterEach, expect, it } from 'vitest' import { createAgentModelCatalogFilePersistence } from './agent-model-catalog-persistence' import { AgentModelCatalogStore } from './agent-model-catalog-store' -vi.mock('node:fs/promises', async (original) => { - const actual = await original() - return { ...actual, writeFile: vi.fn(actual.writeFile) } -}) -await vi.importActual('node:fs/promises') +const directories: string[] = [] afterEach(() => { - vi.restoreAllMocks() + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } }) -it('keeps optional cache write failure from poisoning subsequent serialized writes', async () => { - const directory = mkdtempSync(join(tmpdir(), 'pr-31927-catalog-failure-')) +it("imports an older build's catalog file once and keeps later listings", async () => { + const directory = mkdtempSync(join(tmpdir(), 'orca-model-catalog-')) + directories.push(directory) + const legacyPath = join(directory, 'agent-model-catalog.json') + writeFileSync( + legacyPath, + JSON.stringify({ + version: 3, + entries: [ + { + agent: 'grok', + fingerprint: 'fp', + discovered: { + origin: 'probe', + at: 1, + models: [{ id: 'A', label: 'A', efforts: [], isDefault: true }] + }, + live: null + } + ] + }) + ) const store = new AgentModelCatalogStore() - const persistence = createAgentModelCatalogFilePersistence(directory) - await store.attachPersistence(persistence) - const publish = (id: string) => - store.recordSuccess( - 'fp', - 'grok', - { - origin: 'probe', - models: [{ id, label: id, efforts: [], isDefault: true }] - }, - 'discovery' - ) - vi.mocked(fsPromises.writeFile).mockRejectedValueOnce(new Error('cache unavailable')) - publish('A') - await store.flushPersistence() + await store.attachPersistence(createAgentModelCatalogFilePersistence(directory)) expect(store.get('fp')?.models[0]?.id).toBe('A') - publish('B') + expect(existsSync(legacyPath)).toBe(false) + + store.recordSuccess( + 'fp', + 'grok', + { origin: 'probe', models: [{ id: 'B', label: 'B', efforts: [], isDefault: true }] }, + 'discovery' + ) await store.flushPersistence() - expect((await persistence.load())[0]?.models[0]?.id).toBe('B') + + const restarted = await createAgentModelCatalogFilePersistence(directory).load() + expect(restarted.map((entry) => entry.models[0]?.id)).toEqual(['B']) }) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts index 11de6355500..457bda5a97e 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.ts @@ -1,5 +1,10 @@ -import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { join } from 'node:path' +import { + KeyedJsonRowCache, + parseKeyedJsonRows, + type KeyedJsonRow +} from '../../sqlite/row-cache/keyed-json-row-cache' +import { nextRetryDelayMs } from '../../sqlite/row-cache/row-cache-failure' import type { AgentSessionModelOption, AgentSessionOptionChoice @@ -16,6 +21,7 @@ import { isRecord } from '../../../shared/agent-status/child-work/agent-status-c // Older catalogs lack serviceTiers and cannot safely construct Fast requests. const SCHEMA_VERSION = 3 const SAVE_COALESCE_MS = 500 +const MAX_RETRY_DELAY_MS = 60_000 export type AgentModelCatalogPersistence = { load: () => Promise @@ -166,13 +172,46 @@ function persistedEntry(entry: AgentModelCatalogEntry): unknown { } } +function parseEntries(values: readonly unknown[]): AgentModelCatalogEntry[] { + return values.map(parseEntry).filter((entry): entry is AgentModelCatalogEntry => entry !== null) +} + +function catalogRow(entry: AgentModelCatalogEntry): KeyedJsonRow { + return { + key: `${entry.agent}\u0000${entry.fingerprint}`, + json: JSON.stringify(persistedEntry(entry)) + } +} + +/** Entries of an older build's file; bytes it cannot use (corrupt, other version) reject it. */ +function legacyEntries(text: string): AgentModelCatalogEntry[] | null { + const root = asRecord(JSON.parse(text)) + if (!root || root.version !== SCHEMA_VERSION || !Array.isArray(root.entries)) { + return null + } + return parseEntries(root.entries) +} + +/** One row per catalog entry, so a save writes only the entries whose listing changed. */ export function createAgentModelCatalogFilePersistence( directory: string ): AgentModelCatalogPersistence { - const filePath = join(directory, 'agent-model-catalog.json') + // Stored state or an older build's file could not be read: this session saves nothing, + // leaving both for the next start. Rediscovery refills memory meanwhile. + let cold = false + const cache = new KeyedJsonRowCache(join(directory, 'agent-model-catalog.db'), { + schemaVersion: SCHEMA_VERSION, + // Earlier builds rewrote this whole file (megabytes) per change; it is imported once, then removed. + legacyPath: join(directory, 'agent-model-catalog.json') + }) let pending: (() => readonly AgentModelCatalogEntry[]) | null = null let timer: ReturnType | null = null - let writing = Promise.resolve() + let retryDelayMs = SAVE_COALESCE_MS + + const schedule = (delayMs: number): void => { + timer ??= setTimeout(flush, delayMs) + timer.unref?.() + } const flush = (): Promise => { if (timer !== null) { @@ -181,51 +220,45 @@ export function createAgentModelCatalogFilePersistence( } const snapshot = pending pending = null - if (!snapshot) { - return writing - } - const entries = snapshot() - writing = writing.then(async () => { + if (snapshot && !cold) { try { - await mkdir(dirname(filePath), { recursive: true }) - const tmpPath = `${filePath}.tmp` - await writeFile( - tmpPath, - JSON.stringify({ - version: SCHEMA_VERSION, - entries: entries.map(persistedEntry) - }), - 'utf8' - ) - await rename(tmpPath, filePath) + cache.write(snapshot().map(catalogRow)) + retryDelayMs = SAVE_COALESCE_MS } catch { - // Persistence is optional bookkeeping; preserve the current in-memory catalog. + // Optional bookkeeping (a lock elsewhere, a full disk): memory stays authoritative and + // the latest snapshot is retried later unless a newer save replaces it. + pending ??= snapshot + retryDelayMs = nextRetryDelayMs(retryDelayMs, { + minMs: SAVE_COALESCE_MS, + maxMs: MAX_RETRY_DELAY_MS + }) + schedule(retryDelayMs) } - }) - return writing + } + return Promise.resolve() } return { async load() { - try { - const parsed: unknown = JSON.parse(await readFile(filePath, 'utf8')) - const root = asRecord(parsed) - if (!root || root.version !== SCHEMA_VERSION || !Array.isArray(root.entries)) { - return [] - } - return root.entries - .map(parseEntry) - .filter((entry): entry is AgentModelCatalogEntry => entry !== null) - } catch { - return [] + const loaded = cache.load(legacyEntries) + if (loaded.kind === 'unavailable') { + cold = true + return loaded.legacy ?? [] } + if (loaded.kind === 'rows') { + return parseEntries(parseKeyedJsonRows(loaded.rows).map(({ value }) => value)) + } + try { + // An older build's file is newer than the rows: save it now, which removes the file. + cache.write(loaded.value.map(catalogRow), { importReceipt: loaded.receipt }) + } catch { + cold = true + } + return loaded.value }, save(snapshot) { pending = snapshot - if (timer === null) { - timer = setTimeout(flush, SAVE_COALESCE_MS) - timer.unref?.() - } + schedule(SAVE_COALESCE_MS) }, flush } diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-create.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-create.ts index 6880f7a61cf..eedfdd4936e 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-create.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-create.ts @@ -232,7 +232,9 @@ async function foundConversation( ...(first.selection === undefined ? openingMessageOptions(candidate.record.options) : {}) - } + }, + caller.userClient, + caller.telemetryOwnerKey ).catch((error: unknown) => { if (!(error instanceof CommandReceiptExistsError)) { throw error diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-boundary.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-boundary.ts index ed289861ca6..0a55d6bf1d3 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-boundary.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-boundary.ts @@ -50,13 +50,9 @@ export function structuredAgentSessionForkBoundary( const identity = keys.nativeIdentity(selected.itemId) const opener = turn?.userItemId ? keys.nativeIdentity(turn.userItemId) : undefined const head = record.providerHandleChain.at(-1) - const anchor = record.forkedFrom?.childBoundary - const anchorIndex = - anchor?.kind === 'item' ? items.findIndex((item) => item.itemId === anchor.itemId) : -1 const settled = Boolean( next || (turn && (turn.state === 'completed' || turn.state === 'interrupted')) || - index <= anchorIndex || record.lease.deathEvidence ) const checkpoint: Checkpoint = { diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts new file mode 100644 index 00000000000..b1ae5005d03 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent.ts @@ -0,0 +1,36 @@ +import { prepareStructuredAgentSessionFork } from './structured-agent-session-fork' +import { resolveCommittedStructuredAgentSessionAdoptionIntent } from '../../../runtime/agent-session/structured-agent-session-create-adoption' +import { agentConversationCopyRefusal } from '../../agent-conversation-copy-error' +import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' +import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' + +export async function resolveStructuredAgentSessionForkIntent(input: { + host: StructuredAgentSessionHost | null + forkFrom: { sessionId: string; throughItemId: string } + agent: StructuredAgentId + location: AgentSessionExecutionLocation + envelope: { sessionId: string; clientOperationId: string } + callerKey?: string +}): Promise { + const { host } = input + if (!host) { + throw agentConversationCopyRefusal( + 'structured_agent_session_unsupported', + { reason: 'hostUnsupported' }, + `${acpAgentName(input.agent)} could not reach the execution host. Reconnect to the host, then try again.` + ) + } + return ( + resolveCommittedStructuredAgentSessionAdoptionIntent({ ...input, host }) ?? + prepareStructuredAgentSessionFork({ + ...input, + host, + sessionId: input.forkFrom.sessionId, + throughItemId: input.forkFrom.throughItemId, + envelope: { ...input.envelope, expectedRuntimeFence: null, payloadFingerprint: '' } + }) + ) +} diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts new file mode 100644 index 00000000000..5c60bb1c6bc --- /dev/null +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts @@ -0,0 +1,245 @@ +import { isInheritedAgentSessionItem } from '../../../../shared/agent-session/agent-session-fork' +import { + agentJournalItemKey, + parseAgentJournalItemKey +} from '../../../../shared/agent-session/journal/agent-session-journal-item-key' +import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context' +import { + agentSessionExecutionLocationsEqual, + type AgentSessionExecutionLocation +} from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { isAgentSessionForkSourceAdmissionRefusal } from '../../../../shared/agent-session/failures/agent-session-definitive-refusal' +import { + AGENT_SESSION_FAILURE_COPY, + sayAgentSessionFailureEnglish +} from '../../../../shared/agent-session/failures/agent-session-failure-copy' +import { + AgentConversationCopyError, + agentConversationCopyRefusal +} from '../../agent-conversation-copy-error' +import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' +import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata' +import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { importedAgentSessionForkTipSettled } from './imported-agent-session-fork-tip' +import { structuredAgentSessionForkBoundary } from './structured-agent-session-fork-boundary' + +export type StructuredAgentSessionForkInput = { + host: StructuredAgentSessionHost + sessionId: string + throughItemId: string + agent: StructuredAgentId + location: AgentSessionExecutionLocation + envelope: AgentSessionAttachParams['envelope'] +} + +/** This catch ends before native copying begins; only authored admission failures prove no copy. */ +export async function admitStructuredAgentSessionFork(input: StructuredAgentSessionForkInput) { + try { + return await resolveForkSource(input) + } catch (error) { + if ( + isAgentSessionRefusalError(error) && + error.cause instanceof AgentConversationCopyError && + isAgentSessionForkSourceAdmissionRefusal(error.refusal) + ) { + error.refusal.createAttemptRefusedBeforeCommit = true + } + throw error + } +} + +async function resolveForkSource(input: StructuredAgentSessionForkInput) { + const { host } = input + let original = false + for (;;) { + const name = acpAgentName(input.agent) + if (host.deps.store.selectWritableRecord(input.sessionId).kind === 'missing') { + throw agentConversationCopyRefusal( + 'agent_session_identity_required', + { reason: 'recordMissing' }, + original + ? AGENT_SESSION_FAILURE_COPY.forkOriginalMissing.replace('{{agent}}', name) + : `${name} could not find the source chat. Open the chat again, then try again.` + ) + } + const record = host.deps.store.requireWritableRecord(input.sessionId) + const metadata = structuredAgentRuntimeMetadata(input.agent) + const capability = host.deps.agents.capabilities(input.agent)?.fork + const { head, pendingClear } = activeProviderContext(record) + const fail = ( + message: string, + reason: + | 'conversationCleared' + | 'rewindUnconfirmed' + | 'turnActive' + | 'savedConversationMissing' + | 'providerRejected' + | 'launchFolderMissing' = 'savedConversationMissing' + ): never => { + const refusal = agentConversationCopyRefusal( + 'agent_session_operation_invalid', + { reason }, + message + ) + if (original) { + const piece = + reason === 'savedConversationMissing' + ? 'forkOriginalMissing' + : reason === 'turnActive' + ? 'forkOriginalLatestOnly' + : 'forkOriginalUnavailable' + const title = record.conversationName?.trim() + refusal.refusal.message = sayAgentSessionFailureEnglish(title ? `${piece}Named` : piece, { + agent: name, + detail: title + }) + refusal.cause = new AgentConversationCopyError(refusal.refusal.message) + } + throw refusal + } + if (!capability || !metadata?.transcriptImport || !host.deps.adapter.copyConversation) { + throw agentConversationCopyRefusal( + 'structured_agent_session_unsupported', + { reason: 'hostUnsupported' }, + `${name} cannot copy a chat. Update ${name}, then try again.` + ) + } + if ( + record.provider !== input.agent || + !agentSessionExecutionLocationsEqual(record.location, input.location) || + input.sessionId === input.envelope.sessionId + ) { + fail(`${name} could not open the source chat in this workspace. Open it again and try again.`) + } + if ( + !head || + pendingClear || + (record.conversationCommand?.command === 'clear' && + (record.conversationCommand.phase === 'prepared' || + record.conversationCommand.state === 'unknown')) || + record.rewind?.phase === 'prepared' || + record.rewind?.phase === 'provider-succeeded' + ) { + fail( + `${name} has no confirmed saved context to copy. Finish the rewind or send a message, then try again.`, + pendingClear || !head ? 'conversationCleared' : 'rewindUnconfirmed' + ) + } + const sourceHead = head ?? fail(`${name} has no saved context. Send a message, then try again.`) + const snapshot = await host.journalSnapshot(record.sessionId) + const boundary = structuredAgentSessionForkBoundary( + snapshot, + record, + input.throughItemId, + capability + ) + const selected = + boundary ?? + fail( + `${name} could not find this response in the current chat. Open the chat again and try again.` + ) + if ( + record.forkedFrom && + isInheritedAgentSessionItem( + snapshot.items, + record.forkedFrom.childBoundary, + input.throughItemId + ) + ) { + const ancestor = host.deps.store.getRecord(record.forkedFrom.sessionId) + const originalHead = ancestor && activeProviderContext(ancestor).head + const key = parseAgentJournalItemKey(input.throughItemId) + input = { + ...input, + sessionId: record.forkedFrom.sessionId, + throughItemId: + key?.provider === 'codex' && key.threadId === sourceHead.handle.nativeId && originalHead + ? agentJournalItemKey({ + provider: 'codex', + threadId: originalHead.handle.nativeId, + turnId: key.turnId, + ordinal: key.ordinal + }) + : input.throughItemId + } + original = true + continue + } + const admissions = host.deps.store.admittedSendCount(record.sessionId) + const dispatch = JSON.stringify(snapshot.submissions) + const cwd = + record.launchDirectory ?? + (await host.deps.resolveWorkspacePath?.(record.location.workspaceId)) + if (!cwd) { + fail( + `${name} could not open the source workspace. Open it again and try again.`, + 'launchFolderMissing' + ) + } + const workspaceCwd = + cwd ?? + fail( + `${name} could not open the source workspace. Open it again and try again.`, + 'launchFolderMissing' + ) + const launchEnv = { ...process.env, ...(await host.deps.resolveLaunchEnv?.(input.agent)) } + const providerSessionId = metadata.sessionHistory.rowSessionId(sourceHead) + if (capability === 'tip' && selected.latest && !selected.checkpoint.settled) { + selected.checkpoint.settled = await importedAgentSessionForkTipSettled({ + record, + providerSessionId, + selectedItemId: selected.checkpoint.selectedItemId, + workspaceCwd, + launchEnv + }) + } + if (capability === 'tip' && (!selected.latest || !selected.checkpoint.settled)) { + fail( + `${name} can only fork its latest finished response. Wait for it to finish, then try again.`, + 'turnActive' + ) + } + const throughItemId = input.throughItemId + const requireCurrent = async () => { + const current = host.deps.store.requireWritableRecord(record.sessionId) + const currentSnapshot = await host.journalSnapshot(record.sessionId) + const context = activeProviderContext(current) + const transitionPending = + context.pendingClear || + current.rewind?.phase === 'prepared' || + current.rewind?.phase === 'provider-succeeded' || + (current.conversationCommand?.command === 'clear' && + (current.conversationCommand.phase === 'prepared' || + current.conversationCommand.state === 'unknown')) + const currentBoundary = transitionPending + ? null + : structuredAgentSessionForkBoundary(currentSnapshot, current, throughItemId, capability) + if ( + !agentSessionExecutionLocationsEqual(current.location, record.location) || + currentBoundary?.retained !== selected.retained || + (capability === 'tip' && + (host.deps.store.admittedSendCount(record.sessionId) !== admissions || + JSON.stringify(currentSnapshot.submissions) !== dispatch || + !currentBoundary.latest)) + ) { + fail(`${name} could not finish the copy because the source context changed. Try again.`) + } + return { snapshot: currentSnapshot, boundary: currentBoundary! } + } + await requireCurrent() + return { + record, + metadata, + transcriptImport: metadata.transcriptImport, + selected, + sourceHead, + providerSessionId, + requireCurrent, + fail, + throughItemId + } + } +} diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts index 15df37fda56..ae112b21465 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts @@ -1,211 +1,74 @@ +import { + admitStructuredAgentSessionFork, + type StructuredAgentSessionForkInput +} from './structured-agent-session-fork-source' import { prepareForkSnapshot } from './structured-agent-session-fork-snapshot' import { agentSessionJournalProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { importedAgentSessionForkTipSettled } from './imported-agent-session-fork-tip' import { defaultAgentChatLabel } from '../../../../shared/agent-session/agent-session-chat-label' import { normalizeAgentSessionConversationName, AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH } from '../../../../shared/agent-session/agent-session-conversation-name' import { sliceAtCodeUnitLimit } from '../../../../shared/surrogate-safe-text-slice' -import { - AgentConversationCopyError, - agentConversationCopyRefusal -} from '../../agent-conversation-copy-error' -import { structuredAgentSessionForkBoundary } from './structured-agent-session-fork-boundary' +import { AgentConversationCopyError } from '../../agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' -import { activeProviderContext } from '../../../../shared/agent-session/agent-session-provider-context' import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' -import { - agentSessionExecutionLocationsEqual, - type AgentSessionExecutionLocation -} from '../../../../shared/agent-session/lifecycle/agent-session-record' -import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { - resolveCommittedStructuredAgentSessionAdoptionIntent, - requireUnownedStructuredAgentSessionAdoption -} from '../../../runtime/agent-session/structured-agent-session-create-adoption' -import { structuredAgentRuntimeMetadata } from '../../../runtime/agent-session/installation/structured-agent-runtime-metadata' -import type { StructuredAgentSessionHost } from '../host/structured-agent-session-host' +import { requireUnownedStructuredAgentSessionAdoption } from '../../../runtime/agent-session/structured-agent-session-create-adoption' import type { AgentSessionAttachParams } from './structured-agent-session-attach' -export async function prepareStructuredAgentSessionFork(input: { - host: StructuredAgentSessionHost - sessionId: string - throughItemId: string - agent: StructuredAgentId - location: AgentSessionExecutionLocation - envelope: AgentSessionAttachParams['envelope'] -}): Promise { +export async function prepareStructuredAgentSessionFork( + input: StructuredAgentSessionForkInput +): Promise { const { host } = input const name = acpAgentName(input.agent) - if (host.deps.store.selectWritableRecord(input.sessionId).kind === 'missing') { - throw agentConversationCopyRefusal( - 'agent_session_identity_required', - { reason: 'recordMissing' }, - `${name} could not find the source chat. Open the chat again, then try again.` - ) - } - const record = host.deps.store.requireWritableRecord(input.sessionId) - const metadata = structuredAgentRuntimeMetadata(input.agent) - const capability = host.deps.agents.capabilities(input.agent)?.fork - const { head, pendingClear } = activeProviderContext(record) - const fail = ( - message: string, - reason: - | 'conversationCleared' - | 'rewindUnconfirmed' - | 'turnActive' - | 'savedConversationMissing' - | 'providerRejected' - | 'launchFolderMissing' = 'savedConversationMissing' - ): never => { - throw agentConversationCopyRefusal('agent_session_operation_invalid', { reason }, message) - } - if (!capability || !metadata?.transcriptImport || !host.deps.adapter.copyConversation) { - throw agentConversationCopyRefusal( - 'structured_agent_session_unsupported', - { reason: 'hostUnsupported' }, - `${name} cannot copy a chat. Update ${name}, then try again.` - ) - } - if ( - record.provider !== input.agent || - !agentSessionExecutionLocationsEqual(record.location, input.location) || - input.sessionId === input.envelope.sessionId - ) { - fail(`${name} could not open the source chat in this workspace. Open it again and try again.`) - } - if ( - !head || - pendingClear || - (record.conversationCommand?.command === 'clear' && - (record.conversationCommand.phase === 'prepared' || - record.conversationCommand.state === 'unknown')) || - record.rewind?.phase === 'prepared' || - record.rewind?.phase === 'provider-succeeded' - ) { - fail( - `${name} has no confirmed saved context to copy. Finish the rewind or send a message, then try again.`, - pendingClear || !head ? 'conversationCleared' : 'rewindUnconfirmed' - ) - } - const sourceHead = head ?? fail(`${name} has no saved context. Send a message, then try again.`) - const snapshot = await host.journalSnapshot(record.sessionId) - const boundary = structuredAgentSessionForkBoundary( - snapshot, + const { record, - input.throughItemId, - capability - ) - const selected = - boundary ?? - fail( - `${name} could not find this response in the current chat. Open the chat again and try again.` - ) - const admissions = host.deps.store.admittedSendCount(record.sessionId) - const dispatch = JSON.stringify(snapshot.submissions) - const cwd = - record.launchDirectory ?? (await host.deps.resolveWorkspacePath?.(record.location.workspaceId)) - if (!cwd) { - fail( - `${name} could not open the source workspace. Open it again and try again.`, - 'launchFolderMissing' - ) - } - const workspaceCwd = - cwd ?? - fail( - `${name} could not open the source workspace. Open it again and try again.`, - 'launchFolderMissing' - ) - const launchEnv = { ...process.env, ...(await host.deps.resolveLaunchEnv?.(input.agent)) } - const providerSessionId = metadata.sessionHistory.rowSessionId(sourceHead) - if (capability === 'tip' && selected.latest && !selected.checkpoint.settled) { - selected.checkpoint.settled = await importedAgentSessionForkTipSettled({ - record, - providerSessionId, - selectedItemId: selected.checkpoint.selectedItemId, - workspaceCwd, - launchEnv - }) - } - if (capability === 'tip' && (!selected.latest || !selected.checkpoint.settled)) { - fail( - `${name} can only fork its latest finished response. Wait for it to finish, then try again.`, - 'turnActive' - ) - } - const requireCurrent = async () => { - const current = host.deps.store.requireWritableRecord(record.sessionId) - const currentSnapshot = await host.journalSnapshot(record.sessionId) - const context = activeProviderContext(current) - const transitionPending = - context.pendingClear || - current.rewind?.phase === 'prepared' || - current.rewind?.phase === 'provider-succeeded' || - (current.conversationCommand?.command === 'clear' && - (current.conversationCommand.phase === 'prepared' || - current.conversationCommand.state === 'unknown')) - const currentBoundary = transitionPending - ? null - : structuredAgentSessionForkBoundary( - currentSnapshot, - current, - input.throughItemId, - capability - ) - if ( - !agentSessionExecutionLocationsEqual(current.location, record.location) || - currentBoundary?.retained !== selected.retained || - (capability === 'tip' && - (host.deps.store.admittedSendCount(record.sessionId) !== admissions || - JSON.stringify(currentSnapshot.submissions) !== dispatch || - !currentBoundary.latest)) - ) { - fail(`${name} could not finish the copy because the source context changed. Try again.`) - } - return { snapshot: currentSnapshot, boundary: currentBoundary! } - } - await requireCurrent() + metadata, + transcriptImport, + selected, + sourceHead, + providerSessionId, + requireCurrent, + fail, + throughItemId + } = await admitStructuredAgentSessionFork(input) const title = normalizeAgentSessionConversationName( `${sliceAtCodeUnitLimit(record.conversationName?.trim() || defaultAgentChatLabel(input.agent), AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH - 5)} fork` )! - const copy = await host.deps.adapter - .copyConversation({ - record, - checkpoint: selected.checkpoint, - title, - identity: { - sessionId: record.sessionId, - workspaceId: record.location.workspaceId, - hostId: record.location.executionHostId, - agent: input.agent, - providerHandle: sourceHead.handle - }, - providerSessionId, - accountHome: record.accountHome - }) - .catch((error: unknown) => { - if (isAgentSessionRefusalError(error)) { - throw error - } - host.deps.logger.warn('native conversation copy failed', { - scope: 'chat-fork', - sessionId: record.sessionId, - error - }) - return fail( - error instanceof AgentConversationCopyError - ? error.message - : error instanceof Error && - (error.name === 'TimeoutError' || - (error.cause instanceof Error && error.cause.name === 'TimeoutError')) - ? `${name} took too long to copy this chat. Try again.` - : `${name} could not copy this conversation. Try again.`, - 'providerRejected' - ) + const copy = await host.deps.adapter.copyConversation!({ + record, + checkpoint: selected.checkpoint, + title, + identity: { + sessionId: record.sessionId, + workspaceId: record.location.workspaceId, + hostId: record.location.executionHostId, + agent: input.agent, + providerHandle: sourceHead.handle + }, + providerSessionId, + accountHome: record.accountHome + }).catch((error: unknown) => { + if (isAgentSessionRefusalError(error)) { + throw error + } + host.deps.logger.warn('native conversation copy failed', { + scope: 'chat-fork', + sessionId: record.sessionId, + error }) + return fail( + error instanceof AgentConversationCopyError + ? error.message + : error instanceof Error && + (error.name === 'TimeoutError' || + (error.cause instanceof Error && error.cause.name === 'TimeoutError')) + ? `${name} took too long to copy this chat. Try again.` + : `${name} could not copy this conversation. Try again.`, + 'providerRejected' + ) + }) const current = await requireCurrent() if (!copy.sessionId.trim() || copy.sessionId === providerSessionId) { fail(`${name} did not save an independent chat copy. Try again.`) @@ -219,7 +82,7 @@ export async function prepareStructuredAgentSessionFork(input: { const providerHandle = { transport: metadata.definition.handleTransport, agent: input.agent, - nativeId: metadata.transcriptImport.handleNamesTranscript ? copy.filePath! : copy.sessionId, + nativeId: transcriptImport.handleNamesTranscript ? copy.filePath! : copy.sessionId, ...(copy.resumeCursor ? { resumeCursor: copy.resumeCursor } : {}) } const prepared = prepareForkSnapshot({ @@ -233,7 +96,7 @@ export async function prepareStructuredAgentSessionFork(input: { envelope: input.envelope, fork: { sessionId: record.sessionId, - itemId: input.throughItemId, + itemId: throughItemId, revalidate: async () => { await requireCurrent() }, @@ -269,31 +132,3 @@ export async function prepareStructuredAgentSessionFork(input: { adopt: { providerHandle, conversationName: title } } } - -export async function resolveStructuredAgentSessionForkIntent(input: { - host: StructuredAgentSessionHost | null - forkFrom: { sessionId: string; throughItemId: string } - agent: StructuredAgentId - location: AgentSessionExecutionLocation - envelope: { sessionId: string; clientOperationId: string } - callerKey?: string -}): Promise { - const { host } = input - if (!host) { - throw agentConversationCopyRefusal( - 'structured_agent_session_unsupported', - { reason: 'hostUnsupported' }, - `${acpAgentName(input.agent)} could not reach the execution host. Reconnect to the host, then try again.` - ) - } - return ( - resolveCommittedStructuredAgentSessionAdoptionIntent({ ...input, host }) ?? - prepareStructuredAgentSessionFork({ - ...input, - host, - sessionId: input.forkFrom.sessionId, - throughItemId: input.forkFrom.throughItemId, - envelope: { ...input.envelope, expectedRuntimeFence: null, payloadFingerprint: '' } - }) - ) -} diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts index 4bcb8363673..00fdb85a2d7 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork-boundary.test.ts @@ -1,7 +1,17 @@ +import { fixture } from '../../publication/history/testing/agent-session-history-contract-test-fixture' +import { PI_CWD_BUCKET_LAYOUT } from '../../../../ai-vault/session-cwd-bucket-layouts' +import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork' +import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host' +import { acpHistoryTurns } from '../../../../acp/history/acp-history-replay' +import { translateHistoryTurn } from '../../../../acp/history/acp-history-translation' +import { OPENCODE_ACP_DIALECT } from '../../../../acp/acp-dialects/opencode-dialect' +import { readAcpFixture } from '../../../../acp/timeline/testing/acp-timeline-fixture.test-support' +import { structuredRewindCut } from '../../rewind/structured-rewind-cut' +import type { JournalReplacementItem } from '../../../agent-session-journal/context-epochs/journal-epoch-replacement' import { prepareForkSnapshot } from '../structured-agent-session-fork-snapshot' import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types' -import { readFile } from 'node:fs/promises' - +import { readFile, writeFile, mkdir } from 'node:fs/promises' +import { join } from 'node:path' import { expect, it } from 'vitest' import { claudeConversationForkBoundary } from '../../../../claude/claude-conversation-fork-boundary' import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' @@ -178,3 +188,295 @@ it('cuts before a Claude continuation notice attributed to the next imported pro 'claude:source:late-detail' ]) }) + +it.each(['rewind', 'persisted', 'unrelated T3', 'saved fork'])( + 'forks FOXTROT without the orphan terminal notice: %s', + async (route) => { + const native = (turnId: string, ordinal: number) => + ({ provider: 'codex', threadId: 'thread-1', turnId, ordinal }) as const + const legacy = (recordId: string) => + ({ provider: 'legacy', agent: 'codex', sessionId: 'session-1', recordId }) as const + const root1 = agentJournalItemKey(legacy('root1')) + const root2 = agentJournalItemKey(legacy('root2')) + const source: JournalReplacementItem[] = ( + [ + { + identity: native('T1', 0), + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'first' }] } + }, + { + identity: legacy('root1'), + body: { + kind: 'turn', + turnId: 'T1', + userItemId: 'codex:thread-1:T1:0', + state: 'completed' + } + }, + { + identity: native('T1', 1), + turnScope: { kind: 'turn', turnItemId: root1 }, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'FOXTROT' }] } + }, + { + identity: legacy(continuedOutsideRecordId('T2')), + body: continuedOutsideNotice(false), + turnScope: { kind: 'thread' } + }, + { + identity: legacy('root2'), + body: { + kind: 'turn', + turnId: 'T2', + userItemId: 'codex:thread-1:T2:0', + state: 'completed' + } + }, + { + identity: native('T2', 0), + turnScope: { kind: 'turn', turnItemId: root2 }, + body: { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'terminal prompt' }] + } + }, + { + identity: native('T2', 1), + turnScope: { kind: 'turn', turnItemId: root2 }, + body: { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'terminal answer' }] + } + } + ] satisfies Omit[] + ).map((row) => ({ ...row, observedAt: 123, ownerFence: 0 })) + const journal = fixture.journal + await journal.replaceEpochItems('session_created', 1, source) + if (route === 'rewind') { + const cut = structuredRewindCut(journal, { + itemId: 'codex:thread-1:T2:0', + provider: 'codex', + nativeId: 'thread-1' + }) + expect(cut).not.toBeNull() + await journal.replaceEpochItems('handle_forked', 1, cut!.kept) + } else { + await journal.replaceEpochItems('session_created', 1, [ + ...source.slice(0, 4), + // Earlier work alone cannot be introduced by a later notice. + { + identity: legacy(continuedOutsideRecordId('T1')), + body: continuedOutsideNotice(false), + observedAt: 123, + ownerFence: 0 + }, + ...(route === 'unrelated T3' + ? [ + { + identity: legacy('root3'), + body: { kind: 'turn' as const, turnId: 'T3', state: 'completed' as const }, + observedAt: 123, + ownerFence: 0 + }, + { + ...source[5]!, + identity: native('T3', 0), + turnScope: { + kind: 'turn' as const, + turnItemId: agentJournalItemKey(legacy('root3')) + } + } + ] + : []) + ]) + } + const record = agentSessionRecordFixture({ sessionId: 'session-1', provider: 'codex' }) + let snapshot = journal.snapshot() + let selected = 'codex:thread-1:T1:1' + let sourceThreadId = 'thread-1' + if (route === 'saved fork') { + const copied = prepareForkSnapshot({ + snapshot, + nextItemId: null, + sourceThreadId, + childThreadId: 'child' + }) + await journal.replaceEpochItems('session_created', 1, [ + ...copied, + source[3]!, + { + identity: legacy('fork-marker'), + body: { + kind: 'status', + text: 'Forked', + forkedFrom: { sessionId: 'parent' } + }, + observedAt: 123, + ownerFence: 0 + } + ]) + snapshot = journal.snapshot() + selected = 'codex:child:T1:1' + sourceThreadId = 'child' + } + const boundary = structuredAgentSessionForkBoundary(snapshot, record, selected) + expect(boundary).not.toBeNull() + expect( + prepareForkSnapshot({ + snapshot, + nextItemId: boundary!.nextItemId, + sourceThreadId, + childThreadId: 'result' + }).map((row) => agentJournalItemKey(row.identity)) + ).toEqual(['codex:result:T1:0', 'legacy:codex:session-1:root1', 'codex:result:T1:1']) + } +) + +it('retains the notice for an encoded ACP replay turn only while its introduced work survives', async () => { + const frames = (await readAcpFixture('opencode-v2-reopen-outside')) + .filter((frame) => frame.process === 'C' && frame.message.method === 'session/update') + .map((frame) => ({ method: 'session/update', params: frame.message.params })) + const first = acpHistoryTurns(frames, 'user-message-id')[0]! + if (first.turn === null) { + throw new Error('recorded replay has no user id') + } + const rows = translateHistoryTurn( + { + agent: 'opencode', + sessionId: 'chat', + providerSessionId: 'session-1', + dialect: OPENCODE_ACP_DIALECT, + identity: 'user-message-id' + }, + { ...first, turn: first.turn } + ) + const notice = { + itemId: 'legacy:opencode:chat:continued-outside%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', + body: continuedOutsideNotice(false), + turnScope: { kind: 'thread' as const } + } + const snapshot: AgentJournalSnapshot = { + sessionId: 'chat', + cursor: { epoch: 'epoch', sequence: 3 }, + submissions: [], + items: [ + notice, + ...rows.map((row) => ({ ...row, itemId: agentJournalItemKey(row.identity) })) + ].map((row, index) => ({ ...row, sequence: index + 1, revision: 1, observedAt: 123 })) + } + expect( + prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => + agentJournalItemKey(row.identity) + ) + ).toEqual([ + 'legacy:opencode:chat:continued-outside%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', + 'legacy:opencode:chat:turn-lifecycle%3Ap%3Asession-1%3Amsg_15fad6c9f001d4ix8WtRMUSWtI', + 'legacy:opencode:chat:item%3Ap%3Asession-1%3Asession-1%2Fuser%253Amsg_15fad6c9f001d4ix8WtRMUSWtI' + ]) + snapshot.items[2]!.body = { kind: 'tool-call', name: 'command', state: 'running', input: {} } + expect( + prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => + agentJournalItemKey(row.identity) + ) + ).toEqual([]) + snapshot.items.pop() + expect( + prepareForkSnapshot({ snapshot, nextItemId: null }).map((row) => + agentJournalItemKey(row.identity) + ) + ).toEqual([ + 'legacy:opencode:chat:turn-lifecycle%3Ap%3Asession-1%3Amsg_15fad6c9f001d4ix8WtRMUSWtI' + ]) +}) + +it('refuses an imported ACP tip with assistant prose but no native terminal evidence', async () => { + const nativeId = '019e6b26-18e2-7103-b7a0-7ba6bb071123' + const home = join(fixture.root, 'omp-account') + const sessions = join(home, 'sessions') + const directory = join(sessions, `${PI_CWD_BUCKET_LAYOUT.encodeScopePrefixes(fixture.root)[0]}--`) + await mkdir(directory, { recursive: true }) + await writeFile( + join(directory, `${nativeId}.jsonl`), + `${[ + { type: 'session', version: 3, id: nativeId, cwd: fixture.root }, + { + type: 'message', + id: 'prompt', + parentId: null, + message: { role: 'user', content: 'Remember 57319' } + }, + { + type: 'message', + id: 'response', + parentId: 'prompt', + message: { role: 'assistant', content: [{ type: 'text', text: 'Remembered' }] } + } + ] + .map((row) => JSON.stringify(row)) + .join('\n')}\n` + ) + for (const [recordId, role] of [ + ['prompt', 'user'], + ['response', 'assistant'] + ] as const) { + await fixture.journal.appendItem( + { provider: 'legacy', agent: 'omp', sessionId: nativeId, recordId }, + { + kind: 'message', + role, + blocks: [{ type: 'text', text: role === 'user' ? 'Remember 57319' : 'Remembered' }] + }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + } + const record = agentSessionRecordFixture({ + sessionId: 'session-1', + provider: 'omp', + accountHome: { variable: 'PI_CODING_AGENT_DIR', path: home }, + launchDirectory: fixture.root, + providerHandleChain: [ + { + linkId: 'omp-head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle: { transport: 'acp', agent: 'omp', nativeId } + } + ] + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: boundary preparation reads only these saved source and adapter facets. + const host = { + deps: { + store: { + selectWritableRecord: () => ({ kind: 'writable' }), + requireWritableRecord: () => record, + admittedSendCount: () => 0 + }, + agents: { capabilities: () => ({ fork: 'tip' }) }, + adapter: { + copyConversation: async () => { + throw new Error('unexpected copy') + } + }, + resolveLaunchEnv: async () => ({ PI_CODING_AGENT_DIR: home, OMP_CODING_AGENT_DIR: sessions }) + }, + journalSnapshot: async () => fixture.journal.snapshot() + } as unknown as StructuredAgentSessionHost + await expect( + prepareStructuredAgentSessionFork({ + host, + agent: 'omp', + sessionId: 'session-1', + throughItemId: 'legacy:omp:019e6b26-18e2-7103-b7a0-7ba6bb071123:response', + location: record.location, + envelope: { + sessionId: 'omp-child', + clientOperationId: 'copy', + expectedRuntimeFence: null, + payloadFingerprint: '' + } + }) + ).rejects.toMatchObject({ refusal: { details: { reason: 'turnActive' } } }) +}) diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts new file mode 100644 index 00000000000..1b2317f83df --- /dev/null +++ b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture.ts @@ -0,0 +1,228 @@ +import { vi } from 'vitest' +import { mkdir, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork' +import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host' +import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter' +import type { RestTestRig } from '../../host/testing/structured-agent-session-rest-test-rig' +import { structuredAgentSessionCreateParams } from '../../../../../shared/agent-session/structured-agent-session-create' + +const SOURCE = '019e6b26-18e2-7103-b7a0-7ba6bb071123' +const COPY = '019e6b26-18e2-7103-b7a0-7ba6bb071124' + +export function forkTestSource(rig: RestTestRig, agent: 'claude' | 'codex' = 'codex') { + let admissions = 0 + let capability: 'checkpoint' | 'tip' = 'checkpoint' + const record = agentSessionRecordFixture({ + sessionId: 'source-chat', + provider: agent, + accountHome: { + variable: agent === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME', + path: join(rig.root, 'source-account') + }, + options: { model: 'retired-model', effort: 'high', fastMode: 'false' }, + permissionMode: 'accept-edits', + launchArgs: ['--no-daemon'], + launchDirectory: rig.root, + providerHandleChain: [ + { + linkId: 'source-head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle: + agent === 'claude' ? claudeProviderHandle(SOURCE, 'answer') : codexProviderHandle(SOURCE) + } + ] + }) + const snapshot: AgentJournalSnapshot = { + sessionId: record.sessionId, + cursor: { epoch: 'source-epoch', sequence: 5 }, + submissions: [], + items: [ + { + itemId: agentJournalItemKey({ + provider: 'codex', + threadId: SOURCE, + turnId: 'completed-turn', + ordinal: 0 + }), + sequence: 1, + revision: 1, + observedAt: 1, + body: { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'Remember the nonce 57319' }] + } + }, + { + itemId: 'legacy:codex:source:ended-root', + sequence: 2, + revision: 1, + observedAt: 2, + body: { kind: 'turn', turnId: 'completed-turn', state: 'completed' } + }, + { + itemId: 'legacy:codex:source:selected-response', + sequence: 3, + revision: 1, + observedAt: 3, + turnScope: { kind: 'turn', turnItemId: 'legacy:codex:source:ended-root' }, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Remembered' }] } + }, + { + itemId: 'legacy:codex:source:running-root', + sequence: 3, + revision: 1, + observedAt: 3, + body: { kind: 'turn', turnId: 'active-turn', state: 'running' } + }, + { + itemId: 'legacy:codex:source:ended-child', + sequence: 4, + revision: 1, + observedAt: 4, + agentId: 'child', + body: { kind: 'turn', turnId: 'child-turn', state: 'completed' } + } + ] + } + const copy = vi.fn( + async ( + _input: Parameters>[0] + ): ReturnType> => { + const dir = + agent === 'claude' + ? join(rig.root, 'source-account', 'projects', 'workspace') + : join(rig.root, 'source-account', 'sessions', '2026', '11', '03') + await mkdir(dir, { recursive: true }) + const filePath = join( + dir, + agent === 'claude' ? `${COPY}.jsonl` : `rollout-2026-11-03T19-00-00-${COPY}.jsonl` + ) + if (agent === 'claude') { + await writeFile( + filePath, + `${[ + { + type: 'user', + uuid: 'prompt', + parentUuid: null, + sessionId: COPY, + timestamp: '2026-11-03T19:00:00.000Z', + cwd: rig.root, + message: { role: 'user', content: 'Remember the nonce 57319' } + }, + { + type: 'assistant', + uuid: 'answer', + parentUuid: 'prompt', + sessionId: COPY, + timestamp: '2026-11-03T19:00:01.000Z', + message: { + id: 'msg_answer', + role: 'assistant', + model: 'claude-opus-5-5', + content: [{ type: 'text', text: 'Remembered' }], + stop_reason: 'end_turn' + } + } + ] + .map((row) => JSON.stringify(row)) + .join('\n')}\n` + ) + return { + sessionId: COPY, + filePath, + coverage: { + unit: agent === 'claude' ? 'claude-entry' : 'codex-turn', + ids: agent === 'claude' ? ['prompt', 'answer'] : ['completed-turn'] + }, + ...(agent === 'claude' ? { resumeCursor: 'answer' } : {}) + } + } + await writeFile( + filePath, + `${[ + { + type: 'session_meta', + payload: { id: COPY, timestamp: '2026-11-03T19:00:00.000Z', cwd: rig.root } + }, + { + type: 'response_item', + timestamp: '2026-11-03T19:00:01.000Z', + payload: { type: 'message', role: 'user', content: 'Remember the nonce 57319' } + } + ] + .map((row) => JSON.stringify(row)) + .join('\n')}\n` + ) + return { + sessionId: COPY, + filePath, + coverage: { unit: 'codex-turn' as const, ids: ['completed-turn'] } + } + } + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preparation reads only these source/store/adapter facets; destination founding uses the real rig host below. + const host = { + deps: { + store: { + selectWritableRecord: () => ({ kind: 'writable' }), + requireWritableRecord: () => record, + listConversations: () => [], + admittedSendCount: () => admissions + }, + agents: { capabilities: () => ({ fork: capability }) }, + adapter: { copyConversation: copy }, + logger: { warn: vi.fn() }, + resolveWorkspacePath: async () => rig.root + }, + journalSnapshot: async () => snapshot + } as unknown as StructuredAgentSessionHost + const intent = structuredAgentSessionCreateParams({ + sessionId: `${agent}_independent_child`, + agent, + worktree: 'id:workspace-1', + forkFrom: { + sessionId: record.sessionId, + throughItemId: 'legacy:codex:source:selected-response' + }, + now: rig.clock.now, + randomUuid: () => '00000000-0000-0000-0000-000000000123' + }) + const prepare = () => + prepareStructuredAgentSessionFork({ + host, + sessionId: record.sessionId, + throughItemId: 'legacy:codex:source:selected-response', + agent, + location: record.location, + envelope: intent.envelope + }) + return { + record, + snapshot, + copy, + host, + intent, + prepare, + admit: () => { + admissions++ + }, + tip: () => { + capability = 'tip' + snapshot.items = snapshot.items.filter( + (item) => item.itemId !== 'legacy:codex:source:running-root' + ) + } + } +} diff --git a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts index cc451d109d0..b23257f47a6 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test.ts @@ -1,16 +1,11 @@ -import type { StructuredAgentSessionAdapter } from '../../providers/structured-agent-session-adapter' +import { OrcaRuntimeService } from '../../../../runtime/orca-runtime' +import { forkTestSource } from './structured-agent-session-fork.test-fixture' +import { resolveUncommittedStructuredCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal' +import { handleStructuredAgentSessionCreate } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-create-handler' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { mkdir, writeFile } from 'node:fs/promises' -import { join } from 'node:path' import { agentSessionRecordFixture } from '../../../agent-session-record-test-fixture' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { AgentJournalSnapshot } from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import { prepareStructuredAgentSessionFork } from '../structured-agent-session-fork' -import type { StructuredAgentSessionHost } from '../../host/structured-agent-session-host' import { createRestTestRig, type RestTestRig @@ -31,215 +26,7 @@ afterEach(async () => { vi.restoreAllMocks() }) -function source(agent: 'claude' | 'codex' = 'codex') { - let admissions = 0 - let capability: 'checkpoint' | 'tip' = 'checkpoint' - const record = agentSessionRecordFixture({ - sessionId: 'source-chat', - provider: agent, - accountHome: { - variable: agent === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME', - path: join(rig.root, 'source-account') - }, - options: { model: 'retired-model', effort: 'high', fastMode: 'false' }, - permissionMode: 'accept-edits', - launchArgs: ['--no-daemon'], - launchDirectory: rig.root, - providerHandleChain: [ - { - linkId: 'source-head', - origin: 'created', - mintedAtFence: 1, - observedAt: 1, - handle: - agent === 'claude' ? claudeProviderHandle(SOURCE, 'answer') : codexProviderHandle(SOURCE) - } - ] - }) - const snapshot: AgentJournalSnapshot = { - sessionId: record.sessionId, - cursor: { epoch: 'source-epoch', sequence: 5 }, - submissions: [], - items: [ - { - itemId: agentJournalItemKey({ - provider: 'codex', - threadId: SOURCE, - turnId: 'completed-turn', - ordinal: 0 - }), - sequence: 1, - revision: 1, - observedAt: 1, - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Remember the nonce 57319' }] - } - }, - { - itemId: 'legacy:codex:source:ended-root', - sequence: 2, - revision: 1, - observedAt: 2, - body: { kind: 'turn', turnId: 'completed-turn', state: 'completed' } - }, - { - itemId: 'legacy:codex:source:selected-response', - sequence: 3, - revision: 1, - observedAt: 3, - turnScope: { kind: 'turn', turnItemId: 'legacy:codex:source:ended-root' }, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Remembered' }] } - }, - { - itemId: 'legacy:codex:source:running-root', - sequence: 3, - revision: 1, - observedAt: 3, - body: { kind: 'turn', turnId: 'active-turn', state: 'running' } - }, - { - itemId: 'legacy:codex:source:ended-child', - sequence: 4, - revision: 1, - observedAt: 4, - agentId: 'child', - body: { kind: 'turn', turnId: 'child-turn', state: 'completed' } - } - ] - } - const copy = vi.fn( - async ( - _input: Parameters>[0] - ): ReturnType> => { - const dir = - agent === 'claude' - ? join(rig.root, 'source-account', 'projects', 'workspace') - : join(rig.root, 'source-account', 'sessions', '2026', '11', '03') - await mkdir(dir, { recursive: true }) - const filePath = join( - dir, - agent === 'claude' ? `${COPY}.jsonl` : `rollout-2026-11-03T19-00-00-${COPY}.jsonl` - ) - if (agent === 'claude') { - await writeFile( - filePath, - `${[ - { - type: 'user', - uuid: 'prompt', - parentUuid: null, - sessionId: COPY, - timestamp: '2026-11-03T19:00:00.000Z', - cwd: rig.root, - message: { role: 'user', content: 'Remember the nonce 57319' } - }, - { - type: 'assistant', - uuid: 'answer', - parentUuid: 'prompt', - sessionId: COPY, - timestamp: '2026-11-03T19:00:01.000Z', - message: { - id: 'msg_answer', - role: 'assistant', - model: 'claude-opus-5-5', - content: [{ type: 'text', text: 'Remembered' }], - stop_reason: 'end_turn' - } - } - ] - .map((row) => JSON.stringify(row)) - .join('\n')}\n` - ) - return { - sessionId: COPY, - filePath, - coverage: { - unit: agent === 'claude' ? 'claude-entry' : 'codex-turn', - ids: agent === 'claude' ? ['prompt', 'answer'] : ['completed-turn'] - }, - ...(agent === 'claude' ? { resumeCursor: 'answer' } : {}) - } - } - await writeFile( - filePath, - `${[ - { - type: 'session_meta', - payload: { id: COPY, timestamp: '2026-11-03T19:00:00.000Z', cwd: rig.root } - }, - { - type: 'response_item', - timestamp: '2026-11-03T19:00:01.000Z', - payload: { type: 'message', role: 'user', content: 'Remember the nonce 57319' } - } - ] - .map((row) => JSON.stringify(row)) - .join('\n')}\n` - ) - return { - sessionId: COPY, - filePath, - coverage: { unit: 'codex-turn' as const, ids: ['completed-turn'] } - } - } - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preparation reads only these source/store/adapter facets; destination founding uses the real rig host below. - const host = { - deps: { - store: { - selectWritableRecord: () => ({ kind: 'writable' }), - requireWritableRecord: () => record, - listConversations: () => [], - admittedSendCount: () => admissions - }, - agents: { capabilities: () => ({ fork: capability }) }, - adapter: { copyConversation: copy }, - logger: { warn: vi.fn() }, - resolveWorkspacePath: async () => rig.root - }, - journalSnapshot: async () => snapshot - } as unknown as StructuredAgentSessionHost - const intent = structuredAgentSessionCreateParams({ - sessionId: `${agent}_independent_child`, - agent, - worktree: 'id:workspace-1', - forkFrom: { - sessionId: record.sessionId, - throughItemId: 'legacy:codex:source:selected-response' - }, - now: rig.clock.now, - randomUuid: () => '00000000-0000-0000-0000-000000000123' - }) - const prepare = () => - prepareStructuredAgentSessionFork({ - host, - sessionId: record.sessionId, - throughItemId: 'legacy:codex:source:selected-response', - agent, - location: record.location, - envelope: intent.envelope - }) - return { - record, - snapshot, - copy, - host, - intent, - prepare, - admit: () => { - admissions++ - }, - tip: () => { - capability = 'tip' - snapshot.items = snapshot.items.filter( - (item) => item.itemId !== 'legacy:codex:source:running-root' - ) - } - } -} +const source = (agent: 'claude' | 'codex' = 'codex') => forkTestSource(rig, agent) it('rejects a tip-only copy if a same-head send is admitted during capture', async () => { const test = source() @@ -334,10 +121,198 @@ it('refuses a tip copy after its source head relaunches', async () => { ] return nativeCopy(input) }) - await expect(test.prepare()).rejects.toMatchObject({ + const result = await resolveUncommittedStructuredCreate(test.prepare) + expect(result).toMatchObject({ refusal: { code: 'agent_session_operation_invalid', details: { reason: 'savedConversationMissing' } } }) + expect(result).not.toHaveProperty('refusal.createAttemptRefusedBeforeCommit') +}) + +it('coalesces concurrent fork create replay and refuses a conflicting fork intent', async () => { + const test = source() + const getRecord = rig.store.getRecord.bind(rig.store) + const writable = rig.store.requireWritableRecord.bind(rig.store) + const select = rig.store.selectWritableRecord.bind(rig.store) + const snapshot = rig.host.journalSnapshot.bind(rig.host) + vi.spyOn(rig.store, 'getRecord').mockImplementation((id) => + id === 'source-chat' ? test.record : getRecord(id) + ) + vi.spyOn(rig.store, 'requireWritableRecord').mockImplementation((id) => + id === 'source-chat' ? test.record : writable(id) + ) + vi.spyOn(rig.store, 'selectWritableRecord').mockImplementation((id) => + id === 'source-chat' ? { kind: 'writable', record: test.record } : select(id) + ) + vi.spyOn(rig.host, 'journalSnapshot').mockImplementation((id) => + id === 'source-chat' ? Promise.resolve(test.snapshot) : snapshot(id) + ) + const capabilities = rig.host.deps.agents.capabilities.bind(rig.host.deps.agents) + vi.spyOn(rig.host.deps.agents, 'capabilities').mockImplementation((agent) => { + const supported = capabilities(agent) + return supported ? { ...supported, fork: 'checkpoint' } : null + }) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const nativeCopy = test.copy.getMockImplementation()! + test.copy.mockImplementation(async (input) => { + entered.resolve() + await release.promise + return nativeCopy(input) + }) + rig.host.deps.adapter.copyConversation = test.copy + setStructuredAgentSessionHost(rig.host) + const runtime = new OrcaRuntimeService() + vi.spyOn(runtime, 'resolveStructuredAgentSessionLocation').mockResolvedValue(test.record.location) + vi.spyOn(runtime, 'publishStructuredAgentSessionTab').mockResolvedValue(undefined) + const ctx = { runtime, clientId: 'device-1' } + const first = handleStructuredAgentSessionCreate(test.intent, ctx) + await entered.promise + const replay = handleStructuredAgentSessionCreate(test.intent, ctx) + release.resolve() + const results = await Promise.all([first, replay]) + expect(results).toMatchObject([ + { ok: true, value: { sessionId: 'codex_independent_child' } }, + { ok: true, replayed: true, value: { sessionId: 'codex_independent_child' } } + ]) + const conflicting = structuredAgentSessionCreateParams({ + ...test.intent, + sessionId: test.intent.envelope.sessionId, + forkFrom: { sessionId: 'another-source', throughItemId: 'other-response' }, + now: rig.clock.now, + randomUuid: () => '00000000-0000-0000-0000-000000000123' + }) + expect(await handleStructuredAgentSessionCreate(conflicting, ctx)).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_operation_conflict' } + }) +}) + +it('forks an inherited Codex reply through its original and refuses it after the original rewinds', async () => { + const test = source() + test.snapshot.items[2]!.itemId = 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1' + const first = agentSessionRecordFixture({ + ...test.record, + sessionId: 'first-fork', + providerHandleChain: [ + { ...test.record.providerHandleChain[0]!, handle: codexProviderHandle(COPY) } + ], + forkedFrom: { + sessionId: 'source-chat', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1', + childBoundary: { + kind: 'item', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1' + } + } + }) + const second = agentSessionRecordFixture({ + ...first, + sessionId: 'second-fork', + providerHandleChain: [ + { + ...first.providerHandleChain[0]!, + handle: codexProviderHandle('019e6b26-18e2-7103-b7a0-7ba6bb071125') + } + ], + forkedFrom: { + sessionId: 'first-fork', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1', + childBoundary: { + kind: 'item', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071125:completed-turn:1' + } + } + }) + const records = new Map([test.record, first, second].map((record) => [record.sessionId, record])) + Object.assign(test.host.deps.store, { + getRecord: (id: string) => records.get(id) ?? null, + selectWritableRecord: (id: string) => ({ kind: records.has(id) ? 'writable' : 'missing' }), + requireWritableRecord: (id: string) => records.get(id)! + }) + test.host.journalSnapshot = async (id) => { + if (id === 'source-chat') { + return test.snapshot + } + const thread = id === 'first-fork' ? COPY : '019e6b26-18e2-7103-b7a0-7ba6bb071125' + return { + ...test.snapshot, + sessionId: id, + items: test.snapshot.items.map((item) => ({ + ...item, + itemId: item.itemId.replace(SOURCE, thread) + })) + } + } + const prepare = () => + prepareStructuredAgentSessionFork({ + host: test.host, + sessionId: 'second-fork', + throughItemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071125:completed-turn:1', + agent: 'codex', + location: test.record.location, + envelope: test.intent.envelope + }) + expect((await prepare()).fork).toMatchObject({ + sessionId: 'source-chat', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1' + }) + expect(test.copy.mock.calls[0]![0]).toMatchObject({ + record: { sessionId: 'source-chat' }, + providerSessionId: '019e6b26-18e2-7103-b7a0-7ba6bb071123', + checkpoint: { selectedItemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1' } + }) + const retainedCopies = new Map([ + ['first-fork', await test.host.journalSnapshot('first-fork')], + ['second-fork', await test.host.journalSnapshot('second-fork')] + ]) + test.host.journalSnapshot = async (id) => retainedCopies.get(id) ?? test.snapshot + test.snapshot.items = test.snapshot.items.slice(0, 1) + expect(await resolveUncommittedStructuredCreate(prepare)).toMatchObject({ + refusal: { + code: 'agent_session_operation_invalid', + details: { reason: 'savedConversationMissing' }, + createAttemptRefusedBeforeCommit: true + } + }) + records.delete('source-chat') + expect(await resolveUncommittedStructuredCreate(prepare)).toMatchObject({ + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' }, + createAttemptRefusedBeforeCommit: true + } + }) +}) + +it('checks an inherited tip against the original and refuses after the original advances', async () => { + const test = source() + test.tip() + const inherited = structuredClone(test.snapshot) + test.record.forkedFrom = { + sessionId: 'original', + itemId: 'legacy:codex:source:selected-response', + childBoundary: { kind: 'item', itemId: 'legacy:codex:source:selected-response' } + } + const original = { ...test.record, sessionId: 'original', forkedFrom: undefined } + test.host.deps.store.requireWritableRecord = (id) => (id === 'original' ? original : test.record) + test.host.deps.store.getRecord = (id) => (id === 'original' ? original : test.record) + test.host.journalSnapshot = async (id) => (id === 'original' ? test.snapshot : inherited) + expect((await test.prepare()).fork?.sessionId).toBe('original') + test.snapshot.items.push({ + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:later-user:0', + sequence: 10, + revision: 1, + observedAt: 10, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'new original prompt' }] } + }) + expect(await resolveUncommittedStructuredCreate(test.prepare)).toMatchObject({ + refusal: { + code: 'agent_session_operation_invalid', + details: { reason: 'turnActive' }, + createAttemptRefusedBeforeCommit: true + } + }) }) diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts index af255f5b5f1..b3f25e8c522 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts @@ -40,3 +40,14 @@ export async function resumeStructuredQueue( await journal.appendQueueResume(fence, receipt) return true } + +/** A person's chosen continuation is their recovery from a restart; other pauses keep their own lift. */ +export async function liftStructuredQueueRestartHold( + journal: Pick, + fence: number +): Promise { + const pauses = structuredQueuePauses(journal) + if (pauses.length > 0 && pauses.every((pause) => pause.reason === 'restarted')) { + await journal.appendQueueResume(fence) + } +} diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts index 5cbacc66709..47a2ed7ede4 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts @@ -63,6 +63,10 @@ import type { AgentSessionSwitchResult } from '../../../../shared/agent-session/ export type StructuredAgentSessionCaller = { callerKey: string clientKind?: 'mobile' | 'runtime' + /** Proven by the caller's transport, never inferred from an unnamed/runtime client. */ + userClient?: 'desktop' | 'mobile' + /** Consent-owning paired desktop, including the authenticated parent of a delegated phone. */ + telemetryOwnerKey?: string readsOptionsWithoutModel?: boolean } diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-publication-wiring.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-publication-wiring.ts index f9f95f85f73..7e2734eb44e 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-publication-wiring.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-publication-wiring.ts @@ -1,3 +1,4 @@ +import { observeNativeChatPromptSubmissions } from '../../../telemetry/native-chat-prompt-submissions' import { StructuredAgentSessionConversations } from './structured-agent-session-conversations' import type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types' import type { StructuredAgentSessionClientDelivery } from '../publication/subscribers/structured-agent-session-client-delivery' @@ -20,6 +21,7 @@ export function createStructuredAgentSessionPublicationWiring(input: { observe: (id, journal, rows) => { input.client().requestFailures.observe(id, journal, rows) input.observeRows()?.(id, journal, rows) + observeNativeChatPromptSubmissions(journal, rows) }, forget: (id) => input.client().requestFailures.forget(id), deliver: (id, journal, inputChanged) => { diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts index 94d59e48699..f2b61430a39 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, vi } from 'vitest' import type { AgentStatusStructuredSessionSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { runClaudeControl } from '../../../../claude/claude-agent-sdk-control-requests' import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' import type { ClaudeStructuredSessionEvent } from '../../../../claude/structured/claude-structured-session-event' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts new file mode 100644 index 00000000000..174e754f079 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-prompt-telemetry.test.ts @@ -0,0 +1,250 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { RpcContext } from '../../../../runtime/rpc/core' +import type { RpcCallerIdentity } from '../../../../runtime/rpc/rpc-caller-identity' +import { structuredCallerFor } from '../../../../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate' +import { createTestParams } from './structured-agent-session-create-test-fixture' +import { isTelemetryInitialized, track } from '../../../../telemetry/client' +import { subscribeStructuredChatTelemetry } from '../../../../telemetry/structured-chat-dispatch' +import type { StructuredChatTelemetryEvent } from '../../../../../shared/structured-chat-dispatch-telemetry' +import { + createQueuedMessageTestRig, + type QueuedMessageTestRig +} from './structured-agent-session-queued-message-rig.test-fixture' +import { eventually } from './structured-agent-session-queued-message-rig-provider.test-fixture' +import { openRigTurnFor } from './structured-agent-session-queued-rig-turn.test-fixture' +import { + HOST_TEST_SESSION, + HOST_TEST_THREAD, + hostTestMessage, + hostTestOperationId, + hostTestSendParams +} from './structured-agent-session-host-test-data' + +vi.mock('../../../../telemetry/client', () => ({ + track: vi.fn(), + isTelemetryInitialized: vi.fn(() => true) +})) + +let rig: QueuedMessageTestRig +const prompts = () => + vi.mocked(track).mock.calls.filter(([name]) => name === 'native_chat_prompt_submitted') + +function transportCaller( + caller?: RpcCallerIdentity, + clientKind?: 'mobile' | 'runtime', + pairedDeviceParentId?: string +) { + const context: Partial = { caller, clientKind, pairedDeviceParentId } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: caller derivation reads only transport identity fields supplied here. + return structuredCallerFor(context as RpcContext) +} +const desktop = () => transportCaller({ kind: 'desktop' }) + +beforeEach(async () => { + vi.clearAllMocks() + vi.mocked(isTelemetryInitialized).mockReturnValue(true) + rig = await createQueuedMessageTestRig() +}) +afterEach(async () => rig.dispose()) + +it('counts a desktop prompt at provider acceptance, excluding handover, rejection and replay', async () => { + const rejected = { ...hostTestSendParams('private rejected prompt'), userSend: true as const } + await rig.host.send(desktop(), rejected) + const refused = rejected.envelope.clientOperationId + await eventually(async () => expect((await rig.submission(refused))?.handedOverAt).toBeDefined()) + expect(prompts()).toEqual([]) + await rig.settleRejected(refused, 'Provider refused this prompt') + expect(prompts()).toEqual([]) + + const params = { ...hostTestSendParams('private accepted prompt'), userSend: true as const } + await rig.host.send(desktop(), params) + await eventually(async () => + expect((await rig.submission(params.envelope.clientOperationId))?.handedOverAt).toBeDefined() + ) + expect(prompts()).toEqual([]) + await rig.settleAccepted(params.envelope.clientOperationId, 'accepted-desktop') + const expected = [ + ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'desktop' }] + ] + expect(prompts()).toEqual(expected) + + await rig.host.send(desktop(), params) + expect(prompts()).toEqual(expected) +}) + +it('keeps the phone provenance through automatic queued handoff and ignores withdrawn cards', async () => { + const working = await rig.workingSend() + const caller = transportCaller({ kind: 'paired-device', deviceId: 'phone-1' }, 'mobile') + const queue = async (text: string) => { + const id = hostTestOperationId() + const fields = { body: hostTestMessage(text), delivery: 'queue-if-active' as const } + const answer = await rig.host.send(caller, { + envelope: rig.envelope(fields, 'agentSession.send', id), + ...fields, + userSend: true + }) + expect(answer).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) + return id + } + const withdrawn = await queue('private withdrawn phone prompt') + await rig.deleteQueued(withdrawn) + const waiting = await queue('private queued phone prompt') + expect(prompts()).toEqual([]) + + await rig.settleRejected(working, 'End the earlier request without accepting it') + await eventually(async () => expect((await rig.handoff(waiting))?.handedOverAt).toBeDefined()) + expect(prompts()).toEqual([]) + const handedOver = await rig.handoffId(waiting) + await rig.settleAccepted(handedOver, 'accepted-phone') + expect(prompts()).toEqual([ + ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'mobile' }] + ]) + expect((await rig.host.history({ sessionId: HOST_TEST_SESSION, direction: 'tail' })).ok).toBe( + true + ) + expect(prompts()).toEqual([ + ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'mobile' }] + ]) +}) + +it('does not treat provider-accepted commands or internal messages as user prompts', async () => { + const fields = { command: 'compact' as const } + const commandId = hostTestOperationId() + expect( + await rig.host.conversationCommand(desktop(), { + envelope: rig.envelope(fields, 'agentSession.conversationCommand', commandId), + ...fields + }) + ).toMatchObject({ ok: true }) + await eventually(async () => + expect( + ((await rig.submission(commandId)) ?? (await rig.handoff(commandId)))?.dispatchState + ).toBe('accepted') + ) + rig.finishCompact() + expect(prompts()).toEqual([]) + + const internal = rig.send('private unattended agent message', undefined, { internal: true }) + await internal.result + await eventually(async () => + expect((await rig.submission(internal.id))?.handedOverAt).toBeDefined() + ) + await rig.settleAccepted(internal.id, 'accepted-internal') + expect(prompts()).toEqual([]) +}) + +it('excludes CLI and unproven runtime callers even when their send uses userSend', async () => { + for (const caller of [ + transportCaller({ kind: 'local-cli' }), + transportCaller({ kind: 'local-cli' }, 'runtime'), + transportCaller(undefined, 'runtime'), + transportCaller() + ]) { + const params = { ...hostTestSendParams('private automated prompt'), userSend: true as const } + await rig.host.send(caller, params) + await eventually(async () => + expect((await rig.submission(params.envelope.clientOperationId))?.handedOverAt).toBeDefined() + ) + await rig.settleAccepted(params.envelope.clientOperationId, params.envelope.clientOperationId) + } + expect(prompts()).toEqual([]) +}) + +it('counts the trusted desktop opening message only after its provider accepts it', async () => { + const sessionId = 'new-chat-with-first-prompt' + const firstMessage = { + clientMessageId: hostTestOperationId(), + body: hostTestMessage('private opening prompt') + } + const params = createTestParams(firstMessage, {}, sessionId) + expect(await rig.host.create(desktop(), params, { firstMessage })).toMatchObject({ ok: true }) + await eventually(async () => + expect( + (await rig.host.journalSnapshot(sessionId)).submissions.find( + (entry) => entry.clientMessageId === firstMessage.clientMessageId + )?.handedOverAt + ).toBeDefined() + ) + expect(prompts()).toEqual([]) + await rig.host.settleLateDispatch({ + sessionId, + clientMessageId: firstMessage.clientMessageId, + providerIdentity: { + provider: 'codex', + threadId: HOST_TEST_THREAD, + turnId: 'opening-turn', + ordinal: 0 + } + }) + expect(prompts()).toEqual([ + ['native_chat_prompt_submitted', { agent_kind: 'codex', runtime: 'unknown', client: 'desktop' }] + ]) +}) + +it('relays only provider acceptance with the authenticated desktop or delegated phone owner', async () => { + vi.mocked(isTelemetryInitialized).mockReturnValue(false) + const events: { event: StructuredChatTelemetryEvent; owner: string }[] = [] + const unsubscribe = subscribeStructuredChatTelemetry((event, owner) => + events.push({ event, owner }) + ) + try { + const caller = transportCaller({ kind: 'paired-device', deviceId: 'desktop-a' }, 'runtime') + const desktopSend = { ...hostTestSendParams('private desktop prompt'), userSend: true as const } + await rig.host.send(caller, desktopSend) + await eventually(async () => + expect( + (await rig.submission(desktopSend.envelope.clientOperationId))?.handedOverAt + ).toBeDefined() + ) + expect(events).toEqual([]) + + const queuedId = hostTestOperationId() + const fields = { + body: hostTestMessage('private phone prompt'), + delivery: 'queue-if-active' as const + } + const phone = transportCaller( + { kind: 'paired-device', deviceId: 'delegated-phone' }, + 'mobile', + 'desktop-a' + ) + await rig.host.send(phone, { + envelope: rig.envelope(fields, 'agentSession.send', queuedId), + ...fields, + userSend: true + }) + expect(events).toEqual([]) + await rig.settleAccepted( + desktopSend.envelope.clientOperationId, + `of-${desktopSend.envelope.clientOperationId}` + ) + await rig.host.send(caller, desktopSend) + await openRigTurnFor(rig, desktopSend.envelope.clientOperationId, 'completed', 'success') + await eventually(async () => expect((await rig.handoff(queuedId))?.handedOverAt).toBeDefined()) + await rig.settleAccepted(await rig.handoffId(queuedId), 'remote-phone-turn') + expect(events).toEqual([ + { + owner: 'desktop-a', + event: { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'codex', + client: 'desktop' + } + }, + { + owner: 'desktop-a', + event: { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'codex', + client: 'mobile' + } + } + ]) + expect(events[0].event.id).not.toBe(events[1].event.id) + expect(prompts()).toEqual([]) + } finally { + unsubscribe() + } +}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts index fbcbaffaf00..8e40358d691 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts @@ -134,7 +134,8 @@ export async function interruptedRestart( const fields = { body, delivery: 'queue-if-active' as const } const queued = await previous.host.send(CALLER, { envelope: envelope('agentSession.send', fields), - ...fields + ...fields, + userSend: true }) expect(queued).toMatchObject({ ok: true, value: { queued: expect.anything() } }) } diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind.test.ts index 020eb3ec5ca..966639a089f 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind.test.ts @@ -1,3 +1,10 @@ +import { AgentSessionJournal } from '../../../agent-session-journal/journal-store' +import { recoverStructuredRewind } from '../../rewind/structured-rewind-recovery' +import { persistRewindRecord } from '../../rewind/structured-rewind-record' +import { + projectForkMarker, + readForkMarker +} from '../../publication/history/agent-session-fork-marker' import { expectAtomicRewindCompletion } from './structured-agent-session-rewind-replay.test-fixture' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' import { mkdtemp, rm } from 'node:fs/promises' @@ -240,3 +247,127 @@ it('persists the live native predecessor before revert and retains it after a lo keptTurnId: 'kept' }) }) + +it('refuses inherited rewind and rewinds the first own prompt to the fork point', async () => { + const inherited = await seed() + const ancestry = { + sessionId: 'original-chat', + itemId: 'codex:original-thread:tip:0', + childBoundary: { + kind: 'item' as const, + itemId: agentJournalItemKey({ + provider: 'codex', + threadId: HOST_TEST_THREAD, + turnId: 'tip', + ordinal: 0 + }) + } + } + await store.commitOperationReceipt( + store.conversationReceipts.forkBoundary(HOST_TEST_SESSION, ancestry) + ) + expect(await host.rewind(caller, await params(inherited))).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_operation_invalid', + details: { rewindReason: 'invalid-target' } + } + }) + sink.appendItem( + { provider: 'codex', threadId: HOST_TEST_THREAD, turnId: 'own', ordinal: 0 }, + { ...hostTestMessage('first own prompt'), role: 'user' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await host.flushStreamedEvents(HOST_TEST_SESSION) + adapter.prepareRewind = async () => ({ + ok: true, + revert: { threadId: HOST_TEST_THREAD, beforeTurnId: 'own', keptTurnId: 'tip' } + }) + const own = agentJournalItemKey({ + provider: 'codex', + threadId: HOST_TEST_THREAD, + turnId: 'own', + ordinal: 0 + }) + expect(await host.rewind(caller, await params(own))).toMatchObject({ ok: true }) + expect(store.getRecord(HOST_TEST_SESSION)?.forkedFrom).toEqual(ancestry) + expect( + (await host.journalSnapshot(HOST_TEST_SESSION)).items + .filter((item) => item.body.kind === 'message') + .map((item) => item.body.kind === 'message' && item.body.blocks) + ).toEqual([ + [{ type: 'text', text: '0' }], + [{ type: 'text', text: '1' }], + [{ type: 'text', text: '2' }] + ]) +}) + +it('completes an inherited rewind saved by the PR1 build with an atomic surviving divider after restart', async () => { + const target = await seed() + const fence = store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence + const journal = host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal + await store.commitOperationReceipt( + store.conversationReceipts.forkBoundary(HOST_TEST_SESSION, { + sessionId: 'original-chat', + itemId: 'codex:original-thread:tip:0', + childBoundary: { kind: 'item', itemId: 'codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:tip:0' } + }) + ) + await persistRewindRecord(store, HOST_TEST_SESSION, fence, { + operationId: hostTestOperationId(), + callerKey: 'desktop', + itemId: target, + expectedEpoch: journal.epoch, + phase: 'provider-succeeded', + providerRevert: { + threadId: '019fd532-7c11-7a90-b6de-4e1a2c3d5f60', + beforeTurnId: 'drop', + keptTurnId: 'kept' + } + }) + await journal.close() + store = await openTestAgentSessionRecordStore(directory) + const reopened = new AgentSessionJournal({ + identity: { + sessionId: HOST_TEST_SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('019fd532-7c11-7a90-b6de-4e1a2c3d5f60') + }, + database: openTestJournalHostDatabase(directory) + }) + await reopened.open() + const replace = reopened.replaceEpochItems.bind(reopened) + vi.spyOn(reopened, 'replaceEpochItems').mockImplementationOnce(async (...args) => { + await replace(...args) + throw new Error('crash after atomic completion') + }) + await expect( + recoverStructuredRewind( + { store, logger: createStructuredAgentSessionLogger() }, + HOST_TEST_SESSION, + reopened, + fence + ) + ).rejects.toThrow('crash after atomic completion') + await reopened.close() + store = await openTestAgentSessionRecordStore(directory) + await reopened.open() + await recoverStructuredRewind( + { store, logger: createStructuredAgentSessionLogger() }, + HOST_TEST_SESSION, + reopened, + fence + ) + expect(store.getRecord(HOST_TEST_SESSION)?.forkedFrom?.childBoundary).toEqual({ + kind: 'item', + itemId: 'codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:kept:0' + }) + expect( + projectForkMarker(reopened.snapshot(), readForkMarker(store, HOST_TEST_SESSION)).items.map( + (item) => item.itemId + ) + ).toEqual(['codex:019fd532-7c11-7a90-b6de-4e1a2c3d5f60:kept:0', 'orca:forked-from']) + await reopened.close() +}) diff --git a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts index 4411c7a9902..1bb9432b0ab 100644 --- a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts +++ b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts @@ -7,7 +7,7 @@ import type { AgentSessionExecutionLocation } from '../../../../../shared/agent- import type { AgentSessionHandleProvider } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { AgentSessionJournal } from '../../../agent-session-journal/journal-store' import { createTrackedJournalOpener } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { indexedStatusFeedSession } from './structured-agent-session-status-feed-test-session' import { StructuredAgentSessionStatusFeed } from '../structured-agent-session-status-feed' diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts index 0fb519d98fe..e05d409093c 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-host-mutations.ts @@ -1,6 +1,10 @@ // Share mutation admission/planning/publication. Conversation writes need no child lease; // provider-only effects start their child before admission, sends start through delivery. +import { + forgetNativeChatPrompt, + rememberNativeChatPrompt +} from '../../../telemetry/native-chat-prompt-submissions' import { latestNativeChatUsageLimitCut } from '../../../../shared/native-chat/native-chat-usage-limit-cut' import { refuse } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import type { @@ -110,7 +114,30 @@ export function sendStructuredAgentSessionTurn( } } params.beforeRun?.() - return runQueueableStructuredAgentSessionSend(context, ctx, params, () => plan.run(ctx)) + if (params.userSend && !params.body.command) { + rememberNativeChatPrompt( + ctx.journal, + params.envelope.clientOperationId, + ctx.agent, + caller.userClient, + caller.telemetryOwnerKey + ) + } + try { + const sent = await runQueueableStructuredAgentSessionSend(context, ctx, params, () => + plan.run(ctx) + ) + if (!sent.ok) { + forgetNativeChatPrompt(ctx.journal, params.envelope.clientOperationId) + } + return sent + } catch (error) { + const id = params.envelope.clientOperationId + if (!ctx.journal.submission(id) && !ctx.journal.queuedMessages.get(id)) { + forgetNativeChatPrompt(ctx.journal, id) + } + throw error + } } }, sendPreparation(context, params.envelope, arrival, selection) diff --git a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns.ts b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns.ts index 21ce6eeb569..74898e1589e 100644 --- a/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns.ts +++ b/src/main/native-chat/agent-session-wire/operations/structured-agent-session-turns.ts @@ -1,6 +1,10 @@ // Admission already passed; journal before adapter effects so a crash leaves recoverable unknown work. // Calling the adapter first could lose a turn it accepted. +import { + forgetNativeChatPrompt, + rememberNativeChatPrompt +} from '../../../telemetry/native-chat-prompt-submissions' import { captureStructuredExecutionOptions } from '../options/structured-agent-session-execution-options' import type { AgentSessionFailureWordsContext } from '../../../../shared/agent-session/failures/agent-session-failure-words' import type { @@ -128,7 +132,9 @@ export async function performSend( source?: AgentSessionMessageSource options?: Readonly> selection?: Readonly> - } + }, + userClient?: 'desktop' | 'mobile', + telemetryOwnerKey?: string ): Promise> { const existing = ctx.journal.submission(input.clientMessageId) if (existing && existing.payloadFingerprint !== input.payloadFingerprint) { @@ -148,12 +154,22 @@ export async function performSend( return { ok: false, refusal: captured.refusal } } try { + if (!input.body.command) { + rememberNativeChatPrompt( + ctx.journal, + input.clientMessageId, + ctx.agent, + userClient, + telemetryOwnerKey + ) + } await ctx.journal.appendSubmission( { ...input, options: captured.options, fence: ctx.fence, handoverRecorded: true }, undefined, ctx.operationReceipt ) } catch (error) { + forgetNativeChatPrompt(ctx.journal, input.clientMessageId) return agentSessionAdmissionWriteRefusal(ctx, error) } return { diff --git a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-fork-marker.test.ts b/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-fork-marker.test.ts deleted file mode 100644 index 0ed36a13654..00000000000 --- a/src/main/native-chat/agent-session-wire/publication/history/testing/agent-session-fork-marker.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { expect, it } from 'vitest' -import { agentJournalItemKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { ForkMarker } from '../agent-session-fork-marker' -import { remapForkChildBoundary } from '../../../rewind/agent-session-fork-boundary-remap' -import { fixture, appendItems, item, body } from './agent-session-history-contract-test-fixture' - -function marker(): ForkMarker { - return { - forkedFrom: { - sessionId: 'source-session', - itemId: 'source-reply', - childBoundary: { kind: 'item', itemId: agentJournalItemKey(item(2)) } - }, - sourceName: 'Original chat' - } -} - -it('does not move a pre-clear inherited boundary when only later context is rewound', async () => { - await appendItems(4) - const old = fixture.journal.currentRead().items - const boundary = marker().forkedFrom.childBoundary - const kept = [{ identity: item(3), body: body('item-3'), ownerFence: 0 }] - expect(remapForkChildBoundary(boundary, old, kept, old[1].sequence)).toEqual({ - kind: 'item', - itemId: 'codex:thread-1:turn-1:2' - }) - expect( - remapForkChildBoundary(boundary, old, [ - { identity: item(1), body: body('item-1'), ownerFence: 0 } - ]) - ).toEqual({ kind: 'item', itemId: 'codex:thread-1:turn-1:1' }) -}) diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts index 9075f8218cd..a4ff1c78c62 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts @@ -32,6 +32,7 @@ import { AgentSessionPreDispatchError } from '../operations/structured-agent-ses import { restartContinuationEnvelope } from './structured-agent-session-restart-continuation-envelope' import type { AgentSessionResumeMarker } from '../../../../shared/agent-session/lifecycle/agent-session-resume-marker' import type { StructuredAgentSessionLogger } from '../host/structured-agent-session-logger' +import { liftStructuredQueueRestartHold } from '../delivery/structured-agent-session-queued-pause' /** Envelope acceptance proves only host ownership; preserve provider pending/unknown/rejected outcomes. */ export type StructuredAgentSessionContinuationOutcome = { @@ -90,7 +91,14 @@ export function continuationDeps( (await host.awaitSendHandedOver(sessionId, clientMessageId))?.value ), logger: host.logger, - note: restartNoteWriter(host) + note: restartNoteWriter(host), + liftRestartHold: async (sessionId) => { + const session = host.sessions.get(sessionId) + const fence = host.conversationFence(sessionId) + if (session && fence !== null) { + await liftStructuredQueueRestartHold(session.journal, fence) + } + } } } @@ -154,6 +162,8 @@ export type StructuredAgentSessionContinuationDeps = { ) => Promise /** Attribute host continuation/failure; older clients render tone as plain text. */ note: (sessionId: string, text: string, tone?: 'error' | 'warning') => Promise + /** Release cards held only by the restart once the person's continuation is accepted. */ + liftRestartHold: (sessionId: string) => Promise /** Required to report best-effort note failures. */ logger: StructuredAgentSessionLogger /** Answer at acceptance; caller reports pre-acceptance refusal without duplicate retry notes. */ @@ -198,11 +208,19 @@ export async function startStructuredAgentSessionContinuation( } async function noteOutcome( - deps: Pick, + deps: Pick, sessionId: string, result: StructuredAgentSessionContinuationOutcome ): Promise { if (result.outcome === 'continued') { + try { + await deps.liftRestartHold(sessionId) + } catch { + deps.logger.warn('releasing queued messages after a restart continuation failed', { + scope: 'restart-continuation-queue', + sessionId + }) + } // Attribute only accepted dispatch; note failure must not turn delivered work into failure. try { await deps.note(sessionId, AGENT_SESSION_RESTART_CONTINUATION_NOTE) diff --git a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts b/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts deleted file mode 100644 index 1e722273747..00000000000 --- a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { - startStructuredAgentSessionContinuation, - type StructuredAgentSessionContinuationDeps -} from '../structured-agent-session-restart-continuation' -import { - resumeStructuredAgentSessionsFromRestart, - StructuredAgentSessionResumeAdmission -} from '../structured-agent-session-restart-resume-runner' -import { marker } from './structured-agent-session-restart-resume-test-harness' -import { createStructuredAgentSessionLogger } from '../../host/structured-agent-session-logger' - -type Handover = { dispatchState: string; reason?: string | null } | undefined - -const LIMIT = 3 - -it('holds each slot from accept until handover or rejection, and frees it when the wait ends (P2-27)', async () => { - const handovers = new Map>() - let waiting = 0 - let mostWaiting = 0 - const deps = (sessionId: string): StructuredAgentSessionContinuationDeps => ({ - currentFence: () => 1, - send: vi.fn(async () => ({ ok: true, value: { submission: { dispatchState: 'pending' } } })), - awaitHandedOver: async () => { - const handover = Promise.withResolvers() - handovers.set(sessionId, handover) - waiting += 1 - mostWaiting = Math.max(mostWaiting, waiting) - try { - return await handover.promise - } finally { - waiting -= 1 - } - }, - awaitSettlement: async () => ({ dispatchState: 'accepted' }), - note: async () => undefined, - logger: createStructuredAgentSessionLogger() - }) - const sessions = Array.from({ length: 8 }, (_, index) => `session-${index}`) - const outcomes = resumeStructuredAgentSessionsFromRestart( - { - admission: new StructuredAgentSessionResumeAdmission(LIMIT), - consumeMarker: async () => true, - resume: async (sessionId) => { - const started = await startStructuredAgentSessionContinuation( - deps(sessionId), - sessionId, - marker(), - 'operation-1' - ) - if ('done' in started && started.done.outcome === 'refused') { - throw new Error(started.done.reason ?? 'refused') - } - } - }, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runner reads only each candidate's session id. - sessions.map((sessionId) => ({ sessionId }) as never), - 'modal' - ) - const settle = async (sessionId: string, handover: Handover) => { - await vi.waitFor(() => expect(handovers.has(sessionId)).toBe(true)) - handovers.get(sessionId)!.resolve(handover) - } - - await vi.waitFor(() => expect(waiting).toBe(LIMIT)) - // Acceptance alone must retain the startup slot until handover. - await new Promise((resolve) => setTimeout(resolve, 20)) - expect(handovers.size).toBe(LIMIT) - await settle('session-0', { dispatchState: 'pending' }) - await settle('session-1', { dispatchState: 'rejected', reason: 'Codex could not start.' }) - // An ended wait frees its slot without claiming delivery. - await settle('session-2', undefined) - for (const sessionId of sessions.slice(3)) { - await settle(sessionId, { dispatchState: 'pending' }) - } - - const results = await outcomes - expect(mostWaiting).toBe(LIMIT) - expect(results.find((result) => result.sessionId === 'session-1')).toMatchObject({ - outcome: 'refused', - reason: 'Codex could not start.' - }) - expect(results.filter((result) => result.outcome === 'resumed')).toHaveLength(7) -}) diff --git a/src/main/native-chat/agent-session-wire/rewind/structured-agent-session-rewind.ts b/src/main/native-chat/agent-session-wire/rewind/structured-agent-session-rewind.ts index b4c614a94f2..005d661e383 100644 --- a/src/main/native-chat/agent-session-wire/rewind/structured-agent-session-rewind.ts +++ b/src/main/native-chat/agent-session-wire/rewind/structured-agent-session-rewind.ts @@ -110,7 +110,9 @@ export async function rewindStructuredAgentSession( if (ctx.journal.cursor().epoch !== params.expectedEpoch) { return rewindRefusal('stale-epoch') } - if (!isStructuredRewindTarget(ctx.journal, params.itemId)) { + if ( + !isStructuredRewindTarget(ctx.journal, params.itemId, record.forkedFrom?.childBoundary) + ) { return rewindRefusal('invalid-target') } const head = agentSessionProviderHandleChainHead(record.providerHandleChain)?.handle diff --git a/src/main/native-chat/agent-session-wire/rewind/structured-rewind-cut.ts b/src/main/native-chat/agent-session-wire/rewind/structured-rewind-cut.ts index f2a9bc7767a..bbe6e97ae0d 100644 --- a/src/main/native-chat/agent-session-wire/rewind/structured-rewind-cut.ts +++ b/src/main/native-chat/agent-session-wire/rewind/structured-rewind-cut.ts @@ -1,3 +1,4 @@ +import { isInheritedAgentSessionItem } from '../../../../shared/agent-session/agent-session-fork' import { agentSessionProviderHandleChainHead } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { @@ -83,10 +84,15 @@ export function structuredRewindCut( } /** Admission only; already-saved rewinds complete even if their target is no longer eligible. */ -export function isStructuredRewindTarget(journal: AgentSessionJournal, itemId: string): boolean { +export function isStructuredRewindTarget( + journal: AgentSessionJournal, + itemId: string, + boundary?: NonNullable['childBoundary'] +): boolean { const item = journal.currentRead().items.find((row) => row.itemId === itemId) return ( item !== undefined && + !isInheritedAgentSessionItem(journal.currentRead().items, boundary, itemId) && isAgentSessionRewindTarget( item, (turnItemId) => readAgentJournalTurn(journal.itemBody(turnItemId) ?? undefined)?.userItemId diff --git a/src/main/native-chat/native-chat-open-wake.ts b/src/main/native-chat/native-chat-open-wake.ts index 8d6da959eba..ad8367aa90c 100644 --- a/src/main/native-chat/native-chat-open-wake.ts +++ b/src/main/native-chat/native-chat-open-wake.ts @@ -11,7 +11,7 @@ import { } from '../wsl/filesystem/wsl-unc-access-gate' import { wslGatedAccess } from './wsl-transcript-fs-access' import { WSL_TRANSCRIPT_RUNNING_LEASE_MS } from './wsl-transcript-running-admission' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { nativeChatTranscriptPathOnExecutionHost } from './ssh-transcript-path' type HookRow = Pick diff --git a/src/main/opencode/opencode-pty-launch.ts b/src/main/opencode/opencode-pty-launch.ts index 310c845749e..fc365a73472 100644 --- a/src/main/opencode/opencode-pty-launch.ts +++ b/src/main/opencode/opencode-pty-launch.ts @@ -1,7 +1,7 @@ import { addWslEnvKeys } from '../../shared/wsl-env' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { randomUUID, createHash } from 'node:crypto' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { tokenizeStartupCommand, type AgentStartupShell @@ -28,6 +28,7 @@ import { probeOpenCodeLaunchCapabilities } from './opencode-launch-capabilities' import { reserveOpenCodeStartupPrompt } from './opencode-startup-prompt-owner' import { installOpenCodeStartupPromptForLaunch } from './opencode-startup-prompt-installer' import { needsOpenCodePrivateServer, withOpenCodeStandaloneServer } from './opencode-private-server' +import { applyOpenCodeRootModelOverlay } from './opencode-root-model-launch' export async function prepareOpenCodePtyLaunch(options: { command: string | undefined @@ -138,6 +139,16 @@ export async function prepareOpenCodePtyLaunch(options: { } } if (capabilities.pluginApi === 'v2' && options.shell && !options.wsl && command) { + command = await applyOpenCodeRootModelOverlay({ + command, + shell: options.shell, + version: capabilities.version, + launchEnv, + probeEnv, + envToDelete: options.envToDelete, + cwd: options.cwd, + promptBody: body + }) // Only launches that would start the shared service may claim its port. const standalone = withOpenCodeStandaloneServer(command, options.shell) if (standalone !== command && needsOpenCodePrivateServer(probeEnv)) { diff --git a/src/main/opencode/opencode-root-model-launch.test.ts b/src/main/opencode/opencode-root-model-launch.test.ts new file mode 100644 index 00000000000..4158475d6db --- /dev/null +++ b/src/main/opencode/opencode-root-model-launch.test.ts @@ -0,0 +1,65 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import { prepareOpenCodePtyLaunch } from './opencode-pty-launch' +import { quoteStartupArg } from '../../shared/agent-launch/startup/tui-agent-startup-shell' +import { OPENCODE_STARTUP_PROMPT_BODY_ENV } from '../../shared/agent-launch/startup/opencode-startup-prompt' + +const run = vi.hoisted(() => vi.fn()) +vi.mock('@orca/process-host', () => ({ runProcess: run })) +vi.mock('../ipc/command-path/command-path-resolver', () => ({ + resolveCommandOnLocalPath: async () => '/usr/local/bin/opencode' +})) +vi.mock('./opencode-launch-model-context', () => ({ + probeOpenCodeLaunchModelContext: async () => ({ primaryAgent: 'build' }) +})) +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { endpointFilePath: null } +})) + +const launch = (version: string, command: string, envToDelete: string[] = []) => { + run.mockResolvedValue({ code: 0, stdout: version, timedOut: false }) + return prepareOpenCodePtyLaunch({ + command, + env: { OPENCODE_CONFIG_CONTENT: '{"autoupdate":false}' }, + envToDelete, + cwd: `/repo/${version}`, + isFreshLaunch: true, + shell: 'posix' + }).then((result) => ({ ...result, envToDelete })) +} + +beforeEach(() => run.mockReset()) + +it('starts OpenCode 2 on its own server with the picked model in its launch config', async () => { + const result = await launch('2.0.21', "opencode '--model' 'opencode/big-pickle'") + expect(result.command).toBe('opencode --standalone') + expect(JSON.parse(result.env?.OPENCODE_CONFIG_CONTENT ?? '')).toEqual({ + autoupdate: false, + model: 'opencode/big-pickle', + agents: { build: { model: 'opencode/big-pickle' } } + }) +}) + +it('keeps the overlay when the caller asked to drop inherited OpenCode config', async () => { + const result = await launch('2.0.21', "opencode '--model' 'opencode/big-pickle'", [ + 'OPENCODE_CONFIG_CONTENT' + ]) + expect(JSON.parse(result.env?.OPENCODE_CONFIG_CONTENT ?? '')).toMatchObject({ + model: 'opencode/big-pickle' + }) + expect(result.envToDelete).not.toContain('OPENCODE_CONFIG_CONTENT') +}) + +it('rewrites a PowerShell launch whose prompt only the env body can identify', async () => { + run.mockResolvedValue({ code: 0, stdout: '2.0.21', timedOut: false }) + const prompt = 'Use "a;b"\nthen run `pnpm test`' + const tail = ` --prompt ${quoteStartupArg(prompt, 'powershell')}` + const result = await prepareOpenCodePtyLaunch({ + command: `opencode '--model' 'opencode/big-pickle'${tail}`, + env: { [OPENCODE_STARTUP_PROMPT_BODY_ENV]: prompt }, + envToDelete: [], + cwd: '/repo/powershell', + isFreshLaunch: true, + shell: 'powershell' + }) + expect(result.command).toBe(`opencode --standalone${tail}`) +}) diff --git a/src/main/opencode/opencode-root-model-launch.ts b/src/main/opencode/opencode-root-model-launch.ts new file mode 100644 index 00000000000..6be53e09fec --- /dev/null +++ b/src/main/opencode/opencode-root-model-launch.ts @@ -0,0 +1,57 @@ +import type { AgentStartupShell } from '../../shared/agent-launch/startup/tui-agent-startup-shell' +import { resolveCommandOnLocalPath } from '../ipc/command-path/command-path-resolver' +import { resolveOpenCodeLaunchModelConfig } from './opencode-launch-model-config' +import { probeOpenCodeLaunchModelContext } from './opencode-launch-model-context' +import { isVerifiedOpenCodeConfigModelVersion } from './opencode-model-version-policy' +import { planOpenCodeRootModelRewrite } from './opencode-root-model-overlay' + +/** Moves a root `--model` into the launch's config overlay; anything it cannot apply stays as typed. */ +export async function applyOpenCodeRootModelOverlay(options: { + command: string + shell: AgentStartupShell + version: string | null + launchEnv: Record + /** The environment the launch actually inherits, so an existing overlay is extended, not replaced. */ + probeEnv: Record + envToDelete: string[] + cwd?: string + /** The startup prompt Orca quoted onto the command, when it is still there. */ + promptBody?: string +}): Promise { + if (!isVerifiedOpenCodeConfigModelVersion(options.version)) { + return options.command + } + const rewrite = planOpenCodeRootModelRewrite(options.command, options.shell, options.promptBody) + if (!rewrite) { + return options.command + } + const executable = + rewrite.probeExecutable && options.cwd + ? await resolveCommandOnLocalPath(rewrite.probeExecutable, { + env: options.probeEnv, + cwd: options.cwd + }).catch(() => null) + : null + const context = + executable && options.cwd + ? await probeOpenCodeLaunchModelContext({ + executable, + cwd: options.cwd, + env: options.probeEnv + }).catch(() => null) + : null + const configContent = resolveOpenCodeLaunchModelConfig({ + configContent: options.probeEnv.OPENCODE_CONFIG_CONTENT, + primaryAgent: context?.primaryAgent, + model: rewrite.model + }) + if (configContent === null) { + return options.command + } + options.launchEnv.OPENCODE_CONFIG_CONTENT = configContent + const deletion = options.envToDelete.indexOf('OPENCODE_CONFIG_CONTENT') + if (deletion !== -1) { + options.envToDelete.splice(deletion, 1) + } + return rewrite.command +} diff --git a/src/main/opencode/opencode-root-model-overlay.test.ts b/src/main/opencode/opencode-root-model-overlay.test.ts new file mode 100644 index 00000000000..e565a5b2d33 --- /dev/null +++ b/src/main/opencode/opencode-root-model-overlay.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest' +import { + quoteStartupArg, + type AgentStartupShell +} from '../../shared/agent-launch/startup/tui-agent-startup-shell' +import { planOpenCodeRootModelRewrite } from './opencode-root-model-overlay' + +const q = (args: string[], shell: AgentStartupShell) => + args.map((arg) => quoteStartupArg(arg, shell)).join(' ') + +describe('planOpenCodeRootModelRewrite', () => { + it.each(['posix', 'powershell', 'cmd'] as const)( + 'moves a launch-built %s model into the overlay and keeps the prompt as built', + (shell) => { + // Orca's cmd quoting diverges for quotes and ^&|<>()%!, so a cmd prompt with them stays as typed. + const prompt = shell === 'cmd' ? 'fix a;b then test' : 'it\'s broken; fix "a;b"' + const tail = ` --prompt ${quoteStartupArg(prompt, shell)}` + const command = `opencode ${q(['--auto', '--model', 'opencode/big-pickle'], shell)}${tail}` + expect(planOpenCodeRootModelRewrite(command, shell, prompt)).toEqual({ + command: `opencode --standalone ${q(['--auto'], shell)}${tail}`, + model: 'opencode/big-pickle', + probeExecutable: 'opencode' + }) + } + ) + + it('keeps a PowerShell multiline prompt ending in backticks byte for byte', () => { + const prompt = 'Use "a;b"\nthen run `pnpm test`' + const tail = ` --prompt ${quoteStartupArg(prompt, 'powershell')}` + expect( + planOpenCodeRootModelRewrite( + `& opencode ${q(['--model', 'a/b'], 'powershell')}${tail}`, + 'powershell', + prompt + )?.command + ).toBe(`& opencode --standalone${tail}`) + }) + + it('uses the last of repeated models and an existing --standalone', () => { + expect( + planOpenCodeRootModelRewrite( + `opencode2 --standalone ${q(['--model', 'a/b', '--model=c/d'], 'posix')}`, + 'posix' + ) + ).toMatchObject({ command: 'opencode2 --standalone', model: 'c/d' }) + }) + + it.each([ + ['posix', `opencode ${q(['run', '--model', 'a/b'], 'posix')}`], + ['posix', `opencode ${q(['./pkg', '--model', 'a/b'], 'posix')}`], + ['posix', `opencode ${q(['--server', 'http://127.0.0.1:4096', '--model', 'a/b'], 'posix')}`], + ['posix', `opencode ${q(['-s', 'ses_1', '--model', '$MODEL'], 'posix')}`], + // Hand-typed shapes Orca never emits keep today's behavior. + ['posix', 'opencode --model a/b'], + ['posix', `opencode ${q(['--model', 'a/b'], 'posix')}\n--model c/d`], + ['posix', `opencode ${q(['--model', 'a/b'], 'posix')}; --model c/d`], + ['posix', `opencode ${q(['--model', 'a/b'], 'posix')} --prompt # --model c/d`], + ['posix', `$OC ${q(['--model', 'a/b'], 'posix')}`], + ['cmd', `opencode ${q(['--model', 'a/b'], 'cmd')} --prompt "C:\\"`], + [ + 'cmd', + `opencode ${q(['--model', 'a/b'], 'cmd')} --prompt ${quoteStartupArg('fix "a"', 'cmd')}` + ], + ['cmd', `opencode ${q(['--model', 'a/b'], 'cmd')} --prompt ${quoteStartupArg('x\ny', 'cmd')}`], + ['posix', 'claude --model opus'] + ] as const)('leaves %s `%s` as typed', (shell, command) => { + expect(planOpenCodeRootModelRewrite(command, shell, 'C:\\')).toBeNull() + }) + + it('probes the primary agent only for a new session on it', () => { + expect( + planOpenCodeRootModelRewrite( + `opencode ${q(['-s', 'ses_1', '--model', 'a/b'], 'posix')}`, + 'posix' + )?.probeExecutable + ).toBeUndefined() + }) +}) diff --git a/src/main/opencode/opencode-root-model-overlay.ts b/src/main/opencode/opencode-root-model-overlay.ts new file mode 100644 index 00000000000..4a945c9b466 --- /dev/null +++ b/src/main/opencode/opencode-root-model-overlay.ts @@ -0,0 +1,122 @@ +import { getCommandTokenPathBasename } from '../../shared/command-token-scanner' +import { + quoteStartupArg, + tokenizeStartupCommand, + type AgentStartupShell +} from '../../shared/agent-launch/startup/tui-agent-startup-shell' + +const OPENCODE_EXECUTABLE = /^opencode2?(\.(exe|cmd))?$/i +const MODEL_FLAGS = ['--model', '-m'] +const VALUE_FLAGS = ['--prompt', '--session', '-s'] +// Flags the launch builders append unquoted; every other argument Orca emits is quoteStartupArg'd. +const BARE_FLAGS = new Set(['--prompt', '--standalone']) +const LITERAL_HEAD = /^[A-Za-z0-9._/\\:-]+$/ +// Root options that leave a new session on the primary agent; resuming one makes the overlay moot. +const PROBE_NEUTRAL_FLAGS = new Set(['--auto', '--standalone']) +const LITERAL_MODEL = /^[A-Za-z0-9._/:@#+-]+$/ + +export type OpenCodeRootModelRewrite = { + /** The command without its root model option, with `--standalone` so a private server reads the overlay. */ + command: string + model: string + /** The OpenCode executable token, set only when the remaining root options cannot change the primary agent. */ + probeExecutable?: string +} + +/** + * OpenCode 2's root TUI has no `--model`; its per-launch model is config read by a server this launch starts. + * Only Orca's own emitted shape is rewritten: every argument quoted by quoteStartupArg or a known bare flag, + * so no shell syntax can hide another command. Anything else stays exactly as typed. + */ +export function planOpenCodeRootModelRewrite( + command: string, + shell: AgentStartupShell, + promptBody?: string +): OpenCodeRootModelRewrite | null { + if (shell === 'cmd') { + // cmd ends the line at a newline even inside quotes, and its quoting can split argv where it looks whole. + const whole = tokenizeStartupCommand(command, shell) + if (/[\r\n]/.test(command) || !whole.ok || whole.spans.some((span) => span.divergesFromShell)) { + return null + } + } + // The prompt operand is matched against the body Orca put in the env, never decoded. + const promptSuffix = + promptBody === undefined ? undefined : ` --prompt ${quoteStartupArg(promptBody, shell)}` + const suffix = promptSuffix && command.endsWith(promptSuffix) ? promptSuffix : '' + const prefix = command.slice(0, command.length - suffix.length) + const parsed = tokenizeStartupCommand(prefix, shell) + if (!parsed.ok || parsed.spans[0]?.start !== 0 || parsed.spans.at(-1)?.end !== prefix.length) { + return null + } + const { tokens, spans } = parsed + const raw = (index: number) => prefix.slice(spans[index].start, spans[index].end) + const canonical = (index: number) => + !spans[index].divergesFromShell && raw(index) === quoteStartupArg(tokens[index], shell) + const executable = shell === 'powershell' && raw(0) === '&' ? 1 : 0 + const head = tokens[executable] ?? '' + if ( + spans.some( + (span, index) => index > 0 && prefix.slice(spans[index - 1].end, span.start) !== ' ' + ) || + !OPENCODE_EXECUTABLE.test(getCommandTokenPathBasename(head)) || + !(canonical(executable) || (raw(executable) === head && LITERAL_HEAD.test(head))) || + tokens.some( + (token, index) => + index > executable && !canonical(index) && !(raw(index) === token && BARE_FLAGS.has(token)) + ) + ) { + return null + } + const removals: { start: number; end: number }[] = [] + let model: string | undefined + let probeNeutral = true + let standaloneOption = false + for (let index = executable + 1; index < tokens.length; index += 1) { + const token = tokens[index] + // A positional (subcommand or directory) ends the root options; its own flags are not ours. + if (token === '--' || !token.startsWith('-')) { + return null + } + // Another server never reads this launch's config, so its model flag stays as typed. + if (token === '--server' || token.startsWith('--server=')) { + return null + } + const flag = MODEL_FLAGS.find((name) => token === name || token.startsWith(`${name}=`)) + if (flag) { + const inline = token !== flag + const valueIndex = inline ? index : index + 1 + const value = inline ? token.slice(flag.length + 1) : tokens[valueIndex] + if (value === undefined || value.startsWith('-') || !LITERAL_MODEL.test(value)) { + return null + } + model = value + removals.push({ start: spans[index - 1].end, end: spans[valueIndex].end }) + index = valueIndex + continue + } + standaloneOption ||= token === '--standalone' + if (VALUE_FLAGS.includes(token)) { + probeNeutral &&= token === '--prompt' + index += 1 + continue + } + probeNeutral &&= PROBE_NEUTRAL_FLAGS.has(token) || token.startsWith('--prompt=') + } + if (!model) { + return null + } + let stripped = prefix + for (const removal of removals.toReversed()) { + stripped = `${stripped.slice(0, removal.start)}${stripped.slice(removal.end)}` + } + const headEnd = spans[executable].end + const standalone = standaloneOption + ? stripped + : `${stripped.slice(0, headEnd)} --standalone${stripped.slice(headEnd)}` + return { + command: `${standalone}${suffix}`, + model, + ...(probeNeutral ? { probeExecutable: head } : {}) + } +} diff --git a/src/main/opencode/opencode-startup-prompt-owner.test.ts b/src/main/opencode/opencode-startup-prompt-owner.test.ts index 89d2035abc8..110175fb087 100644 --- a/src/main/opencode/opencode-startup-prompt-owner.test.ts +++ b/src/main/opencode/opencode-startup-prompt-owner.test.ts @@ -13,7 +13,7 @@ const ownership = vi.hoisted(() => ({ ptyOwnership: new Map(), ptyIncarnationById: new Map() })) -vi.mock('../agent-hooks/server', () => ({ +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { setStartupPromptClaimListener: (claim: typeof control.claim, clear: () => void) => { control.claim = claim diff --git a/src/main/opencode/opencode-startup-prompt-owner.ts b/src/main/opencode/opencode-startup-prompt-owner.ts index e7b3ed5ab40..7e44fc54981 100644 --- a/src/main/opencode/opencode-startup-prompt-owner.ts +++ b/src/main/opencode/opencode-startup-prompt-owner.ts @@ -1,5 +1,5 @@ import type { PtySpawnOutcome } from '../ipc/pty/spawn-outcome' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { IPtyProvider, PtySpawnResult } from '../providers/pty-provider-contract' import { ptyIncarnationById, ptyOwnership } from '../ipc/pty/provider/ownership-state' diff --git a/src/main/opencode/opencode-status-plugin-startup-refresh.ts b/src/main/opencode/opencode-status-plugin-startup-refresh.ts index 99978ecf045..7aad30f65a6 100644 --- a/src/main/opencode/opencode-status-plugin-startup-refresh.ts +++ b/src/main/opencode/opencode-status-plugin-startup-refresh.ts @@ -1,5 +1,5 @@ import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import type { ManagedHookDetectionSettings } from '../agent-hooks/managed-hook-detection-commands' +import type { ManagedHookDetectionSettings } from '../agent-hooks/installation/managed-hook-detection-commands' import { openCode2HookService, openCodeHookService } from './hook-service' // Refresh running OpenCode 2 services on upgrade without waiting for a pane to rewrite the plugin. diff --git a/src/main/opencode/opencode-wsl-probe-environment.test.ts b/src/main/opencode/opencode-wsl-probe-environment.test.ts index 77432f130c0..98ee5004b55 100644 --- a/src/main/opencode/opencode-wsl-probe-environment.test.ts +++ b/src/main/opencode/opencode-wsl-probe-environment.test.ts @@ -7,7 +7,9 @@ vi.mock('@orca/process-host', () => ({ runProcess: run })) vi.mock('../wsl/execution/wsl-executable-path', () => ({ resolveWslExecutablePath: () => 'wsl.exe' })) -vi.mock('../agent-hooks/server', () => ({ agentHookServer: { endpointFilePath: null } })) +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { endpointFilePath: null } +})) beforeEach(() => { run.mockReset().mockResolvedValue({ code: 0, stdout: '2.0.16', timedOut: false }) diff --git a/src/main/orca-profiles/new-profile-state.test.ts b/src/main/orca-profiles/new-profile-state.test.ts index 35f854dc8e5..593ea8290ae 100644 --- a/src/main/orca-profiles/new-profile-state.test.ts +++ b/src/main/orca-profiles/new-profile-state.test.ts @@ -68,7 +68,7 @@ describe('new desktop profile initialization', () => { activeTabId: null }) expect(published.settings.telemetry).toEqual( - inherited ?? + (inherited && { ...inherited, protectedMilestones: { installCohort: 'existing' } }) ?? expect.objectContaining({ existedBeforeTelemetryRelease: false, optedIn: true, @@ -128,6 +128,30 @@ describe('new desktop profile initialization', () => { expect(readPublishedState()).toEqual(original) }) + it('starts an inherited install with its own existing-profile milestone state', () => { + initializeNewOrcaProfileState( + profileId, + { + optedIn: true, + installId: 'retained-install-id', + existedBeforeTelemetryRelease: false, + protectedMilestones: { + installCohort: 'fresh', + firstAgentInteractionDay: 20_766, + meaningfulActivityDay: 20_766 + } + }, + root + ) + + expect(readPublishedState().settings.telemetry).toEqual({ + optedIn: true, + installId: 'retained-install-id', + existedBeforeTelemetryRelease: false, + protectedMilestones: { installCohort: 'existing' } + }) + }) + it('preserves existing JSON as input for its later import', () => { const path = getOrcaProfileDataFile(profileId, root) const original = '{"settings":{"telemetry":{"installId":"older"}}}' diff --git a/src/main/orca-profiles/new-profile-state.ts b/src/main/orca-profiles/new-profile-state.ts index a55a5194a26..d4d27a6de73 100644 --- a/src/main/orca-profiles/new-profile-state.ts +++ b/src/main/orca-profiles/new-profile-state.ts @@ -30,9 +30,19 @@ export function initializeNewOrcaProfileState( } const defaults = getDefaultPersistedState(homedir()) const cohorts = new LoadedCohortMigrationOperations({ loadNeedsSave: false }) + // Inherited consent belongs to an install that already existed, so its milestone cohort is not fresh. const initial = cohorts.migrateCohortSeeds( telemetry - ? { ...defaults, settings: { ...defaults.settings, telemetry } } + ? cohorts.migrateTelemetry( + { + ...defaults, + settings: { + ...defaults.settings, + telemetry: { ...telemetry, protectedMilestones: { installCohort: 'existing' } } + } + }, + true + ) : cohorts.migrateTelemetry(defaults, false), false ) diff --git a/src/main/orca-profiles/profile-project-domain-state.ts b/src/main/orca-profiles/profile-project-domain-state.ts index 1ac7ebc9893..d691ee0e1f6 100644 --- a/src/main/orca-profiles/profile-project-domain-state.ts +++ b/src/main/orca-profiles/profile-project-domain-state.ts @@ -1,3 +1,4 @@ +import { ProfileStateLegacyDocumentRefresh } from '../persistence/profile-state/profile-state-legacy-document-refresh' import { openProfileStateDatabase, openProfileStateDatabaseReadOnly @@ -78,6 +79,8 @@ export function writeProfileProjectDomainChanges( if (!result.changed || result.revision !== changes.expectedRevision + 1) { throw new Error('Profile domain transfer did not commit its expected revision') } + // This profile may not be running; keep the copy older builds read current too. + new ProfileStateLegacyDocumentRefresh().refresh(opened.db) } finally { opened.db.close() } diff --git a/src/main/orcad/electron-serve-provider-selection.test.ts b/src/main/orcad/electron-serve-provider-selection.test.ts index b5333f85c9c..f201d43aebf 100644 --- a/src/main/orcad/electron-serve-provider-selection.test.ts +++ b/src/main/orcad/electron-serve-provider-selection.test.ts @@ -20,7 +20,7 @@ vi.mock('@orca/process-host', async (importOriginal) => ({ vi.mock('./orcad-browser-install-park', () => ({ openOrcadBrowserInstallPark: () => null })) import { resolveOrcadBrowserProvider, type OrcadBrowserProvider } from './orcad-browser-provider' -import { agentBrowserCommandOf } from '../browser/agent-browser/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' const FAKE_SIDECAR = join(import.meta.dirname, '__fixtures__', 'fake-orcad-electron-sidecar.cjs') const INSTALLED_EXECUTABLE = join('/Applications', 'Orca.app', 'Contents', 'MacOS', 'Orca') diff --git a/src/main/orcad/external-chromium-browser-process.ts b/src/main/orcad/external-chromium-browser-process.ts index fb3c8c00f35..e170c0e50b4 100644 --- a/src/main/orcad/external-chromium-browser-process.ts +++ b/src/main/orcad/external-chromium-browser-process.ts @@ -20,7 +20,7 @@ import { } from './external-chromium-tab-projection' import { ExternalChromiumTabRegistry } from './external-chromium-tab-registry' import { runExternalChromiumPageInput, type PageInputSession } from './external-chromium-page-input' -import { agentBrowserSnapshotArgs } from '../browser/agent-browser/agent-browser-snapshot-arguments' +import { agentBrowserSnapshotArgs } from '../browser/agent-browser/protocol/agent-browser-snapshot-arguments' import { Snapshot } from '../../shared/rpc-contract/browser-observation-params' import { ExpectedPageUrlGuard } from '../browser/cdp/input/browser-expected-page-url' diff --git a/src/main/orcad/external-chromium-browser-session.test.ts b/src/main/orcad/external-chromium-browser-session.test.ts index 041254291ea..4d0127bc655 100644 --- a/src/main/orcad/external-chromium-browser-session.test.ts +++ b/src/main/orcad/external-chromium-browser-session.test.ts @@ -16,7 +16,7 @@ vi.mock('node:fs/promises', () => ({ })) import { ExternalChromiumBrowserSession } from './external-chromium-browser-session' -import { agentBrowserCommandOf } from '../browser/agent-browser/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' const BASE = { executablePath: '/opt/orca/chromium', diff --git a/src/main/orcad/external-chromium-browser-session.ts b/src/main/orcad/external-chromium-browser-session.ts index 6b3f07bd76a..364a6edad00 100644 --- a/src/main/orcad/external-chromium-browser-session.ts +++ b/src/main/orcad/external-chromium-browser-session.ts @@ -8,13 +8,13 @@ import { agentBrowserBatchInput, isAgentBrowserStaleRefError, parseAgentBrowserJsonOutput -} from '../browser/agent-browser/agent-browser-batch-command' +} from '../browser/agent-browser/protocol/agent-browser-batch-command' import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' import { Screenshot } from '../../shared/rpc-contract/browser-observation-params' import { agentBrowserScreenshotArgs, readAgentBrowserScreenshot -} from '../browser/agent-browser/agent-browser-screenshot-arguments' +} from '../browser/agent-browser/observation/agent-browser-screenshot-arguments' import { runProcess } from '@orca/process-host' import { resolveExternalChromiumProfilePath } from './external-chromium-profile-path' diff --git a/src/main/orcad/external-chromium-command-arguments.ts b/src/main/orcad/external-chromium-command-arguments.ts index 080c6a0bf48..e3ff45e5a45 100644 --- a/src/main/orcad/external-chromium-command-arguments.ts +++ b/src/main/orcad/external-chromium-command-arguments.ts @@ -1,6 +1,6 @@ import { BrowserError } from '../browser/browser-error' -import { agentBrowserSetMediaArguments } from '../browser/agent-browser/agent-browser-set-media-arguments' -import { agentBrowserWaitArguments } from '../browser/agent-browser/agent-browser-wait-arguments' +import { agentBrowserSetMediaArguments } from '../browser/agent-browser/protocol/agent-browser-set-media-arguments' +import { agentBrowserWaitArguments } from '../browser/agent-browser/protocol/agent-browser-wait-arguments' const TARGET_OVERRIDE_FLAGS: Record = { '--args': true, '--cdp': true, diff --git a/src/main/orcad/orcad-agent-browser-binary.ts b/src/main/orcad/orcad-agent-browser-binary.ts index 69e103aba10..c8e8e7261fe 100644 --- a/src/main/orcad/orcad-agent-browser-binary.ts +++ b/src/main/orcad/orcad-agent-browser-binary.ts @@ -2,7 +2,7 @@ import { accessSync, constants, existsSync } from 'node:fs' import { arch, platform } from 'node:os' import { dirname, join } from 'node:path' import { orcadAgentBrowserNativeName } from '../../shared/orcad-agent-browser-name' -import { ensureDependencyBinaryExecutable } from '../browser/agent-browser/agent-browser-dependency-binary' +import { ensureDependencyBinaryExecutable } from '../browser/agent-browser/helper-process/agent-browser-dependency-binary' /** A slot carries only its own target's driver, so trying both libc names needs no libc probe. */ function hostDriverNames(): string[] { diff --git a/src/main/orcad/orcad-browser-provider.test.ts b/src/main/orcad/orcad-browser-provider.test.ts index 2468e432f98..a24452e201c 100644 --- a/src/main/orcad/orcad-browser-provider.test.ts +++ b/src/main/orcad/orcad-browser-provider.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import { agentBrowserCommandOf } from '../browser/agent-browser/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' import { resolveInstalledElectronExecutable, resolveOrcadBrowserProvider diff --git a/src/main/orcad/orcad-daemon-teardown-fixture.ts b/src/main/orcad/orcad-daemon-teardown-fixture.ts index 5b19ca45a05..bbd400bf7dc 100644 --- a/src/main/orcad/orcad-daemon-teardown-fixture.ts +++ b/src/main/orcad/orcad-daemon-teardown-fixture.ts @@ -9,7 +9,7 @@ import { type ProcessTableIndexOf } from '../../shared/process-table-index' import { removeTree } from '../../shared/windows-transient-lock-removal' -import { parseLinuxStartTicks } from '../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { DaemonEndpointOwnershipError } from '../daemon/launch/daemon-endpoint-adoption' import { parseLinuxProcessState } from '../daemon/endpoint/identity/daemon-incarnation-evidence' import { readDaemonPidRecord } from '../daemon/endpoint/identity/daemon-endpoint-incarnation' diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 9a04cfa9093..b305803b629 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -90,11 +90,11 @@ async function startOrcadRuntime( const { resolveDaemonSessionScrollbackRows } = await import('../daemon/sessions/daemon-session-scrollback-window') const { collectOrcadHealth } = await import('./orcad-health') - const { agentHookServer } = await import('../agent-hooks/server') - await import('../agent-hooks/managed-agent-hook-controls') - const { agentHookRuntimeDeps } = await import('../agent-hooks/agent-hook-runtime-deps') + const { agentHookServer } = await import('../agent-hooks/server/agent-hook-server') + await import('../agent-hooks/installation/managed-agent-hook-controls') + const { agentHookRuntimeDeps } = await import('../agent-hooks/runtime/agent-hook-runtime-deps') const { installHookStatusSessionTabsRepublish } = - await import('../agent-hooks/hook-status-session-tabs-republish') + await import('../agent-hooks/runtime/hook-status-session-tabs-republish') const { startOrcadAgentHookServer, startOrcadManagedAgentHooks } = await import('./orcad-managed-agent-hooks') const { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } = diff --git a/src/main/orcad/orcad-host-identity-reset.ts b/src/main/orcad/orcad-host-identity-reset.ts new file mode 100644 index 00000000000..0afe2c36631 --- /dev/null +++ b/src/main/orcad/orcad-host-identity-reset.ts @@ -0,0 +1,51 @@ +// CLI entry for `orca serve reset-identity`; plain Node, loaded from the packaged CLI. +import { existsSync } from 'node:fs' +import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { OrcadInstanceLockError } from './orcad-data-root-privacy' +import { + HostIdentityRotationNotStartedError, + rotateHostIdentity +} from '../runtime/host-instance-identity' + +export type HostIdentityResetResult = + | { status: 'reset' } + | { status: 'missing' } + | { status: 'running'; message: string } + /** Nothing changed on disk. */ + | { status: 'failed'; message: string } + /** The next Orca start finishes the rotation before it serves pairing. */ + | { status: 'incomplete'; message: string } + +const RUNNING_LOCK_CODES: ReadonlySet = new Set([ + 'orcad_instance_lock_held', + 'orcad_instance_lock_holder_unverifiable' +]) + +/** Holds the profile lock so no running Orca reads or rewrites the files mid-rotation. */ +export function resetHostIdentityUnderLock(userDataPath: string): HostIdentityResetResult { + if (!existsSync(userDataPath)) { + return { status: 'missing' } + } + let lock: ReturnType + try { + // The path may be a desktop profile, whose permissions a reset must not change. + lock = acquireOrcadInstanceLock(userDataPath, { enforcePrivateDataRoot: false }) + } catch (error) { + // Other lock errors (an unusable or shared data root) carry their own guidance. + if (error instanceof OrcadInstanceLockError && RUNNING_LOCK_CODES.has(error.code)) { + return { status: 'running', message: error.message } + } + throw error + } + try { + rotateHostIdentity(userDataPath) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + return error instanceof HostIdentityRotationNotStartedError + ? { status: 'failed', message } + : { status: 'incomplete', message } + } finally { + lock.release() + } + return { status: 'reset' } +} diff --git a/src/main/orcad/orcad-instance-lock.ts b/src/main/orcad/orcad-instance-lock.ts index bcc0eaf7168..0012cc218df 100644 --- a/src/main/orcad/orcad-instance-lock.ts +++ b/src/main/orcad/orcad-instance-lock.ts @@ -72,6 +72,8 @@ export type OrcadInstanceLockHooks = OrcadDataRootPrivacyHooks & { holderIdentity?: (record: OrcadLockRecord) => OrcadProcessIdentityVerdict /** Desktop callers must first hold Electron’s single-instance lock to reclaim desktop records. */ role?: 'orcad' | 'desktop' + /** Tighten and verify data-root permissions; defaults to on for the orcad role only. */ + enforcePrivateDataRoot?: boolean machineIdentity?: () => string | null /** Establishes locality for legacy machine-less records. */ dataRootIsOnLocalDisk?: (dataRoot: string) => boolean @@ -118,7 +120,7 @@ export function acquireOrcadInstanceLock( ) } // Desktop profiles retain existing permissions; orcad tightens its own roots. - if ((hooks.role ?? 'orcad') === 'orcad') { + if (hooks.enforcePrivateDataRoot ?? (hooks.role ?? 'orcad') === 'orcad') { assertOrcadDataRootIsPrivate(dataRoot, hooks) } diff --git a/src/main/orcad/orcad-managed-agent-hooks.ts b/src/main/orcad/orcad-managed-agent-hooks.ts index eb88b9f2097..86ddef5b14f 100644 --- a/src/main/orcad/orcad-managed-agent-hooks.ts +++ b/src/main/orcad/orcad-managed-agent-hooks.ts @@ -1,18 +1,18 @@ import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service' import { getAppEnvironment } from '../../shared/app-environment' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { adoptLoginShellAgentHomes } from '../agent-hooks/agent-home-login-shell' -import { hydrateAgentCliShellPath } from '../agent-hooks/local-agent-cli-presence' +import { adoptLoginShellAgentHomes } from '../agent-hooks/installation/agent-home-login-shell' +import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/managed-agent-hook-startup' +import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/opencode-status-plugin-startup-refresh' import type { ProfilePreferences } from '../persistence/loading-store/profile-preferences' import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { AgentHookServer } from '../agent-hooks/server' -import { installLocalHookRootEvidence } from '../agent-hooks/local-hook-root-evidence' +import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' +import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' /** SSH and WSL-host panes run beside this host, so it proves which agent owns each pane, from the * first record its startup replay reads. */ diff --git a/src/main/orcad/orcad-process-start-time.ts b/src/main/orcad/orcad-process-start-time.ts index ac0c91d957e..555ace95778 100644 --- a/src/main/orcad/orcad-process-start-time.ts +++ b/src/main/orcad/orcad-process-start-time.ts @@ -1,6 +1,6 @@ // Linux ticks/boot ID avoid drifting wall time; Windows uses kernel creation time. Unknown never proves exit. import { readFileSync, statSync } from 'node:fs' -import { parseLinuxStartTicks } from '../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { getProcessStartedAtMs, START_TIME_TOLERANCE_MS, diff --git a/src/main/orcad/orcad-sidecar-runtime-client.ts b/src/main/orcad/orcad-sidecar-runtime-client.ts index dbb25ff0d6d..9e8b832f590 100644 --- a/src/main/orcad/orcad-sidecar-runtime-client.ts +++ b/src/main/orcad/orcad-sidecar-runtime-client.ts @@ -4,6 +4,7 @@ import { z } from 'zod' import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap' import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' import { BrowserError } from '../browser/browser-error' +import { daemonSocketDirIsTrusted } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' const SIDECAR_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 const RuntimeResponse = z.discriminatedUnion('ok', [ @@ -30,6 +31,13 @@ export async function sendOrcadSidecarRequest( 'Electron browser sidecar has no local RPC transport.' ) } + // A relocated socket lives in shared /tmp; never send the auth token to a planted listener. + if (transport.kind === 'unix' && !daemonSocketDirIsTrusted(transport.endpoint)) { + throw new BrowserError( + BROWSER_UNAVAILABLE_ERROR_CODE, + 'Electron browser sidecar socket directory is not private to this user.' + ) + } return await new Promise((resolve, reject) => { const socket = createConnection(transport.endpoint) const requestId = randomUUID() diff --git a/src/main/orcad/orcad-stale-lock-reclaim.test.ts b/src/main/orcad/orcad-stale-lock-reclaim.test.ts index 462a1ac35d3..060740df8e5 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.test.ts +++ b/src/main/orcad/orcad-stale-lock-reclaim.test.ts @@ -1,9 +1,18 @@ -import { chmodSync, existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + utimesSync, + writeFileSync +} from 'node:fs' import { createServer, type Server } from 'node:net' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' import type { OrcadLockRecord } from './orcad-instance-lock' +import { shortDaemonSocketDir } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' import { probeOrcadEndpoint, reclaimStaleOrcadInstanceLock, @@ -167,6 +176,31 @@ describe.skipIf(process.platform === 'win32')('reclaimStaleOrcadInstanceLock (#3 ) }) + it('refuses while the holder answers at a socket relocated for a long data root', async () => { + const root = makeRoot() + writeLock(root, holderRecord()) + const relocatedDir = shortDaemonSocketDir(root, process.getuid!()) + mkdirSync(relocatedDir, { recursive: true, mode: 0o700 }) + roots.push(relocatedDir) + const server = createServer() + servers.push(server) + await new Promise((resolve) => + server.listen(join(relocatedDir, `o-${HOLDER_PID}-rt.sock`), resolve) + ) + const result = await reclaimStaleOrcadInstanceLock( + root, + { yes: true, hintRuntime: null }, + rebootedBox() + ) + expect(result).toMatchObject({ + status: 'refused', + message: expect.stringContaining('Something on this machine answers') + }) + expect(readOrcadInstanceLockRecord(join(root, ORCAD_LOCK_FILE_NAME))?.nonce).toBe( + 'stale-holder' + ) + }) + // Root reads through mode 000, so the case only exists for an ordinary user. it.skipIf(process.getuid?.() === 0)( 'refuses, rather than reporting nothing to do, when the lock cannot be reached', diff --git a/src/main/orcad/orcad-stale-lock-reclaim.ts b/src/main/orcad/orcad-stale-lock-reclaim.ts index c010175a0ae..7baf1ce9fd8 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.ts +++ b/src/main/orcad/orcad-stale-lock-reclaim.ts @@ -1,5 +1,6 @@ // Shared-home locks need explicit operator confirmation: local silence cannot prove a remote holder exited. import { readdirSync, statSync } from 'node:fs' +import { readdir } from 'node:fs/promises' import { createConnection } from 'node:net' import { hostname } from 'node:os' import { join } from 'node:path' @@ -20,7 +21,10 @@ import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspect import { resolveUserDataPath } from './orcad-app-paths' import { profileStateAccessMachineIdentity } from '../persistence/profile-state/profile-state-access-identity' import { readRuntimeMetadata } from '../runtime/rpc/server/runtime-metadata' -import { RUNTIME_SOCKET_NAME_REGEX } from '../runtime/rpc/server/runtime-rpc-socket-metadata' +import { + RUNTIME_SOCKET_NAME_REGEX, + runtimeSocketDirs +} from '../runtime/rpc/server/runtime-rpc-socket-metadata' import { ORCAD_RECLAIM_STALE_LOCK_FLAG, ORCAD_STALE_LOCK_DATA_ROOT_FLAG, @@ -176,7 +180,7 @@ async function checkStaleLock( if (!(now - writtenMs >= ORCAD_STALE_LOCK_MIN_AGE_MS)) { return { refusal: `The lock is less than ${ORCAD_STALE_LOCK_MIN_AGE_MS / 60_000} minutes old.` } } - const endpoints = holderEndpoints(dataRoot, holder.pid) + const endpoints = await holderEndpoints(dataRoot, holder.pid) if (!endpoints) { return { refusal: 'The runtime record in the data root cannot be read.' } } @@ -205,7 +209,7 @@ async function checkStaleLock( } /** Null leaves endpoints unverifiable when runtime metadata is unreadable. */ -function holderEndpoints(dataRoot: string, pid: number): string[] | null { +async function holderEndpoints(dataRoot: string, pid: number): Promise { const endpoints = new Set() try { const metadata = readRuntimeMetadata(dataRoot) @@ -214,10 +218,12 @@ function holderEndpoints(dataRoot: string, pid: number): string[] | null { endpoints.add(transport.endpoint) } } - for (const entry of readdirSync(dataRoot)) { - if (RUNTIME_SOCKET_NAME_REGEX.exec(entry)?.[1] === String(pid)) { - endpoints.add(join(dataRoot, entry)) - } + for (const dir of runtimeSocketDirs(dataRoot)) { + // A long data root relocates the holder's socket; it only listens in a dir this user can read. + const entries = dir === dataRoot ? readdirSync(dir) : await readdir(dir).catch(() => []) + entries + .filter((entry) => RUNTIME_SOCKET_NAME_REGEX.exec(entry)?.[1] === String(pid)) + .forEach((entry) => endpoints.add(join(dir, entry))) } } catch { return null diff --git a/src/main/persistence/loading-store/github-cache-database.test.ts b/src/main/persistence/loading-store/github-cache-database.test.ts new file mode 100644 index 00000000000..7ce6da03f07 --- /dev/null +++ b/src/main/persistence/loading-store/github-cache-database.test.ts @@ -0,0 +1,57 @@ +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import SyncDatabase from '../../sqlite/sync-database' +import { + getGithubCacheDatabaseFile, + readGitHubCacheDatabase, + writeGitHubCacheDatabase +} from './github-cache-database' + +const directories: string[] = [] + +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +function profileDataFile(): string { + const directory = mkdtempSync(join(tmpdir(), 'orca-github-cache-')) + directories.push(directory) + return join(directory, 'orca-data.json') +} + +const pr = (fetchedAt: number) => ({ data: null, fetchedAt }) +const sidecarPath = (dataFile: string) => join(dataFile, '..', 'orca-github-cache.json') +const save = (dataFile: string, cache: Parameters[1]): void => { + void writeGitHubCacheDatabase(dataFile, cache, { busyTimeoutMs: 0, importedLegacyFileHash: null }) +} + +describe('github cache database', () => { + it('keeps an older build sidecar until its imported rows commit', async () => { + const dataFile = profileDataFile() + save(dataFile, { pr: { 'o/r#1': pr(1) }, issue: {} }) + writeFileSync(sidecarPath(dataFile), JSON.stringify({ pr: { 'o/r#5': pr(5) }, issue: {} })) + const legacy = readGitHubCacheDatabase(dataFile) + expect(legacy.cache).toEqual({ pr: { 'o/r#5': pr(5) }, issue: {} }) + + const locker = new SyncDatabase(getGithubCacheDatabaseFile(dataFile)) + locker.exec('BEGIN IMMEDIATE') + const options = { busyTimeoutMs: 0, importedLegacyFileHash: legacy.sidecarHash } + expect(() => writeGitHubCacheDatabase(dataFile, legacy.cache!, options)).toThrow(/locked/) + expect(existsSync(sidecarPath(dataFile))).toBe(true) + locker.exec('ROLLBACK') + locker.close() + + await writeGitHubCacheDatabase(dataFile, legacy.cache!, options) + expect(existsSync(sidecarPath(dataFile))).toBe(false) + expect(readGitHubCacheDatabase(dataFile)).toEqual({ + cache: { pr: { 'o/r#5': pr(5) }, issue: {} }, + fromSidecar: false, + sidecarHash: null, + unavailable: false + }) + }) +}) diff --git a/src/main/persistence/loading-store/github-cache-database.ts b/src/main/persistence/loading-store/github-cache-database.ts new file mode 100644 index 00000000000..eaddcf85130 --- /dev/null +++ b/src/main/persistence/loading-store/github-cache-database.ts @@ -0,0 +1,127 @@ +import { dirname, join } from 'node:path' +import type { PersistedState } from '../../../shared/persisted-state-types' +import { + KeyedJsonRowCache, + parseKeyedJsonRows, + type KeyedJsonRow +} from '../../sqlite/row-cache/keyed-json-row-cache' +import { getGithubCacheFile } from './user-data-path' + +type GitHubCache = PersistedState['githubCache'] +type GitHubCacheKind = keyof GitHubCache + +/** Main-thread callers never wait out another writer's lock; they retry later instead. */ +export const GITHUB_CACHE_ROUTINE_BUSY_TIMEOUT_MS = 25 +/** Quit and explicit barriers may wait briefly so a transient lock does not drop the save. */ +export const GITHUB_CACHE_BARRIER_BUSY_TIMEOUT_MS = 500 + +// 2: rows moved to the shared keyed row layout; a version-1 cache rebuilds empty once. +const GITHUB_CACHE_SCHEMA_VERSION = 2 +const KINDS: readonly GitHubCacheKind[] = ['pr', 'issue'] + +export function getGithubCacheDatabaseFile(dataFile: string): string { + return join(dirname(dataFile), 'orca-github-cache.db') +} + +/** + * Next-launch copy of the PR/issue caches, one row per entry, so a save rewrites only entries + * whose content changed. Disposable: a corrupt or mismatched database rebuilds empty and the + * next poll refills it. No handle outlives a call (profile moves, Windows). + */ +function githubCacheRows(dataFile: string): KeyedJsonRowCache { + return new KeyedJsonRowCache(getGithubCacheDatabaseFile(dataFile), { + schemaVersion: GITHUB_CACHE_SCHEMA_VERSION, + busyTimeoutMs: GITHUB_CACHE_ROUTINE_BUSY_TIMEOUT_MS, + holdConnection: false, + legacyPath: getGithubCacheFile(dataFile) + }) +} + +export type StoredGitHubCache = { + /** What to hydrate, or null when nothing can be hydrated now. */ + cache: GitHubCache | null + /** `cache` came from an older build's sidecar, so it must be saved as rows. */ + fromSidecar: boolean + /** Receipt of an older build's sidecar to retire once rows that supersede it commit. */ + sidecarHash: string | null + /** The rows or the sidecar could not be read: this session must not save over them. */ + unavailable: boolean +} + +/** + * Startup read. An older build's sidecar is newer than the rows unless the rows record having + * imported exactly its bytes. While either cannot be read, nothing is hydrated and the caller + * saves nothing this session, so neither the rows nor an unread sidecar are lost. + */ +export function readGitHubCacheDatabase(dataFile: string): StoredGitHubCache { + const loaded = githubCacheRows(dataFile).load(parseGitHubCacheSidecar) + if (loaded.kind === 'unavailable') { + return { cache: null, fromSidecar: false, sidecarHash: null, unavailable: true } + } + if (loaded.kind === 'import') { + return { + cache: loaded.value, + fromSidecar: true, + sidecarHash: loaded.receipt, + unavailable: false + } + } + const cache: GitHubCache = { pr: {}, issue: {} } + for (const { key: id, value } of parseKeyedJsonRows(loaded.rows)) { + const separator = id.indexOf('\u0000') + const kind = KINDS.find((candidate) => candidate === id.slice(0, separator)) + if (kind) { + Object.assign(cache[kind], { [id.slice(separator + 1)]: value }) + } + } + const hasRows = Object.keys(cache.pr).length + Object.keys(cache.issue).length > 0 + return { + cache: hasRows ? cache : null, + fromSidecar: false, + sidecarHash: null, + unavailable: false + } +} + +/** + * Save the cache, writing only rows whose content changed. `importedLegacyFileHash` names the + * sidecar whose content `cache` already holds (imported or superseded): the commit records it, + * then removes the sidecar if it is still that file. Throws on a failed commit, busy included. + */ +export function writeGitHubCacheDatabase( + dataFile: string, + cache: GitHubCache, + options: { busyTimeoutMs: number; importedLegacyFileHash: string | null } +): void { + githubCacheRows(dataFile).write(githubCacheRowsOf(cache), { + busyTimeoutMs: options.busyTimeoutMs, + importReceipt: options.importedLegacyFileHash ?? undefined + }) +} + +function githubCacheRowsOf(cache: GitHubCache): KeyedJsonRow[] { + const rows: KeyedJsonRow[] = [] + for (const kind of KINDS) { + for (const [key, entry] of Object.entries(cache[kind] ?? {})) { + const json = JSON.stringify(entry) + if (json !== undefined) { + rows.push({ key: `${kind}\u0000${key}`, json }) + } + } + } + return rows +} + +/** The shape check the sidecar reader always applied; unusable sidecars are rejected. */ +function parseGitHubCacheSidecar(text: string): GitHubCache | null { + const parsed: unknown = JSON.parse(text) + if (!isRecord(parsed) || !isRecord(parsed.pr) || !isRecord(parsed.issue)) { + return null + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: same shape check the sidecar reader always applied; entries stay opaque cache payloads. + return parsed as GitHubCache +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} diff --git a/src/main/persistence/loading-store/github-cache-persistence.ts b/src/main/persistence/loading-store/github-cache-persistence.ts new file mode 100644 index 00000000000..3370bc5ec08 --- /dev/null +++ b/src/main/persistence/loading-store/github-cache-persistence.ts @@ -0,0 +1,117 @@ +import type { StoreRuntimeState } from './store-runtime-state' +import { + GITHUB_CACHE_BARRIER_BUSY_TIMEOUT_MS, + GITHUB_CACHE_ROUTINE_BUSY_TIMEOUT_MS, + writeGitHubCacheDatabase +} from './github-cache-database' +import { classifyRowCacheFailure, nextRetryDelayMs } from '../../sqlite/row-cache/row-cache-failure' + +type GitHubCachePersistenceRuntime = Pick< + StoreRuntimeState, + | 'dataFile' + | 'githubCacheDirty' + | 'githubCacheLegacyFileHash' + | 'githubCachePersistenceDisabled' + | 'githubCachePersistedAt' + | 'githubCachePersistTimer' + | 'githubCacheRetryDelayMs' + | 'profileMaintenancePending' + | 'quitFlushStarted' + | 'state' + | 'writesFrozen' +> + +/** + * The cache only seeds next launch's sidebar before the first poll, so routine saves wait this + * long; quit and explicit flush barriers save at once. A crash loses at most this much churn, + * which the next poll refetches. + */ +const GITHUB_CACHE_PERSIST_INTERVAL_MS = 3 * 60_000 +const GITHUB_CACHE_FIRST_RETRY_MS = 5_000 + +/** + * `routine` saves wait for the interval (or a pending retry) and never run while maintenance, + * finalization or a freeze owns the profile. `barrier` is an admitted maintenance or final flush: + * it saves now. Barriers are best-effort for this disposable cache: a failure (such as another + * writer's lock) is logged and retried later rather than failing quit or a profile switch, and + * the cost is stale sidebar facts until the first poll after restart. + */ +export function persistGithubCache( + runtime: GitHubCachePersistenceRuntime, + mode: 'routine' | 'barrier' +): void { + if (!runtime.githubCacheDirty || runtime.githubCachePersistenceDisabled) { + return + } + if (mode === 'barrier') { + writeGithubCacheNow(runtime, true) + return + } + // An armed timer is the next save: the interval or a busy retry's backoff. + if (isFenced(runtime) || runtime.githubCachePersistTimer !== null) { + return + } + const remaining = runtime.githubCachePersistedAt + GITHUB_CACHE_PERSIST_INTERVAL_MS - Date.now() + if (remaining <= 0) { + writeGithubCacheNow(runtime, false) + } else { + armGithubCacheTimer(runtime, remaining, 'interval') + } +} + +/** Maintenance, freeze or quit owns the profile; resume (if any) rearms through persistGithubCache. */ +export function suspendGithubCachePersistence(runtime: GitHubCachePersistenceRuntime): void { + if (runtime.githubCachePersistTimer !== null) { + clearTimeout(runtime.githubCachePersistTimer) + runtime.githubCachePersistTimer = null + } +} + +/** `retry` saves at its own backoff deadline; `interval` re-applies the routine cadence. */ +function armGithubCacheTimer( + runtime: GitHubCachePersistenceRuntime, + delayMs: number, + kind: 'interval' | 'retry' +): void { + runtime.githubCachePersistTimer = setTimeout(() => { + runtime.githubCachePersistTimer = null + if (kind === 'interval') { + persistGithubCache(runtime, 'routine') + } else if (runtime.githubCacheDirty && !isFenced(runtime)) { + writeGithubCacheNow(runtime, false) + } + }, delayMs) + runtime.githubCachePersistTimer.unref?.() +} + +function isFenced(runtime: GitHubCachePersistenceRuntime): boolean { + return runtime.writesFrozen || runtime.profileMaintenancePending || runtime.quitFlushStarted +} + +function writeGithubCacheNow(runtime: GitHubCachePersistenceRuntime, barrier: boolean): void { + suspendGithubCachePersistence(runtime) + try { + // Synchronous: no later mutation can interleave, so the cache is clean once this returns. + writeGitHubCacheDatabase(runtime.dataFile, runtime.state.githubCache, { + busyTimeoutMs: barrier + ? GITHUB_CACHE_BARRIER_BUSY_TIMEOUT_MS + : GITHUB_CACHE_ROUTINE_BUSY_TIMEOUT_MS, + importedLegacyFileHash: runtime.githubCacheLegacyFileHash + }) + runtime.githubCacheDirty = false + runtime.githubCacheLegacyFileHash = null + runtime.githubCachePersistedAt = Date.now() + runtime.githubCacheRetryDelayMs = 0 + } catch (error) { + // Another connection holds the lock (or the disk refused): back off rather than block. + const delay = nextRetryDelayMs(runtime.githubCacheRetryDelayMs, { + minMs: GITHUB_CACHE_FIRST_RETRY_MS, + maxMs: GITHUB_CACHE_PERSIST_INTERVAL_MS + }) + runtime.githubCacheRetryDelayMs = delay + armGithubCacheTimer(runtime, delay, 'retry') + if (classifyRowCacheFailure(error) !== 'busy') { + console.warn('[persistence] Failed to write github cache snapshot:', error) + } + } +} diff --git a/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts b/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts index 1e988411bb8..5fec85a3c54 100644 --- a/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts +++ b/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { getDefaultPersistedState } from '../../../shared/constants' import type { PersistedState } from '../../../shared/persisted-state-types' +import type { TelemetrySettings } from '../../../shared/telemetry-settings-types' import { LoadedCohortMigrationOperations } from './loaded-cohort-migrations' const seed = (state: PersistedState, fileExistedOnLoad: boolean) => @@ -10,16 +11,11 @@ const seed = (state: PersistedState, fileExistedOnLoad: boolean) => ).settings describe('Claude Code theme sync cohort', () => { - it('turns the sync on for a new profile', () => { - expect(seed(getDefaultPersistedState('/home/user'), false)).toMatchObject({ - claudeCodeThemeSync: true, - claudeCodeThemeSyncOffer: 'settled' - }) - }) - - it('keeps an existing profile off and owes it the offer, even when a writer copied the default in', () => { - const existing = getDefaultPersistedState('/home/user') - expect(seed(existing, true)).toMatchObject({ + it.each([ + ['new', false], + ['existing', true] + ])('keeps a %s profile off and owes it the offer', (_cohort, fileExistedOnLoad) => { + expect(seed(getDefaultPersistedState('/home/user'), fileExistedOnLoad)).toMatchObject({ claudeCodeThemeSync: false, claudeCodeThemeSyncOffer: 'pending' }) @@ -41,3 +37,48 @@ describe('Claude Code theme sync cohort', () => { }) }) }) + +describe('protected milestone install cohort', () => { + const migrate = (state: PersistedState, fileExistedOnLoad: boolean) => + new LoadedCohortMigrationOperations({ loadNeedsSave: false }).migrateTelemetry( + state, + fileExistedOnLoad + ).settings.telemetry?.protectedMilestones + + const withTelemetry = ( + protectedMilestones?: TelemetrySettings['protectedMilestones'] + ): PersistedState => { + const state = getDefaultPersistedState('/home/user') + return { + ...state, + settings: { + ...state.settings, + telemetry: { + optedIn: true, + installId: 'install-1', + existedBeforeTelemetryRelease: false, + ...(protectedMilestones ? { protectedMilestones } : {}) + } + } + } + } + + it('marks a profile created on this load fresh', () => { + expect(migrate(getDefaultPersistedState('/home/user'), false)).toEqual({ + installCohort: 'fresh' + }) + }) + + it('marks an upgraded profile existing without touching its cursors', () => { + expect(migrate(withTelemetry({ meaningfulActivityDay: 20_000 }), true)).toEqual({ + installCohort: 'existing', + meaningfulActivityDay: 20_000 + }) + }) + + it('never re-freezes a cohort already recorded', () => { + expect(migrate(withTelemetry({ installCohort: 'fresh' }), true)).toEqual({ + installCohort: 'fresh' + }) + }) +}) diff --git a/src/main/persistence/loading-store/loaded-cohort-migrations.ts b/src/main/persistence/loading-store/loaded-cohort-migrations.ts index 85eef2c9028..d284106d891 100644 --- a/src/main/persistence/loading-store/loaded-cohort-migrations.ts +++ b/src/main/persistence/loading-store/loaded-cohort-migrations.ts @@ -44,16 +44,13 @@ export class LoadedCohortMigrationOperations { } if (state.settings?.claudeCodeThemeSyncOffer === undefined) { this.runtime.loadNeedsSave = true - // Why: existing users keep Claude Code's look until they accept the offer at their next Claude launch. - // Not keyed on a saved claudeCodeThemeSync: offline writers copy the default (on) into old profiles. - const offer = existingProfile + // Why every profile: settings.json is global, so even a fresh profile must not restyle Claude Code unasked. state = { ...state, settings: { ...state.settings, - ...(offer - ? { claudeCodeThemeSync: false, claudeCodeThemeSyncOffer: 'pending' as const } - : { claudeCodeThemeSyncOffer: 'settled' as const }) + claudeCodeThemeSync: false, + claudeCodeThemeSyncOffer: 'pending' } } } @@ -122,6 +119,41 @@ export class LoadedCohortMigrationOperations { } migrateTelemetry(state: PersistedState, fileExistedOnLoad: boolean): PersistedState { + return this.seedMilestoneInstallCohort( + this.migrateTelemetryIdentity(state, fileExistedOnLoad), + fileExistedOnLoad + ) + } + + /** Freeze once so upgraded profiles' first post-release interaction is never counted as activation. */ + private seedMilestoneInstallCohort( + state: PersistedState, + fileExistedOnLoad: boolean + ): PersistedState { + const telemetry = state.settings?.telemetry + if (!telemetry || telemetry.protectedMilestones?.installCohort !== undefined) { + return state + } + this.runtime.loadNeedsSave = true + return { + ...state, + settings: { + ...state.settings, + telemetry: { + ...telemetry, + protectedMilestones: { + ...telemetry.protectedMilestones, + installCohort: fileExistedOnLoad ? 'existing' : 'fresh' + } + } + } + } + } + + private migrateTelemetryIdentity( + state: PersistedState, + fileExistedOnLoad: boolean + ): PersistedState { const existing = state.settings?.telemetry // Partial telemetry blocks still require migration unless all invariants hold. if ( diff --git a/src/main/persistence/loading-store/loaded-state-parsing.ts b/src/main/persistence/loading-store/loaded-state-parsing.ts index f5225f4134b..05a523cba7d 100644 --- a/src/main/persistence/loading-store/loaded-state-parsing.ts +++ b/src/main/persistence/loading-store/loaded-state-parsing.ts @@ -18,7 +18,7 @@ import { isLegacyOpenCodeSessionCookie, isLegacySshPtyOwnerLease } from '../leasing-ssh-ptys/secret-validation' -import { readGithubCacheSnapshot } from './user-data-path' +import { readGitHubCacheDatabase } from './github-cache-database' import { retainLegacyOpenCodeGoApiKey } from './legacy-opencode-go-api-key-migration' import { gcStaleWorktreeMeta, @@ -50,6 +50,8 @@ type LoadedStateParsingOperationsRuntime = Pick< StoreRuntimeState, | 'dataFile' | 'githubCacheDirty' + | 'githubCacheLegacyFileHash' + | 'githubCachePersistenceDisabled' | 'loadNeedsSave' | 'originalExperimentalNativeChat' | 'protectedSecrets' @@ -287,18 +289,25 @@ export class LoadedStateParsingOperations { chatUiLaunchTipAudience: audience } - // Legacy inline caches seed the session, then move to the cache sidecar. + // Cache precedence, resolved once: an inline legacy cache, else an older build's sidecar, + // else the saved rows. Whatever wins is saved as rows, which retires any sidecar it supersedes. const legacyCache = migrated.githubCache const hasLegacyCache = Object.keys(legacyCache?.pr ?? {}).length > 0 || Object.keys(legacyCache?.issue ?? {}).length > 0 + const stored = readStoredGitHubCache(this.runtime.dataFile) if (hasLegacyCache) { this.runtime.loadNeedsSave = true // Persist the seed even when no cache poll refresh occurs this session. this.runtime.githubCacheDirty = true - } else { - migrated.githubCache = readGithubCacheSnapshot(this.runtime.dataFile) ?? migrated.githubCache + } else if (stored?.cache) { + migrated.githubCache = stored.cache + // A sidecar import, or rows that already hold it, saves so the sidecar retires. + this.runtime.githubCacheDirty ||= stored.sidecarHash !== null } + this.runtime.githubCacheLegacyFileHash = stored?.sidecarHash ?? null + // Unread rows or an unread sidecar may hold newer entries than this session will poll. + this.runtime.githubCachePersistenceDisabled = stored?.unavailable ?? false logStartupMilestone('persistence-load-done', () => ({ repos: migrated.repos.length, @@ -307,3 +316,15 @@ export class LoadedStateParsingOperations { return migrated } } + +function readStoredGitHubCache( + dataFile: string +): ReturnType | null { + try { + return readGitHubCacheDatabase(dataFile) + } catch (error) { + // A disposable cache must never block startup; the first poll refills it. + console.warn('[persistence] Failed to read github cache:', error) + return null + } +} diff --git a/src/main/persistence/loading-store/profile-preferences.ts b/src/main/persistence/loading-store/profile-preferences.ts index d7143a3e82b..4be94581122 100644 --- a/src/main/persistence/loading-store/profile-preferences.ts +++ b/src/main/persistence/loading-store/profile-preferences.ts @@ -23,6 +23,7 @@ import { } from '../applying-settings/feature-interaction-recording' import type { StoreRuntimeState } from './store-runtime-state' +import { persistGithubCache } from './github-cache-persistence' import type { WriteSchedulingOperations } from './write-scheduling' import { scheduleSave } from './write-scheduling' import { bumpLocalWorktreeScanGeneration } from '../../workspaces/catalog/local-worktree-scan-generation' @@ -30,9 +31,17 @@ import { bumpLocalWorktreeScanGeneration } from '../../workspaces/catalog/local- type ProfilePreferencesRuntime = Pick< StoreRuntimeState, | 'activeViewPreference' + | 'dataFile' | 'githubCacheDirty' - | 'githubCacheGeneration' + | 'githubCachePersistedAt' + | 'githubCacheLegacyFileHash' + | 'githubCachePersistenceDisabled' + | 'githubCachePersistTimer' + | 'githubCacheRetryDelayMs' | 'githubCacheWriteListeners' + | 'profileMaintenancePending' + | 'quitFlushStarted' + | 'writesFrozen' | 'protectedSecrets' | 'runDurableMutation' | 'settingsChangeListeners' @@ -197,7 +206,7 @@ export class ProfilePreferences { // Cache polls write a sidecar at flush; scheduling a full profile save here amplifies every poll. this[profilePreferencesContext].runtime.state.githubCache = cache this[profilePreferencesContext].runtime.githubCacheDirty = true - this[profilePreferencesContext].runtime.githubCacheGeneration += 1 + persistGithubCache(this[profilePreferencesContext].runtime, 'routine') for (const listener of this[profilePreferencesContext].runtime.githubCacheWriteListeners) { listener() } diff --git a/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts b/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts index 2a0a8bd8ff7..1122b932b38 100644 --- a/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts +++ b/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' -import { clearMigrationUnsupportedPty } from '../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPty } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { createWorkerMaintenanceFixture, maintenanceBarrier diff --git a/src/main/persistence/loading-store/profile-state-maintenance.ts b/src/main/persistence/loading-store/profile-state-maintenance.ts index 85e3bae7d3b..3f04eba8e92 100644 --- a/src/main/persistence/loading-store/profile-state-maintenance.ts +++ b/src/main/persistence/loading-store/profile-state-maintenance.ts @@ -5,6 +5,7 @@ import type { StoreRuntimeState } from './store-runtime-state' import { drainProfileStateOperations } from './profile-state-flush-lifetime' import { flushCurrentStateAsync } from './write-flush-barriers' import { scheduleSave } from './write-scheduling' +import { persistGithubCache, suspendGithubCachePersistence } from './github-cache-persistence' export type ProfileStateMaintenanceOptions = { signal?: AbortSignal @@ -21,6 +22,7 @@ export function freezeProfileStateWrites(runtime: StoreRuntimeState): void { clearTimeout(runtime.writeTimer) runtime.writeTimer = null } + suspendGithubCachePersistence(runtime) runtime.profileStateAuthority?.close?.() } @@ -30,6 +32,7 @@ export async function freezeProfileStateWritesAsync(runtime: StoreRuntimeState): clearTimeout(runtime.writeTimer) runtime.writeTimer = null } + suspendGithubCachePersistence(runtime) try { await drainProfileStateOperations([ runtime.pendingProfileMaintenance, @@ -56,6 +59,7 @@ export function beginProfileStateMaintenance( clearTimeout(runtime.writeTimer) runtime.writeTimer = null } + suspendGithubCachePersistence(runtime) const resumePreference = runtime.activeViewPreference.pauseForMaintenance() const resumeScheduling = () => { runtime.writesFrozen = false @@ -63,6 +67,8 @@ export function beginProfileStateMaintenance( runtime.pendingProfileMaintenance = null resumePreference() scheduleSave(domains.scheduling) + // Updates admitted while paused (or a retry it skipped) resume their routine save. + persistGithubCache(runtime, 'routine') } const paused = pauseProfileState(runtime, domains, options).then((authority) => { let consumed = false @@ -162,7 +168,7 @@ async function drainProfileFileWork(runtime: StoreRuntimeState): Promise { runtime.staleProfileStateTempCleanup, runtime.pendingWrite, runtime.pendingSnapshotFileWork, - runtime.pendingGithubCacheWrite, + runtime.staleGithubCacheTempCleanup, runtime.activeViewPreference.waitForPendingWrite(), runtime.profileStateAuthority?.drainBackups?.( runtime.profileMaintenancePending || runtime.quitFlushStarted diff --git a/src/main/persistence/loading-store/store-runtime-state.ts b/src/main/persistence/loading-store/store-runtime-state.ts index 6a03d732750..951187da47b 100644 --- a/src/main/persistence/loading-store/store-runtime-state.ts +++ b/src/main/persistence/loading-store/store-runtime-state.ts @@ -83,9 +83,14 @@ export class StoreRuntimeState { dirtyProfileStateDomains: Set | null = new Set() pendingAutomationRunsAfter: readonly AutomationRun[] | undefined githubCacheDirty = false - githubCacheGeneration = 0 + githubCachePersistedAt = Date.now() + githubCachePersistTimer: ReturnType | null = null + githubCacheRetryDelayMs = 0 + /** Fingerprint of a sidecar the loaded cache imported or supersedes; retired once rows commit. */ + githubCacheLegacyFileHash: string | null = null + /** The saved cache or an older build's sidecar was unreadable at load: save nothing this session. */ + githubCachePersistenceDisabled = false readonly githubCacheWriteListeners = new Set<() => void>() - pendingGithubCacheWrite: Promise | null = null readonly staleGithubCacheTempCleanup: Promise readonly staleProfileStateTempCleanup: Promise readonly gitUsernameCache = new Map() diff --git a/src/main/persistence/loading-store/store.ts b/src/main/persistence/loading-store/store.ts index 595f9b0b0fc..0deffce5565 100644 --- a/src/main/persistence/loading-store/store.ts +++ b/src/main/persistence/loading-store/store.ts @@ -2,8 +2,8 @@ import { dirname } from 'node:path' import { setMigrationUnsupportedPty, setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/migration-unsupported-pty-state' -import { agentHookServer } from '../../agent-hooks/server' +} from '../../agent-hooks/observations/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { ActiveViewPreference } from '../preferences/active-view-preference' import { registerPersistedPaneKeyAlias } from '../restoring-sessions/pane-alias-normalization' import { normalizePersistedPaneIdentityState } from '../restoring-sessions/workspace-pane-normalization' diff --git a/src/main/persistence/loading-store/user-data-path.ts b/src/main/persistence/loading-store/user-data-path.ts index 470d611f49b..bbbd5af3d1a 100644 --- a/src/main/persistence/loading-store/user-data-path.ts +++ b/src/main/persistence/loading-store/user-data-path.ts @@ -1,7 +1,6 @@ import { getAppEnvironment } from '../../../shared/app-environment' -import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' +import { copyFileSync, existsSync, mkdirSync, rmSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import type { PersistedState } from '../../../shared/persisted-state-types' import { hardenExistingSecureFile } from '../../../shared/secure-storage/secure-file' import { MOBILE_PAIRING_USERDATA_FILES } from '../../runtime/rpc/server/pairing/mobile-pairing-files' @@ -29,22 +28,6 @@ export function getGithubCacheFile(dataFile = getDataFile()): string { return join(dirname(dataFile), 'orca-github-cache.json') } -export function readGithubCacheSnapshot(dataFile: string): PersistedState['githubCache'] | null { - try { - const parsed = JSON.parse(readFileSync(getGithubCacheFile(dataFile), 'utf-8')) as unknown - const isPlainRecord = (value: unknown): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value) - if ( - isPlainRecord(parsed) && - isPlainRecord((parsed as { pr?: unknown }).pr) && - isPlainRecord((parsed as { issue?: unknown }).issue) - ) { - return parsed as PersistedState['githubCache'] - } - } catch {} - return null -} - /** Reuse the path captured before app.setName; late resolution can change casing and strand paired devices. */ export function getCanonicalUserDataPath(): string { if (!_userDataDir) { diff --git a/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts b/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts index 578a8a2f798..dd3938763d2 100644 --- a/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts +++ b/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts @@ -2,7 +2,7 @@ import type { PersistedState } from '../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { sanitizeWorkspaceSessionTerminalRetirements } from '../../runtime/terminal/surface/mobile-session-terminal-persistence-retirement' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { setMigrationUnsupportedPty } from '../../agent-hooks/migration-unsupported-pty-state' +import { setMigrationUnsupportedPty } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { pruneLocalTerminalScrollbackBuffers } from '../../../shared/workspace-session/workspace-session-terminal-buffers' import { pruneWorkspaceSessionBrowserHistory } from '../../../shared/workspace-session/workspace-session-browser-history' import { migrateWorkspaceSessionTerminalScrollbackSnapshots } from '../../pty/scrollback/terminal-scrollback-snapshots' diff --git a/src/main/persistence/loading-store/workspace-session-write-listeners.ts b/src/main/persistence/loading-store/workspace-session-write-listeners.ts index c1772e4229b..87e66bf49eb 100644 --- a/src/main/persistence/loading-store/workspace-session-write-listeners.ts +++ b/src/main/persistence/loading-store/workspace-session-write-listeners.ts @@ -2,6 +2,7 @@ import type { ExecutionHostId } from '../../../shared/execution-host' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import type { StoreRuntimeState } from './store-runtime-state' import { refileEditorViews } from './layout-editor-views' +import { WORKSPACE_SESSION_DOMAINS } from '../workspace-session-domains' /** Null means any partition may have changed. */ export type WorkspaceSessionWriteListener = (hostId: ExecutionHostId | null) => void @@ -9,10 +10,7 @@ export type WorkspaceSessionWriteListener = (hostId: ExecutionHostId | null) => /** Null means any partition may have changed. */ export type WorkspaceSessionOperationListener = (hostIds: readonly ExecutionHostId[] | null) => void -const WORKSPACE_SESSION_DOMAINS: readonly string[] = [ - 'workspaceSession', - 'workspaceSessionsByHostId' -] +const SESSION_DOMAINS: readonly string[] = WORKSPACE_SESSION_DOMAINS /** Full saves may contain untracked session edits; an absent host makes all partitions candidates. */ export function notifyWorkspaceSessionWritten( @@ -23,7 +21,7 @@ export function notifyWorkspaceSessionWritten( dirtyDomains?: readonly string[], hostId?: ExecutionHostId ): void { - if (dirtyDomains && !dirtyDomains.some((domain) => WORKSPACE_SESSION_DOMAINS.includes(domain))) { + if (dirtyDomains && !dirtyDomains.some((domain) => SESSION_DOMAINS.includes(domain))) { return } // Refile views before listeners project the updated session. diff --git a/src/main/persistence/loading-store/write-flush-barriers.ts b/src/main/persistence/loading-store/write-flush-barriers.ts index bb302fcdadb..629f67d748e 100644 --- a/src/main/persistence/loading-store/write-flush-barriers.ts +++ b/src/main/persistence/loading-store/write-flush-barriers.ts @@ -1,7 +1,4 @@ -import { writeFileSync, renameSync, unlinkSync } from 'node:fs' -import { rename, rm, writeFile } from 'node:fs/promises' -import { durableWriteTempPath } from '../../filesystem/durable-file-write' -import { getGithubCacheFile } from './user-data-path' +import { persistGithubCache } from './github-cache-persistence' import type { StoreRuntimeState } from './store-runtime-state' import type { PrimaryStateWriteOperations } from './primary-state-writes' @@ -16,16 +13,18 @@ type WriteFlushBarrierOperationsRuntime = Pick< | 'dataFile' | 'firstPendingSaveAt' | 'githubCacheDirty' - | 'githubCacheGeneration' + | 'githubCachePersistedAt' + | 'githubCacheLegacyFileHash' + | 'githubCachePersistenceDisabled' + | 'githubCachePersistTimer' + | 'githubCacheRetryDelayMs' | 'lastDurableWriteGeneration' - | 'pendingGithubCacheWrite' | 'pendingProfileFlushes' | 'pendingProfileMaintenance' | 'profileMaintenancePending' | 'profileStateAuthority' | 'quitFlushPromise' | 'quitFlushStarted' - | 'staleGithubCacheTempCleanup' | 'staleProfileStateTempCleanup' | 'state' | 'writeGeneration' @@ -70,7 +69,7 @@ export class WriteFlushBarrierOperations { } catch (err) { console.error('[active-view] Failed to flush preference:', err) } - writeGithubCacheSnapshotSync(this) + persistGithubCache(runtime, 'routine') } flushAsync(): Promise { @@ -177,7 +176,11 @@ export async function flushCurrentStateAsync( await (final ? runtime.activeViewPreference.flushAsync() : runtime.activeViewPreference.flushPendingAsync(signal)) - await writeGithubCacheSnapshotAsync(owner, final, signal) + // Quit and explicit barriers save the cache now; best-effort flushes may wait. + persistGithubCache( + runtime, + final || requireInitialGenerationDurable ? 'barrier' : 'routine' + ) if (final || runtime.profileMaintenancePending) { await runtime.profileStateAuthority?.drainBackups?.(true) } @@ -200,83 +203,3 @@ export async function flushCurrentStateAsync( } }) } - -export async function writeGithubCacheSnapshotAsync( - owner: WriteFlushBarrierOperations, - drainToStableGeneration = true, - signal?: AbortSignal -): Promise { - const { runtime } = owner[writeFlushBarrierOperationsContext] - if (!runtime.githubCacheDirty) { - return - } - const previousWrite = runtime.pendingGithubCacheWrite ?? runtime.staleGithubCacheTempCleanup - const nextWrite = previousWrite - .then(async () => { - while (runtime.githubCacheDirty) { - if (signal?.aborted) { - throw new Error('GitHub cache flush aborted') - } - const generation = runtime.githubCacheGeneration - const cacheFile = getGithubCacheFile(runtime.dataFile) - const tmpFile = durableWriteTempPath(cacheFile) - let renamed = false - try { - await writeFile(tmpFile, JSON.stringify(runtime.state.githubCache), 'utf-8') - if (generation === runtime.githubCacheGeneration) { - await rename(tmpFile, cacheFile) - renamed = true - if (generation === runtime.githubCacheGeneration) { - runtime.githubCacheDirty = false - } - } - } finally { - if (!renamed) { - await rm(tmpFile).catch(() => {}) - } - } - if (signal?.aborted) { - throw new Error('GitHub cache flush aborted') - } - if (!drainToStableGeneration) { - break - } - } - }) - .catch((err) => { - console.warn('[persistence] Failed to write github cache snapshot:', err) - }) - .finally(() => { - if (runtime.pendingGithubCacheWrite === nextWrite) { - runtime.pendingGithubCacheWrite = null - } - }) - runtime.pendingGithubCacheWrite = nextWrite - await nextWrite -} - -export function writeGithubCacheSnapshotSync(owner: WriteFlushBarrierOperations): void { - const { runtime } = owner[writeFlushBarrierOperationsContext] - if (!runtime.githubCacheDirty) { - return - } - if (runtime.pendingGithubCacheWrite) { - void writeGithubCacheSnapshotAsync(owner) - return - } - const cacheFile = getGithubCacheFile(runtime.dataFile) - const generation = runtime.githubCacheGeneration - const tmpFile = durableWriteTempPath(cacheFile) - try { - writeFileSync(tmpFile, JSON.stringify(runtime.state.githubCache), 'utf-8') - renameSync(tmpFile, cacheFile) - if (generation === runtime.githubCacheGeneration) { - runtime.githubCacheDirty = false - } - } catch (err) { - try { - unlinkSync(tmpFile) - } catch {} - console.warn('[persistence] Failed to write github cache snapshot:', err) - } -} diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-browser-cookie-store.ts b/src/main/persistence/moving-wsl-projects/wsl-move-browser-cookie-store.ts index ecc827eed23..6432123eba8 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-browser-cookie-store.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-browser-cookie-store.ts @@ -7,7 +7,7 @@ import { flushBrowserPartitionCookies } from '../../browser/cookies/browser-partition-cookie-copy' import { activeBrowserRoutePartitionOrcaProfileId } from '../../browser/routing/partitions/browser-route-partition-binding-runtime' -import { browserSessionRegistry } from '../../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../../browser/sessions/profiles/browser-session-registry' import { browserSessionsInitialized } from '../../browser/sessions/browser-session-startup' import { bindWslHostBrowserRoutePartition, diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts index 7fe3e1e1dbd..0f95c5a5574 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { collectWslMoveGateInputs, type WslMoveGateFactSources } from './wsl-move-gate-facts' import { assessWslMoveTerminals } from './wsl-move-terminal-gate' diff --git a/src/main/persistence/persistence-async-write-syscalls.test.ts b/src/main/persistence/persistence-async-write-syscalls.test.ts index 19e9049f3b6..499df38a519 100644 --- a/src/main/persistence/persistence-async-write-syscalls.test.ts +++ b/src/main/persistence/persistence-async-write-syscalls.test.ts @@ -152,27 +152,6 @@ describe('worker persistence avoids synchronous profile filesystem calls', () => expect(readState().ui.sidebarWidth).toBe(511) }) - it('drains mutations made while a sidecar rename is stalled', async () => { - const { store, readState } = await createWorkerMaintenanceFixture() - const started = maintenanceBarrier() - const finish = maintenanceBarrier() - fsCalls.waitAsync = (name, path) => { - if (name !== 'rename' || !path.includes('orca-github-cache.json.')) { - return - } - started.resolve() - return finish.promise - } - store.updateUI({ sidebarWidth: 611 }) - store.setGitHubCache({ pr: {}, issue: {} }) - const barrier = store.flushPendingOrThrowAsync() - await started.promise - store.updateUI({ sidebarWidth: 612 }) - finish.resolve() - await barrier - expect(readState().ui.sidebarWidth).toBe(612) - }) - it('serializes queued durable mutations and refuses a synchronous live flush', async () => { const { store, authority, readState } = await createWorkerMaintenanceFixture() const gate = pauseCommit(authority) diff --git a/src/main/persistence/persistence-flush-and-save-scheduling.test.ts b/src/main/persistence/persistence-flush-and-save-scheduling.test.ts index cec21e4fd09..163c2505dff 100644 --- a/src/main/persistence/persistence-flush-and-save-scheduling.test.ts +++ b/src/main/persistence/persistence-flush-and-save-scheduling.test.ts @@ -190,7 +190,7 @@ describe('Store', () => { }) }) - it('keeps GitHub cache sidecars scoped to explicit profile data files', async () => { + it('keeps the GitHub cache scoped to explicit profile data files', async () => { const profileADir = join(testState.dir, 'profiles', 'a') const profileBDir = join(testState.dir, 'profiles', 'b') const profileADataFile = join(profileADir, 'orca-data.json') @@ -204,12 +204,12 @@ describe('Store', () => { initDataPath() const profileAStore = createSqliteTestStore(Store, { dataFile: profileADataFile }) profileAStore.setGitHubCache({ pr: { 'o/r#a': { fetchedAt: 10 } as never }, issue: {} }) - profileAStore.flush() + await profileAStore.flushPendingOrThrowAsync() const profileBStore = createSqliteTestStore(Store, { dataFile: profileBDataFile }) expect(profileBStore.getGitHubCache().pr['o/r#a']).toBeUndefined() profileBStore.setGitHubCache({ pr: { 'o/r#b': { fetchedAt: 20 } as never }, issue: {} }) - profileBStore.flush() + await profileBStore.flushPendingOrThrowAsync() const restartedProfileA = createSqliteTestStore(Store, { dataFile: profileADataFile }) const restartedProfileB = createSqliteTestStore(Store, { dataFile: profileBDataFile }) diff --git a/src/main/persistence/persistence-loading-store-extraction.test.ts b/src/main/persistence/persistence-loading-store-extraction.test.ts index 1a3ffe08b47..c0a3094804d 100644 --- a/src/main/persistence/persistence-loading-store-extraction.test.ts +++ b/src/main/persistence/persistence-loading-store-extraction.test.ts @@ -107,7 +107,7 @@ describe('loading Store extraction seams', () => { const first = await createStore() const { Store } = await import('./loading-store/store') const { setMigrationUnsupportedPty } = - await import('../agent-hooks/migration-unsupported-pty-state') + await import('../agent-hooks/observations/migration-unsupported-pty-state') const secondDataFile = join(testState.dir, 'second-profile', 'orca-data.json') const second = createSqliteTestStore(Store, { dataFile: secondDataFile }) diff --git a/src/main/persistence/profile-state/profile-state-database-schema.ts b/src/main/persistence/profile-state/profile-state-database-schema.ts index 2b66285478b..9b4a0ff4f39 100644 --- a/src/main/persistence/profile-state/profile-state-database-schema.ts +++ b/src/main/persistence/profile-state/profile-state-database-schema.ts @@ -38,3 +38,26 @@ export function createProfileStateTablesSql(): string { updated_at INTEGER NOT NULL );` } + +/** Additive split-domain storage (see profile-state-document-parts); older v3 builds ignore it. */ +export const PROFILE_STATE_DOCUMENT_PARTS_TABLE = 'profile_state_document_parts' +export const PROFILE_STATE_DOCUMENT_PARTS_META_TABLE = 'profile_state_document_parts_meta' + +export function createProfileStateDocumentPartsTablesSql(): string { + return `CREATE TABLE IF NOT EXISTS ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE} ( + domain TEXT PRIMARY KEY NOT NULL, + domain_version INTEGER NOT NULL, + revision INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + content_hash TEXT NOT NULL, + legacy_revision INTEGER + ); + CREATE TABLE IF NOT EXISTS ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} ( + domain TEXT NOT NULL, + part_key TEXT NOT NULL, + ordinal INTEGER NOT NULL, + payload TEXT NOT NULL, + content_hash TEXT NOT NULL, + PRIMARY KEY (domain, part_key) + );` +} diff --git a/src/main/persistence/profile-state/profile-state-database-snapshot.ts b/src/main/persistence/profile-state/profile-state-database-snapshot.ts index fd216434819..3f416d4a7f2 100644 --- a/src/main/persistence/profile-state/profile-state-database-snapshot.ts +++ b/src/main/persistence/profile-state/profile-state-database-snapshot.ts @@ -4,6 +4,7 @@ import { basename, dirname, resolve } from 'node:path' import Database from '../../sqlite/sync-database' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' import { durableWriteTempPath, renameDurable } from '../../filesystem/durable-file-write' +import { refreshStaleProfileStateLegacyDocuments } from './profile-state-legacy-document-refresh' /** Caller owns the destination and keeps the source connection open until completion. */ export async function writeProfileStateDatabaseSnapshotAsync( @@ -38,6 +39,9 @@ export async function writeProfileStateDatabaseSnapshotAsync( if (snapshot.pragma('journal_mode = DELETE', { simple: true }) !== 'delete') { throw new Error('Profile state snapshot could not become a self-contained database') } + // A restored snapshot outlives any later refresh of the live copy, so older builds + // reading it must already see current legacy rows. + refreshStaleProfileStateLegacyDocuments(snapshot) } finally { snapshot.close() } diff --git a/src/main/persistence/profile-state/profile-state-database.ts b/src/main/persistence/profile-state/profile-state-database.ts index 83fcd713e1c..e641cc463c1 100644 --- a/src/main/persistence/profile-state/profile-state-database.ts +++ b/src/main/persistence/profile-state/profile-state-database.ts @@ -1,4 +1,5 @@ import { withProfileStateWriteTransaction } from './profile-state-write-transaction' +import { ensureProfileStateDocumentPartsTables } from './profile-state-document-parts' import { hasProfileStateAuthorityMarker } from './profile-state-authority-marker' import Database, { isSqliteAvailable } from '../../sqlite/sync-database' import { migrateAutomationRunsStorage } from './profile-state-automation-runs-migration' @@ -113,6 +114,8 @@ export function openProfileStateDatabase( // journal_mode can change the header even without row writes; validate everything first. migrateProfileStateSchema(probe, storedVersion, profileId) configureProfileStatePragmas(probe) + // Additive tables older v3 builds ignore (no schema bump); after busy_timeout is set. + ensureProfileStateDocumentPartsTables(probe) hardenSqliteDatabaseFiles(dbPath) transferred = true return { db: probe, readOnly: false, profileId } diff --git a/src/main/persistence/profile-state/profile-state-document-part-ordinals.ts b/src/main/persistence/profile-state/profile-state-document-part-ordinals.ts new file mode 100644 index 00000000000..cdc9beadaf8 --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-document-part-ordinals.ts @@ -0,0 +1,73 @@ +const ORDINAL_GAP = 1024 + +/** + * Order-preserving ordinals that reuse as many existing values as possible, so inserting, + * removing or moving one key rewrites only that key's row instead of renumbering the rest. + * Keeps the longest run of keys whose previous ordinals are already increasing and spreads + * the others into the gaps between them. + */ +export function assignProfileStatePartOrdinals( + keys: readonly string[], + previous: ReadonlyMap +): number[] { + const kept = keepLongestIncreasing(keys.map((key) => previous.get(key))) + const ordinals: number[] = Array.from({ length: keys.length }, () => 0) + let index = 0 + while (index < keys.length) { + if (kept[index] !== undefined) { + ordinals[index] = kept[index]! + index++ + continue + } + let end = index + while (end < keys.length && kept[end] === undefined) { + end++ + } + const count = end - index + const low = index > 0 ? ordinals[index - 1]! : undefined + const high = end < keys.length ? kept[end]! : undefined + const start = low ?? (high !== undefined ? high - (count + 1) * ORDINAL_GAP : 0) + const stop = high ?? start + (count + 1) * ORDINAL_GAP + const step = Math.floor((stop - start) / (count + 1)) + if (step < 1) { + return keys.map((_, position) => position * ORDINAL_GAP) + } + for (let offset = 0; offset < count; offset++) { + ordinals[index + offset] = start + step * (offset + 1) + } + index = end + } + return ordinals +} + +/** Longest strictly increasing subsequence; other positions become undefined. */ +function keepLongestIncreasing(values: readonly (number | undefined)[]): (number | undefined)[] { + const tails: number[] = [] + const tailIndex: number[] = [] + const parent: number[] = Array.from({ length: values.length }, () => -1) + values.forEach((value, index) => { + if (value === undefined) { + return + } + let low = 0 + let high = tails.length + while (low < high) { + const middle = (low + high) >> 1 + if (tails[middle]! < value) { + low = middle + 1 + } else { + high = middle + } + } + tails[low] = value + tailIndex[low] = index + parent[index] = low > 0 ? tailIndex[low - 1]! : -1 + }) + const kept: (number | undefined)[] = Array.from({ length: values.length }, () => undefined) + let cursor = tailIndex.at(-1) ?? -1 + while (cursor !== -1) { + kept[cursor] = values[cursor] + cursor = parent[cursor]! + } + return kept +} diff --git a/src/main/persistence/profile-state/profile-state-document-parts-reader.ts b/src/main/persistence/profile-state/profile-state-document-parts-reader.ts new file mode 100644 index 00000000000..735d69dd9b3 --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-document-parts-reader.ts @@ -0,0 +1,76 @@ +import type Database from '../../sqlite/sync-database' +import { + isProfileStateSplitDomain, + PROFILE_STATE_SPLIT_DOMAIN_DEPTHS +} from './profile-state-document-parts' +import { readProfileStateSplitDocument, safeInteger } from './profile-state-document-parts-storage' +import { + isRecord, + ProfileStateDocumentCorruptionError, + validateProfileStateDocumentRow, + type ProfileStateDocument +} from './profile-state-document-validation' + +const SPLIT_DOMAIN_LIST = [...PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.keys()] + .map((domain) => `'${domain}'`) + .join(',') + +/** + * Document row columns that skip the legacy payload of split domains: their parts are + * usually authoritative, and that payload can be megabytes. + */ +export const PROFILE_STATE_DOCUMENT_ROW_COLUMNS = `domain, + CASE WHEN domain IN (${SPLIT_DOMAIN_LIST}) THEN NULL ELSE payload END AS payload, + domain_version, revision, updated_at, content_hash` + +/** Validated document for a row selected with PROFILE_STATE_DOCUMENT_ROW_COLUMNS. */ +export function readProfileStateDocumentRow( + db: Database.Database, + row: unknown, + retainParsedValue: boolean +): ProfileStateDocument & { value?: unknown } { + return ( + readProfileStateSplitDocumentForRow(db, row, retainParsedValue) ?? + validateProfileStateDocumentRow(withLegacyPayload(db, row), { retainParsedValue }) + ) +} + +// Runs inside the caller's open statement, so it reads the same snapshot. +function withLegacyPayload(db: Database.Database, row: unknown): unknown { + if (!isRecord(row) || row.payload !== null || typeof row.domain !== 'string') { + return row + } + const legacy: unknown = db + .prepare('SELECT payload FROM profile_state_documents WHERE domain = ?') + .get(row.domain) + return { ...row, payload: isRecord(legacy) ? legacy.payload : null } +} + +/** The reassembled document when this legacy row's domain is stored as parts. */ +export function readProfileStateSplitDocumentForRow( + db: Database.Database, + row: unknown, + retainParsedValue: boolean +): (ProfileStateDocument & { value?: unknown }) | undefined { + const revision = isRecord(row) ? safeInteger(row.revision) : undefined + if ( + !isRecord(row) || + typeof row.domain !== 'string' || + !isProfileStateSplitDomain(row.domain) || + revision === undefined + ) { + return undefined + } + const document = readProfileStateSplitDocument(db, row.domain, revision) + if (!document || !retainParsedValue) { + return document + } + try { + return { ...document, value: JSON.parse(document.payload) } + } catch { + throw new ProfileStateDocumentCorruptionError( + `Profile state document parts are invalid JSON: ${row.domain}`, + row.domain + ) + } +} diff --git a/src/main/persistence/profile-state/profile-state-document-parts-storage.ts b/src/main/persistence/profile-state/profile-state-document-parts-storage.ts new file mode 100644 index 00000000000..9641f09e0fc --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-document-parts-storage.ts @@ -0,0 +1,303 @@ +import type Database from '../../sqlite/sync-database' +import { + assembleProfileStateDomainPayload, + hasProfileStateDocumentPartsTables, + hashProfileStatePart, + isProfileStateSplitDomain, + PROFILE_STATE_DOCUMENT_PARTS_META_TABLE, + PROFILE_STATE_DOCUMENT_PARTS_TABLE, + PROFILE_STATE_SPLIT_DOMAIN_DEPTHS, + splitProfileStateDomainValue, + type ProfileStateDocumentPart +} from './profile-state-document-parts' +import { + hashProfileStatePayload, + isRecord, + ProfileStateDocumentCorruptionError, + type ProfileStateDocument +} from './profile-state-document-validation' +import { assignProfileStatePartOrdinals } from './profile-state-document-part-ordinals' + +type PartsMeta = { + domainVersion: number + revision: number + updatedAt: number + contentHash: string + legacyRevision: number | null +} + +function readPartsMeta(db: Database.Database, domain: string): PartsMeta | undefined { + if (!hasProfileStateDocumentPartsTables(db)) { + return undefined + } + const row = db + .prepare( + `SELECT domain_version, revision, updated_at, content_hash, legacy_revision + FROM ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE} WHERE domain = ?` + ) + .get(domain) + if (row === undefined) { + return undefined + } + const domainVersion = isRecord(row) ? safeInteger(row.domain_version) : undefined + const revision = isRecord(row) ? safeInteger(row.revision) : undefined + const updatedAt = isRecord(row) ? safeInteger(row.updated_at) : undefined + const legacyRevision = isRecord(row) ? safeInteger(row.legacy_revision) : undefined + if ( + !isRecord(row) || + // Same bounds as an ordinary document row, which this metadata stands in for. + domainVersion === undefined || + domainVersion < 1 || + revision === undefined || + revision < 1 || + updatedAt === undefined || + updatedAt < 0 || + typeof row.content_hash !== 'string' || + !/^[a-f0-9]{64}$/.test(row.content_hash) || + (row.legacy_revision !== null && (legacyRevision === undefined || legacyRevision < 1)) + ) { + throw new ProfileStateDocumentCorruptionError( + `Profile state document parts metadata is invalid: ${domain}`, + domain + ) + } + return { + domainVersion, + revision, + updatedAt, + contentHash: row.content_hash, + legacyRevision: legacyRevision ?? null + } +} + +export function safeInteger(value: unknown): number | undefined { + return typeof value === 'number' && Number.isSafeInteger(value) ? value : undefined +} + +export function readLegacyRevision(db: Database.Database, domain: string): number | null { + const row = db + .prepare('SELECT revision FROM profile_state_documents WHERE domain = ?') + .get(domain) + return (isRecord(row) ? safeInteger(row.revision) : undefined) ?? null +} + +/** Parts win only while the legacy row is the one this layout last synced. */ +export function authoritativeMeta( + db: Database.Database, + domain: string, + legacyRevision: number | null +): PartsMeta | undefined { + const meta = readPartsMeta(db, domain) + return meta !== undefined && legacyRevision !== null && meta.legacyRevision === legacyRevision + ? meta + : undefined +} + +/** Reassembled document for a split domain, or undefined when its legacy row is authoritative. */ +export function readProfileStateSplitDocument( + db: Database.Database, + domain: string, + legacyRevision: number +): ProfileStateDocument | undefined { + if (!isProfileStateSplitDomain(domain)) { + return undefined + } + const meta = authoritativeMeta(db, domain, legacyRevision) + if (!meta) { + return undefined + } + const rows = db + .prepare( + `SELECT part_key, payload, content_hash FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} + WHERE domain = ? ORDER BY ordinal` + ) + .iterate(domain) + const parts: ProfileStateDocumentPart[] = [] + for (const row of rows) { + if ( + !isRecord(row) || + typeof row.part_key !== 'string' || + typeof row.payload !== 'string' || + row.content_hash !== hashProfileStatePart(row.payload) + ) { + throw new ProfileStateDocumentCorruptionError( + `Profile state document part is invalid: ${domain}`, + domain + ) + } + parts.push({ key: row.part_key, payload: row.payload }) + } + let payload: string + try { + payload = assembleProfileStateDomainPayload(parts) + } catch { + throw new ProfileStateDocumentCorruptionError( + `Profile state document parts are invalid: ${domain}`, + domain + ) + } + if (hashProfileStatePayload(payload) !== meta.contentHash) { + throw new ProfileStateDocumentCorruptionError( + `Profile state document parts hash mismatch: ${domain}`, + domain + ) + } + return { + domain, + payload, + domainVersion: meta.domainVersion, + revision: meta.revision, + updatedAt: meta.updatedAt, + contentHash: meta.contentHash + } +} + +export type SplitDomainWriteState = + | { kind: 'unsplit' } + | { kind: 'parts'; legacyRevision: number; contentHash: string; revision: number } + +/** Lets the writer compare by hash without reading or re-validating a stale legacy payload. */ +export function readSplitDomainWriteState( + db: Database.Database, + domain: string +): SplitDomainWriteState { + if (!isProfileStateSplitDomain(domain)) { + return { kind: 'unsplit' } + } + const legacyRevision = readLegacyRevision(db, domain) + const meta = authoritativeMeta(db, domain, legacyRevision) + return meta && legacyRevision !== null + ? { kind: 'parts', legacyRevision, contentHash: meta.contentHash, revision: meta.revision } + : { kind: 'unsplit' } +} + +export function deleteProfileStateDomainParts(db: Database.Database, domain: string): void { + if (!hasProfileStateDocumentPartsTables(db)) { + return + } + db.prepare(`DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} WHERE domain = ?`).run(domain) + db.prepare(`DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE} WHERE domain = ?`).run(domain) +} + +export function clearProfileStateDocumentParts(db: Database.Database): void { + if (!hasProfileStateDocumentPartsTables(db)) { + return + } + db.exec(`DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE}; + DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE};`) +} + +/** + * Write only the parts whose content or position changed. Returns false when the payload + * cannot be split losslessly; the caller then stores it as an ordinary legacy row. + */ +export function writeProfileStateDomainParts( + db: Database.Database, + args: { + domain: string + payload: string + /** Already-parsed payload, when the caller has it. */ + value?: unknown + payloadHash: string + domainVersion: number + revision: number + updatedAt: number + /** Legacy row revision after this write; parts stay authoritative only while it matches. */ + legacyRevision: number + /** Existing parts are a valid base to diff against. */ + diffExisting: boolean + } +): boolean { + if (!hasProfileStateDocumentPartsTables(db)) { + return false + } + const depth = PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.get(args.domain) + if (depth === undefined) { + return false + } + const parts = splitProfileStateDomainValue( + args.value === undefined ? JSON.parse(args.payload) : args.value, + depth + ) + // Non-canonical JSON (whitespace, escapes) would not round-trip byte-for-byte. + if (assembleProfileStateDomainPayload(parts) !== args.payload) { + deleteProfileStateDomainParts(db, args.domain) + return false + } + const existing = new Map() + if (args.diffExisting) { + for (const row of db + .prepare( + `SELECT part_key, ordinal, content_hash FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} + WHERE domain = ?` + ) + .iterate(args.domain)) { + if (isRecord(row) && typeof row.part_key === 'string') { + existing.set(row.part_key, { + ordinal: Number(row.ordinal), + contentHash: String(row.content_hash) + }) + } + } + } else { + db.prepare(`DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} WHERE domain = ?`).run( + args.domain + ) + } + const ordinals = assignProfileStatePartOrdinals( + parts.map(({ key }) => key), + new Map([...existing].map(([key, { ordinal }]) => [key, ordinal])) + ) + const insert = db.prepare( + `INSERT INTO ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} + (domain, part_key, ordinal, payload, content_hash) VALUES (?, ?, ?, ?, ?)` + ) + const updatePayload = db.prepare( + `UPDATE ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} SET ordinal = ?, payload = ?, content_hash = ? + WHERE domain = ? AND part_key = ?` + ) + const updateOrdinal = db.prepare( + `UPDATE ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} SET ordinal = ? WHERE domain = ? AND part_key = ?` + ) + const remove = db.prepare( + `DELETE FROM ${PROFILE_STATE_DOCUMENT_PARTS_TABLE} WHERE domain = ? AND part_key = ?` + ) + const seen = new Set() + parts.forEach((part, index) => { + seen.add(part.key) + const ordinal = ordinals[index]! + const previous = existing.get(part.key) + const contentHash = hashProfileStatePart(part.payload) + if (!previous) { + insert.run(args.domain, part.key, ordinal, part.payload, contentHash) + } else if (previous.contentHash !== contentHash) { + updatePayload.run(ordinal, part.payload, contentHash, args.domain, part.key) + } else if (previous.ordinal !== ordinal) { + updateOrdinal.run(ordinal, args.domain, part.key) + } + }) + for (const key of existing.keys()) { + if (!seen.has(key)) { + remove.run(args.domain, key) + } + } + db.prepare( + `INSERT INTO ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE} + (domain, domain_version, revision, updated_at, content_hash, legacy_revision) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(domain) DO UPDATE SET + domain_version = excluded.domain_version, + revision = excluded.revision, + updated_at = excluded.updated_at, + content_hash = excluded.content_hash, + legacy_revision = excluded.legacy_revision` + ).run( + args.domain, + args.domainVersion, + args.revision, + args.updatedAt, + args.payloadHash, + args.legacyRevision + ) + return true +} diff --git a/src/main/persistence/profile-state/profile-state-document-parts.test.ts b/src/main/persistence/profile-state/profile-state-document-parts.test.ts new file mode 100644 index 00000000000..608b1f7f764 --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-document-parts.test.ts @@ -0,0 +1,168 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { exportProfileStateJson, readProfileStateRevision } from './profile-state-documents' +import { + openProfileStateDatabase, + openProfileStateDatabaseReadOnly, + profileStateDatabaseFile +} from './profile-state-database' +import { writeProfileStateDomains } from './profile-state-domain-writes' +import { readProfileStateDomainsWithRevisionFromDatabase } from './profile-state-domain-reader' +import { hashProfileStatePayload, isRecord } from './profile-state-document-validation' +import { writeProfileStateBackup } from './profile-state-backup-job' +import { ProfileStateSqliteAuthority } from './profile-state-sqlite-authority' + +const directories: string[] = [] + +afterEach(() => { + vi.useRealTimers() + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +function databasePath(): string { + const directory = mkdtempSync(join(tmpdir(), 'orca-profile-state-parts-')) + directories.push(directory) + return profileStateDatabaseFile(directory) +} + +function open() { + return openProfileStateDatabase(databasePath(), 'profile-a').db +} + +type Db = ReturnType + +function write(db: Db, domains: Record): void { + writeProfileStateDomains(db, { + expectedRevision: readProfileStateRevision(db), + replacements: Object.entries(domains).map(([domain, payload]) => ({ domain, payload })) + }) +} + +function read(db: Db, domain: string): unknown { + const result = readProfileStateDomainsWithRevisionFromDatabase(db, [domain]) + if (result.kind !== 'values') { + throw result.error + } + return result.values.get(domain) +} + +/** What a build without per-entry storage reads: only profile_state_documents. */ +function readAsOlderBuild(path: string, domain: string): string { + const { db } = openProfileStateDatabaseReadOnly(path, 'profile-a') + try { + const row: unknown = db + .prepare('SELECT payload FROM profile_state_documents WHERE domain = ?') + .get(domain) + return isRecord(row) && typeof row.payload === 'string' ? row.payload : '' + } finally { + db.close() + } +} + +const v1 = + '{"runtime:a":{"tabsByWorktree":{"wt1":[{"id":"t1","title":"shell"}],"wt2":[{"id":"t2"}]},"activeTabId":"t1"},"ssh:b":{"tabsByWorktree":{}}}' +const v2 = + '{"runtime:a":{"tabsByWorktree":{"wt2":[{"id":"t2"}],"wt3":[],"wt1":[{"id":"t1","title":"renamed"}]},"activeTabId":"t1"},"ssh:b":{"tabsByWorktree":{}}}' + +describe('profile state document parts', () => { + it('reads back the exact document after entries change, appear and move', () => { + const db = open() + try { + write(db, { workspaceSessionsByHostId: v1, other: '1' }) + write(db, { workspaceSessionsByHostId: v2 }) + + expect(exportProfileStateJson(db)).toBe(`{"workspaceSessionsByHostId":${v2},"other":1}`) + } finally { + db.close() + } + }) + + it('gives an older build current state after a crash once the writer reopens', () => { + const path = databasePath() + openProfileStateDatabase(path, 'profile-a').db.close() + const crashed = new ProfileStateSqliteAuthority(path, 'profile-a') + crashed.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v1 }]) + crashed.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v2 }]) + // A crash never runs the graceful-close refresh. + crashed.close() + + const reopened = new ProfileStateSqliteAuthority(path, 'profile-a') + try { + reopened.writeSerializedDomains([{ domain: 'other', payload: '1' }]) + expect(readAsOlderBuild(path, 'workspaceSessionsByHostId')).toBe(v2) + } finally { + reopened.close() + } + }) + + it('trusts a document an older build rewrote, then keeps later writes', () => { + const db = open() + try { + write(db, { workspaceSessionsByHostId: v1 }) + write(db, { workspaceSessionsByHostId: v2 }) + // An older build knows only profile_state_documents. + const olderPayload = '{"runtime:a":{"activeTabId":"from-older-build"}}' + const revision = readProfileStateRevision(db) + 1 + db.prepare( + `UPDATE profile_state_documents SET payload = ?, content_hash = ?, revision = ? + WHERE domain = 'workspaceSessionsByHostId'` + ).run(olderPayload, hashProfileStatePayload(olderPayload), revision) + db.prepare(`UPDATE profile_state_meta SET value = ? WHERE key = 'revision'`).run( + String(revision) + ) + + expect(read(db, 'workspaceSessionsByHostId')).toEqual({ + 'runtime:a': { activeTabId: 'from-older-build' } + }) + + write(db, { workspaceSessionsByHostId: v1 }) + write(db, { workspaceSessionsByHostId: v2 }) + expect(exportProfileStateJson(db)).toBe(`{"workspaceSessionsByHostId":${v2}}`) + } finally { + db.close() + } + }) + + it('gives an older build current state after writes stop, without another write', () => { + const path = databasePath() + openProfileStateDatabase(path, 'profile-a').db.close() + const first = new ProfileStateSqliteAuthority(path, 'profile-a') + first.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v1 }]) + const revision = first.revision + first.close() + + vi.useFakeTimers() + const writer = new ProfileStateSqliteAuthority(path, 'profile-a') + try { + writer.initializeFromRevision(revision) + writer.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v2 }]) + vi.advanceTimersByTime(60 * 60_000) + expect(readAsOlderBuild(path, 'workspaceSessionsByHostId')).toBe(v2) + } finally { + writer.close() + } + }) + + it('publishes backups whose older-build copy is current', async () => { + const path = databasePath() + openProfileStateDatabase(path, 'profile-a').db.close() + const writer = new ProfileStateSqliteAuthority(path, 'profile-a') + try { + writer.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v1 }]) + writer.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v2 }]) + const backup = join(directories.at(-1)!, 'backup.db') + await writeProfileStateBackup({ + databasePath: path, + profileId: 'profile-a', + targetPath: backup + }) + expect(readAsOlderBuild(backup, 'workspaceSessionsByHostId')).toBe(v2) + } finally { + writer.close() + } + }) +}) diff --git a/src/main/persistence/profile-state/profile-state-document-parts.ts b/src/main/persistence/profile-state/profile-state-document-parts.ts new file mode 100644 index 00000000000..ac100651fa8 --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-document-parts.ts @@ -0,0 +1,150 @@ +import type Database from '../../sqlite/sync-database' +import { hashProfileStatePayload, isRecord } from './profile-state-document-validation' +import { WORKSPACE_SESSION_DOMAINS } from '../workspace-session-domains' + +/** + * Large map-shaped domains are stored as one row per entry so a save rewrites only the + * entries that changed. Readers reassemble the exact original JSON, so everything above + * this layer still sees one document per domain. + * + * Older builds ignore these tables and read the domain's legacy `profile_state_documents` + * row. That row is refreshed from the parts when the writer starts, at most every five minutes while it runs, and at graceful close; when an + * older build rewrites it, its revision no longer matches `legacy_revision` and the legacy + * row becomes authoritative again until the next write re-splits it. + */ +export { + PROFILE_STATE_DOCUMENT_PARTS_META_TABLE, + PROFILE_STATE_DOCUMENT_PARTS_TABLE +} from './profile-state-database-schema' +import { + createProfileStateDocumentPartsTablesSql, + PROFILE_STATE_DOCUMENT_PARTS_META_TABLE, + PROFILE_STATE_DOCUMENT_PARTS_TABLE +} from './profile-state-database-schema' + +const [LOCAL_SESSION_DOMAIN, HOST_SESSION_DOMAIN] = WORKSPACE_SESSION_DOMAINS + +/** Object nesting levels split into rows; arrays and scalars are always leaves. */ +export const PROFILE_STATE_SPLIT_DOMAIN_DEPTHS: ReadonlyMap = new Map([ + // host → session field → tab/worktree/pane entry + [HOST_SESSION_DOMAIN, 3], + // session field → tab/worktree/pane entry + [LOCAL_SESSION_DOMAIN, 2], + // environment → { workspaces } → worktree + ['remoteLayoutSnapshots', 3], + ['worktreeMeta', 1], + ['worktreeMetaByIdentity', 1], + ['worktreeIdentityAliases', 1] +]) + +export function isProfileStateSplitDomain(domain: string): boolean { + return PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.has(domain) +} + +export type ProfileStateDocumentPart = { + /** JSON array of the object keys leading to this value. */ + key: string + payload: string +} + +/** Depth-first parts whose concatenation reproduces JSON.stringify(value) exactly. */ +export function splitProfileStateDomainValue( + value: unknown, + depth: number +): ProfileStateDocumentPart[] { + const parts: ProfileStateDocumentPart[] = [] + const visit = (current: unknown, path: string[], remaining: number): void => { + if (remaining > 0 && isRecord(current) && typeof current.toJSON !== 'function') { + // JSON.stringify drops undefined/function/symbol members; the parts must match it. + const children = Object.entries(current).filter( + ([, child]) => + child !== undefined && typeof child !== 'function' && typeof child !== 'symbol' + ) + if (children.length > 0) { + for (const [key, child] of children) { + visit(child, [...path, key], remaining - 1) + } + return + } + } + const payload = JSON.stringify(current) + if (payload !== undefined) { + parts.push({ key: JSON.stringify(path), payload }) + } + } + visit(value, [], depth) + return parts +} + +/** Inverse of split: rebuild the document text from depth-first ordered parts. */ +export function assembleProfileStateDomainPayload( + parts: readonly ProfileStateDocumentPart[] +): string { + let out = '' + let open: string[] = [] + let first = true + for (const part of parts) { + const path = parsePartKey(part.key) + let common = 0 + while (common < open.length && common < path.length - 1 && open[common] === path[common]) { + common++ + } + for (let i = open.length; i > common; i--) { + out += '}' + } + open = open.slice(0, common) + if (!first) { + out += ',' + } + for (let i = common; i < path.length - 1; i++) { + out += `${JSON.stringify(path[i])}:{` + open.push(path[i]!) + } + if (path.length > 0) { + out += `${JSON.stringify(path.at(-1))}:` + } + out += part.payload + first = false + } + out += '}'.repeat(open.length) + if (parts.length === 0) { + return '{}' + } + return parts.length === 1 && parsePartKey(parts[0]!.key).length === 0 ? out : `{${out}}` +} + +function parsePartKey(key: string): string[] { + const path: unknown = JSON.parse(key) + if (!Array.isArray(path) || !path.every((segment) => typeof segment === 'string')) { + throw new Error('Profile state document part key is invalid') + } + return path +} + +export function hashProfileStatePart(payload: string): string { + return hashProfileStatePayload(payload) +} + +const partsTablesByDatabase = new WeakMap() + +/** Read-only and pre-split databases may not have the tables; treat them as unsplit. */ +export function hasProfileStateDocumentPartsTables(db: Database.Database): boolean { + const cached = partsTablesByDatabase.get(db) + if (cached !== undefined) { + return cached + } + const rows = db + .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?)`) + .all(PROFILE_STATE_DOCUMENT_PARTS_TABLE, PROFILE_STATE_DOCUMENT_PARTS_META_TABLE) + const present = rows.length === 2 + // Only cache presence: a writable open may create the tables after a negative probe. + if (present) { + partsTablesByDatabase.set(db, true) + } + return present +} + +export function ensureProfileStateDocumentPartsTables(db: Database.Database): void { + db.exec(createProfileStateDocumentPartsTablesSql()) + partsTablesByDatabase.set(db, true) +} diff --git a/src/main/persistence/profile-state/profile-state-document-reader.ts b/src/main/persistence/profile-state/profile-state-document-reader.ts index 221a89b3176..39580c19b56 100644 --- a/src/main/persistence/profile-state/profile-state-document-reader.ts +++ b/src/main/persistence/profile-state/profile-state-document-reader.ts @@ -4,9 +4,12 @@ import { assertProfileStateDocumentRevision, readProfileStateRevision } from './profile-state-revision' +import { + PROFILE_STATE_DOCUMENT_ROW_COLUMNS, + readProfileStateDocumentRow +} from './profile-state-document-parts-reader' import { ProfileStateDocumentCorruptionError, - validateProfileStateDocumentRow, type ProfileStateDocument, type ProfileStateParsedDocument, type ProfileStateValidatedDocument @@ -45,7 +48,7 @@ export function readProfileStateDocuments( : readProfileStateAutomationRunsDocument(db, profileRevision) const rows = db .prepare( - `SELECT domain, payload, domain_version, revision, updated_at, content_hash + `SELECT ${PROFILE_STATE_DOCUMENT_ROW_COLUMNS} FROM profile_state_documents ORDER BY rowid` ) .iterate() @@ -55,9 +58,7 @@ export function readProfileStateDocuments( | ProfileStateValidatedDocument )[] = [] for (const row of rows) { - const document = validateProfileStateDocumentRow(row, { - retainParsedValue: options.representation === 'parsed' - }) + const document = readProfileStateDocumentRow(db, row, options.representation === 'parsed') assertProfileStateDocumentRevision(document.revision, profileRevision, document.domain) if ( normalized !== undefined && diff --git a/src/main/persistence/profile-state/profile-state-documents.ts b/src/main/persistence/profile-state/profile-state-documents.ts index 79ab282cc28..ca0fa1fdc70 100644 --- a/src/main/persistence/profile-state/profile-state-documents.ts +++ b/src/main/persistence/profile-state/profile-state-documents.ts @@ -19,6 +19,7 @@ import { } from './profile-state-automation-runs' import { readProfileStateDocuments } from './profile-state-document-reader' +import { clearProfileStateDocumentParts } from './profile-state-document-parts-storage' import { readProfileStateRevision } from './profile-state-revision' import { readProfileStateJsonAcceptance } from './legacy-json/profile-state-json-acceptance' @@ -95,6 +96,8 @@ export function importProfileStateJson( } const revision = actualRevision + 1 clearProfileStateAutomationRuns(db) + // Imported rows are authoritative; the next write of a split domain re-splits it. + clearProfileStateDocumentParts(db) db.exec('DELETE FROM profile_state_documents') const automationRuns = entries.find((entry) => entry.domain === 'automationRuns') const normalizedRuns = diff --git a/src/main/persistence/profile-state/profile-state-domain-reader.ts b/src/main/persistence/profile-state/profile-state-domain-reader.ts index 8e87a6d5bfa..103813c213d 100644 --- a/src/main/persistence/profile-state/profile-state-domain-reader.ts +++ b/src/main/persistence/profile-state/profile-state-domain-reader.ts @@ -6,9 +6,10 @@ import { import { readProfileStateAutomationRunsDocument } from './profile-state-automation-runs' import { openProfileStateDatabaseReadOnly } from './profile-state-database' import { - validateProfileStateDocumentRow, - type ProfileStateParsedDocument -} from './profile-state-document-validation' + PROFILE_STATE_DOCUMENT_ROW_COLUMNS, + readProfileStateDocumentRow +} from './profile-state-document-parts-reader' +import type { ProfileStateParsedDocument } from './profile-state-document-validation' export type ProfileStateDomainReadResult = | { kind: 'value'; value: unknown } @@ -96,16 +97,14 @@ function readSelectedDocuments( const placeholders = domains.map(() => '?').join(',') const rows = db .prepare( - `SELECT domain, payload, domain_version, revision, updated_at, content_hash + `SELECT ${PROFILE_STATE_DOCUMENT_ROW_COLUMNS} FROM profile_state_documents WHERE domain IN (${placeholders}) ORDER BY rowid` ) .iterate(...domains) return Array.from(rows, (row) => { - const { payload: _payload, ...document } = validateProfileStateDocumentRow(row, { - retainParsedValue: true - }) + const { payload: _payload, ...document } = readProfileStateDocumentRow(db, row, true) return { ...document, value: document.value } }) } diff --git a/src/main/persistence/profile-state/profile-state-domain-write-validation.ts b/src/main/persistence/profile-state/profile-state-domain-write-validation.ts index e2216e14018..b899e477496 100644 --- a/src/main/persistence/profile-state/profile-state-domain-write-validation.ts +++ b/src/main/persistence/profile-state/profile-state-domain-write-validation.ts @@ -1,4 +1,5 @@ import { PROFILE_STATE_DOCUMENT_VERSION } from './profile-state-database-schema' +import { isProfileStateSplitDomain } from './profile-state-document-parts' import { hashProfileStateJson } from './profile-state-documents' import type { AutomationRunsWritePreparation } from './profile-state-automation-runs' import type { @@ -11,6 +12,8 @@ export type PreparedProfileStateMutation = ProfileStateDomainMutation & { payloadHash: string | null // Retain the checked history only for this write to avoid reparsing during normalization. automationRunsValue?: unknown + /** Parsed payload of a split domain, so storing its parts does not parse it again. */ + splitDomainValue?: unknown automationRuns?: AutomationRunsWritePreparation } @@ -58,7 +61,8 @@ export function prepareProfileStateDomainMutation( now: replacement.now, domainVersion: replacement.domainVersion ?? PROFILE_STATE_DOCUMENT_VERSION, payloadHash, - automationRunsValue: replacement.domain === 'automationRuns' ? parsed : undefined + automationRunsValue: replacement.domain === 'automationRuns' ? parsed : undefined, + splitDomainValue: isProfileStateSplitDomain(replacement.domain) ? parsed : undefined } } diff --git a/src/main/persistence/profile-state/profile-state-domain-writes.ts b/src/main/persistence/profile-state/profile-state-domain-writes.ts index bf0205f3681..44314d9ab3b 100644 --- a/src/main/persistence/profile-state/profile-state-domain-writes.ts +++ b/src/main/persistence/profile-state/profile-state-domain-writes.ts @@ -17,6 +17,12 @@ import { } from './profile-state-automation-runs' import { isRecord, validateProfileStateDocumentRow } from './profile-state-document-validation' import { assertProfileStateDocumentRevision } from './profile-state-revision' +import { + deleteProfileStateDomainParts, + readSplitDomainWriteState, + writeProfileStateDomainParts +} from './profile-state-document-parts-storage' +import { isProfileStateSplitDomain } from './profile-state-document-parts' import { prepareProfileStateDomainMutation, validateProfileStateDomainTransaction, @@ -90,7 +96,18 @@ export function writeProfileStateDomains( const currentAutomationRuns = readCurrentAutomationRunsState(db, actualRevision) const updates: PreparedProfileStateMutation[] = [] + const splitStates = new Map>() for (const mutation of prepared) { + const splitState = readSplitDomainWriteState(db, mutation.domain) + splitStates.set(mutation.domain, splitState) + if (splitState.kind === 'parts') { + // Compare by hash; the legacy row is a stale downgrade copy and is not re-read. + assertProfileStateDocumentRevision(splitState.revision, actualRevision, mutation.domain) + if (mutation.payload === null || mutation.payloadHash !== splitState.contentHash) { + updates.push(mutation) + } + continue + } const existing = db .prepare( `SELECT domain, payload, domain_version, revision, updated_at, content_hash @@ -172,11 +189,29 @@ export function writeProfileStateDomains( } if (mutation.payload === null) { db.prepare('DELETE FROM profile_state_documents WHERE domain = ?').run(mutation.domain) + deleteProfileStateDomainParts(db, mutation.domain) } else { const updatedAt = (mutation.now ?? Date.now)() if (!Number.isSafeInteger(updatedAt) || updatedAt < 0) { throw new Error(`Profile state domain update timestamp is invalid: ${mutation.domain}`) } + const splitState = splitStates.get(mutation.domain) + if ( + splitState?.kind === 'parts' && + writeProfileStateDomainParts(db, { + domain: mutation.domain, + payload: mutation.payload, + value: mutation.splitDomainValue, + payloadHash: mutation.payloadHash!, + domainVersion: mutation.domainVersion, + revision: nextRevision, + updatedAt, + legacyRevision: splitState.legacyRevision, + diffExisting: true + }) + ) { + continue + } db.prepare( `INSERT INTO profile_state_documents (domain, payload, domain_version, revision, updated_at, content_hash) @@ -195,6 +230,20 @@ export function writeProfileStateDomains( updatedAt, mutation.payloadHash ) + if (isProfileStateSplitDomain(mutation.domain)) { + // The legacy row now matches; later writes touch only the parts that change. + writeProfileStateDomainParts(db, { + domain: mutation.domain, + payload: mutation.payload, + value: mutation.splitDomainValue, + payloadHash: mutation.payloadHash!, + domainVersion: mutation.domainVersion, + revision: nextRevision, + updatedAt, + legacyRevision: nextRevision, + diffExisting: false + }) + } } } db.prepare( diff --git a/src/main/persistence/profile-state/profile-state-legacy-document-refresh.ts b/src/main/persistence/profile-state/profile-state-legacy-document-refresh.ts new file mode 100644 index 00000000000..fb58a751409 --- /dev/null +++ b/src/main/persistence/profile-state/profile-state-legacy-document-refresh.ts @@ -0,0 +1,137 @@ +import type Database from '../../sqlite/sync-database' +import { + hasProfileStateDocumentPartsTables, + PROFILE_STATE_DOCUMENT_PARTS_META_TABLE, + PROFILE_STATE_SPLIT_DOMAIN_DEPTHS +} from './profile-state-document-parts' +import { + authoritativeMeta, + readLegacyRevision, + readProfileStateSplitDocument +} from './profile-state-document-parts-storage' +import { withProfileStateWriteTransaction } from './profile-state-write-transaction' + +/** + * Older builds read the legacy rows. Starting the writer brings them current (covering an + * earlier crash); while it runs they lag the parts by at most this long, even when writes + * stop, which bounds what a downgrade straight after a crash can miss. Each refresh rewrites + * only stale rows. + */ +const LEGACY_DOCUMENT_REFRESH_INTERVAL_MS = 5 * 60 * 1000 + +type DatabaseSource = () => Database.Database | undefined + +export class ProfileStateLegacyDocumentRefresh { + private refreshedAt = Date.now() + private caughtUp = false + private timer: ReturnType | undefined + private scheduled = false + + /** + * The writer thread also refreshes on a timer through quiet periods; other authorities run + * on threads that must not block on a refresh, so they only refresh around their own writes. + */ + startWriterThread(db: Database.Database | undefined): void { + this.scheduled = true + this.catchUp(db) + } + + /** A crash skips the close-time refresh; catch older builds up once before writing on. */ + catchUp(db: Database.Database | undefined): void { + if (!this.caughtUp) { + this.caughtUp = true + this.refresh(db) + } + } + + beforeClose(db: Database.Database | undefined, graceful: boolean | undefined): void { + clearTimeout(this.timer) + this.timer = undefined + if (graceful) { + this.refresh(db) + } + } + + afterWrite(source: DatabaseSource): void { + const remaining = this.refreshedAt + LEGACY_DOCUMENT_REFRESH_INTERVAL_MS - Date.now() + if (remaining <= 0) { + this.refresh(source()) + } else if (this.scheduled && this.timer === undefined) { + this.timer = setTimeout(() => { + this.timer = undefined + this.refresh(source()) + }, remaining) + this.timer.unref?.() + } + } + + /** Best effort: a failed refresh rolls back, leaving older builds a staler copy, never a wrong one. */ + refresh(db: Database.Database | undefined): void { + // An open transaction means a write is unsettled; the next refresh will catch up. + if (!db || db.isTransaction) { + return + } + clearTimeout(this.timer) + this.timer = undefined + this.refreshedAt = Date.now() + try { + refreshStaleProfileStateLegacyDocuments(db) + } catch (error) { + console.warn('[profile-state] Failed to refresh legacy documents:', error) + } + } +} + +/** Throws on failure; the transaction leaves legacy rows as they were. */ +export function refreshStaleProfileStateLegacyDocuments(db: Database.Database): void { + // Most checks find nothing stale; skip the write transaction entirely then. + if (staleLegacyDomains(db).length > 0) { + withProfileStateWriteTransaction(db, () => refreshProfileStateLegacyDocuments(db)) + } +} + +function staleLegacyDomains(db: Database.Database): { domain: string; legacyRevision: number }[] { + if (!hasProfileStateDocumentPartsTables(db)) { + return [] + } + const stale: { domain: string; legacyRevision: number }[] = [] + for (const domain of PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.keys()) { + const legacyRevision = readLegacyRevision(db, domain) + if (legacyRevision === null) { + continue + } + const meta = authoritativeMeta(db, domain, legacyRevision) + if (meta && meta.revision !== legacyRevision) { + stale.push({ domain, legacyRevision }) + } + } + return stale +} + +/** + * Bring stale legacy rows up to date so an older build (or a downgrade) reads current + * state. The profile revision does not move: the logical content is unchanged. + */ +function refreshProfileStateLegacyDocuments(db: Database.Database): void { + for (const { domain, legacyRevision } of staleLegacyDomains(db)) { + const document = readProfileStateSplitDocument(db, domain, legacyRevision) + if (!document) { + continue + } + db.prepare( + `UPDATE profile_state_documents + SET payload = ?, domain_version = ?, revision = ?, updated_at = ?, content_hash = ? + WHERE domain = ?` + ).run( + document.payload, + document.domainVersion, + document.revision, + document.updatedAt, + document.contentHash, + domain + ) + db.prepare( + `UPDATE ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE} SET legacy_revision = ? WHERE domain = ?` + ).run(document.revision, domain) + } +} diff --git a/src/main/persistence/profile-state/profile-state-revision.ts b/src/main/persistence/profile-state/profile-state-revision.ts index ec4dd57454d..44c49af54b5 100644 --- a/src/main/persistence/profile-state/profile-state-revision.ts +++ b/src/main/persistence/profile-state/profile-state-revision.ts @@ -5,6 +5,10 @@ import { PROFILE_STATE_AUTOMATION_RUNS_TABLE } from './profile-state-automation-runs-model' import { isRecord, ProfileStateDocumentCorruptionError } from './profile-state-document-validation' +import { + hasProfileStateDocumentPartsTables, + PROFILE_STATE_DOCUMENT_PARTS_META_TABLE +} from './profile-state-document-parts' export function readProfileStateRevision(db: Database.Database): number { const row = db @@ -27,7 +31,12 @@ export function assertProfileStateRepairRevision(db: Database.Database, revision `SELECT 1 FROM ( SELECT revision FROM profile_state_documents UNION ALL SELECT revision FROM ${PROFILE_STATE_AUTOMATION_RUNS_TABLE} - UNION ALL SELECT revision FROM ${PROFILE_STATE_AUTOMATION_RUNS_META_TABLE} + UNION ALL SELECT revision FROM ${PROFILE_STATE_AUTOMATION_RUNS_META_TABLE}${ + hasProfileStateDocumentPartsTables(db) + ? ` + UNION ALL SELECT revision FROM ${PROFILE_STATE_DOCUMENT_PARTS_META_TABLE}` + : '' + } ) WHERE typeof(revision) IN ('integer', 'real') AND revision BETWEEN 1 AND ? AND revision = CAST(revision AS INTEGER) AND revision > ? LIMIT 1` diff --git a/src/main/persistence/profile-state/profile-state-section-repair.ts b/src/main/persistence/profile-state/profile-state-section-repair.ts index 71669a608fe..344f1c78baa 100644 --- a/src/main/persistence/profile-state/profile-state-section-repair.ts +++ b/src/main/persistence/profile-state/profile-state-section-repair.ts @@ -1,4 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' +import { readProfileStateSplitDocumentForRow } from './profile-state-document-parts-reader' import type Database from '../../sqlite/sync-database' import { ProfileStateRecoveryCommandError, @@ -237,7 +238,9 @@ function scanProfileStateSections(db: Database.Database): SectionScan | undefine const domain = isRecord(row) && typeof row.domain === 'string' ? row.domain : undefined let document: ReturnType try { - document = validateProfileStateDocumentRow(row, { retainParsedValue: true }) + document = + readProfileStateSplitDocumentForRow(db, row, true) ?? + validateProfileStateDocumentRow(row, { retainParsedValue: true }) } catch (error) { if (!(error instanceof ProfileStateDocumentCorruptionError) || domain === undefined) { throw error diff --git a/src/main/persistence/profile-state/profile-state-sqlite-authority.ts b/src/main/persistence/profile-state/profile-state-sqlite-authority.ts index 7aef0e7e026..bd15fa2545a 100644 --- a/src/main/persistence/profile-state/profile-state-sqlite-authority.ts +++ b/src/main/persistence/profile-state/profile-state-sqlite-authority.ts @@ -35,6 +35,7 @@ import { buildCompleteDocumentReplacements } from './profile-state-complete-repl import { ProfileStateBackupRotation } from './profile-state-backup-rotation' import { ensureProfileStateAuthorityMarker } from './profile-state-authority-marker' import type { ProfileStateWriterInitialization } from './profile-state-writer-protocol' +import { ProfileStateLegacyDocumentRefresh } from './profile-state-legacy-document-refresh' /** Reuse one writable handle; fenced domain commits preserve unchanged normalized rows. */ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { @@ -42,6 +43,7 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { private observedRevision: number | undefined private writableDatabase: ReturnType | undefined private backupRotation: ProfileStateBackupRotation | undefined + private readonly legacyDocuments = new ProfileStateLegacyDocumentRefresh() constructor( private readonly databasePath: string, @@ -71,6 +73,7 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { assertProfileStateRevisionOnDisk(this.databasePath, this.profileId, revision) this.observedRevision = revision this.assertCurrentRevision() + this.legacyDocuments.startWriterThread(this.writableDatabase?.db) } get revision(): number { @@ -148,11 +151,13 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { this.readSerializedState() } const opened = this.openWritableDatabase() + this.legacyDocuments.catchUp(this.writableDatabase?.db) this.observedRevision = writeProfileStateDomains(opened.db, { expectedRevision: this.observedRevision ?? 0, replacements, automationRunsAfter }).revision + this.legacyDocuments.afterWrite(() => this.writableDatabase?.db) } assertCurrentRevision(): void { @@ -199,6 +204,7 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { }) } const opened = this.openWritableDatabase() + this.legacyDocuments.catchUp(this.writableDatabase?.db) const currentRevision = readProfileStateRevision(opened.db) const complete = buildCompleteDocumentReplacements(opened.db, replacements) if (currentRevision === 0 || complete.length === 0) { @@ -219,6 +225,7 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { expectedRevision: this.observedRevision ?? currentRevision, replacements: complete }).revision + this.legacyDocuments.afterWrite(() => this.writableDatabase?.db) } scheduleBackup(): void { @@ -247,9 +254,11 @@ export class ProfileStateSqliteAuthority implements ProfileStateAuthority { return quarantineProfileStateDatabase(this.databasePath, this.profileId, quarantineRoot, reason) } - close(): void { + /** Only a graceful shutdown refreshes legacy rows; quarantine and maintenance closes must not write. */ + close(options: { refreshLegacyDocuments?: boolean } = {}): void { this.assertActive() this.backupRotation?.stop() + this.legacyDocuments.beforeClose(this.writableDatabase?.db, options.refreshLegacyDocuments) this.writableDatabase?.db.close() this.writableDatabase = undefined } diff --git a/src/main/persistence/profile-state/profile-state-worker-authority.test.ts b/src/main/persistence/profile-state/profile-state-worker-authority.test.ts index 60f3b09c580..c449dc4dfd7 100644 --- a/src/main/persistence/profile-state/profile-state-worker-authority.test.ts +++ b/src/main/persistence/profile-state/profile-state-worker-authority.test.ts @@ -2,6 +2,8 @@ import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { ProfileStateBackupRotation } from './profile-state-backup-rotation' import { ProfileStateWriteWorkerClient } from './profile-state-writer-worker-client' +import { openProfileStateDatabaseReadOnly } from './profile-state-database' +import { isRecord } from './profile-state-document-validation' import { createWorkerMaintenanceFixture, maintenanceBarrier @@ -17,6 +19,37 @@ vi.mock('../../ssh/config/ssh-config-parser', () => ({ })) describe('worker authority close admission', () => { + it('leaves the older-build copy alone for maintenance and brings it current on close', async () => { + const { authority, databaseFile, profileId } = await createWorkerMaintenanceFixture() + const v1 = '{"runtime:a":{"activeTabId":"t1"}}' + const v2 = '{"runtime:a":{"activeTabId":"t2"}}' + const v3 = '{"runtime:a":{"activeTabId":"t3"}}' + // What a build without per-entry storage reads. + const readAsOlderBuild = () => { + const { db } = openProfileStateDatabaseReadOnly(databaseFile, profileId) + try { + const row: unknown = db + .prepare(`SELECT payload FROM profile_state_documents WHERE domain = ?`) + .get('workspaceSessionsByHostId') + return isRecord(row) ? row.payload : undefined + } finally { + db.close() + } + } + await authority.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v1 }]) + // Restarting the writer catches the older-build copy up to v1. + await (await authority.pauseForMaintenance()).resume() + await authority.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v2 }]) + + const maintenance = await authority.pauseForMaintenance() + expect(readAsOlderBuild()).toBe(v1) + await maintenance.resume() + await authority.writeSerializedDomains([{ domain: 'workspaceSessionsByHostId', payload: v3 }]) + + await authority.close() + expect(readAsOlderBuild()).toBe(v3) + }) + it('reports a failed maintenance resume without accepting a changed database', async () => { const notify = vi.fn() const { authority, peer } = await createWorkerMaintenanceFixture(undefined, notify) diff --git a/src/main/persistence/profile-state/profile-state-worker-authority.ts b/src/main/persistence/profile-state/profile-state-worker-authority.ts index 12f561fe621..49ba60ce74a 100644 --- a/src/main/persistence/profile-state/profile-state-worker-authority.ts +++ b/src/main/persistence/profile-state/profile-state-worker-authority.ts @@ -133,16 +133,17 @@ export class ProfileStateWorkerAuthority implements AsyncProfileStateAuthority { return this.backups.drain() } - close(): Promise { + /** By default a graceful shutdown, which also brings the downgrade copy current. */ + close(options: { refreshLegacyDocuments?: boolean } = {}): Promise { this.cancelIdleStop() this.writer?.stopAdmission() - this.closing ??= this.finishClose() + this.closing ??= this.finishClose(options.refreshLegacyDocuments !== false) return this.closing } async pauseForMaintenance(): Promise { this.assertWritable() - await this.close() + await this.close({ refreshLegacyDocuments: false }) const writer = this.writer const revision = writer ? writer.acknowledgedRevision : this.requireStoppedRevision() let consumed = false @@ -163,7 +164,7 @@ export class ProfileStateWorkerAuthority implements AsyncProfileStateAuthority { await this.writer.ready this.assertWritable() } catch (error) { - await this.close() + await this.close({ refreshLegacyDocuments: false }) throw error } } @@ -171,7 +172,7 @@ export class ProfileStateWorkerAuthority implements AsyncProfileStateAuthority { } async quarantineDatabase(quarantineRoot?: string, reason?: string) { - await this.close() + await this.close({ refreshLegacyDocuments: false }) return quarantineProfileStateDatabase( this.initialization.databasePath, this.initialization.profileId, @@ -180,12 +181,12 @@ export class ProfileStateWorkerAuthority implements AsyncProfileStateAuthority { ) } - private async finishClose(): Promise { + private async finishClose(refreshLegacyDocuments: boolean): Promise { this.backups.stop() // A stop already under way owns the writer; let it finish before deciding what is left to close. const writerClosed = this.stopping - ? this.stopping.then(() => this.writer?.close()) - : this.writer?.close() + ? this.stopping.then(() => this.writer?.close({ refreshLegacyDocuments })) + : this.writer?.close({ refreshLegacyDocuments }) const settled = await Promise.allSettled([this.backups.drain(), writerClosed]) for (const result of settled) { if (result.status === 'rejected') { @@ -309,7 +310,7 @@ export class ProfileStateWorkerAuthority implements AsyncProfileStateAuthority { return } this.stopping = writer - .close() + .close({ refreshLegacyDocuments: true }) .then(() => { if (this.writer === writer) { this.writer = null diff --git a/src/main/persistence/profile-state/profile-state-writer-connection.ts b/src/main/persistence/profile-state/profile-state-writer-connection.ts index b9a7214ae4e..d13f50dacdd 100644 --- a/src/main/persistence/profile-state/profile-state-writer-connection.ts +++ b/src/main/persistence/profile-state/profile-state-writer-connection.ts @@ -93,9 +93,9 @@ export class ProfileStateWriterConnection { this.draining = true } - close(): Promise { + close(options: { refreshLegacyDocuments?: boolean } = {}): Promise { this.stopAdmission() - this.closePromise ??= this.finishClose() + this.closePromise ??= this.finishClose(options.refreshLegacyDocuments === true) return this.closePromise } @@ -118,12 +118,12 @@ export class ProfileStateWriterConnection { return this.thread?.exited ?? true } - private async finishClose(): Promise { + private async finishClose(refreshLegacyDocuments: boolean): Promise { await this.active?.promise.catch(() => {}) if (!this.failure && !this.didExit) { const closeRequestId = this.nextId try { - await this.dispatch({ command: 'close' }) + await this.dispatch({ command: 'close', refreshLegacyDocuments }) } finally { // Ownership requires observed exit, not timeout or termination request. await this.awaitExit(closeRequestId) diff --git a/src/main/persistence/profile-state/profile-state-writer-protocol.ts b/src/main/persistence/profile-state/profile-state-writer-protocol.ts index 28e6f8a6a4d..fc6dd1f262d 100644 --- a/src/main/persistence/profile-state/profile-state-writer-protocol.ts +++ b/src/main/persistence/profile-state/profile-state-writer-protocol.ts @@ -18,7 +18,9 @@ export type ProfileStateWriterCommand = replacements: readonly ProfileStateDomainReplacement[] runPayloads: readonly string[] } - | { command: 'assert-revision' | 'close' } + | { command: 'assert-revision' } + /** Only a graceful shutdown refreshes the downgrade copy; maintenance and quarantine must not write. */ + | { command: 'close'; refreshLegacyDocuments?: boolean } | { command: 'export-json' | 'export-latest'; targetPath: string } export type ProfileStateWriterRequest = ProfileStateWriterCommand & { id: number } @@ -71,8 +73,12 @@ export function isProfileStateWriterRequest(value: unknown): value is ProfileSta case 'write-state': return value.payload instanceof Uint8Array case 'assert-revision': - case 'close': return true + case 'close': + return ( + value.refreshLegacyDocuments === undefined || + typeof value.refreshLegacyDocuments === 'boolean' + ) case 'export-json': case 'export-latest': return typeof value.targetPath === 'string' && value.targetPath.length > 0 diff --git a/src/main/persistence/profile-state/profile-state-writer-worker-entry.ts b/src/main/persistence/profile-state/profile-state-writer-worker-entry.ts index 1ec8f826549..b037ad87952 100644 --- a/src/main/persistence/profile-state/profile-state-writer-worker-entry.ts +++ b/src/main/persistence/profile-state/profile-state-writer-worker-entry.ts @@ -71,7 +71,7 @@ async function execute(request: ProfileStateWriterRequest): Promise ({ registerPaneKeyAliasMock: vi.fn() })) -vi.mock('../../agent-hooks/server', () => ({ +vi.mock('../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { registerPaneKeyAlias: registerPaneKeyAliasMock } diff --git a/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts b/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts index 74dee65d128..211ad36c315 100644 --- a/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts +++ b/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts @@ -2,7 +2,7 @@ import type { LegacyPaneKeyAliasEntry, PersistedState } from '../../../shared/pe import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { MigrationUnsupportedPtyEntry } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { LOCAL_EXECUTION_HOST_ID, toSshExecutionHostId, diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts b/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts index 9f85ce204c2..d56ff5ea2d6 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts +++ b/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { repairDuplicatePtyPanesOnStart } from '../../runtime/terminal/identity/moved-pane-owner-rekey' import { getDefaultWorkspaceSession } from '../../../shared/constants' diff --git a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts index b97c7b6cf11..5d7ad4d96be 100644 --- a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts +++ b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts @@ -3,11 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { clearMigrationUnsupportedPty, setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/migration-unsupported-pty-state' +} from '../../agent-hooks/observations/migration-unsupported-pty-state' import { StateSerializationSecretHandlingOperations } from '../loading-store/state-serialization-secret-handling' import { openProfileStateDatabaseReadOnly } from '../profile-state/profile-state-database' import { profileStateDatabaseFile } from '../../../shared/profile-state-storage-paths' diff --git a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts b/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts index 60230392d15..5e53a8e125a 100644 --- a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts +++ b/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts @@ -10,7 +10,7 @@ import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -87,7 +87,7 @@ describe('Store', () => { }) await createStore() - const { agentHookServer } = await import('../../agent-hooks/server') + const { agentHookServer } = await import('../../agent-hooks/server/agent-hook-server') agentHookServer.ingestTerminalStatus({ paneKey: physicalPaneKey, tabId: 'tab-source', diff --git a/src/main/persistence/workspace-session-domains.ts b/src/main/persistence/workspace-session-domains.ts new file mode 100644 index 00000000000..3c27e0a0754 --- /dev/null +++ b/src/main/persistence/workspace-session-domains.ts @@ -0,0 +1,2 @@ +/** Profile-state domains that hold saved workspace sessions (local and per host). */ +export const WORKSPACE_SESSION_DOMAINS = ['workspaceSession', 'workspaceSessionsByHostId'] as const diff --git a/src/main/plugins/hooks/plugin-hook-participants.ts b/src/main/plugins/hooks/plugin-hook-participants.ts index d54a186fdd5..de4c50a6981 100644 --- a/src/main/plugins/hooks/plugin-hook-participants.ts +++ b/src/main/plugins/hooks/plugin-hook-participants.ts @@ -8,7 +8,7 @@ import { } from '../../../shared/plugins/workers/plugin-hook-chain' import { setPluginHookRunner, type PluginHookRunner } from './plugin-hook-dispatch' import type { PluginService } from '../plugin-service' -import { setAgentToolHookTerminalResolver } from '../../agent-hooks/agent-tool-call-reader' +import { setAgentToolHookTerminalResolver } from '../../agent-hooks/tool-events/agent-tool-call-reader' import type { PluginWorkerHandle } from '../workers/plugin-host-process' import { PLUGIN_WORKER_READY_TIMEOUT_MS } from '../../../shared/plugins/workers/plugin-host-protocol' import { pluginApprovedRevision } from '../workers/plugin-resident-worker' diff --git a/src/main/plugins/panels/plugin-frame-guest-policies.ts b/src/main/plugins/panels/plugin-frame-guest-policies.ts index 619bccf6ffc..3cc5a8465e6 100644 --- a/src/main/plugins/panels/plugin-frame-guest-policies.ts +++ b/src/main/plugins/panels/plugin-frame-guest-policies.ts @@ -1,7 +1,7 @@ import { BrowserWindow, Menu, webContents as electronWebContents } from 'electron' import type { Session, WebContents } from 'electron' import type { KeybindingOverrides } from '../../../shared/keybindings' -import { setupGuestShortcutForwarding } from '../../browser/guest-lifecycle/input/browser-guest-shortcut-forwarding' +import { setupGuestShortcutForwarding } from '../../browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-forwarding' import { buildEditableContextMenuTemplate } from '../../window/editable-context-menu' import { isAllowedPluginFrameNavigation } from './plugin-frame-request-policy' diff --git a/src/main/qoder/real-cli.test.ts b/src/main/qoder/real-cli.test.ts index f605e5e1ac4..15f0af89e5a 100644 --- a/src/main/qoder/real-cli.test.ts +++ b/src/main/qoder/real-cli.test.ts @@ -26,7 +26,7 @@ vi.mock('node:os', async (importOriginal) => { vi.mock('electron', () => ({ app: { getPath: () => sandbox.home } })) import { qoderHookService } from './hook-service' import { markQoderWorkspaceTrusted } from './workspace-trust' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' it.skipIf(process.env.ORCA_REAL_QODER_CLI_TEST !== '1')( 'generates and resumes a real task through managed hooks', diff --git a/src/main/qoder/workspace-trust.ts b/src/main/qoder/workspace-trust.ts index d452eb87dc0..d27233e2dd3 100644 --- a/src/main/qoder/workspace-trust.ts +++ b/src/main/qoder/workspace-trust.ts @@ -1,6 +1,10 @@ import { realpathSync } from 'node:fs' import { join } from 'node:path' -import { isPlainObject, readHooksJson, writeHooksJson } from '../agent-hooks/installer-utils' +import { + isPlainObject, + readHooksJson +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' // Qoder 1.1.64 writes this exact shape after accepting its folder-trust prompt. export function withQoderTrustedWorkspace( diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.meta.json b/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.meta.json new file mode 100644 index 00000000000..5105234ddc1 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-11-08T19:48:25.862Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy 1.4.11, macOS, Google account, AGY_CLI_HIDE_ACCOUNT_INFO=1; one background task running, a second turn mid-way through a foreground command", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.txt b/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.txt new file mode 100644 index 00000000000..f597c1b7b8d --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-busy-with-background-task.txt @@ -0,0 +1,591 @@ +[>q[?2026$p[?2027$p]7501;?]11;?[>4m[?1049h[?25l[?5W[?2004h[>4;2m[>5u[?u +▄▀▀▄ +▀▀▀▀▀▀ +▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome back! You are currently not signed in. + + ⣷ Signing in...[>4m[<1u[?1049l[>4;2m[>5u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.5.3 +▀▀▀▀▀▀ ~/orca-lanes/pr37732/agyws +▀▀▀▀▀▀▀▀ +▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts [?25h[?25l Gemini 3.8 Flash (Low) +~/orca-lanes/pr37732/agyws + + + + + + +Gemini 3.8 Flash · low [?25h[?25l M + ┃ Meet Gemini 4 Argon + ┃ Google’s most capable frontier model is now available in Antigravity. Built for complex, multi-step agentic + ┃ workflows, and deep reasoning. If it's not currently available to you, please reach out to your administrator to + ┃ enable it. + ┃ Learn more: https://docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools-settings#configure-model- + ┃ availability + ┃ esc to dismiss +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25lS[?25h[?25ltart the shell command "sleep 3 + + G[?25h[?25l03" as a background task, do not wai[?25h[?25lt for it, and end your turn with the[?25h[?25l word + Started. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Gemini 3.8 Flash · low [?25h[?25l + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25l M──────────────────────────────────────────────────────────── +> Start the shell command "sleep 303" as a background task, do not wait for it, and end your turn with the word + Started. +⣷ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣯ + +[?25h[?25l ⣟ Gene + +[?25h[?25l ⡿ Generatin + +[?25h[?25l ⢿ Generating... + +[?25h[?25l ⣻ Generating... + +[?25h[?25l ⣽ + +[?25h[?25l ⣾ Genera + +[?25h[?25l ⣷ Generating. + +[?25h[?25l ⣯ Generating... + +[?25h[?25l ⣟ Generating... + +[?25h[?25l ⡿ G + +[?25h[?25l ⢿ Genera + +[?25h[?25l ⣻ Generating. + +[?25h[?25l ⣽ Generating... + +[?25h[?25l.. +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣾ + + +[?25h[?25l ⣷ Ge + + +[?25h[?25l  +○ Running (sleep 303) (ctrl+o to expand) +⣷ Running command... +└ Tip: Use /settings to configure your environment. + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25lunn + + +[?25h[?25l ⣯ + + +[?25h[?25l Runnin + + +[?25h[?25lunning  + + +[?25h[?25l ⣟ + + +[?25h[?25l ● +ning com + + +[?25h[?25lg comma + + +[?25h[?25l ⡿ + + +[?25h[?25lcommand. + + +[?25h[?25lmand... + + +[?25h[?25l ⢿ + + +[?25h[?25l nd.. + + +[?25h[?25l ⣻ Running command... + + +[?25h[?25l ○ +⣽ + + + + + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⣾ Runn + + +[?25h[?25l ⣷ Running c + + +[?25h[?25l ⣯ Running command + + +[?25h[?25l ⣟ Running command... + + +[?25h[?25l ⡿ Running command... + + +[?25h[?25l ⢿ R + + +[?25h[?25l ⣻ Runnin + + +[?25h[?25l ⣽ Running com + + +[?25h[?25l ⣾ Running command + + +[?25h[?25l ⣷ Running command... + + +[?25h[?25l ⣯ Running command... + + +[?25h[?25l ⣟ Ru + + +[?25h[?25l ⡿ Running + + +[?25h[?25l ⢿ Running comm + + +[?25h[?25l  + Started. +⢿ Running command... +└ Tip: Use /settings to configure your environment. + +> + + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⣻ Running command.. + + +[?25h[?25land... + + +[?25h[?25l ⣽ Running command.. + + +[?25h[?25l ⣾ Running command... + + +[?25h[?25l + + + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25lR[?25h[?25lun the shell command "sleep 40" + + + + G[?25h[?25l in the foreground and wait for it.[?25h[?25l + + + +? for shortcuts[?25h[?25lM +> Run the shell command "sleep 40" in the foreground and wait for it. +⣾ Loading... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⣷ Loading... + +[?25h[?25l ⣯ Loading... + +[?25h[?25l ⣟ + +[?25h[?25l ⡿ Load + +[?25h[?25l ⢿ Loading.. + +[?25h[?25l ⣻ Loading... + +[?25h[?25l ⣽ Loading... + +[?25h[?25l ⣾ Loa + +[?25h[?25l ⣷ Loading. + +[?25h[?25l ⣯ Loading... + +[?25h[?25l ⣟ Loading... + +[?25h[?25l ⡿ Lo + +[?25h[?25l ⢿ Loading + +[?25h[?25l ⣻ Loading... + +[?25h[?25l ⣽ Loading... + +[?25h[?25l ⣾ L + +[?25h[?25l Loadin + +[?25h[?25l ⣷ + +[?25h[?25l ⣯ Loading... + +[?25h[?25l  +○ Running (sleep 40) (ctrl+o to expand) +⣯ Running command... + +> + + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25land... + +[?25h[?25l ⣟ Running command. + +[?25h[?25l ● +.. + +[?25h[?25l. + +[?25h[?25l ⡿ + +[?25h[?25l Ru + +[?25h[?25l ⢿ Ru + +[?25h[?25lnn + +[?25h[?25l Runnin + +[?25h[?25l ⣻ + +[?25h[?25l ○ +unning  + +[?25h[?25l ⣽ Running com + +[?25h[?25l ⣾ Running command. + +[?25h[?25l ⣷ Running command... + +[?25h[?25l ⣯ Running command... + +[?25h[?25l ⣟ Ru + +[?25h[?25l ⡿ Running  + +[?25h[?25l ⢿ Running comma + +[?25h[?25l ⣻ Running command... + +[?25h[?25l ⣽ Running command... + +[?25h[?25l ⣾ + +[?25h[?25l ⣷ Runn + +[?25h[?25l ⣯ Running c + +[?25h[?25l ⣟ Running comman + +[?25h[?25l ⡿ Running command... + +[?25h[?25l ⢿ Running command... + +[?25h[?25l ⣻ + +[?25h[?25l ⣽ Runni + +[?25h[?25l ⣾ Running co + +[?25h[?25l ⣷ Running command + +[?25h[?25l ⣯ Running command... + +[?25h[?25l ⣟ Running command... + +[?25h[?25l ⡿ R + +[?25h[?25l ⢿ Runnin + +[?25h[?25l ⣻ Running com + +[?25h[?25l ⣽ Running command. + +[?25h[?25l ⣾ Running command... + +[?25h[?25l ⣷ Running command... + +[?25h[?25l ⣯ Ru + +[?25h[?25l ⣟ Running + +[?25h[?25l ⡿ Running comm + +[?25h[?25l ⢿ Running command.. + +[?25h[?25l ⣻ Running command... + +[?25h[?25l ⣽ Running command... + +[?25h[?25l ⣾ Run + +[?25h[?25l ⣷ Running  + +[?25h[?25l ⣯ Running comma + +[?25h[?25l ⣟ Running command... + +[?25h[?25l ⡿ Running command... + +[?25h[?25l ⢿ + +[?25h[?25l ⣻ Runn + +[?25h[?25l ⣽ Running c + +[?25h[?25l ⣾ Running comman + +[?25h[?25l ⣷ Running command... + +[?25h[?25l ⣯ Running command... + +[?25h[?25l ⣟ + +[?25h[?25l ⡿ Runni + +[?25h[?25l ⢿ Running co + +[?25h[?25l ⣻ Running command + +[?25h[?25l ⣽ Running command... + +[?25h[?25l ⣾ Running command... + +[?25h[?25l ⣷ R + +[?25h[?25l ⣯ Runnin + +[?25h[?25l ⣟ Running com + +[?25h[?25l ⡿ Running command. + +[?25h[?25l ⢿ Running command... + +[?25h[?25l ⣻ Running command... + +[?25h[?25l ⣽ Ru + +[?25h[?25l ⣾ Running + +[?25h[?25l ⣷ Running comm + +[?25h[?25l ⣯ Running command.. + +[?25h[?25l ⣟ Running command... + +[?25h[?25l ⡿ Running command... + +[?25h[?25l ⢿ Run + +[?25h[?25l ⣻ Running  + +[?25h[?25l ⣽ Running comma + +[?25h[?25l ⣾ Running command... + +[?25h[?25l ⣷ Running command... + +[?25h[?25l ⣯ + +[?25h[?25l ⣟ Runn + +[?25h[?25l ⡿ Running c + +[?25h[?25l ⢿ Running comman + +[?25h[?25l ⣻ Running command... + +[?25h[?25l ⣽ Running command... + +[?25h[?25l ⣾ + +[?25h[?25l ⣷ Runni + +[?25h[?25l ⣯ Running co + +[?25h[?25l ⣟ Running command + +[?25h[?25l ⡿ Running command... + +[?25h[?25l ⢿ Running command... + +[?25h[?25l ⣻ R + +[?25h[?25l ⣽ Runnin + +[?25h[?25l ⣾ Running com + +[?25h[?25l ⣷ Running command. + +[?25h[?25l ⣯ Running command... + +[?25h[?25l ⣟ Running command... + +[?25h[?25l ⡿ Ru + +[?25h[?25l ⢿ Running + +[?25h[?25l ⣻ Running comm + +[?25h[?25l ⣽ Running command.. + +[?25h[?25l ⣾ Running command... + +[?25h[?25l ⣷ Running command... + +[?25h[?25l ⣯ Run + +[?25h[?25l ⣟ Running  + +[?25h[?25l ⡿ Running comma + +[?25h[?25l ⢿ Running command... + +[?25h[?25l ⣻ Running command... + +[?25h[?25l ⣽ +└ Tip: Use /context to see what files are in the conversation. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:48:13] sleep 40 running + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 2 task(s) · /tasks [?25h[?25l ⣾ Runn + + +[?25h[?25l ⣷ Running c + + +[?25h[?25l ⣯ Running comman + + +[?25h[?25l ⣟ Running command... + + +[?25h[?25l ⡿ Running command... + + +[?25h[?25l ⢿ + + +[?25h[?25l ⣻ Runni + + +[?25h[?25l ⣽ Running co + + +[?25h[?25l ⣾ Running command + + +[?25h[?25l ⣷ Running command... + + +[?25h[?25l ⣯ Running command... + + +[?25h[?25l ⣟ R + + +[?25h[?25l ⡿ Runnin + + +[?25h[?25l ⢿ Running com + + +[?25h[?25l ⣻ Running command. + + +[?25h[?25l  + The command +⣻ Running command... +└ Tip: Use /context to see what files are in the conversation. + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:48:13] sleep 40 running + ● [14:47:49] sleep 303 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 2 task(s) · /tasks [?25h[?25l ⣽ Running command... + + +[?25h[?25lsleep 40 +.. + + +[?25h[?25lhas been started (task ID: 8a42e + + + +[?25h[?25l ⣾ + + +[?25h[?25l0ec-4f52-4e1a-8d02-cdbfc + + + +[?25h[?25l0f46 + + + +[?25h[?25l ⣷ Ru + + +[?25h[?25l ⣯ Running + + +[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.meta.json b/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.meta.json new file mode 100644 index 00000000000..2a2802e9bb2 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-11-08T19:48:21.856Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy 1.4.11, macOS, Google account, AGY_CLI_HIDE_ACCOUNT_INFO=1; one background task running, an unsent draft in the composer", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.txt b/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.txt new file mode 100644 index 00000000000..bb564831339 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-draft-with-background-task.txt @@ -0,0 +1,244 @@ +[>q[?2026$p[?2027$p]11;?]7501;?[>4m[?1049h[?25l[?5W[?2004h[>4;2m[>5u[?u +▄▀▀▄ +▀▀▀▀▀▀ +▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome back! You are currently not signed in. + + ⣷ Signing in...[>4m[<1u[?1049l[>4;2m[>5u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.5.3 +▀▀▀▀▀▀ ~/orca-lanes/pr37732/agyws +▀▀▀▀▀▀▀▀ +▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts [?25h[?25l Gemini 3.8 Flash (Low) +~/orca-lanes/pr37732/agyws + + + + + + +Gemini 3.8 Flash · low [?25h[?25l M + ┃ Meet Gemini 4 Argon + ┃ Google’s most capable frontier model is now available in Antigravity. Built for complex, multi-step agentic + ┃ workflows, and deep reasoning. If it's not currently available to you, please reach out to your administrator to + ┃ enable it. + ┃ Learn more: https://docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools-settings#configure-model- + ┃ availability + ┃ esc to dismiss +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25lS[?25h[?25ltart the shell command "sleep 304" + + G[?25h[?25l as a background task, do not wait f[?25h[?25lor it, and end your turn with the wo[?25h[?25lrd + Started. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Gemini 3.8 Flash · low [?25h[?25l + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25l M──────────────────────────────────────────────────────────── +> Start the shell command "sleep 304" as a background task, do not wait for it, and end your turn with the word + Started. +⣷ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣯ + +[?25h[?25l ⣟ Gene + +[?25h[?25l ⡿ Generatin + +[?25h[?25l ⢿ Generating... + +[?25h[?25l ⣻ Generating... + +[?25h[?25l ⣽ G + +[?25h[?25l ⣾ Genera + +[?25h[?25l ⣷ Generating. + +[?25h[?25l ⣯ Generating... + +[?25h[?25l ⣟ Generating... + +[?25h[?25l ⡿ G + +[?25h[?25l ⢿ Genera + +[?25h[?25l ⣻ Generating.. + +[?25h[?25l ⣽ Generating... + +[?25h[?25l. +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣾ + + +[?25h[?25l  +○ Running (sleep 304) (ctrl+o to expand) +⣾ Running command... +└ Tip: Use /settings to configure your environment. + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣷ + + +[?25h[?25l Ru + + +[?25h[?25lun + + +[?25h[?25l ⣯ Runn + + +[?25h[?25l Running + + +[?25h[?25l ⣟ Running c + + +[?25h[?25l ● +ing comm + + +[?25h[?25l ⡿ Running comman + + +[?25h[?25lommand.. + + +[?25h[?25l ⢿ Running command... + + +[?25h[?25l nd + + +[?25h[?25l ⣻ Running command... + + +[?25h[?25l ○ + + + +[?25h[?25l + + ● [14:47:49] sleep 304 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⣽ + + +[?25h[?25l ⣾ Runni + + +[?25h[?25l ⣷ Running co + + +[?25h[?25l ⣯ Running command + + +[?25h[?25l ⣟ Running command... + + +[?25h[?25l ⡿ Running command... + + +[?25h[?25l ⢿ R + + +[?25h[?25l ⣻ Runnin + + +[?25h[?25l ⣽ Running co + + +[?25h[?25l ng com + + +[?25h[?25l ⣾ Running command + + +[?25h[?25l ⣷ Running command... + + +[?25h[?25l ⣯ Running command... + + +[?25h[?25l ⣟ Ru + + +[?25h[?25l ⡿ Running + + +[?25h[?25l ⢿ Running comm + + +[?25h[?25l ⣻ Running command.. + + +[?25h[?25l ⣽ Running command... + + +[?25h[?25l ⣾ Running command... + + +[?25h[?25l Run + + +[?25h[?25l ⣷ Run + + +[?25h[?25l ⣯ Running + + +[?25h[?25l ⣟ Running comma + + +[?25h[?25l ⡿ Running command... + + +[?25h[?25l  + Started. +⡿ Running command... +└ Tip: Use /settings to configure your environment. + +> + + ● [14:47:49] sleep 304 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⢿ Running command... + + +[?25h[?25l ⣻ + + +[?25h[?25l + + + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:47:49] sleep 304 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25luns + + + + G[?25h[?25lent draft[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.meta.json b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.meta.json new file mode 100644 index 00000000000..27c7349e716 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-11-08T19:47:27.977Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy 1.4.11, macOS, Google account, AGY_CLI_HIDE_ACCOUNT_INFO=1; one background task running, turn ended at the idle composer", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.txt b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.txt new file mode 100644 index 00000000000..ef6ef551413 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-background-task.txt @@ -0,0 +1,173 @@ +[>q[?2026$p[?2027$p]11;?]7501;?[>4m[?1049h[?25l[?5W[?2004h[>4;2m[>1u[?u +▄▀▀▄ +▀▀▀▀▀▀ +▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome back! You are currently not signed in. + + ⣷ Signing in...[>4m[<1u[?1049l[>4;2m[>1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.4.11 +▀▀▀▀▀▀ ~/orca-lanes/pr37732/agyws +▀▀▀▀▀▀▀▀ +▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts [?25h[?25l Gemini 3.8 Flash (Low) +~/orca-lanes/pr37732/agyws + + + + + + +Gemini 3.8 Flash · low [?25h[?25l M + ┃ Meet Gemini 4 Argon + ┃ Google’s most capable frontier model is now available in Antigravity. Built for complex, multi-step agentic + ┃ workflows, and deep reasoning. If it's not currently available to you, please reach out to your administrator to + ┃ enable it. + ┃ Learn more: https://docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools-settings#configure-model- + ┃ availability + ┃ esc to dismiss +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25lS[?25h[?25ltart the shell command "sl + + G[?25h[?25leep 300" as a background task, do no[?25h[?25lt wait for it, and end your turn with[?25h[?25l the word + Started. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Gemini 3.8 Flash · low [?25h[?25l + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25l M──────────────────────────────────────────────────────────── +> Start the shell command "sleep 300" as a background task, do not wait for it, and end your turn with the word + Started. +⣷ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25len + +[?25h[?25l ⣯ Genera + +[?25h[?25l ⣟ Generating. + +[?25h[?25l ⡿ Generating... + +[?25h[?25l ⢿ Generating... + +[?25h[?25l ⣻ Ge + +[?25h[?25l ⣽ Generat + +[?25h[?25l ⣾ Generating.. + +[?25h[?25l ⣷ Generating... + +[?25h[?25l ⣯ Generating... + +[?25h[?25l ⣟ Gen + +[?25h[?25l ⡿ Generati + +[?25h[?25l ⢿ Generating... + +[?25h[?25l ⣻ Generating... + +[?25h[?25l ⣽ + +[?25h[?25l  +○ Running (sleep 300) (ctrl+o to expand) +⣽ Generating... + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l Running command... + +[?25h[?25l ⣾ Running command. + +[?25h[?25lmand.. + +[?25h[?25land... + +[?25h[?25l nd + +[?25h[?25l ⣷ Running command. + +[?25h[?25l.. + +[?25h[?25l. + +[?25h[?25l ⣯ + +[?25h[?25l ● + + +[?25h[?25l ⣟ Ru + +[?25h[?25lnn + +[?25h[?25l Runnin + +[?25h[?25l ⡿ Running + +[?25h[?25l ⢿ Running comm + +[?25h[?25l ○ + command + +[?25h[?25l + + ● [14:46:49] sleep 300 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⣻ Running command.. + +[?25h[?25l ⣽ Running command... + +[?25h[?25l ⣾ Running command... + +[?25h[?25l ⣷ Run + +[?25h[?25l ⣯ Running  + +[?25h[?25l ⣟ Running comma + +[?25h[?25l ⡿ Running command... + +[?25h[?25l ⢿ Running command... + +[?25h[?25l ⣻ + +[?25h[?25l ⣽ Runn + +[?25h[?25l ⣾ Running c + +[?25h[?25l ⣷ Running comman + +[?25h[?25l ⣯ Running command... + +[?25h[?25ld... + +[?25h[?25l  + Started +⣟ Running command... + +> + + ● [14:46:49] sleep 300 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l ⡿ + +[?25h[?25l  + + + + + +? for shortcuts[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.meta.json b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.meta.json new file mode 100644 index 00000000000..4173a380ff2 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-11-08T19:48:31.841Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy 1.4.11, macOS, Google account, AGY_CLI_HIDE_ACCOUNT_INFO=1; two background tasks running, turn ended at the idle composer", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.txt b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.txt new file mode 100644 index 00000000000..02f5f4a0c45 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-1-4-11-ready-two-background-tasks.txt @@ -0,0 +1,232 @@ +[>q[?2026$p[?2027$p]11;?]7501;?[>4m[?1049h[?25l[?5W[?2004h[>4;2m[>5u[?u +▄▀▀▄ +▀▀▀▀▀▀ +▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome back! You are currently not signed in. + + ⣷ Signing in...[>4m[<1u[?1049l[>4;2m[>5u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.5.3 +▀▀▀▀▀▀ ~/orca-lanes/pr37732/agyws +▀▀▀▀▀▀▀▀ +▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcuts [?25h[?25l Gemini 3.8 Flash (Low) +~/orca-lanes/pr37732/agyws + + + + + + +Gemini 3.8 Flash · low [?25h[?25l M + ┃ Meet Gemini 4 Argon + ┃ Google’s most capable frontier model is now available in Antigravity. Built for complex, multi-step agentic + ┃ workflows, and deep reasoning. If it's not currently available to you, please reach out to your administrator to + ┃ enable it. + ┃ Learn more: https://docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools-settings#configure-model- + ┃ availability + ┃ esc to dismiss +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25lS[?25h[?25ltart two background tasks, "slee + + G[?25h[?25lp 301" and "sleep 302", do not wait[?25h[?25lfor them, and end your turn with the[?25h[?25l word + Started. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Gemini 3.8 Flash · low [?25h[?25l + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low [?25h[?25l M──────────────────────────────────────────────────────────── +> Start two background tasks, "sleep 301" and "sleep 302", do not wait for them, and end your turn with the word + Started. +⣷ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣯ + +[?25h[?25l ⣟ Gene + +[?25h[?25l ⡿ Generatin + +[?25h[?25l ⢿ Generating... + +[?25h[?25l ⣻ Generating... + +[?25h[?25l ⣽ + +[?25h[?25l ⣾ Gener + +[?25h[?25l ⣷ Generating + +[?25h[?25l ⣯ Generating... + +[?25h[?25l ⣟ Generating... + +[?25h[?25l ⡿ G + +[?25h[?25l ⢿ Genera + +[?25h[?25lenerating +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣻ Generating. + + +[?25h[?25l ⣽ Generating... + + +[?25h[?25l  +● Running (sleep 301) (ctrl+o to expand) +⣽ Generating... +└ Tip: Use /settings to configure your environment. + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25l ⣾ + + +[?25h[?25l ○ + Gen + + +[?25h[?25l ⣷ + + +[?25h[?25lner + + +[?25h[?25lan (sleep 301) +○ Running (sleep 302) (ctrl+o to expand) +⣷ Running command... +└ Tip: Use /settings to configure your environment. +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low [?25h[?25lunn + + +[?25h[?25l ⣯ Runn + + +[?25h[?25lin + + +[?25h[?25l Running  + + +[?25h[?25l ⣟ + + +[?25h[?25lning co + + +[?25h[?25l ⡿ Running comman + + +[?25h[?25l ⢿ Running command... + + +[?25h[?25l ⣻ Running command... + + +[?25h[?25l ⣽ + + +[?25h[?25l + + ● [14:47:49] sleep 301 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 1 task(s) · /tasks [?25h[?25l Runn + + +[?25h[?25l ⣾ Runn + + +[?25h[?25l ⣷ Running c + + +[?25h[?25l ⣯ Running comman + + +[?25h[?25l ⣟ Running command... + + +[?25h[?25l ⡿ Running command... + + +[?25h[?25l + +50] sleep 302 + ● [14:47:49] sleep 301 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 2 task(s) · /tasks [?25h[?25l ⢿ R + + +[?25h[?25l ⣻ Runnin + + +[?25h[?25l ⣽ Running com + + +[?25h[?25l ⣾ Running command + + +[?25h[?25l ⣷ Running command... + + +[?25h[?25l ⣯ Running command... + + +[?25h[?25l ⣟ Ru + + +[?25h[?25l ⡿ Running + + +[?25h[?25l ⢿ Running comm + + +[?25h[?25l ⣻ Running command.. + + +[?25h[?25l ⣽ Running command... + + +[?25h[?25l  + Started. +⣽ Running command... +└ Tip: Use /settings to configure your environment. + +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:47:50] sleep 302 running + ● [14:47:49] sleep 301 running +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.8 Flash · low · 2 task(s) · /tasks [?25h[?25l ⣾ + + +[?25h[?25l + + + + + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + ● [14:47:50] sleep 302 running +49] sleep 301 +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.8 Flash · low · 2 task(s) · /tasks [?25h \ No newline at end of file diff --git a/src/main/runtime/agent-session/environment/structured-session-child-env.ts b/src/main/runtime/agent-session/environment/structured-session-child-env.ts index 477968ced55..37bec85bfcf 100644 --- a/src/main/runtime/agent-session/environment/structured-session-child-env.ts +++ b/src/main/runtime/agent-session/environment/structured-session-child-env.ts @@ -9,26 +9,14 @@ import { ORCA_AGENT_SESSION_ID_ENV, ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV } from '../../../../shared/agent-session/lifecycle/agent-session-caller-env' -import { - ORCA_SCRUB_SAFE_LAUNCH_ENV, - ORCA_SCRUB_SAFE_PANE_ENV -} from '../../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env' import { ORCA_STRUCTURED_SESSION_ENV } from '../../../../shared/structured-session-marker' import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' -import { AGENT_HOOK_RUNTIME_ENV_KEYS } from '../../../ipc/pty/host-env/spawn-env-keys' +import { AGENT_PANE_HOOK_ENV_KEYS } from '../../../ipc/pty/host-env/spawn-env-keys' import { resolveStructuredWorkerIdentityForSession } from '../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' /** Remove inherited pane identity so hook status cannot compete with the structured-session producer. */ -export const STRUCTURED_CHILD_ENV_TO_DELETE: readonly string[] = [ - 'ORCA_PANE_KEY', - 'ORCA_TAB_ID', - 'ORCA_WORKTREE_ID', - 'ORCA_AGENT_LAUNCH_TOKEN', - ORCA_SCRUB_SAFE_PANE_ENV, - ORCA_SCRUB_SAFE_LAUNCH_ENV, - ...AGENT_HOOK_RUNTIME_ENV_KEYS -] +export const STRUCTURED_CHILD_ENV_TO_DELETE: readonly string[] = AGENT_PANE_HOOK_ENV_KEYS export type SealedStructuredSessionChild = { env: Record diff --git a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts b/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts index 3e1e0df66fe..1d3c69f9dcb 100644 --- a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts @@ -20,7 +20,7 @@ import { import '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import '../../orca-runtime-tests/scripted-codex-transport.test-fixture' -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { makeStructuredAgentStatusSubject } from '../../../../shared/agent-status/contracts/agent-status-subject' diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts index cb32152823f..f4082664bd6 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts @@ -24,7 +24,7 @@ vi.mock('../../../text-generation/commit-message-text-generation', async (import const actual = await importOriginal() return { ...actual, generateConversationNameFromContext: mocks.generate } }) -vi.mock('../../../agent-hooks/first-work-generation-target', () => ({ +vi.mock('../../../agent-hooks/first-work/first-work-generation-target', () => ({ resolveGenerationTarget: mocks.target })) vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts index 3994d985617..8a1e7918a54 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts @@ -21,7 +21,7 @@ import { generateConversationNameFromContext, resolveTextGenerationParams } from '../../../text-generation/commit-message-text-generation' -import { resolveGenerationTarget } from '../../../agent-hooks/first-work-generation-target' +import { resolveGenerationTarget } from '../../../agent-hooks/first-work/first-work-generation-target' type StructuredChatNamingRuntime = { resolveWorkspace: ( diff --git a/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts b/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts index 11cd7840f1b..b95c20424a3 100644 --- a/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts +++ b/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts @@ -1,6 +1,6 @@ import { vi, type Mock, type MockInstance } from 'vitest' -import { AgentHookServer } from '../../../agent-hooks/server' -import { agentHookRuntimeDeps } from '../../../agent-hooks/agent-hook-runtime-deps' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { agentHookRuntimeDeps } from '../../../agent-hooks/runtime/agent-hook-runtime-deps' import { AgentStatusObservedPaneIdentities } from '../../terminal/identity/agent-status-observed-pane-identity' import { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' import { hostTestState } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' diff --git a/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts b/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts index 5c09977fb8b..198a8dca8d0 100644 --- a/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts +++ b/src/main/runtime/agent-session/records/structured-agent-session-mobile-restore.test.ts @@ -6,7 +6,8 @@ import { attach, seedApproval, envelope, - CALLER + CALLER, + hostTestRecoveryCapsuleSettled } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' import { HOST_TEST_SESSION as SESSION, @@ -86,6 +87,8 @@ describe('prompt delivery after host recovery', () => { } unsubscribe() await original.closeDismissals() + // A restarted process starts after the old one's capsule writes finished or died with it. + await hostTestRecoveryCapsuleSettled() const restarted = new RuntimeMobileNotificationController() restarted.configureDismissalStore(h.root) const events: MobileNotificationEvent[] = [] diff --git a/src/main/runtime/agent-session/structured-child-records-switch.test.ts b/src/main/runtime/agent-session/structured-child-records-switch.test.ts index 3563c3af9bc..09a232c2a74 100644 --- a/src/main/runtime/agent-session/structured-child-records-switch.test.ts +++ b/src/main/runtime/agent-session/structured-child-records-switch.test.ts @@ -14,7 +14,7 @@ import type { } from '../../codex/app-server/codex-app-server-connection-types' import type { openCodexAppServerConnection } from '../../codex/app-server/codex-app-server-connection' import { collectRuntimeWorktreeAgentSources } from '../workspaces/process-listing/runtime-worktree-agent-sources' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' import { HOST_TEST_SESSION as SESSION, diff --git a/src/main/runtime/agent-state-rules/antigravity-background-task-rules.test.ts b/src/main/runtime/agent-state-rules/antigravity-background-task-rules.test.ts new file mode 100644 index 00000000000..408195ec75e --- /dev/null +++ b/src/main/runtime/agent-state-rules/antigravity-background-task-rules.test.ts @@ -0,0 +1,32 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { HeadlessEmulator } from '../../daemon/emulation/headless-emulator' +import { visibleNonBlankTerminalLines } from '../terminal/output/tail/terminal-tail-read' +import { evaluateAgentStateRules } from './agent-state-rules-engine' + +async function verdictFor(fixture: string) { + const emulator = new HeadlessEmulator({ cols: 120, rows: 40 }) + await emulator.write( + readFileSync(join(__dirname, '..', '__fixtures__', `${fixture}.txt`), 'utf8') + ) + const lines = visibleNonBlankTerminalLines(emulator.getVisibleLines()) + emulator.dispose() + return evaluateAgentStateRules('antigravity', { readScreenLines: () => lines }) +} + +describe('antigravity composer with background task rows', () => { + it.each([ + 'antigravity-1-4-11-ready-background-task', + 'antigravity-1-4-11-ready-two-background-tasks' + ])('reads %s as a strong idle composer', async (fixture) => { + expect(await verdictFor(fixture)).toMatchObject({ state: 'idle', strength: 'strong' }) + }) + + it.each([ + 'antigravity-1-4-11-busy-with-background-task', + 'antigravity-1-4-11-draft-with-background-task' + ])('holds %s', async (fixture) => { + expect(await verdictFor(fixture)).toMatchObject({ state: 'hold' }) + }) +}) diff --git a/src/main/runtime/agent-state-rules/antigravity.json b/src/main/runtime/agent-state-rules/antigravity.json index 39b055db75a..24e31b40fa6 100644 --- a/src/main/runtime/agent-state-rules/antigravity.json +++ b/src/main/runtime/agent-state-rules/antigravity.json @@ -26,6 +26,28 @@ }, "answer": { "state": "idle", "strength": "strong", "requiresQuiet": true } }, + { + "id": "composer_ready_background_tasks", + "why": "agy 1.4 lists running background tasks (`● [14:12:56] sleep 900 running`) under the composer, closed by another rule above the hint row, so the composer is no longer in the bottom four rows. The hint row still decides as in composer_ready: a turn's own foreground command is listed the same way, but the hint then reads `esc to cancel`. One task row is required so the rule cannot collapse onto composer_ready's rows; more than six tasks reads as not shown.", + "priority": 490, + "when": { + "region": "screen", + "rows": [ + { "regex": "^─{8,}$" }, + { "regex": "^>$|^>\\s+[a-z][a-z-]*\\s+mode:\\s", "ignoreCase": true }, + { "regex": "^─{8,}$" }, + { "optional": { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" } }, + { "optional": { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" } }, + { "optional": { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" } }, + { "optional": { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" } }, + { "optional": { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" } }, + { "regex": "^●\\s+\\[\\d{1,2}:\\d{2}:\\d{2}\\]\\s+\\S" }, + { "regex": "^─{8,}$" }, + { "regex": "^\\? for shortcuts", "ignoreCase": true } + ] + }, + "answer": { "state": "idle", "strength": "strong", "requiresQuiet": true } + }, { "id": "composer_ready_custom_status_line", "why": "A custom statusLine replaces the hint row, so `esc to cancel` never shows; agy 1.5.2 then marks a turn only with a braille spinner row above the composer. Status rows may not hold a rule run, a hint, or agy's own `[mode · ]model · effort` footer, which drops its hint while the composer holds a draft. Pickers between the composer and status rows break the run. A custom row shaped like that footer holds; a mode-shaped draft above a custom statusLine still reads idle.", diff --git a/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts b/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts index 7e5dc0a34e3..35465319fc9 100644 --- a/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts +++ b/src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts @@ -68,7 +68,7 @@ vi.mock('../../../browser/guest-lifecycle/browser-main-window-readiness', () => whenBrowserMainWindowReady: whenBrowserMainWindowReadyMock })) -vi.mock('../../../browser/sessions/browser-session-registry', () => ({ +vi.mock('../../../browser/sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: browserSessionRegistryMock })) diff --git a/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts b/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts index ec5d8f6bbc5..5b956775376 100644 --- a/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts +++ b/src/main/runtime/browser/client-pages/renderer-browser-lifecycle.test.ts @@ -51,7 +51,10 @@ function browserRuntime(closeTab = vi.fn(async (_pageId: string) => {}), runtime ownsTab: (pageId) => livePages.has(pageId) && !desktopPageIds.has(pageId) }) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the bridge inventory is used by this lifecycle test. - runtime.setAgentBrowserBridge({ tabList: () => ({ tabs: [...livePages.values()] }) } as never) + runtime.setAgentBrowserBridge({ + tabList: () => ({ tabs: [...livePages.values()] }), + getRemoteTabFaviconUrl: () => null + } as never) electronMocks.BrowserWindow.fromId.mockImplementation((id: number) => id === 1 ? { isDestroyed: () => false } : null ) diff --git a/src/main/runtime/browser/commands/browser-dialogs.ts b/src/main/runtime/browser/commands/browser-dialogs.ts index df71f06a8e1..dc409fcd650 100644 --- a/src/main/runtime/browser/commands/browser-dialogs.ts +++ b/src/main/runtime/browser/commands/browser-dialogs.ts @@ -1,5 +1,5 @@ import type { AgentBrowserBridge } from '../../../browser/agent-browser/agent-browser-bridge' -import type { BrowserDialogAnswer } from '../../../browser/agent-browser/agent-browser-bridge-page-commands' +import type { BrowserDialogAnswer } from '../../../browser/agent-browser/commands/agent-browser-bridge-page-commands' import type { BrowserCommandTargetParams } from './browser-command-contracts' import type { RuntimeBrowserCommandTargets } from './browser-command-targets' diff --git a/src/main/runtime/browser/commands/browser-profiles.ts b/src/main/runtime/browser/commands/browser-profiles.ts index 2a6726acec9..ef857edd7ee 100644 --- a/src/main/runtime/browser/commands/browser-profiles.ts +++ b/src/main/runtime/browser/commands/browser-profiles.ts @@ -13,16 +13,16 @@ import type { BrowserProfileImportFromBrowserResult } from '../../../../shared/runtime-browser-contracts' import { BrowserError } from '../../../browser/browser-error' -import { browserSessionRegistry } from '../../../browser/sessions/browser-session-registry' -import { browserManager } from '../../../browser/browser-manager' +import { browserSessionRegistry } from '../../../browser/sessions/profiles/browser-session-registry' +import { browserManager } from '../../../browser/guest-lifecycle/manager/browser-manager' import { randomUUID } from 'node:crypto' import { ipcMain } from 'electron' import { waitForTabRegistration } from '../../../ipc/browser/browser-tab-registration-wait' import { detectInstalledBrowsers, - importCookiesFromBrowser, selectBrowserProfile -} from '../../../browser/cookies/browser-cookie-import' +} from '../../../browser/cookies/sources/browser-cookie-detection' +import { importCookiesFromBrowser } from '../../../browser/cookies/browser-cookie-import' import type { BrowserCommandTargetParams, RuntimeBrowserCommandHost diff --git a/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts b/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts index edf1f68d464..2c2399366d0 100644 --- a/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts +++ b/src/main/runtime/browser/headless/orca-runtime-serve-browser-restore.test.ts @@ -30,7 +30,7 @@ function restartedServe(session: WorkspaceSessionState = savedServeTabs()) { ownsTab: () => true }) runtime.setAgentBrowserBridge( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only tabList from the bridge on these paths. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only these bridge methods on these paths. { tabList: vi.fn(() => ({ tabs: livePages.map((browserPageId, index) => ({ @@ -42,6 +42,7 @@ function restartedServe(session: WorkspaceSessionState = savedServeTabs()) { active: false })) })), + getRemoteTabFaviconUrl: () => null, getRegisteredTabs: vi.fn(() => registered()), snapshot: vi.fn(async () => ({ snapshot: '' })), getActivePageId: vi.fn(() => livePages[0] ?? null), diff --git a/src/main/runtime/browser/tabs/browser-tab-catalog.ts b/src/main/runtime/browser/tabs/browser-tab-catalog.ts index c9350825e03..08580e35dea 100644 --- a/src/main/runtime/browser/tabs/browser-tab-catalog.ts +++ b/src/main/runtime/browser/tabs/browser-tab-catalog.ts @@ -1,9 +1,9 @@ import type { RuntimeBrowserClientPage } from '../client-pages/runtime-browser-page-registry' import type { BrowserTabListResult } from '../../../../shared/runtime-browser-contracts' -import { browserSessionRegistry } from '../../../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../../../browser/sessions/profiles/browser-session-registry' import { mergeBrowserTabListing } from './browser-tab-listing' import { BrowserError } from '../../../browser/browser-error' -import { browserManager } from '../../../browser/browser-manager' +import { browserManager } from '../../../browser/guest-lifecycle/manager/browser-manager' import type { BrowserCommandTargetParams, RuntimeBrowserCommandHost diff --git a/src/main/runtime/browser/tabs/browser-tab-close.ts b/src/main/runtime/browser/tabs/browser-tab-close.ts index 7f172893408..bb5b8183890 100644 --- a/src/main/runtime/browser/tabs/browser-tab-close.ts +++ b/src/main/runtime/browser/tabs/browser-tab-close.ts @@ -4,7 +4,7 @@ import { retireRuntimeBrowserClientPage } from '../client-pages/browser-client-page-close' import { BrowserError } from '../../../browser/browser-error' -import { browserManager } from '../../../browser/browser-manager' +import { browserManager } from '../../../browser/guest-lifecycle/manager/browser-manager' import { closeBrowserTabInRenderer } from './browser-tab-renderer-close' import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' import type { RuntimeBrowserCommandTargets } from '../commands/browser-command-targets' diff --git a/src/main/runtime/browser/tabs/browser-tab-creation.ts b/src/main/runtime/browser/tabs/browser-tab-creation.ts index 318dd1a09ee..cc003bf5f62 100644 --- a/src/main/runtime/browser/tabs/browser-tab-creation.ts +++ b/src/main/runtime/browser/tabs/browser-tab-creation.ts @@ -6,7 +6,7 @@ import { publishCreatedBrowserSessionTab, resolveBrowserTabCreateFocus } from './browser-tab-create-publication' -import { browserSessionRegistry } from '../../../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../../../browser/sessions/profiles/browser-session-registry' import { BrowserError } from '../../../browser/browser-error' import { waitForTabRegistration } from '../../../ipc/browser/browser-tab-registration-wait' import type { RuntimeBrowserCommandHost } from '../commands/browser-command-contracts' diff --git a/src/main/runtime/browser/tabs/browser-tab-queries.ts b/src/main/runtime/browser/tabs/browser-tab-queries.ts index cfa440c66ad..015ecdb007a 100644 --- a/src/main/runtime/browser/tabs/browser-tab-queries.ts +++ b/src/main/runtime/browser/tabs/browser-tab-queries.ts @@ -5,7 +5,10 @@ import type { BrowserTabSwitchResult } from '../../../../shared/runtime-browser-contracts' import type { BrowserCertificateProceedResult } from '../../../../shared/browser-workspace-types' -import { browserCertificateTrustController, browserManager } from '../../../browser/browser-manager' +import { + browserCertificateTrustController, + browserManager +} from '../../../browser/guest-lifecycle/manager/browser-manager' import { BrowserError } from '../../../browser/browser-error' import { publishSwitchedBrowserSessionTab } from './browser-tab-create-publication' import type { diff --git a/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts b/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts index 48f601a21ff..df45dff0da5 100644 --- a/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts +++ b/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts @@ -21,7 +21,7 @@ vi.mock('../../../ssh/config/ssh-config-parser', () => ({ vi.mock('../../../claude/agent-view/agent-view-service', () => ({ getClaudeAgentViewService: () => ({ reconcile: async () => {} }) })) -vi.mock('../../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: vi.fn(async () => {}) })) diff --git a/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts b/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts index 183955abe23..8fa66df5038 100644 --- a/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts +++ b/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts @@ -17,7 +17,7 @@ vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) -vi.mock('../../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: hooks.apply })) void Object.fromEntries(Object.keys(tuiAgentPermissions.YOLO_TUI_AGENT_ARGS).map((id) => [id, ''])) diff --git a/src/main/runtime/client/settings/runtime-client-settings.ts b/src/main/runtime/client/settings/runtime-client-settings.ts index 6df23705be3..16b1030d13a 100644 --- a/src/main/runtime/client/settings/runtime-client-settings.ts +++ b/src/main/runtime/client/settings/runtime-client-settings.ts @@ -20,8 +20,8 @@ import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-ov import { nativeChatQueueFollowUps } from '../../../../shared/native-chat/input/native-chat-follow-up-behavior' import { nativeChatShowsCiResultLines } from '../../../../shared/native-chat/native-chat-appearance-settings' import type { TerminalQuickCommand } from '../../../../shared/terminal/quick-commands/terminal-quick-command-types' -import { recordManagedHookInstallFailure } from '../../../agent-hooks/install-telemetry' -import { applyAgentStatusHooksEnabled } from '../../../agent-hooks/managed-agent-hook-controls' +import { recordManagedHookInstallFailure } from '../../../agent-hooks/installation/install-telemetry' +import { applyAgentStatusHooksEnabled } from '../../../agent-hooks/installation/managed-agent-hook-controls' import { isWslHostOrcadProcess } from '../../../ipc/wsl-guest-windows-drive-path' import { isAgentStatusHooksEnabledForAgent } from '../../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { RuntimeStore } from '../../construction/runtime-store-contract' diff --git a/src/main/runtime/construction/orca-runtime-agent-transitions.ts b/src/main/runtime/construction/orca-runtime-agent-transitions.ts index 76a1c89a1bf..bf809fb30f7 100644 --- a/src/main/runtime/construction/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/construction/orca-runtime-agent-transitions.ts @@ -1,5 +1,5 @@ import { watchMovedWorkerResumeSessions } from '../rpc/methods/orchestration/worker/worker-resume-session-capture' -import { AgentTransitionDetector } from '../../agent-hooks/agent-transition-detector' +import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' import type { ConnectorCloud } from '../../connector-cloud/connector-cloud' import type { ExternalConversationSeam } from '../../external-conversations/external-conversation-seam' import { installExternalConversations } from '../../external-conversations/external-conversations-install' diff --git a/src/main/runtime/host-instance-identity.test.ts b/src/main/runtime/host-instance-identity.test.ts new file mode 100644 index 00000000000..ffc5594c52e --- /dev/null +++ b/src/main/runtime/host-instance-identity.test.ts @@ -0,0 +1,299 @@ +import { randomUUID } from 'node:crypto' +import { cpSync, mkdtempSync, readdirSync, readFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, describe, expect, it } from 'vitest' +import { loadOrCreateE2EEKeypair, writeNewE2EEKeypair } from './rpc/server/pairing/e2ee-keypair' +import { DeviceRegistry } from './rpc/server/pairing/device-registry' +import { + HOST_INSTALLATION_FILENAME, + loadOrCreateHostInstallationId +} from './hosts/platform-probe/host-descriptor' +import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { + ensureHostInstanceIdentity, + hostInstanceIdFromEnv, + HOST_INSTANCE_FILENAME, + IDENTITY_BACKUPS_DIRNAME, + rotateHostIdentity, + type HostIdentityWrite +} from './host-instance-identity' +import { E2EE_KEYPAIR_FILENAME } from '../../shared/remote-runtime/host-store/runtime-e2ee-keypair-file' +import { DEVICE_REGISTRY_FILENAME } from './rpc/server/pairing/mobile-pairing-files' + +const vmA = hostInstanceIdFromEnv({ ORCA_INSTANCE_ID: 'vm-a' }) +const vmB = hostInstanceIdFromEnv({ ORCA_INSTANCE_ID: 'vm-b' }) + +/** What pairing serves after one startup. */ +async function identity(dir: string) { + return { + publicKeyB64: loadOrCreateE2EEKeypair(dir).publicKeyB64, + registry: new DeviceRegistry(dir), + installationId: await loadOrCreateHostInstallationId(dir) + } +} + +async function pairedHost(dir: string) { + const host = await identity(dir) + const { token } = host.registry.addDevice('Phone') + host.registry.flushPendingLastSeen() + return { ...host, token } +} + +function failingWriteOf(filename: string): HostIdentityWrite { + return (path, value) => { + if (path.endsWith(filename)) { + throw new Error(`simulated crash writing ${filename}`) + } + return writeDurableSecureJsonFile(path, value) + } +} + +describe('ensureHostInstanceIdentity', () => { + let dir: string + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-host-instance-')) + }) + + it('never rotates while ORCA_INSTANCE_ID is unset, even with an id recorded', async () => { + const before = await pairedHost(dir) + expect(ensureHostInstanceIdentity(dir, null)).toEqual({ kind: 'unchanged' }) + ensureHostInstanceIdentity(dir, vmA) + expect(ensureHostInstanceIdentity(dir, null)).toEqual({ kind: 'unchanged' }) + + const after = await identity(dir) + expect(after.publicKeyB64).toBe(before.publicKeyB64) + expect(after.installationId).toBe(before.installationId) + expect(after.registry.validateToken(before.token)).not.toBeNull() + }) + + it('only records the first ORCA_INSTANCE_ID on an existing install', async () => { + const before = await pairedHost(dir) + expect(ensureHostInstanceIdentity(dir, vmA)).toEqual({ kind: 'recorded' }) + expect(ensureHostInstanceIdentity(dir, vmA)).toEqual({ kind: 'unchanged' }) + + const after = await identity(dir) + expect(after.publicKeyB64).toBe(before.publicKeyB64) + expect(after.registry.validateToken(before.token)).not.toBeNull() + expect(readFileSync(join(dir, HOST_INSTANCE_FILENAME), 'utf8')).not.toContain('vm-a') + }) + + it('rotates the identity and clears pairings when ORCA_INSTANCE_ID changes', async () => { + ensureHostInstanceIdentity(dir, vmA) + const source = await pairedHost(dir) + const clone = mkdtempSync(join(tmpdir(), 'orca-host-instance-clone-')) + cpSync(dir, clone, { recursive: true }) + + expect(ensureHostInstanceIdentity(clone, vmB)).toEqual({ + kind: 'rotated', + reason: 'instance_changed' + }) + const rotated = await identity(clone) + expect(rotated.publicKeyB64).not.toBe(source.publicKeyB64) + expect(rotated.installationId).not.toBe(source.installationId) + expect(rotated.registry.validateToken(source.token)).toBeNull() + expect(rotated.registry.listDevices()).toEqual([]) + + expect(ensureHostInstanceIdentity(clone, vmB)).toEqual({ kind: 'unchanged' }) + expect((await identity(clone)).publicKeyB64).toBe(rotated.publicKeyB64) + // The source keeps its own identity. + expect((await identity(dir)).registry.validateToken(source.token)).not.toBeNull() + }) + + it.each([ + ['the staged keypair', 'orca-e2ee-keypair.json.next'], + ['the staged registry', `${DEVICE_REGISTRY_FILENAME}.next`], + ['the rotating marker', HOST_INSTANCE_FILENAME] + ])('keeps serving the old identity when writing %s fails', async (_label, failing) => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + + expect(ensureHostInstanceIdentity(dir, vmB, failingWriteOf(failing))).toMatchObject({ + kind: 'kept' + }) + const after = await identity(dir) + expect(after.publicKeyB64).toBe(before.publicKeyB64) + expect(after.installationId).toBe(before.installationId) + expect(after.registry.validateToken(before.token)).not.toBeNull() + expect(readdirSync(dir).filter((name) => name.endsWith('.next'))).toEqual([]) + // The change is still pending, so a start that can write applies it. + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ + kind: 'rotated', + reason: 'instance_changed' + }) + }) + + it('keeps serving the old identity when the first id cannot be recorded', async () => { + const before = await pairedHost(dir) + expect( + ensureHostInstanceIdentity(dir, vmA, failingWriteOf(HOST_INSTANCE_FILENAME)) + ).toMatchObject({ kind: 'kept' }) + expect((await identity(dir)).registry.validateToken(before.token)).not.toBeNull() + }) + + it('finishes a publish interrupted after the marker on the next start, without the variable', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + + // Every staged file was moved into place; clearing `rotating` failed. + const failFinalMarker: HostIdentityWrite = (path, value) => { + if (path.endsWith(HOST_INSTANCE_FILENAME) && !JSON.stringify(value).includes('rotating')) { + throw new Error('simulated crash clearing the marker') + } + return writeDurableSecureJsonFile(path, value) + } + expect(() => ensureHostInstanceIdentity(dir, vmB, failFinalMarker)).toThrow(/simulated crash/) + + expect(ensureHostInstanceIdentity(dir, null)).toEqual({ + kind: 'rotated', + reason: 'interrupted_rotation' + }) + const after = await identity(dir) + expect(after.publicKeyB64).not.toBe(before.publicKeyB64) + expect(after.installationId).not.toBe(before.installationId) + expect(after.registry.validateToken(before.token)).toBeNull() + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ kind: 'unchanged' }) + }) + + it('publishes the rest of a staged identity after a crash between renames', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + // The keypair was already moved into place; the registry and installation id were not. + const newKey = writeNewE2EEKeypair(dir, writeDurableSecureJsonFile).publicKeyB64 + writeDurableSecureJsonFile(join(dir, `${DEVICE_REGISTRY_FILENAME}.next`), []) + const stagedInstallationId = randomUUID() + writeDurableSecureJsonFile(join(dir, `${HOST_INSTALLATION_FILENAME}.next`), { + installationId: stagedInstallationId + }) + writeDurableSecureJsonFile(join(dir, HOST_INSTANCE_FILENAME), { + v: 1, + instanceId: vmB, + rotating: true + }) + + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ + kind: 'rotated', + reason: 'interrupted_rotation' + }) + const after = await identity(dir) + expect(after.publicKeyB64).toBe(newKey) + expect(after.installationId).toBe(stagedInstallationId) + expect(after.registry.validateToken(before.token)).toBeNull() + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ kind: 'unchanged' }) + }) + + it('finishes the rotation when the rotating marker is published but its write still fails', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + // For example the directory sync after the marker rename fails. + const failAfterMarkerRename: HostIdentityWrite = (path, value) => { + const result = writeDurableSecureJsonFile(path, value) + if (path.endsWith(HOST_INSTANCE_FILENAME) && JSON.stringify(value).includes('rotating')) { + throw new Error('simulated directory sync failure') + } + return result + } + + expect(ensureHostInstanceIdentity(dir, vmB, failAfterMarkerRename)).toEqual({ + kind: 'rotated', + reason: 'instance_changed' + }) + const after = await identity(dir) + expect(after.publicKeyB64).not.toBe(before.publicKeyB64) + expect(after.registry.validateToken(before.token)).toBeNull() + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ kind: 'unchanged' }) + }) + + it('keeps the recorded id when a manual reset runs without ORCA_INSTANCE_ID', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + rotateHostIdentity(dir, null) + const after = await identity(dir) + expect(after.publicKeyB64).not.toBe(before.publicKeyB64) + expect(ensureHostInstanceIdentity(dir, vmA)).toEqual({ kind: 'unchanged' }) + // A copy made after the reset and started with another id still rotates. + expect(ensureHostInstanceIdentity(dir, vmB)).toMatchObject({ kind: 'rotated' }) + }) + + it('finishes an interrupted rotation before a manual reset stages a new one', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + const failFinalMarker: HostIdentityWrite = (path, value) => { + if (path.endsWith(HOST_INSTANCE_FILENAME) && !JSON.stringify(value).includes('rotating')) { + throw new Error('simulated crash clearing the marker') + } + return writeDurableSecureJsonFile(path, value) + } + expect(() => ensureHostInstanceIdentity(dir, vmB, failFinalMarker)).toThrow(/simulated crash/) + + rotateHostIdentity(dir, null) + const after = await identity(dir) + expect(after.registry.validateToken(before.token)).toBeNull() + expect(readdirSync(dir).filter((name) => name.endsWith('.next'))).toEqual([]) + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ kind: 'unchanged' }) + }) + + it('moves the replaced identity into a backup folder and keeps the newest five', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + rotateHostIdentity(dir, vmA, writeDurableSecureJsonFile, () => new Date('2026-01-01T00:00:00Z')) + + const backups = join(dir, IDENTITY_BACKUPS_DIRNAME) + const [first] = readdirSync(backups) + expect(first).toMatch(/^2026-01-01T00-00-00-000Z-[0-9a-f]{6}$/) + const saved = JSON.parse(readFileSync(join(backups, first, E2EE_KEYPAIR_FILENAME), 'utf8')) + expect(saved.publicKeyB64).toBe(before.publicKeyB64) + expect(readdirSync(join(backups, first)).sort()).toEqual( + [E2EE_KEYPAIR_FILENAME, DEVICE_REGISTRY_FILENAME, HOST_INSTALLATION_FILENAME].sort() + ) + + for (let day = 2; day <= 7; day++) { + rotateHostIdentity( + dir, + vmA, + writeDurableSecureJsonFile, + () => new Date(`2026-01-0${day}T00:00:00Z`) + ) + } + const kept = readdirSync(backups).sort() + expect(kept).toHaveLength(5) + expect(kept[0]).toMatch(/^2026-01-03/) + }) + + it('reports a reset as done when it finished an interrupted rotation but cannot stage another', async () => { + ensureHostInstanceIdentity(dir, vmA) + const before = await pairedHost(dir) + const failFinalMarker: HostIdentityWrite = (path, value) => { + if (path.endsWith(HOST_INSTANCE_FILENAME) && !JSON.stringify(value).includes('rotating')) { + throw new Error('simulated crash clearing the marker') + } + return writeDurableSecureJsonFile(path, value) + } + expect(() => ensureHostInstanceIdentity(dir, vmB, failFinalMarker)).toThrow(/simulated crash/) + + expect(() => + rotateHostIdentity(dir, null, failingWriteOf('orca-e2ee-keypair.json.next')) + ).not.toThrow() + expect((await identity(dir)).registry.validateToken(before.token)).toBeNull() + expect(readdirSync(dir).filter((name) => name.endsWith('.next'))).toEqual([]) + expect(ensureHostInstanceIdentity(dir, vmB)).toEqual({ kind: 'unchanged' }) + }) + + it('never prunes the backup it just made', async () => { + ensureHostInstanceIdentity(dir, vmA) + await pairedHost(dir) + for (let day = 5; day <= 9; day++) { + rotateHostIdentity( + dir, + vmA, + writeDurableSecureJsonFile, + () => new Date(`2027-01-0${day}T00:00:00Z`) + ) + } + // The clock went back (or the image carried later backups). + rotateHostIdentity(dir, vmA, writeDurableSecureJsonFile, () => new Date('2026-01-01T00:00:00Z')) + const kept = readdirSync(join(dir, IDENTITY_BACKUPS_DIRNAME)).sort() + expect(kept).toHaveLength(5) + expect(kept[0]).toMatch(/^2026-01-01/) + }) +}) diff --git a/src/main/runtime/host-instance-identity.ts b/src/main/runtime/host-instance-identity.ts new file mode 100644 index 00000000000..f327cf246b6 --- /dev/null +++ b/src/main/runtime/host-instance-identity.ts @@ -0,0 +1,288 @@ +// Copies of one machine image share the pairing identity files; ORCA_INSTANCE_ID tells the copies apart. +import { createHash, randomBytes, randomUUID } from 'node:crypto' +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from 'node:fs' +import { basename, join } from 'node:path' +import { z } from 'zod' +import { + bestEffortFsyncDirectorySync, + writeDurableSecureJsonFile +} from '../../shared/secure-storage/secure-file' +import { E2EE_KEYPAIR_FILENAME } from '../../shared/remote-runtime/host-store/runtime-e2ee-keypair-file' +import { writeNewE2EEKeypair } from './rpc/server/pairing/e2ee-keypair' +import { DEVICE_REGISTRY_FILENAME } from './rpc/server/pairing/mobile-pairing-files' +import { HOST_INSTALLATION_FILENAME } from './hosts/platform-probe/host-descriptor' + +export const HOST_INSTANCE_FILENAME = 'orca-host-instance.json' +export const ORCA_INSTANCE_ID_ENV = 'ORCA_INSTANCE_ID' +const MAX_HOST_INSTANCE_FILE_BYTES = 4 * 1024 +const IDENTITY_FILENAMES = [ + E2EE_KEYPAIR_FILENAME, + DEVICE_REGISTRY_FILENAME, + HOST_INSTALLATION_FILENAME +] as const +const STAGED_SUFFIX = '.next' +/** Replaced identity files are moved here so an unwanted rotation can be undone by hand. */ +export const IDENTITY_BACKUPS_DIRNAME = 'orca-identity-backups' +const MAX_IDENTITY_BACKUPS = 5 +const BACKUP_NAME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{6}$/ + +/** `instanceId` is hashed so the file never republishes a provisioner value. `rotating` is written + * only once every new file is staged beside the live one; a start that sees it publishes them. */ +const HostInstanceMarkerSchema = z.object({ + v: z.literal(1), + instanceId: z.string().min(1).optional(), + rotating: z.literal(true).optional(), + /** Backup folder for the files a `rotating` publish replaces; stable across an interrupted publish. */ + backup: z.string().optional() +}) +type HostInstanceMarker = z.infer + +export type HostIdentityOutcome = + | { kind: 'unchanged' } + | { kind: 'recorded' } + | { kind: 'rotated'; reason: 'instance_changed' | 'interrupted_rotation' } + /** Nothing was changed on disk, so the existing identity is still whole and safe to serve. */ + | { kind: 'kept'; error: unknown } + +export type HostIdentityWrite = (path: string, value: unknown) => boolean + +/** The rotation failed before any live identity file was touched. */ +export class HostIdentityRotationNotStartedError extends Error { + constructor(cause: unknown) { + super( + `Could not write the new pairing identity; the current one is unchanged: ${cause instanceof Error ? cause.message : String(cause)}`, + { cause } + ) + this.name = 'HostIdentityRotationNotStartedError' + } +} + +export function hostInstanceIdFromEnv(env: NodeJS.ProcessEnv = process.env): string | null { + const raw = env[ORCA_INSTANCE_ID_ENV]?.trim() + return raw ? createHash('sha256').update(`orca-host-instance\0${raw}`).digest('hex') : null +} + +function isMissing(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT' +} + +function readMarker(markerPath: string): HostInstanceMarker | null { + let raw: string + try { + raw = readFileSync(markerPath, 'utf8') + } catch (error) { + if (isMissing(error)) { + return null + } + throw error + } + if (raw.length > MAX_HOST_INSTANCE_FILE_BYTES) { + return null + } + try { + const parsed = HostInstanceMarkerSchema.safeParse(JSON.parse(raw)) + return parsed.success ? parsed.data : null + } catch { + // Writes are atomic, so a bad file was edited by hand; re-record it rather than unpair. + return null + } +} + +function markerFor(instanceId: string | undefined): HostInstanceMarker { + return { v: 1, ...(instanceId ? { instanceId } : {}) } +} + +function newBackupName(now: Date): string { + return `${now.toISOString().replace(/[:.]/g, '-')}-${randomBytes(3).toString('hex')}` +} + +function stagedIdentityPaths(userDataPath: string): { live: string; staged: string }[] { + return IDENTITY_FILENAMES.map((name) => { + const live = join(userDataPath, name) + return { live, staged: `${live}${STAGED_SUFFIX}` } + }) +} + +/** Writes the new identity beside the live files, which stay untouched. */ +function stageNewIdentity(userDataPath: string, write: HostIdentityWrite): void { + const stage: HostIdentityWrite = (path, value) => write(`${path}${STAGED_SUFFIX}`, value) + writeNewE2EEKeypair(userDataPath, stage) + stage(join(userDataPath, DEVICE_REGISTRY_FILENAME), []) + stage(join(userDataPath, HOST_INSTALLATION_FILENAME), { installationId: randomUUID() }) +} + +function discardStagedIdentity(userDataPath: string): void { + for (const { staged } of stagedIdentityPaths(userDataPath)) { + try { + rmSync(staged, { force: true }) + } catch { + // A leftover staged file is ignored until a later rotation overwrites it. + } + } +} + +/** Best effort: a failed backup must not block the rotation, so the live file is then overwritten. */ +function backUpLiveFile(live: string, backupDir: string | null): void { + if (!backupDir) { + return + } + try { + mkdirSync(backupDir, { recursive: true, mode: 0o700 }) + const saved = join(backupDir, basename(live)) + // A resumed publish keeps the first backup; a live file recreated meanwhile is not the original. + if (!existsSync(saved)) { + renameSync(live, saved) + } + } catch { + // ENOENT: an earlier, interrupted publish already moved it (or it never existed). + } +} + +function pruneIdentityBackups(userDataPath: string, current: string | undefined): void { + const root = join(userDataPath, IDENTITY_BACKUPS_DIRNAME) + try { + // Never the one just made, even when copied-in backups carry later timestamps. + const names = readdirSync(root) + .filter((name) => BACKUP_NAME_RE.test(name) && name !== current) + .sort() + for (const name of names.slice(0, Math.max(0, names.length - (MAX_IDENTITY_BACKUPS - 1)))) { + rmSync(join(root, name), { recursive: true, force: true }) + } + } catch { + // Old backups are only disk space; never fail a rotation over them. + } +} + +/** Moves each staged file over its live file, after moving the live file into the backup folder. + * Staging finished before the `rotating` marker was written, so a missing staged file was already + * moved by an earlier, interrupted publish. */ +function publishStagedIdentity( + userDataPath: string, + marker: { instanceId?: string; backup?: string }, + write: HostIdentityWrite +): void { + const backupDir = + marker.backup && BACKUP_NAME_RE.test(marker.backup) + ? join(userDataPath, IDENTITY_BACKUPS_DIRNAME, marker.backup) + : null + for (const { live, staged } of stagedIdentityPaths(userDataPath)) { + if (!existsSync(staged)) { + continue + } + backUpLiveFile(live, backupDir) + try { + renameSync(staged, live) + } catch (error) { + if (!isMissing(error)) { + throw error + } + } + } + bestEffortFsyncDirectorySync(userDataPath) + write(join(userDataPath, HOST_INSTANCE_FILENAME), markerFor(marker.instanceId)) + pruneIdentityBackups(userDataPath, marker.backup) +} + +/** + * New keypair, no paired devices, new installation id. Callers must hold the profile lock. + * Without `instanceId` the recorded id is kept, so a manual reset never forgets it. + * Throws HostIdentityRotationNotStartedError when the old identity is still whole; any other + * error means the next start must finish the rotation before serving. + */ +export function rotateHostIdentity( + userDataPath: string, + instanceId: string | null = hostInstanceIdFromEnv(), + write: HostIdentityWrite = writeDurableSecureJsonFile, + now: () => Date = () => new Date() +): void { + const markerPath = join(userDataPath, HOST_INSTANCE_FILENAME) + let stored: HostInstanceMarker | null + try { + stored = readMarker(markerPath) + } catch (error) { + throw new HostIdentityRotationNotStartedError(error) + } + const finishedEarlierRotation = !!stored?.rotating + if (stored?.rotating) { + // Staging below reuses the `.next` paths, so an earlier rotation must be finished first. + publishStagedIdentity(userDataPath, stored, write) + } + // After finishing an earlier rotation the identity is already new and was never served, which + // is what a reset asks for; reporting "nothing changed" would be false. + const notStarted = (error: unknown): void => { + discardStagedIdentity(userDataPath) + if (!finishedEarlierRotation) { + throw new HostIdentityRotationNotStartedError(error) + } + } + const marker: HostInstanceMarker = { + ...markerFor(instanceId ?? stored?.instanceId), + rotating: true, + backup: newBackupName(now()) + } + try { + stageNewIdentity(userDataPath, write) + } catch (error) { + notStarted(error) + return + } + try { + write(markerPath, marker) + } catch (error) { + // The write can fail after its rename (directory sync); a published `rotating` marker + // needs the staged files, so only discard them once the marker is known not to say so. + let onDisk: HostInstanceMarker | null + try { + onDisk = readMarker(markerPath) + } catch { + throw error + } + if (!onDisk?.rotating) { + notStarted(error) + return + } + } + publishStagedIdentity(userDataPath, marker, write) +} + +/** + * Rotates only when ORCA_INSTANCE_ID is set and differs from the id recorded with this identity. + * Unset never rotates; the first id seen is recorded so adopting the variable keeps pairings. + * Throws only when a started rotation cannot be finished, so old and new files may be mixed. + */ +export function ensureHostInstanceIdentity( + userDataPath: string, + instanceId: string | null = hostInstanceIdFromEnv(), + write: HostIdentityWrite = writeDurableSecureJsonFile +): HostIdentityOutcome { + const markerPath = join(userDataPath, HOST_INSTANCE_FILENAME) + const stored = readMarker(markerPath) + if (stored?.rotating) { + publishStagedIdentity( + userDataPath, + { instanceId: instanceId ?? stored.instanceId, backup: stored.backup }, + write + ) + return { kind: 'rotated', reason: 'interrupted_rotation' } + } + if (!instanceId || stored?.instanceId === instanceId) { + return { kind: 'unchanged' } + } + if (!stored?.instanceId) { + try { + write(markerPath, markerFor(instanceId)) + } catch (error) { + return { kind: 'kept', error } + } + return { kind: 'recorded' } + } + try { + rotateHostIdentity(userDataPath, instanceId, write) + } catch (error) { + if (error instanceof HostIdentityRotationNotStartedError) { + return { kind: 'kept', error } + } + throw error + } + return { kind: 'rotated', reason: 'instance_changed' } +} diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index e37156142cd..7126bd28a12 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -12,7 +12,7 @@ import { runtimeBrowserCommandsFactorySupportsClientHosting, runtimeBrowserUnavailableCause } from '../browser/installation/runtime-browser-commands-factory' -import { isBrowserIdentityModeStoreInitialized } from '../../browser/identity/browser-identity-mode-store' +import { isBrowserIdentityModeStoreInitialized } from '../../browser/identity/mode/browser-identity-mode-store' import { servesLocalWslMigrationSource } from '../../orcad/orcad-migration-wsl-destination' import { ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY } from '../../../shared/orcad-runtime-capabilities' import { advertisedOrcadMigrationDestinationCapabilities } from '../../orcad/orcad-migration-destination-capabilities' diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts index b134747fe0b..a43d8abd3d7 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts @@ -204,7 +204,7 @@ describe('RelayControlClient', () => { const { socket, authorization, capabilities, path } = await accepted expect(authorization).toBe('Bearer scoped-token') // Strict older cells reject new hello keys; advertise capabilities in upgrade headers. - expect(capabilities).toBe('pending-conn-details,idle-regional-rehome-v1') + expect(capabilities).toBe('pending-conn-details,idle-regional-rehome-v1,client-keepalive-v1') expect(path).toBe('/v1/host/control') const hello = await nextJson(socket) expect(hello).toMatchObject({ @@ -274,6 +274,13 @@ describe('RelayControlClient', () => { // ast-grep-ignore: test-no-wall-clock -- Real loopback protocol timestamps must match the client clock. socket.send(JSON.stringify({ type: 'ping', t: Date.now() })) await expect(nextJson(socket)).resolves.toMatchObject({ type: 'pong' }) + // Offered: the host sends the exact keepalive frame (the edge answers it without waking). + socket.send(JSON.stringify({ type: 'keepalive-offer', v: 1, intervalMs: 1_000 })) + const keepalive = await new Promise((resolve) => { + socket.once('message', (raw) => resolve(raw.toString())) + }) + expect(keepalive).toBe('{"type":"keepalive"}') + socket.send('{"type":"keepalive-ack"}') socket.send( JSON.stringify({ type: 'conn-open', diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts b/src/main/runtime/mobile-cloud-relay/relay-control-client.ts index 0744919c9d2..e5227a79034 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-control-client.ts @@ -9,7 +9,6 @@ import { RelayDrainMessageSchema, RelayHostChallengeMessageSchema, RelayHostHelloAckMessageSchema, - RelayPingMessageSchema, RELAY_HOST_CAPABILITY_HEADERS, encodeRelayHostHello, parseRelayControlMessage, @@ -48,6 +47,7 @@ export class RelayControlClient { this.liveness = new RelayControlLiveness({ cellUrl: this.relayOrigin, ping: () => this.socket?.ping(), + send: (frame) => this.socket?.send(frame), isLive: () => this.isLive(), terminate: () => this.socket?.terminate(), random: options.livenessRandom @@ -207,8 +207,7 @@ export class RelayControlClient { this.failProtocol('control message before activation') return } - if (RelayPingMessageSchema.safeParse(message).success) { - this.socket?.send(JSON.stringify({ type: 'pong', t: message.t })) + if (this.liveness.handleLivenessMessage(message)) { return } const connection = RelayConnectionOpenMessageSchema.safeParse(message) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts new file mode 100644 index 00000000000..aa103136bdb --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts @@ -0,0 +1,62 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { RelayControlLiveness } from './relay-control-liveness' + +describe('RelayControlLiveness keepalive', () => { + afterEach(() => { + vi.useRealTimers() + }) + + function liveness(live = { value: true }) { + const terminate = vi.fn() + // The relay's ack is an inbound frame. + const sendKeepalive = vi.fn((frame: string) => { + expect(frame).toBe('{"type":"keepalive"}') + instance.noteInbound() + }) + const instance: RelayControlLiveness = new RelayControlLiveness({ + cellUrl: 'https://relay.test', + ping: vi.fn(), + isLive: () => live.value, + terminate, + send: sendKeepalive + }) + return { instance, sendKeepalive, terminate, live } + } + + it('sends a keepalive instead of tearing down when its own timers were held back', () => { + vi.useFakeTimers() + const terminate = vi.fn() + const send = vi.fn() + const instance = new RelayControlLiveness({ + cellUrl: 'https://relay.test', + ping: vi.fn(), + isLive: () => true, + terminate, + send + }) + instance.start() + instance.startKeepalive(25_000) + // A throttled app: no timer ran for 100 s, then the silence check runs before the keepalive. + vi.setSystemTime(Date.now() + 100_000) + vi.advanceTimersToNextTimer() + expect(terminate).not.toHaveBeenCalled() + expect(send).toHaveBeenCalledWith('{"type":"keepalive"}') + // Still unanswered at a later check: the link is judged dead as before. + vi.advanceTimersByTime(80_000) + expect(terminate).toHaveBeenCalledOnce() + }) + + it('ignores an offer before the control is active and stops with the control', () => { + vi.useFakeTimers() + const { instance, sendKeepalive } = liveness() + instance.startKeepalive(25_000) + vi.advanceTimersByTime(50_000) + expect(sendKeepalive).not.toHaveBeenCalled() + instance.start() + instance.startKeepalive(25_000) + instance.stop() + vi.advanceTimersByTime(100_000) + expect(sendKeepalive).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts index 9368f4f4660..1d85b1431a0 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts @@ -1,5 +1,11 @@ import type { RelayControlRequestTimeout } from './relay-control-requests' import { RELAY_RENEWAL_JITTER_RATIO } from './relay-renewal-jitter' +import { + RELAY_CLIENT_KEEPALIVE_FRAME, + RelayKeepaliveAckMessageSchema, + RelayKeepaliveOfferMessageSchema, + RelayPingMessageSchema +} from './relay-control-protocol' // STA-7672: request timeout may be relay load or half-open TCP; probe before inferring death. @@ -19,6 +25,7 @@ type TeardownReason = 'probe-unanswered' | 'silence-limit' export type RelayControlLivenessOptions = { cellUrl: string ping: () => void + send?: (frame: string) => void isLive: () => boolean terminate: () => void random?: () => number @@ -28,6 +35,8 @@ export class RelayControlLiveness { private readonly random: () => number private probe: { timer: ReturnType; misses: number } | null = null private silenceTimer: ReturnType | null = null + private keepaliveTimer: ReturnType | null = null + private keepaliveSentAt = 0 private openedAt = 0 private lastInboundAt = 0 @@ -40,6 +49,12 @@ export class RelayControlLiveness { this.lastInboundAt = this.openedAt this.silenceTimer = setInterval(() => { if (Date.now() - this.lastInboundAt > SILENCE_LIMIT_MS) { + // Our own keepalive timer was held back too (a throttled app), so the silence says nothing + // about the link: send one now and judge on the next check. + if (this.keepaliveTimer && Date.now() - this.keepaliveSentAt > SILENCE_LIMIT_MS) { + this.sendKeepalive() + return + } this.tearDown('silence-limit') } }, SILENCE_CHECK_INTERVAL_MS) @@ -56,11 +71,48 @@ export class RelayControlLiveness { this.clearProbe() } + /** Relay pings, the keepalive offer and its acks; the caller already counted them as inbound. */ + handleLivenessMessage(message: Record): boolean { + const ping = RelayPingMessageSchema.safeParse(message) + if (ping.success) { + this.options.send?.(JSON.stringify({ type: 'pong', t: ping.data.t })) + return true + } + const offer = RelayKeepaliveOfferMessageSchema.safeParse(message) + if (offer.success) { + this.startKeepalive(offer.data.intervalMs) + return true + } + return RelayKeepaliveAckMessageSchema.safeParse(message).success + } + + // The relay offered the host-sent keepalive: its answer is an inbound frame, so it keeps the + // silence bound met without relay pings. Relays that never offer keep pinging as before. + startKeepalive(intervalMs: number): void { + if (this.keepaliveTimer || !this.silenceTimer || !this.options.send) { + return + } + this.keepaliveSentAt = Date.now() + this.keepaliveTimer = setInterval(() => this.sendKeepalive(), intervalMs) + this.keepaliveTimer.unref?.() + } + + private sendKeepalive(): void { + if (this.options.isLive()) { + this.keepaliveSentAt = Date.now() + this.options.send?.(RELAY_CLIENT_KEEPALIVE_FRAME) + } + } + stop(): void { if (this.silenceTimer) { clearInterval(this.silenceTimer) this.silenceTimer = null } + if (this.keepaliveTimer) { + clearInterval(this.keepaliveTimer) + this.keepaliveTimer = null + } this.clearProbe() } diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts b/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts index d1609c628b9..a0fca00db85 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts @@ -30,9 +30,13 @@ const ConnectionKindSchema = z.enum(['invite', 'resume']) // Strict deployed cells reject new hello keys; mirror contract capabilities in upgrade headers. export const RELAY_HOST_CAPABILITY_HEADERS = { - 'x-orca-host-capabilities': 'pending-conn-details,idle-regional-rehome-v1' + 'x-orca-host-capabilities': 'pending-conn-details,idle-regional-rehome-v1,client-keepalive-v1' } as const +// Mirror relay-contract RELAY_CLIENT_KEEPALIVE_*: sent only after a relay's keepalive-offer. The +// relay answers it without waking, so the bytes must match exactly. +export const RELAY_CLIENT_KEEPALIVE_FRAME = '{"type":"keepalive"}' + // Mirror RELAY_PROTOCOL_LIMITS.hostAttachDeadlineMs, the phone's data-socket attach window. export const RELAY_HOST_ATTACH_DEADLINE_MS = 10_000 @@ -85,6 +89,18 @@ export const RelayPingMessageSchema = z .object({ type: z.literal('ping'), t: EpochMsSchema }) .strict() +export const RelayKeepaliveOfferMessageSchema = z + .object({ + type: z.literal('keepalive-offer'), + v: z.literal(1), + intervalMs: z.number().int().min(1_000).max(60_000) + }) + .strict() + +export const RelayKeepaliveAckMessageSchema = z + .object({ type: z.literal('keepalive-ack') }) + .strict() + export const RelayInviteCreatedMessageSchema = z .object({ type: z.literal('invite-created'), diff --git a/src/main/runtime/multi-client-terminal.integration.test.ts b/src/main/runtime/multi-client-terminal.integration.test.ts new file mode 100644 index 00000000000..3672c1d514a --- /dev/null +++ b/src/main/runtime/multi-client-terminal.integration.test.ts @@ -0,0 +1,423 @@ +import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache' +import type * as WorktreeListingModule from '../git/worktrees/catalog/worktree-listing' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { pairedRuntimeConnectionFromOffer } from '../../shared/remote-runtime/pairing/paired-runtime-connection' +import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' +import { + subscribeRemoteRuntimeRequest, + type RemoteRuntimeSubscription +} from '../../shared/remote-runtime/remote-runtime-client' +import { + TerminalStreamOpcode, + decodeTerminalStreamFrame, + decodeTerminalStreamText, + encodeTerminalStreamFrame, + encodeTerminalStreamJson, + encodeTerminalStreamText +} from '../../shared/terminal/stream/terminal-stream-protocol' +import { OrcaRuntimeService } from './orca-runtime' +import { OrcaRuntimeRpcServer } from './rpc/server/runtime-rpc' +import { readRuntimeMetadata } from './rpc/server/runtime-metadata' +import { sendRequest } from './rpc/server/runtime-rpc-test-harness' +import { makeStore } from './rpc/server/runtime-rpc-worktree-store-fixtures' +import { partialRuntimeStore } from './orca-runtime-tests/runtime-store-partial-fixture' +import { settledWriteStub } from '../providers/settled-pty-write-stub' +import { publishHeadlessRuntimeGraph } from './session-graph/headless-runtime-graph' +import { committingSpawn } from './orca-runtime-tests/bind-first-pane.test-fixture' + +vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ + ...(await importOriginal()), + listWorktrees: getWorktreeListingMocks().listWorktrees +})) + +vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({ + ...(await importOriginal()), + listWorktreesStrict: getWorktreeListingMocks().listWorktreesStrict +})) + +const { getWorktreeListingMocks } = vi.hoisted(() => { + const worktrees = [ + { path: '/tmp/worktree-a', head: 'abc', branch: 'a', isBare: false, isMainWorktree: false } + ] + const listings = { + listWorktrees: vi.fn().mockResolvedValue(worktrees), + listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) + } + return { getWorktreeListingMocks: () => listings } +}) + +const PTY_ID = 'shared-pty' +const SPAWN = { cols: 80, rows: 24 } +const WORKTREE = 'id:repo-1::/tmp/worktree-a' + +type Client = Awaited> +// Pairing handshakes can exceed waitFor's 1s default on a loaded CI worker. +const SLOW_WAIT = { timeout: 5_000 } +// Surfaced in afterEach so a protocol regression fails loudly instead of as a waitFor timeout. +const streamErrors: unknown[] = [] +const StreamResponse = z + .object({ + type: z.string().optional(), + streamId: z.number().optional(), + mode: z.string().optional(), + driver: z.object({ kind: z.string() }).optional() + }) + .loose() +type StreamResponse = z.infer + +async function attach( + pairingUrl: string, + client: { id: string; type: 'desktop' | 'mobile' }, + terminal: string, + viewport: { cols: number; rows: number } +) { + const pairing = parsePairingCode(pairingUrl)! + const responses: StreamResponse[] = [] + const frames: ReturnType[] = [] + const subscription: RemoteRuntimeSubscription = await subscribeRemoteRuntimeRequest( + pairedRuntimeConnectionFromOffer(pairing), + 'terminal.multiplex', + {}, + 15_000, + { + onResponse: (response) => { + const parsed = response.ok ? StreamResponse.safeParse(response.result) : null + if (parsed && !parsed.success) { + streamErrors.push(parsed.error) + } + responses.push(parsed?.success ? parsed.data : {}) + }, + onBinary: (bytes) => frames.push(decodeTerminalStreamFrame(bytes)), + onError: (error) => streamErrors.push(error) + } + ) + await vi.waitFor(() => expect(responses.some((r) => r.type === 'ready')).toBe(true), SLOW_WAIT) + const streamId = 7 + let controlSeq = 0 + let inputSeq = 0 + const inputSessionId = `${client.id}-input-session` + const frame = (opcode: TerminalStreamOpcode, payload: Uint8Array, seq = 0) => + subscription.sendBinary( + encodeTerminalStreamFrame({ + opcode, + streamId: opcode === TerminalStreamOpcode.Subscribe ? 0 : streamId, + seq, + payload + }) + ) + frame( + TerminalStreamOpcode.Subscribe, + encodeTerminalStreamJson({ + streamId, + terminal, + client, + viewport, + // The subset of the renderer multiplexer's capabilities that governs input and sizing. + capabilities: { + ackOutput: 1, + writeUnavailable: 1, + inputAck: 1, + ...(client.type === 'desktop' ? { desktopViewportClaims: 1 } : {}) + }, + inputSessionId + }), + ++controlSeq + ) + await vi.waitFor( + () => + expect(responses.some((r) => r.type === 'subscribed' && r.streamId === streamId)).toBe(true), + SLOW_WAIT + ) + return { + client, + frames, + responses, + fitMode: () => responses.findLast((r) => r.type === 'fit-override-changed')?.mode, + driver: () => responses.findLast((r) => r.type === 'driver-changed')?.driver?.kind, + inputAcks: () => frames.filter((f) => f?.opcode === TerminalStreamOpcode.InputAck).length, + type: (text: string) => + frame(TerminalStreamOpcode.Input, encodeTerminalStreamText(text), ++inputSeq), + resize: (cols: number, rows: number) => + frame(TerminalStreamOpcode.Resize, encodeTerminalStreamJson({ cols, rows })), + // Desktop/web panes claim before resizing when the user focuses/types. + claim: (cols: number, rows: number) => { + frame(TerminalStreamOpcode.ClaimViewport, encodeTerminalStreamJson({ cols, rows })) + frame(TerminalStreamOpcode.Resize, encodeTerminalStreamJson({ cols, rows })) + }, + output: () => + frames + .filter((f) => f?.opcode === TerminalStreamOpcode.Output && f.streamId === streamId) + .map((f) => decodeTerminalStreamText(f!.payload)) + .join(''), + close: () => subscription.close() + } +} + +// Desktop app, web client and phone attach to one `orca serve`-style runtime through the shared remote-runtime client. +describe('multiple clients on one headless runtime', () => { + const cleanups: (() => unknown)[] = [] + afterEach(async () => { + const errors = streamErrors.splice(0) + for (const cleanup of cleanups.splice(0).toReversed()) { + await cleanup() + } + expect(errors).toEqual([]) + }) + + async function start() { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-multi-client-')) + cleanups.push(() => rmSync(userDataPath, { recursive: true, force: true })) + const writes: string[] = [] + const sizes: { cols: number; rows: number }[] = [SPAWN] + // Headless: no notifier/window, like `orca serve`. + const runtime = new OrcaRuntimeService(partialRuntimeStore(makeStore())) + runtime.setPtyController({ + spawn: committingSpawn(runtime, vi.fn().mockResolvedValue({ id: PTY_ID })), + write: (_ptyId, data) => { + writes.push(data) + return true + }, + writeWithSettlement: settledWriteStub((_ptyId, data) => { + writes.push(data) + }), + resize: (_ptyId, cols, rows) => { + sizes.push({ cols, rows }) + return true + }, + kill: () => true, + getForegroundProcess: async () => null + }) + publishHeadlessRuntimeGraph(runtime) + // Counts viewer departures the runtime has finished handling, so "everyone left" is observed, not slept on. + let viewerLeaves = 0 + const unregister = runtime.unregisterRemoteDesktopViewers.bind(runtime) + vi.spyOn(runtime, 'unregisterRemoteDesktopViewers').mockImplementation(async (...args) => { + try { + return await unregister(...args) + } finally { + viewerLeaves++ + } + }) + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + await server.start() + cleanups.push(() => server.stop()) + const pair = (name: string, scope: 'runtime' | 'mobile') => { + const offer = server.createPairingOffer({ address: '127.0.0.1', name, scope }) + if (!offer.available) { + throw new Error('pairing unavailable') + } + return offer.pairingUrl + } + const desktopUrl = pair('desktop', 'runtime') + const metadata = readRuntimeMetadata(userDataPath)! + const created = await sendRequest(metadata.transports[0]!.endpoint, { + id: 'create', + authToken: metadata.authToken, + method: 'terminal.create', + params: { + worktree: WORKTREE, + command: 'shell', + tabId: 'tab-1', + leafId: '11111111-1111-4111-8111-111111111111', + cols: SPAWN.cols, + rows: SPAWN.rows + } + }) + const handle = z.object({ terminal: z.object({ handle: z.string() }) }).parse(created.result) + .terminal.handle + const joinClient = async ( + url: string, + client: { id: string; type: 'desktop' | 'mobile' }, + viewport: { cols: number; rows: number } + ) => { + const attached = await attach(url, client, handle, viewport) + cleanups.push(() => attached.close()) + return attached + } + return { + runtime, + writes, + sizes, + size: () => sizes.at(-1)!, + viewerLeaves: () => viewerLeaves, + desktopUrl, + webUrl: pair('web', 'runtime'), + phoneUrl: pair('phone', 'mobile'), + join: joinClient, + handle, + endpoint: metadata.transports[0]!.endpoint, + authToken: metadata.authToken + } + } + + async function typed(client: Client, text: string) { + const acks = client.inputAcks() + client.type(text) + await vi.waitFor(() => expect(client.inputAcks()).toBeGreaterThan(acks)) + } + + it('fans output out to every client and gives size to the last deliberate typist', async () => { + const h = await start() + const desktop = await h.join( + h.desktopUrl, + { id: 'desktop', type: 'desktop' }, + { cols: 200, rows: 50 } + ) + const web = await h.join(h.webUrl, { id: 'web', type: 'desktop' }, { cols: 120, rows: 40 }) + const script = await h.join( + h.webUrl, + { id: 'script', type: 'desktop' }, + { cols: 100, rows: 30 } + ) + // Attaching only observes geometry. + expect(h.size()).toEqual(SPAWN) + + h.runtime.onPtyData(PTY_ID, 'shared-output\r\n', 1) + await vi.waitFor(() => + expect([desktop, web, script].map((c) => c.output().includes('shared-output'))).toEqual([ + true, + true, + true + ]) + ) + + desktop.claim(200, 50) + await typed(desktop, 'd1') + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + await vi.waitFor(() => + expect([desktop.fitMode(), web.fitMode()]).toEqual(['desktop-fit', 'remote-desktop-fit']) + ) + + web.claim(120, 40) + await typed(web, 'w1') + expect(h.size()).toEqual({ cols: 120, rows: 40 }) + await vi.waitFor(() => + expect([desktop.fitMode(), web.fitMode()]).toEqual(['remote-desktop-fit', 'desktop-fit']) + ) + + // Unclaimed input and passive resizes from a non-owner neither move nor block the size. + await typed(desktop, 'd2') + desktop.resize(210, 55) + await typed(desktop, 'd3') + expect(h.size()).toEqual({ cols: 120, rows: 40 }) + expect(h.writes).toEqual(['d1', 'w1', 'd2', 'd3']) + + // Two typists who both claim, taking turns: the PTY grid flips on every turn. + for (let i = 0; i < 5; i++) { + desktop.claim(200, 50) + await typed(desktop, `a${i}`) + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + web.claim(120, 40) + await typed(web, `b${i}`) + expect(h.size()).toEqual({ cols: 120, rows: 40 }) + } + expect(h.writes.slice(4)).toEqual(['a0', 'b0', 'a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'b4']) + + // The same race without waiting: each client's own order survives and the grid only ever + // lands on one of the two claimed sizes. Cross-client interleaving is not guaranteed. + const burstStart = h.sizes.length + for (let i = 0; i < 5; i++) { + desktop.claim(200, 50) + desktop.type(`c${i}`) + web.claim(120, 40) + web.type(`e${i}`) + } + await vi.waitFor(() => expect(h.writes).toHaveLength(24)) + const burst = h.writes.slice(14) + expect(burst.filter((w) => w.startsWith('c'))).toEqual(['c0', 'c1', 'c2', 'c3', 'c4']) + expect(burst.filter((w) => w.startsWith('e'))).toEqual(['e0', 'e1', 'e2', 'e3', 'e4']) + for (const size of h.sizes.slice(burstStart)) { + expect([ + { cols: 200, rows: 50 }, + { cols: 120, rows: 40 } + ]).toContainEqual(size) + } + }) + + it('moves size to the remaining active client when the owner drops, and a reconnect stays passive', async () => { + const h = await start() + const desktop = await h.join( + h.desktopUrl, + { id: 'desktop', type: 'desktop' }, + { cols: 200, rows: 50 } + ) + const web = await h.join(h.webUrl, { id: 'web', type: 'desktop' }, { cols: 120, rows: 40 }) + desktop.claim(200, 50) + await typed(desktop, 'd1') + web.claim(120, 40) + await typed(web, 'w1') + expect(h.size()).toEqual({ cols: 120, rows: 40 }) + + // A network blip on the owning web client resizes the PTY for everyone. + web.close() + await vi.waitFor(() => expect(h.size()).toEqual({ cols: 200, rows: 50 })) + const webAgain = await h.join(h.webUrl, { id: 'web', type: 'desktop' }, { cols: 120, rows: 40 }) + await vi.waitFor(() => expect(webAgain.fitMode()).toBe('remote-desktop-fit')) + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + + webAgain.claim(120, 40) + await typed(webAgain, 'w2') + expect(h.size()).toEqual({ cols: 120, rows: 40 }) + + // Headless runtimes keep the last owner's grid once every viewer leaves. + // Close one at a time: two sockets closing together race on which leave the server sees first. + const leavesBefore = h.viewerLeaves() + webAgain.close() + await vi.waitFor(() => expect(h.viewerLeaves()).toBe(leavesBefore + 1), SLOW_WAIT) + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + const resizesBeforeLastLeave = h.sizes.length + desktop.close() + await vi.waitFor(() => expect(h.viewerLeaves()).toBe(leavesBefore + 2), SLOW_WAIT) + expect(h.sizes.length).toBe(resizesBeforeLastLeave) + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + }) + + it('lets a passively attached phone take the floor from every desktop until take-back', async () => { + const h = await start() + const desktop = await h.join( + h.desktopUrl, + { id: 'desktop', type: 'desktop' }, + { cols: 200, rows: 50 } + ) + const web = await h.join(h.webUrl, { id: 'web', type: 'desktop' }, { cols: 120, rows: 40 }) + desktop.claim(200, 50) + await typed(desktop, 'd1') + + const phone = await h.join(h.phoneUrl, { id: 'phone', type: 'mobile' }, { cols: 50, rows: 30 }) + await vi.waitFor(() => expect(h.size()).toEqual({ cols: 50, rows: 30 })) + await vi.waitFor(() => expect([desktop.driver(), web.driver()]).toEqual(['mobile', 'mobile'])) + + // Desktop and web input is acknowledged but dropped while the phone drives. + await typed(desktop, 'd2') + await typed(web, 'w2') + await typed(phone, 'p1') + expect(h.writes).toEqual(['d1', 'p1']) + + const takeBack = await sendRequest(h.endpoint, { + id: 'take-back', + authToken: h.authToken, + method: 'terminal.restoreFit', + params: { terminal: h.handle } + }) + expect(takeBack.result).toEqual({ restored: true }) + expect(h.size()).toEqual({ cols: 200, rows: 50 }) + await typed(desktop, 'd3') + + // Deliberate phone input takes the floor straight back. + await typed(phone, 'p2') + expect(h.size()).toEqual({ cols: 50, rows: 30 }) + expect(h.writes).toEqual(['d1', 'p1', 'd3', 'p2']) + + phone.close() + await vi.waitFor(() => expect(h.size()).toEqual({ cols: 200, rows: 50 })) + }) +}) diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index e2543fea2fa..dfd87d389f6 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -272,7 +272,7 @@ vi.mock('../../preflight/agent-detection', () => ({ detectInstalledAgentsWithShellPathHydration: detectInstalledAgentsWithShellPathHydrationMock })) -vi.mock('../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) diff --git a/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts index 5c4c9cff6fe..e1af126a9aa 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts @@ -3,7 +3,7 @@ import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) diff --git a/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts index d7da23283b4..b438293f2a8 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../telemetry/cohort-classifier', () => ({ diff --git a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts index 06cb7f5ca5f..5138af1f54a 100644 --- a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts +++ b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts @@ -14,7 +14,12 @@ import type { Party } from './crew-parties' import { crewParentRelations } from './crew-parent-relations' import { createCrewHostDerivation } from './crew-host-derivation' import { statusForFleetWorker } from '../../../../shared/orchestration/fleet/orchestration-fleet-status-index' -import { projectLiveness } from '../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection' +import { + projectLiveness, + sessionActivityEvidence +} from '../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection' +import { createSessionWorkerLivenessReader } from '../workers/lifecycle/session-worker-liveness' +import { isStructuredWorkerHandle } from '../../../../shared/orchestration/workers/structured-worker-handle' import { federatedMessageNamesOnlyHome } from '../workers/reports/dispatch-report-mailbox' import { workerReportRefusal } from '../workers/reports/worker-report-admission' import { isEquivalentPaneKey } from '../db/pane-key-match' @@ -50,6 +55,7 @@ export function buildCrewSnapshot( const { party, alias, addressOf, getParty, aliasesFor } = registry const records = host.deps.records const runningSession = createLineageRunningSessionResolver(records) + const observeSession = createSessionWorkerLivenessReader(db, host.deps.statuses, records) const hydrate = (addresses: string[], panes: string[] = []) => { const provenance = host.sourceInputs.provenance(addresses, panes) for (const family of [provenance.local, provenance.remote]) { @@ -149,8 +155,13 @@ export function buildCrewSnapshot( evidence.binding.terminalHandle === target.terminalHandle && evidence.binding.paneKey === target.paneKey && (evidence.binding.kind !== 'worker' || evidence.binding.dispatchId === assignment?.id))) - const fresh = - bound && projectLiveness({ resource: null }, evidence, now).verdict === 'live' + // Chats keep their own status row: their reach check queries SQLite on every Crew rebuild. + const session = isStructuredWorkerHandle(worker?.agentTerminalHandle) + ? observeSession(worker!) + : undefined + const fresh = session + ? sessionActivityEvidence(session) + : bound && projectLiveness({ resource: null }, evidence, now).verdict === 'live' ? evidence : undefined const row: OrchestrationCrewRow = { diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts index f63c8a46b64..5653a51832f 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-projection.ts @@ -19,6 +19,10 @@ import { isRecentPresentationDispatch } from '../db/dispatch-context/dispatch-lo import { currentRunCoordinatorOrcaSessionId } from '../db/runs/run-coordinator-orca-session' import type { DispatchContextRow } from '../db/orchestration-records' import type { PtyPaneOf } from '../../terminal/surface/pty-pane-query' +import { + createDispatchSessionLivenessReader, + type DispatchSessionObserver +} from '../workers/lifecycle/session-worker-liveness' export type RuntimeAgentOrchestrationDependencies = { getDb(): OrchestrationDb | null @@ -36,6 +40,14 @@ export type RuntimeAgentOrchestrationDependencies = { getSessionRecords(): AgentSessionRecordReader | null } +type DispatchProjectionOptions = { + // Handles are process-local; pane identity still names the Dispatch after restart. + paneKey?: string + evidence?: FleetAgentStatusEvidence + observeSession?: DispatchSessionObserver + deferAttention?: boolean +} + export class RuntimeAgentOrchestrationProjection { constructor(private readonly deps: RuntimeAgentOrchestrationDependencies) {} @@ -46,9 +58,12 @@ export class RuntimeAgentOrchestrationProjection { } const scope = createOrchestrationProjectionScope(db, this.deps) const contexts: Record = {} + const statuses = this.deps.getAgentStatusSnapshot() const evidenceByPaneKey = new Map( - this.deps.getAgentStatusSnapshot().map((evidence) => [evidence.activity.paneKey, evidence]) + statuses.map((evidence) => [evidence.activity.paneKey, evidence]) ) + const sessions = createDispatchSessionLivenessReader(db, statuses, scope.records) + const observeSession = sessions.observe // Batch attention queries below; per-pane reads would repeat every 16ms publication. const batchAttention = typeof db.getWorkerAttentionFactsForDispatches === 'function' const queriedHandles = new Set() @@ -65,6 +80,7 @@ export class RuntimeAgentOrchestrationProjection { { paneKey, evidence: evidenceByPaneKey.get(paneKey), + observeSession, deferAttention: batchAttention }, scope @@ -89,6 +105,7 @@ export class RuntimeAgentOrchestrationProjection { { paneKey, evidence: evidenceByPaneKey.get(paneKey), + observeSession, deferAttention: batchAttention }, scope @@ -106,6 +123,7 @@ export class RuntimeAgentOrchestrationProjection { { paneKey, evidence: evidenceByPaneKey.get(paneKey), + observeSession, deferAttention: batchAttention }, scope @@ -131,6 +149,7 @@ export class RuntimeAgentOrchestrationProjection { facts, isRoot: facts.isRoot, evidence: evidenceByPaneKey.get(paneKey), + session: sessions.observed(context.dispatchId), now }) } @@ -143,12 +162,7 @@ export class RuntimeAgentOrchestrationProjection { getForHandle( handle: string, db = this.deps.getDb(), - options: { - // Handles are process-local; pane identity still names the Dispatch after restart. - paneKey?: string - evidence?: FleetAgentStatusEvidence - deferAttention?: boolean - } = {}, + options: DispatchProjectionOptions = {}, scope = createOrchestrationProjectionScope(db, this.deps) ): AgentStatusOrchestrationContext | undefined { const { paneKey } = options @@ -164,10 +178,11 @@ export class RuntimeAgentOrchestrationProjection { dispatch: DispatchContextRow, handle: string, db: OrchestrationDb | null, - options: { paneKey?: string; evidence?: FleetAgentStatusEvidence; deferAttention?: boolean }, + options: DispatchProjectionOptions, scope: ReturnType ): AgentStatusOrchestrationContext { const { paneKey, evidence, deferAttention = false } = options + const session = options.observeSession?.(dispatch) const task = scope.task(dispatch.task_id, dispatch.run_id) const display = crewTaskDisplay(task) const owningRun = @@ -273,7 +288,7 @@ export class RuntimeAgentOrchestrationProjection { ) ?? {} const attention = !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' - ? buildWorkerAttentionContext({ db, dispatch, task, evidence, now: scope.now }) + ? buildWorkerAttentionContext({ db, dispatch, task, evidence, session, now: scope.now }) : undefined return { taskId: dispatch.task_id, diff --git a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts index 0d09c93f41a..b00b5da501a 100644 --- a/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts +++ b/src/main/runtime/orchestration/crew/runtime-agent-orchestration-scope.ts @@ -11,9 +11,11 @@ export function createOrchestrationProjectionScope( const runs = new Map>() const panes = new Map>() const now = Date.now() - const resolve = createCanonicalSessionPaneResolver(deps.getSessionRecords()) + const records = deps.getSessionRecords() + const resolve = createCanonicalSessionPaneResolver(records) return { now, + records, resolve, sessionDispatches: () => { const destinations = new Map< diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-claim.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-claim.ts new file mode 100644 index 00000000000..c59c5a39b4a --- /dev/null +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-claim.ts @@ -0,0 +1,52 @@ +import { OrchestrationError } from '../../orchestration-error' +import type { OrchestrationDb } from '../orchestration-db' +import type { DispatchContextRow } from '../orchestration-records' +import type { OrcaRuntimeService } from '../../../orca-runtime' + +// A starting Dispatch names its terminal only in its start options until its authority attaches. +// A start stranded by a runtime restart is racing nothing, so only this runtime's starts claim. +const STARTING_ON_TERMINAL_SQL = `SELECT d.* FROM dispatch_contexts d + JOIN worker_dispatches w ON w.dispatch_id = d.id + WHERE d.status = 'pending' AND w.state = 'starting' AND w.runtime_epoch = ? + AND json_extract(w.start_options, '$.terminal') = ? + ORDER BY d.rowid LIMIT 1` + +/** Refuse a worker-start or follow-up onto a terminal another open Dispatch holds or is starting on. + * worker-start and the follow-up a send starts both claim through here, so whichever comes second is refused before any wait. */ +export function refuseClaimedWorkerTerminal( + db: OrchestrationDb, + handle: string | undefined, + runtime: Pick, + /** A racing follow-up of the same settled Dispatch is left to `follow_up_claimed`, which steers the send into it. */ + followUpOf: string | undefined +): void { + if (!handle) { + return + } + const open = + db.findActiveDispatchForAssignee(handle, runtime.getTerminalPaneKey(handle) ?? undefined) ?? + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: selects whole dispatch_contexts rows. + (db.db.prepare(STARTING_ON_TERMINAL_SQL).get(runtime.getRuntimeId(), handle) as + | DispatchContextRow + | undefined) + if (open && !(followUpOf && open.follow_up_of_dispatch_id === followUpOf)) { + throw terminalBusyError(db, handle, open) + } +} + +function terminalBusyError( + db: OrchestrationDb, + handle: string, + open: DispatchContextRow +): OrchestrationError { + const task = db.getTask(open.task_id) + const title = task?.task_title ?? task?.spec.split('\n')[0]?.slice(0, 80) + const followUp = open.follow_up_of_dispatch_id + ? `, the follow-up of Dispatch ${open.follow_up_of_dispatch_id}` + : '' + return new OrchestrationError( + 'terminal_busy', + `Terminal ${handle} is busy: Dispatch ${open.id}${followUp} (task ${open.task_id}${title ? ` "${title}"` : ''}) is still open on it. To answer it or give it more work, use your Orca CLI's \`orchestration send --to dispatch:${open.id}\`; to replace it, run \`orchestration worker-stop --dispatch ${open.id}\` and then start again. No effects were applied.`, + { effectsApplied: false, dispatchId: open.id, taskId: open.task_id } + ) +} diff --git a/src/main/runtime/orchestration/mailbox/formatting/message-formatting.ts b/src/main/runtime/orchestration/mailbox/formatting/message-formatting.ts index 436482442f7..bd1112261b0 100644 --- a/src/main/runtime/orchestration/mailbox/formatting/message-formatting.ts +++ b/src/main/runtime/orchestration/mailbox/formatting/message-formatting.ts @@ -2,6 +2,10 @@ import type { MessageRow } from '../../db/orchestration-records' import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' import type { OrchestrationCliCommand } from '../../workers/launch/orchestration-cli-command' import type { OrchestrationMailContent } from '../../../../../shared/agent-session/agent-session-message-source' +import { + formatReportFollowUpLine, + type ReportFollowUpAction +} from '../../../../../shared/orchestration/mailbox/orchestration-report-follow-up' const BANNER_WIDTH = 60 const SEPARATOR = '─'.repeat(BANNER_WIDTH) @@ -17,6 +21,8 @@ export type MessageFormattingOptions = { supportedActionHints?: readonly string[] /** The CLI name the recipient runs; a chat's reply line must name the one it has. */ cliCommand?: OrchestrationCliCommand + /** A finished task's report offers its follow-up instead of a reply its worker would never read. */ + followUp?: ReportFollowUpAction } function resolveAuthority( @@ -96,7 +102,9 @@ export function formatMessageBannerWithContent( const body = msg.body ? appendField(msg.body) : undefined const payload = msg.payload ? appendField(msg.payload, '[Payload: ', ']') : undefined - if (authority === 'current') { + if (authority === 'current' && options.followUp) { + lines.push(`[${formatReportFollowUpLine(options.followUp, options.cliCommand ?? 'orca')}]`) + } else if (authority === 'current') { const explicitFrom = msg.to_handle.startsWith('run:') || msg.to_handle.startsWith('dispatch:') ? '' diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts index 70f4e6d1356..ece9005e896 100644 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-custody.ts @@ -171,7 +171,7 @@ export async function settleStructuredMailSends(input: { switch (state.kind) { case 'accepted': // A pointer's handover shows the agent none of an oversized message; `check` still has it. - retire(unread !== undefined && structuredMailFitsWhole(unread, input.cliCommand)) + retire(unread !== undefined && structuredMailFitsWhole(db, unread, input.cliCommand)) continue case 'unknown': // It may have reached the agent: never sent again; `check` still returns it. diff --git a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts index 1645f36a11f..5f432be1a32 100644 --- a/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts +++ b/src/main/runtime/orchestration/mailbox/structured-mail/structured-mail-source.ts @@ -13,6 +13,7 @@ import type { OrchestrationDb } from '../../db/orchestration-db' import { agentMessageRelation } from '../senders/agent-message-relation' import { agentMessageSender, type SenderSnapshotResolver } from '../senders/agent-message-sender' import type { OrchestrationCliCommand } from '../../workers/launch/orchestration-cli-command' +import { completionReportFollowUp } from '../../workers/reports/report-follow-up-action' import { formatMessageBanner, formatMessageBannerWithContent, @@ -117,7 +118,10 @@ export function structuredMailMessage(input: { senderSnapshot: SenderSnapshotResolver }): { body: AgentJournalMessageItem; whole: boolean } { const from = structuredMailSource({ ...input, batch: [input.message] }) - const formatted = formatMessageBannerWithContent(input.message, { cliCommand: input.cliCommand }) + const formatted = formatMessageBannerWithContent(input.message, { + cliCommand: input.cliCommand, + followUp: completionReportFollowUp(input.db, input.message) + }) const whole = [{ type: 'text' as const, text: formatted.text }] if (!structuredAgentSessionBlocksTooLarge(whole)) { return { @@ -148,17 +152,15 @@ export function structuredMailMessage(input: { /** Whether a message goes to a chat whole, rather than as a pointer at `check`. */ export function structuredMailFitsWhole( + db: OrchestrationDb, message: MessageRow, cliCommand: OrchestrationCliCommand ): boolean { - return !structuredAgentSessionBlocksTooLarge(wholeMailBlocks(message, cliCommand)) -} - -function wholeMailBlocks( - message: MessageRow, - cliCommand: OrchestrationCliCommand -): AgentJournalMessageItem['blocks'] { - return [{ type: 'text', text: formatMessageBanner(message, { cliCommand }) }] + const text = formatMessageBanner(message, { + cliCommand, + followUp: completionReportFollowUp(db, message) + }) + return !structuredAgentSessionBlocksTooLarge([{ type: 'text', text }]) } type ReportFact = { kind: 'mail' } | { kind: 'invalid' } | { kind: 'valid'; dispatchId: string } diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts index c6c9eee33b8..c0e79e71901 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import * as pty from 'node-pty' import { expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { getManagedScript } from '../../../../codex/hooks/definitions/codex-hook-script' import { getSyntheticAgentTerminalTitle } from '../../../../../shared/agent-status/title/synthetic-agent-title' import { extractAllOscTitles } from '../../../../../shared/agent-status/title/osc-title-extraction' diff --git a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts index a028dffdac2..e84bf3599bf 100644 --- a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts @@ -12,7 +12,7 @@ import '../db/dispatch-row-writer' import '../db/attempt-outcome-projection' import { createRootDispatch } from '../db/root-dispatch-test-fixture' import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../../orca-runtime' import { makeStore } from '../../rpc/server/runtime-rpc-worktree-store-fixtures' import { spawnedPtyEnv } from '../../terminal/launch/spawned-pty-env-fixtures' diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts index d927830bfe2..e67a0e42c38 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import type { AgentPhase } from '../../../../../shared/agent-status/lifecycle/agent-transitions' import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' import { resolveStructuredWorkerIdentityForSession } from '../structured-sessions/structured-worker-authority' diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts index bd845ca202d..fad7fa3988c 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail-rig.test-fixture.ts @@ -303,7 +303,7 @@ export const WAIT = { timeout: 10_000, interval: 10 } /** A chat got the whole orchestration message: its subject and its reply command. */ export function isWholeMail(text: string): boolean { - return text.includes('\nSubject: ') && /\[Reply: orca(-dev)? orchestration reply --id /.test(text) + return text.includes('\nSubject: ') && /\[[^\]\n]*: orca(-dev)? orchestration /.test(text) } export function turnText(turn: { text: string }): string { diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts index 1419fa48215..7745cf67b03 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-worker-authority.ts @@ -119,7 +119,7 @@ export function isRecordedStructuredWorkerSession( /** The session running this worker now: the one minted for it, or its `/clear` successor. */ export function structuredWorkerSession( identity: Pick, - context?: StructuredWorkerReadContext + context?: Pick ): LineageRunningSession { if (context) { return context.resolveSession(identity.sessionId) @@ -130,7 +130,7 @@ export function structuredWorkerSession( /** The worker's running session on this host, or the typed refusal an actor answers instead. */ function locateStructuredWorker( identity: Pick, - context?: StructuredWorkerReadContext + context?: Pick ): { running: RunningStructuredSession } | { reason: string; refusal: OrchestrationError } { const located = structuredWorkerSession(identity, context) if (located.kind === 'here') { @@ -254,9 +254,10 @@ export function structuredWorkerTerminalState( /** Read the current session's durable liveness without requiring registry identity, which forget removes before some settlement probes. */ export function observeStructuredWorker( - identity: Pick + identity: Pick, + context?: Pick ): StructuredWorkerObservation { - const located = locateStructuredWorker(identity) + const located = locateStructuredWorker(identity, context) return 'running' in located ? observeStructuredSession(located.running.sessionId) : { status: 'unverifiable', reason: located.reason } diff --git a/src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.ts b/src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.ts index db644506184..7a1c5fa9c08 100644 --- a/src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.ts +++ b/src/main/runtime/orchestration/workers/lifecycle/lifecycle-reconciliation.ts @@ -13,7 +13,7 @@ function isSamePane(assigneePaneKey: string, senderPaneKey: string): boolean { return Boolean(assigneeLeaf && senderLeaf && assigneeLeaf === senderLeaf) } -function hasLifecycleAuthority( +export function hasLifecycleAuthority( dispatch: { assignee_handle: string | null; assignee_pane_key: string | null }, msg: MessageRow ): boolean { diff --git a/src/main/runtime/orchestration/workers/lifecycle/session-worker-liveness.ts b/src/main/runtime/orchestration/workers/lifecycle/session-worker-liveness.ts new file mode 100644 index 00000000000..022a30e3a6c --- /dev/null +++ b/src/main/runtime/orchestration/workers/lifecycle/session-worker-liveness.ts @@ -0,0 +1,108 @@ +import type { FleetAgentStatusEvidence } from '../../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' +import type { FleetSessionObservation } from '../../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { isStructuredWorkerHandle } from '../../../../../shared/orchestration/workers/structured-worker-handle' +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { DispatchContextRow } from '../../db/orchestration-records' +import { + createLineageRunningSessionResolver, + readAgentSessionRecordStore, + type AgentSessionRecordReader +} from '../../addressing/session-lineage/structured-session-lineage' +import { + observeStructuredWorker, + resolveStructuredWorkerIdentity +} from '../../terminal-authority/structured-sessions/structured-worker-authority' +import { sessionIdFromStructuredWorkerIncarnation } from '../../terminal-authority/structured-sessions/structured-worker-identity' +import { chatAssigneeSessionId, observeChatAssignee } from './chat-assignee' + +export type SessionWorkerSubject = { + agentTerminalHandle: string | null + resource?: { processIncarnation?: string | null } | null +} + +/** Chat-mode workers' liveness for every fleet surface, from in-memory session records; undefined selects the terminal path. */ +export function createSessionWorkerLivenessReader( + db: OrchestrationDb | null | undefined, + statuses: readonly FleetAgentStatusEvidence[], + records: AgentSessionRecordReader | null = readAgentSessionRecordStore() +): (worker: SessionWorkerSubject) => FleetSessionObservation | undefined { + const resolveSession = createLineageRunningSessionResolver(records) + let statusByPane: Map | undefined + // A session's status row lives at its derived pane key, not the worker's minted one. + const activityFor = (sessionId: string) => { + statusByPane ??= new Map(statuses.map((status) => [status.activity.paneKey, status])) + return statusByPane.get( + structuredAgentSessionPaneKey(structuredAgentSessionTabId(sessionId), sessionId) + ) + } + const live = (sessionId: string): FleetSessionObservation => { + const activity = activityFor(sessionId) + return activity ? { status: 'live', activity } : { status: 'live' } + } + return (worker) => { + const handle = worker.agentTerminalHandle + const chat = chatAssigneeSessionId(handle) + if (chat) { + const observed = observeChatAssignee(chat, db, records) + return observed.status === 'live' + ? live(observed.session.sessionId) + : observed.status === 'exited' + ? { status: 'exited' } + : { status: 'unverifiable', detail: observed.reason } + } + if (!isStructuredWorkerHandle(handle)) { + return undefined + } + const sessionId = + sessionIdFromStructuredWorkerIncarnation(worker.resource?.processIncarnation) ?? + resolveStructuredWorkerIdentity(handle, db)?.sessionId + if (!sessionId) { + return { status: 'unverifiable', detail: 'No session record names this structured worker.' } + } + const observed = observeStructuredWorker({ sessionId }, { resolveSession }) + const running = resolveSession(sessionId) + return observed.status === 'live' + ? live(running.kind === 'here' ? running.sessionId : sessionId) + : observed.status === 'exited' + ? { status: 'exited' } + : { status: 'unverifiable', detail: observed.reason ?? 'The session cannot be verified.' } + } +} + +export type DispatchSessionObserver = ( + dispatch: Pick +) => FleetSessionObservation | undefined + +/** Structured workers' verdicts for per-pane attention, once per Dispatch so the batched pass reads the same one. */ +export function createDispatchSessionLivenessReader( + ...args: Parameters +): { + observe: DispatchSessionObserver + observed: (dispatchId: string) => FleetSessionObservation | undefined +} { + const read = createSessionWorkerLivenessReader(...args) + const byDispatch = new Map() + return { + observe: (dispatch) => { + // A chat's reach check queries SQLite; this runs per publication, so chats keep their status row here. + if (!isStructuredWorkerHandle(dispatch.assignee_handle)) { + return undefined + } + if (!byDispatch.has(dispatch.id)) { + byDispatch.set( + dispatch.id, + read({ + agentTerminalHandle: dispatch.assignee_handle, + resource: { processIncarnation: dispatch.process_incarnation } + }) + ) + } + return byDispatch.get(dispatch.id) + }, + observed: (dispatchId) => byDispatch.get(dispatchId) + } +} diff --git a/src/main/runtime/orchestration/workers/reports/report-follow-up-action.ts b/src/main/runtime/orchestration/workers/reports/report-follow-up-action.ts new file mode 100644 index 00000000000..4a7f0deec10 --- /dev/null +++ b/src/main/runtime/orchestration/workers/reports/report-follow-up-action.ts @@ -0,0 +1,102 @@ +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { DispatchContextRow, MessageRow } from '../../db/orchestration-records' +import { + resolveWorkerLineage, + type WorkerLineage +} from '../../db/dispatch-context/worker-follow-up-lineage' +import { selectWorkerFollowUpPlan } from '../../db/dispatch-context/worker-follow-up-plan' +import { hasLifecycleAuthority } from '../lifecycle/lifecycle-reconciliation' +import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../shared/orchestration/orchestration-rpc-contract' +import type { ReportFollowUpAction } from '../../../../../shared/orchestration/mailbox/orchestration-report-follow-up' + +const isActive = (dispatch: DispatchContextRow) => + dispatch.status === 'pending' || dispatch.status === 'dispatched' + +/** The Dispatch that authored an established completion report: a canonical dispatch: sender, or a + * worker_done the lifecycle accepted. Never inferred from the terminal's current Dispatch. */ +export function completionReportDispatchId( + db: OrchestrationDb, + message: MessageRow +): string | undefined { + if (message.from_handle.startsWith('dispatch:')) { + return message.from_handle.slice('dispatch:'.length) + } + if (message.type !== 'worker_done' || !message.payload) { + return undefined + } + let payload: unknown + try { + payload = JSON.parse(message.payload) + } catch { + return undefined + } + if ( + typeof payload !== 'object' || + payload === null || + '_orcaLifecycleRejection' in payload || + !('dispatchId' in payload) || + typeof payload.dispatchId !== 'string' || + !('taskId' in payload) + ) { + return undefined + } + const dispatch = db.getDispatchContextById(payload.dispatchId) + return dispatch && dispatch.task_id === payload.taskId && hasLifecycleAuthority(dispatch, message) + ? dispatch.id + : undefined +} + +/** Undefined while the Dispatch is still active: mail to it reaches its worker. */ +export function reportFollowUpAction( + db: OrchestrationDb, + dispatchId: string, + lineageCache?: Map +): ReportFollowUpAction | undefined { + const dispatch = db.getDispatchContextById(dispatchId) + if (!dispatch || isActive(dispatch)) { + return undefined + } + const finishedElsewhere = (id: string): ReportFollowUpAction => { + const federated = db.getFederatedDispatch(id) + return federated + ? { kind: 'worker_start_on', server: federated.environment_name } + : { kind: 'worker_start' } + } + const plan = selectWorkerFollowUpPlan( + dispatch, + () => resolveWorkerLineage(db, dispatchId, undefined, lineageCache), + 'status', + (id) => Boolean(db.getFederatedDispatch(id)), + (id) => Boolean(db.getWorkerDispatch(id)) + ) + if (plan?.kind === 'start') { + return { kind: 'send', dispatchId, active: false } + } + if (plan?.kind === 'steer') { + const latest = db.getDispatchContextById(plan.dispatchId) + return latest && isActive(latest) + ? { kind: 'send', dispatchId: latest.id, active: true } + : finishedElsewhere(plan.dispatchId) + } + return finishedElsewhere(dispatchId) +} + +/** The follow-up a current-contract completion report offers once its task finished. + * Pass one `lineageCache` across a batch so reports of one worker share its lineage walk. */ +export function completionReportFollowUp( + db: OrchestrationDb, + message: MessageRow, + lineageCache?: Map +): ReportFollowUpAction | undefined { + // Legacy mail is inspect-only. + if ( + message.type !== 'worker_done' || + message.run_id === ORCHESTRATION_LEGACY_RUN_ID || + message.delivery_contract === 'legacy_direct' || + message.delivery_contract === 'audit_only' + ) { + return undefined + } + const dispatchId = completionReportDispatchId(db, message) + return dispatchId ? reportFollowUpAction(db, dispatchId, lineageCache) : undefined +} diff --git a/src/main/runtime/orchestration/workers/reports/worker-attention-context.ts b/src/main/runtime/orchestration/workers/reports/worker-attention-context.ts index 0c59c0ee2de..94e7ff960b0 100644 --- a/src/main/runtime/orchestration/workers/reports/worker-attention-context.ts +++ b/src/main/runtime/orchestration/workers/reports/worker-attention-context.ts @@ -1,4 +1,5 @@ import type { FleetAgentStatusEvidence } from '../../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' +import type { FleetSessionObservation } from '../../../../../shared/orchestration/fleet/orchestration-fleet-projection' import { projectOrchestrationFleetAttention } from '../../../../../shared/orchestration/fleet/orchestration-fleet-attention' import { resolveFleetWorkerOutcome } from '../../../../../shared/orchestration/fleet/orchestration-fleet-outcome-resolution' import { projectLiveness } from '../../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection' @@ -11,6 +12,7 @@ export function buildWorkerAttentionContext(args: { dispatch: DispatchContextRow task: TaskRow | undefined evidence: FleetAgentStatusEvidence | undefined + session?: FleetSessionObservation now?: number }) { const now = args.now ?? Date.now() @@ -19,6 +21,7 @@ export function buildWorkerAttentionContext(args: { facts, isRoot: facts.isRoot, evidence: args.evidence, + session: args.session, now }) } @@ -27,6 +30,8 @@ export function projectWorkerAttentionContext(args: { facts: WorkerAttentionFacts isRoot: boolean evidence: FleetAgentStatusEvidence | undefined + /** A chat-mode worker's host verdict, which outranks its status row's age. */ + session?: FleetSessionObservation now: number }) { return projectOrchestrationFleetAttention({ @@ -54,7 +59,8 @@ export function projectWorkerAttentionContext(args: { : { hostScope: args.facts.hostScope, releaseState: args.facts.releaseState } }, args.evidence, - args.now + args.now, + args.session ) }) } diff --git a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts index fcfa7ce292a..91467c30a54 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import { agentVerdictDisplayMark } from '../../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import { hookRowAgentPhase } from '../../../../../shared/agent-status/lifecycle/agent-transitions' diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts index 97e870f9d36..eaf3299653e 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentSessionTurnCompletionEvent } from '../../../../../shared/agent-session/view/agent-session-turn-completion-wire' import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/main/runtime/push/notifications/mobile-notification-dismissal-entries.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-entries.ts new file mode 100644 index 00000000000..03af706fe6f --- /dev/null +++ b/src/main/runtime/push/notifications/mobile-notification-dismissal-entries.ts @@ -0,0 +1,137 @@ +import type { MobileNotificationEvent } from './runtime-mobile-notification-controller' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { DeliveredNotificationIdentity } from '../../../../shared/mobile-notification-identity' +import type { KeyedJsonRow } from '../../../sqlite/row-cache/keyed-json-row-cache' +import { + isStructuredAttentionOrigin, + type StructuredAttentionOrigin +} from '../../../../shared/agent-session/agent-session-attention' + +export type DeliveredNotificationRecord = DeliveredNotificationIdentity & { + structuredOrigin?: StructuredAttentionOrigin + worktreeId?: string + paneKey?: string + workspaceExecutionHostId?: ExecutionHostId | null + executionHost?: `runtime:${string}` +} +export type DismissalRecordEntry = DeliveredNotificationRecord & { + dismissedThrough: number + expiresAt: number +} +export type DismissalEvent = MobileNotificationEvent & { + notificationEpoch: string + notificationSeq: number +} +type RecordEntry = DismissalRecordEntry + +export const DISMISSAL_LIMIT = 4096 +const RETENTION_MS = 7 * 86400_000 + +/** The history after `event` at `now`: expired records drop, the newest LIMIT remain. */ +export function applyDismissalEvent( + entries: readonly RecordEntry[], + event: DismissalEvent & { notificationId: string }, + now: number +): RecordEntry[] { + const kept = entries.filter((entry) => entry.expiresAt > now) + const same = (entry: RecordEntry) => + entry.notificationId === event.notificationId && + entry.notificationEpoch === event.notificationEpoch + let next: RecordEntry[] + if (event.type === 'dismiss' && event.dismissedDelivery) { + const target = event.dismissedDelivery + next = kept.map((entry) => + entry.notificationId === target.notificationId && + entry.notificationEpoch === target.notificationEpoch + ? { + ...entry, + dismissedThrough: Math.max(entry.dismissedThrough, target.notificationSeq), + expiresAt: now + RETENTION_MS + } + : entry + ) + } else if (event.type === 'notification') { + next = [ + ...kept.filter((entry) => !same(entry)), + { + notificationId: event.notificationId, + notificationEpoch: event.notificationEpoch, + notificationSeq: event.notificationSeq, + ...(event.workspaceExecutionHostId !== undefined + ? { workspaceExecutionHostId: event.workspaceExecutionHostId } + : {}), + ...(event.worktreeId ? { worktreeId: event.worktreeId } : {}), + ...(event.paneKey ? { paneKey: event.paneKey } : {}), + ...(event.executionHost ? { executionHost: event.executionHost } : {}), + ...(event.structuredOrigin ? { structuredOrigin: event.structuredOrigin } : {}), + dismissedThrough: kept.find(same)?.dismissedThrough ?? -1, + expiresAt: now + RETENTION_MS + } + ] + } else { + next = kept + .filter((entry) => !same(entry)) + .map((entry) => + entry.notificationId === event.notificationId + ? { ...entry, dismissedThrough: entry.notificationSeq, expiresAt: now + RETENTION_MS } + : entry + ) + next.push({ + notificationId: event.notificationId, + notificationEpoch: event.notificationEpoch, + notificationSeq: event.notificationSeq, + dismissedThrough: event.notificationSeq, + expiresAt: now + RETENTION_MS + }) + } + return next.slice(-DISMISSAL_LIMIT) +} + +/** Records from a stored row or an older build's file; unusable ones are dropped. */ +export function readDismissalEntries(values: readonly unknown[]): RecordEntry[] { + return values.flatMap(readEntry).slice(-DISMISSAL_LIMIT) +} + +/** Rows keyed by delivery identity; a repeated identity keeps its last position. */ +export function dismissalRows(entries: readonly RecordEntry[]): KeyedJsonRow[] { + const rows = new Map() + for (const entry of entries) { + const key = `${entry.notificationId}\u0000${entry.notificationEpoch}` + rows.delete(key) + rows.set(key, { key, json: JSON.stringify(entry) }) + } + return [...rows.values()] +} + +export function isLiveDismissalEntry(entry: RecordEntry, now: number): boolean { + return entry.expiresAt > now && entry.dismissedThrough < entry.notificationSeq +} + +/** Keep records with unknown future origin kinds, degrading only their origin to none. */ +function readEntry(value: unknown): RecordEntry[] { + if (!isEntry(value)) { + return [] + } + const { structuredOrigin, ...entry } = value + return [isStructuredAttentionOrigin(structuredOrigin) ? { ...entry, structuredOrigin } : entry] +} + +function isEntry( + value: unknown +): value is Omit & { structuredOrigin?: unknown } { + if (!value || typeof value !== 'object') { + return false + } + const item = value as RecordEntry + return ( + typeof item.notificationId === 'string' && + item.notificationId.length > 0 && + typeof item.notificationEpoch === 'string' && + item.notificationEpoch.length > 0 && + Number.isSafeInteger(item.notificationSeq) && + item.notificationSeq >= 0 && + Number.isSafeInteger(item.dismissedThrough) && + item.dismissedThrough >= -1 && + Number.isFinite(item.expiresAt) + ) +} diff --git a/src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts index 4461bf267c8..cdf2851868b 100644 --- a/src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts +++ b/src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts @@ -1,38 +1,53 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import type * as fs from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it, vi } from 'vitest' +import type * as SyncDatabaseModule from '../../../sqlite/sync-database' import { MobileNotificationDismissalStore } from './mobile-notification-dismissal-store' -vi.mock('node:fs', async (original) => { - const f = await original() - return { ...f, readFileSync: vi.fn(f.readFileSync) } + +const failure = vi.hoisted(() => ({ remainingOpens: 0 })) +vi.mock('../../../sqlite/sync-database', async (original) => { + const actual = await original() + class FailingOpen extends actual.default { + constructor(...args: ConstructorParameters) { + if (failure.remainingOpens > 0) { + failure.remainingOpens -= 1 + throw Object.assign(new Error('read failed'), { code: 'EIO' }) + } + super(...args) + } + } + return { ...actual, default: FailingOpen } }) -it('preserves dismissal history after EIO', async () => { + +it('keeps history it could not read and merges dismissals recorded meanwhile', async () => { const dir = mkdtempSync(join(tmpdir(), 'push-comment-')) + const dismiss = (notificationId: string, notificationSeq: number) => ({ + type: 'dismiss' as const, + notificationId, + notificationEpoch: 'epoch', + notificationSeq + }) try { const store = new MobileNotificationDismissalStore(dir) - store.record({ - type: 'dismiss', - notificationId: 'old', + store.record(dismiss('old', 1)) + await store.close() + // The startup read fails; close() retries it and saves what was recorded meanwhile. + failure.remainingOpens = 1 + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const restarted = new MobileNotificationDismissalStore(dir) + expect(restarted.hasLiveDelivery('anything')).toBe(true) + restarted.record(dismiss('new', 2)) + await restarted.close() + + const recovered = new MobileNotificationDismissalStore(dir) + await recovered.close() + const shown = (notificationId: string) => ({ + notificationId, notificationEpoch: 'epoch', notificationSeq: 1 }) - await store.close() - const path = join(dir, 'mobile-notification-dismissals.json') - const before = readFileSync(path, 'utf8') - vi.mocked(readFileSync).mockImplementationOnce(() => { - throw Object.assign(new Error('read failed'), { code: 'EIO' }) - }) - const restarted = new MobileNotificationDismissalStore(dir) - restarted.record({ - type: 'dismiss', - notificationId: 'new', - notificationEpoch: 'epoch', - notificationSeq: 2 - }) - await restarted.flush() - expect(readFileSync(path, 'utf8')).toBe(before) + expect(recovered.reconcile([shown('old'), shown('new')])).toEqual([shown('old'), shown('new')]) } finally { vi.restoreAllMocks() rmSync(dir, { recursive: true, force: true }) diff --git a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts index b6d3bcc5cbc..9b45b703736 100644 --- a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts +++ b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -87,7 +87,7 @@ it('lists only live deliveries across a restart', async () => { expect(restarted.liveDeliveries()[0]).toMatchObject({ workspaceExecutionHostId: null }) }) -it('keeps a record whose origin a newer build wrote, losing only that origin', () => { +it("imports an older build's file, keeping a record whose origin it cannot read", async () => { const h = fixture() const origin = { scope: { @@ -114,7 +114,12 @@ it('keeps a record whose origin a newer build wrote, losing only that origin', ( } ]) ) - expect(new MobileNotificationDismissalStore(h.path).liveDeliveries()).toEqual([ + const imported = new MobileNotificationDismissalStore(h.path) + await imported.close() + expect(existsSync(join(h.path, 'mobile-notification-dismissals.json'))).toBe(false) + const restarted = new MobileNotificationDismissalStore(h.path) + stores.push(restarted) + expect(restarted.liveDeliveries()).toEqual([ shown, expect.objectContaining({ notificationId: 'known', structuredOrigin: expect.anything() }) ]) @@ -123,7 +128,7 @@ it('keeps a record whose origin a newer build wrote, losing only that origin', ( it('retains in-memory delivery and retirement when durable writes fail', async () => { const h = fixture() const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - mkdirSync(join(h.path, 'mobile-notification-dismissals.json')) + mkdirSync(join(h.path, 'mobile-notification-dismissals.db')) h.store.record({ ...alert, ...shown }) expect(h.store.liveDeliveries()).toHaveLength(1) h.store.record({ @@ -144,10 +149,11 @@ it('retains in-memory delivery and retirement when durable writes fail', async ( it('saves records synchronously from the moment close() is called, ahead of the queued async write', async () => { const h = fixture() - const savedIds = () => - new MobileNotificationDismissalStore(h.path) - .liveDeliveries() - .map((entry) => entry.notificationId) + const savedIds = () => { + const reader = new MobileNotificationDismissalStore(h.path) + void reader.close() + return reader.liveDeliveries().map((entry) => entry.notificationId) + } h.store.record({ ...alert, ...shown, notificationId: 'before-close' }) const closing = h.store.close() h.store.record({ ...alert, ...shown, notificationId: 'while-closing' }) diff --git a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts index e6e2e69f799..be911b81694 100644 --- a/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts +++ b/src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts @@ -1,150 +1,116 @@ -import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { isUnreadableError } from '../../../../shared/secure-storage/secure-file' -import { AtomicSnapshotWriter } from '../../../persistence/atomic-snapshot-writer' -import type { MobileNotificationEvent } from './runtime-mobile-notification-controller' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import { + KeyedJsonRowCache, + parseKeyedJsonRows +} from '../../../sqlite/row-cache/keyed-json-row-cache' +import { nextRetryDelayMs } from '../../../sqlite/row-cache/row-cache-failure' import type { DeliveredNotificationIdentity } from '../../../../shared/mobile-notification-identity' import { - isStructuredAttentionOrigin, - type StructuredAttentionOrigin -} from '../../../../shared/agent-session/agent-session-attention' + applyDismissalEvent, + dismissalRows, + DISMISSAL_LIMIT, + isLiveDismissalEntry, + readDismissalEntries, + type DeliveredNotificationRecord, + type DismissalEvent, + type DismissalRecordEntry +} from './mobile-notification-dismissal-entries' -export type DeliveredNotificationRecord = DeliveredNotificationIdentity & { - structuredOrigin?: StructuredAttentionOrigin - worktreeId?: string - paneKey?: string - workspaceExecutionHostId?: ExecutionHostId | null - executionHost?: `runtime:${string}` -} -type RecordEntry = DeliveredNotificationRecord & { dismissedThrough: number; expiresAt: number } -const LIMIT = 4096 -const RETENTION_MS = 7 * 86400_000 +export type { DeliveredNotificationRecord } from './mobile-notification-dismissal-entries' + +const DATABASE_FILE = 'mobile-notification-dismissals.db' +// Earlier builds rewrote this whole file per alert; it is imported once, then removed. +const LEGACY_FILE = 'mobile-notification-dismissals.json' +const RETRY_BACKOFF = { minMs: 100, maxMs: 60_000 } function warnPersistFailed(error: unknown): void { console.warn('[notifications] Could not persist dismissal recovery state', error) } +type PendingEvent = { event: DismissalEvent & { notificationId: string }; at: number } + +/** + * One SQLite row per delivery, so each alert or dismissal saves only the rows it changed. + * Until stored history is read it is never replaced: events queue and merge into it once a + * retry reads it, and meanwhile any delivery may still be live. + */ export class MobileNotificationDismissalStore { - private readonly path: string - private entries: RecordEntry[] = [] - private unreadable = false + private entries: DismissalRecordEntry[] = [] + private historyKnown = false + private readonly pending: PendingEvent[] = [] + private dirty = false + private retryTimer: ReturnType | undefined + private retryDelayMs = 0 private closed = false // Notification ids need no secure writer; its synchronous Windows icacls froze windows per alert (STA-9692). - private readonly writer: AtomicSnapshotWriter + private readonly cache: KeyedJsonRowCache + constructor(userDataPath: string) { - this.path = join(userDataPath, 'mobile-notification-dismissals.json') - this.writer = new AtomicSnapshotWriter(() => this.path, { fileMode: 0o600 }) - try { - const value: unknown = JSON.parse(readFileSync(this.path, 'utf8')) - if (Array.isArray(value)) { - this.entries = value.flatMap(readEntry).slice(-LIMIT) - } - } catch (error) { - this.unreadable = isUnreadableError(error) - // Missing history cannot establish that a delivered alert was dismissed. + this.cache = new KeyedJsonRowCache(join(userDataPath, DATABASE_FILE), { + schemaVersion: 1, + legacyPath: join(userDataPath, LEGACY_FILE) + }) + const unread = this.hydrate() + if (unread) { + // Show what an older build's file says while the stored history stays unread. + this.entries = unread.legacy ?? [] + this.scheduleRetry() } } - record( - event: MobileNotificationEvent & { notificationEpoch: string; notificationSeq: number } - ): void { - if (!event.notificationId) { + record(event: DismissalEvent): void { + const { notificationId } = event + if (!notificationId) { return } const now = Date.now() - const kept = this.entries.filter((entry) => entry.expiresAt > now) - const same = (entry: RecordEntry) => - entry.notificationId === event.notificationId && - entry.notificationEpoch === event.notificationEpoch - let next: RecordEntry[] - if (event.type === 'dismiss' && event.dismissedDelivery) { - const target = event.dismissedDelivery - next = kept.map((entry) => - entry.notificationId === target.notificationId && - entry.notificationEpoch === target.notificationEpoch - ? { - ...entry, - dismissedThrough: Math.max(entry.dismissedThrough, target.notificationSeq), - expiresAt: now + RETENTION_MS - } - : entry - ) - } else if (event.type === 'notification') { - next = [ - ...kept.filter((entry) => !same(entry)), - { - notificationId: event.notificationId, - notificationEpoch: event.notificationEpoch, - notificationSeq: event.notificationSeq, - ...(event.workspaceExecutionHostId !== undefined - ? { workspaceExecutionHostId: event.workspaceExecutionHostId } - : {}), - ...(event.worktreeId ? { worktreeId: event.worktreeId } : {}), - ...(event.paneKey ? { paneKey: event.paneKey } : {}), - ...(event.executionHost ? { executionHost: event.executionHost } : {}), - ...(event.structuredOrigin ? { structuredOrigin: event.structuredOrigin } : {}), - dismissedThrough: kept.find(same)?.dismissedThrough ?? -1, - expiresAt: now + RETENTION_MS - } - ] - } else { - next = kept - .filter((entry) => !same(entry)) - .map((entry) => - entry.notificationId === event.notificationId - ? { ...entry, dismissedThrough: entry.notificationSeq, expiresAt: now + RETENTION_MS } - : entry - ) - next.push({ - notificationId: event.notificationId, - notificationEpoch: event.notificationEpoch, - notificationSeq: event.notificationSeq, - dismissedThrough: event.notificationSeq, - expiresAt: now + RETENTION_MS - }) - } - next = next.slice(-LIMIT) - this.entries = next - if (this.unreadable) { - return - } - const serialize = () => JSON.stringify(this.entries, null, 2) - if (this.closed) { - // Exit would drop an asynchronous write. - try { - this.writer.writeSync(serialize) - } catch (error) { - warnPersistFailed(error) + this.entries = applyDismissalEvent(this.entries, { ...event, notificationId }, now) + if (!this.historyKnown) { + this.pending.push({ event: { ...event, notificationId }, at: now }) + this.pending.splice(0, Math.max(0, this.pending.length - DISMISSAL_LIMIT)) + if (this.closed) { + // No retry timer runs after close: one bounded attempt, keeping the event on failure. + this.attempt() } return } - this.writer.write(serialize).catch(warnPersistFailed) + this.dirty = true + if (!this.persist() && !this.closed) { + this.scheduleRetry() + } } + /** One bounded attempt to read unread history and save what is pending. */ flush(): Promise { - return this.writer.waitForPendingWrite().catch(() => {}) + this.attempt() + return Promise.resolve() } - /** Committed exits only: subsequent records write synchronously; wait for the pending write. */ + /** Saves what it can and releases the database; later records still save per write. */ close(): Promise { + clearTimeout(this.retryTimer) + this.retryTimer = undefined + this.attempt() this.closed = true - return this.flush() + this.cache.close() + return Promise.resolve() } - /** Unreadable history cannot rule a delivery out. */ + /** Unread history cannot rule a delivery out. */ hasLiveDelivery(notificationId: string): boolean { const now = Date.now() return ( - this.unreadable || - this.entries.some((entry) => entry.notificationId === notificationId && isLive(entry, now)) + !this.historyKnown || + this.entries.some( + (entry) => entry.notificationId === notificationId && isLiveDismissalEntry(entry, now) + ) ) } liveDeliveries(): DeliveredNotificationRecord[] { const now = Date.now() return this.entries - .filter((entry) => isLive(entry, now)) + .filter((entry) => isLiveDismissalEntry(entry, now)) .map( ({ notificationId, @@ -181,37 +147,85 @@ export class MobileNotificationDismissalStore { ) ) } -} -function isLive(entry: RecordEntry, now: number): boolean { - return entry.expiresAt > now && entry.dismissedThrough < entry.notificationSeq -} + /** Returns why history stays unread, or undefined once it is read and merged. */ + private hydrate(): { legacy?: DismissalRecordEntry[] } | undefined { + // A file still present came from an older build unless its receipt shows it was imported. + const loaded = this.cache.load(readLegacyHistory) + if (loaded.kind === 'unavailable') { + console.warn('[notifications] Could not read dismissal recovery state', loaded.error) + return { legacy: loaded.legacy } + } + let entries: DismissalRecordEntry[] + if (loaded.kind === 'import') { + try { + this.cache.write(dismissalRows(loaded.value), { importReceipt: loaded.receipt }) + } catch (error) { + console.warn('[notifications] Could not read dismissal recovery state', error) + return { legacy: loaded.value } + } + entries = loaded.value + } else { + entries = readDismissalEntries(parseKeyedJsonRows(loaded.rows).map(({ value }) => value)) + } + for (const { event, at } of this.pending) { + entries = applyDismissalEvent(entries, event, at) + } + this.dirty = this.pending.length > 0 + this.pending.length = 0 + this.entries = entries + this.historyKnown = true + return undefined + } -/** Keep records with unknown future origin kinds, degrading only their origin to none. */ -function readEntry(value: unknown): RecordEntry[] { - if (!isEntry(value)) { - return [] + private persist(): boolean { + if (!this.dirty || !this.historyKnown) { + return true + } + try { + this.cache.write(dismissalRows(this.entries)) + this.dirty = false + this.retryDelayMs = 0 + return true + } catch (error) { + warnPersistFailed(error) + return false + } + } + + private attempt(): boolean { + if (!this.historyKnown && this.hydrate()) { + return false + } + return this.persist() + } + + private scheduleRetry(): void { + if (this.retryTimer || this.closed) { + return + } + this.retryDelayMs = nextRetryDelayMs(this.retryDelayMs, RETRY_BACKOFF) + const delay = this.retryDelayMs + this.retryTimer = setTimeout(() => { + this.retryTimer = undefined + if (!this.attempt()) { + this.scheduleRetry() + } + }, delay) + const timer: unknown = this.retryTimer + if ( + typeof timer === 'object' && + timer !== null && + 'unref' in timer && + typeof timer.unref === 'function' + ) { + timer.unref() + } } - const { structuredOrigin, ...entry } = value - return [isStructuredAttentionOrigin(structuredOrigin) ? { ...entry, structuredOrigin } : entry] } -function isEntry( - value: unknown -): value is Omit & { structuredOrigin?: unknown } { - if (!value || typeof value !== 'object') { - return false - } - const item = value as RecordEntry - return ( - typeof item.notificationId === 'string' && - item.notificationId.length > 0 && - typeof item.notificationEpoch === 'string' && - item.notificationEpoch.length > 0 && - Number.isSafeInteger(item.notificationSeq) && - item.notificationSeq >= 0 && - Number.isSafeInteger(item.dismissedThrough) && - item.dismissedThrough >= -1 && - Number.isFinite(item.expiresAt) - ) +/** History an older build wrote; corrupt bytes are rejected and never replace stored rows. */ +function readLegacyHistory(text: string): DismissalRecordEntry[] | null { + const value: unknown = JSON.parse(text) + return Array.isArray(value) ? readDismissalEntries(value) : null } diff --git a/src/main/runtime/push/notifications/terminal-agent-phone-push.ts b/src/main/runtime/push/notifications/terminal-agent-phone-push.ts index a1757d35ee7..26dc92a63be 100644 --- a/src/main/runtime/push/notifications/terminal-agent-phone-push.ts +++ b/src/main/runtime/push/notifications/terminal-agent-phone-push.ts @@ -1,6 +1,6 @@ // Push hook-agent finish/input alerts from windowless execution hosts using desktop rules. A window already pushes these phones; the phone suppresses its own visible chat. import { getConnectionExecutionHostId } from '../../../../shared/execution-host' -import type { AgentPaneChange } from '../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../agent-hooks/observations/agent-transition-detector' import { agentMainAgentVerdict } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/runtime/push/notifications/terminal-agent-turn-news.ts b/src/main/runtime/push/notifications/terminal-agent-turn-news.ts index fb0a619c04c..f436af11266 100644 --- a/src/main/runtime/push/notifications/terminal-agent-turn-news.ts +++ b/src/main/runtime/push/notifications/terminal-agent-turn-news.ts @@ -1,5 +1,5 @@ // Share desktop completion/input timing and hook rows; phone/connector listeners choose wording and transport. -import type { AgentPaneChange } from '../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../agent-hooks/observations/agent-transition-detector' import { mainAgentTurnInterrupted } from '../../../../shared/agent-status/lifecycle/agent-lead-status-fold' import { agentTurnEndedOnPurpose } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index 5b57b3ab3e6..4fe418b297c 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -157,6 +157,8 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ 'worker_prompt_too_large', 'terminal_worktree_mismatch', 'terminal_is_coordinator', + // Another open Dispatch holds the terminal; data names it and says no effects were applied. + 'terminal_busy', // The user chose Keep open; only they can undo it, so a coordinator must not retry blindly. 'terminal_kept_open', 'worker_cannot_coordinate_own_run', diff --git a/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts b/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts index eb961a53c0a..3bdc3a48b05 100644 --- a/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts +++ b/src/main/runtime/rpc/methods/browser/browser-identity-rpc.ts @@ -3,7 +3,7 @@ import { BrowserIdentitySet } from '../../../../../shared/rpc-contract/browser-i import { getBrowserIdentityModeStatus, setBrowserIdentityMode -} from '../../../../browser/identity/browser-identity-mode-store' +} from '../../../../browser/identity/mode/browser-identity-mode-store' // Process identity has no BrowserTarget and does not drive pages, so keep it separate from browser-core. export const BROWSER_IDENTITY_METHODS = [ diff --git a/src/main/runtime/rpc/methods/client-events/client-events-prompt-telemetry.test.ts b/src/main/runtime/rpc/methods/client-events/client-events-prompt-telemetry.test.ts new file mode 100644 index 00000000000..ac6e3d0f53f --- /dev/null +++ b/src/main/runtime/rpc/methods/client-events/client-events-prompt-telemetry.test.ts @@ -0,0 +1,112 @@ +import { expect, it } from 'vitest' +import { + STRUCTURED_CHAT_PROMPT_TELEMETRY_CLIENT_CAPABILITY, + STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY +} from '../../../../../shared/structured-chat-dispatch-telemetry' +import { recordStructuredChatPromptAccepted } from '../../../../telemetry/structured-chat-dispatch' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' +// Import the registry to avoid client-events' module-init cycle through ipc/ssh. +import { ALL_RPC_METHODS } from '../rpc-method-registry' + +const subscribe = eraseRpcMethods(ALL_RPC_METHODS) + .filter(isStreamingMethod) + .find((method) => method.name === 'runtime.clientEvents.subscribe')! + +function open(overrides: Partial = {}) { + const events: unknown[] = [] + let cleanup = () => {} + const fake = { + onClientEvent: () => () => {}, + getClientSettings: () => ({}), + registerSubscriptionCleanup: (_id: string, close: () => void) => { + cleanup = close + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the stream reads only these runtime members. + const runtime = fake as unknown as OrcaRuntimeService + const done = subscribe.handler( + {}, + { + runtime, + caller: { kind: 'paired-device', deviceId: 'desktop-a' }, + pairedDeviceId: 'desktop-a', + clientKind: 'runtime', + clientCapabilities: [STRUCTURED_CHAT_PROMPT_TELEMETRY_CLIENT_CAPABILITY], + ...overrides + }, + (event) => { + if ( + typeof event === 'object' && + event !== null && + 'type' in event && + event.type === 'structuredChatPromptAccepted' + ) { + events.push(event) + } + } + ) + return { events, done, close: () => cleanup() } +} + +it('addresses live observations only to capable authenticated owning desktops, with no reconnect backfill', async () => { + const owner = open() + const other = open({ + caller: { kind: 'paired-device', deviceId: 'desktop-b' }, + pairedDeviceId: 'desktop-b' + }) + const old = open({ clientCapabilities: [STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY] }) + const phone = open({ clientKind: 'mobile' }) + const unproven = open({ caller: undefined, clientId: 'desktop-a' }) + const cli = open({ caller: { kind: 'local-cli' }, clientId: 'desktop-a' }) + const streams = [owner, other, old, phone, unproven, cli] + let reconnected: ReturnType | undefined + try { + recordStructuredChatPromptAccepted( + { agent_kind: 'codex', client: 'mobile', runtime: 'unknown' }, + 'desktop-a' + ) + expect(owner.events).toEqual([ + { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'codex', + client: 'mobile' + } + ]) + expect([other.events, old.events, phone.events, unproven.events, cli.events]).toEqual([ + [], + [], + [], + [], + [] + ]) + + owner.close() + await owner.done + recordStructuredChatPromptAccepted( + { agent_kind: 'codex', client: 'desktop', runtime: 'unknown' }, + 'desktop-a' + ) + reconnected = open() + expect(reconnected.events).toEqual([]) + recordStructuredChatPromptAccepted( + { agent_kind: 'claude-code', client: 'desktop', runtime: 'unknown' }, + 'desktop-a' + ) + expect(reconnected.events).toEqual([ + { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'claude-code', + client: 'desktop' + } + ]) + expect(owner.events).toHaveLength(1) + } finally { + for (const stream of [...streams, ...(reconnected ? [reconnected] : [])]) { + stream.close() + await stream.done + } + } +}) diff --git a/src/main/runtime/rpc/methods/client-events/client-events.ts b/src/main/runtime/rpc/methods/client-events/client-events.ts index 56d6d5e5703..f78a7844631 100644 --- a/src/main/runtime/rpc/methods/client-events/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events/client-events.ts @@ -10,7 +10,10 @@ import { } from '../../../../../shared/rpc-contract/client-events-params' import { BROWSER_CLIENT_HOST_REQUEST_CAPABILITY } from '../../../../../shared/browser/client-hosting/browser-client-host-request-protocol' import { getBrowserHostRequestRegistry } from '../../../browser-host/leases/browser-host-request-registry' -import { STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY } from '../../../../../shared/structured-chat-dispatch-telemetry' +import { + STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY, + STRUCTURED_CHAT_PROMPT_TELEMETRY_CLIENT_CAPABILITY +} from '../../../../../shared/structured-chat-dispatch-telemetry' import { subscribeStructuredChatTelemetry } from '../../../../telemetry/structured-chat-dispatch' import { structuredCallerFor } from '../structured-sessions/creation/structured-agent-session-gate' @@ -38,18 +41,24 @@ export const CLIENT_EVENT_METHODS = [ clientCapabilities?.includes(BROWSER_CLIENT_HOST_REQUEST_CAPABILITY) ? getBrowserHostRequestRegistry(runtime).register({ pairedDeviceId, emit }) : undefined - const unsubscribeTelemetry = clientCapabilities?.includes( + const readsStarts = clientCapabilities?.includes( STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY ) - ? subscribeStructuredChatTelemetry((event, callerKey) => { - if ( - callerKey === structuredCallerFor(ctx).callerKey && - clientCapabilities?.includes(STRUCTURED_CHAT_START_TELEMETRY_CLIENT_CAPABILITY) - ) { - emit(event) - } - }) - : undefined + const readsPrompts = + ctx.caller?.kind === 'paired-device' && + clientKind === 'runtime' && + clientCapabilities?.includes(STRUCTURED_CHAT_PROMPT_TELEMETRY_CLIENT_CAPABILITY) + const unsubscribeTelemetry = + readsStarts || readsPrompts + ? subscribeStructuredChatTelemetry((event, callerKey) => { + if ( + callerKey === structuredCallerFor(ctx).callerKey && + (event.type === 'structuredChatPromptAccepted' ? readsPrompts : readsStarts) + ) { + emit(event) + } + }) + : undefined const seq = ++clientEventSubscriptionSeq const subscriptionId = `runtime-client-events-${connectionId ?? 'inproc'}-${seq}` diff --git a/src/main/runtime/rpc/methods/history/ai-vault.ts b/src/main/runtime/rpc/methods/history/ai-vault.ts index 54006f3c7af..0ec0a41183c 100644 --- a/src/main/runtime/rpc/methods/history/ai-vault.ts +++ b/src/main/runtime/rpc/methods/history/ai-vault.ts @@ -107,6 +107,7 @@ export const AI_VAULT_METHODS = [ unlimited: params.unlimited, force: params.force, scopePaths: params.scopePaths, + scopeOnly: params.scopeOnly, includeAntigravityIdeSessions: params.includeAntigravityIdeSessions }, signal diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts index 65509b36c5f..79f9710cc50 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-control-mail.test.ts @@ -217,6 +217,48 @@ describe('orchestration federation control mail', () => { expect(workerDb.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(1) }) + it('refuses a reply to a finished paired-host report by naming a new worker there', async () => { + const taskId = homeDb.getDispatchContextById(dispatchId)!.task_id + workerDb.enqueueFederationRelay({ + dispatchId, + direction: 'to_home', + kind: 'worker_done', + payload: JSON.stringify({ + from: `dispatch:${dispatchId}`, + subject: 'Done', + body: 'Finished remotely.', + type: 'worker_done', + priority: 'normal', + threadId: null, + payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded', filesModified: [] }) + }), + settleRemoteOutcome: 'succeeded' + }) + await syncFederationBarrier(homeRuntime, homeDb) + const report = homeDb + .getUnreadMessages(`run:${runId}`) + .find((message) => message.type === 'worker_done')! + + await expect( + homeDispatcher.dispatch({ + id: 'reply-finished-remote', + authToken: 'coordinator-token', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: 'reply-finished-remote-request', + method: 'orchestration.reply', + params: { from: 'term_coord', id: report.id, body: 'One more thing' } + }) + ).resolves.toMatchObject({ + ok: false, + error: { + code: 'dispatch_inactive', + data: { followUp: { kind: 'worker_start_on', server: 'worker' } } + } + }) + expect(homeDb.getAllMessagesForHandle(`dispatch:${dispatchId}`)).toHaveLength(0) + expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(0) + }) + function checkRequest(id: string, wait = false, timeoutMs = 5_000, types?: string): RpcRequest { return { id, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts index ed62647b116..504e15b9fc2 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -5,7 +5,7 @@ import { parseMessageTypes } from '../routing' import { checkRunMailbox } from './check-run' import { checkWorkerMailbox } from './check-worker' import { checkDirectMailbox } from './check-direct' -import { checkedMailboxes } from './mailbox-message-receipt' +import { checkedMailboxes, withReportFollowUps } from './mailbox-message-receipt' import { withRunCheckNext } from '../receipt-next' import { orchestrationSkillRecoveryData } from '../../../../../../shared/orchestration/orchestration-rpc-contract' import { hasRunBindingKey } from '../../../../orchestration/addressing/orchestration-caller-identity' @@ -51,7 +51,7 @@ export const ORCHESTRATION_CHECK_METHODS = [ if (consumingCheck) { runtime.withdrawStaleChatMail(checkedMailboxes(result)) } - return result + return withReportFollowUps(db, result) } if (params.run || boundRun) { const result = await checkRunMailbox({ diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/mailbox-message-receipt.ts b/src/main/runtime/rpc/methods/orchestration/messaging/mailbox-message-receipt.ts index 8df1169ef46..4561130732c 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/mailbox-message-receipt.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/mailbox-message-receipt.ts @@ -1,6 +1,8 @@ import type { MessageRow } from '../../../../orchestration/db/orchestration-records' import type { MailboxDeliveryBatch } from '../../../../orchestration/db/messages/role-mailbox-delivery' import { formatMessageBanner } from '../../../../orchestration/mailbox/formatting/message-formatting' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import { completionReportFollowUp } from '../../../../orchestration/workers/reports/report-follow-up-action' // Hide read/sequence, pointer_* and sender_pane_key: they are runtime delivery plumbing, not caller mailbox truth. const INTERNAL_MESSAGE_COLUMNS = [ @@ -75,6 +77,43 @@ export function handsOverBatch(result: unknown): boolean { ) } +/** Adds each finished completion report's follow-up action, so every check view offers the same one. */ +export function withReportFollowUps(db: OrchestrationDb, result: T): T { + if (typeof result !== 'object' || result === null || !('messages' in result)) { + return result + } + const { messages } = result + if (!Array.isArray(messages) || !messages.some((message) => message?.type === 'worker_done')) { + return result + } + const formatted = 'formatted' in result && typeof result.formatted === 'string' + let changed = false + const lineageCache = new Map() + const rows = messages.map((message: MailboxMessageReceipt) => { + const row = + formatted || message.type === 'worker_done' ? db.getMessageById(message.id) : undefined + const followUp = row ? completionReportFollowUp(db, row, lineageCache) : undefined + changed ||= followUp !== undefined + return { message, row, followUp } + }) + if (!changed) { + return result + } + return { + ...result, + messages: rows.map(({ message, followUp }) => + followUp ? { ...message, follow_up: followUp } : message + ), + ...(formatted + ? { + formatted: rows + .flatMap(({ row, followUp }) => (row ? [formatMessageBanner(row, { followUp })] : [])) + .join('\n\n') + } + : {}) + } +} + /** The mailboxes a consuming check took mail from: its messages' own, and the one an acknowledgement * settled. Only their waiting cards can have gone stale. */ export function checkedMailboxes(result: unknown): string[] { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.test.ts b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.test.ts index e0aa628c5e0..9021538b40f 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.test.ts @@ -99,6 +99,38 @@ describe('orchestration recipient routing oracle', () => { expect(check.messages.map((message) => message.id)).toEqual([result.message.id]) }) + it('keeps a reply to a live terminal-only sender readable there and reports its limitation', async () => { + setup() + mockTerminalPaneKeys((handle) => + handle === 'term_coord' + ? harness.coordinatorPaneKey + : handle === 'term_live' + ? 'tab_live:leaf_live' + : null + ) + const note = db.insertMessage({ + from: 'term_live', + to: `run:${senderRunId}`, + subject: 'Pull-mail note', + runId: senderRunId + }) + + const reply = await harness.call( + 'orchestration.reply', + { id: note.id, from: 'term_coord', body: 'Got it' }, + ctx + ) + + const [stored] = db.getAllMessagesForHandle('term_live') + expect(reply).toMatchObject({ + message: { id: stored!.id, to_handle: 'term_live' }, + warnings: [{ code: 'legacy_terminal_recipient', recipient: 'term_live' }] + }) + expect(await harness.call('orchestration.check', { terminal: 'term_live' }, ctx)).toMatchObject( + { messages: [{ id: stored!.id }], count: 1 } + ) + }) + it('normalizes a cross-Run coordinator handle to the recipient Run mailbox', async () => { setup() const recipientPane = 'tab_recipient:leaf_recipient' diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts index 3bbbf914eca..483f6dfc8d6 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts @@ -17,6 +17,8 @@ import { refuseUndeliverableSessionRecipient, type SessionRecipientRefusal } from './session-recipient' +import { reportFollowUpAction } from '../../../../orchestration/workers/reports/report-follow-up-action' +import { formatReportFollowUpNext } from '../../../../../../shared/orchestration/mailbox/orchestration-report-follow-up' const ACTIVE_DISPATCH_STATUSES: readonly DispatchStatus[] = ['pending', 'dispatched'] @@ -30,10 +32,27 @@ export function assertDispatchMailboxDeliverable( if (!dispatch || ACTIVE_DISPATCH_STATUSES.includes(dispatch.status)) { return } - const recipientRun = currentDispatchAssigneeRun(runtime, db, dispatch)?.id ?? dispatch.run_id + const workerRun = currentDispatchAssigneeRun(runtime, db, dispatch) + // The owning Run is usually the sender's own; only a Run the worker itself coordinates is its mailbox. + if (workerRun && workerRun.id !== dispatch.run_id) { + throw new OrchestrationError( + 'dispatch_inactive', + `Dispatch ${dispatchId} is ${dispatch.status}; its worker will never read that mailbox. Send to run:${workerRun.id} instead, or start a new Dispatch for follow-up work.` + ) + } + const followUp = reportFollowUpAction(db, dispatchId) throw new OrchestrationError( 'dispatch_inactive', - `Dispatch ${dispatchId} is ${dispatch.status}; its worker will never read that mailbox. Send to run:${recipientRun} instead, or start a new Dispatch for follow-up work.` + `Dispatch ${dispatchId} is ${dispatch.status}; its worker will never read that mailbox.${ + followUp + ? ` ${formatReportFollowUpNext(followUp)}${ + followUp.kind === 'send' && !followUp.active + ? ' Only --type status, dispatch or handoff continues a worker; status is the default.' + : '' + }` + : '' + }`, + followUp ? { followUp } : undefined ) } @@ -139,13 +158,13 @@ export function selectRunBoundDispatchRecipient( } } -// Replies share send routing; unresolved historical senders keep their original address. +// Replies share send routing; an unresolvable bare sender is refused rather than stored where nothing reads. export function resolveReplyRecipient(params: { runtime: OrcaRuntimeService db: OrchestrationDb originalFrom: string originalRunId: string | undefined -}): { to: string; runId: string | undefined } { +}): { to: string; runId: string | undefined; warning?: SendRecipientWarning } { const { runtime, db, originalFrom, originalRunId } = params const unchanged = { to: originalFrom, runId: originalRunId } if (originalFrom.startsWith('run:')) { @@ -167,7 +186,16 @@ export function resolveReplyRecipient(params: { handle: originalFrom, senderRunId: originalRunId }) - return recipient.ok ? { to: recipient.to, runId: recipient.runId ?? originalRunId } : unchanged + if (!recipient.ok) { + throw new OrchestrationError(recipient.code, `${recipient.message} No reply was sent.`, { + effectsApplied: false + }) + } + return { + to: recipient.to, + runId: recipient.runId ?? originalRunId, + ...(recipient.warning ? { warning: recipient.warning } : {}) + } } export type SendRecipientWarning = { diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index f5b0a3b7ec4..b0bd4ec708f 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -16,6 +16,11 @@ import { helperQuestionAnswerer } from './helper-question-answerer' import { replyToRemoteRunHome } from './reply-remote' import { withAnswerNext } from '../receipt-next' import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' +import { + completionReportDispatchId, + reportFollowUpAction +} from '../../../../orchestration/workers/reports/report-follow-up-action' +import { formatFinishedReportReplyRefusal } from '../../../../../../shared/orchestration/mailbox/orchestration-report-follow-up' export const ORCHESTRATION_REPLY_METHOD = defineMethod({ name: 'orchestration.reply', @@ -155,6 +160,16 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ if (db.getRun(original.run_id)?.home_database === 'remote') { return await replyToRemoteRunHome({ runtime, db, original, params, signal }) } + // A finished task's worker never reads a reply to its report; refuse before marking or storing anything. + const reportDispatchId = completionReportDispatchId(db, original) + const followUp = reportDispatchId ? reportFollowUpAction(db, reportDispatchId) : undefined + if (reportDispatchId && followUp) { + throw new OrchestrationError( + 'dispatch_inactive', + formatFinishedReportReplyRefusal(reportDispatchId, followUp), + { effectsApplied: false, followUp } + ) + } const recipient = resolveReplyRecipient({ runtime, db, @@ -171,7 +186,10 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ runId: recipient.runId }) - const receipt = { message: exposeMessage(reply) } + const receipt = { + message: exposeMessage(reply), + ...(recipient.warning ? { warnings: [recipient.warning] } : {}) + } return recordReceiptBeforeNudge(recordMutationReceipt, receipt, () => runtime.notifyMessageArrived(reply.to_handle, reply.type) ) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-safety.test.ts b/src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-safety.test.ts index ef261e96ea4..bf76f34c2ef 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-safety.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-safety.test.ts @@ -328,7 +328,7 @@ describe('mail for a lead whose pane coordinates its own Run', () => { expect(result).not.toHaveProperty('warnings') }) - it('keeps a reply on the raw handle when the sender has no Run or live pane', async () => { + it('refuses a reply when the sender has no Run or live pane, storing nothing', async () => { setup() const note = db.insertMessage({ from: 'term_offline', @@ -337,13 +337,11 @@ describe('mail for a lead whose pane coordinates its own Run', () => { runId: rootRun.id }) - const reply = await call('orchestration.reply', { - id: note.id, - from: 'term_coord', - body: 'Ack' - }) - - expect(reply).toMatchObject({ message: { to_handle: 'term_offline', run_id: rootRun.id } }) + await expect( + call('orchestration.reply', { id: note.id, from: 'term_coord', body: 'Ack' }) + ).rejects.toMatchObject({ code: 'terminal_not_found' }) + expect(db.getMessageById(note.id)?.read).toBe(0) + expect(db.getAllMessagesForHandle('term_offline')).toHaveLength(0) }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts new file mode 100644 index 00000000000..19f206c77c0 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/finished-report-reply.test.ts @@ -0,0 +1,90 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import './worker-resume-session-capture' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +// A coordinator replying to a finished worker's report, through the same calls the CLI makes. +describe('a reply to a finished worker report', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + }) + + async function reportDone() { + const { taskId, dispatchId } = await h.startWorker() + await h.call('orchestration.send', { + from: 'term_worker', + type: 'worker_done', + subject: 'Done', + payload: JSON.stringify({ taskId, dispatchId, outcome: 'succeeded' }) + }) + const report = h.db + .getUnreadMessages(`run:${h.activeRunId}`) + .find((message) => message.type === 'worker_done')! + return { dispatchId, reportId: report.id } + } + + const reply = (id: string) => + h.call('orchestration.reply', { id, from: 'term_coord', body: 'Also fix the docs' }) + + it('is refused without writing anything, and check offers the send that continues the worker', async () => { + h.setup() + const { dispatchId, reportId } = await reportDone() + + await expect(reply(reportId)).rejects.toMatchObject({ + code: 'dispatch_inactive', + data: { effectsApplied: false, followUp: { kind: 'send', dispatchId, active: false } } + }) + expect(h.db.getMessageById(reportId)?.read).toBe(0) + expect(h.db.getAllMessagesForHandle('term_worker')).toHaveLength(0) + expect(h.db.getAllMessagesForHandle(`dispatch:${dispatchId}`)).toHaveLength(0) + + expect(await h.call('orchestration.check', { terminal: 'term_coord' })).toMatchObject({ + messages: [{ id: reportId, follow_up: { kind: 'send', dispatchId, active: false } }] + }) + }) + + it('never lands in a later task on the same terminal, and names that running follow-up', async () => { + h.setup() + const { dispatchId, reportId } = await reportDone() + await h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'Next task', + body: 'unrelated work' + }) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(followUp.status).toBe('dispatched') + const before = h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`).length + + await expect(reply(reportId)).rejects.toMatchObject({ + code: 'dispatch_inactive', + data: { followUp: { kind: 'send', dispatchId: followUp.id, active: true } } + }) + expect(h.db.getAllMessagesForHandle(`dispatch:${followUp.id}`)).toHaveLength(before) + expect(h.db.getAllMessagesForHandle('term_worker')).toHaveLength(0) + }) + + it('refuses another message type to a finished worker by naming the continuing send, not a Run', async () => { + h.setup() + const { dispatchId } = await reportDone() + + const refused: unknown = await h + .call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + type: 'escalation', + subject: 'Look again' + }) + .catch((error: unknown) => error) + + expect(refused).toMatchObject({ + code: 'dispatch_inactive', + message: expect.not.stringContaining(`run:${h.activeRunId}`), + data: { followUp: { kind: 'send', dispatchId, active: false } } + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts index 7231e3e6e85..ae80a2162bc 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { AgentStatusOrchestrationContext } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { AgentHookServer } from '../../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../../orca-runtime' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index 4e718de9a00..1af01cf6710 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -1,4 +1,5 @@ import { createLocalWorkerStartDispatch } from './local-worker-start-dispatch' +import { refuseClaimedWorkerTerminal } from '../../../../orchestration/db/worker-dispatch/worker-terminal-claim' import { probeWorkerOpenCodeModelLaunchSupport } from './worker-opencode-model-preflight' import { resolveWorkerConfiguredAgentParams } from './worker-configured-agent-preflight' import { waitForWorkerAgentReady } from '../../../../terminal/wait/launched-agent-composer-readiness' @@ -138,6 +139,8 @@ export async function startLocalWorker(args: { const hostMode = resolveWorkerStartModeOnHost(runtime, args.mode, resolvedWorktree?.id, agent) let mode = chatWorkerMode(await hostMode, chat) + // Synchronous through the Dispatch insert, so nothing else claims the terminal in between. + refuseClaimedWorkerTerminal(db, params.terminal, runtime, args.followUp?.of) const run = args.bindRun() const started = createLocalWorkerStartDispatch(args, { params, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts index c3314f2bca5..262e84b2298 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/session-worker-observation.ts @@ -1,9 +1,8 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrcaSessionId } from '../../../../../../shared/orca-session-address' +import { isStructuredWorkerHandle } from '../../../../../../shared/orchestration/workers/structured-worker-handle' import { chatAssigneeSessionId, - observeChatAssignee, - type ChatAssigneeObservation + observeChatAssignee } from '../../../../orchestration/workers/lifecycle/chat-assignee' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import { @@ -45,6 +44,7 @@ export async function inspectSessionWorker( if (!structured) { return null } + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) // Structured registry proves pane/lineage identity without a PTY. // Omit agentWait: terminal scans cannot see journal questions, and null falsely claims no wait. const exact = db.isDispatchProcessCurrent({ @@ -69,14 +69,18 @@ export async function inspectSessionWorker( } } -/** A fleet page's chat verdicts, read off the session records a restart leaves uninstalled. */ -export async function chatAssigneeObserver( +/** Session verdicts read records that a restart leaves uninstalled until something asks. */ +export async function ensureSessionWorkerRecords( runtime: Pick, - db: OrchestrationDb, rows: readonly { agentTerminalHandle: string | null }[] -): Promise<(sessionId: OrcaSessionId) => ChatAssigneeObservation> { - if (rows.some((row) => chatAssigneeSessionId(row.agentTerminalHandle))) { +): Promise { + if ( + rows.some( + (row) => + chatAssigneeSessionId(row.agentTerminalHandle) || + isStructuredWorkerHandle(row.agentTerminalHandle) + ) + ) { await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) } - return (sessionId) => observeChatAssignee(sessionId, db) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts new file mode 100644 index 00000000000..efaf9137e9d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts @@ -0,0 +1,194 @@ +// Chat-mode workers have no terminal hook stream; worker-list must read the structured host's own verdict. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { agentSessionConversationView } from '../../../../../../shared/agent-session/lifecycle/agent-session-conversation-view' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' +import type { AgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-record' +import type { FleetAgentStatusEvidence } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-agent-status-evidence' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../../../../shared/agent-session/view/structured-agent-session-projection' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import '../../../../orchestration/db/contract-constants' +import '../../../../orchestration/db/dispatch-row-writer' +import '../../../../orchestration/db/attempt-outcome-projection' + +const hostRef: { current: unknown } = { current: null } + +vi.mock( + '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry', + () => ({ getStructuredAgentSessionHost: () => hostRef.current }) +) + +const { projectWorkerFleet } = await import('./worker-list-projection') +const { ensureSessionWorkerRecords, inspectSessionWorker } = + await import('./session-worker-observation') +const { createSessionWorkerLivenessReader } = + await import('../../../../orchestration/workers/lifecycle/session-worker-liveness') +const { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} = + await import('../../../../orchestration/terminal-authority/structured-sessions/structured-worker-identity') + +const SESSION = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' +const NOW = 10 * 60 * 60 * 1000 +const HOUR = 60 * 60 * 1000 + +function record( + provider: 'codex' | 'claude', + lease: Partial = {} +): AgentSessionRecord { + return { + ...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: SESSION, ...lease })), + provider + } +} + +function installHost(current: AgentSessionRecord, attached: boolean) { + hostRef.current = { + deps: { + store: { + getConversation: () => agentSessionConversationView(current), + listConversations: () => [agentSessionConversationView(current)], + getVisibleSessionTabIndex: () => ({ present: true, sessionIds: [SESSION] }) + } + }, + getSessionTabId: () => `agent-session:${SESSION}`, + hasSession: () => attached + } +} + +/** The session's own status row, as the structured status feed publishes it. */ +function sessionStatus( + state: FleetAgentStatusEvidence['activity']['state'], + at: number +): FleetAgentStatusEvidence { + return { + binding: { kind: 'unresolved', reason: 'pane_not_bound' }, + clock: { kind: 'observed', at }, + deliveredAt: at, + activity: { + paneKey: structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION), + connectionId: null, + state, + agentType: 'codex', + model: null, + worktreeId: 'wt_1', + restoredUnconfirmed: false, + providerSessionOnly: false + } + } +} + +describe('worker-list liveness for chat-mode workers', () => { + let db: OrchestrationDb + beforeEach(() => { + db = new OrchestrationDb(':memory:') + structuredWorkerIdentities.clear() + hostRef.current = null + }) + afterEach(() => db.close()) + + function seed() { + const task = db.createTask({ runId: 'run_legacy_local', spec: 'structured work' }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 9 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle: mintStructuredWorkerHandle(), + paneKey: mintStructuredWorkerPaneKey(SESSION), + processIncarnation: structuredWorkerProcessIncarnation(SESSION), + worktreeId: 'wt_1', + effects: [], + setupState: 'not_configured', + hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), + terminalOwnership: 'created' + }) + db.markWorkerDispatchReady(dispatch.id) + return dispatch.id + } + + function project(statuses: FleetAgentStatusEvidence[]) { + const dispatchId = seed() + const rows = db.listWorkerTerminalResources({ dispatchIds: [dispatchId], limit: 1 }) + return projectWorkerFleet({ + rows, + attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], NOW), + statuses, + limit: 1, + now: NOW, + observeSession: createSessionWorkerLivenessReader(db, statuses) + }).workers[0]! + } + + it('keeps an idle Claude chat worker live after its last turn is hours old', () => { + installHost(record('claude'), true) + const worker = project([sessionStatus('done', NOW - 2 * HOUR)]) + + expect(worker.liveness.verdict).toBe('live') + expect(worker.stage.activity).toBe('done') + expect(worker.attention.requiresAction).toBe(false) + }) + + it('reports a session the host saw exit as exited', () => { + installHost( + record('codex', { + claimStatus: 'released', + deathEvidence: { kind: 'exit-observed', detail: 'provider exited', observedAt: 1 } + }), + false + ) + const worker = project([sessionStatus('done', NOW - HOUR)]) + + expect(worker.liveness).toEqual({ verdict: 'exited', source: 'execution_host' }) + expect(worker.nextAction.kind).toBe('recover') + }) + + it('names the lost host when the session cannot be observed', () => { + const worker = project([]) + + expect(worker.liveness).toEqual({ + verdict: 'unverifiable', + reason: 'host_unavailable', + detail: 'The structured agent-session host is not installed in this runtime generation.' + }) + expect(worker.attention.requiresAction).toBe(true) + }) + + it('installs the session host after a restart before judging a structured worker', async () => { + const dispatchId = seed() + const ended = record('codex', { + claimStatus: 'released', + deathEvidence: { kind: 'exit-observed', detail: 'provider exited', observedAt: 1 } + }) + // After a restart the host is not installed until a caller asks for it. + const runtime = { ensureStructuredAgentSessionHost: async () => installHost(ended, false) } + const rows = db.listWorkerTerminalResources({ dispatchIds: [dispatchId], limit: 1 }) + + await ensureSessionWorkerRecords(runtime, rows) + const listed = projectWorkerFleet({ + rows, + attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], NOW), + statuses: [], + limit: 1, + now: NOW, + observeSession: createSessionWorkerLivenessReader(db, []) + }) + expect(listed.workers[0]!.liveness).toEqual({ verdict: 'exited', source: 'execution_host' }) + + hostRef.current = null + const shown = await inspectSessionWorker(runtime, db, dispatchId, rows[0]!.agentTerminalHandle!) + expect(shown?.status).toBe('exited') + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts index da2e603492e..7ec92f45a9d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts @@ -1,8 +1,7 @@ import { ORCHESTRATION_FLEET_PAGE_MAX, projectOrchestrationFleet, - type FleetDurableWorker, - type OrchestrationFleetWorker + type FleetDurableWorker } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' import { resolveFleetWorkerOutcome } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-outcome-resolution' import { @@ -11,17 +10,12 @@ import { } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership' import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' import type { OrcaRuntimeService } from '../../../../orca-runtime' -import type { OrcaSessionId } from '../../../../../../shared/orca-session-address' -import { - chatAssigneeSessionId, - type ChatAssigneeObservation -} from '../../../../orchestration/workers/lifecycle/chat-assignee' +import { createSessionWorkerLivenessReader } from '../../../../orchestration/workers/lifecycle/session-worker-liveness' import { applyFederatedFleetObservations, - readFederatedFleetSnapshots, - refreshFleetWorkerVerdict + readFederatedFleetSnapshots } from '../federation/federated-fleet-snapshot' -import { chatAssigneeObserver } from './session-worker-observation' +import { ensureSessionWorkerRecords } from './session-worker-observation' export type WorkerListPageParams = { run?: string @@ -37,8 +31,7 @@ export function projectWorkerFleet(args: { limit: number now: number completeProjection?: boolean - /** A chat assignee's verdict; no agent-status row names a chat, so its reach stands in. */ - observeChat?: (sessionId: OrcaSessionId) => ChatAssigneeObservation + observeSession?: Parameters[0]['observeSession'] }) { const workers: FleetDurableWorker[] = args.rows.map((row) => { return { @@ -72,12 +65,12 @@ export function projectWorkerFleet(args: { ...projectOrchestrationFleet({ workers, statuses: args.statuses, + observeSession: args.observeSession, limit: args.limit, now: args.now }), durable } - applyChatAssigneeLiveness(fleet, args.observeChat, args.now) return fleet } @@ -87,6 +80,7 @@ export function projectWorkerFleet(args: { ...projectOrchestrationFleet({ workers: workers.slice(offset, offset + ORCHESTRATION_FLEET_PAGE_MAX), statuses: args.statuses, + observeSession: args.observeSession, limit: ORCHESTRATION_FLEET_PAGE_MAX, now: args.now }).workers @@ -97,35 +91,9 @@ export function projectWorkerFleet(args: { page: { limit: workers.length, total: workers.length, hasMore: false, nextCursor: null }, durable } - applyChatAssigneeLiveness(fleet, args.observeChat, args.now) return fleet } -/** Read off the session records, as worker-show and mail read it: at rest is live, closed exited. */ -function applyChatAssigneeLiveness( - fleet: { workers: OrchestrationFleetWorker[]; durable: ReadonlyMap }, - observeChat: ((sessionId: OrcaSessionId) => ChatAssigneeObservation) | undefined, - now: number -): void { - for (const worker of observeChat ? fleet.workers : []) { - const chat = chatAssigneeSessionId(fleet.durable.get(worker.dispatchId)?.agentTerminalHandle) - // A durable death certificate (a stop, a release) outranks a read of the records. - if (!chat || !observeChat || worker.liveness.verdict === 'exited') { - continue - } - const observed = observeChat(chat) - worker.liveness = - observed.status === 'live' - ? { verdict: 'live', observedAt: now, source: 'execution_host' } - : observed.status === 'exited' - ? { verdict: 'exited', source: 'execution_host' } - : { verdict: 'unverifiable', reason: 'host_unavailable' } - worker.evidence.liveStatus = observed.status === 'live' ? 'fresh' : 'unavailable' - worker.evidence.lastObservedAt = observed.status === 'live' ? now : null - refreshFleetWorkerVerdict(worker, fleet.durable) - } -} - /** worker-list's projection of these rows; includeRemote layers on execution-host verdicts. */ export async function projectWorkerListFleet( runtime: OrcaRuntimeService, @@ -134,17 +102,19 @@ export async function projectWorkerListFleet( ) { const db = runtime.getOrchestrationDb() const now = Date.now() + const statuses = runtime.getOrchestrationFleetAgentStatusSnapshot() + await ensureSessionWorkerRecords(runtime, rows) const fleet = projectWorkerFleet({ rows, attentionFacts: db.getWorkerAttentionFactsForDispatches( rows.map((row) => row.dispatchId), now ), - statuses: runtime.getOrchestrationFleetAgentStatusSnapshot(), + statuses, limit: options.limit, now, completeProjection: options.completeProjection, - observeChat: await chatAssigneeObserver(runtime, db, rows) + observeSession: createSessionWorkerLivenessReader(db, statuses) }) const federated = options.includeRemote ? await readFederatedFleetSnapshots({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts index ff730cba736..775c27929ba 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts @@ -5,7 +5,7 @@ import type { OrchestrationDb } from '../../../../orchestration/db/orchestration import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection' import { projectWorkerFleet } from './worker-list-projection' -import { observeChatAssignee } from '../../../../orchestration/workers/lifecycle/chat-assignee' +import { createSessionWorkerLivenessReader } from '../../../../orchestration/workers/lifecycle/session-worker-liveness' import { inspectSessionWorker } from './session-worker-observation' import type { DispatchContextRow, @@ -214,13 +214,14 @@ export function projectFleetWorkerPage( return null } const now = Date.now() + const statuses = runtime.getOrchestrationFleetAgentStatusSnapshot() return projectWorkerFleet({ rows, attentionFacts: db.getWorkerAttentionFactsForDispatches([dispatchId], now), - statuses: runtime.getOrchestrationFleetAgentStatusSnapshot(), + statuses, limit: 1, now, - observeChat: (sessionId) => observeChatAssignee(sessionId, db) + observeSession: createSessionWorkerLivenessReader(db, statuses) }) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts deleted file mode 100644 index bbbd83ab00f..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { MAX_TIMER_DELAY_MS } from '../../../../../../shared/timer-delay' -import { ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS } from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import { resolveFederatedWorkerStartBudgets } from './worker-start-budgets' - -describe('worker-start transport budgets', () => { - it('does not silently shorten an overflowing request', () => { - const timeoutMs = MAX_TIMER_DELAY_MS - ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS + 1 - expect(() => resolveFederatedWorkerStartBudgets(timeoutMs, 1_000)).toThrow( - 'derived timeout must fit' - ) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts new file mode 100644 index 00000000000..ec82660373d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-busy-terminal.test.ts @@ -0,0 +1,98 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { getFollowUpDispatch } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/terminal-authority/release/worker-terminal-auto-release-scheduler' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +describe('worker-start onto a terminal another Dispatch holds', () => { + const h = createOrchestrationWorkerReleaseHarness() + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + }) + + const rows = () => + h.db.db + .prepare( + 'SELECT (SELECT count(*) FROM tasks) AS tasks, (SELECT count(*) FROM dispatch_contexts) AS dispatches' + ) + .get() + const startOnWorker = () => + h.call('orchestration.workerStart', { + from: 'term_coord', + terminal: 'term_worker', + spec: 'next task' + }) + const send = (dispatchId: string) => + h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'More', + body: 'and the docs' + }) + /** Holds the next readiness wait on the reused terminal until released. */ + const holdReadiness = () => { + const held = h.deferred() + const wait = vi.mocked(h.runtime.waitForTerminal).getMockImplementation() + vi.mocked(h.runtime.waitForTerminal).mockImplementationOnce(async (...args) => { + await held.promise + return wait!(...args) + }) + return held + } + + it('is refused before any Task, Dispatch or readiness wait, naming the open Dispatch', async () => { + h.setup() + const { dispatchId } = await h.startWorker() + const before = rows() + const waits = vi.mocked(h.runtime.waitForTerminal).mock.calls.length + + const refusal = await startOnWorker().catch((error: unknown) => error) + + expect(refusal).toMatchObject({ + code: 'terminal_busy', + data: { effectsApplied: false, dispatchId } + }) + expect(refusal).toMatchObject({ + message: expect.stringContaining(`send --to dispatch:${dispatchId}`) + }) + expect(refusal).toMatchObject({ + message: expect.stringContaining(`worker-stop --dispatch ${dispatchId}`) + }) + expect(rows()).toEqual(before) + expect(vi.mocked(h.runtime.waitForTerminal).mock.calls).toHaveLength(waits) + }) + + it('refuses worker-start while a follow-up is starting on the finished worker', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + const held = holdReadiness() + const followUp = send(dispatchId) + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) + const followUpId = getFollowUpDispatch(h.db, dispatchId)!.id + + await expect(startOnWorker()).rejects.toMatchObject({ + code: 'terminal_busy', + data: { effectsApplied: false, dispatchId: followUpId } + }) + held.resolve() + await expect(followUp).resolves.toMatchObject({ state: 'ready', dispatchId: followUpId }) + }) + + it('refuses the follow-up a send would start while worker-start is starting there', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + const dispatches = h.db.db.prepare('SELECT * FROM dispatch_contexts').all().length + const held = holdReadiness() + const start = startOnWorker() + await vi.waitFor(() => expect(rows()).toMatchObject({ dispatches: dispatches + 1 })) + + await expect(send(dispatchId)).rejects.toMatchObject({ + code: 'terminal_busy', + data: { effectsApplied: false } + }) + expect(getFollowUpDispatch(h.db, dispatchId)).toBeUndefined() + held.resolve() + await expect(start).resolves.toMatchObject({ state: 'ready' }) + }) +}) diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts index b06374b42a6..5fb0666abc1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate.ts @@ -132,6 +132,24 @@ export async function requireRenameStructuredHost( export function structuredCallerFor(ctx: RpcContext): StructuredAgentSessionCaller { return { clientKind: ctx.clientKind, + telemetryOwnerKey: + ctx.caller?.kind === 'paired-device' + ? ctx.clientKind === 'runtime' + ? ctx.caller.deviceId + : ctx.clientKind === 'mobile' + ? ctx.pairedDeviceParentId + : undefined + : undefined, + userClient: + ctx.caller?.kind === 'desktop' + ? 'desktop' + : ctx.caller?.kind === 'paired-device' + ? ctx.clientKind === 'mobile' + ? 'mobile' + : ctx.clientKind === 'runtime' + ? 'desktop' + : undefined + : undefined, callerKey: ctx.caller?.kind === 'paired-device' ? rpcCallerOperationKey(ctx.caller) diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts index 0ffd9e9066a..fdab266aaf1 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts @@ -1,3 +1,9 @@ +import { createRestTestRig } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' +import { forkTestSource } from '../../../../../native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture' +import { agentSessionRecordFixture } from '../../../../../native-chat/agent-session-record-test-fixture' +import { codexProviderHandle } from '../../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { resolveStructuredAgentSessionForkIntent } from '../../../../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent' +import { structuredAgentSessionCreateParams } from '../../../../../../shared/agent-session/structured-agent-session-create' import { EVERY_AGENT_CHAT } from '../../../../../../shared/native-chat/every-agent-chat.test-fixture' // Before attach, classify no-effects refusal; at/after attach, failure cannot prove no session exists. @@ -164,3 +170,143 @@ describe('a create refused before it commits', () => { expect(attach).not.toHaveBeenCalled() }) }) + +async function forkHost() { + const rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) + const test = forkTestSource(rig) + test.snapshot.items[2]!.itemId = 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1' + const child = agentSessionRecordFixture({ + ...test.record, + sessionId: 'copied-chat', + providerHandleChain: [ + { + ...test.record.providerHandleChain[0]!, + handle: codexProviderHandle('019e6b26-18e2-7103-b7a0-7ba6bb071124') + } + ], + forkedFrom: { + sessionId: 'source-chat', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071123:completed-turn:1', + childBoundary: { + kind: 'item', + itemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1' + } + } + }) + const childSnapshot = { + ...structuredClone(test.snapshot), + sessionId: child.sessionId, + items: test.snapshot.items.map((item) => ({ + ...item, + itemId: item.itemId.replace( + '019e6b26-18e2-7103-b7a0-7ba6bb071123', + '019e6b26-18e2-7103-b7a0-7ba6bb071124' + ) + })) + } + const records = new Map([ + ['copied-chat', child], + ['source-chat', test.record] + ]) + const getRecord = rig.store.getRecord.bind(rig.store) + const select = rig.store.selectWritableRecord.bind(rig.store) + const writable = rig.store.requireWritableRecord.bind(rig.store) + vi.spyOn(rig.store, 'getRecord').mockImplementation((id) => records.get(id) ?? getRecord(id)) + vi.spyOn(rig.store, 'requireWritableRecord').mockImplementation( + (id) => records.get(id) ?? writable(id) + ) + vi.spyOn(rig.store, 'selectWritableRecord').mockImplementation((id) => + records.has(id) ? { kind: 'writable', record: records.get(id)! } : select(id) + ) + const snapshot = rig.host.journalSnapshot.bind(rig.host) + vi.spyOn(rig.host, 'journalSnapshot').mockImplementation((id) => + id === 'copied-chat' + ? Promise.resolve(childSnapshot) + : id === 'source-chat' + ? Promise.resolve(test.snapshot) + : snapshot(id) + ) + const capabilities = rig.host.deps.agents.capabilities.bind(rig.host.deps.agents) + vi.spyOn(rig.host.deps.agents, 'capabilities').mockImplementation((agent) => { + const supported = capabilities(agent) + return supported ? { ...supported, fork: 'checkpoint' } : null + }) + rig.host.deps.adapter.copyConversation = test.copy + setStructuredAgentSessionHost(rig.host) + const createFork = (sessionId: string) => + create( + { + resolveStructuredAgentSessionCreateIntent: async ( + input: Parameters[0] + ) => { + if (!input.forkFrom) { + throw new Error('Expected a fork intent') + } + return resolveStructuredAgentSessionForkIntent({ + ...input, + forkFrom: input.forkFrom, + host: rig.host, + location: test.record.location + }) + } + }, + structuredAgentSessionCreateParams({ + sessionId, + worktree: WORKTREE, + agent: 'codex', + forkFrom: { + sessionId: 'copied-chat', + throughItemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1' + }, + randomUuid: () => '00000000-0000-0000-0000-000000000001', + now: 1800000000000 + }) + ) + return { rig, test, records, createFork } +} + +it('preserves source-admission proof through real fork create without publishing a destination', async () => { + const { rig, test, records, createFork } = await forkHost() + try { + records.delete('source-chat') + expect(refusalOf(await createFork('codex_missing_original'))).toMatchObject({ + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' }, + createAttemptRefusedBeforeCommit: true + }) + expect(rig.store.getRecord('codex_missing_original')).toBeNull() + records.set('source-chat', test.record) + test.snapshot.items = test.snapshot.items.slice(0, 1) + expect(refusalOf(await createFork('codex_removed_original_reply'))).toMatchObject({ + code: 'agent_session_operation_invalid', + details: { reason: 'savedConversationMissing' }, + createAttemptRefusedBeforeCommit: true + }) + expect(rig.store.getRecord('codex_removed_original_reply')).toBeNull() + } finally { + setStructuredAgentSessionHost(null) + await rig.dispose() + } +}) + +it('does not prove no copy when source revalidation fails after the native copy', async () => { + const { rig, test, createFork } = await forkHost() + try { + const nativeCopy = test.copy.getMockImplementation()! + test.copy.mockImplementationOnce(async (input) => { + const copy = await nativeCopy(input) + test.snapshot.items = test.snapshot.items.slice(0, 1) + return copy + }) + const refusal = refusalOf(await createFork('codex_changed_after_copy')) + expect(refusal).toMatchObject({ + code: 'agent_session_operation_invalid', + details: { reason: 'savedConversationMissing' } + }) + expect(refusal).not.toHaveProperty('createAttemptRefusedBeforeCommit') + expect(rig.store.getRecord('codex_changed_after_copy')).toBeNull() + } finally { + setStructuredAgentSessionHost(null) + await rig.dispose() + } +}) diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts index fcff7ffa12e..46a1484336b 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.ts @@ -40,12 +40,16 @@ const PRECOMMIT_REFUSAL_MESSAGE = 'Orca cannot open a structured agent chat for function precommitRefusal(error: unknown, agent?: string): AgentSessionWireRefusal { // A refusal the host raised keeps its situation; a bare code names none. if (isAgentSessionRefusalError(error)) { - return agentSessionRefusalFromReference( + const refusal = agentSessionRefusalFromReference( error.refusal, error.cause instanceof AgentConversationCopyError ? error.cause.message : PRECOMMIT_REFUSAL_MESSAGE ) + return error.cause instanceof AgentConversationCopyError && + error.refusal.createAttemptRefusedBeforeCommit + ? { ...refusal, createAttemptRefusedBeforeCommit: true } + : refusal } const code = wireRefusalCode(error) if (code) { diff --git a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts index 2841c1aa37e..76b1dad635f 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts @@ -5,7 +5,7 @@ import { import { defineMethod, defineStreamingMethod } from '../../core' import { bindStructuredAgentSessionStream } from '../structured-sessions/subscriptions/structured-agent-session-status-stream' import { TerminalViewClaudeAgent } from '../../../../../shared/rpc-contract/terminal-unary-params' -import { agentHookServer } from '../../../../agent-hooks/server' +import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { assertTerminalAgentSendable } from '../../terminal-agent-send-guard' import { assertTerminalSendExactPtyBinding, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts index c8c07ee0e88..001bfb60da3 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts @@ -1,5 +1,5 @@ import type { z } from 'zod' -import { agentHookServer } from '../../../../agent-hooks/server' +import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../orca-runtime' import type { TerminalSend } from '../../../../../shared/rpc-contract/terminal-unary-params' import { diff --git a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts b/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts index edeb1145994..7d09650965e 100644 --- a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts +++ b/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from './dispatcher' import { diff --git a/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts b/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts index 2a9e7fcf539..ea948afe817 100644 --- a/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts +++ b/src/main/runtime/rpc/server/pairing/e2ee-keypair.ts @@ -67,12 +67,20 @@ export function loadOrCreateE2EEKeypair(userDataPath: string): E2EEKeypair { } } + return writeNewE2EEKeypair(userDataPath) +} + +/** Atomically replaces any stored keypair with a fresh one. */ +export function writeNewE2EEKeypair( + userDataPath: string, + write: (path: string, value: unknown) => boolean = writeSecureJsonFile +): E2EEKeypair { const keypair = nacl.box.keyPair() const publicKeyB64 = Buffer.from(keypair.publicKey).toString('base64') const secretKeyB64 = Buffer.from(keypair.secretKey).toString('base64') const data: KeypairFile = { v: KEYPAIR_VERSION, publicKeyB64, secretKeyB64 } - writeSecureJsonFile(filePath, data) + write(join(userDataPath, KEYPAIR_FILENAME), data) return { publicKey: keypair.publicKey, secretKey: keypair.secretKey, publicKeyB64 } } diff --git a/src/main/runtime/rpc/server/runtime-rpc-binary-routing.ts b/src/main/runtime/rpc/server/runtime-rpc-binary-routing.ts index 7175c095868..d85122753a5 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-binary-routing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-binary-routing.ts @@ -2,6 +2,7 @@ import type { WebSocket } from 'ws' import type { TerminalStreamFrame } from '../../../../shared/terminal/stream/terminal-stream-protocol' import { DeviceRegistry } from './pairing/device-registry' import { loadOrCreateE2EEKeypair, type E2EEKeypair } from './pairing/e2ee-keypair' +import { ensureHostInstanceIdentity, type HostIdentityOutcome } from '../../host-instance-identity' import { RuntimeRpcState } from './runtime-rpc-state' import { DEVICE_REGISTRY_UNAVAILABLE_GUIDANCE, @@ -86,6 +87,16 @@ export class RuntimeRpcBinaryRouting extends RuntimeRpcState { } protected initializePairingIdentity(): PairingIdentityInitialization { + try { + logHostIdentityOutcome(ensureHostInstanceIdentity(this.userDataPath)) + } catch (error) { + // A rotation that started but could not finish must not be served; the next start finishes it. + console.error('[runtime] Failed to finish rotating the pairing identity:', error) + return { + ok: false, + failure: pairingUnavailable('e2ee_key_unavailable', E2EE_KEY_UNAVAILABLE_GUIDANCE) + } + } let deviceRegistry: DeviceRegistry try { deviceRegistry = new DeviceRegistry(this.userDataPath) @@ -112,3 +123,21 @@ export class RuntimeRpcBinaryRouting extends RuntimeRpcState { return { ok: true, deviceRegistry, e2eeKeypair } } } + +function logHostIdentityOutcome(outcome: HostIdentityOutcome): void { + if (outcome.kind === 'kept') { + console.error( + '[runtime] Could not apply ORCA_INSTANCE_ID; serving the existing pairing identity unchanged. Orca retries on the next start.', + outcome.error + ) + } else if (outcome.kind === 'rotated' && outcome.reason === 'instance_changed') { + // Loud on purpose: a value that changes on every start would un-pair clients each time. + console.error( + '[runtime] ORCA_INSTANCE_ID differs from the value recorded with this pairing identity, so Orca created a new identity and removed all paired devices. Clients must pair with this host again. If this host was not copied, set ORCA_INSTANCE_ID to a value that stays the same across restarts.' + ) + } else if (outcome.kind === 'rotated') { + console.error( + '[runtime] Finished an interrupted pairing identity rotation. Clients must pair with this host again.' + ) + } +} diff --git a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts index 6f75116275a..9a6c89046ab 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts @@ -1,3 +1,5 @@ +import { stat } from 'node:fs/promises' +import { basename, join } from 'node:path' import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../../../shared/agent-launch/contracts/agent-launch-runtime-capability' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { placeUnshownLiveTerminalsBestEffort } from '../../terminal/adoption/unshown-live-terminal-placement' @@ -25,8 +27,13 @@ import { } from './runtime-rpc-pairing-types' import { createRuntimeTransportMetadata, + runtimeSocketDirs, sweepOrphanedRuntimeSockets } from './runtime-rpc-socket-metadata' +import { + daemonSocketDirIsTrusted, + ensureDaemonSocketDir +} from '../../../daemon/endpoint/publication/daemon-socket-endpoint-path' import { errorMessage } from '../../../../shared/error-message' import { loadHostDescriptor, @@ -39,11 +46,6 @@ export class RuntimeRpcLifecycle extends RuntimeRpcWebSocketDispatch { return } - // Sweep sockets orphaned by SIGKILL/OOM; Windows pipes leave no files. - if (this.platform !== 'win32') { - sweepOrphanedRuntimeSockets(this.userDataPath, this.pid) - } - const transportMeta = createRuntimeTransportMetadata( this.userDataPath, this.pid, @@ -51,6 +53,27 @@ export class RuntimeRpcLifecycle extends RuntimeRpcWebSocketDispatch { this.runtime.getRuntimeId() ) + // Verify a relocated dir's owner before anything lists or unlinks inside it. + if (transportMeta.kind === 'unix') { + ensureDaemonSocketDir(transportMeta.endpoint) + } + + // Sweep sockets orphaned by SIGKILL/OOM; Windows pipes leave no files. + if (this.platform !== 'win32') { + for (const dir of runtimeSocketDirs(this.userDataPath)) { + if ( + dir === this.userDataPath || + ((await stat(dir).then( + () => true, + () => false + )) && + daemonSocketDirIsTrusted(join(dir, basename(transportMeta.endpoint)))) + ) { + sweepOrphanedRuntimeSockets(dir, this.pid) + } + } + } + const socketTransport = new UnixSocketTransport({ endpoint: transportMeta.endpoint, kind: transportMeta.kind as 'unix' | 'named-pipe', diff --git a/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts b/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts index 512839e8750..88be749ebbf 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts @@ -1,13 +1,14 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' import '../unused-default-rpc-methods.test-fixture' -import { existsSync, mkdtempSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { dirname, join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' import * as runtimeMetadataModule from './runtime-metadata' import { readRuntimeMetadata, writeRuntimeMetadata } from './runtime-metadata' +import { shortDaemonSocketDir } from '../../../daemon/endpoint/publication/daemon-socket-endpoint-path' import { createRuntimeTransportMetadata } from './runtime-rpc-socket-metadata' import { OrcaRuntimeRpcServer } from './runtime-rpc' @@ -153,4 +154,28 @@ describe('OrcaRuntimeRpcServer', () => { writeMetadataSpy.mockRestore() }) + + it.skipIf(process.platform === 'win32')( + 'never sweeps inside a relocated socket dir that is not private to this user', + async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const relocatedDir = shortDaemonSocketDir(userDataPath, process.getuid!()) + mkdirSync(dirname(relocatedDir), { recursive: true, mode: 0o700 }) + mkdirSync(relocatedDir, { recursive: true, mode: 0o755 }) + const deadSocket = join(relocatedDir, 'o-99999999-dead.sock') + writeFileSync(deadSocket, '') + const server = new OrcaRuntimeRpcServer({ + methods: [], + runtime: new OrcaRuntimeService(), + userDataPath + }) + try { + await server.start() + expect(existsSync(deadSocket)).toBe(true) + } finally { + await server.stop() + rmSync(relocatedDir, { recursive: true, force: true }) + } + } + ) }) diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts index 03365ca82c6..97cb6df3fd1 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing-offer.test.ts @@ -1,13 +1,13 @@ import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' import '../unused-default-rpc-methods.test-fixture' -import { mkdirSync, mkdtempSync } from 'node:fs' +import { cpSync, mkdirSync, mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../orca-runtime' import { OrcaRuntimeRpcServer } from './runtime-rpc' -import '../../../../shared/remote-runtime/pairing/pairing' +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' import { DEVICE_REGISTRY_FILENAME } from './pairing/mobile-pairing-files' import '../../../../shared/remote-runtime/host-store/runtime-e2ee-keypair-file' import '../methods/host-management/status' @@ -49,6 +49,46 @@ const { getWorktreeListingMocks } = vi.hoisted(() => { }) describe('OrcaRuntimeRpcServer', () => { + it('gives a copy started with another ORCA_INSTANCE_ID its own key and drops copied tokens', async () => { + const pairingFrom = async (userDataPath: string, instanceId: string) => { + vi.stubEnv('ORCA_INSTANCE_ID', instanceId) + const server = new OrcaRuntimeRpcServer({ + methods: [], + runtime: new OrcaRuntimeService(), + userDataPath, + enableWebSocket: true, + wsPort: 0 + }) + await server.start() + const offer = server.createPairingOffer({ name: 'Clone test' }) + return { server, parsed: offer.available ? parsePairingCode(offer.pairingUrl) : null } + } + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const source = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const clone = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + try { + const original = await pairingFrom(source, 'vm-a') + await original.server.stop() + const sourceToken = original.parsed?.deviceToken ?? '' + expect(sourceToken).toBeTruthy() + cpSync(source, clone, { recursive: true }) + + const cloned = await pairingFrom(clone, 'vm-b') + expect(cloned.parsed?.publicKeyB64).toBeTruthy() + expect(cloned.parsed?.publicKeyB64).not.toBe(original.parsed?.publicKeyB64) + expect(cloned.server.getDeviceRegistry()?.validateToken(sourceToken)).toBeNull() + await cloned.server.stop() + + const restarted = await pairingFrom(source, 'vm-a') + expect(restarted.parsed?.publicKeyB64).toBe(original.parsed?.publicKeyB64) + expect(restarted.server.getDeviceRegistry()?.validateToken(sourceToken)).not.toBeNull() + await restarted.server.stop() + } finally { + vi.unstubAllEnvs() + errorSpy.mockRestore() + } + }) + it('reports a registry persistence failure without retaining a ghost credential', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const server = new OrcaRuntimeRpcServer({ diff --git a/src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts b/src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts index 72a183fa1f1..163f7c69cc6 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts @@ -1,14 +1,28 @@ import { readdirSync, rmSync } from 'node:fs' import { join } from 'node:path' import type { RuntimeTransportMetadata } from '../../../../shared/runtime-bootstrap' +import { + resolveDaemonUnixSocketPath, + shortDaemonSocketDir +} from '../../../daemon/endpoint/publication/daemon-socket-endpoint-path' // MUST match createRuntimeTransportMetadata's o-${pid}-${suffix}.sock naming; unit tests enforce parity. export const RUNTIME_SOCKET_NAME_REGEX = /^o-(\d+)-[A-Za-z0-9_-]+\.sock$/ -export function sweepOrphanedRuntimeSockets(userDataPath: string, ownPid: number): void { +/** Dirs that can hold this userData's runtime sockets: itself and its relocated short dir. */ +export function runtimeSocketDirs( + userDataPath: string, + uid: number | undefined = process.getuid?.() +): string[] { + return uid === undefined + ? [userDataPath] + : [userDataPath, shortDaemonSocketDir(userDataPath, uid)] +} + +export function sweepOrphanedRuntimeSockets(socketDir: string, ownPid: number): void { let entries: string[] try { - entries = readdirSync(userDataPath) + entries = readdirSync(socketDir) } catch { // First launch may have no userData to sweep. return @@ -32,7 +46,7 @@ export function sweepOrphanedRuntimeSockets(userDataPath: string, ownPid: number } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') { try { - rmSync(join(userDataPath, entry), { force: true }) + rmSync(join(socketDir, entry), { force: true }) } catch { // Sweep best-effort; later startup or reboot handles unlink failures. } @@ -57,6 +71,7 @@ export function createRuntimeTransportMetadata( } return { kind: 'unix', - endpoint: join(userDataPath, `o-${pid}-${endpointSuffix}.sock`) + // Long userData paths overflow sun_path (EINVAL); relocate like the daemon socket. + endpoint: resolveDaemonUnixSocketPath(userDataPath, `o-${pid}-${endpointSuffix}.sock`, platform) } } diff --git a/src/main/runtime/rpc/server/runtime-socket-sweep.test.ts b/src/main/runtime/rpc/server/runtime-socket-sweep.test.ts index 16725cb0f23..21930770506 100644 --- a/src/main/runtime/rpc/server/runtime-socket-sweep.test.ts +++ b/src/main/runtime/rpc/server/runtime-socket-sweep.test.ts @@ -6,7 +6,10 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { sweepOrphanedRuntimeSockets } from './runtime-rpc-socket-metadata' +import { + createRuntimeTransportMetadata, + sweepOrphanedRuntimeSockets +} from './runtime-rpc-socket-metadata' describe('sweepOrphanedRuntimeSockets', () => { // Use an always-live non-runner pid (POSIX init) to distinguish own-pid skip, live sibling retention and dead sweep. @@ -37,3 +40,16 @@ describe('sweepOrphanedRuntimeSockets', () => { } ) }) + +describe('createRuntimeTransportMetadata', () => { + it.runIf(process.platform !== 'win32')( + 'keeps the socket path within the macOS sun_path limit for a long userData path', + () => { + const userDataPath = `/Users/someone/${'x'.repeat(130)}/userdata` + const { endpoint } = createRuntimeTransportMetadata(userDataPath, 12345, 'darwin', 'rt') + // macOS listen() returns EINVAL past 103 bytes (sun_path is 104 including NUL). + expect(Buffer.byteLength(endpoint)).toBeLessThanOrEqual(103) + expect(endpoint).toMatch(/^\/tmp\/\.orca-daemon-\d+\/[0-9a-f]{12}\/o-12345-rt\.sock$/) + } + ) +}) diff --git a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts b/src/main/runtime/rpc/terminal-claude-agent-view.test.ts index 6e7269f1f18..c6e45cfedcb 100644 --- a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts +++ b/src/main/runtime/rpc/terminal-claude-agent-view.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from './dispatcher' import { createTerminalInputReservation } from '../terminal/input/terminal-input-admission' diff --git a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts index 7bc7298e4e1..a191155093d 100644 --- a/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts @@ -67,6 +67,7 @@ export abstract class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs exten loading: false, canGoBack: false, canGoForward: false, + faviconUrl: this.agentBrowserBridge?.getRemoteTabFaviconUrl(tab.browserPageId) ?? null, loadError: tab.loadError ?? undefined, certificateFailure: tab.certificateFailure ?? undefined, ...(persistedProps ? { color: persistedProps.color } : {}), diff --git a/src/main/runtime/session-lifecycle/projection/mobile-session-browser-equality.ts b/src/main/runtime/session-lifecycle/projection/mobile-session-browser-equality.ts index e05ab7a166b..48e766c514a 100644 --- a/src/main/runtime/session-lifecycle/projection/mobile-session-browser-equality.ts +++ b/src/main/runtime/session-lifecycle/projection/mobile-session-browser-equality.ts @@ -19,6 +19,7 @@ export function headlessBrowserTabsUnchanged( tab.loading === prev.loading && tab.canGoBack === prev.canGoBack && tab.canGoForward === prev.canGoForward && + (tab.faviconUrl ?? null) === (prev.faviconUrl ?? null) && tab.browserProfileId === prev.browserProfileId && tab.executionHostKey === prev.executionHostKey && ((tab.placement === undefined && prev.placement === undefined) || diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts index 07b47ae9c16..50d798486ab 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts @@ -13,7 +13,7 @@ import type { } from '../../../../shared/runtime-session-contracts' import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { resolveTerminalTabTitle } from '../../../../shared/tab-title-resolution' -import { indexAgentStatusRowsByPaneKey } from '../../../agent-hooks/agent-status-pane-index' +import { indexAgentStatusRowsByPaneKey } from '../../../agent-hooks/runtime/agent-status-pane-index' import { demoteRuntimeMobileAgentStatus, renewRuntimeMobileAgentStatusFromPtyTitle, diff --git a/src/main/runtime/session-tabs/mobile-session-hydration.ts b/src/main/runtime/session-tabs/mobile-session-hydration.ts index eb44f6df004..087f9e10d94 100644 --- a/src/main/runtime/session-tabs/mobile-session-hydration.ts +++ b/src/main/runtime/session-tabs/mobile-session-hydration.ts @@ -259,11 +259,20 @@ export abstract class OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspa ? mergedActiveTab.parentTabId : mergedActiveTab.id : null - const rebuiltTabGroups: RuntimeMobileSessionTabGroup[] = navigationGroups + // Saved groups without a saved active group record no selection; keep the restored tab selected. + const restoredGroups = + hasCurrentNavigation || navigationActiveGroupId || !activeTopLevelId + ? navigationGroups + : navigationGroups?.map((group) => + group.activeTabId === null && group.tabOrder.includes(activeTopLevelId) + ? { ...group, activeTabId: activeTopLevelId } + : group + ) + const rebuiltTabGroups: RuntimeMobileSessionTabGroup[] = restoredGroups ? appendBrowserTabOrder( mergeMobileSessionTabGroups( entryWorktreeId, - navigationGroups, + restoredGroups, mergedTabs, mergedActiveTab?.type === 'terminal' ? mergedActiveTab : null, session.tabGroups?.[entryWorktreeId] diff --git a/src/main/runtime/session-tabs/structured-session-create-support.ts b/src/main/runtime/session-tabs/structured-session-create-support.ts index a904aa5a05e..a784ee9e5c0 100644 --- a/src/main/runtime/session-tabs/structured-session-create-support.ts +++ b/src/main/runtime/session-tabs/structured-session-create-support.ts @@ -1,5 +1,5 @@ import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from '../../../shared/agent-launch/permissions/agent-chat-permission-mode' -import { resolveStructuredAgentSessionForkIntent } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork' +import { resolveStructuredAgentSessionForkIntent } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-fork-intent' import { captureStructuredAgentCliSource, structuredAgentCliSourceFromEvidence diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts index 8ec975df0c4..121339898d9 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts @@ -28,7 +28,7 @@ import { parseWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' import { anySleepKeyNames } from '../terminal/stop/worktree-terminal-sleep-key' -import { resolveAgentWorkspaceExecutionHostId } from '../../agent-hooks/restored-status-dead-terminal-sweep' +import { resolveAgentWorkspaceExecutionHostId } from '../../agent-hooks/observations/restored-status-dead-terminal-sweep' import { WORKTREE_METADATA_DOMAINS } from '../../persistence/loading-store/worktree-identity-metadata' import { isWslMoveProjectBlocked, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts index 4f2402ab6b8..747518ed768 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { hostWorktreeTarget, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts b/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts index 10fd38c8891..4eecc2e8cbc 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts @@ -12,7 +12,7 @@ import { createKeyedTrailingEdgeCoalescer } from '../client/events/keyed-trailin import { agentPaneWorkspace, type AgentPaneWorkspace -} from '../../agent-hooks/agent-transition-detector' +} from '../../agent-hooks/observations/agent-transition-detector' import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' import { isWslMoveProjectBlocked, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts index 78863fa974d..e356416d19a 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts @@ -1,7 +1,7 @@ // Runs on plain Node, as orcad does: the producer and its runtime wiring import no Electron. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-session-contracts' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts index 91b5426aafb..5ab5dfe4ee4 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from '../rpc/dispatcher' import type { RpcDispatchStreamingOptions } from '../rpc/dispatcher-stream-options' diff --git a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts b/src/main/runtime/sidebar-inputs/sort-stamp-records.ts index b713a119305..b3df494b5f8 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamp-records.ts @@ -1,5 +1,5 @@ import { getRepoRegistrationHostIds } from '../../../shared/repo-host-identity' -import type { AgentPaneWorkspace } from '../../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import type { diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts b/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts index a7c1ad2c86a..d6d91090e99 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { AgentStatusStoreView } from './workspace-activity-facts-producer' import '../../../shared/agent-status/contracts/agent-status-subject' @@ -11,7 +11,7 @@ import '../../../shared/sidebar-list/sort-stamps' import type { SmartStampFields } from '../../../shared/sidebar-list/sort-stamps' import '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' import type { AgentTransitionStep } from '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -import { AgentTransitionDetector } from '../../agent-hooks/agent-transition-detector' +import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' import '../../../shared/sidebar-list/stamp-order' import { SortStampsProducer, type StoredTierEvidence } from './sort-stamps-producer' import type { SortStampsStore } from './sort-stamp-records' diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts b/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts index 79fbc652968..62ac2330c75 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts @@ -19,7 +19,7 @@ import { type AgentPaneChange, type AgentPaneWorkspace, type AgentTransitionDetector -} from '../../agent-hooks/agent-transition-detector' +} from '../../agent-hooks/observations/agent-transition-detector' import { listTieredWorkspaces, readSortStamps, diff --git a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts b/src/main/runtime/sidebar-inputs/terminal-use-producer.ts index 120791197ac..91f894f9d0b 100644 --- a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts +++ b/src/main/runtime/sidebar-inputs/terminal-use-producer.ts @@ -3,7 +3,7 @@ import { writeWorkspaceRecord, type WorkspaceRecordStore } from './sort-stamp-records' -import type { AgentPaneWorkspace } from '../../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' /** At most one write per workspace per minute; cleanup judges idleness in days. */ export const TERMINAL_USE_THROTTLE_MS = 60_000 diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts index c396f8b4173..e956f8c0519 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { SidebarClock } from './sidebar-clock' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' import { WorkspaceActivityFactsProducer, diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts index bf26af4845b..21445f85287 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts @@ -17,7 +17,7 @@ import { type WorkspaceActivityFacts, type WorkspaceActivityFactsSnapshot } from '../../../shared/sidebar-list/workspace-activity-facts' -import type { AgentHookServer } from '../../agent-hooks/server' +import type { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { SidebarClock } from './sidebar-clock' export type WorkspaceSurfaceActivity = Omit diff --git a/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts b/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts index 7b8c12b2e50..1d426772c77 100644 --- a/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts +++ b/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts @@ -1,6 +1,6 @@ -import { AgentHookServer } from '../../../agent-hooks/server' -import { agentHookRuntimeDeps } from '../../../agent-hooks/agent-hook-runtime-deps' -import { installHookStatusSessionTabsRepublish } from '../../../agent-hooks/hook-status-session-tabs-republish' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { agentHookRuntimeDeps } from '../../../agent-hooks/runtime/agent-hook-runtime-deps' +import { installHookStatusSessionTabsRepublish } from '../../../agent-hooks/runtime/hook-status-session-tabs-republish' import { AgentStatusObservedPaneIdentities } from './agent-status-observed-pane-identity' type WiredRuntime = { diff --git a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts index 23446b903dd..005bad4d89d 100644 --- a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts +++ b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts @@ -2,7 +2,7 @@ // ORCA_PANE_KEY its env exported, so that key's agent status must follow it to the new pane. import { randomUUID } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { PtyProcessInfo } from '../../../providers/pty-process-info' await import('../../orca-runtime-tests/runtime-test-module-registration.spec') diff --git a/src/main/runtime/terminal/identity/exported-pane-key-follow.ts b/src/main/runtime/terminal/identity/exported-pane-key-follow.ts index 2e02d0cf887..7e344a683b9 100644 --- a/src/main/runtime/terminal/identity/exported-pane-key-follow.ts +++ b/src/main/runtime/terminal/identity/exported-pane-key-follow.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' type ExportedPaneKeyPty = Pick diff --git a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts index 467d33bf8e1..63e4edb4d22 100644 --- a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts +++ b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { forgetFailedAgentLaunches } from '../../../agent-launch/agent-launch-pane-attachment' import type { Store } from '../../../persistence/loading-store/store' import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts b/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts index a0d528e1bc0..83c47c0c9b0 100644 --- a/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts +++ b/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts @@ -4,7 +4,7 @@ import type { RuntimeTerminalPromptDelivery, RuntimeTerminalSend } from '../../../../shared/runtime-terminal-send-contract' -import type { AgentTransitionDetector } from '../../../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../../../agent-hooks/observations/agent-transition-detector' import { OrcaRuntimeWithWriteTerminalAgentPrompt } from './terminal-agent-prompt' import { AgentPromptPermissionReturnedError, diff --git a/src/main/runtime/terminal/output/headless-terminal-state.ts b/src/main/runtime/terminal/output/headless-terminal-state.ts index 51f41c159c3..6df5db366d7 100644 --- a/src/main/runtime/terminal/output/headless-terminal-state.ts +++ b/src/main/runtime/terminal/output/headless-terminal-state.ts @@ -221,6 +221,13 @@ export abstract class OrcaRuntimeWithCreatePtyHeadlessTerminalState extends Orca }) } + /** A resize the PTY took before this mirror existed: the TUI repaints for it, so unlike a reflow it leaves the grid readable. */ + resizeHeadlessTerminalToPtyGrid(ptyId: string, cols: number, rows: number): void { + if (cols > 0 && rows > 0) { + this.resizeHeadlessTerminal(ptyId, cols, rows) + } + } + /** Reflow to provider-proven size after early live bytes used default geometry; preserve renderer restore baselines because no pane was measured. */ reflowHeadlessTerminalToPtyGrid(ptyId: string, cols: number, rows: number): void { if (cols <= 0 || rows <= 0) { diff --git a/src/main/runtime/terminal/output/terminal-buffer-operations.ts b/src/main/runtime/terminal/output/terminal-buffer-operations.ts index 92a911054a0..a1260a785f3 100644 --- a/src/main/runtime/terminal/output/terminal-buffer-operations.ts +++ b/src/main/runtime/terminal/output/terminal-buffer-operations.ts @@ -14,9 +14,13 @@ import { } from './tail/terminal-tail-restore-seed' import { hookLeadTurnState } from '../wait/tui-idle-hook-lane' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { restoreFromReattachedReadyScreen } from '../wait/reattached-ready-screen' +import type { RuledScreen } from '../wait/screen-input-veto' +import type { AgentStatus } from '../../../../shared/agent-status/title/agent-title-core' export abstract class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged { + protected abstract readCaughtUpRuledScreen(ptyId: string): RuledScreen | null protected abstract serializePreferredRestoredTerminalBuffer( ptyId: string, opts?: { scrollbackRows?: number } @@ -246,7 +250,8 @@ export abstract class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRun /** A surviving process main never saw live still has its agent's last own report, which the hook * server restores across restarts. Nothing can type into the terminal while main is down, so the - * report is current as long as an agent, not a shell, still holds the process. */ + * report is current as long as an agent, not a shell, still holds the process. Without a report, + * a screen-ruled agent's own strong ready screen speaks for it: such agents may write no title at rest. */ restoreReattachedAgentStatus(ptyId: string): void { const pty = this.ptysById.get(ptyId) if (!pty?.connected || pty.lastAgentStatusObservedLive) { @@ -254,31 +259,44 @@ export abstract class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRun } const { incarnationId } = pty const generation = this.getPtyLifecycleGeneration(ptyId) + // A respawn, an exit or a live report since the reattach decides instead. + const isCurrent = (): boolean => + this.ptysById.get(ptyId) === pty && + pty.incarnationId === incarnationId && + this.getPtyLifecycleGeneration(ptyId) === generation && + pty.connected && + !pty.lastAgentStatusObservedLive const paneKeys = [...this.collectAgentStatusPaneKeysForPty(ptyId)] void Promise.all([ this.ptyForegroundAgent.identifyForeground(ptyId), + // Why: the ready-screen read needs the seeded snapshot applied. + this.headlessTerminals.get(ptyId)?.writeChain, ...paneKeys.map((paneKey) => agentHookServer.readRestoredAgentStatus(paneKey)) - ]).then(([agent, ...reports]) => { + ]).then(([agent, , ...reports]) => { const report = reports.find((candidate) => candidate !== null) const turn = agent && report ? hookLeadTurnState(report) : null - // A respawn, an exit or a live report since the reattach decides instead. - if ( - !turn || - this.ptysById.get(ptyId) !== pty || - pty.incarnationId !== incarnationId || - this.getPtyLifecycleGeneration(ptyId) !== generation || - !pty.connected || - pty.lastAgentStatusObservedLive - ) { + if (!isCurrent()) { return } - this.applyTrackedPtyTitle(ptyId, pty.lastOscTitle ?? '', pty.lastOscTitle ?? '', undefined, { - statusOnly: true, - status: turn === 'done' ? 'idle' : turn - }) + if (turn) { + this.applyReattachedAgentStatus(ptyId, turn === 'done' ? 'idle' : turn) + } else if (agent) { + restoreFromReattachedReadyScreen({ + agent, + readScreen: () => this.readCaughtUpRuledScreen(ptyId), + readOutputClockAt: () => this.readOutputClockAt(ptyId), + isCurrent, + applyIdle: () => this.applyReattachedAgentStatus(ptyId, 'idle') + }) + } }) } + private applyReattachedAgentStatus(ptyId: string, status: AgentStatus): void { + const title = this.ptysById.get(ptyId)?.lastOscTitle ?? '' + this.applyTrackedPtyTitle(ptyId, title, title, undefined, { statusOnly: true, status }) + } + protected readOutputClockAt(ptyId: string | null | undefined): number | null { const pty = ptyId ? this.ptysById.get(ptyId) : undefined return pty ? (pty.lastOutputAt ?? pty.outputObservedSince ?? null) : null diff --git a/src/main/runtime/terminal/output/terminal-title-observation.ts b/src/main/runtime/terminal/output/terminal-title-observation.ts index 9894093fe8b..6d0b0c76879 100644 --- a/src/main/runtime/terminal/output/terminal-title-observation.ts +++ b/src/main/runtime/terminal/output/terminal-title-observation.ts @@ -6,6 +6,7 @@ import { detectAgentStatusFromTitle } from '../../../../shared/agent-status/titl import { terminalTitleBlocksExplicitAgentStatus } from '../../workspaces/process-listing/runtime-worktree-status-projection' import type { ClaudeTerminalEvidence } from '../../../../shared/claude-terminal-interrupt' import { agentStatusTakesTypedInput } from '../../orchestration/mailbox/routing/mailbox-owner' +import { hermesNativeTitleStatus } from '../../../../shared/agent-status/title/providers/hermes-terminal-title' export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWithGetUnpersistedTrackedTitleForPty { protected abstract collectPaneKeysForPty(ptyId: string): Set @@ -54,6 +55,7 @@ export abstract class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWit protected classifyPtyTitleStatus(ptyId: string, rawTitle: string): AgentStatus | null { return ( this.ptyTitleTrackersByPtyId.get(ptyId)?.programActivity ?? + hermesNativeTitleStatus(rawTitle, this.getPaneTerminalAgent(ptyId)) ?? detectAgentStatusFromTitle(rawTitle) ) } diff --git a/src/main/runtime/terminal/wait/reattached-ready-screen.ts b/src/main/runtime/terminal/wait/reattached-ready-screen.ts new file mode 100644 index 00000000000..f4703af0706 --- /dev/null +++ b/src/main/runtime/terminal/wait/reattached-ready-screen.ts @@ -0,0 +1,71 @@ +import type { TerminalAgent } from '../../../../shared/agent-status/identity/terminal-agent' +import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' +import { + evaluateAgentStateRules, + readsTrustedScreen +} from '../../agent-state-rules/agent-state-rules-engine' +import type { RuledScreen } from './screen-input-veto' +import { TUI_IDLE_QUIESCENCE_MS } from './terminal-idle-policy' + +/** Long enough for a renderer's resize repaint and a redraw-interrupted quiet window. */ +const RECHECK_WINDOW_MS = 60_000 + +type ReattachedReadyScreen = { kind: 'idle' } | { kind: 'recheck'; afterMs: number } | null + +/** Whether a reattached agent's own strong ready rule holds on its trusted grid. Only agents whose + * rules read that grid qualify; a grid not yet readable or a quiet window still owed asks for a + * recheck, and anything else (busy, draft, dialog, unknown screen) answers nothing. */ +function readReattachedReadyScreen( + agent: TerminalAgent | null, + screen: RuledScreen | null, + outputClockAt: number | null +): ReattachedReadyScreen { + if (!isTuiAgent(agent) || !readsTrustedScreen(agent)) { + return null + } + if (!screen) { + return { kind: 'recheck', afterMs: TUI_IDLE_QUIESCENCE_MS } + } + const verdict = evaluateAgentStateRules(agent, { readScreenLines: () => screen.lines }) + if (verdict?.state !== 'idle' || verdict.strength !== 'strong') { + return null + } + const quietRemainingMs = + outputClockAt === null + ? TUI_IDLE_QUIESCENCE_MS + : TUI_IDLE_QUIESCENCE_MS - (Date.now() - outputClockAt) + return !verdict.requiresQuiet || quietRemainingMs <= 0 + ? { kind: 'idle' } + : { kind: 'recheck', afterMs: quietRemainingMs + 50 } +} + +export type ReattachedReadyScreenRestore = { + agent: TerminalAgent + readScreen: () => RuledScreen | null + readOutputClockAt: () => number | null + /** False once a respawn, exit or live status decides instead. */ + isCurrent: () => boolean + applyIdle: () => void +} + +/** Give a reattached agent idle when its ready screen holds, rechecking within a bounded window. */ +export function restoreFromReattachedReadyScreen( + restore: ReattachedReadyScreenRestore, + recheckUntil = Date.now() + RECHECK_WINDOW_MS +): void { + const ready = readReattachedReadyScreen( + restore.agent, + restore.readScreen(), + restore.readOutputClockAt() + ) + if (ready?.kind === 'idle') { + restore.applyIdle() + } else if (ready?.kind === 'recheck' && Date.now() < recheckUntil) { + const recheck = (): void => { + if (restore.isCurrent()) { + restoreFromReattachedReadyScreen(restore, recheckUntil) + } + } + setTimeout(recheck, ready.afterMs).unref?.() + } +} diff --git a/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts index 5170a99dd7e..ae8621abbf0 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts @@ -1,4 +1,4 @@ -import type { AgentTransitionDetector } from '../../../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../../../agent-hooks/observations/agent-transition-detector' import { readCrewRuntimeInputs, watchCrewRuntimeSources diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts index a6c06f9ec09..25f1ab94ca1 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts @@ -14,7 +14,7 @@ import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' -import { AgentHookServer, _internals } from '../../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../../agent-hooks/server/agent-hook-server' import { createTrackedJournalOpener } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import type { AgentSessionJournal } from '../../../native-chat/agent-session-journal/journal-store' import { StructuredAgentSessionStatusFeed } from '../../../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts index 11c6eb83b23..2dae613aa8f 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts @@ -8,7 +8,7 @@ import { StructuredAgentSessionStatusFeed } from '../../../native-chat/agent-ses import { createTrackedJournalOpener } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' -import { AgentHookServer, _internals } from '../../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../../agent-hooks/server/agent-hook-server' import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 6334fb8480e..36045b65990 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -34,8 +34,8 @@ import { } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { openAgentSessionRecordStoreOnce } from '../../agent-session/records/agent-session-record-store-slot' import type { AgentSessionRecordStore } from '../../agent-session/records/agent-session-record-store' -import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from '../../../agent-hooks/first-work-structured-session-rename' -import { firstWorkRenameDeps } from '../../../agent-hooks/first-work-rename-runtime' +import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from '../../../agent-hooks/first-work/first-work-structured-session-rename' +import { firstWorkRenameDeps } from '../../../agent-hooks/first-work/first-work-rename-runtime' import { createStructuredChatNamingHandler } from '../../../native-chat/structured-chat-naming' import { structuredChatNamingDeps } from '../../agent-session/naming/structured-chat-naming-runtime' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' diff --git a/src/main/sqlite/row-cache/keyed-json-row-cache.test.ts b/src/main/sqlite/row-cache/keyed-json-row-cache.test.ts new file mode 100644 index 00000000000..c23eadd9adb --- /dev/null +++ b/src/main/sqlite/row-cache/keyed-json-row-cache.test.ts @@ -0,0 +1,167 @@ +import { + chmodSync, + closeSync, + copyFileSync, + existsSync, + mkdtempSync, + openSync, + rmSync, + writeFileSync, + writeSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import SyncDatabase from '../sync-database' +import { KeyedJsonRowCache, parseKeyedJsonRows } from './keyed-json-row-cache' + +const directories: string[] = [] +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +function paths() { + const directory = mkdtempSync(join(tmpdir(), 'orca-row-cache-')) + directories.push(directory) + return { path: join(directory, 'cache.db'), legacyPath: join(directory, 'cache.json') } +} + +const row = (key: string, value: string) => ({ key, json: JSON.stringify(value) }) +/** An older build's file: a JSON array of strings; anything else is rejected. */ +const parseLegacy = (text: string): string[] | null => { + const value: unknown = JSON.parse(text) + return Array.isArray(value) ? value.map(String) : null +} + +/** What a store restores at startup: imported legacy values, or the stored rows. */ +function restore(cache: KeyedJsonRowCache): unknown { + const loaded = cache.load(parseLegacy) + if (loaded.kind === 'unavailable') { + return 'unavailable' + } + if (loaded.kind === 'import') { + cache.write( + loaded.value.map((value) => row(value, value)), + { importReceipt: loaded.receipt } + ) + return loaded.value + } + return parseKeyedJsonRows(loaded.rows).map(({ value }) => value) +} + +describe('keyed JSON row cache', () => { + it('saves exactly its own rows after another connection committed in between', () => { + const { path } = paths() + const first = new KeyedJsonRowCache(path, { schemaVersion: 1 }) + const second = new KeyedJsonRowCache(path, { schemaVersion: 1 }) + try { + first.write([row('a', 'a1'), row('b', 'b1')]) + second.write([row('a', 'a1'), row('b', 'b1')]) + first.write([row('a', 'a2'), row('b', 'b1')]) + second.write([row('a', 'a1'), row('b', 'b2')]) + + expect(restore(new KeyedJsonRowCache(path, { schemaVersion: 1 }))).toEqual(['a1', 'b2']) + } finally { + first.close() + second.close() + } + }) + + it("imports an older build's file once, even when the same bytes are later restored", () => { + const { path, legacyPath } = paths() + const options = { schemaVersion: 1, holdConnection: false, legacyPath } + writeFileSync(legacyPath, '["from file"]') + copyFileSync(legacyPath, `${legacyPath}.copy`) + + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['from file']) + expect(existsSync(legacyPath)).toBe(false) + new KeyedJsonRowCache(path, options).write([row('x', 'saved later')]) + // A leftover copy (failed deletion, a backup restore) is recognised by its bytes. + copyFileSync(`${legacyPath}.copy`, legacyPath) + + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['saved later']) + expect(existsSync(legacyPath)).toBe(false) + writeFileSync(legacyPath, '["rewritten by an older build"]') + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['rewritten by an older build']) + }) + + it('recognises a file imported under the earlier length:mtime:hash receipt', () => { + const { path, legacyPath } = paths() + const options = { schemaVersion: 1, holdConnection: false, legacyPath } + new KeyedJsonRowCache(path, options).write([row('x', 'saved later')], { + importReceipt: + '13:1700000000000:526aa8236d656e8a8b8cd78bee7a16d95e1e93e99d18a37298c506cf9c789750' + }) + writeFileSync(legacyPath, '["from file"]') + + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['saved later']) + expect(existsSync(legacyPath)).toBe(false) + }) + + it('keeps the stored rows when an older build file is rejected', () => { + const { path, legacyPath } = paths() + const options = { schemaVersion: 1, holdConnection: false, legacyPath } + new KeyedJsonRowCache(path, options).write([row('a', 'stored')]) + writeFileSync(legacyPath, '{ not json') + + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['stored']) + expect(existsSync(legacyPath)).toBe(false) + }) + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'leaves an unreadable older build file and the rows for a later start', + () => { + const { path, legacyPath } = paths() + const options = { schemaVersion: 1, holdConnection: false, legacyPath } + new KeyedJsonRowCache(path, options).write([row('a', 'stored')]) + writeFileSync(legacyPath, '["from file"]') + chmodSync(legacyPath, 0o000) + + expect(restore(new KeyedJsonRowCache(path, options))).toBe('unavailable') + chmodSync(legacyPath, 0o600) + expect(restore(new KeyedJsonRowCache(path, options))).toEqual(['from file']) + } + ) + + it('reports rows held under an exclusive lock as unavailable and keeps the older file', () => { + const { path, legacyPath } = paths() + const options = { schemaVersion: 1, holdConnection: false, legacyPath } + new KeyedJsonRowCache(path, options).write([row('a', 'stored')]) + writeFileSync(legacyPath, '["from file"]') + const locker = new SyncDatabase(path) + locker.pragma('locking_mode = EXCLUSIVE') + locker.exec('BEGIN EXCLUSIVE') + try { + expect(restore(new KeyedJsonRowCache(path, { ...options, busyTimeoutMs: 0 }))).toBe( + 'unavailable' + ) + } finally { + locker.exec('ROLLBACK') + locker.close() + } + expect(existsSync(legacyPath)).toBe(true) + }) + + it('rebuilds a database whose row pages are corrupt and saves again', () => { + const { path } = paths() + new KeyedJsonRowCache(path, { schemaVersion: 1, holdConnection: false }).write([row('a', '1')]) + const db = new SyncDatabase(path) + const root = db.prepare(`SELECT rootpage FROM sqlite_master WHERE name = 'rows'`).get() + const pageSize = Number(db.pragma('page_size', { simple: true })) + db.close() + const fd = openSync(path, 'r+') + writeSync( + fd, + Buffer.from([0xff, 0xff, 0xff, 0xff]), + 0, + 4, + (Number(root?.rootpage) - 1) * pageSize + ) + closeSync(fd) + + new KeyedJsonRowCache(path, { schemaVersion: 1, holdConnection: false }).write([row('b', '2')]) + expect(restore(new KeyedJsonRowCache(path, { schemaVersion: 1 }))).toEqual(['2']) + }) +}) diff --git a/src/main/sqlite/row-cache/keyed-json-row-cache.ts b/src/main/sqlite/row-cache/keyed-json-row-cache.ts new file mode 100644 index 00000000000..e6202151e43 --- /dev/null +++ b/src/main/sqlite/row-cache/keyed-json-row-cache.ts @@ -0,0 +1,349 @@ +import { existsSync } from 'node:fs' +import SyncDatabase from '../sync-database' +import { + openVersionedCacheDatabase, + removeVersionedCacheDatabase +} from '../versioned-cache-database' +import { hardenSqliteDatabaseFiles } from '../harden-database-files' +import { classifyRowCacheFailure } from './row-cache-failure' +import { readLegacyJsonSource, removeLegacyJsonSource } from './legacy-json-source' + +export type KeyedJsonRow = { key: string; json: string } + +export type KeyedJsonRowCacheOptions = { + schemaVersion: number + /** Lock wait per call. Main-thread callers keep it short and retry later instead. */ + busyTimeoutMs?: number + /** False opens and closes the database per call, so no handle outlives it (profile moves). */ + holdConnection?: boolean + /** JSON file older builds wrote; see load(). */ + legacyPath?: string +} + +/** + * What a store hydrates at startup. + * - rows: the stored rows (no older-build file, or one already imported or rejected). + * - import: an older build's file is newer than the rows; save `value` with `receipt`. + * - unavailable: the rows or the file cannot be read now. The store must neither hydrate a + * replacement nor save over rows it never read; `legacy` is the file's value if it was read. + */ +export type KeyedJsonRowLoad = + | { kind: 'rows'; rows: KeyedJsonRow[] } + | { kind: 'import'; value: T; receipt: string; rows: KeyedJsonRow[] } + | { kind: 'unavailable'; error: unknown; legacy?: T } + +type StoredRow = { seq: number; json: string } + +const DEFAULT_BUSY_TIMEOUT_MS = 25 +const RECEIPT_KEY = 'legacy_import_receipt' +const SCHEMA_SQL = `CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS rows(key TEXT PRIMARY KEY, seq INTEGER NOT NULL, value TEXT NOT NULL);` + +/** + * An ordered list of JSON values, one SQLite row each, so a save writes only the rows whose + * value or position changed. Corruption rebuilds the file once; busy and unreadable files + * throw from write(), and callers retry later. + */ +export class KeyedJsonRowCache { + private db: SyncDatabase | null = null + private stored = new Map() + private maxSeq = 0 + private dataVersion: unknown + private closed = false + private readonly busyTimeoutMs: number + + constructor( + readonly path: string, + private readonly options: KeyedJsonRowCacheOptions + ) { + this.busyTimeoutMs = options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS + } + + /** + * Startup read of the rows and, when configured, the older build's file. That file is newer + * than the rows unless the rows record importing exactly its bytes; `parse` returning null + * rejects it. An imported or rejected file is removed here and never replaces the rows. + */ + load(parse: (text: string) => T | null, busyTimeoutMs?: number): KeyedJsonRowLoad { + const legacyPath = this.options.legacyPath + const source = legacyPath ? readLegacyJsonSource(legacyPath) : { kind: 'absent' as const } + const parsed = source.kind === 'read' ? parseOrNull(parse, source.text) : null + const legacy = parsed ?? undefined + const snapshot = this.readSnapshot(busyTimeoutMs ?? this.busyTimeoutMs) + if (snapshot.kind === 'unavailable') { + return { kind: 'unavailable', error: snapshot.error, ...(legacy ? { legacy } : {}) } + } + if (source.kind === 'unreadable') { + // A file that may be newer than the rows cannot be ruled out until it can be read. + return { kind: 'unavailable', error: source.error } + } + if (source.kind === 'read' && legacyPath) { + if (parsed !== null && !receiptNames(snapshot.receipt, source.receipt)) { + return { kind: 'import', value: parsed, receipt: source.receipt, rows: snapshot.rows } + } + // Already imported (its removal failed before) or rejected: the rows stay authoritative. + removeLegacyJsonSource(legacyPath, source.receipt) + } + return { kind: 'rows', rows: snapshot.rows } + } + + /** Hydration rejected an imported value after load(): remove its file, keep the rows. */ + discardLegacy(receipt: string): void { + if (this.options.legacyPath) { + removeLegacyJsonSource(this.options.legacyPath, receipt) + } + } + + /** + * Saves `rows` in order. `importReceipt` records the older build's file these rows now hold, + * in the same transaction, and removes that file once committed. Throws on failure (busy + * included); the baseline is unchanged, so a retry is exact. + */ + write( + rows: readonly KeyedJsonRow[], + options: { importReceipt?: string; busyTimeoutMs?: number } = {} + ): void { + const busyTimeoutMs = options.busyTimeoutMs ?? this.busyTimeoutMs + try { + this.withRebuild(() => this.commit(rows, options.importReceipt, busyTimeoutMs)) + } finally { + // After close() (late events at teardown), each write opens and closes its own handle. + if (this.options.holdConnection === false || this.closed) { + this.closeDatabase() + } + } + if (options.importReceipt !== undefined && this.options.legacyPath) { + removeLegacyJsonSource(this.options.legacyPath, options.importReceipt) + } + } + + close(): void { + this.closed = true + this.closeDatabase() + } + + /** One read-only snapshot: another connection's write lock cannot block it. */ + private readSnapshot( + busyTimeoutMs: number + ): + | { kind: 'rows'; rows: KeyedJsonRow[]; receipt: unknown } + | { kind: 'unavailable'; error: unknown } { + // One-shot startup probe, so an unused store creates no file. + if (!existsSync(this.path)) { + return { kind: 'rows', rows: [], receipt: undefined } + } + let db: SyncDatabase | null = null + try { + db = new SyncDatabase(this.path, { readonly: true, fileMustExist: true }) + db.pragma(`busy_timeout = ${busyTimeoutMs}`) + db.exec('BEGIN') + try { + const tables = db + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('meta', 'rows')" + ) + .all() + const version = + tables.length === 2 + ? db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() + : undefined + if (version?.value !== String(this.options.schemaVersion)) { + // Another layout holds nothing this build reads; the first write rebuilds it. + return { kind: 'rows', rows: [], receipt: undefined } + } + const rows = [...readRows(db).stored].map(([key, { json }]) => ({ key, json })) + return { kind: 'rows', rows, receipt: readReceipt(db) } + } finally { + rollback(db) + } + } catch (error) { + if (classifyRowCacheFailure(error) !== 'corrupt') { + return { kind: 'unavailable', error } + } + db?.close() + db = null + try { + // Damaged rows hold nothing recoverable; the next write rebuilds the cache. + removeVersionedCacheDatabase(this.path, 'fail-fast') + } catch (removeError) { + return { kind: 'unavailable', error: removeError } + } + return { kind: 'rows', rows: [], receipt: undefined } + } finally { + db?.close() + } + } + + private commit( + rows: readonly KeyedJsonRow[], + importReceipt: string | undefined, + busyTimeoutMs: number + ): void { + const db = this.database(busyTimeoutMs) + db.pragma(`busy_timeout = ${busyTimeoutMs}`) + db.exec('BEGIN IMMEDIATE') + try { + // Another connection committed since our baseline: diff against what is on disk. + if (db.pragma('data_version', { simple: true }) !== this.dataVersion) { + this.readBaseline(db) + } + const baseline = this.stored + const next = new Map() + let maxSeq = this.maxSeq + let previous = 0 + for (const { key, json } of rows) { + const old = baseline.get(key) + // Keep a row's position while the order allows it; moved rows go after the rest. + const seq = old && old.seq > previous ? old.seq : ++maxSeq + previous = seq + next.set(key, { seq, json }) + } + const upsert = db.prepare( + `INSERT INTO rows(key, seq, value) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET seq = excluded.seq, value = excluded.value` + ) + for (const [key, row] of next) { + const old = baseline.get(key) + if (!old || old.seq !== row.seq || old.json !== row.json) { + upsert.run(key, row.seq, row.json) + } + } + const remove = db.prepare('DELETE FROM rows WHERE key = ?') + for (const key of baseline.keys()) { + if (!next.has(key)) { + remove.run(key) + } + } + if (importReceipt !== undefined) { + db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)').run( + RECEIPT_KEY, + importReceipt + ) + } + // Sampled while the write lock excludes other writers, so no outside commit hides here. + const version = db.pragma('data_version', { simple: true }) + db.exec('COMMIT') + this.stored = next + this.maxSeq = maxSeq + this.dataVersion = version + } catch (error) { + rollback(db) + throw error + } + } + + /** + * Call inside a transaction: the version is sampled with the rows of the same snapshot, and + * all three are published together, so a failed read never vouches for an older baseline. + */ + private readBaseline(db: SyncDatabase): void { + this.dataVersion = undefined + const version = db.pragma('data_version', { simple: true }) + const { stored, maxSeq } = readRows(db) + this.stored = stored + this.maxSeq = maxSeq + this.dataVersion = version + } + + /** A damaged page can surface on any statement; rebuild once and redo the operation. */ + private withRebuild(operation: () => T): T { + try { + return operation() + } catch (error) { + if (classifyRowCacheFailure(error) !== 'corrupt') { + throw error + } + this.closeDatabase() + // Fail fast: a file held open elsewhere (Windows) throws, and the caller retries later. + removeVersionedCacheDatabase(this.path, 'fail-fast') + return operation() + } + } + + private database(busyTimeoutMs: number): SyncDatabase { + if (this.db) { + return this.db + } + const db = openVersionedCacheDatabase(this.path, { + version: this.options.schemaVersion, + // The caller's budget covers opening too: schema setup writes, so it can meet the lock. + busyTimeoutMs, + removal: 'fail-fast', + // Rows can hold prompts, PR titles and notification ids; keep them user-only. + directoryMode: 0o700, + sql: SCHEMA_SQL + }) + hardenSqliteDatabaseFiles(this.path) + this.db = db + // A fresh connection cannot vouch for a baseline read through an earlier one. + this.dataVersion = undefined + this.stored = new Map() + this.maxSeq = 0 + return db + } + + private closeDatabase(): void { + try { + this.db?.close() + } catch { + // Closing a failed handle must not mask the original error. + } + this.db = null + } +} + +function readRows(db: SyncDatabase): { stored: Map; maxSeq: number } { + const stored = new Map() + let maxSeq = 0 + for (const row of db.prepare('SELECT key, seq, value FROM rows ORDER BY seq').all()) { + const { key, seq, value } = row + if (typeof key === 'string' && typeof seq === 'number' && typeof value === 'string') { + stored.set(key, { seq, json: value }) + maxSeq = Math.max(maxSeq, seq) + } + } + return { stored, maxSeq } +} + +function readReceipt(db: SyncDatabase): unknown { + return db.prepare('SELECT value FROM meta WHERE key = ?').get(RECEIPT_KEY)?.value +} + +function rollback(db: SyncDatabase): void { + if (db.isTransaction) { + db.exec('ROLLBACK') + } +} + +/** Parsed values of rows, skipping any that no longer parse (the next save rewrites them). */ +export function parseKeyedJsonRows( + rows: readonly KeyedJsonRow[] +): { key: string; value: unknown }[] { + return rows.flatMap(({ key, json }) => { + try { + const value: unknown = JSON.parse(json) + return [{ key, value }] + } catch { + return [] + } + }) +} + +function parseOrNull(parse: (text: string) => T | null, text: string): T | null { + try { + return parse(text) + } catch { + return null + } +} + +/** + * Whether a stored import receipt names these bytes. Builds before the shared row cache wrote + * `::`; its hash still identifies the same bytes. + */ +function receiptNames(stored: unknown, receipt: string): boolean { + if (typeof stored !== 'string') { + return false + } + return stored === receipt || /^\d+:\d+:([0-9a-f]{64})$/.exec(stored)?.[1] === receipt +} diff --git a/src/main/sqlite/row-cache/legacy-json-source.ts b/src/main/sqlite/row-cache/legacy-json-source.ts new file mode 100644 index 00000000000..7c5e4e2b7c6 --- /dev/null +++ b/src/main/sqlite/row-cache/legacy-json-source.ts @@ -0,0 +1,45 @@ +import { createHash } from 'node:crypto' +import { readFileSync, rmSync } from 'node:fs' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' + +/** A JSON file an older build may have written, before its rows moved into SQLite. */ +export type LegacyJsonSource = + | { kind: 'absent' } + /** Present but not readable now (permissions, a Windows lock): neither absent nor imported. */ + | { kind: 'unreadable'; error: unknown } + | { kind: 'read'; text: string; receipt: string } + +/** + * One-shot startup read. `receipt` is the hash of these exact bytes (not their mtime, so a + * copied or restored leftover is still recognised as already imported). + */ +export function readLegacyJsonSource(path: string): LegacyJsonSource { + let bytes: Buffer + try { + bytes = readFileSync(path) + } catch (error) { + return isDefinitiveAbsence(error) ? { kind: 'absent' } : { kind: 'unreadable', error } + } + return { + kind: 'read', + text: bytes.toString('utf8'), + receipt: createHash('sha256').update(bytes).digest('hex') + } +} + +/** + * Removes the file only while it still holds the bytes `receipt` names, never a rewrite by + * another build since. One-shot: after the import commits, or when its bytes were rejected. + */ +export function removeLegacyJsonSource(path: string, receipt: string): void { + const current = readLegacyJsonSource(path) + if (current.kind !== 'read' || current.receipt !== receipt) { + return + } + try { + rmSync(path, { force: true }) + } catch (error) { + // A committed receipt marks it imported, so a leftover file cannot shadow newer rows. + console.warn('[sqlite] Could not remove a migrated legacy JSON file:', error) + } +} diff --git a/src/main/sqlite/row-cache/row-cache-failure.ts b/src/main/sqlite/row-cache/row-cache-failure.ts new file mode 100644 index 00000000000..8d6c9a0b69a --- /dev/null +++ b/src/main/sqlite/row-cache/row-cache-failure.ts @@ -0,0 +1,19 @@ +import { isSqliteCorruption, isTransientSqliteContention } from '../sqlite-read-failure' +import { isUnusableDatabaseError } from '../versioned-cache-database' + +/** busy: another connection holds the lock, retry later. corrupt: rebuild. other: report. */ +export type RowCacheFailure = 'busy' | 'corrupt' | 'other' + +export function classifyRowCacheFailure(error: unknown): RowCacheFailure { + if (isTransientSqliteContention(error)) { + return 'busy' + } + return isSqliteCorruption(error) || isUnusableDatabaseError(error) ? 'corrupt' : 'other' +} + +export type RetryBackoff = { readonly minMs: number; readonly maxMs: number } + +/** Doubling delay after `previousMs` (0 for the first failure), clamped to the range. */ +export function nextRetryDelayMs(previousMs: number, { minMs, maxMs }: RetryBackoff): number { + return Math.min(maxMs, Math.max(minMs, previousMs * 2)) +} diff --git a/src/main/sqlite/versioned-cache-database.ts b/src/main/sqlite/versioned-cache-database.ts index cc40d452e9a..5fef05e7fa8 100644 --- a/src/main/sqlite/versioned-cache-database.ts +++ b/src/main/sqlite/versioned-cache-database.ts @@ -1,4 +1,4 @@ -import { mkdirSync } from 'node:fs' +import { mkdirSync, rmSync } from 'node:fs' import { dirname } from 'node:path' import SyncDatabase from './sync-database' import { removeTreeSync } from '../../shared/windows-transient-lock-removal' @@ -14,8 +14,15 @@ export type VersionedCacheDatabaseSchema = { directoryMode?: number // Applies only to a new file; rows near half a default page waste the other half. pageSize?: number + // Main-thread callers pass a short wait so a locked file fails fast instead of freezing. + busyTimeoutMs?: number + // Main-thread callers pass 'fail-fast' so a rebuild blocked by a held file throws at once + // (callers retry later) instead of sleeping through Windows unlock retries. + removal?: CacheDatabaseRemoval } +export type CacheDatabaseRemoval = 'retry' | 'fail-fast' + /** Rebuild unreadable/stale cache schemas: source files remain authoritative, so replacement costs only a rescan instead of stranding the feature. */ export function openVersionedCacheDatabase( path: string, @@ -32,21 +39,21 @@ export function openVersionedCacheDatabase( throw error } // One retry only: a second failure on a file we just created is not corruption. - removeVersionedCacheDatabase(path) + removeVersionedCacheDatabase(path, schema.removal) return openExisting(path, schema) } } function openExisting(path: string, schema: VersionedCacheDatabaseSchema): SyncDatabase { // Null closed handles so cleanup cannot mask the real failure with ERR_INVALID_STATE. - let db: SyncDatabase | null = openWithPragmas(path, schema.pageSize) + let db: SyncDatabase | null = openWithPragmas(path, schema) try { if (isStaleSchema(db, schema.version)) { // Unlink stale caches; dropping multi-GB tables can exceed scanner readiness deadlines. db.close() db = null - removeVersionedCacheDatabase(path) - db = openWithPragmas(path, schema.pageSize) + removeVersionedCacheDatabase(path, schema.removal) + db = openWithPragmas(path, schema) } db.exec(schema.sql) schema.afterSchema?.(db) @@ -65,7 +72,7 @@ function openExisting(path: string, schema: VersionedCacheDatabaseSchema): SyncD const UNUSABLE_DATABASE = /SQLITE_CORRUPT|SQLITE_NOTADB|file is not a database|database disk image is malformed/i -function isUnusableDatabaseError(error: unknown): boolean { +export function isUnusableDatabaseError(error: unknown): boolean { if (!(error instanceof Error)) { return false } @@ -76,11 +83,17 @@ function isUnusableDatabaseError(error: unknown): boolean { ) } -function openWithPragmas(path: string, pageSize: number | undefined): SyncDatabase { +function openWithPragmas( + path: string, + { + pageSize, + busyTimeoutMs = 5000 + }: Pick +): SyncDatabase { const db = new SyncDatabase(path) try { // Set busy timeout before WAL pragmas so another process's lock can clear. - db.pragma('busy_timeout = 5000') + db.pragma(`busy_timeout = ${Math.max(0, Math.trunc(busyTimeoutMs))}`) if (pageSize !== undefined) { db.pragma(`page_size = ${pageSize}`) } @@ -97,12 +110,19 @@ function openWithPragmas(path: string, pageSize: number | undefined): SyncDataba } } -export function removeVersionedCacheDatabase(path: string): void { +export function removeVersionedCacheDatabase( + path: string, + removal: CacheDatabaseRemoval = 'retry' +): void { if (path === ':memory:') { return } for (const suffix of ['', '-wal', '-shm', '-journal']) { - removeTreeSync(`${path}${suffix}`) + if (removal === 'fail-fast') { + rmSync(`${path}${suffix}`, { recursive: true, force: true }) + } else { + removeTreeSync(`${path}${suffix}`) + } } } diff --git a/src/main/ssh/authentication/ssh-agent-identity-filter.test.ts b/src/main/ssh/authentication/ssh-agent-identity-filter.test.ts index 1a09e41f8a0..5efe234e2b1 100644 --- a/src/main/ssh/authentication/ssh-agent-identity-filter.test.ts +++ b/src/main/ssh/authentication/ssh-agent-identity-filter.test.ts @@ -85,30 +85,6 @@ describe('createIdentityFilteredAgent', () => { expect(mocks.readFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub')) }) - it('expands Windows-style configured identity file paths before filtering', async () => { - const allowedKey = makeKey('allowed') - mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed') - mocks.parseKey.mockReturnValue(allowedKey) - mocks.createAgent.mockReturnValue({ - getIdentities: vi.fn((callback) => callback(undefined, [allowedKey])), - sign: vi.fn() - }) - - const agent = createIdentityFilteredAgent('/tmp/agent.sock', ['~\\.ssh\\work_key']) - const identities = await new Promise((resolve, reject) => { - agent?.getIdentities((error, keys) => { - if (error) { - reject(error) - return - } - resolve(keys ?? []) - }) - }) - - expect(identities).toEqual([allowedKey]) - expect(mocks.readFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub')) - }) - it('filters nested public key entries returned by ssh2 agents', async () => { const allowedKey = makeKey('allowed') const otherKey = makeKey('other') diff --git a/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts b/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts index f01c46b5871..43e4f362d3e 100644 --- a/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts +++ b/src/main/ssh/authentication/ssh-keyboard-interactive.test.ts @@ -42,23 +42,6 @@ describe('isKeyboardInteractivePasswordPrompt', () => { }) describe('collectKeyboardInteractiveResponses', () => { - it('forwards verification prompts with instructions and the echo flag', async () => { - const requestCredential = vi.fn(async () => '1') - const session = createSession({ requestCredential }) - - const responses = await collectKeyboardInteractiveResponses(session, 'Choose an option:', [ - { prompt: 'Passcode or option (1-2):', echo: true } - ]) - - expect(responses).toEqual(['1']) - expect(requestCredential).toHaveBeenCalledWith( - 'target-1', - 'keyboard-interactive', - 'Choose an option:\nPasscode or option (1-2):', - true - ) - }) - it('answers a password prompt from the cache without prompting', async () => { const requestCredential = vi.fn(async () => 'unused') const session = createSession({ @@ -108,29 +91,6 @@ describe('collectKeyboardInteractiveResponses', () => { expect(session.isCancelled()).toBe(true) }) - it('short-circuits every later round once cancelled', async () => { - const requestCredential = vi.fn(async () => 'answer') - const session = createSession({ requestCredential }) - session.markCancelled() - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Duo passcode:', echo: false } - ]) - - expect(responses).toBeNull() - expect(requestCredential).not.toHaveBeenCalled() - }) - - it('returns null when no credential prompter is available', async () => { - const session = createSession({ requestCredential: undefined }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password: ', echo: false } - ]) - - expect(responses).toBeNull() - }) - it('discards a password resolved after the attempt is cancelled', async () => { let answer: (value: string) => void = () => {} const requestCredential = vi @@ -153,17 +113,4 @@ describe('collectKeyboardInteractiveResponses', () => { expect(setCachedPassword).not.toHaveBeenCalled() expect(requestCredential).toHaveBeenCalledTimes(1) }) - - it('accepts an empty response without caching it as a password', async () => { - const requestCredential = vi.fn(async () => '') - const setCachedPassword = vi.fn() - const session = createSession({ requestCredential, setCachedPassword }) - - const responses = await collectKeyboardInteractiveResponses(session, '', [ - { prompt: 'Password: ', echo: false } - ]) - - expect(responses).toEqual(['']) - expect(setCachedPassword).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts b/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts deleted file mode 100644 index c2d40ae0c72..00000000000 --- a/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { - createCancelledConnectAttemptError, - isCancelledConnectAttemptError -} from './ssh-connect-attempt-cancellation' -import { isAuthError, isTransientReconnectError } from './ssh-reconnect-error-classification' - -describe('createCancelledConnectAttemptError', () => { - it('is recognisable by identity, not just by message text', () => { - const error = createCancelledConnectAttemptError() - expect(isCancelledConnectAttemptError(error)).toBe(true) - // A cancelled attempt must never look like a permanent failure to the reconnect ladder. - expect(isTransientReconnectError(error)).toBe(false) - expect(isAuthError(error)).toBe(false) - }) - - it('does not classify unrelated errors as cancellations', () => { - expect(isCancelledConnectAttemptError(new Error('connect ETIMEDOUT'))).toBe(false) - }) - - it('ignores a lookalike message from a producer that skipped the factory', () => { - // Every real producer imports the factory, so message text alone must not qualify. - expect( - isCancelledConnectAttemptError(new Error(createCancelledConnectAttemptError().message)) - ).toBe(false) - }) -}) diff --git a/src/main/ssh/connection/ssh-connection-direct-startup.test.ts b/src/main/ssh/connection/ssh-connection-direct-startup.test.ts deleted file mode 100644 index 7d2f9878b22..00000000000 --- a/src/main/ssh/connection/ssh-connection-direct-startup.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { EventEmitter } from 'node:events' -import { - resetSshConnectionMocks, - spawnSystemSshCommandMock -} from './testing/ssh-connection-test-harness' -import { - createCallbacks, - createResolvedConfig, - createTarget -} from './testing/ssh-connection-test-fixtures' -import type { createSystemCommandChannel } from './testing/ssh-connection-test-fixtures' -import { SshConnection } from './ssh-connection' -import { resolveWithSshG } from '../config/ssh-g-config-resolution' - -vi.mock('../authentication/ssh2-module-load', async () => - (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() -) -vi.mock('../system-transport/system-ssh-binary', async () => - (await import('./testing/ssh-connection-test-harness')).createSystemSshBinaryModule() -) -vi.mock('../system-transport/system-ssh-args', async (importOriginal) => - (await import('./testing/ssh-connection-test-harness')).withSystemSshArgsMocks( - await importOriginal() - ) -) -vi.mock('../system-transport/system-ssh-command', async (importOriginal) => - (await import('./testing/ssh-connection-test-harness')).withSystemSshCommandMocks( - await importOriginal() - ) -) -vi.mock( - '../system-transport/file-transfer/system-ssh-file-binary-transfer', - async (importOriginal) => - (await import('./testing/ssh-connection-test-harness')).withSystemSshFileBinaryTransferMocks( - await importOriginal() - ) -) -vi.mock('../system-transport/file-transfer/system-ssh-file-transfer', async (importOriginal) => - (await import('./testing/ssh-connection-test-harness')).withSystemSshFileTransferMocks( - await importOriginal() - ) -) -vi.mock('../system-transport/ssh-control-socket', async () => - (await import('./testing/ssh-connection-test-harness')).createControlSocketModule() -) -vi.mock('../config/ssh-config-parser', async () => - (await import('./testing/ssh-connection-test-harness')).createSshConfigParserModule() -) -vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => - (await import('./testing/ssh-connection-test-harness')).withSshGConfigResolutionMocks( - await importOriginal() - ) -) - -describe('SshConnection', () => { - beforeEach(() => { - resetSshConnectionMocks() - }) - - it('removes system SSH probe listeners after timeout', async () => { - vi.useFakeTimers() - const channel = new EventEmitter() as ReturnType - channel.stdin = { end: vi.fn(), write: vi.fn() } - channel.stderr = new EventEmitter() - channel.close = vi.fn() - spawnSystemSshCommandMock.mockReturnValueOnce(channel) - vi.mocked(resolveWithSshG).mockResolvedValueOnce(createResolvedConfig()) - const conn = new SshConnection(createTarget({ configHost: 'fdpass-host' }), createCallbacks()) - - try { - const connect = expect(conn.connect()).rejects.toThrow('System SSH connection timed out') - await vi.advanceTimersByTimeAsync(30_000) - - await connect - expect(channel.close).toHaveBeenCalled() - expect(channel.listenerCount('data')).toBe(0) - // Lifetime observers remain until physical close, even after the probe timed out. - expect(channel.listenerCount('error')).toBe(2) - expect(channel.listenerCount('close')).toBe(2) - expect(channel.stderr.listenerCount('data')).toBe(0) - expect( - (conn as unknown as { systemCommandChannels: Set }).systemCommandChannels.size - ).toBe(0) - channel.emit('close', 0) - expect(channel.listenerCount('close')).toBe(0) - expect(channel.listenerCount('error')).toBe(1) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts b/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts index 9e3b3c3dd9c..8bf99a85149 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-store-wiring.test.ts @@ -1,7 +1,7 @@ /** Prove accepted first-contact keys persist and inform later connections. Isolate the bound module-level store: real disk I/O cannot settle inside the shared reconnect suite's fake ticks. */ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { Socket } from 'node:net' -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as SshGConfigResolution from '../config/ssh-g-config-resolution' @@ -66,11 +66,7 @@ vi.mock('../config/ssh-g-config-resolution', async (importOriginal) => ({ })) import { SshConnection } from './ssh-connection' -import { - initSshHostKeyStoreFile, - isTrusted, - loadTrustedHostKeys -} from '../host-keys/ssh-host-key-store' +import { initSshHostKeyStoreFile, loadTrustedHostKeys } from '../host-keys/ssh-host-key-store' import type { SshTarget } from '../../../shared/ssh-types' const target = (overrides?: Partial): SshTarget => ({ @@ -120,30 +116,6 @@ describe('recording a first-contact host key', () => { ) }) - it('accepts the same key from the store on the next connection', async () => { - await new SshConnection(target(), callbacks()).connect() - await waitForStoredKeys(1) - - await expect( - isTrusted({ - host: 'example.com', - port: 22, - keyType: 'ssh-ed25519', - key: VALID_ED25519_HOST_KEY - }) - ).resolves.toBe('match') - }) - - it('does not record the same key twice', async () => { - await new SshConnection(target(), callbacks()).connect() - await waitForStoredKeys(1) - await new SshConnection(target(), callbacks()).connect() - // Give a duplicate write time to land before asserting it never did. - await new Promise((resolve) => setTimeout(resolve, 50)) - - expect(await loadTrustedHostKeys()).toHaveLength(1) - }) - // Recorded trust must refuse changed keys even when known_hosts has no entry. it('refuses a different key for a host it recorded itself', async () => { await new SshConnection(target(), callbacks()).connect() @@ -155,38 +127,4 @@ describe('recording a first-contact host key', () => { await expect(second.connect()).rejects.toThrow(/host key verification failed/i) expect(hostKeyAccepted).toBe(false) }) - - // Unreadable known_hosts permits connection without recording; withheld evidence must never become durable first-contact trust. - it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( - 'records nothing when a known_hosts file exists but cannot be read', - async () => { - const home = mkdtempSync(join(tmpdir(), 'orca-ssh-home-')) - mkdirSync(join(home, '.ssh')) - const knownHosts = join(home, '.ssh', 'known_hosts') - writeFileSync(knownHosts, '') - chmodSync(knownHosts, 0o000) - vi.stubEnv('HOME', home) - - try { - await new SshConnection(target(), callbacks()).connect() - await new Promise((resolve) => setTimeout(resolve, 50)) - - expect(hostKeyAccepted).toBe(true) - expect(await loadTrustedHostKeys()).toEqual([]) - } finally { - vi.unstubAllEnvs() - rmSync(home, { recursive: true, force: true }) - } - } - ) - - it('records nothing for an on-demand runtime target', async () => { - await new SshConnection( - target({ owner: { type: 'on-demand-runtime', runtimeId: 'rt-1' } }), - callbacks() - ).connect() - await new Promise((resolve) => setTimeout(resolve, 50)) - - expect(await loadTrustedHostKeys()).toEqual([]) - }) }) diff --git a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts index 83d9c88b553..ea3ef9e3d96 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { connectAttempts, ssh2Mock } from './testing/ssh-connection-test-client' +import { ssh2Mock } from './testing/ssh-connection-test-client' import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' @@ -54,14 +54,6 @@ describe('SshConnection host key verification', () => { resetSshConnectionMocks() }) - it('refuses a host key whose own blob cannot be identified', async () => { - ssh2Mock.presentedHostKey = UNIDENTIFIABLE_HOST_KEY - const conn = new SshConnection(createTarget(), createCallbacks()) - - await expect(conn.connect()).rejects.toThrow() - expect(ssh2Mock.lastHostKeyAccepted, 'the handshake accepted an unidentifiable key').toBe(false) - }) - // A rejected host key must bypass credential fallbacks or auth-shaped errors could disclose a secret to the refused peer. it('never asks for a credential after refusing a host key', async () => { vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock') @@ -109,7 +101,7 @@ describe('SshConnection host key verification', () => { } }) - // Unreadable known_hosts connects as SSH does, including cloud-placeholder files, but must record no trust; store-wiring tests prove that boundary. + // Unreadable known_hosts connects as SSH does, including cloud-placeholder files. it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( 'still connects when a known_hosts file exists but cannot be read', async () => { @@ -131,12 +123,4 @@ describe('SshConnection host key verification', () => { } } ) - - it('does not retry a refused host key', async () => { - ssh2Mock.presentedHostKey = UNIDENTIFIABLE_HOST_KEY - const conn = new SshConnection(createTarget(), createCallbacks()) - - await expect(conn.connect()).rejects.toThrow() - expect(connectAttempts).toBe(1) - }) }) diff --git a/src/main/ssh/connection/ssh-connection-loopback-route.test.ts b/src/main/ssh/connection/ssh-connection-loopback-route.test.ts index 665ecd93b4c..d77a07d8c2d 100644 --- a/src/main/ssh/connection/ssh-connection-loopback-route.test.ts +++ b/src/main/ssh/connection/ssh-connection-loopback-route.test.ts @@ -3,7 +3,6 @@ import { resetSshConnectionMocks } from './testing/ssh-connection-test-harness' import { createCallbacks, createTarget } from './testing/ssh-connection-test-fixtures' import { SshConnection } from './ssh-connection' import type { SystemSshLoopbackRoute } from '../system-transport/forwarding/system-ssh-loopback-route' -import { uploadFileViaSystemSsh } from '../system-transport/file-transfer/system-ssh-file-binary-transfer' const { startRouteMock } = vi.hoisted(() => ({ startRouteMock: vi.fn() })) @@ -96,57 +95,6 @@ describe('SshConnection loopback route', () => { ) }) - it('drops the route when its forward exits, so commands fall back to the proxy', async () => { - const finishStart = deferRouteStart() - const conn = new SshConnection( - createTarget({ proxyCommand: 'ssh -W %h:%p bastion.example.com' }), - createCallbacks() - ) - await conn.connect() - const route = createRoute(50001) - finishStart(route) - await vi.waitFor(() => expect(route.onExit).toHaveBeenCalled()) - - const onExit = vi.mocked(route.onExit).mock.calls[0]?.[0] - onExit?.() - - expect(conn.getSystemSshBuildArgsOptions().loopbackRoute).toBeUndefined() - }) - - it('stops an open upload session from dialling a route that has since exited', async () => { - const finishStart = deferRouteStart() - const conn = new SshConnection( - createTarget({ proxyCommand: 'ssh -W %h:%p bastion.example.com' }), - createCallbacks() - ) - await conn.connect() - const route = createRoute(50001) - finishStart(route) - await vi.waitFor(() => expect(route.onExit).toHaveBeenCalled()) - const uploadSession = await conn.openFileUploadSession() - - vi.mocked(route.onExit).mock.calls[0]?.[0]?.() - await uploadSession.uploadFile('/tmp/a.txt', '/remote/a.txt') - - expect(vi.mocked(uploadFileViaSystemSsh).mock.calls.at(-1)?.[3]?.loopbackRoute).toBeUndefined() - }) - - it('disposes the route on disconnect', async () => { - const finishStart = deferRouteStart() - const conn = new SshConnection( - createTarget({ proxyCommand: 'ssh -W %h:%p bastion.example.com' }), - createCallbacks() - ) - await conn.connect() - const route = createRoute(50001) - finishStart(route) - await vi.waitFor(() => expect(conn.getSystemSshBuildArgsOptions().loopbackRoute).toBeDefined()) - - await conn.disconnect() - - expect(route.dispose).toHaveBeenCalled() - }) - it('does not start a route for a connection torn down as it reported connected', async () => { let conn: SshConnection | null = null conn = new SshConnection( diff --git a/src/main/ssh/external-editors/zed-ssh-url.test.ts b/src/main/ssh/external-editors/zed-ssh-url.test.ts deleted file mode 100644 index 4be131c5727..00000000000 --- a/src/main/ssh/external-editors/zed-ssh-url.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' -import { resolveZedSshUrl } from './zed-ssh-url' - -function createTarget(overrides: Partial = {}): SshTarget { - return { - id: 'ssh-1', - label: 'Builder', - host: 'builder.example.com', - port: 22, - username: 'ada', - source: 'manual', - ...overrides - } -} - -describe('resolveZedSshUrl', () => { - it('keeps a custom port in the URL instead of requiring an SSH config alias', () => { - expect(resolveZedSshUrl(createTarget({ port: 2222 }), '/srv/project')).toEqual({ - ok: true, - url: 'ssh://ada@builder.example.com:2222/srv/project' - }) - }) - - it('uses only the alias for config-backed targets so local ssh config supplies user and port', () => { - expect( - resolveZedSshUrl( - createTarget({ source: 'ssh-config', configHost: ' devbox ', port: 2222 }), - '/srv/project' - ) - ).toEqual({ ok: true, url: 'ssh://devbox/srv/project' }) - }) - - it('percent-encodes user and path segments that would otherwise end the URL early', () => { - expect( - resolveZedSshUrl( - createTarget({ username: 'ada@corp', host: '2001:db8::1' }), - '/home/Ada Lovelace/a#b?c%d' - ) - ).toEqual({ - ok: true, - url: 'ssh://ada%40corp@[2001:db8::1]:22/home/Ada%20Lovelace/a%23b%3Fc%25d' - }) - }) - - it('asks for an ssh config alias when a manual host needs settings the URL cannot carry', () => { - expect( - resolveZedSshUrl(createTarget({ identityFile: '~/.ssh/builder', port: 2222 }), '/srv') - ).toEqual({ ok: false, reason: 'ssh-alias-required', host: 'builder.example.com', port: 2222 }) - expect(resolveZedSshUrl(createTarget({ jumpHost: 'bastion' }), '/srv')).toMatchObject({ - reason: 'ssh-alias-required' - }) - }) - - it('refuses hosts and paths Zed cannot round-trip', () => { - expect( - resolveZedSshUrl(createTarget({ source: 'ssh-config', configHost: 'team devbox' }), '/srv') - ).toEqual({ ok: false, reason: 'remote-editor-unsupported' }) - expect(resolveZedSshUrl(createTarget({ host: '-oProxyCommand=x' }), '/srv')).toMatchObject({ - reason: 'ssh-alias-required' - }) - expect(resolveZedSshUrl(createTarget(), 'C:\\Users\\ada\\project')).toEqual({ - ok: false, - reason: 'remote-editor-unsupported' - }) - expect(resolveZedSshUrl(createTarget({ host: 'bad\nhost' }), '/srv')).toEqual({ - ok: false, - reason: 'ssh-target-invalid' - }) - }) -}) diff --git a/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts index 1d35b327d27..fd464162eed 100644 --- a/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts +++ b/src/main/ssh/file-transfer/ssh-exec-stdin-file-transfer.test.ts @@ -1,4 +1,4 @@ -import { createHash, randomBytes } from 'node:crypto' +import { randomBytes } from 'node:crypto' import { existsSync, mkdirSync, @@ -79,20 +79,6 @@ function localShellConnection(rewrite: (command: string) => string = (c) => c): } describe.skipIf(process.platform === 'win32')('exec-stdin writer through a real shell', () => { - it('streams a payload over 10 MB byte-for-byte', async () => { - const dir = tempDir() - const payload = randomBytes(12 * 1024 * 1024 + 7) - const local = join(dir, 'runtime.tar.gz') - writeFileSync(local, payload) - const remote = join(dir, 'remote', 'nested', 'runtime.tar.gz') - - await uploadFileViaExecStdin(localShellConnection(), local, remote) - - const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex') - expect(sha(readFileSync(remote))).toBe(sha(payload)) - expect(readdirSync(join(dir, 'remote', 'nested'))).toEqual(['runtime.tar.gz']) - }, 60_000) - it('leaves no file behind when the host receives fewer bytes than were sent', async () => { const dir = tempDir() const local = join(dir, 'payload.bin') diff --git a/src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts b/src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts index 1cc32636fdb..f8d962c6711 100644 --- a/src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts +++ b/src/main/ssh/file-transfer/ssh-file-transfer-abort.test.ts @@ -91,27 +91,4 @@ describe('raceSftpFileTransferWithAbort', () => { vi.useRealTimers() } }) - - it('removes the close waiter when the teardown deadline expires', async () => { - vi.useFakeTimers() - try { - const controller = new AbortController() - const removeCloseListener = vi.fn() - const outcome = raceSftpFileTransferWithAbort( - new Promise(() => {}), - controller.signal, - () => removeCloseListener - ).catch((error: Error) => error) - - controller.abort() - await vi.advanceTimersByTimeAsync(5_000) - - await expect(outcome).resolves.toMatchObject({ - sshTransferTeardownConfirmed: false - }) - expect(removeCloseListener).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts b/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts index 04e49b7860e..446732e0fa6 100644 --- a/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts +++ b/src/main/ssh/filesystem/ssh-remote-directory-browse.test.ts @@ -60,21 +60,4 @@ describe.skipIf(process.platform === 'win32')('browseSshDirectory over a POSIX s { name: 'real-file.txt', isDirectory: false } ]) }) - - it('navigates into a symlinked directory and lists an empty one as empty', async () => { - await mkdir(join(root, 'real-dir', 'project'), { recursive: true }) - await mkdir(join(root, 'empty-real')) - await symlink(join(root, 'real-dir'), join(root, 'linked-dir')) - await symlink(join(root, 'empty-real'), join(root, 'linked-empty')) - - const linked = await browseSshDirectory(shellBackedManager(), 'ssh-1', join(root, 'linked-dir')) - const empty = await browseSshDirectory( - shellBackedManager(), - 'ssh-1', - join(root, 'linked-empty') - ) - - expect(linked.entries).toEqual([{ name: 'project', isDirectory: true }]) - expect(empty.entries).toEqual([]) - }) }) diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts deleted file mode 100644 index 5e8f7bd16ba..00000000000 --- a/src/main/ssh/host-server/ssh-host-server-on-connect-held-move.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** #27267: stopped conversions must release their fence or report it retained and resume next connect. */ -import { describe, expect, it, vi } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' -import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' -import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' -import { unservedHostServerMessage, unservedServerStatus } from './ssh-host-unserved-status' - -const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } - -function fencedHost(phase: 'source-fenced' | 'destination-staged', registered: boolean) { - const host: { phase: string | null; registered: boolean } = { phase, registered } - return { - host, - deps: (overrides: Parameters[0] = {}) => - hostServerDepsStub({ - managedEnvironmentId: () => (host.phase && host.registered ? 'env-1' : null), - hasUnfinishedConversion: () => - host.phase === 'source-fenced' || host.phase === 'destination-staged', - isFencedBeforeStaging: () => host.phase === 'source-fenced', - ...overrides - }) - } -} - -describe('a move to the managed server that stops short', () => { - it('keeps the host locked and says the move is paused when the server cannot answer', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const { deps } = fencedHost('source-fenced', true) - const d = deps({ - convert: vi.fn(async () => { - throw new Error('Could not connect to the remote Orca runtime.') - }), - abandonConversion: vi.fn(async () => { - throw new Error('Could not connect to the remote Orca runtime.') - }) - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toMatchObject({ route: 'unserved', reason: 'failed', held: true }) - expect(d.abandonConversion).toHaveBeenCalledWith(target) - // Never an unavailability record: that would stop later connects from resuming. - expect(d.recordUnavailable).not.toHaveBeenCalled() - if (result.route !== 'unserved') { - throw new Error('expected unserved') - } - expect(unservedHostServerMessage(result)).toContain('Connect again to resume') - expect(unservedServerStatus(result)).toMatchObject({ kind: 'relay', held: true }) - warn.mockRestore() - }) - - it('gives the host back, with no lock to report, when the server proves it holds nothing', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const { host, deps } = fencedHost('destination-staged', true) - const d = deps({ - convert: vi.fn(async () => { - throw new Error('orcad_migration_commit_not_committed:staged') - }), - abandonConversion: vi.fn(async () => { - host.phase = null - }) - }) - const result = await resolveHostServerOnConnect(target, d) - expect(result).toEqual({ - route: 'unserved', - reason: 'failed', - detail: 'orcad_migration_commit_not_committed:staged' - }) - if (result.route === 'unserved') { - expect(unservedHostServerMessage(result)).toBe( - 'Orca couldn’t start its server on this host. Try connecting again.' - ) - } - warn.mockRestore() - }) -}) diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts index e7ddac1f80e..c93bcf0ceb6 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect-node-download.test.ts @@ -4,7 +4,7 @@ import type { SshTarget } from '../../../shared/ssh-types' import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' import { unservedHostServerMessage } from './ssh-host-unserved-status' -import { sftpSessionClosedError } from '../file-transfer/ssh-file-transfer-abort' + import { NodeRuntimeUnreachableError } from '../../managed-server/install/remote-node-runtime-host-download' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } @@ -54,11 +54,4 @@ describe('a managed-server setup that could not download Node', () => { expect(result).not.toHaveProperty('nodeDownloadBlocked') expect(unservedHostServerMessage(result)).toContain('Try connecting again') }) - - it('lets lost contact win, since nothing proves the host failed', async () => { - const lost = new Error('upload failed', { cause: sftpSessionClosedError() }) - const result = await deployFailingWith(lost) - expect(result).toMatchObject({ contactLost: true }) - expect(result).not.toHaveProperty('nodeDownloadBlocked') - }) }) diff --git a/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts b/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts deleted file mode 100644 index a3f2e379c2b..00000000000 --- a/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { eventSchemas } from '../../../shared/telemetry-event-registry' - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) - -const { track } = await import('../../telemetry/client') -const { hostServerFailure, hostServerRefusal, trackSshHostServerEvent } = - await import('./ssh-host-server-telemetry') - -const linuxGlibc = { os: 'linux', arch: 'x64', libc: 'glibc' } as const - -function tracked() { - const call = vi.mocked(track).mock.calls.at(-1) - if (!call) { - throw new Error('nothing was tracked') - } - return call -} - -function expectSchemaValid(): unknown { - const [name, props] = tracked() - expect(eventSchemas[name].safeParse(props).success).toBe(true) - return props -} - -describe('ssh host server telemetry', () => { - beforeEach(() => { - vi.mocked(track).mockReset() - }) - - it('narrows any unrecognised code, so free text never reaches an event', () => { - expect(hostServerRefusal('orcad_migration_/home/me/secret')).toBe('other') - expect(hostServerFailure('Error: ssh me@host.example failed')).toBe('other') - expect(hostServerFailure('orcad_activation_no_readiness')).toBe('activation_no_readiness') - expect(hostServerFailure('unsupported_host')).toBe('unsupported_host') - - trackSshHostServerEvent( - { - kind: 'decided', - outcome: 'relay', - reason: 'host.example.com', - refusal: null, - recorded: false, - durationMs: 0 - }, - linuxGlibc - ) - expect(expectSchemaValid()).toMatchObject({ reason: 'other' }) - }) -}) diff --git a/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts index af7b544c86c..18964298bb7 100644 --- a/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts @@ -67,7 +67,7 @@ vi.mock('../../protocol/ssh-channel-multiplexer', () => ({ } })) -import { LegacyRelayClient, LegacyRelayOwnerHeldError } from './legacy-relay-client' +import { LegacyRelayClient } from './legacy-relay-client' const GRANT = { protocolVersion: 1, @@ -103,14 +103,6 @@ beforeEach(() => { }) describe('the legacy relay client', () => { - it('never displaces an attached owner', async () => { - fake.respond = () => { - throw rpcError(-32044) - } - await expect(open()).rejects.toBeInstanceOf(LegacyRelayOwnerHeldError) - expect(fake.requests).toHaveLength(1) - }) - it('talks to a relay that predates owner claims', async () => { fake.respond = (method) => { if (method === 'pty.openClient') { @@ -120,9 +112,4 @@ describe('the legacy relay client', () => { } await expect(open()).resolves.toMatchObject({ ownerClaim: null }) }) - - it('refuses a grant that is not the owner role', async () => { - fake.respond = () => ({ ...GRANT, role: 'subscriber' }) - await expect(open()).rejects.toThrow('did not grant the terminal owner role') - }) }) diff --git a/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts index 7b181ff9b13..e0d5d71ad36 100644 --- a/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts @@ -20,19 +20,6 @@ beforeEach(() => { }) describe('a bridged pane no visible view shows', () => { - it('sends none of its output to the window, and one fresh screen once shown', async () => { - subject.setPaused(PTY, true) - for (let i = 0; i < 1000; i++) { - subject.onData(PTY, 'x'.repeat(4096)) - } - expect(sent).toEqual([]) - subject.setPaused(PTY, false) - await vi.waitFor(() => expect(sent).toEqual(['replay:SCREEN'])) - expect(reread).toHaveBeenCalledTimes(1) - subject.onData(PTY, 'live') - expect(sent).toEqual(['replay:SCREEN', 'data:live']) - }) - it('keeps output printed after the snapshot behind the screen it follows', async () => { let snapshot: (replay: string) => void = () => {} let finish: () => void = () => {} @@ -80,12 +67,6 @@ describe('a bridged pane no visible view shows', () => { expect(sent.at(-1)).toBe('data:c') }) - it('still sends kitty, window-size and capability queries', () => { - subject.setPaused(PTY, true) - subject.onData(PTY, 'a\x1b[?ub\x1b[18tc\x1bP+q544e\x1b\\d') - expect(sent).toEqual(['data:\x1b[?u\x1b[18t\x1bP+q544e\x1b\\']) - }) - it('reopens an oversized OSC a reveal cut, so its payload never prints', async () => { reread.mockRejectedValueOnce(new Error('ssh down')) subject.setPaused(PTY, true) @@ -101,22 +82,6 @@ describe('a bridged pane no visible view shows', () => { expect(sent).toEqual(['data:shown\x1b[', 'data:\x1b[c']) }) - it('carries a query split across chunks until it completes', () => { - subject.setPaused(PTY, true) - subject.onData(PTY, 'bulk\x1b[') - subject.onData(PTY, 'c') - expect(sent).toEqual(['data:\x1b[c']) - }) - - it('still sends command marks, titles and bells, but not an oversized OSC', () => { - subject.setPaused(PTY, true) - subject.onData(PTY, 'out\x1b]133;D;0\x07text\x1b]0;') - subject.onData(PTY, 'title\x1b\\ding\x07') - subject.onData(PTY, `\x1b]1337;File=${'x'.repeat(5000)}`) - subject.onData(PTY, 'y\x07after\x07') - expect(sent).toEqual(['data:\x1b]133;D;0\x07', 'data:\x1b]0;title\x1b\\\x07', 'data:\x07']) - }) - it('re-reads output a hidden pane printed after its reattach’s screen', async () => { subject.setPaused(PTY, true) subject.screenSent(PTY) diff --git a/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts b/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts index 5d710c43870..100259656c6 100644 --- a/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts +++ b/src/main/ssh/legacy-relay/bridge/legacy-relay-move-retry.test.ts @@ -73,17 +73,6 @@ afterEach(() => { }) describe('the last bridged relay terminal', () => { - it('reports once when the relay proves the only pane exited', async () => { - startHost() - await startLegacyRelayBridge(TARGET) - - relay.ptys.delete('pty-1') - relay.clients[0].emitExit('pty-1', 0) - - expect(lastExits).toEqual([TARGET]) - expect(legacyRelayBridgedPanes()).toEqual([]) - }) - it('never reports lost contact as exit', async () => { startHost() await startLegacyRelayBridge(TARGET) diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts index 35a329449d9..10f04e478e8 100644 --- a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts @@ -5,7 +5,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { - windowsPipesNotRunHere, parseWindowsRelayInventory, WINDOWS_RELAY_INVENTORY_JS } from './ssh-host-relay-windows-inventory' @@ -59,13 +58,4 @@ describe('the Windows relay inventory', () => { ) ).toBeNull() }) - - it("sets aside only pipes the host proved another account's or gone", () => { - expect( - windowsPipesNotRunHere( - JSON.stringify({ '\\\\.\\pipe\\A': 'EACCES', '\\\\.\\pipe\\B': 'ok', C: 'ENOENT' }) - ) - ).toEqual(new Set(['\\\\.\\pipe\\a', 'c'])) - expect(windowsPipesNotRunHere('garbage')).toEqual(new Set()) - }) }) diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts deleted file mode 100644 index fd22247584a..00000000000 --- a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseRelayDaemonRuntimes } from './ssh-relay-endpoint-runtime' - -describe('the runtime each relay daemon runs on', () => { - it('reads a pinned and a legacy host-Node daemon from their argv', () => { - const pinned = '/home/dev/.orca-remote/node-runtimes/v24/bin/node' - const runtimes = parseRelayDaemonRuntimes( - [ - `${pinned} relay.js --detached --grace-time 0 --sock-path /home/dev/.orca-remote/relay-2/relay-a.sock --credential-file x`, - '/usr/local/bin/node relay.js --detached --grace-time 300 --sock-path /home/dev/.orca-remote/relay-1/relay-b.sock --log-file y', - // A bridge client is not a daemon, and a line without a socket is skipped. - '/usr/bin/node relay.js --connect --sock-path /home/dev/.orca-remote/relay-1/relay-b.sock', - 'grep -F relay.js --detached' - ].join('\n') - ) - expect([...runtimes]).toEqual([ - ['/home/dev/.orca-remote/relay-2/relay-a.sock', pinned], - ['/home/dev/.orca-remote/relay-1/relay-b.sock', '/usr/local/bin/node'] - ]) - }) -}) diff --git a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts index 5d6552b4ae4..7d4f44b9cfc 100644 --- a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts @@ -4,24 +4,23 @@ import { expect, it, vi } from 'vitest' import { RELAY_SENTINEL } from '../../protocol/relay-handshake' import { waitForSentinel } from './ssh-relay-sentinel' -it.each(Array.from({ length: RELAY_SENTINEL.length + 1 }, (_, i) => i))( - 'preserves the marker and binary payload when split at byte %i', - async (split) => { - const channel = Object.assign(new EventEmitter(), { - stderr: new EventEmitter(), - stdin: { write: vi.fn(() => true) }, - close: vi.fn() - }) - const pending = waitForSentinel(channel as unknown as ClientChannel) - const marker = Buffer.from(RELAY_SENTINEL) - const payload = Buffer.from([0, 255, 128, 10, 13, 1]) - channel.emit('data', Buffer.alloc(63 * 1024, 120)) - channel.emit('data', marker.subarray(0, split)) - channel.emit('data', Buffer.concat([marker.subarray(split), payload])) - const transport = await pending - const received: Buffer[] = [] - transport.onData((bytes) => received.push(bytes)) - expect(Buffer.concat(received)).toEqual(payload) - expect(channel.close).not.toHaveBeenCalled() - } -) +it('preserves binary payload across a split ready marker', async () => { + const split = 12 + const channel = Object.assign(new EventEmitter(), { + stderr: new EventEmitter(), + stdin: { write: vi.fn(() => true) }, + close: vi.fn() + }) + // SAFETY: This fake implements the channel members used during this handshake and subscription. + const pending = waitForSentinel(channel as unknown as ClientChannel) + const marker = Buffer.from(RELAY_SENTINEL) + const payload = Buffer.from([0, 255, 128, 10, 13, 1]) + channel.emit('data', Buffer.alloc(63 * 1024, 120)) + channel.emit('data', marker.subarray(0, split)) + channel.emit('data', Buffer.concat([marker.subarray(split), payload])) + const transport = await pending + const received: Buffer[] = [] + transport.onData((bytes) => received.push(bytes)) + expect(Buffer.concat(received)).toEqual(payload) + expect(channel.close).not.toHaveBeenCalled() +}) diff --git a/src/main/ssh/protocol/remote-frame-protocol.test.ts b/src/main/ssh/protocol/remote-frame-protocol.test.ts index f6472700658..5815580f775 100644 --- a/src/main/ssh/protocol/remote-frame-protocol.test.ts +++ b/src/main/ssh/protocol/remote-frame-protocol.test.ts @@ -1,12 +1,7 @@ import { describe, expect, it } from 'vitest' import { HEADER_LENGTH, FrameDecoder } from '../../../shared/relay-frame-decoder' import type { DecodedFrame } from '../../../shared/relay-frame-decoder-contract' -import { - MessageType, - encodeFrame, - encodeJsonRpcFrame, - parseJsonRpcMessage -} from './remote-frame-protocol' +import { MessageType, encodeFrame, encodeJsonRpcFrame } from './remote-frame-protocol' describe('frame encoding', () => { it('rejects messages larger than MAX_MESSAGE_SIZE', () => { @@ -24,31 +19,6 @@ describe('FrameDecoder', () => { // Freeze clock for framing cases; relay-protocol-backpressure.test.ts separately covers time-sliced drain under CI load. const frozenClock = { now: () => 0 } - it('skips oversized frames and calls onError instead of throwing', () => { - const errors: Error[] = [] - const frames: DecodedFrame[] = [] - const decoder = new FrameDecoder( - (f) => frames.push(f), - (err) => errors.push(err), - frozenClock - ) - - const oversizedLength = 17 * 1024 * 1024 - const header = Buffer.alloc(HEADER_LENGTH) - header[0] = MessageType.Regular - header.writeUInt32BE(1, 1) - header.writeUInt32BE(0, 5) - header.writeUInt32BE(oversizedLength, 9) - - const fakePayload = Buffer.alloc(oversizedLength) - const fullFrame = Buffer.concat([header, fakePayload]) - - decoder.feed(fullFrame) - expect(frames).toHaveLength(0) - expect(errors).toHaveLength(1) - expect(errors[0].message).toContain('discarded') - }) - it('skips an oversized frame fed in odd-sized chunks and resynchronizes', () => { const errors: Error[] = [] const frames: DecodedFrame[] = [] @@ -78,10 +48,3 @@ describe('FrameDecoder', () => { expect(frames[0].payload.toString()).toBe('after') }) }) - -describe('parseJsonRpcMessage', () => { - it('throws on invalid jsonrpc version', () => { - const payload = Buffer.from(JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'x' })) - expect(() => parseJsonRpcMessage(payload)).toThrow('Invalid JSON-RPC version') - }) -}) diff --git a/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts index e3d03cb790e..218d08006e3 100644 --- a/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer-saturation-wedge.test.ts @@ -49,18 +49,6 @@ describe('SshChannelMultiplexer on a transport that saturates and never drains', expect(mux.isDisposed()).toBe(true) }) - it('fails a request parked behind saturation rather than leaving it pending forever', async () => { - const settled = vi.fn() - mux.request('pty.spawn', {}).then( - () => settled('resolved'), - () => settled('rejected') - ) - - await vi.advanceTimersByTimeAsync(TIMEOUT_MS * 10 + KEEPALIVE_SEND_MS) - - expect(settled).toHaveBeenCalledWith('rejected') - }) - it('keeps a slow-but-alive peer connected while its own keepalives arrive', async () => { // Outbound saturation proves nothing; inbound keepalives alone must preserve a slow live peer. let seq = 1 diff --git a/src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts deleted file mode 100644 index 30fc5e218ac..00000000000 --- a/src/main/ssh/protocol/ssh-channel-multiplexer-settlement.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { SshChannelMultiplexer } from './ssh-channel-multiplexer' -import type { MultiplexerTransport } from './ssh-multiplexer-transport-writer' - -function transportHarness(): { - transport: MultiplexerTransport - settlements: ((result: { ok: true } | { ok: false; error: Error }) => void)[] -} { - const settlements: ((result: { ok: true } | { ok: false; error: Error }) => void)[] = [] - return { - transport: { - write: (_data, onSettled) => { - if (onSettled) { - settlements.push(onSettled) - } - }, - supportsWriteSettlement: true, - onData: vi.fn(), - onClose: vi.fn() - }, - settlements - } -} - -describe('SshChannelMultiplexer notification settlement', () => { - it('reports publication only from the transport write callback', () => { - const harness = transportHarness() - const mux = new SshChannelMultiplexer(harness.transport) - const settled = vi.fn() - - mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled) - expect(settled).not.toHaveBeenCalled() - harness.settlements[0]({ ok: true }) - expect(settled).toHaveBeenCalledWith({ outcome: 'accepted' }) - mux.dispose() - }) - - it('reports a synchronous write failure without publishing success', () => { - const error = new Error('write failed') - const mux = new SshChannelMultiplexer({ - write: () => { - throw error - }, - supportsWriteSettlement: true, - onData: vi.fn(), - onClose: vi.fn() - }) - const settled = vi.fn() - - mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled) - expect(settled).toHaveBeenCalledWith({ - outcome: 'unverifiable', - reason: 'transport_settlement_lost', - bytesHandedToTransport: true, - error - }) - expect(mux.isDisposed()).toBe(true) - }) - - it('settles once when a hostile transport invokes its callback and then throws', () => { - const mux = new SshChannelMultiplexer({ - write: (_data, onSettled) => { - onSettled?.({ ok: true }) - throw new Error('late throw') - }, - supportsWriteSettlement: true, - onData: vi.fn(), - onClose: vi.fn() - }) - const settled = vi.fn() - - mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled) - expect(settled).toHaveBeenCalledOnce() - expect(settled).toHaveBeenCalledWith({ outcome: 'accepted' }) - }) - - it('fails an unsettled publication when the multiplexer is disposed', () => { - const close = vi.fn() - const mux = new SshChannelMultiplexer({ - write: () => false, - supportsWriteSettlement: true, - onDrain: vi.fn(), - onData: vi.fn(), - onClose: vi.fn(), - close - }) - const settled = vi.fn() - - mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled) - expect(settled).not.toHaveBeenCalled() - mux.dispose() - - expect(settled).toHaveBeenCalledWith({ - outcome: 'unverifiable', - reason: 'transport_settlement_lost', - bytesHandedToTransport: true, - error: expect.objectContaining({ code: 'DISPOSED' }) - }) - expect(close).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts b/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts index bb9b712e330..842d478f324 100644 --- a/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts +++ b/src/main/ssh/protocol/ssh-channel-multiplexer.test.ts @@ -36,22 +36,6 @@ function makeResponseFrame(requestId: number, result: unknown, seq: number): Buf return encodeFrame(MessageType.Regular, seq, 0, payload) } -function makeErrorResponseFrame( - requestId: number, - code: number, - message: string, - seq: number -): Buffer { - const payload = Buffer.from( - JSON.stringify({ - jsonrpc: '2.0', - id: requestId, - error: { code, message } - }) - ) - return encodeFrame(MessageType.Regular, seq, 0, payload) -} - function makeNotificationFrame( method: string, params: Record, @@ -83,15 +67,6 @@ describe('SshChannelMultiplexer', () => { }) describe('request/response', () => { - it('rejects on error response', async () => { - const promise = mux.request('pty.spawn', { cols: 80, rows: 24 }) - - const response = makeErrorResponseFrame(1, -33004, 'PTY allocation failed', 1) - transport.dataCallbacks[0](response) - - await expect(promise).rejects.toThrow('PTY allocation failed') - }) - it('runs beforeResolve before an adjacent notification in the same decoder turn', async () => { const order: string[] = [] mux.onNotification(() => order.push('notification')) @@ -158,40 +133,6 @@ describe('SshChannelMultiplexer', () => { }) describe('notifications', () => { - it('typed dispatcher only fires for its method', () => { - const chunkHandler = vi.fn() - const otherHandler = vi.fn() - const generic = vi.fn() - mux.onNotificationByMethod('fs.streamChunk', chunkHandler) - mux.onNotificationByMethod('fs.streamEnd', otherHandler) - mux.onNotification(generic) - - transport.dataCallbacks[0]( - makeNotificationFrame('fs.streamChunk', { streamId: 1, seq: 0, data: 'aGk=' }, 1) - ) - - expect(chunkHandler).toHaveBeenCalledWith({ streamId: 1, seq: 0, data: 'aGk=' }) - expect(otherHandler).not.toHaveBeenCalled() - expect(generic).toHaveBeenCalledWith('fs.streamChunk', { - streamId: 1, - seq: 0, - data: 'aGk=' - }) - }) - - it('typed dispatcher unsubscribe removes only that handler', () => { - const a = vi.fn() - const b = vi.fn() - const unsubA = mux.onNotificationByMethod('fs.streamEnd', a) - mux.onNotificationByMethod('fs.streamEnd', b) - unsubA() - - transport.dataCallbacks[0](makeNotificationFrame('fs.streamEnd', { streamId: 7 }, 1)) - - expect(a).not.toHaveBeenCalled() - expect(b).toHaveBeenCalledWith({ streamId: 7 }) - }) - it('contains generic notification handler failures', () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) const badHandler = vi.fn(() => { @@ -276,40 +217,7 @@ describe('SshChannelMultiplexer', () => { }) }) - describe('probeLiveness', () => { - it('sends a keepalive and resolves true when any frame arrives', async () => { - const writesBefore = transport.written.length - const probe = mux.probeLiveness(5_000) - - expect(transport.written.length).toBe(writesBefore + 1) - expect(transport.written.at(-1)![0]).toBe(MessageType.KeepAlive) - - transport.dataCallbacks[0](encodeKeepAliveFrame(1, 0)) - await expect(probe).resolves.toBe(true) - }) - - it('resolves false when no frame arrives before the timeout', async () => { - const probe = mux.probeLiveness(5_000) - vi.advanceTimersByTime(5_000) - await expect(probe).resolves.toBe(false) - }) - - it('resolves false when the mux is disposed while probing', async () => { - const probe = mux.probeLiveness(5_000) - mux.dispose() - await expect(probe).resolves.toBe(false) - }) - }) - describe('dispose', () => { - it('rejects all pending requests on dispose', async () => { - const promise = mux.request('pty.spawn') - - mux.dispose() - - await expect(promise).rejects.toThrow('Multiplexer disposed') - }) - it('tags a request after a shutdown dispose with DISPOSED', async () => { mux.dispose() @@ -329,22 +237,6 @@ describe('SshChannelMultiplexer', () => { expect(error.code).toBe('CONNECTION_LOST') }) - it('reports a settled notify after a lost connection as transient', () => { - transport.closeCallbacks[0]() - - const settled = vi.fn() - mux.notifyWithSettlement('pty.data', { id: 'pty-1', data: 'x' }, settled) - - expect(settled).toHaveBeenCalledWith({ - outcome: 'refused', - reason: 'transport_disposed', - error: expect.objectContaining({ - message: 'SSH connection lost, reconnecting...', - code: 'CONNECTION_LOST' - }) - }) - }) - it('fires a dispose handler registered after dispose with the recorded reason', () => { mux.dispose('connection_lost') diff --git a/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts index 0ad90a5755f..573f5854347 100644 --- a/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts +++ b/src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts @@ -46,50 +46,6 @@ function transportHarness(writeResults: (boolean | void)[]): WriterHarness { } describe('SshMultiplexerTransportWriter', () => { - it('selects queued control before ordinary backlog at the drain boundary', () => { - const harness = transportHarness([false, true, true, true]) - const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn()) - - writer.enqueue(Buffer.from('ordinary-1'), 'ordinary') - writer.enqueue(Buffer.from('ordinary-2'), 'ordinary') - writer.enqueue(Buffer.from('ordinary-3'), 'ordinary') - writer.enqueue(Buffer.from('control'), 'control') - - expect(harness.writes.map(String)).toEqual(['ordinary-1']) - harness.drain() - expect(harness.writes.map(String)).toEqual([ - 'ordinary-1', - 'control', - 'ordinary-2', - 'ordinary-3' - ]) - writer.dispose() - }) - - it('preserves FIFO within each lane and prevents ordinary starvation', () => { - const harness = transportHarness([false, ...Array(8).fill(true)]) - const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn()) - - writer.enqueue(Buffer.from('ordinary-1'), 'ordinary') - writer.enqueue(Buffer.from('ordinary-2'), 'ordinary') - for (let index = 1; index <= 6; index++) { - writer.enqueue(Buffer.from(`control-${index}`), 'control') - } - - harness.drain() - expect(harness.writes.map(String)).toEqual([ - 'ordinary-1', - 'control-1', - 'control-2', - 'control-3', - 'control-4', - 'ordinary-2', - 'control-5', - 'control-6' - ]) - writer.dispose() - }) - it('waits for drain and settles each write once', () => { const harness = transportHarness([false, true, true]) const failed = vi.fn() @@ -190,31 +146,6 @@ describe('SshMultiplexerTransportWriter', () => { expect(failed).toHaveBeenCalledOnce() }) - it('settles legacy callback-less transports on acceptance and drain', () => { - const emitter = new EventEmitter() - const write = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(undefined) - const transport: MultiplexerTransport = { - write, - onDrain: (callback) => { - emitter.on('drain', callback) - }, - onData: vi.fn(), - onClose: vi.fn() - } - const writer = new SshMultiplexerTransportWriter(transport, vi.fn()) - const first = vi.fn() - const second = vi.fn() - - writer.enqueue(Buffer.from('first'), 'ordinary', first) - writer.enqueue(Buffer.from('second'), 'control', second) - expect(first).not.toHaveBeenCalled() - expect(second).not.toHaveBeenCalled() - - emitter.emit('drain') - expect(first).toHaveBeenCalledWith({ outcome: 'accepted' }) - expect(second).toHaveBeenCalledWith({ outcome: 'accepted' }) - }) - it('does not miss a drain emitted synchronously by a hostile transport', () => { let drain = (): void => {} const write = vi.fn(() => { diff --git a/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts b/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts index 618e8f92eaf..9ed7eded54f 100644 --- a/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts +++ b/src/main/ssh/remote-exec/ssh-exec-command-decoder-fallback.test.ts @@ -5,32 +5,19 @@ import { runProcess } from '@orca/process-host' import { wrapRemoteCommandForPosixShell } from './ssh-posix-command-wrapper' import type { SshExecOptions } from '../connection/ssh-exec-options' import { execCommand } from './remote-exec-command' -import { - captureOrcadStateSnapshotCommand, - parseOrcadSnapshotCapture -} from '../../managed-server/host-state/orcad-state-snapshot' -import { getRemoteHostPlatform } from '../remote-host/ssh-remote-platform' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' type HostOptions = { /** PATH on the host; '' leaves only shell builtins, so no base64 or gzip. */ path?: string - /** An SSH gateway that cuts the exec request at this many bytes and merges stderr into stdout. */ - gatewayLimitBytes?: number } /** Exercise the actual transport wrapper through real /bin/sh. */ function host(options: HostOptions = {}) { const exec = vi.fn() exec.mockImplementation(async (command: string, execOptions?: SshExecOptions) => { - let remote = wrapRemoteCommandForPosixShell(command, { + const remote = wrapRemoteCommandForPosixShell(command, { compress: execOptions?.compressCommand === true }) - if (options.gatewayLimitBytes !== undefined) { - remote = `${Buffer.from(remote).subarray(0, options.gatewayLimitBytes).toString()} 2>&1` - } const result = await runProcess({ program: '/bin/sh', args: ['-c', remote], @@ -68,32 +55,5 @@ describe.skipIf(process.platform === 'win32')( false ]) }) - - it('captures a snapshot whole through a gateway that cuts exec requests at 6 KiB and merges stderr', async () => { - const base = mkdtempSync(join(tmpdir(), 'orcad-gateway-capture-')) - try { - const root = join(base, '.orca') - mkdirSync(join(root, 'profiles'), { recursive: true }) - writeFileSync(join(root, 'profiles', 'p.json'), 'state') - const snapshot = join(base, '.orca-remote', 'orcad-state-snapshots', 'pre-1') - const command = captureOrcadStateSnapshotCommand( - getRemoteHostPlatform('linux-x64'), - root, - snapshot, - join(base, '.orca-remote') - ) - const gatewayLimitBytes = 6 * 1024 - expect( - Buffer.byteLength(wrapRemoteCommandForPosixShell(command, { compress: false })) - ).toBeLessThan(gatewayLimitBytes) - - const output = await execCommand(host({ gatewayLimitBytes }), command) - - expect(parseOrcadSnapshotCapture(output)).toBe('captured') - expect(existsSync(join(snapshot, 'state.tar'))).toBe(true) - } finally { - rmSync(base, { recursive: true, force: true }) - } - }) } ) diff --git a/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts b/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts index 8311f5c6ee0..448a2d78cea 100644 --- a/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts +++ b/src/main/ssh/remote-exec/ssh-exec-rc-stdout-noise.test.ts @@ -9,24 +9,9 @@ import { runProcess } from '@orca/process-host' import { wrapRemoteCommandForPosixShell } from './ssh-posix-command-wrapper' import type { SshExecOptions } from '../connection/ssh-exec-options' import { execCommand, isSshCommandExitError } from './remote-exec-command' -import { readRemoteHomeCommand } from './ssh-remote-commands' + import type { SshConnection } from '../connection/ssh-connection' import { tryResolveViaLoginShell } from '../remote-host/node-toolchain/ssh-remote-node-resolution' -import { - normalizeRemoteHome, - validateRemoteHome, - type RemoteHostPlatform -} from '../remote-host/ssh-remote-platform' - -const LINUX_HOST: RemoteHostPlatform = { - os: 'linux', - arch: 'x64', - relayPlatform: 'linux-x64', - pathFlavor: 'posix', - commandDialect: 'posix', - pathSeparator: '/', - pathDelimiter: ':' -} const HOME = '/home/fishu' @@ -64,16 +49,6 @@ const STARTUP_NOISE: [string, string][] = [ ] describe.skipIf(process.platform === 'win32')('SSH exec under noisy startup files', () => { - it.each(STARTUP_NOISE)('reads a valid remote home despite %s', async (_name, startup) => { - const conn = hostWithStartupOutput(startup) - const home = normalizeRemoteHome( - await execCommand(conn, readRemoteHomeCommand(LINUX_HOST)), - LINUX_HOST - ) - expect(home).toBe(HOME) - expect(validateRemoteHome(home, LINUX_HOST)).toBe(true) - }) - it('keeps token probes exact and the exit code intact', async () => { const conn = hostWithStartupOutput('echo OK') await expect(execCommand(conn, 'echo MISSING')).resolves.toBe('MISSING\n') diff --git a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts b/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts index 36edace9928..d72e4dbc362 100644 --- a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts +++ b/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts @@ -21,15 +21,4 @@ describe('Windows remote command line limit', () => { expect(gunzipSync(Buffer.from(payload, 'base64')).toString('utf-8')).toBe(script) expect(bootstrap).toContain('Invoke-Expression $OrcaScriptText') }) - - it('refuses a script no encoding can fit instead of letting cmd.exe reject it', () => { - let seed = 12345 - const incompressible = Array.from({ length: 60_000 }, () => { - seed = (seed * 1103515245 + 12345) % 2147483648 - return String.fromCharCode(97 + (seed % 26)) - }).join('') - expect(() => powerShellCommand(`Write-Output '${incompressible}'`)).toThrow( - /Orca budgets 8000 for a line sshd hands to cmd\.exe/u - ) - }) }) diff --git a/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts b/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts index 7c33ac7aac5..854a4efb46a 100644 --- a/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform-detection.test.ts @@ -96,18 +96,6 @@ describe('detectRemoteHostPlatform failure reporting', () => { vi.restoreAllMocks() }) - it('does not misreport a refused exec channel as an unsupported platform', async () => { - execCommandMock.mockRejectedValue(maxSessionsError()) - - // The host is linux-x64 and fully supported; the probe never ran. - await expect(detectRemoteHostPlatform(conn)).rejects.toThrow(/open failed/iu) - await expect(detectRemoteHostPlatform(conn)).rejects.toMatchObject({ - cause: expect.objectContaining({ reason: 2 }) - }) - // Both probes run: the second gets a fresh session-channel retry budget. - expect(execCommandMock).toHaveBeenCalledTimes(4) - }) - it('still detects Windows when the uname probe hits the session limit', async () => { execCommandMock .mockRejectedValueOnce(maxSessionsError()) @@ -134,23 +122,6 @@ describe('detectRemoteHostPlatform failure reporting', () => { expect(execCommandMock).toHaveBeenCalledTimes(1) }) - it('prefers a refused channel over the other probe non-zero exit', async () => { - execCommandMock - .mockRejectedValueOnce(new Error('Command "sh -c ..." failed (exit 127): sh: not found')) - .mockRejectedValueOnce(maxSessionsError()) - - await expect(detectRemoteHostPlatform(conn)).rejects.toThrow(/open failed/u) - await expect(detectRemoteHostPlatform(conn)).rejects.not.toThrow(/exit 127/u) - }) - - it('returns null when a parsed uname is genuinely unsupported', async () => { - execCommandMock - .mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ FreeBSD x86_64\n') - .mockRejectedValueOnce(new Error('powershell.exe: not found')) - - await expect(detectRemoteHostPlatform(conn)).resolves.toBeNull() - }) - it('does not call an unmappable uname unsupported when PowerShell was refused', async () => { // Cygwin sh on a win32-x64 host: only PowerShell can settle it, and it never ran. execCommandMock diff --git a/src/main/ssh/remote-host/ssh-remote-platform.test.ts b/src/main/ssh/remote-host/ssh-remote-platform.test.ts index b55b6138f88..1012133be81 100644 --- a/src/main/ssh/remote-host/ssh-remote-platform.test.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform.test.ts @@ -25,10 +25,6 @@ describe('assertSafeRemotePathSegment', () => { 'trailing.', 'trailing ', 'NUL', - 'con.txt', - 'CONIN$', - 'CLOCK$.log', - 'COM1.log', 'LPT¹' ])('rejects Win32-special segment %j', (segment) => { expect(() => assertSafeRemotePathSegment(segment, 'windows')).toThrow( diff --git a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts index c0cb84358c0..6eaa56a3050 100644 --- a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts @@ -12,18 +12,10 @@ describe('toSftpRemotePath', () => { expect(toSftpRemotePath('C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') }) - it('converts the separators Orca stores paths with', () => { - expect(toSftpRemotePath('C:\\Users\\dev\\f.bin')).toBe('/C:/Users/dev/f.bin') - }) - it('declines a UNC path rather than guessing where it lands', () => { // A guess here writes real bytes to the wrong place; declining falls back to another transport. expect(() => toSftpRemotePath('//server/share/f.bin')).toThrow(UnsupportedSftpPathError) }) - - it('declines a relative path, which would resolve against the session start directory', () => { - expect(() => toSftpRemotePath('Users/dev/f.bin')).toThrow(UnsupportedSftpPathError) - }) }) describe('quoteSftpBatchArgument', () => { @@ -32,10 +24,6 @@ describe('quoteSftpBatchArgument', () => { expect(quoteSftpBatchArgument('C:\\src\\f.bin')).toBe('"C:\\\\src\\\\f.bin"') }) - it('keeps a path with spaces as one argument', () => { - expect(quoteSftpBatchArgument('/tmp/two words.bin')).toBe('"/tmp/two words.bin"') - }) - it('escapes an embedded quote, which would otherwise end the argument early', () => { expect(quoteSftpBatchArgument('/tmp/dq".bin')).toBe('"/tmp/dq\\".bin"') }) @@ -43,8 +31,4 @@ describe('quoteSftpBatchArgument', () => { it('refuses a line break, which would split one batch command into two', () => { expect(() => quoteSftpBatchArgument('/tmp/a\nrm -rf b')).toThrow(UnsupportedSftpPathError) }) - - it('refuses a NUL, which truncates the argument', () => { - expect(() => quoteSftpBatchArgument('/tmp/a\0b')).toThrow(UnsupportedSftpPathError) - }) }) diff --git a/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts index 5a98be2b7ec..9b70ff6599b 100644 --- a/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-windows-upload.test.ts @@ -29,12 +29,7 @@ import { clearWindowsRemoteWriteCapabilitiesForTests, getWindowsRemoteWriteCapabilities } from './system-ssh-windows-write-capabilities' -import { - explainWindowsPowerShellStdinFailure, - WINDOWS_STDIN_WRITE_CHUNK_BYTES, - WINDOWS_STDIN_WRITE_TIMEOUT_MS, - writeWindowsRemoteFile -} from './system-ssh-windows-write-strategy' +import { WINDOWS_STDIN_WRITE_CHUNK_BYTES } from './system-ssh-windows-write-strategy' import type { SshTarget } from '../../../../shared/ssh-types' type FakeChannel = EventEmitter & { @@ -91,9 +86,6 @@ const fileWrites = (): RecordedCommand[] => const writtenPath = (command: RecordedCommand): string => /\$path = '((?:[^']|'')*)'/.exec(command.script)?.[1]?.replace(/''/g, "'") ?? '' -const putLines = (): string[] => - sftpBatches.flatMap((batch) => batch.script.split('\n').filter((line) => line.startsWith('put '))) -const putDestination = (line: string): string => /put "(?:[^"]*)" "([^"]*)"/.exec(line)?.[1] ?? '' const putSource = (line: string): string => /put "([^"]*)"/.exec(line)?.[1] ?? '' function acceptSftp(): void { @@ -213,20 +205,6 @@ describe('Windows upload over sftp', () => { expect(getWindowsRemoteWriteCapabilities(target).shouldTry('sftp-subsystem')).toBe(true) expect(fileWrites()).toHaveLength(0) }) - - it('keeps using sftp for the next file after one path it could not spell', async () => { - writeFileSync(join(localDir, 'relay.js'), 'x') - - await uploadFileViaSystemSsh(target, join(localDir, 'relay.js'), '//fileserver/share/a.js', { - hostPlatform - }) - await uploadFileViaSystemSsh(target, join(localDir, 'relay.js'), `${remoteRoot}/b.js`, { - hostPlatform - }) - - expect(putLines()).toHaveLength(1) - expect(putDestination(putLines()[0]!)).toContain('/C:/Users/dev/.orca-remote/b.js') - }) }) describe('Windows upload on a host with no sftp subsystem', () => { @@ -302,76 +280,4 @@ describe('Windows upload on a host with no sftp subsystem', () => { expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(true) expect(commands.some((command) => command.script.includes('::Move('))).toBe(false) }) - - it.each([ - 'relay-CommandNotFoundException.js', - 'is not recognized as an internal or external command.js' - ])('propagates a timeout whose filename resembles a missing command: %s', async (file) => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const remotePath = `${remoteRoot}/${file}` - writeFileSync(join(localDir, file), 'x') - let noteWriteStarted: () => void = () => {} - const writeStarted = new Promise((resolve) => { - noteWriteStarted = resolve - }) - spawnSystemSshCommandMock.mockImplementation((_target: SshTarget, command: string) => { - const executable = command.split(' ')[0] ?? '' - return createFakeChannel((channel) => { - commands.push({ - script: decodePowerShellCommand(command), - executable, - stdin: channel.written - }) - if (executable !== 'pwsh.exe') { - setImmediate(() => channel.emit('close', 0, null)) - } else { - noteWriteStarted() - } - }) - }) - try { - const result = expect( - uploadFileViaSystemSsh(target, join(localDir, file), remotePath, { hostPlatform }) - ).rejects.toThrow('timed out') - await writeStarted - await vi.advanceTimersByTimeAsync(WINDOWS_STDIN_WRITE_TIMEOUT_MS + 1) - await result - - expect(fileWrites().map((write) => write.executable)).toEqual(['pwsh.exe']) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(true) - expect(commands.some((command) => command.script.includes('::Move('))).toBe(false) - } finally { - vi.useRealTimers() - } - }) - - it.each([ - 'relay-CommandNotFoundException.js', - 'is not recognized as an internal or external command.js' - ])('propagates a short source whose filename resembles a missing command: %s', async (file) => { - await expect( - writeWindowsRemoteFile( - target, - `${remoteRoot}/${file}`, - { - totalBytes: 1, - readChunk: async () => Buffer.alloc(0), - withLocalFile: async (send) => send(join(localDir, file)) - }, - {} - ) - ).rejects.toThrow('Source ran short') - - expect(fileWrites()).toHaveLength(0) - expect(getWindowsRemoteWriteCapabilities(target).shouldTry('pwsh')).toBe(true) - expect(commands.some((command) => command.script.includes('::Move('))).toBe(false) - }) -}) - -describe('last-resort Windows PowerShell failure reporting', () => { - it('leaves a real failure alone, so a permission error is not reported as a host limitation', () => { - const denied = new Error('write C:/x at offset 0 failed (exit 1): Access to the path is denied') - - expect(explainWindowsPowerShellStdinFailure(denied)).toBe(denied) - }) }) diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts index 73aeb6d0eab..44cbebff518 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-port-reservation.test.ts @@ -54,11 +54,4 @@ describe('local forward port reservation', () => { await expect(reserveLocalForwardPort(port, ['ssh'], cancel)).resolves.toBe(port) expect(cancel).not.toHaveBeenCalled() }) - - it('keeps the bind error when neither recovery released the port', async () => { - const port = await holdPort() - await expect(reserveLocalForwardPort(port, ['ssh'], async () => false)).rejects.toThrow( - `Local port 127.0.0.1:${port} is not available` - ) - }) }) diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts index d509a0d568b..5cdec80a062 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-muxed-forward-cancel.test.ts @@ -79,12 +79,4 @@ describe('system SSH muxed forward cancel', () => { false ) }) - - it('asks no master on Windows, whose OpenSSH cannot multiplex', async () => { - Object.defineProperty(process, 'platform', { value: 'win32' }) - await expect(cancelMuxedLocalForward(createTarget(), 59418, '127.0.0.1', 6768)).resolves.toBe( - false - ) - expect(runProcessMock).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts index 04acf701825..a9784a863b5 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-orphaned-forward.test.ts @@ -213,27 +213,4 @@ describe('stopOrphanedOrcaSshForward', () => { vi.useRealTimers() } }) - - it('touches nothing when no orphan holds the port, or the table cannot be read', async () => { - const kill = vi.fn() - await expect( - stopOrphanedOrcaSshForward(47123, EXPECTED, { - listProcesses: async () => [], - kill, - readStartTimeMs: async () => 1_000, - platform: 'darwin' - }) - ).resolves.toBe(false) - await expect( - stopOrphanedOrcaSshForward(47123, EXPECTED, { - listProcesses: async () => { - throw new Error('ps failed') - }, - kill, - readStartTimeMs: async () => 1_000, - platform: 'darwin' - }) - ).resolves.toBe(false) - expect(kill).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/system-transport/ssh-proxy-command.test.ts b/src/main/ssh/system-transport/ssh-proxy-command.test.ts index 1344c37144b..9111a674abd 100644 --- a/src/main/ssh/system-transport/ssh-proxy-command.test.ts +++ b/src/main/ssh/system-transport/ssh-proxy-command.test.ts @@ -93,24 +93,6 @@ describe('spawnProxyCommand', () => { setPlatform(realPlatform) }) - it('passes the cmd.exe command line verbatim so inner quotes survive', () => { - setPlatform('win32') - spawnMock.mockReturnValue(createMockProxyProcess()) - - spawnProxyCommand( - { kind: 'proxy-command', command: 'cloudflared access ssh --hostname %h --port %p' }, - 'target.example.com', - 22, - 'deploy' - ) - - expect(spawnMock).toHaveBeenCalledWith( - process.env.ComSpec || 'cmd.exe', - ['/d', '/s', '/c', '"cloudflared access ssh --hostname "target.example.com" --port "22""'], - expect.objectContaining({ windowsVerbatimArguments: true }) - ) - }) - it('refuses values that cmd.exe cannot quote safely', () => { setPlatform('win32') spawnMock.mockReturnValue(createMockProxyProcess()) diff --git a/src/main/startup/agent-hooks-uninstall-preflight.ts b/src/main/startup/agent-hooks-uninstall-preflight.ts index 30946ae9841..7d9ea337188 100644 --- a/src/main/startup/agent-hooks-uninstall-preflight.ts +++ b/src/main/startup/agent-hooks-uninstall-preflight.ts @@ -54,7 +54,8 @@ export function runAgentHooksUninstallPreflight(argv: readonly string[] = proces } // Loaded only here, so ordinary startup never pays for every agent's hook module. void removeAgentHooksForUninstall(async () => { - const { removeManagedAgentHooks } = await import('../agent-hooks/managed-agent-hook-controls') + const { removeManagedAgentHooks } = + await import('../agent-hooks/installation/managed-agent-hook-controls') return removeManagedAgentHooks() }).then((code) => { clearTimeout(timeout) diff --git a/src/main/startup/branch-rename-hook.ts b/src/main/startup/branch-rename-hook.ts index bb5781a65ea..76e96b1af69 100644 --- a/src/main/startup/branch-rename-hook.ts +++ b/src/main/startup/branch-rename-hook.ts @@ -1,6 +1,6 @@ -import { maybeAutoRenameBranchOnFirstWork } from '../agent-hooks/first-work-branch-rename' -import { firstWorkRenameDeps } from '../agent-hooks/first-work-rename-runtime' -import { agentHookServer } from '../agent-hooks/server' +import { maybeAutoRenameBranchOnFirstWork } from '../agent-hooks/first-work/first-work-branch-rename' +import { firstWorkRenameDeps } from '../agent-hooks/first-work/first-work-rename-runtime' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { mainProcessState as state } from './main-process-state' /** Arms first-work rename from the hook store itself, so headless serve (no window) renames too. */ diff --git a/src/main/startup/browser-process-user-agent-ordering.test.ts b/src/main/startup/browser-process-user-agent-ordering.test.ts index 16c3eb14ed0..f1f4a4b25b6 100644 --- a/src/main/startup/browser-process-user-agent-ordering.test.ts +++ b/src/main/startup/browser-process-user-agent-ordering.test.ts @@ -198,7 +198,7 @@ vi.mock('./ensure-virtual-display', () => ({ vi.mock('./gpu-lifecycle') vi.mock('./main-process-state', () => ({ mainProcessState: {} })) vi.mock('./synthetic-title-runtime') -vi.mock('../browser/identity/browser-identity-mode-store', () => ({ +vi.mock('../browser/identity/mode/browser-identity-mode-store', () => ({ initializeBrowserIdentityModeStore: (path: string) => { mocks.events.push(`read-mode:${path}`) return { diff --git a/src/main/startup/main-process-account-services.ts b/src/main/startup/main-process-account-services.ts index 18670a8ffa2..f2e6f26462e 100644 --- a/src/main/startup/main-process-account-services.ts +++ b/src/main/startup/main-process-account-services.ts @@ -11,9 +11,9 @@ import { readOpenCodeGoApiKey, saveOpenCodeGoApiKey } from '../opencode/opencode-go-api-key-store' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { prewarmStructuredAgentModelCatalogs } from '../runtime/agent-session/model-catalog/structured-agent-model-catalog-wiring' import { mainProcessState as state } from './main-process-state' diff --git a/src/main/startup/main-process-i18n-menu.ts b/src/main/startup/main-process-i18n-menu.ts index fcbd510d81a..c75bac814cf 100644 --- a/src/main/startup/main-process-i18n-menu.ts +++ b/src/main/startup/main-process-i18n-menu.ts @@ -19,7 +19,7 @@ import { } from './main-window-actions' import { ensureAutoUpdaterConfigured } from '../window/attach-main-window-services' import { logStartupMilestone } from './startup-diagnostics' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' export async function initializeMainProcessI18nAndMenu(): Promise { const store = state.store diff --git a/src/main/startup/main-process-observers.ts b/src/main/startup/main-process-observers.ts index 92711003e54..473327c15a0 100644 --- a/src/main/startup/main-process-observers.ts +++ b/src/main/startup/main-process-observers.ts @@ -8,8 +8,8 @@ import { listCapableSharedControlSockets, startDesktopPresenceReporter } from '../notifications/desktop-presence-reporter' -import { agentHookServer } from '../agent-hooks/server' -import { installHookStatusSessionTabsRepublish } from '../agent-hooks/hook-status-session-tabs-republish' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { installHookStatusSessionTabsRepublish } from '../agent-hooks/runtime/hook-status-session-tabs-republish' import { initTelemetry, track } from '../telemetry/client' import { setCodexTrustGrantTelemetry } from '../codex/trust/grants/codex-trust-grant-telemetry' import { initObservability } from '../observability/index' diff --git a/src/main/startup/main-process-plugins.ts b/src/main/startup/main-process-plugins.ts index 624cf2a8c81..3b910fb8800 100644 --- a/src/main/startup/main-process-plugins.ts +++ b/src/main/startup/main-process-plugins.ts @@ -34,7 +34,7 @@ import { isUsablePluginLanguagePack } from '../../shared/plugins/languages/plugi import { rebuildAppMenu } from '../menu/register-app-menu' import { rebuildSystemTrayMenu } from '../tray/system-tray' import { logStartupMilestone } from './startup-diagnostics' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { bindPluginRuntime, createPluginAgentStatusForwarder, diff --git a/src/main/startup/main-process-preflight.ts b/src/main/startup/main-process-preflight.ts index 247cf45f005..16bddb5f6bd 100644 --- a/src/main/startup/main-process-preflight.ts +++ b/src/main/startup/main-process-preflight.ts @@ -102,7 +102,7 @@ import { import { mainProcessState as state } from './main-process-state' import { initializeSyntheticTitleRuntime } from './synthetic-title-runtime' import { initializeBrowserProcessUserAgent } from '../browser/identity/browser-process-user-agent' -import { initializeBrowserIdentityModeStore } from '../browser/identity/browser-identity-mode-store' +import { initializeBrowserIdentityModeStore } from '../browser/identity/mode/browser-identity-mode-store' import { acquireProfileStateRuntimeAdmission } from '../persistence/profile-state/profile-state-access' import { getActiveProfileStateLocation } from '../persistence/profile-state/profile-state-active-location' import { diff --git a/src/main/startup/main-process-pty-startup.ts b/src/main/startup/main-process-pty-startup.ts index a569f1389bf..f914308f0c1 100644 --- a/src/main/startup/main-process-pty-startup.ts +++ b/src/main/startup/main-process-pty-startup.ts @@ -25,14 +25,14 @@ import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { agentHookServer } from '../agent-hooks/server' -import { createLocalTmuxManagedPtyResolver } from '../agent-hooks/local-tmux-managed-pty' -import { installLocalHookRootEvidence } from '../agent-hooks/local-hook-root-evidence' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { createLocalTmuxManagedPtyResolver } from '../agent-hooks/observations/local-tmux-managed-pty' +import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' import { indexPersistedPaneKeyPtyIds, resolveAgentWorkspaceExecutionHostId, retireRestoredStatusesWithDeadTerminals -} from '../agent-hooks/restored-status-dead-terminal-sweep' +} from '../agent-hooks/observations/restored-status-dead-terminal-sweep' import { startFirstWindowStartupServices } from './first-window-startup-services' import { logStartupMilestone } from './startup-diagnostics' import type { WindowsDesktopStartupServices } from './windows-desktop-shell-path-startup' diff --git a/src/main/startup/main-process-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts index 4d27a406cf2..95451a1393b 100644 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ b/src/main/startup/main-process-quit-pending-writer.test.ts @@ -23,9 +23,11 @@ const dependencies: Record> = { }, '../ipc/ssh/ssh-shutdown-drain': { beginSshShutdown }, './main-process-connector-startup': { desktopConnectorCloud: () => null }, - '../agent-hooks/server': { agentHookServer: { stop: stopAgentHookServer } }, - '../agent-hooks/wsl-hook-relay-manager': { wslHookRelayManager: { disposeAll: idle() } }, - '../agent-hooks/managed-agent-hook-controls': { + '../agent-hooks/server/agent-hook-server': { agentHookServer: { stop: stopAgentHookServer } }, + '../agent-hooks/wsl-relay/wsl-hook-relay-manager': { + wslHookRelayManager: { disposeAll: idle() } + }, + '../agent-hooks/installation/managed-agent-hook-controls': { removeManagedAgentHooksAsync: vi.fn(async () => []) }, '../runtime/agent-session/structured-agent-session-runtime': { @@ -41,10 +43,10 @@ const dependencies: Record> = { }, '../ipc/browser/desktop-browser-bridge-wiring': { disposeDesktopBrowserBridge: idle() }, '../orca-profiles/profile-cloud-session-owner': { flushUnsavedCloudSessions: idle() }, - '../browser/browser-manager': { + '../browser/guest-lifecycle/manager/browser-manager': { browserManager: { setBrowserGuestStateChangedListener: idle(), setOffscreenTabOpener: idle() } }, - '../browser/sessions/browser-session-registry': { browserSessionRegistry: {} }, + '../browser/sessions/profiles/browser-session-registry': { browserSessionRegistry: {} }, '../browser/routing/local-host-partitions/local-ssh-browser-route': { closeAllLocalSshBrowserRoutes: settled() }, @@ -55,7 +57,7 @@ const dependencies: Record> = { '../dock/unread-badge': { setUnreadDockBadgeCount: idle() }, '../tray/system-tray': { destroySystemTray: idle() }, '../telemetry/client': { shutdownTelemetry: settled() }, - '../observability': { shutdownObservability: settled() }, + '../observability/index': { shutdownObservability: settled() }, '../updater': { isQuittingForUpdate: vi.fn(() => false) }, '../updater-lifecycle-diagnostics': { recordUpdaterLifecycle: idle() }, '../macos-permissions/macos-tcc-prompt-notice': { stopTccPromptNotice: idle() }, diff --git a/src/main/startup/main-process-quit-update-veto.test.ts b/src/main/startup/main-process-quit-update-veto.test.ts index 1cc335550b0..9a71b26cd7e 100644 --- a/src/main/startup/main-process-quit-update-veto.test.ts +++ b/src/main/startup/main-process-quit-update-veto.test.ts @@ -8,9 +8,9 @@ const dependencyExports: [string, string[]][] = [ ['../ipc/pty/kill-all', ['killAllPty']], ['../daemon/providers/lifecycle/daemon-provider-state', ['disconnectDaemon', 'shutdownDaemon']], ['../ipc/ssh-shutdown-drain', ['beginSshShutdown']], - ['../agent-hooks/server', ['agentHookServer']], - ['../agent-hooks/wsl-hook-relay-manager', ['wslHookRelayManager']], - ['../agent-hooks/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], + ['../agent-hooks/server/agent-hook-server', ['agentHookServer']], + ['../agent-hooks/wsl-relay/wsl-hook-relay-manager', ['wslHookRelayManager']], + ['../agent-hooks/installation/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], [ '../runtime/agent-session/structured-agent-session-runtime', ['stopStructuredAgentSessionRuntime'] @@ -27,8 +27,8 @@ const dependencyExports: [string, string[]][] = [ ], ['../ipc/browser/desktop-browser-bridge-wiring', ['disposeDesktopBrowserBridge']], ['../orca-profiles/profile-cloud-session-owner', ['flushUnsavedCloudSessions']], - ['../browser/browser-manager', ['browserManager']], - ['../browser/sessions/browser-session-registry', ['browserSessionRegistry']], + ['../browser/guest-lifecycle/manager/browser-manager', ['browserManager']], + ['../browser/sessions/profiles/browser-session-registry', ['browserSessionRegistry']], ['../codex/codex-state-db-backfill-recovery', ['stopCodexStateDbBackfillRecoveries']], ['../codex/codex-account-session-bridge', ['stopCodexAccountSessionBridges']], ['../git/refs/maintenance/local-repo-ref-maintenance', ['awaitPackedRefsLockRelease']], @@ -38,7 +38,7 @@ const dependencyExports: [string, string[]][] = [ ['../dock/unread-badge', ['setUnreadDockBadgeCount']], ['../tray/system-tray', ['destroySystemTray']], ['../telemetry/client', ['shutdownTelemetry']], - ['../observability', ['shutdownObservability']], + ['../observability/index', ['shutdownObservability']], ['../updater', ['isQuittingForUpdate']], ['../updater-lifecycle-diagnostics', ['recordUpdaterLifecycle']], ['../macos-permissions/macos-tcc-prompt-notice', ['stopTccPromptNotice']], diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index 9c17b61a314..6ab8794ad84 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -10,16 +10,16 @@ import { shutdownDaemon } from '../daemon/providers/lifecycle/daemon-provider-state' import { beginSshShutdown } from '../ipc/ssh/ssh-shutdown-drain' -import { agentHookServer } from '../agent-hooks/server' -import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' -import { removeManagedAgentHooksAsync } from '../agent-hooks/managed-agent-hook-controls' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' +import { removeManagedAgentHooksAsync } from '../agent-hooks/installation/managed-agent-hook-controls' import { stopStructuredAgentSessionRuntime } from '../runtime/agent-session/structured-agent-session-runtime' import { setStructuredAgentSessionTeardownTrigger } from '../runtime/agent-session/structured-agent-session-runtime-teardown' import { awaitRuntimeFileWatcherUnsubscribes } from '../runtime/files/watch/file-watcher-leases' import { clearRuntimeMetadataIfOwned } from '../runtime/rpc/server/runtime-metadata' import { shutdownPairedRuntimeBrowserClientHosts } from '../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-runtime' import { disposeDesktopBrowserBridge } from '../ipc/browser/desktop-browser-bridge-wiring' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { stopCodexStateDbBackfillRecoveries } from '../codex/history/index/codex-state-db-backfill-recovery' import { stopCodexAccountSessionBridges } from '../codex/history/bridges/codex-account-session-bridge' import { awaitPackedRefsLockRelease } from '../git/refs/maintenance/local-repo-ref-maintenance' diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 83c363d4128..e598f4f1823 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -7,8 +7,11 @@ import { setNodeDistMirrorSettingReader } from '../node-runtime/node-dist-mirror import { handleBrowserGuestLogin } from '../browser/guest-lifecycle/prompts/browser-http-auth-prompt' import { installMainThreadHangWatchdog } from '../hang-watchdog/main-thread-hang-watchdog' import { preservePreviousHangDetection } from '../hang-watchdog/previous-hang-detection' -import { browserCertificateTrustController, browserManager } from '../browser/browser-manager' -import { browserSiteDisplayController } from '../browser/site-settings/browser-site-display-controller' +import { + browserCertificateTrustController, + browserManager +} from '../browser/guest-lifecycle/manager/browser-manager' +import { browserSiteDisplayController } from '../browser/site-settings/display/browser-site-display-controller' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' import { getAppEnvironment } from '../../shared/app-environment' @@ -29,7 +32,7 @@ import { configureWindowsHostGitEnvironmentReadiness, setDefaultWslDistroOverride } from '../git/runner' -import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' +import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { applyAppIcon } from '../window/desktop-integration/app-icon' import { shouldSuppressDevEducation, @@ -38,7 +41,7 @@ import { import { awaitBrowserSessionProxies, setBrowserNetworkProxySettingsResolver -} from '../browser/sessions/browser-session-proxy' +} from '../browser/sessions/proxy/browser-session-proxy' import { installDocPreviewProtocolHandler } from '../browser/document-preview/doc-preview-protocol' import { installMediaPreviewProtocolHandler } from '../media/media-preview-protocol' import { installJiraImageProtocolHandler } from '../jira/attachments/image-protocol' @@ -49,7 +52,7 @@ import { switchBrowserExtensionSupport } from '../browser/extensions/browser-extension-startup' import { whenBrowserExtensionSessionsLoaded } from '../browser/extensions/profile-sessions/browser-extension-session-loader' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { logStartupMilestone } from './startup-diagnostics' import { writeHttp1CompatibilityMarker } from './http1-compatibility-marker' import { mainProcessState as state } from './main-process-state' @@ -60,7 +63,7 @@ import { reconcileManagedWslCliRegistrations } from '../cli/wsl-cli-registration-reconciliation' import { createWslCliReconciliationStartupBarrier } from './wsl-cli-reconciliation-startup-barrier' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { reportProfileStateWriteFailure } from './profile-state-write-failure' import { reportProfileStateSaveDelay } from './profile-state-save-delay' diff --git a/src/main/startup/main-process-ready-identity-write.test.ts b/src/main/startup/main-process-ready-identity-write.test.ts index 945f25eec73..6515dfd68a3 100644 --- a/src/main/startup/main-process-ready-identity-write.test.ts +++ b/src/main/startup/main-process-ready-identity-write.test.ts @@ -116,7 +116,7 @@ vi.mock('../hang-watchdog/hang-detection-marker', () => ({ consumeHangDetectionMarker: vi.fn(() => null), hangDetectionMarkerPath: vi.fn(() => '/test-marker') })) -vi.mock('../browser/browser-manager', () => ({ +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ browserCertificateTrustController: {}, browserManager: { installCertificateRequestGuard: vi.fn(), @@ -159,7 +159,7 @@ vi.mock('../git/command-runner/wsl-command-resolution', async (importOriginal) = ...(await importOriginal>()), setDefaultWslDistroOverride: vi.fn() })) -vi.mock('../agent-hooks/wsl-hook-relay-manager', () => ({ +vi.mock('../agent-hooks/wsl-relay/wsl-hook-relay-manager', () => ({ wslHookRelayManager: { setManagedHookSettingsResolver: vi.fn() } })) vi.mock('../window/desktop-integration/app-icon', () => ({ applyAppIcon: vi.fn() })) @@ -167,7 +167,7 @@ vi.mock('./dev-education-suppression', () => ({ shouldSuppressDevEducation: () => false, suppressDevEducationForStore: vi.fn() })) -vi.mock('../browser/sessions/browser-session-proxy', () => ({ +vi.mock('../browser/sessions/proxy/browser-session-proxy', () => ({ awaitBrowserSessionProxies: vi.fn(async () => {}), setBrowserNetworkProxySettingsResolver: vi.fn(), invalidateBrowserSessionProxyApplication: vi.fn() @@ -188,7 +188,7 @@ vi.mock('../browser/client-hosts/lifecycle/paired-runtime-browser-client-host-ru vi.mock('../browser/routing/partitions/browser-route-partition-storage-runtime', () => ({ collectOrphanedBrowserRoutePartitionStorage: vi.fn(async () => {}) })) -vi.mock('../browser/sessions/browser-session-partition-policies', () => ({ +vi.mock('../browser/sessions/partition-policies/browser-session-partition-policies', () => ({ installBrowserSessionPartitionPolicies: vi.fn(async () => {}), forgetBrowserSessionPartitionConfiguration: vi.fn(), clearBrowserSessionPartitionPolicies: vi.fn() @@ -202,7 +202,7 @@ vi.mock('../browser/routing/sessions/browser-session-route-policies', () => ({ installBrowserRoutePartitionPolicies: vi.fn(), clearBrowserRoutePartitionPolicies: vi.fn() })) -vi.mock('../browser/sessions/browser-session-profile-retirement', () => ({ +vi.mock('../browser/sessions/profiles/browser-session-profile-retirement', () => ({ retireFailedBrowserSessionProfile: vi.fn(async () => {}) })) vi.mock('../browser/webauthn/browser-webauthn-account-picker', () => ({ @@ -246,8 +246,8 @@ import { BROWSER_IDENTITY_MODE_FILE, BROWSER_IDENTITY_MODE_VERSION, readBrowserIdentityModeRecord -} from '../browser/identity/browser-identity-mode-record' -import { BROWSER_SESSION_META_FILE_NAME } from '../browser/sessions/browser-session-meta-store' +} from '../browser/identity/mode/browser-identity-mode-record' +import { BROWSER_SESSION_META_FILE_NAME } from '../browser/sessions/profiles/browser-session-meta-store' import { getOrcaProfileBrowserSessionPartition } from '../../shared/orca-profiles' // Transform the ready graph at collection, outside any test timeout; tests re-evaluate it after resetModules. import './main-process-ready' @@ -289,7 +289,7 @@ function seedRetiredProfile(): void { /** Use fresh module graphs to reset the registry's initialization latch. */ async function runReady(): Promise { - const identity = await import('../browser/identity/browser-identity-mode-store') + const identity = await import('../browser/identity/mode/browser-identity-mode-store') // Preflight fixes identity for this launch. identity.initializeBrowserIdentityModeStore(mocks.userDataPath) const { initializeMainProcessReady } = await import('./main-process-ready') diff --git a/src/main/startup/main-process-ready-runtime.ts b/src/main/startup/main-process-ready-runtime.ts index a50f1f4a0a9..cb50c15cffe 100644 --- a/src/main/startup/main-process-ready-runtime.ts +++ b/src/main/startup/main-process-ready-runtime.ts @@ -6,7 +6,7 @@ import { AgentBrowserBridge } from '../browser/agent-browser/agent-browser-bridg import { EmulatorBridge } from '../emulator/emulator-bridge' import { RpcDispatcher } from '../runtime/rpc/dispatcher' import { DESKTOP_RPC_CALLER, LOCAL_CLI_RPC_CALLER } from '../runtime/rpc/rpc-caller-identity' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { configureBrowserClientPageAutomationRuntime } from '../browser/client-pages/execution/browser-client-page-automation-runtime' import { BrowserExpectedUrlMismatch } from '../../shared/browser/client-hosting/browser-expected-url' import { BrowserClientPageCommandError } from '../browser/client-pages/execution/browser-client-page-command-failure' @@ -16,9 +16,9 @@ import { recordProcessGoneCrash } from './main-window-lifecycle-flags' import { handleGpuChildCrash } from './gpu-lifecycle' import { isGpuFallbackCrashCandidate } from '../crash-reporting/gpu-crash-fallback-decision' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { hydrateAgentCliShellPath } from '../agent-hooks/local-agent-cli-presence' +import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/managed-agent-hook-startup' +import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' import { shouldInstallManagedHooks } from './configure-process' import { mainProcessState as state } from './main-process-state' import { initializeMainProcessObservers } from './main-process-observers' diff --git a/src/main/startup/main-process-runtime-launch-activation.test.ts b/src/main/startup/main-process-runtime-launch-activation.test.ts index e7766f4a949..c6ab3ae918f 100644 --- a/src/main/startup/main-process-runtime-launch-activation.test.ts +++ b/src/main/startup/main-process-runtime-launch-activation.test.ts @@ -54,7 +54,7 @@ vi.mock('../providers/local-pty/local-pty-provider', () => ({ LocalPtyProvider: vi.mock('../browser/backends/offscreen-browser-backend', () => ({ OffscreenBrowserBackend: class {} })) -vi.mock('../browser/browser-manager', () => ({ browserManager: {} })) +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: {} })) vi.mock('./main-process-relay-status', () => ({ getDesktopRelayStatus: vi.fn(), publishDesktopRelayStatus: vi.fn() @@ -106,7 +106,7 @@ vi.mock('./startup-diagnostics', () => ({ logStartupMilestone: vi.fn() })) const setupHeadlessServeAutoUpdater = vi.hoisted(() => vi.fn()) vi.mock('../window/main-window-updater', () => ({ setupHeadlessServeAutoUpdater })) vi.mock('../server/serve-stdout-boundary', () => ({ emitServeBrowserIdentityActionLine: vi.fn() })) -vi.mock('../browser/identity/browser-identity-mode-store', () => ({ +vi.mock('../browser/identity/mode/browser-identity-mode-store', () => ({ getBrowserIdentityModeStatus: vi.fn() })) const showWindowWithoutStealingFocus = vi.hoisted(() => vi.fn()) diff --git a/src/main/startup/main-process-runtime-launch.ts b/src/main/startup/main-process-runtime-launch.ts index 903353282be..544ed1666c9 100644 --- a/src/main/startup/main-process-runtime-launch.ts +++ b/src/main/startup/main-process-runtime-launch.ts @@ -15,7 +15,7 @@ import { registerHeadlessPtyRuntime } from '../ipc/pty/register-headless-runtime import { LocalPtyProvider } from '../providers/local-pty/local-pty-provider' import { publishHeadlessRuntimeGraph } from '../runtime/session-graph/headless-runtime-graph' import { OffscreenBrowserBackend } from '../browser/backends/offscreen-browser-backend' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { getDesktopRelayStatus } from './main-process-relay-status' import { startDesktopRelayService } from './main-process-relay-startup' import { getServeOptions, getBundledWebClientRoot, printServeReady } from './main-process-serve' @@ -53,7 +53,7 @@ import { preserveStateBeforeUpdateRestart } from '../updater/update-restart-pres import { resolveUpdateInstallMode } from '../updater/updater-service' import { scheduleAgentLaunchRecordWarmup } from './agent-launch-record-warmup' import { emitServeBrowserIdentityActionLine } from '../server/serve-stdout-boundary' -import { getBrowserIdentityModeStatus } from '../browser/identity/browser-identity-mode-store' +import { getBrowserIdentityModeStatus } from '../browser/identity/mode/browser-identity-mode-store' type RuntimeService = NonNullable diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 9dbe36f1e74..9af01fb0f51 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -10,16 +10,16 @@ import { translateMain } from '../i18n/main-i18n' import { OrcaRuntimeService } from '../runtime/orca-runtime' import { getLocalPtyProvider } from '../ipc/pty/provider/registry' import { clearProviderPtyState } from '../ipc/pty/provider/state-cleanup' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { toAgentStatusIpcPayload } from '../agent-hooks/server/server-status-identity' -import { browserManager } from '../browser/browser-manager' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { loadAgentSessionClaimSigner } from '../runtime/agent-session/ownership/agent-session-claim-identity' import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' import { codexAiVaultSessionResumePreparation } from '../codex/history/resume/codex-ai-vault-session-resume' import { prepareCodexPinnedLaunchHome } from './codex-session-resume-launch' import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { agentHookRuntimeDeps } from '../agent-hooks/agent-hook-runtime-deps' +import { agentHookRuntimeDeps } from '../agent-hooks/runtime/agent-hook-runtime-deps' import { getDaemonProvider } from '../daemon/providers/lifecycle/daemon-provider-state' import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' @@ -36,7 +36,7 @@ import { import { registerRecipeVmWaker } from '../runtime/workspaces/sleep/recipe-vm-waker-registry' import { openRecipeVmEnvironment } from '../ipc/runtime-environments/runtime-environment-recipe-vm-wake' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store' +import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-workspace-runtime' import { installWslOrcadAccountShim } from './wsl-orcad-account-env-wiring' import { codexStructuredLaunchHomeResolvers, diff --git a/src/main/startup/main-window-actions.ts b/src/main/startup/main-window-actions.ts index 0f4b1edd83e..16a5bf71a73 100644 --- a/src/main/startup/main-window-actions.ts +++ b/src/main/startup/main-window-actions.ts @@ -8,7 +8,7 @@ import { type Tray, type WebContents } from 'electron' -import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/native-browser-popup-windows' +import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/presentation/native-browser-popup-windows' import type { UpdateCheckOptions } from '../../shared/update-status-types' import type { AppMenuQuitHandlers } from '../menu/app-menu-quit-item' import type { createWebContentsTimedFlag } from './web-contents-timed-flag' diff --git a/src/main/startup/main-window-agent-status.ts b/src/main/startup/main-window-agent-status.ts index 383bf8a6725..23409edbe1f 100644 --- a/src/main/startup/main-window-agent-status.ts +++ b/src/main/startup/main-window-agent-status.ts @@ -1,6 +1,6 @@ import type { BrowserWindow } from 'electron' -import { agentHookServer } from '../agent-hooks/server' -import { setMigrationUnsupportedPtyListener } from '../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { setMigrationUnsupportedPtyListener } from '../agent-hooks/observations/migration-unsupported-pty-state' import { getDashboardPopoutWindow } from '../window/dashboard-popout-window' import { stopSyntheticTitleSpinnerTimer } from './synthetic-title-runtime' import { mainProcessState as state } from './main-process-state' diff --git a/src/main/startup/quit/quit-path-durable-write-blocking.test.ts b/src/main/startup/quit/quit-path-durable-write-blocking.test.ts index 340e732e023..141b1bea1a1 100644 --- a/src/main/startup/quit/quit-path-durable-write-blocking.test.ts +++ b/src/main/startup/quit/quit-path-durable-write-blocking.test.ts @@ -286,45 +286,6 @@ describe('quit-path durable writes never park the main thread', () => { expect(readState(dir).ui.sidebarWidth).toBe(200) }) - it('serializes github-cache snapshots and keeps the newest generation', async () => { - const dir = makeDir() - const store = await createStore(dir) - let releaseWrite!: () => void - const writeRelease = new Promise((resolve) => { - releaseWrite = resolve - }) - let signalWrite!: () => void - releases.push(releaseWrite) - const writeStarted = new Promise((resolve) => { - signalWrite = resolve - }) - let held = false - fsCalls.dirPrefix = dir - fsCalls.recording = true - fsCalls.waitAsync = (fn, target) => { - if (held || fn !== 'writeFile' || !target.includes('orca-github-cache.json')) { - return null - } - held = true - signalWrite() - return writeRelease - } - - store.setGitHubCache({ pr: { test: { data: null, fetchedAt: 1 } }, issue: {} }) - const finalFlush = store.flushAsync() - await writeStarted - store.setGitHubCache({ pr: { test: { data: null, fetchedAt: 2 } }, issue: {} }) - - releaseWrite() - await finalFlush - fsCalls.recording = false - - expect(JSON.parse(readFileSync(join(dir, 'orca-github-cache.json'), 'utf-8'))).toEqual({ - pr: { test: { data: null, fetchedAt: 2 } }, - issue: {} - }) - }) - it('stats.flushAsync() wins over a debounced write already in flight', async () => { const dir = makeDir() const stats = await createStatsCollector(dir) diff --git a/src/main/startup/synthetic-title-runtime.ts b/src/main/startup/synthetic-title-runtime.ts index ae64e518b7b..7c5d24652bb 100644 --- a/src/main/startup/synthetic-title-runtime.ts +++ b/src/main/startup/synthetic-title-runtime.ts @@ -1,5 +1,5 @@ import { registerPaneKeyTeardownListener, getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import type { AgentStatusState } from '../../shared/agent-status/contracts/agent-status-types' import { normalizeTerminalTitle } from '../../shared/agent-status/title/agent-title-status' import { diff --git a/src/main/stats/agent-session-transition-recorder.test.ts b/src/main/stats/agent-session-transition-recorder.test.ts index 53df1d4a82c..9dfaeeb3c04 100644 --- a/src/main/stats/agent-session-transition-recorder.test.ts +++ b/src/main/stats/agent-session-transition-recorder.test.ts @@ -1,13 +1,17 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Mock } from 'vitest' -import { AgentSessionTransitionRecorder } from './agent-session-transition-recorder' -import type { AgentSessionSink, AgentSessionStatusEvent } from './agent-session-transition-recorder' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' + +import { + AgentSessionTransitionRecorder, + type AgentSessionSink, + type AgentSessionStatusEvent +} from './agent-session-transition-recorder' + import { StatsCollector } from './collector' -import { AgentHookServer, _internals } from '../agent-hooks/server' -import { PANE as STORE_PANE } from '../agent-hooks/server.test-fixtures' +import { AgentHookServer, _internals } from '../agent-hooks/server/agent-hook-server' +import { PANE as STORE_PANE } from '../agent-hooks/server/testing/server.test-fixtures' let userDataDir: string diff --git a/src/main/telemetry/burst-cap.ts b/src/main/telemetry/burst-cap.ts index 58eec375a78..9758afdb1ab 100644 --- a/src/main/telemetry/burst-cap.ts +++ b/src/main/telemetry/burst-cap.ts @@ -1,6 +1,7 @@ // Per-event refill caps runaway producers; non-refilling session/consent ceilings bound aggregate volume. Reset per telemetry session and warn once per bucket so overflow cannot flood stderr. import { eventSchemas, type EventName } from '../../shared/telemetry-events' +import { isProtectedMilestoneEvent } from './event-sampling' const PER_EVENT_DEFAULT_CAPACITY = 30 const PER_EVENT_AGENT_ERROR_CAPACITY = 20 @@ -59,6 +60,11 @@ export function consumeBurstToken(name: EventName): boolean { } return false } + // Once-per-day milestones keep their own bucket so noisy diagnostics cannot starve them. + if (isProtectedMilestoneEvent(name)) { + bucket.tokens -= 1 + return true + } if (perSessionCount >= PER_SESSION_CEILING) { if (!perSessionWarned) { perSessionWarned = true diff --git a/src/main/telemetry/client-prompt-sampling.test.ts b/src/main/telemetry/client-prompt-sampling.test.ts index ea85823f0ea..a406f223e2b 100644 --- a/src/main/telemetry/client-prompt-sampling.test.ts +++ b/src/main/telemetry/client-prompt-sampling.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { EventProps } from '../../shared/telemetry-events' import { track } from './client' import { + BASE_COMMON, cleanupTelemetryClientTest, setupTelemetryClientTest, type TelemetryClientTestState @@ -18,7 +19,13 @@ describe('prompt event sampling', () => { beforeEach(() => { vi.useFakeTimers() - state = setupTelemetryClientTest() + // Milestones already earned, so only the sampled prompt stream is measured here. + state = setupTelemetryClientTest({ + optedIn: true, + installId: BASE_COMMON.install_id, + existedBeforeTelemetryRelease: false, + protectedMilestones: { firstAgentInteractionDay: 0, meaningfulActivityDay: 1_000_000 } + }) }) afterEach(() => { diff --git a/src/main/telemetry/client-protected-milestones.test.ts b/src/main/telemetry/client-protected-milestones.test.ts new file mode 100644 index 00000000000..3b0dd9e715a --- /dev/null +++ b/src/main/telemetry/client-protected-milestones.test.ts @@ -0,0 +1,281 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { GlobalSettings } from '../../shared/global-settings-types' +import type { EventProps } from '../../shared/telemetry-events' +import { _enableTransportForTests, track } from './client' +import { + BASE_COMMON, + cleanupTelemetryClientTest, + setupTelemetryClientTest, + type TelemetryClientTestState +} from './client-test-harness' +import { recordMobileChatSend, recordMobileViewOpened } from './mobile-client-telemetry' +import { observeTerminalUserInput } from './protected-milestones' + +const hookPrompt: EventProps<'agent_prompt_sent'> = { + agent_kind: 'claude-code', + launch_source: 'unknown', + request_kind: 'followup' +} +const sidebarSend: EventProps<'agent_prompt_sent'> = { ...hookPrompt, launch_source: 'sidebar' } +const sidebarLaunch: EventProps<'agent_started'> = { + agent_kind: 'codex', + launch_source: 'sidebar', + request_kind: 'new' +} + +function telemetry( + protectedMilestones: NonNullable['protectedMilestones'] = { + installCohort: 'fresh' + } +): GlobalSettings['telemetry'] { + return { + optedIn: true, + installId: BASE_COMMON.install_id, + existedBeforeTelemetryRelease: false, + protectedMilestones + } +} + +describe('protected telemetry milestones', () => { + let state: TelemetryClientTestState + + type Message = { event: string; properties: Record } + let earlier: Message[] = [] + // Thrown captures were never accepted by the SDK queue. + const accepted = (): Message[] => [ + ...earlier, + ...state.mock.capture.mock.calls + .filter((_, index) => state.mock.capture.mock.results[index]?.type !== 'throw') + .map(([message]): Message => message) + ] + const captured = (event: string) => accepted().filter((message) => message.event === event) + const milestones = () => + accepted() + .map((message) => message.event) + .filter((event) => event === 'first_agent_interaction' || event === 'meaningful_activity_day') + const restart = () => { + const saved = state.settings.telemetry + earlier = accepted() + cleanupTelemetryClientTest(state.envStash) + state = setupTelemetryClientTest(saved) + } + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-08T23:58:00Z')) + earlier = [] + state = setupTelemetryClientTest(telemetry()) + }) + + afterEach(() => { + cleanupTelemetryClientTest(state.envStash) + vi.useRealTimers() + }) + + it('emits the first observed interaction once, across restarts, with unsampled props', () => { + vi.spyOn(Math, 'random').mockReturnValue(0) + track('agent_prompt_sent', sidebarSend) + track('agent_prompt_sent', sidebarSend) + restart() + track('agent_prompt_sent', sidebarSend) + + const first = captured('first_agent_interaction') + expect(first).toHaveLength(1) + expect(first[0].properties).toEqual({ + ...BASE_COMMON, + source: 'orca_send', + agent_kind: 'claude-code', + install_cohort: 'fresh', + $process_person_profile: false + }) + expect(state.settings.telemetry?.protectedMilestones).toEqual({ + installCohort: 'fresh', + firstAgentInteractionDay: 20_765, + meaningfulActivityDay: 20_765 + }) + }) + + it('records one meaningful day per UTC day across midnight and restart', () => { + track('agent_started', sidebarLaunch) + track('workspace_created', { source: 'sidebar', from_existing_branch: false }) + vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) + restart() + track('workspace_created', { source: 'sidebar', from_existing_branch: false }) + restart() + track('agent_started', sidebarLaunch) + + expect(captured('meaningful_activity_day').map((m) => m.properties.trigger)).toEqual([ + 'agent_started', + 'workspace_created' + ]) + expect(state.settings.telemetry?.protectedMilestones?.meaningfulActivityDay).toBe(20_766) + }) + + it('keeps milestones when the source prompt is sampled out', () => { + vi.spyOn(Math, 'random').mockReturnValue(0.99) + expect(track('agent_prompt_sent', sidebarSend)).toBe(false) + + expect(captured('agent_prompt_sent')).toHaveLength(0) + expect(milestones()).toEqual(['first_agent_interaction', 'meaningful_activity_day']) + expect(captured('meaningful_activity_day')[0].properties).not.toHaveProperty('sample_rate') + }) + + it('is not starved once noisy events exhaust the session budget', () => { + for (let index = 0; index < 1_000; index++) { + vi.advanceTimersByTime(3_000) + track('agent_error', { agent_kind: 'codex', error_class: 'unknown' }) + } + expect(track('agent_error', { agent_kind: 'codex', error_class: 'unknown' })).toBe(false) + + vi.spyOn(Math, 'random').mockReturnValue(0) + expect(track('agent_prompt_sent', sidebarSend)).toBe(false) + expect(milestones()).toEqual(['first_agent_interaction', 'meaningful_activity_day']) + }) + + it('retries a milestone whose capture was not accepted', () => { + state.mock.capture.mockImplementationOnce(() => { + throw new Error('queue rejected') + }) + track('native_chat_prompt_submitted', { + agent_kind: 'codex', + runtime: 'local', + client: 'desktop' + }) + expect(state.settings.telemetry?.protectedMilestones?.firstAgentInteractionDay).toBeUndefined() + + track('native_chat_prompt_submitted', { + agent_kind: 'codex', + runtime: 'local', + client: 'desktop' + }) + expect(milestones()).toEqual(['meaningful_activity_day', 'first_agent_interaction']) + expect(state.settings.telemetry?.protectedMilestones?.firstAgentInteractionDay).toBe(20_765) + }) + + it('does not consume milestones while consent or the build gate blocks transmission', () => { + state.settings.telemetry!.optedIn = false + track('agent_started', sidebarLaunch) + state.settings.telemetry!.optedIn = true + _enableTransportForTests(false) + track('agent_started', sidebarLaunch) + _enableTransportForTests(true) + expect(milestones()).toEqual([]) + expect(state.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + + track('agent_started', sidebarLaunch) + expect(milestones()).toEqual(['meaningful_activity_day']) + }) + + it('ignores invalid source payloads and renderer-unreachable raw fields', () => { + const rawPrompt = { ...sidebarSend, prompt: 'private text' } + track('agent_prompt_sent', rawPrompt) + const rawMilestone = { + source: 'orca_send', + agent_kind: 'codex', + install_cohort: 'fresh', + prompt: 'private text' + } as const + expect(track('first_agent_interaction', rawMilestone)).toBe(false) + const forged = { trigger: 'app_opened', install_cohort: 'fresh' } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately forges an out-of-enum trigger to prove runtime schema rejection. + const launchOnly = forged as EventProps<'meaningful_activity_day'> + expect(track('meaningful_activity_day', launchOnly)).toBe(false) + expect(milestones()).toEqual([]) + expect(state.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + }) + + it('does not mark activity from passive, automated or unattributed observations', () => { + track('app_opened', {}) + track('agent_started', { ...sidebarLaunch, request_kind: 'resume' }) + track('agent_started', { ...sidebarLaunch, launch_source: 'orchestration' }) + track('agent_started', { ...sidebarLaunch, launch_source: 'cli' }) + track('workspace_created', { source: 'unknown', from_existing_branch: false }) + recordMobileChatSend('mobile', 'claude', { ok: true, replayed: true }) + recordMobileChatSend('runtime', 'claude', { ok: true, replayed: false }) + recordMobileViewOpened( + { clientKind: 'mobile' }, + { + surface: 'chat', + viewKey: 'chat:1', + agent: () => 'claude' + } + ) + expect(milestones()).toEqual([]) + + for (const launch_source of ['orchestration', 'cli', 'unknown'] as const) { + track('agent_prompt_sent', { ...hookPrompt, launch_source }) + } + expect(milestones()).toEqual(['first_agent_interaction']) + expect(captured('first_agent_interaction')[0].properties.source).toBe('unattributed_prompt') + }) + + it('keeps commands and unacknowledged PTY sends from consuming chat milestones', () => { + track('native_chat_message_sent', { agent_kind: 'codex', runtime: 'local', client: 'desktop' }) + recordMobileChatSend('mobile', 'claude', { ok: true, replayed: false }) + expect(milestones()).toEqual([]) + expect(state.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + + track('native_chat_prompt_submitted', { + agent_kind: 'codex', + runtime: 'remote', + client: 'desktop' + }) + expect(captured('first_agent_interaction')[0].properties).toMatchObject({ + source: 'native_chat', + agent_kind: 'codex' + }) + expect(captured('meaningful_activity_day')[0].properties.trigger).toBe('native_chat') + }) + + it('counts a provider-accepted phone prompt as an interaction and an active day', () => { + track('native_chat_prompt_submitted', { + agent_kind: 'claude-code', + runtime: 'unknown', + client: 'mobile' + }) + + expect(captured('first_agent_interaction')[0].properties).toMatchObject({ + source: 'mobile_chat', + agent_kind: 'claude-code' + }) + expect(captured('meaningful_activity_day')[0].properties).toMatchObject({ + trigger: 'mobile_chat', + install_cohort: 'fresh' + }) + }) + + it('reports profiles without a frozen cohort as existing', () => { + state.settings.telemetry = telemetry({}) + track('agent_started', sidebarLaunch) + expect(captured('meaningful_activity_day')[0].properties.install_cohort).toBe('existing') + }) + + it('marks terminal activity once per day across restart and UTC rollover', () => { + observeTerminalUserInput() + restart() + observeTerminalUserInput() + expect(milestones()).toEqual(['meaningful_activity_day']) + + vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) + observeTerminalUserInput() + expect( + captured('meaningful_activity_day').map((message) => message.properties.trigger) + ).toEqual(['terminal_input', 'terminal_input']) + expect(state.settings.telemetry?.protectedMilestones?.meaningfulActivityDay).toBe(20_766) + }) + + it('rate-limits blocked terminal checks within the day and retries immediately after UTC midnight', () => { + vi.setSystemTime(new Date('2026-11-08T23:59:59Z')) + state.settings.telemetry!.optedIn = false + observeTerminalUserInput() + state.settings.telemetry!.optedIn = true + observeTerminalUserInput() + expect(milestones()).toEqual([]) + expect(state.settings.telemetry?.protectedMilestones?.meaningfulActivityDay).toBeUndefined() + + vi.setSystemTime(new Date('2026-11-09T00:00:01Z')) + observeTerminalUserInput() + expect(milestones()).toEqual(['meaningful_activity_day']) + expect(state.settings.telemetry?.protectedMilestones?.meaningfulActivityDay).toBe(20_766) + }) +}) diff --git a/src/main/telemetry/client.ts b/src/main/telemetry/client.ts index 978f13b974e..2a9417355bb 100644 --- a/src/main/telemetry/client.ts +++ b/src/main/telemetry/client.ts @@ -7,11 +7,13 @@ import type { AgentDashboardSurface } from '../../shared/telemetry-agent-dashboa import type { Store } from '../persistence/loading-store/store' import { consumeBurstToken, resetBurstCapsForSession } from './burst-cap' import { telemetryEventSampleRate } from './event-sampling' +import * as protectedMilestones from './protected-milestones' import { experimentCohortProps } from './experiment-cohort-props' import { getCohortAtEmit } from './cohort-classifier' import { isConsentEnvOverridden, resolveConsent } from './consent' import * as postHogStart from './posthog-client-start' -import { buildCommonProps, createPostHogClient, waitForCaptureEnqueue } from './posthog-transport' +import { buildCommonProps, createPostHogClient } from './posthog-transport' +import { captureOptOutBeforeSdkOptOut } from './opt-out-capture' import { commonPropsSchema, validate } from './validator' export { shouldOptOutSdkAtInit } from './posthog-transport' @@ -42,6 +44,8 @@ let storeRef: Store | null = null let testTransportEnabled = false +type CaptureProperties = Readonly> + // Banner resolution gates first app_opened; mark and emit atomically. let appOpenedTrackedThisSession = false const trackedDashboardActiveDays = new Map() @@ -54,6 +58,7 @@ export function initTelemetry(store: Store, scheduleStart: postHogStart.StartSch // Reset banner/app-open gating each launch, not once per install. appOpenedTrackedThisSession = false trackedDashboardActiveDays.clear() + protectedMilestones.bindSession(store, enqueueCapture, isTelemetryEnabled) postHogStart.resetStart() if (!TELEMETRY_ENABLED || !IS_OFFICIAL_BUILD || BUILD_IDENTITY === null || WRITE_KEY === null) { @@ -139,11 +144,16 @@ export function track(name: N, props: EventProps): boole (!posthog && !postHogStart.isStartDeferred()) || !commonProps || !storeRef || - posthog?.optedOut || - (sampleRate < 1 && Math.random() >= sampleRate) + posthog?.optedOut ) { return false } + const sampledOut = sampleRate < 1 && Math.random() >= sampleRate + // Milestones derive from every observation, so sampling and budgets cannot hide them. + const milestoneDay = protectedMilestones.observationDay(name) + if (sampledOut && milestoneDay === null) { + return false + } const dashboardActiveSurface = name === 'agent_dashboard_active' && @@ -163,7 +173,8 @@ export function track(name: N, props: EventProps): boole } // Cap floods before expensive live consent reads, including opted-out renderers. - if (!consumeBurstToken(name)) { + const withinBudget = !sampledOut && consumeBurstToken(name) + if (!withinBudget && milestoneDay === null) { return false } @@ -179,6 +190,12 @@ export function track(name: N, props: EventProps): boole if (!result.ok) { return false } + if (milestoneDay !== null) { + protectedMilestones.record(name, result.props, settings, milestoneDay) + } + if (!withinBudget) { + return false + } if (dashboardActiveSurface) { if (settings.experimentalAgentDashboardPopout !== true) { return false @@ -198,22 +215,7 @@ export function track(name: N, props: EventProps): boole ? { sample_rate: sampleRate } : {} - // Node SDK requires per-capture person-profile suppression. - const message = { - distinctId: commonProps.install_id, - event: name, - properties: { - ...commonProps, - ...result.props, - ...mainOwnedProps, - $process_person_profile: false - } - } - if (posthog) { - posthog.capture(message) - } else { - postHogStart.holdCapture(message, ensurePostHogClient) - } + enqueueCapture(name, { ...result.props, ...mainOwnedProps }) if (dashboardActiveSurface && settings.telemetry) { trackedDashboardActiveDays.set(dashboardActiveSurface, dashboardActiveDay) try { @@ -233,6 +235,23 @@ export function track(name: N, props: EventProps): boole return true } +function enqueueCapture(name: EventName, props: CaptureProperties): void { + if (!commonProps) { + throw new Error('telemetry common props missing') + } + // Node SDK requires per-capture person-profile suppression. + const message = { + distinctId: commonProps.install_id, + event: name, + properties: { ...commonProps, ...props, $process_person_profile: false } + } + if (posthog) { + posthog.capture(message) + } else { + postHogStart.holdCapture(message, ensurePostHogClient) + } +} + export async function setOptIn(via: OptInVia, optedIn: boolean): Promise { if (!storeRef) { return @@ -263,27 +282,9 @@ export async function setOptIn(via: OptInVia, optedIn: boolean): Promise { if (!client || isConsentEnvOverridden()) { return } - // Enqueue opt-out directly before disabling SDK; track would reject it under the newly stored preference. try { - if (!shuttingDown && commonProps && consumeBurstToken('telemetry_opted_out')) { - const validated = validate('telemetry_opted_out', { via }) - if (validated.ok) { - const uuid = randomUUID() - const enqueued = waitForCaptureEnqueue(client, 'telemetry_opted_out', uuid) - client.capture({ - distinctId: commonProps.install_id, - event: 'telemetry_opted_out', - uuid, - properties: { - ...commonProps, - ...validated.props, - $process_person_profile: false - } - }) - if (!(await enqueued)) { - console.warn('[telemetry] telemetry_opted_out did not enqueue before SDK opt-out') - } - } + if (!shuttingDown && commonProps) { + await captureOptOutBeforeSdkOptOut(client, commonProps, via) } } catch (err) { console.warn('[telemetry] telemetry_opted_out capture failed before SDK opt-out:', err) diff --git a/src/main/telemetry/event-sampling.ts b/src/main/telemetry/event-sampling.ts index 91bd9b48105..2c866e465aa 100644 --- a/src/main/telemetry/event-sampling.ts +++ b/src/main/telemetry/event-sampling.ts @@ -1,7 +1,17 @@ import type { EventName } from '../../shared/telemetry-events' +// Low-volume protected milestones: never sampled and exempt from the shared session ceiling. +const PROTECTED_MILESTONE_EVENTS: ReadonlySet = new Set([ + 'first_agent_interaction', + 'meaningful_activity_day' +]) + +export function isProtectedMilestoneEvent(name: string): boolean { + return PROTECTED_MILESTONE_EVENTS.has(name) +} + export function telemetryEventSampleRate(name: EventName): 0.01 | 0.001 | 1 { - if (name === 'agent_prompt_sent') { + if (name === 'agent_prompt_sent' || name === 'native_chat_prompt_submitted') { return 0.01 } if (name === 'daemon_audit_eligibility') { diff --git a/src/main/telemetry/native-chat-prompt-submissions.ts b/src/main/telemetry/native-chat-prompt-submissions.ts new file mode 100644 index 00000000000..e1f81ed8c86 --- /dev/null +++ b/src/main/telemetry/native-chat-prompt-submissions.ts @@ -0,0 +1,86 @@ +import { tuiAgentToAgentKind } from '../../shared/agent-kind' +import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config' +import type { EventProps } from '../../shared/telemetry-events' +import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' +import type { JournalRow } from '../native-chat/agent-session-journal/durable-rows/journal-row-schema' +import { recordStructuredChatPromptAccepted } from './structured-chat-dispatch' + +type PromptJournal = Pick +type PromptSource = EventProps<'native_chat_prompt_submitted'> +const pendingPrompts = new WeakMap< + PromptJournal, + Map +>() +const MAX_PENDING_PROMPTS_PER_JOURNAL = 256 + +/** Fresh user sends retain device provenance through queued-message conversion, without persisting telemetry state. */ +export function rememberNativeChatPrompt( + journal: PromptJournal, + clientMessageId: string, + agent: string, + userClient: 'desktop' | 'mobile' | undefined, + ownerKey?: string +): void { + if (!userClient) { + return + } + let pending = pendingPrompts.get(journal) + if (!pending) { + pending = new Map() + pendingPrompts.set(journal, pending) + } + if (pending.has(clientMessageId)) { + return + } + if (pending.size >= MAX_PENDING_PROMPTS_PER_JOURNAL) { + const oldest = pending.keys().next().value + if (oldest !== undefined) { + pending.delete(oldest) + } + } + pending.set(clientMessageId, { + ownerKey, + source: { + agent_kind: isTuiAgent(agent) ? tuiAgentToAgentKind(agent) : 'other', + // The host cannot establish the desktop renderer's execution-target classification. + runtime: 'unknown', + client: userClient + } + }) +} + +export function forgetNativeChatPrompt(journal: PromptJournal, clientMessageId: string): void { + pendingPrompts.get(journal)?.delete(clientMessageId) +} + +/** Observe only committed transitions, never history snapshots, local reservations or handover preambles. */ +export function observeNativeChatPromptSubmissions( + journal: PromptJournal, + rows: readonly JournalRow[] | undefined +): void { + const pending = pendingPrompts.get(journal) + if (!pending?.size || !rows) { + return + } + for (const row of rows) { + if (row.kind === 'epoch') { + pending.clear() + } else if (row.kind === 'queue' && row.change.op === 'withdrawn') { + pending.delete(row.messageId) + } else if (row.kind === 'dispatch') { + const submission = journal.submission(row.clientMessageId) + const sourceId = submission?.queuedMessageId ?? row.clientMessageId + const source = pending.get(sourceId) + if (row.state === 'accepted' && source) { + pending.delete(sourceId) + try { + recordStructuredChatPromptAccepted(source.source, source.ownerKey) + } catch (error) { + console.warn('[telemetry] native chat prompt observation failed', error) + } + } else if (row.state === 'rejected' && !submission?.queuedMessageId) { + pending.delete(sourceId) + } + } + } +} diff --git a/src/main/telemetry/opt-out-capture.ts b/src/main/telemetry/opt-out-capture.ts new file mode 100644 index 00000000000..c98ab22e216 --- /dev/null +++ b/src/main/telemetry/opt-out-capture.ts @@ -0,0 +1,32 @@ +import { randomUUID } from 'node:crypto' +import type { PostHog } from 'posthog-node' +import type { CommonProps, OptInVia } from '../../shared/telemetry-events' +import { consumeBurstToken } from './burst-cap' +import { waitForCaptureEnqueue } from './posthog-transport' +import { validate } from './validator' + +/** Enqueue opt-out directly before disabling the SDK; track would reject it under the newly stored preference. */ +export async function captureOptOutBeforeSdkOptOut( + client: PostHog, + common: CommonProps, + via: OptInVia +): Promise { + if (!consumeBurstToken('telemetry_opted_out')) { + return + } + const validated = validate('telemetry_opted_out', { via }) + if (!validated.ok) { + return + } + const uuid = randomUUID() + const enqueued = waitForCaptureEnqueue(client, 'telemetry_opted_out', uuid) + client.capture({ + distinctId: common.install_id, + event: 'telemetry_opted_out', + uuid, + properties: { ...common, ...validated.props, $process_person_profile: false } + }) + if (!(await enqueued)) { + console.warn('[telemetry] telemetry_opted_out did not enqueue before SDK opt-out') + } +} diff --git a/src/main/telemetry/protected-milestones.ts b/src/main/telemetry/protected-milestones.ts new file mode 100644 index 00000000000..94a11f47bfd --- /dev/null +++ b/src/main/telemetry/protected-milestones.ts @@ -0,0 +1,260 @@ +// Derives protected milestones from already-validated, consented product events so sampling and the shared budget cannot hide them. +// Not exactly-once: cursors advance at SDK enqueue/hold acceptance (a quit before flush loses the event) and persist via the +// debounced settings save (a crash before that save can re-emit after restart), so dashboards dedupe per install_id. + +import type { GlobalSettings } from '../../shared/global-settings-types' +import { utcDayIndex } from '../../shared/telemetry-day' +import { eventSchemas, type EventName, type EventProps } from '../../shared/telemetry-events' +import type { + FirstAgentInteractionSource, + MeaningfulActivityTrigger +} from '../../shared/telemetry-protected-milestone-schemas' +import type { TelemetrySettings } from '../../shared/telemetry-settings-types' +import type { Store } from '../persistence/loading-store/store' +import { consumeBurstToken } from './burst-cap' +import { validate } from './validator' + +export type ProtectedMilestone = + | { name: 'first_agent_interaction'; props: EventProps<'first_agent_interaction'> } + | { name: 'meaningful_activity_day'; props: EventProps<'meaningful_activity_day'> } + +type ProtectedMilestoneCursor = { firstInteractionDone: boolean; activityDay: number } +type Observation = EventName | 'terminal_input' +type SourceObservation = + | { name: 'agent_started'; props: EventProps<'agent_started'> } + | { name: 'agent_prompt_sent'; props: EventProps<'agent_prompt_sent'> } + | { name: 'native_chat_prompt_submitted'; props: EventProps<'native_chat_prompt_submitted'> } + | { name: 'workspace_created'; props: EventProps<'workspace_created'> } + | { name: 'terminal_input' } +type Enqueue = (name: ProtectedMilestone['name'], props: ProtectedMilestone['props']) => void +type MilestoneSession = { store: Store; enqueue: Enqueue; isEnabled: () => boolean } + +const SOURCE_EVENTS: ReadonlySet = new Set([ + 'agent_started', + 'agent_prompt_sent', + 'native_chat_prompt_submitted', + 'workspace_created' +]) +// Automation and scriptable launches cannot prove a person acted that day. +const UNATTRIBUTED_LAUNCH_SOURCES: ReadonlySet = new Set([ + 'orchestration', + 'cli', + 'unknown' +]) + +// While a UTC day is unmarked, typing must cost at most one consent read a minute within that day. +const TERMINAL_INPUT_CHECK_INTERVAL_MS = 60_000 + +// Mirrors accepted cursors so a failed settings write cannot re-emit within the session. +let cursor: ProtectedMilestoneCursor | null = null +let session: MilestoneSession | null = null +let lastTerminalInputCheckAt: number | null = null + +/** Bind the telemetry session's store, capture path and live gates; each launch starts from persisted cursors. */ +export function bindSession(store: Store, enqueue: Enqueue, isEnabled: () => boolean): void { + session = { store, enqueue, isEnabled } + cursor = null + lastTerminalInputCheckAt = null +} + +/** Cheap pre-check before consent reads: the UTC day an observation could still earn a milestone for, else null. */ +export function observationDay(name: EventName, now = Date.now()): number | null { + if (!SOURCE_EVENTS.has(name)) { + return null + } + const day = utcDayIndex(now) + // An unknown cursor defers to the persisted one. + if (!cursor || cursor.activityDay < day) { + return day + } + const canStillInteract = + !cursor.firstInteractionDone && name !== 'agent_started' && name !== 'workspace_created' + return canStillInteract ? day : null +} + +// Re-parse with the source schema so eligibility reads typed fields; only runs while a milestone is unearned. +function parseObservation(name: Observation, props: unknown): SourceObservation | null { + if (name === 'terminal_input') { + return { name } + } + if (name === 'agent_started') { + const parsed = eventSchemas.agent_started.safeParse(props) + return parsed.success ? { name, props: parsed.data } : null + } + if (name === 'agent_prompt_sent') { + const parsed = eventSchemas.agent_prompt_sent.safeParse(props) + return parsed.success ? { name, props: parsed.data } : null + } + if (name === 'native_chat_prompt_submitted') { + const parsed = eventSchemas.native_chat_prompt_submitted.safeParse(props) + return parsed.success ? { name, props: parsed.data } : null + } + if (name === 'workspace_created') { + const parsed = eventSchemas.workspace_created.safeParse(props) + return parsed.success ? { name, props: parsed.data } : null + } + return null +} + +function interactionSource(observation: SourceObservation): FirstAgentInteractionSource | null { + if (observation.name === 'native_chat_prompt_submitted') { + return observation.props.client === 'mobile' ? 'mobile_chat' : 'native_chat' + } + if (observation.name === 'agent_prompt_sent') { + return UNATTRIBUTED_LAUNCH_SOURCES.has(observation.props.launch_source) + ? 'unattributed_prompt' + : 'orca_send' + } + return null +} + +function activityTrigger(observation: SourceObservation): MeaningfulActivityTrigger | null { + if (observation.name === 'terminal_input') { + return 'terminal_input' + } + if (observation.name === 'agent_started') { + // Resumes include background wakes of sleeping sessions. + return observation.props.request_kind === 'new' && + !UNATTRIBUTED_LAUNCH_SOURCES.has(observation.props.launch_source) + ? 'agent_started' + : null + } + if (observation.name === 'workspace_created') { + return observation.props.source === 'unknown' ? null : 'workspace_created' + } + const source = interactionSource(observation) + return source === 'unattributed_prompt' ? null : source +} + +function hydrate(saved: TelemetrySettings['protectedMilestones']): ProtectedMilestoneCursor { + const persisted = { + firstInteractionDone: saved?.firstAgentInteractionDay !== undefined, + activityDay: saved?.meaningfulActivityDay ?? -1 + } + cursor = { + firstInteractionDone: persisted.firstInteractionDone || cursor?.firstInteractionDone === true, + activityDay: Math.max(persisted.activityDay, cursor?.activityDay ?? -1) + } + return cursor +} + +/** Milestones a validated, consented observation earns. */ +function earnedProtectedMilestones( + name: Observation, + props: unknown, + telemetry: TelemetrySettings | undefined, + day: number +): ProtectedMilestone[] { + const observation = parseObservation(name, props) + if (!observation) { + return [] + } + const current = hydrate(telemetry?.protectedMilestones) + // Unknown provenance must not claim a fresh install. + const install_cohort = telemetry?.protectedMilestones?.installCohort ?? 'existing' + const earned: ProtectedMilestone[] = [] + const source = interactionSource(observation) + if ( + source && + (observation.name === 'agent_prompt_sent' || + observation.name === 'native_chat_prompt_submitted') && + !current.firstInteractionDone + ) { + earned.push({ + name: 'first_agent_interaction', + props: { source, agent_kind: observation.props.agent_kind, install_cohort } + }) + } + const trigger = activityTrigger(observation) + if (trigger && current.activityDay < day) { + earned.push({ name: 'meaningful_activity_day', props: { trigger, install_cohort } }) + } + return earned +} + +/** Advance the cursor for an accepted capture and return the settings value to persist. */ +function acceptProtectedMilestone( + milestone: ProtectedMilestone['name'], + telemetry: TelemetrySettings | undefined, + day: number +): NonNullable { + const current = hydrate(telemetry?.protectedMilestones) + const saved = telemetry?.protectedMilestones ?? {} + if (milestone === 'first_agent_interaction') { + current.firstInteractionDone = true + return { ...saved, firstAgentInteractionDay: saved.firstAgentInteractionDay ?? day } + } + current.activityDay = Math.max(current.activityDay, day) + return { ...saved, meaningfulActivityDay: current.activityDay } +} + +/** Persist each cursor only after its capture is enqueued or held, so rejected attempts retry on the next observation. */ +export function record( + name: Observation, + props: unknown, + settings: GlobalSettings, + day: number +): void { + if (!session) { + return + } + const { store, enqueue } = session + for (const milestone of earnedProtectedMilestones(name, props, settings.telemetry, day)) { + if (!consumeBurstToken(milestone.name)) { + continue + } + const validated = validate(milestone.name, milestone.props) + if (!validated.ok) { + continue + } + try { + enqueue(milestone.name, validated.props) + } catch (err) { + console.warn('[telemetry] protected milestone capture failed', err) + continue + } + const telemetry = store.getSettings().telemetry + const protectedMilestones = acceptProtectedMilestone(milestone.name, telemetry, day) + if (!telemetry) { + continue + } + try { + store.updateSettings({ telemetry: { ...telemetry, protectedMilestones } }) + } catch (err) { + console.warn('[telemetry] failed to persist protected milestone cursor', err) + } + } +} + +/** Genuine desktop xterm input admitted by a local or remote transport marks the day. */ +export function observeTerminalUserInput(now = Date.now()): void { + const day = utcDayIndex(now) + if (!session || (cursor && cursor.activityDay >= day)) { + return + } + const last = lastTerminalInputCheckAt + if ( + last !== null && + utcDayIndex(last) === day && + now >= last && + now - last < TERMINAL_INPUT_CHECK_INTERVAL_MS + ) { + return + } + try { + if (!session.isEnabled()) { + lastTerminalInputCheckAt = now + return + } + const settings = session.store.getSettings() + if (hydrate(settings.telemetry?.protectedMilestones).activityDay >= day) { + return + } + lastTerminalInputCheckAt = now + record('terminal_input', undefined, settings, day) + } catch (err) { + lastTerminalInputCheckAt = now + // Telemetry must never disturb terminal input. + console.warn('[telemetry] terminal activity milestone failed', err) + } +} diff --git a/src/main/telemetry/structured-chat-dispatch.ts b/src/main/telemetry/structured-chat-dispatch.ts index 0699b980c37..97ffb5378ad 100644 --- a/src/main/telemetry/structured-chat-dispatch.ts +++ b/src/main/telemetry/structured-chat-dispatch.ts @@ -3,21 +3,31 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' import type { StructuredChatStartTelemetryEvent, + StructuredChatPromptTelemetryEvent, StructuredChatTelemetryEvent } from '../../shared/structured-chat-dispatch-telemetry' import { agentKindSchema } from '../../shared/telemetry-property-schemas' -import { isTelemetryInitialized } from './client' +import { isTelemetryInitialized, track } from './client' +import type { EventProps } from '../../shared/telemetry-events' type TelemetryListener = (event: StructuredChatTelemetryEvent, callerKey: string) => void const remoteListeners = new Set() const receivedEvents = new Set() -const telemetryEventSchema = z.strictObject({ - type: z.literal('structuredChatAgentStart'), - id: z.uuid(), - agent_kind: agentKindSchema, - launch_source: z.literal('unknown'), - request_kind: z.enum(['new', 'resume']) -}) +const telemetryEventSchema = z.discriminatedUnion('type', [ + z.strictObject({ + type: z.literal('structuredChatAgentStart'), + id: z.uuid(), + agent_kind: agentKindSchema, + launch_source: z.literal('unknown'), + request_kind: z.enum(['new', 'resume']) + }), + z.strictObject({ + type: z.literal('structuredChatPromptAccepted'), + id: z.uuid(), + agent_kind: agentKindSchema, + client: z.enum(['desktop', 'mobile']) + }) +]) /** Live, best-effort delivery; outcomes settled without the caller connected are not replayed. */ export function subscribeStructuredChatTelemetry(listener: TelemetryListener): () => void { @@ -40,13 +50,39 @@ export function recordRemoteStructuredChatTelemetry(value: unknown): boolean { receivedEvents.delete(receivedEvents.values().next().value!) } try { - recordAgentStartTelemetry(event, 'structured') + if (event.type === 'structuredChatPromptAccepted') { + track('native_chat_prompt_submitted', { + agent_kind: event.agent_kind, + runtime: 'remote', + client: event.client + }) + } else { + recordAgentStartTelemetry(event, 'structured') + } } catch { // A telemetry failure must not interrupt runtime event delivery. } return true } +/** A paired owner retains consent authority even when this host also runs a desktop. */ +export function recordStructuredChatPromptAccepted( + source: EventProps<'native_chat_prompt_submitted'>, + ownerKey: string | undefined +): void { + if (ownerKey) { + const event: StructuredChatPromptTelemetryEvent = { + type: 'structuredChatPromptAccepted', + id: randomUUID(), + agent_kind: source.agent_kind, + client: source.client + } + relayStructuredChatTelemetry(event, ownerKey) + } else if (isTelemetryInitialized()) { + track('native_chat_prompt_submitted', source) + } +} + export function recordStructuredChatAgentStart( telemetry: Pick< StructuredChatStartTelemetryEvent, diff --git a/src/main/telemetry/structured-chat-prompt-owner.test.ts b/src/main/telemetry/structured-chat-prompt-owner.test.ts new file mode 100644 index 00000000000..ff0cdbed471 --- /dev/null +++ b/src/main/telemetry/structured-chat-prompt-owner.test.ts @@ -0,0 +1,155 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { RpcContext } from '../runtime/rpc/core' +import type { RpcCallerIdentity } from '../runtime/rpc/rpc-caller-identity' +import { structuredCallerFor } from '../runtime/rpc/methods/structured-sessions/creation/structured-agent-session-gate' +import type { StructuredChatTelemetryEvent } from '../../shared/structured-chat-dispatch-telemetry' +import { _setCommonPropsForTests } from './client' +import { + BASE_COMMON, + cleanupTelemetryClientTest, + setupTelemetryClientTest, + type TelemetryClientTestState +} from './client-test-harness' +import { + recordRemoteStructuredChatTelemetry, + recordStructuredChatPromptAccepted, + subscribeStructuredChatTelemetry +} from './structured-chat-dispatch' + +const HOST_INSTALL = '11111111-1111-4111-8111-111111111111' +const OWNER_INSTALL = '22222222-2222-4222-8222-222222222222' +let active: TelemetryClientTestState | undefined +let relayed: { event: StructuredChatTelemetryEvent; owner: string }[] +let unsubscribe: () => void + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-08T23:58:00Z')) + relayed = [] + unsubscribe = subscribeStructuredChatTelemetry((event, owner) => relayed.push({ event, owner })) +}) +afterEach(() => { + unsubscribe() + if (active) { + cleanupTelemetryClientTest(active.envStash) + active = undefined + } + vi.useRealTimers() +}) + +function desktop(installId: string, optedIn: boolean): TelemetryClientTestState { + if (active) { + cleanupTelemetryClientTest(active.envStash) + } + active = setupTelemetryClientTest({ + installId, + optedIn, + existedBeforeTelemetryRelease: false, + protectedMilestones: { installCohort: 'fresh' } + }) + _setCommonPropsForTests({ ...BASE_COMMON, install_id: installId }) + return active +} + +function accept( + caller: RpcCallerIdentity, + clientKind?: 'mobile' | 'runtime', + pairedDeviceParentId?: string +): void { + const context: Partial = { caller, clientKind, pairedDeviceParentId } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: caller derivation reads only the supplied transport identity fields. + const identity = structuredCallerFor(context as RpcContext) + if (!identity.userClient) { + throw new Error('expected a transport-proven user') + } + recordStructuredChatPromptAccepted( + { agent_kind: 'codex', runtime: 'unknown', client: identity.userClient }, + identity.telemetryOwnerKey + ) +} + +const captured = (state: TelemetryClientTestState, name: string) => + state.mock.capture.mock.calls.map(([event]) => event).filter((event) => event.event === name) + +it('lets the originating desktop opt in even when its initialized execution host opts out', () => { + const host = desktop(HOST_INSTALL, false) + accept({ kind: 'paired-device', deviceId: 'originating-desktop' }, 'runtime') + expect(relayed).toEqual([ + { + owner: 'originating-desktop', + event: { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'codex', + client: 'desktop' + } + } + ]) + expect(host.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + expect(host.mock.capture.mock.calls).toEqual([]) + + const owner = desktop(OWNER_INSTALL, true) + recordRemoteStructuredChatTelemetry(relayed[0].event) + expect(owner.settings.telemetry?.protectedMilestones).toEqual({ + installCohort: 'fresh', + firstAgentInteractionDay: 20_765, + meaningfulActivityDay: 20_765 + }) + expect(captured(owner, 'first_agent_interaction')[0].properties).toMatchObject({ + install_id: OWNER_INSTALL, + source: 'native_chat' + }) + expect(captured(owner, 'meaningful_activity_day')[0].properties).toMatchObject({ + install_id: OWNER_INSTALL, + trigger: 'native_chat' + }) +}) + +it('respects a delegated phone owners opt-out even when its initialized execution host opts in', () => { + const host = desktop(HOST_INSTALL, true) + accept({ kind: 'paired-device', deviceId: 'delegated-phone' }, 'mobile', 'originating-desktop') + expect(relayed).toEqual([ + { + owner: 'originating-desktop', + event: { + type: 'structuredChatPromptAccepted', + id: expect.any(String), + agent_kind: 'codex', + client: 'mobile' + } + } + ]) + expect(host.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + expect(host.mock.capture.mock.calls).toEqual([]) + + const owner = desktop(OWNER_INSTALL, false) + recordRemoteStructuredChatTelemetry(relayed[0].event) + expect(owner.settings.telemetry?.protectedMilestones).toEqual({ installCohort: 'fresh' }) + expect(owner.mock.capture.mock.calls).toEqual([]) +}) + +it('keeps the local desktop and its directly paired phone on host installation consent', () => { + const host = desktop(HOST_INSTALL, true) + accept({ kind: 'desktop' }) + vi.setSystemTime(new Date('2026-11-09T00:01:00Z')) + accept({ kind: 'paired-device', deviceId: 'direct-phone' }, 'mobile') + expect(relayed).toEqual([]) + expect(host.settings.telemetry?.protectedMilestones).toEqual({ + installCohort: 'fresh', + firstAgentInteractionDay: 20_765, + meaningfulActivityDay: 20_766 + }) + expect(captured(host, 'first_agent_interaction')[0].properties).toMatchObject({ + install_id: HOST_INSTALL, + source: 'native_chat' + }) + expect( + captured(host, 'meaningful_activity_day').map((event) => ({ + install_id: event.properties.install_id, + trigger: event.properties.trigger + })) + ).toEqual([ + { install_id: HOST_INSTALL, trigger: 'native_chat' }, + { install_id: HOST_INSTALL, trigger: 'mobile_chat' } + ]) +}) diff --git a/src/main/text-generation/source-control-agent-hook-isolation.test.ts b/src/main/text-generation/source-control-agent-hook-isolation.test.ts new file mode 100644 index 00000000000..7043a4dc273 --- /dev/null +++ b/src/main/text-generation/source-control-agent-hook-isolation.test.ts @@ -0,0 +1,63 @@ +import { afterAll, expect, it } from 'vitest' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSourceControlAgent } from './source-control-agent-launch' + +const folder = mkdtempSync(join(tmpdir(), 'orca-generation-hook-isolation-')) +afterAll(() => rmSync(folder, { recursive: true, force: true })) + +it('keeps background generation from reporting hooks against the launching terminal', async () => { + const agent = join(folder, 'report-environment.cjs') + writeFileSync( + agent, + `process.stdin.resume() +console.log(JSON.stringify({ + pane: process.env.ORCA_PANE_KEY ?? null, + fallbackPane: process.env.ORCA_AGENT_PANE ?? null, + launch: process.env.ORCA_AGENT_LAUNCH_TOKEN ?? null, + endpoint: process.env.ORCA_AGENT_HOOK_ENDPOINT ?? null, + port: process.env.ORCA_AGENT_HOOK_PORT ?? null, + disabled: process.env.ORCA_AGENT_HOOKS_DISABLED, + home: process.env.CODEX_HOME +})) +` + ) + const child = spawnSourceControlAgent({ + binary: process.execPath, + args: [agent], + cwd: folder, + env: { + ...process.env, + ORCA_PANE_KEY: 'dev-tab:dev-pane', + ORCA_AGENT_PANE: 'dev-tab:dev-pane', + ORCA_AGENT_LAUNCH_TOKEN: 'parent-launch', + ORCA_AGENT_HOOK_ENDPOINT: '/parent/hook.sock', + ORCA_AGENT_HOOK_PORT: '57279', + ORCA_AGENT_HOOKS_DISABLED: '0', + CODEX_HOME: join(folder, 'managed-home') + }, + stdinMode: 'pipe', + useCwdForNative: true + }) + let stdout = '' + let stderr = '' + child.stdout?.on('data', (chunk) => (stdout += chunk.toString())) + child.stderr?.on('data', (chunk) => (stderr += chunk.toString())) + const closed = new Promise((resolve, reject) => { + child.on('close', resolve) + child.on('error', reject) + }) + child.stdin?.end() + + expect(await closed, stderr).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + pane: null, + fallbackPane: null, + launch: null, + endpoint: null, + port: null, + disabled: '1', + home: join(folder, 'managed-home') + }) +}) diff --git a/src/main/text-generation/source-control-agent-launch.ts b/src/main/text-generation/source-control-agent-launch.ts index 51a18712934..66b97a0ea6a 100644 --- a/src/main/text-generation/source-control-agent-launch.ts +++ b/src/main/text-generation/source-control-agent-launch.ts @@ -1,8 +1,11 @@ import { wslDistroForCommand } from '../../shared/wsl-paths' import { spawnProcess } from '@orca/process-host' import { withCliRuntimeOnPath } from '../../shared/node-cli-command-resolution' +import { ORCA_AGENT_HOOKS_DISABLED_ENV } from '../../shared/agent-hook-listener/transport/agent-hook-suppression-env' +import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' import { resolveCliCommand } from '../codex-cli/command' import { wslAwareSpawn } from '../git/runner' +import { AGENT_PANE_HOOK_ENV_KEYS } from '../ipc/pty/host-env/spawn-env-keys' import { spawnSupervisedAgent } from './source-control-supervised-agent-spawn' import type { SourceControlAgentSpawnInput, @@ -22,6 +25,11 @@ const WSL_LAUNCHER_ENV_KEYS = [ 'WINDIR' ] as const +const BACKGROUND_HOOK_ENV_KEYS = new Set([ + ...AGENT_PANE_HOOK_ENV_KEYS, + ORCA_AGENT_HOOKS_DISABLED_ENV +]) + function buildWslLauncherEnv(explicitEnv: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv { const env: NodeJS.ProcessEnv = {} for (const key of WSL_LAUNCHER_ENV_KEYS) { @@ -42,23 +50,36 @@ export const spawnSourceControlAgent: SpawnSourceControlAgent = (input) => { const wslDistro = input.preparation ? wslDistroForCommand(input.cwd, input.wslDistro) : input.wslDistro - const spawnEnv = input.env ?? process.env + // Background agents cannot report hooks against the terminal that launched Orca. + const spawnEnv = { ...(input.env ?? process.env) } + for (const key of Object.keys(spawnEnv)) { + if (BACKGROUND_HOOK_ENV_KEYS.has(process.platform === 'win32' ? key.toUpperCase() : key)) { + delete spawnEnv[key] + } + } + spawnEnv[ORCA_AGENT_HOOKS_DISABLED_ENV] = '1' if (process.platform === 'win32' && wslDistro) { // Apply command assignments after guest login-shell setup, never to the Windows launcher. - const assignments = Object.entries(input.commandEnv ?? {}).map( - ([key, value]) => `${key}=${value}` - ) + const assignments = Object.entries(input.commandEnv ?? {}) + .filter(([key]) => !BACKGROUND_HOOK_ENV_KEYS.has(key)) + .map(([key, value]) => `${key}=${value}`) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: WSL spawn pipes both output streams and supplies the configured stdin stream. return wslAwareSpawn( assignments.length ? '/usr/bin/env' : input.binary, assignments.length ? [...assignments, input.binary, ...input.args] : input.args, { cwd: input.cwd, - env: buildWslLauncherEnv(input.env), + env: buildWslLauncherEnv(spawnEnv), stdio: [input.stdinMode, 'pipe', 'pipe'], windowsHide: true, wslDistro, useWslLoginShell: true, + // Profiles may restore pane identity; clear it in the guest before invoking the agent. + wslShellCommand: [ + `command unset ${AGENT_PANE_HOOK_ENV_KEYS.join(' ')}`, + `command export ${ORCA_AGENT_HOOKS_DISABLED_ENV}=1`, + quotePosixShell(assignments.length ? '/usr/bin/env' : input.binary) + ].join(' && '), ...(input.preparation ? { preparation: input.preparation } : {}) } ) as SpawnedSourceControlAgentProcess diff --git a/src/main/text-generation/source-control-wsl-launch.test.ts b/src/main/text-generation/source-control-wsl-launch.test.ts index 176e34b4fe1..434ec7df29e 100644 --- a/src/main/text-generation/source-control-wsl-launch.test.ts +++ b/src/main/text-generation/source-control-wsl-launch.test.ts @@ -11,7 +11,7 @@ import { prepareWslPrompt } from './source-control-prompt-files' import { producePromptRecords } from './source-control-prompt-producer' import { planCommitMessageGeneration } from '../../shared/source-control/ai/generation/commit-message-plan' import { withPlatform } from './commit-message-text-generation-test-harness' -import './source-control-agent-launch' +import { spawnSourceControlAgent } from './source-control-agent-launch' import './source-control-local-generation' import { resolveCommand } from '../git/command-runner/wsl-command-resolution' @@ -42,6 +42,86 @@ function planned(agentId: 'omp' | 'codex' = 'omp') { return result.plan } +it.skipIf(process.platform === 'win32')( + 'clears profile-restored hook identity after login while preserving shell function commands', + async () => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), 'orca-wsl-hook-isolation-'))) + const profile = join(directory, 'rc') + const shell = join(directory, 'bash') + const reader = join(directory, 'reader.cjs') + writeFileSync( + shell, + `#!/bin/sh\nexec /bin/bash --noprofile --rcfile ${quotePosixShell(profile)} -ic "$2"\n`, + { mode: 0o700 } + ) + writeFileSync( + join(directory, 'getent'), + `#!/bin/sh\nprintf '%s\\n' ${quotePosixShell(`user:x:1:1:User:${directory}:${shell}`)}\n`, + { mode: 0o700 } + ) + writeFileSync( + profile, + `export ORCA_PANE_KEY=profile-pane ORCA_AGENT_PANE=profile-pane ORCA_AGENT_HOOK_PORT=54321 ORCA_AGENT_HOOKS_DISABLED=0 +export CODEX_HOME=profile-managed-home +review_agent() { ${quotePosixShell(process.execPath)} ${quotePosixShell(reader)} "$@"; } +` + ) + writeFileSync( + reader, + `console.log(JSON.stringify({ + pane: process.env.ORCA_PANE_KEY ?? null, + alias: process.env.ORCA_AGENT_PANE ?? null, + port: process.env.ORCA_AGENT_HOOK_PORT ?? null, + disabled: process.env.ORCA_AGENT_HOOKS_DISABLED, + home: process.env.CODEX_HOME, + args: process.argv.slice(2) +})) +` + ) + // Run the real guest login command locally; only replace the Windows executable boundary. + spawnMock.mockImplementationOnce((_program, args, options) => + nativeSpawn('/bin/sh', ['-c', args.at(-1)], options) + ) + try { + const child = withPlatform('win32', () => + spawnSourceControlAgent({ + binary: 'review_agent', + args: ['literal $HOME'], + wslDistro: 'Review', + env: { + ...process.env, + HOME: directory, + SHELL: shell, + PATH: `${directory}:${process.env.PATH}` + }, + stdinMode: 'pipe', + useCwdForNative: true + }) + ) + let stdout = '' + let stderr = '' + child.stdout?.on('data', (chunk) => (stdout += chunk)) + child.stderr?.on('data', (chunk) => (stderr += chunk)) + const closed = new Promise((resolve, reject) => { + child.on('error', reject) + child.on('close', resolve) + }) + child.stdin?.end() + expect(await closed, stderr).toBe(0) + expect(JSON.parse(stdout)).toEqual({ + pane: null, + alias: null, + port: null, + disabled: '1', + home: 'profile-managed-home', + args: ['literal $HOME'] + }) + } finally { + await rm(directory, { recursive: true, force: true }) + } + } +) + it.each([false, true])( 'prepares before hostile profiles and preserves login invocation/cwd/env (assigned=%s)', async (assigned) => { diff --git a/src/main/window/attach-main-window-services.test.ts b/src/main/window/attach-main-window-services.test.ts index ceb616646f8..4587cba9df4 100644 --- a/src/main/window/attach-main-window-services.test.ts +++ b/src/main/window/attach-main-window-services.test.ts @@ -135,7 +135,7 @@ vi.mock('../ipc/worktrees/creation/worktree-base-directory-watcher', () => ({ scheduleWorktreeBaseDirectoryWatcherSync: scheduleWorktreeBaseDirectoryWatcherSyncMock })) -vi.mock('../browser/browser-manager', () => ({ +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ browserManager: { unregisterAll: browserManagerUnregisterAllMock } diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 3f7993d0a97..079f4856459 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -20,11 +20,11 @@ import type { } from '../ipc/pty/host-env/types' import { registerDaemonManagementHandlers } from '../ipc/pty/pty-management' import { registerSshHandlers } from '../ipc/ssh/ssh' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { hasSystemMediaAccess, requestSystemMediaAccess -} from '../browser/site-settings/browser-media-access' +} from '../browser/site-settings/permissions/browser-media-access' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RuntimeWorktreeLifecycleEvent } from '../runtime/workspaces/lifecycle/worktree-lifecycle-event' import type { diff --git a/src/main/window/clipboard-ipc-handlers.ts b/src/main/window/clipboard-ipc-handlers.ts index ba7de6c7750..305568c8828 100644 --- a/src/main/window/clipboard-ipc-handlers.ts +++ b/src/main/window/clipboard-ipc-handlers.ts @@ -1,11 +1,4 @@ -import { - app, - clipboard, - ipcMain, - nativeImage, - type IpcMainInvokeEvent, - type WebContents -} from 'electron' +import { app, clipboard, ipcMain, nativeImage } from 'electron' import { randomUUID } from 'node:crypto' import { open, stat } from 'node:fs/promises' import { runProcess } from '@orca/process-host' @@ -13,12 +6,16 @@ import type { Store } from '../persistence/loading-store/store' import { PATH_ACCESS_DENIED_MESSAGE } from '../ipc/filesystem/access/filesystem-auth' import { resolveDesktopAuthorizedPath } from '../ipc/filesystem/access/local-file-access-resolution' import { isENOENT } from '../ipc/filesystem/access/filesystem-path-containment' -import { isTrustedMainRendererSender } from '../ipc/main-renderer-sender-trust' +import { + assertTrustedClipboardSender, + assertTrustedClipboardTextSender +} from './clipboard-ipc-sender-trust' import { assertClipboardTextWriteWithinLimitWithYield, assertClipboardTextWithinLimitWithYield, type ReadClipboardTextOptions } from '../../shared/clipboard-text' +import { clipboardHtmlMayHaveLinks } from '../../shared/clipboard-link-html' import { saveClipboardImageBufferAsTempFile, type SaveClipboardImageAsTempFileArgs @@ -52,13 +49,12 @@ import { publishClipboardOperation, publishClipboardText } from './clipboard-text-publisher' -import { isDashboardPopoutRenderer } from './dashboard-popout-window' import { restoreNativeChatPastes } from './native-chat-paste-files' import { savePastedTextAsFile, type SavePastedTextAsFileArgs } from './native-chat-pasted-text-file' import { agentSessionPastedImageName } from '../../shared/agent-session/agent-session-attachments' import type { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' -let trustedClipboardRendererWebContentsId: number | null = null +export { setTrustedClipboardRendererWebContentsId } from './clipboard-ipc-sender-trust' type ClipboardWriteFileRequest = { filePath: string @@ -105,16 +101,13 @@ async function saveClipboardImageBufferForTarget( return saveClipboardImageBufferAsTempFile(buffer, args) } -export function setTrustedClipboardRendererWebContentsId(webContentsId: number | null): void { - trustedClipboardRendererWebContentsId = webContentsId -} - export function registerClipboardHandlers( store: Store, handlerOptions: ClipboardHandlerOptions = {} ): void { ipcMain.removeHandler('clipboard:readText') ipcMain.removeHandler('clipboard:readSelectionText') + ipcMain.removeHandler('clipboard:readLinkHtml') ipcMain.removeHandler('clipboard:writeText') ipcMain.removeHandler('clipboard:writeTerminalText') ipcMain.removeHandler('clipboard:writeSelectionText') @@ -134,6 +127,12 @@ export function registerClipboardHandlers( assertTrustedClipboardTextSender(event) return assertClipboardTextWithinLimitWithYield(clipboard.readText(), options) }) + // Rich-text copies keep their links only in the HTML flavor; skip shipping HTML that has none. + ipcMain.handle('clipboard:readLinkHtml', (event): string => { + assertTrustedClipboardSender(event) + const html = clipboard.readHTML() + return clipboardHtmlMayHaveLinks(html) ? html : '' + }) ipcMain.handle( 'clipboard:readSelectionText', async (event, options?: ReadClipboardTextOptions) => { @@ -293,20 +292,3 @@ function normalizeClipboardWriteFileRequest(args: unknown): ClipboardWriteFileRe } return { filePath } } - -function assertTrustedClipboardSender(event: IpcMainInvokeEvent): void { - if (!isTrustedClipboardRenderer(event.sender)) { - throw new Error('Unauthorized clipboard IPC sender') - } -} - -function assertTrustedClipboardTextSender(event: IpcMainInvokeEvent): void { - // Dashboard popouts need text clipboard authority only; never extend it to images, files or remote operations. - if (!isTrustedClipboardRenderer(event.sender) && !isDashboardPopoutRenderer(event.sender)) { - throw new Error('Unauthorized clipboard IPC sender') - } -} - -function isTrustedClipboardRenderer(sender: WebContents): boolean { - return isTrustedMainRendererSender(sender, trustedClipboardRendererWebContentsId) -} diff --git a/src/main/window/clipboard-ipc-sender-trust.ts b/src/main/window/clipboard-ipc-sender-trust.ts new file mode 100644 index 00000000000..8961d5147de --- /dev/null +++ b/src/main/window/clipboard-ipc-sender-trust.ts @@ -0,0 +1,26 @@ +import type { IpcMainInvokeEvent, WebContents } from 'electron' +import { isTrustedMainRendererSender } from '../ipc/main-renderer-sender-trust' +import { isDashboardPopoutRenderer } from './dashboard-popout-window' + +let trustedClipboardRendererWebContentsId: number | null = null + +export function setTrustedClipboardRendererWebContentsId(webContentsId: number | null): void { + trustedClipboardRendererWebContentsId = webContentsId +} + +export function assertTrustedClipboardSender(event: IpcMainInvokeEvent): void { + if (!isTrustedClipboardRenderer(event.sender)) { + throw new Error('Unauthorized clipboard IPC sender') + } +} + +export function assertTrustedClipboardTextSender(event: IpcMainInvokeEvent): void { + // Dashboard popouts need text clipboard authority only; never extend it to images, files or remote operations. + if (!isTrustedClipboardRenderer(event.sender) && !isDashboardPopoutRenderer(event.sender)) { + throw new Error('Unauthorized clipboard IPC sender') + } +} + +function isTrustedClipboardRenderer(sender: WebContents): boolean { + return isTrustedMainRendererSender(sender, trustedClipboardRendererWebContentsId) +} diff --git a/src/main/window/createMainWindow-close-confirmation.test.ts b/src/main/window/createMainWindow-close-confirmation.test.ts index 37ad359fc82..648e8612ab4 100644 --- a/src/main/window/createMainWindow-close-confirmation.test.ts +++ b/src/main/window/createMainWindow-close-confirmation.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) vi.mock('../browser/routing/sessions/browser-route-session-runtime', async () => { diff --git a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts b/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts index ac621b9597c..591077f57f6 100644 --- a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts +++ b/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { diff --git a/src/main/window/createMainWindow-markdown-editor-focus.test.ts b/src/main/window/createMainWindow-markdown-editor-focus.test.ts index c4581123424..266da4c502e 100644 --- a/src/main/window/createMainWindow-markdown-editor-focus.test.ts +++ b/src/main/window/createMainWindow-markdown-editor-focus.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) diff --git a/src/main/window/createMainWindow-recovery-reload-watchdog.test.ts b/src/main/window/createMainWindow-recovery-reload-watchdog.test.ts index ce24dd3f410..0a6eba6f099 100644 --- a/src/main/window/createMainWindow-recovery-reload-watchdog.test.ts +++ b/src/main/window/createMainWindow-recovery-reload-watchdog.test.ts @@ -18,7 +18,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { diff --git a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts b/src/main/window/createMainWindow-renderer-crash-recovery.test.ts index 6e09b682c79..f7af4315088 100644 --- a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts +++ b/src/main/window/createMainWindow-renderer-crash-recovery.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', async () => { diff --git a/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts b/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts index 2a66a6ee6d6..9472153d322 100644 --- a/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts +++ b/src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) diff --git a/src/main/window/createMainWindow-user-quit-close.test.ts b/src/main/window/createMainWindow-user-quit-close.test.ts index 71f7272ee49..aae0a67723d 100644 --- a/src/main/window/createMainWindow-user-quit-close.test.ts +++ b/src/main/window/createMainWindow-user-quit-close.test.ts @@ -9,7 +9,7 @@ vi.mock('./macos-tahoe-release', async () => vi.mock('./desktop-integration/app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock() ) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) diff --git a/src/main/window/createMainWindow.test.ts b/src/main/window/createMainWindow.test.ts index b887df0d8d2..031f151e887 100644 --- a/src/main/window/createMainWindow.test.ts +++ b/src/main/window/createMainWindow.test.ts @@ -12,7 +12,7 @@ vi.mock('./desktop-integration/app-icon', async () => vi.mock('../browser-passwords/browser-password-guest-service', () => ({ attachBrowserPasswordGuest: vi.fn() })) -vi.mock('../browser/browser-manager', async () => +vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => (await import('./createMainWindow-test-harness')).browserManagerMock() ) vi.mock('../browser/routing/sessions/browser-route-session-runtime', async () => ({ diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index d0df2162b55..fe4bd86ad28 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -2,7 +2,7 @@ import { app, BrowserWindow, nativeTheme, powerMonitor, screen } from 'electron' import { release } from 'node:os' import { join } from 'node:path' import { getAppIconPath } from './desktop-integration/app-icon' -import { browserManager } from '../browser/browser-manager' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' import { getBrowserClientHostId } from '../browser/client-hosts/lifecycle/browser-client-host-id' import { formatBrowserClientHostIdArgument } from '../../shared/browser/client-hosting/browser-client-host-id-argument' import { formatWindowMaterialArgument, resolveWindowMaterial } from '../../shared/window-material' diff --git a/src/main/window/main-window-webview-security.ts b/src/main/window/main-window-webview-security.ts index 7d3ca780af4..f598a5dedc1 100644 --- a/src/main/window/main-window-webview-security.ts +++ b/src/main/window/main-window-webview-security.ts @@ -2,8 +2,8 @@ import type { BrowserWindow } from 'electron' import { join } from 'node:path' import { ORCA_BROWSER_GUEST_WEB_PREFERENCES } from '../../shared/browser-guest-web-preferences' import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' -import { browserManager } from '../browser/browser-manager' -import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' +import { browserManager } from '../browser/guest-lifecycle/manager/browser-manager' +import { browserSessionRegistry } from '../browser/sessions/profiles/browser-session-registry' import { enforceLocalSshWebRtcPolicyForGuest, isLocalSshBrowserPartition diff --git a/src/main/window/updater-package-recovery-ipc.test.ts b/src/main/window/updater-package-recovery-ipc.test.ts index 52ae7cb43e7..60c1ab212c9 100644 --- a/src/main/window/updater-package-recovery-ipc.test.ts +++ b/src/main/window/updater-package-recovery-ipc.test.ts @@ -41,7 +41,9 @@ vi.mock('../ipc/pty/register-handlers', () => ({ registerPtyHandlers: vi.fn() }) vi.mock('../memory/hydrate-local-pty-registry', () => ({ hydrateLocalPtyRegistryAtBoot: vi.fn() })) -vi.mock('../browser/browser-manager', () => ({ browserManager: { unregisterAll: vi.fn() } })) +vi.mock('../browser/guest-lifecycle/manager/browser-manager', () => ({ + browserManager: { unregisterAll: vi.fn() } +})) vi.mock('../macos-permissions/macos-tcc-prompt-notice', () => ({ acknowledgePendingTccPromptNotice: vi.fn(), consumePendingTccPromptNotice: vi.fn(), diff --git a/src/main/workspaces/catalog/provisioned-root-ssh-adoption.ts b/src/main/workspaces/catalog/provisioned-root-ssh-adoption.ts index eb9086ebc6e..a0ef6bd2213 100644 --- a/src/main/workspaces/catalog/provisioned-root-ssh-adoption.ts +++ b/src/main/workspaces/catalog/provisioned-root-ssh-adoption.ts @@ -11,7 +11,10 @@ import { getEphemeralVmRecipeResultProjectRoot } from '../../../shared/ephemeral-vm-recipes' import { listEphemeralVmRuntimes } from '../../../shared/ephemeral-vm-runtime-store' -import type { EphemeralVmRuntimeRecord } from '../../../shared/ephemeral-vm-runtimes' +import { + hasEphemeralVmRecipeResult, + type EphemeralVmProvisionedRuntimeRecord +} from '../../../shared/ephemeral-vm-runtimes' import { provisionedRootPathsEqual } from './provisioned-root-checkout' type AdoptionArgs = AdoptProvisionedRootArgs & { @@ -58,12 +61,13 @@ function requireOwnedProvisionedRootRuntime( userDataPath: string, runtimeId: string, connectionId: string -): EphemeralVmRuntimeRecord { +): EphemeralVmProvisionedRuntimeRecord { const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId) if (!runtime) { throw new Error(`Unknown ephemeral VM runtime: ${runtimeId}`) } if ( + !hasEphemeralVmRecipeResult(runtime) || runtime.connectionMode !== 'ssh' || runtime.sshTargetId !== connectionId || runtime.recipe?.checkoutMode !== 'provisioned-root' || diff --git a/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts b/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts index 47e8fcbc805..b7ba94b948e 100644 --- a/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts +++ b/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts @@ -3,12 +3,15 @@ import type { CreateWorktreeArgs } from '../../../shared/worktree/create-types' import type { Worktree } from '../../../shared/worktree/types' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { getDefaultSettings } from '../../../shared/constants' -import { firstWorkRenameDeps } from '../../agent-hooks/first-work-rename-runtime' +import { firstWorkRenameDeps } from '../../agent-hooks/first-work/first-work-rename-runtime' import { maybeAutoRenameBranchOnFirstWork, resetFirstWorkBranchRenameState -} from '../../agent-hooks/first-work-branch-rename' -import { gitResponder, workingEvent } from '../../agent-hooks/first-work-branch-rename-test-harness' +} from '../../agent-hooks/first-work/first-work-branch-rename' +import { + gitResponder, + workingEvent +} from '../../agent-hooks/first-work/testing/first-work-branch-rename-test-harness' import { mergeWorktree } from '../../ipc/worktree-metadata-merge' export const typedLabelCreateRequests: Pick< diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts index f273f88949a..1f335efe069 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery-wsl.test.ts @@ -1,9 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdir, mkdtemp, readdir, rm } from 'node:fs/promises' +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { MARINE_CREATURES } from '../../../../shared/marine-creatures' import { createRetiredNameLookup } from '../../../../shared/worktree/retired-name-registry' +import { encodeClaudeProjectPath } from '../../../ai-vault/scanners/claude/claude-project-dir-encoding' +import { + RETIREMENT_BACKFILL_RETRY_AFTER_FAILURE_MS, + runRetirementBackfillScan +} from './worktree-retirement-backfill-scan' const { runWslTranscriptFsTaskMock, getWslHomeAsyncMock } = vi.hoisted(() => ({ runWslTranscriptFsTaskMock: vi.fn(), @@ -26,6 +31,7 @@ const { ensureRetiredWorktreeNamesBackfilled } = await import('./worktree-name-r const { WslTranscriptFsError } = await import('../../../native-chat/wsl-transcript-fs-gate') const FIRST = MARINE_CREATURES[0].toLowerCase() +const SECOND = MARINE_CREATURES[1].toLowerCase() const DISTRO_ROOT = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\orca\\workspaces' describe('retirement discovery on WSL', () => { @@ -138,6 +144,92 @@ describe('retirement discovery on WSL', () => { } }) + // A distro-root workspace folder encodes to the root prefix `-` on the Linux side. + it.each([ + ['a host bucket under the older \\\\wsl$\\ spelling', 'host', `--wsl--ubuntu-${FIRST}`], + ['a distro bucket', 'distro', `-${FIRST}`] + ])('keeps %s below a distro-root workspace folder spent', async (_case, side, bucket) => { + const homes = { + host: await mkdtemp(join(tmpdir(), 'orca-wsl-host-home-')), + distro: await mkdtemp(join(tmpdir(), 'orca-wsl-distro-home-')) + } + try { + await mkdir(join(homes[side], '.claude', 'projects', bucket), { recursive: true }) + + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['\\\\wsl.localhost\\Ubuntu'], + home: homes.host, + env: {}, + resolveWslHome: async () => homes.distro + }) + + expect(retired.names).toEqual(new Set([FIRST])) + } finally { + await rm(homes.host, { force: true, recursive: true }) + await rm(homes.distro, { force: true, recursive: true }) + } + }) + + // A refused permission stays refused on retry; a slow route may answer next time. + it.each([ + ['a permission refusal', Object.assign(new Error('EACCES'), { code: 'EACCES' }), 1], + ['a slow route', new WslTranscriptFsError('timeout', 'filesystem access is slow'), 2] + ])( + 'after %s on a long-path transcript, a later create rescans only if retrying can help', + async (_case, refusal, expectedProbes) => { + const distro = '\\\\wsl.localhost\\Ubuntu' + const longRoot = `/${'a'.repeat(229)}` + const distroDir = await mkdtemp(join(tmpdir(), 'orca-wsl-distro-')) + const hostHome = await mkdtemp(join(tmpdir(), 'orca-wsl-host-home-')) + try { + const projects = join(distroDir, 'home', 'ada', '.claude', 'projects') + await mkdir(join(distroDir, longRoot), { recursive: true }) + await mkdir(join(distroDir, 'home', 'ada', 'orca', 'workspaces'), { recursive: true }) + await mkdir(join(projects, `-home-ada-orca-workspaces-${FIRST}`), { recursive: true }) + const hashed = join( + projects, + `${encodeClaudeProjectPath(`${longRoot}/${SECOND}`).slice(0, 200)}-1x2y3z` + ) + await mkdir(hashed, { recursive: true }) + await writeFile(join(hashed, 'session.jsonl'), '{}\n') + let probes = 0 + runWslTranscriptFsTaskMock.mockImplementation( + async (options: { operation: string; path: string }) => { + if (options.path.endsWith('session.jsonl')) { + probes += 1 + throw refusal + } + const local = join(distroDir, options.path.slice(distro.length).replaceAll('\\', '/')) + return options.operation === 'readdir' + ? readdir(local, { withFileTypes: true }) + : stat(local) + } + ) + let now = 0 + vi.spyOn(performance, 'now').mockImplementation(() => now) + const store = {} + const create = () => + runRetirementBackfillScan(store, 'ns', () => + discoverRetiredWorktreeNames({ + workspaceRoots: [DISTRO_ROOT, `${distro}${longRoot}`], + home: hostHome, + env: {}, + resolveWslHome: async () => `${distro}\\home\\ada` + }) + ) + + await expect(create()).resolves.toEqual(new Set([FIRST])) + now += RETIREMENT_BACKFILL_RETRY_AFTER_FAILURE_MS + 1 + await expect(create()).resolves.toEqual(new Set([FIRST])) + + expect(probes).toBe(expectedProbes) + } finally { + await rm(distroDir, { force: true, recursive: true }) + await rm(hostHome, { force: true, recursive: true }) + } + } + ) + it('reaches distro discovery from the real backfill, not only when called directly', async () => { const distroHome = await mkdtemp(join(tmpdir(), 'orca-wsl-backfill-home-')) try { diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts new file mode 100644 index 00000000000..c05caae9750 --- /dev/null +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.test.ts @@ -0,0 +1,47 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { MARINE_CREATURES } from '../../../../shared/marine-creatures' +import { encodeClaudeProjectPath } from '../../../ai-vault/scanners/claude/claude-project-dir-encoding' +import { discoverRetiredWorktreeNames } from './worktree-retirement-discovery' + +const FIRST = MARINE_CREATURES[0].toLowerCase() + +describe('retirement discovery of Claude buckets', () => { + let home: string + + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'orca-retire-claude-')) + }) + + afterEach(async () => { + await rm(home, { force: true, recursive: true }) + }) + + // Claude Code cuts a long bucket name to `-`; only the transcript cwd names the workspace. + async function addHashedBucket(cwd: string): Promise { + const bucket = join( + home, + '.claude', + 'projects', + `${encodeClaudeProjectPath(cwd).slice(0, 200)}-1x2y3z` + ) + await mkdir(bucket, { recursive: true }) + await writeFile(join(bucket, 'session.jsonl'), `${JSON.stringify({ type: 'user', cwd })}\n`) + } + + it.each([ + ['the cut falls inside the workspace name', 195, false], + ['the workspace root alone is longer than the cut', 230, false], + // Case-insensitive volumes let the transcript spell the same root differently. + ['the transcript spells the root in another case', 230, true] + ])('keeps a long workspace path spent when %s', async (_case, rootLength, upperCaseCwd) => { + const root = `/synthetic/${'a'.repeat(rootLength - '/synthetic/'.length)}` + await addHashedBucket(`${upperCaseCwd ? root.toUpperCase() : root}/${FIRST}`) + + const retired = await discoverRetiredWorktreeNames({ workspaceRoots: [root], home, env: {} }) + + expect(retired).toEqual({ names: new Set([FIRST]), complete: true }) + }) +}) diff --git a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts index c51fe6e78ae..940318dc311 100644 --- a/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts +++ b/src/main/workspaces/removal/retirement/worktree-retirement-discovery.ts @@ -2,11 +2,19 @@ import { claudeProfileHistoryDirs } from '../../../claude-accounts/claude-profil import { homedir } from 'node:os' import { join } from 'node:path' import { isWslUncPath, parseWslUncPath } from '../../../../shared/wsl-paths' +import { relativePathInsideRoot } from '../../../../shared/cross-platform-path' import { - encodeClaudeProjectPaths, - isClaudeProjectDirInScope + claudeProjectBucketNameBelowScope, + mayBeHashedClaudeProjectBucketName } from '../../../ai-vault/scanners/claude/claude-project-dir-encoding' +import { CLAUDE_CWD_BUCKET_LAYOUT } from '../../../ai-vault/session-cwd-bucket-layouts' +import { + cachedProjectDirCwd, + cwdBucketScopePrefixes +} from '../../../ai-vault/session-scanner-scope-discovery' import { wslGatedReaddir, wslGatedStat } from '../../../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../../../native-chat/wsl-transcript-fs-error' +import { mapWithConcurrency } from '../../../../shared/map-with-concurrency' import type { RetirementScanResult } from './worktree-retirement-backfill-scan' import { normalizeRetirableGeneratedName } from './worktree-name-retirement' import { getWslHomeAsync } from '../../../wsl/discovery/distro-catalog' @@ -29,21 +37,54 @@ export function collectRetiredNamesFromLeafNames(leafNames: Iterable): S /** Strip the encoded parent before extracting leaves; trailing-dash parsing can retire a numeric workspace's parent. */ export function extractBucketLeafCandidates( bucketName: string, - encodedParents: readonly string[] + encodedParents: Iterable ): string[] { const bucket = bucketName.toLowerCase() - for (const parent of encodedParents) { - if (!parent || bucket === parent || !isClaudeProjectDirInScope(bucket, [parent])) { - continue - } - const remainder = bucket.slice(parent.length + 1) + // Every matching parent counts: a root parent (`-`) also prefixes the bucket of a longer one. + return [...encodedParents].flatMap((parent) => { + const remainder = claudeProjectBucketNameBelowScope(bucket, parent) if (!remainder) { - continue + return [] } const firstSegment = remainder.split('-')[0] return remainder === firstSegment ? [remainder] : [remainder, firstSegment] + }) +} + +// Each probe lists a bucket and reads up to 3 transcripts. Host dirs overlap; the WSL gate still runs one scan task at a time. +const HASHED_BUCKET_PROBE_CONCURRENCY = 4 + +/** A permission refusal on one transcript or bucket stays refused on retry, so it must not keep the scan open. */ +function isPersistentFileRefusal(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | null)?.code + return !(error instanceof WslTranscriptFsError) && (code === 'EACCES' || code === 'EPERM') +} + +/** A `-` bucket name has lost the workspace name; its transcript cwd still has it. */ +async function hashedBucketLeafNames( + projectDir: string, + roots: readonly string[] +): Promise<{ names: string[]; refused: boolean }> { + let refused = false + const cwd = await cachedProjectDirCwd( + projectDir, + (_issue, error) => { + refused ||= !isPersistentFileRefusal(error) + }, + 'claude' + ) + if (!cwd) { + // Unresolved like a bucket with no cwd; only a retryable refusal leaves the scan incomplete. + return { names: [], refused } + } + // Compare paths, not names: /repo/my-app and /repo/my/app share a bucket name. Fold case like the bucket match. + const folded = cwd.toLowerCase() + return { + names: roots.flatMap( + (root) => relativePathInsideRoot(root.toLowerCase(), folded)?.split('/')[0] || [] + ), + refused } - return [] } /** Share WSL scan admission/deadlines; report refusals without discarding names readable from other sources. */ @@ -95,14 +136,18 @@ function getClaudeProjectsDir(home: string, env: NodeJS.ProcessEnv): string { type ClaudeProjectsSource = { projectsDir: string - encodedParents: string[] + /** Workspace roots as this source's Claude records its cwd. */ + roots: string[] + encodedParents: ReadonlySet } -// Fold both sides for case-insensitive filesystems; missed buckets risk reissuing used paths. -function encodeParents(paths: readonly string[]): string[] { - return paths - .filter((path) => path.length > 0) - .flatMap((path) => encodeClaudeProjectPaths(path).map((encoded) => encoded.toLowerCase())) +// Session History's bucket rules (long-path cut, roots, case, both WSL spellings); missed buckets risk reissuing used paths. +function claudeProjectsSource(projectsDir: string, roots: string[]): ClaudeProjectsSource { + return { + projectsDir, + roots, + encodedParents: cwdBucketScopePrefixes(CLAUDE_CWD_BUCKET_LAYOUT, roots) + } } /** WSL agents leave buckets in the distro home; only its default location is visible, not distro CLAUDE_CONFIG_DIR. */ @@ -114,13 +159,13 @@ async function claudeProjectsSources(args: { }): Promise<{ sources: ClaudeProjectsSource[]; complete: boolean }> { const sources: ClaudeProjectsSource[] = [] let complete = true - const hostParents = encodeParents(args.workspaceRoots) - if (hostParents.length > 0) { + const hostRoots = args.workspaceRoots.filter((root) => root.length > 0) + if (hostRoots.length > 0) { for (const projectsDir of new Set([ getClaudeProjectsDir(args.home ?? homedir(), args.env ?? process.env), ...claudeProfileHistoryDirs('projects') ])) { - sources.push({ projectsDir, encodedParents: hostParents }) + sources.push(claudeProjectsSource(projectsDir, hostRoots)) } } const linuxRootsByDistro = new Map() @@ -137,10 +182,7 @@ async function claudeProjectsSources(args: { for (const [distro, linuxRoots] of linuxRootsByDistro) { const distroHome = await resolveWslHome(distro) if (distroHome) { - sources.push({ - projectsDir: join(distroHome, '.claude', 'projects'), - encodedParents: encodeParents(linuxRoots) - }) + sources.push(claudeProjectsSource(join(distroHome, '.claude', 'projects'), linuxRoots)) continue } // Unresolved distro homes leave agent history unread, so discovery must remain retryable. @@ -170,8 +212,21 @@ export async function discoverRetiredWorktreeNames(args: { for (const source of bucketSources.sources) { const listing = await readDirectoryNames(source.projectsDir) refused ||= listing.refused + const hashedDirs: string[] = [] for (const bucket of listing.names) { - leafNames.push(...extractBucketLeafCandidates(bucket, source.encodedParents)) + const candidates = extractBucketLeafCandidates(bucket, source.encodedParents) + leafNames.push(...candidates) + // An in-scope hashed bucket always leaves a remainder (its hash), so it has candidates. + if (candidates.length > 0 && mayBeHashedClaudeProjectBucketName(bucket)) { + hashedDirs.push(join(source.projectsDir, bucket)) + } + } + const probes = await mapWithConcurrency(hashedDirs, HASHED_BUCKET_PROBE_CONCURRENCY, (dir) => + hashedBucketLeafNames(dir, source.roots) + ) + for (const probe of probes) { + leafNames.push(...probe.names) + refused ||= probe.refused } } diff --git a/src/main/zcode/hook-config-json.ts b/src/main/zcode/hook-config-json.ts index 1edc0ca679f..28db782e71b 100644 --- a/src/main/zcode/hook-config-json.ts +++ b/src/main/zcode/hook-config-json.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { isZCodeHooksEnabled, readZCodeEventMap, type ZCodeConfig } from './hook-settings' export type ZCodeConfigSource = { diff --git a/src/main/zcode/hook-service.ts b/src/main/zcode/hook-service.ts index 9a18cd37078..39539fa788b 100644 --- a/src/main/zcode/hook-service.ts +++ b/src/main/zcode/hook-service.ts @@ -1,22 +1,18 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { - readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyZCodeManagedHooks, getZCodeConfigPath, diff --git a/src/main/zcode/hook-settings.ts b/src/main/zcode/hook-settings.ts index 01937f65811..63f219de024 100644 --- a/src/main/zcode/hook-settings.ts +++ b/src/main/zcode/hook-settings.ts @@ -2,15 +2,17 @@ import { homedir } from 'node:os' import { join } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - hookDefinitionHasManagedCommand, - isPlainObject, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + hookDefinitionHasManagedCommand, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const ZCODE_SCRIPT_BASE = 'zcode-hook' diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 4a644a11d6f..0b83d3f7157 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -2,7 +2,10 @@ import type { OrcaHooks } from '../../shared/orca-yaml-hook-types' import type { PublicKnownRuntimeEnvironment } from '../../shared/remote-runtime/host-catalog/runtime-environments' import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-recipes' import type { EphemeralVmRecipeResultWarning } from '../../shared/ephemeral-vm-recipe-diagnostics' -import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' +import type { + EphemeralVmProvisionedRuntimeRecord, + EphemeralVmRuntimeRecord +} from '../../shared/ephemeral-vm-runtimes' import type { EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' export type EphemeralVmApi = { @@ -38,7 +41,7 @@ export type EphemeralVmApi = { | { ok: true connectionType: 'orca-server' - runtime: EphemeralVmRuntimeRecord + runtime: EphemeralVmProvisionedRuntimeRecord environment: PublicKnownRuntimeEnvironment stderr: string warnings: EphemeralVmRecipeResultWarning[] @@ -46,7 +49,7 @@ export type EphemeralVmApi = { | { ok: true connectionType: 'ssh' - runtime: EphemeralVmRuntimeRecord + runtime: EphemeralVmProvisionedRuntimeRecord sshTargetId: string /** The managed Orca server the host runs; its workspace lives there. */ environmentId?: string @@ -68,6 +71,8 @@ export type EphemeralVmApi = { resumeWorkspace: (args: { workspaceId: string }) => Promise cleanup: (args: { runtimeId: string }) => Promise stopCleanup: (args: { runtimeId: string }) => Promise + /** Drops an interrupted write-ahead record that never received a recipe result. */ + forgetRuntime: (args: { runtimeId: string }) => Promise getCleanupCommand: (args: { runtimeId: string }) => Promise<{ runtimeId: string command: string | null diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index 351701276ab..ee9748e499d 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -20,5 +20,6 @@ export const ephemeralVmApi = { resumeWorkspace: (args) => ipcRenderer.invoke('ephemeralVm:resumeWorkspace', args), cleanup: (args) => ipcRenderer.invoke('ephemeralVm:cleanup', args), stopCleanup: (args) => ipcRenderer.invoke('ephemeralVm:stopCleanup', args), + forgetRuntime: (args) => ipcRenderer.invoke('ephemeralVm:forgetRuntime', args), getCleanupCommand: (args) => ipcRenderer.invoke('ephemeralVm:getCleanupCommand', args) } satisfies PreloadApi['ephemeralVm'] diff --git a/src/preload/api/pty-api.ts b/src/preload/api/pty-api.ts index e7fef744f4e..68e22c51ffc 100644 --- a/src/preload/api/pty-api.ts +++ b/src/preload/api/pty-api.ts @@ -115,6 +115,8 @@ export type PtyApi = { shellReadyArmed?: boolean }> write: (id: string, data: string, inputKind: TerminalInputKind) => void + /** Genuine xterm input admitted by a local or remote transport; carries no terminal bytes. */ + noteUserInput?: () => void /** `requireWriteSettlement` waits for the provider's acknowledgment on any provider. */ writeAccepted: ( id: string, diff --git a/src/preload/api/pty-bridge-session-control.ts b/src/preload/api/pty-bridge-session-control.ts index 6be75eff418..b57e1593f61 100644 --- a/src/preload/api/pty-bridge-session-control.ts +++ b/src/preload/api/pty-bridge-session-control.ts @@ -101,6 +101,7 @@ export const ptySessionControlApi = { write: (id: string, data: string, inputKind: TerminalInputKind): void => { ipcRenderer.send('pty:write', { id, data, inputKind }) }, + noteUserInput: (): void => ipcRenderer.send('pty:noteUserInput'), writeAccepted: ( id: string, data: string, diff --git a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts index ed9e8eb9b0a..1aa0df2b6ab 100644 --- a/src/preload/api/ui-bridge-clipboard-and-window-controls.ts +++ b/src/preload/api/ui-bridge-clipboard-and-window-controls.ts @@ -106,6 +106,7 @@ export const uiClipboardAndWindowControlsApi = { }, readClipboardText: (options?: ReadClipboardTextOptions): Promise => ipcRenderer.invoke('clipboard:readText', options), + readClipboardLinkHtml: (): Promise => ipcRenderer.invoke('clipboard:readLinkHtml'), readSelectionClipboardText: (options?: ReadClipboardTextOptions): Promise => ipcRenderer.invoke('clipboard:readSelectionText', options), saveClipboardImageAsTempFile: (args?: { diff --git a/src/preload/api/ui-window-api.ts b/src/preload/api/ui-window-api.ts index 401c835b0bb..e97ee1730e6 100644 --- a/src/preload/api/ui-window-api.ts +++ b/src/preload/api/ui-window-api.ts @@ -8,6 +8,8 @@ import type { export type UiWindowApi = { readClipboardText: (options?: ReadClipboardTextOptions) => Promise + /** The clipboard's HTML when it may carry links; empty otherwise. */ + readClipboardLinkHtml: () => Promise readSelectionClipboardText: (options?: ReadClipboardTextOptions) => Promise saveClipboardImageAsTempFile: (args?: { connectionId?: string | null diff --git a/src/renderer/src/components/activity/activity-event-build-cache.ts b/src/renderer/src/components/activity/activity-event-build-cache.ts index 8dfe2f9f6dd..9193f3b4ade 100644 --- a/src/renderer/src/components/activity/activity-event-build-cache.ts +++ b/src/renderer/src/components/activity/activity-event-build-cache.ts @@ -110,7 +110,8 @@ export function resolvePaneBuild( repo: request.repo, entry: rowEntry, tab: request.tab, - agentType: request.agentType + agentType: request.agentType, + migrationUnsupportedPtyId: request.migrationUnsupportedPtyId } cache?.panes.set(request.cacheKey, { diff --git a/src/renderer/src/components/activity/activity-search-query.test.tsx b/src/renderer/src/components/activity/activity-search-query.test.tsx index c03d0be3d8b..25df53dc89c 100644 --- a/src/renderer/src/components/activity/activity-search-query.test.tsx +++ b/src/renderer/src/components/activity/activity-search-query.test.tsx @@ -68,16 +68,75 @@ function options(query: string): Parameters[0] { } describe('Activity search query in the real hook', () => { - it('excludes acknowledged rows from an unread search', () => { + it('keeps live rows but excludes acknowledged finished rows from an unread search', () => { const panes = installThreads(12) + const entries = useAppStore.getState().agentStatusByPaneKey useAppStore.setState({ + agentStatusByPaneKey: Object.fromEntries( + panes.map((paneKey, index) => [ + paneKey, + index === 0 ? entries[paneKey] : { ...entries[paneKey], state: 'done' as const } + ]) + ), acknowledgedAgentsByPaneKey: Object.fromEntries(panes.map((paneKey) => [paneKey, 100_000])) }) const activity = renderHook(() => useAgentPaneThreads({ ...options(' PROJECT ☃ '), readFilter: 'unread' }) ) expect(activity.result.current.allThreads).toHaveLength(12) - expect(activity.result.current.visibleThreads).toEqual([]) + expect(activity.result.current.visibleThreads.map((thread) => thread.paneKey)).toEqual([ + panes[0] + ]) + }) + + it('hides acknowledged unavailable rows unless selected in the unread filter', () => { + const [livePane, unavailablePane] = installThreads(2) + const entries = useAppStore.getState().agentStatusByPaneKey + useAppStore.setState({ + agentStatusByPaneKey: { [livePane]: entries[livePane] }, + migrationUnsupportedByPtyId: { + 'pty-tab-1': { + ptyId: 'pty-tab-1', + paneKey: unavailablePane, + reason: 'legacy-numeric-pane-key', + source: 'local', + updatedAt: 99_000 + } + }, + acknowledgedAgentsByPaneKey: { [livePane]: 100_000, [unavailablePane]: 100_000 } + }) + const activity = renderHook, string | null>( + (selectedPaneKey: string | null) => + useAgentPaneThreads({ ...options(''), readFilter: 'unread', selectedPaneKey }), + { initialProps: null } + ) + expect(activity.result.current.visibleThreads.map((thread) => thread.paneKey)).toEqual([ + 'tab-0:11111111-1111-4111-8111-111111111111' + ]) + activity.rerender(unavailablePane) + expect( + activity.result.current.visibleThreads.map((thread) => thread.paneKey).toSorted() + ).toEqual([ + 'tab-0:11111111-1111-4111-8111-111111111111', + 'tab-1:11111111-1111-4111-8111-111111111111' + ]) + act(() => useAppStore.setState({ activityClearedAtByPaneKey: { [unavailablePane]: 99_000 } })) + activity.rerender(null) + expect(activity.result.current.visibleThreads.map((thread) => thread.paneKey)).toEqual([ + 'tab-0:11111111-1111-4111-8111-111111111111' + ]) + act(() => + useAppStore.setState({ + activityClearedAtByPaneKey: {}, + acknowledgedAgentsByPaneKey: { [livePane]: 100_000 } + }) + ) + expect( + activity.result.current.visibleThreads.map((thread) => thread.paneKey).toSorted() + ).toEqual([ + 'tab-0:11111111-1111-4111-8111-111111111111', + 'tab-1:11111111-1111-4111-8111-111111111111' + ]) }) it('keeps selection, child classification and scoped row order', () => { diff --git a/src/renderer/src/components/activity/activity-thread-builder.ts b/src/renderer/src/components/activity/activity-thread-builder.ts index 6ebf0d702d8..473820dac4d 100644 --- a/src/renderer/src/components/activity/activity-thread-builder.ts +++ b/src/renderer/src/components/activity/activity-thread-builder.ts @@ -130,6 +130,7 @@ export function buildAgentPaneThreads( latestTimestamp: liveAgent.timestamp, latestEvent: null, events: [], + migrationUnsupportedPtyId: liveAgent.migrationUnsupportedPtyId, unread: false }) continue @@ -142,6 +143,7 @@ export function buildAgentPaneThreads( existing.agentType = liveAgent.agentType existing.currentAgentState = liveAgent.state existing.currentAgentEntry = liveAgent.entry + existing.migrationUnsupportedPtyId ??= liveAgent.migrationUnsupportedPtyId existing.responsePreview = statusPreviewForEntry( liveAgent.entry, liveAgent.entry.state, diff --git a/src/renderer/src/components/activity/activity-thread-types.ts b/src/renderer/src/components/activity/activity-thread-types.ts index b6ba66cdb29..f336ad375b0 100644 --- a/src/renderer/src/components/activity/activity-thread-types.ts +++ b/src/renderer/src/components/activity/activity-thread-types.ts @@ -40,6 +40,7 @@ export type ActivityLiveAgentSnapshot = { entry: AgentStatusEntry tab: TerminalTab agentType: AgentType + migrationUnsupportedPtyId?: string } // Why: keyed per agent pane (tab + leaf id), not per workspace, so the list shows one row per agent; paneKey is `${tabId}:${leafId}`. diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index e32bb3c9ec2..66406c57320 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -221,10 +221,11 @@ export function useAgentPaneThreads(args: { const matchesSearchQuery = normalizedQuery === null ? null : createActivityThreadSearchMatcher(normalizedQuery) return scopeVisibleThreads.filter((thread) => { - // Why: keep the just-selected thread visible after auto-mark-read flips it to read, else unread-only mode makes the clicked row vanish from the list. + // Keep live agents and the selected row visible after marking read; migration blocks are unavailable. if ( readFilter === 'unread' && !thread.unread && + (thread.currentAgentState === null || thread.migrationUnsupportedPtyId !== undefined) && thread.paneKey !== effectiveSelectedPaneKey ) { return false diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index aec35bb04c9..7e420a90701 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -4,9 +4,11 @@ import type { AgentLaunchSetupPanelProps } from './AgentLaunchSetupButton' import { agentLaunchSetupOptionRows, agentLaunchSetupRowGroups, - agentLaunchSetupCatalogState as catalogOf + agentLaunchSetupCatalogState as catalogOf, + agentLaunchSetupModelRows } from './agent-launch-setup-option-rows' import { useRef, useState } from 'react' +import { useSetupModelHighlight } from './use-setup-model-highlight' import { Check, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react' import { getAgentSessionOptionLaunchCatalog } from '../../../../shared/agent-session/options/agent-session-option-catalog' import { @@ -89,6 +91,15 @@ export function AgentLaunchSetupPanel({ const { hasModels, catalogPending, catalogMessage } = catalogOf(entry, models, currentModel, mode) const modelInArguments = textActionArgumentsOwnModel(entry, draft) const modelDisabled = disabled || defaultsPending || catalogPending + const modelRows = agentLaunchSetupModelRows( + models, + currentModel, + modelQuery, + legacy, + modelInArguments + ) + const modelList = useRef(null) + const highlight = useSetupModelHighlight(modelList, modelRows.start, modelQuery) const options = agentPickerEntryOptions(entry, currentModel, draft.surface) const optionRows = agentLaunchSetupOptionRows({ options, @@ -164,6 +175,7 @@ export function AgentLaunchSetupPanel({ } }} onKeyDown={(event) => { + highlight.endKey() event.stopPropagation() if ( !disabled && @@ -179,6 +191,8 @@ export function AgentLaunchSetupPanel({ { if ( !disabled && @@ -194,6 +208,7 @@ export function AgentLaunchSetupPanel({ } }} onKeyDown={(event) => { + highlight.onKeyDown(event) if (event.key === 'Enter') { event.stopPropagation() } @@ -238,29 +253,28 @@ export function AgentLaunchSetupPanel({ {t('agentPicker.legacyModels', 'Legacy models')} ) : null} - {models - .filter( - (model) => - !model.hidden && - (model.id === currentModel || modelQuery || Boolean(model.isLegacy) === legacy) - ) - .map((model) => ( + {modelRows.rows.map((model) => { + const current = model.unlisted || (currentModel === model.id && !modelInArguments) + return ( editDraft({ kind: 'choice', patch: { model: model.id } })} + data-current={current} + onSelect={() => { + if (!model.unlisted) { + editDraft({ kind: 'choice', patch: { model: model.id } }) + } + }} > {model.label} - {currentModel === model.id && !modelInArguments ? ( - - ) : null} + {current ? : null} - ))} + ) + })} {!legacy && !modelQuery && legacyCount > 0 ? ( setLegacy(true)}> @@ -274,17 +288,6 @@ export function AgentLaunchSetupPanel({ ) : null} - {currentModel && !models.some((model) => model.id === currentModel) ? ( - {}} - data-current="true" - > - {currentModel} - - - ) : null} diff --git a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts index 7a9e07ca2d1..ba9b27772d4 100644 --- a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts +++ b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts @@ -11,7 +11,8 @@ import type { } from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' import type { AgentPickerEntry, - AgentPickerDraft + AgentPickerDraft, + AgentPickerModel } from '../../../../shared/agent-launch/picker/agent-launch-picker' import type { agentPickerPanelArguments } from '../../../../shared/agent-launch/picker/agent-launch-picker-arguments' @@ -242,3 +243,26 @@ export function agentLaunchSetupCatalogState( : null return { hasModels, catalogPending, catalogMessage } } + +/** Visible model rows, plus the model the list starts on. */ +export function agentLaunchSetupModelRows( + models: readonly AgentPickerModel[], + currentModel: string | undefined, + query: string, + legacy: boolean, + modelInArguments: boolean +) { + const rows: { id: string; label: string; unlisted?: true }[] = models.filter( + (model) => + !model.hidden && (model.id === currentModel || query || Boolean(model.isLegacy) === legacy) + ) + // Why one keyed list: when the catalog later lists an unlisted current model, its row keeps + // its identity, so the highlight stays on it instead of jumping to the first model. + if (currentModel && !models.some((model) => model.id === currentModel)) { + rows.push({ id: currentModel, label: currentModel, unlisted: true }) + } + // An Arguments-owned text action has no current model row, so it starts on its default as before. + const start = + !modelInArguments && rows.some((row) => row.id === currentModel) ? currentModel : undefined + return { rows, start } +} diff --git a/src/renderer/src/components/agent/use-setup-model-highlight.ts b/src/renderer/src/components/agent/use-setup-model-highlight.ts new file mode 100644 index 00000000000..bd48d53d862 --- /dev/null +++ b/src/renderer/src/components/agent/use-setup-model-highlight.ts @@ -0,0 +1,53 @@ +import { useLayoutEffect, useRef, useState, type KeyboardEvent, type RefObject } from 'react' + +const NAVIGATION_KEYS = new Set(['ArrowUp', 'ArrowDown', 'Home', 'End']) + +/** + * Starts the model list's highlight on `start`, and returns to it when a search is cleared. + * Why the navigation flag: controlled cmdk reports user moves and its own first-item picks through + * the same callback; only its own picks are undone. + */ +export function useSetupModelHighlight( + root: RefObject, + start: string | undefined, + query: string +) { + const [reassert, setReassert] = useState(false) + const navigating = useRef(false) + const value = query ? undefined : start + // Why: cmdk applies `value` only when the prop changes, so after its own pick we release it for + // one render and set it again. A start that arrives or returns is brought into view. + useLayoutEffect(() => { + if (reassert) { + setReassert(false) + } else if (value !== undefined) { + root.current + ?.querySelector(`[cmdk-item][data-value="${CSS.escape(value)}"]`) + ?.scrollIntoView({ block: 'nearest' }) + } + }, [reassert, value, root]) + return { + // The flag spans one event: set before cmdk handles it, cleared once it bubbles past the list. + command: { + value: reassert ? undefined : value, + onValueChange: (next: string) => { + if (!navigating.current && value !== undefined && next !== value) { + setReassert(true) + } + }, + onPointerMoveCapture: () => { + navigating.current = true + }, + onPointerMove: () => { + navigating.current = false + } + }, + onKeyDown: (event: KeyboardEvent) => { + navigating.current = + NAVIGATION_KEYS.has(event.key) || (event.ctrlKey && 'jknp'.includes(event.key)) + }, + endKey: () => { + navigating.current = false + } + } +} diff --git a/src/renderer/src/components/browser-favicon.tsx b/src/renderer/src/components/browser-favicon.tsx index d8de2b5d647..86e1ba67c31 100644 --- a/src/renderer/src/components/browser-favicon.tsx +++ b/src/renderer/src/components/browser-favicon.tsx @@ -1,7 +1,7 @@ import { useState } from 'react' import { Globe, Loader2 } from 'lucide-react' import { cn } from '@/lib/utils' -import { displayableFaviconUrl } from './browser-pane/describe-page/browser-favicon-url' +import { displayableFaviconUrl } from '../../../shared/browser/browser-favicon-url' export function BrowserFavicon({ faviconUrl, diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.ts b/src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.ts index b783a607c7a..4ecd873eebd 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.ts +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-address-bar-suggestions.ts @@ -17,7 +17,7 @@ import { matchBrowserHistory, prepareBrowserHistoryEntries } from '@/lib/browser/history/browser-history-match' -import { displayableFaviconUrl } from '../describe-page/browser-favicon-url' +import { displayableFaviconUrl } from '../../../../../shared/browser/browser-favicon-url' import { formatBrowserPaletteUrl } from '@/lib/browser/palette/browser-palette-search' import { isClipboardTextByteLengthOverLimit } from '../../../../../shared/clipboard-text' import { translate } from '@/i18n/i18n' diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-guest-session.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-guest-session.ts index 3a6f160e543..193f26ae20b 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-guest-session.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-guest-session.ts @@ -92,12 +92,12 @@ export function createBrowserPageWebviewGuestSession({ return null } } - const ownsGuest = (webContentsId: number | null): boolean => - webContentsId !== null && + const ownsWebview = (): boolean => !guestRecovery.isDisposed() && webviewRef.current === webview && - webviewRegistry.get(browserTabId) === webview && - readWebContentsId() === webContentsId + webviewRegistry.get(browserTabId) === webview + const ownsGuest = (webContentsId: number | null): boolean => + webContentsId !== null && ownsWebview() && readWebContentsId() === webContentsId const registerGuest = (webContentsId: number | null): Promise => { if (webContentsId === null || !ownsGuest(webContentsId)) { return Promise.resolve(null) @@ -235,7 +235,8 @@ export function createBrowserPageWebviewGuestSession({ liveWebContentsId === null || registeredWebContentsIds.get(browserTabId) !== liveWebContentsId if (queuedAnnotationViewportBridgeSync) { void registerGuest(liveWebContentsId).then((registered) => { - if (!ownsGuest(liveWebContentsId)) { + // Why: an unreadable ID has no owner to fence; validation must still retry until it reads. + if (liveWebContentsId === null ? !ownsWebview() : !ownsGuest(liveWebContentsId)) { return } const completedRecovery = guestRecovery.finish() diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-navigation-handlers.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-navigation-handlers.ts index 1728de5c9ef..57893cc0f36 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-navigation-handlers.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-navigation-handlers.ts @@ -16,7 +16,7 @@ import { import { browserNavigationLeavesFaviconOrigin, pickDisplayableFaviconUrl -} from '../describe-page/browser-favicon-url' +} from '../../../../../shared/browser/browser-favicon-url' import { applyBrowserExtensionPageFavicon, isChromeExtensionPageUrl diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.test.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.test.ts new file mode 100644 index 00000000000..53fc131f313 --- /dev/null +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import type { KernelOutputType } from '../../../../../../shared/notebook-kernel-types' +import { parseIpynbOutput } from '../document/ipynb-parse' +import { applyKernelOutput, toStoredOutputs, type LiveOutputs } from './ipynb-kernel-outputs' + +const EMPTY: LiveOutputs = { outputs: [], clearOnNextOutput: false } +type Frame = [KernelOutputType, Record] + +function apply(frames: Frame[], live = EMPTY): LiveOutputs { + return frames.reduce( + (current, [type, content]) => applyKernelOutput(current, type, content), + live + ) +} + +// 2.5 MiB of stdout in 64 KiB chunks. +function flood(): LiveOutputs { + const chunk = 'x'.repeat(65536) + return apply(Array.from({ length: 40 }, (): Frame => ['stream', { name: 'stdout', text: chunk }])) +} + +describe('notebook cell output budget', () => { + it('keeps the first 2 MiB of stream text, then one notice, and drops later chunks', () => { + const live = flood() + expect(live.outputs).toHaveLength(2) + expect(live.outputs[0]).toEqual({ + output_type: 'stream', + name: 'stdout', + text: 'x'.repeat(2097152) + }) + expect(live.outputs[1]?.output_type).toBe('display_data') + expect(toStoredOutputs(live.outputs)).toEqual(live.outputs) + + const after = apply( + [ + ['stream', { name: 'stdout', text: 'more' }], + ['stream', { name: 'stderr', text: 'warn' }] + ], + live + ) + expect(after).toBe(live) + }) + + it('leaves the previous display in place when its update does not fit', () => { + const live = apply([ + [ + 'display_data', + { data: { 'text/plain': '0%' }, metadata: {}, transient: { display_id: 'p' } } + ], + [ + 'update_display_data', + { + data: { 'image/png': 'A'.repeat(16777216) }, + metadata: {}, + transient: { display_id: 'p' } + } + ] + ]) + expect(live.outputs).toHaveLength(2) + expect(live.outputs[0]?.data).toEqual({ 'text/plain': '0%' }) + expect(live.outputs[1]?.output_type).toBe('display_data') + }) + + it('keeps the first error after truncation with its summary visible live and saved', () => { + const live = applyKernelOutput(flood(), 'error', { + ename: 'ValueError', + evalue: 'Set API_TOKEN first.', + traceback: ['Traceback (most recent call last):', 'z'.repeat(33554432), 'ValueError: ...'] + }) + expect(live.outputs.map((output) => output.output_type)).toEqual([ + 'stream', + 'display_data', + 'error' + ]) + const saved = toStoredOutputs(live.outputs) + expect(saved).toEqual(live.outputs) + const parsed = parseIpynbOutput(saved[2]) + if (parsed?.kind !== 'error') { + throw new Error('Expected an error output') + } + expect(parsed.traceback.startsWith('Traceback (most recent call last):\nzzz')).toBe(true) + expect(parsed.traceback.endsWith('\nValueError: Set API_TOKEN first.')).toBe(true) + }) +}) diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.ts new file mode 100644 index 00000000000..cb4dbef1b0d --- /dev/null +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-output-budget.ts @@ -0,0 +1,165 @@ +import { translate } from '@/i18n/i18n' +import { ownRetainedString } from '../../../../../../shared/own-retained-string' +import { sliceAtCodeUnitLimit } from '../../../../../../shared/surrogate-safe-text-slice' +import { isRecord } from '../document/ipynb-parse' +import type { NotebookOutput } from './ipynb-kernel-outputs' +import { noticeOutput } from './ipynb-kernel-runs' + +// Why: a larger text block stalls the cell's rendering; rich outputs need more room for images. +const MAX_STREAM_CHARS = 2 * 1024 * 1024 +const MAX_OUTPUT_CHARS = 16 * 1024 * 1024 +const MAX_OUTPUTS = 2000 +const truncationNotices = new WeakSet() +const outputSizes = new WeakMap() + +function outputSize(output: NotebookOutput): number { + let size = outputSizes.get(output) + if (size === undefined) { + if (output.output_type === 'stream') { + const { text, ...fields } = output + size = String(text).length + JSON.stringify(fields).length + } else { + size = JSON.stringify(output).length + } + outputSizes.set(output, size) + } + return size +} + +function outputBudget(outputs: NotebookOutput[]) { + let count = 0 + let streamChars = 0 + let totalChars = 0 + const diagnostics = new Set() + for (const output of outputs) { + if (truncationNotices.has(output)) { + continue + } + const type = output.output_type + // Why: the first error and result have separate finite allowances, even after ordinary output fills. + if ((type === 'error' || type === 'execute_result') && !diagnostics.has(type)) { + diagnostics.add(type) + continue + } + count += 1 + totalChars += outputSize(output) + streamChars += type === 'stream' ? String(output.text).length : 0 + // Why: replacements can share a display ID; stop sizing as soon as admission is impossible. + if (totalChars > MAX_OUTPUT_CHARS) { + break + } + } + return { count, streamChars, totalChars } +} + +export function hasTruncationNotice(outputs: NotebookOutput[]): boolean { + return outputs.some((output) => truncationNotices.has(output)) +} + +function withTruncationNotice(outputs: NotebookOutput[]): NotebookOutput[] { + if (hasTruncationNotice(outputs)) { + return outputs + } + const notice = noticeOutput( + translate( + 'auto.components.editor.IpynbViewer.outputTruncated', + "Output truncated: Orca kept the start of this cell's output and discarded the rest. To keep all of it, write it to a file instead." + ) + ) + truncationNotices.add(notice) + return [...outputs, notice] +} + +function ownedHead(text: string, limit: number): string { + return text.length <= limit ? text : ownRetainedString(sliceAtCodeUnitLimit(text, limit)) +} + +/** Cuts only the new stream text; overflowing rich outputs are omitted whole. */ +export function fitOutputBudget( + previous: NotebookOutput[], + outputs: NotebookOutput[] +): NotebookOutput[] { + const { count, streamChars, totalChars } = outputBudget(outputs) + if (count <= MAX_OUTPUTS && streamChars <= MAX_STREAM_CHARS && totalChars <= MAX_OUTPUT_CHARS) { + return outputs + } + const last = outputs.at(-1) + let keep = 0 + if (last?.output_type === 'stream' && count <= MAX_OUTPUTS) { + const text = String(last.text) + keep = text.length - Math.max(streamChars - MAX_STREAM_CHARS, totalChars - MAX_OUTPUT_CHARS) + const shown = outputs.length === previous.length ? String(previous.at(-1)?.text).length : 0 + keep = Math.max(keep, Math.min(shown, text.length)) + } + return withTruncationNotice([ + ...outputs.slice(0, -1), + ...(last && keep > 0 ? [{ ...last, text: ownedHead(String(last.text), keep) }] : []) + ]) +} + +/** Reject an oversized replacement atomically, preserving every display with the matching ID. */ +export function fitDisplayUpdateBudget( + previous: NotebookOutput[], + outputs: NotebookOutput[] +): NotebookOutput[] { + return outputBudget(outputs).totalChars <= MAX_OUTPUT_CHARS + ? outputs + : withTruncationNotice(previous) +} + +function diagnosticText(value: unknown, limit: number): string { + if (typeof value === 'string') { + return ownedHead(value, limit) + } + if (!Array.isArray(value)) { + return '' + } + let text = '' + for (const line of value) { + if (typeof line === 'string') { + text += ownedHead((text ? '\n' : '') + line, limit - text.length) + } + if (text.length >= limit - 1) { + break + } + } + return text +} + +function diagnosticFallback(output: NotebookOutput): NotebookOutput { + if (output.output_type === 'error') { + const ename = diagnosticText(output.ename, 1024) + const evalue = diagnosticText(output.evalue, 64 * 1024) + const summary = `${ename}: ${evalue}` + // Why: the renderer displays traceback alone, so its final error summary must survive the cut. + const traceback = diagnosticText( + output.traceback, + MAX_STREAM_CHARS - ename.length - evalue.length - summary.length - 1 + ) + return { + output_type: 'error', + ename, + evalue, + traceback: traceback ? [traceback, summary] : [summary] + } + } + const data = isRecord(output.data) ? output.data : {} + const value = + data['text/plain'] ?? Object.entries(data).find(([mime]) => mime.startsWith('text/'))?.[1] + return { + output_type: 'execute_result', + execution_count: output.execution_count, + data: { 'text/plain': diagnosticText(value, MAX_STREAM_CHARS) }, + metadata: {} + } +} + +/** Keep a first error/result after the ordinary budget, with its own 16 MiB ceiling. */ +export function appendDiagnostic( + outputs: NotebookOutput[], + diagnostic: NotebookOutput +): NotebookOutput[] { + return outputSize(diagnostic) <= MAX_OUTPUT_CHARS + ? [...outputs, diagnostic] + : withTruncationNotice([...outputs, diagnosticFallback(diagnostic)]) +} diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-outputs.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-outputs.ts index 7894cf65a89..030632d6103 100644 --- a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-outputs.ts +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-outputs.ts @@ -1,5 +1,11 @@ import type { KernelOutputType } from '../../../../../../shared/notebook-kernel-types' import { isRecord } from '../document/ipynb-parse' +import { + appendDiagnostic, + fitDisplayUpdateBudget, + fitOutputBudget, + hasTruncationNotice +} from './ipynb-kernel-output-budget' /** An nbformat v4 output; while live it may also carry the kernel's `transient.display_id`. */ export type NotebookOutput = Record @@ -83,6 +89,19 @@ function toOutput(type: KernelOutputType, content: Record): Not : { output_type: 'display_data', ...bundle, transient: content.transient } } +function appendOutput( + outputs: NotebookOutput[], + type: KernelOutputType, + content: Record +): NotebookOutput[] { + const last = outputs.at(-1) + if (type === 'stream' && last?.output_type === 'stream' && last.name === content.name) { + return [...outputs.slice(0, -1), streamOutput(content, last)] + } + return [...outputs, type === 'stream' ? streamOutput(content) : toOutput(type, content)] +} + +/** Returns `live` itself when the output is dropped, so callers can skip waking store subscribers. */ export function applyKernelOutput( live: T, type: KernelOutputType, @@ -95,26 +114,37 @@ export function applyKernelOutput( } if (type === 'update_display_data') { const id = displayId(content) - return { - ...live, - outputs: live.outputs.map((output) => - id !== undefined && displayId(output) === id - ? { ...output, data: content.data ?? {}, metadata: content.metadata ?? {} } - : output - ) + if (id === undefined || !live.outputs.some((output) => displayId(output) === id)) { + return live } + const updated = live.outputs.map((output) => + displayId(output) === id + ? { ...output, data: content.data ?? {}, metadata: content.metadata ?? {} } + : output + ) + const outputs = fitDisplayUpdateBudget(live.outputs, updated) + return outputs === live.outputs ? live : { ...live, outputs } } const outputs = live.clearOnNextOutput ? [] : live.outputs - const last = outputs.at(-1) - if (type === 'stream' && last?.output_type === 'stream' && last.name === content.name) { + // Why: first diagnostics survive ordinary truncation, with a separate finite allowance. + if ( + (type === 'error' || type === 'execute_result') && + !outputs.some((output) => output.output_type === type) + ) { return { ...live, - outputs: [...outputs.slice(0, -1), streamOutput(content, last)], + outputs: appendDiagnostic(outputs, toOutput(type, content)), clearOnNextOutput: false } } - const output = type === 'stream' ? streamOutput(content) : toOutput(type, content) - return { ...live, outputs: [...outputs, output], clearOnNextOutput: false } + if (hasTruncationNotice(outputs)) { + return live + } + return { + ...live, + outputs: fitOutputBudget(outputs, appendOutput(outputs, type, content)), + clearOnNextOutput: false + } } /** Drops live-only fields so the outputs are valid nbformat. */ diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-runs.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-runs.ts index 17f77470dcd..1a882129893 100644 --- a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-runs.ts +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-runs.ts @@ -1,5 +1,10 @@ import type { NotebookOutput } from './ipynb-kernel-outputs' -import { runningCellKey, type CellRun, type NotebookKernelSession } from './ipynb-kernel-store' +import { + runningCellKey, + updateSession, + type CellRun, + type NotebookKernelSession +} from './ipynb-kernel-store' export function startRun(): CellRun { return { @@ -12,6 +17,20 @@ export function startRun(): CellRun { } } +export function markRunCommitted(filePath: string, key: string): void { + updateSession(filePath, ({ runs }) => { + const run = runs[key] + return run ? { runs: { ...runs, [key]: { ...run, outputs: [], committed: true } } } : {} + }) +} + +/** Forgets finished runs, e.g. after Clear All Outputs; the executing run keeps streaming. */ +export function forgetFinishedRuns(filePath: string): void { + updateSession(filePath, ({ runs }) => ({ + runs: Object.fromEntries(Object.entries(runs).filter(([, run]) => run.finishedAt === null)) + })) +} + export function stopRuns(session: NotebookKernelSession, extraOutputs: NotebookOutput[] = []) { const key = runningCellKey(session) const run = key === null ? null : session.runs[key] diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session.ts index a7ad4cf49e0..9aae0197c75 100644 --- a/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session.ts +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-kernel-session.ts @@ -268,20 +268,6 @@ export function cancelSetup(filePath: string): void { })) } -export function markRunCommitted(filePath: string, key: string): void { - updateSession(filePath, ({ runs }) => { - const run = runs[key] - return run ? { runs: { ...runs, [key]: { ...run, outputs: [], committed: true } } } : {} - }) -} - -/** Forgets finished runs, e.g. after Clear All Outputs; the executing run keeps streaming. */ -export function forgetFinishedRuns(filePath: string): void { - updateSession(filePath, ({ runs }) => ({ - runs: Object.fromEntries(Object.entries(runs).filter(([, run]) => run.finishedAt === null)) - })) -} - function handleFrame({ filePath, frame }: KernelFrameEvent): void { if (!isOpen(filePath)) { return @@ -312,9 +298,10 @@ function handleFrame({ filePath, frame }: KernelFrameEvent): void { pump(filePath) return } - updateSession(filePath, ({ runs }) => ({ - runs: { ...runs, [key]: applyKernelOutput(runs[key], frame.type, frame.content) } - })) + const next = applyKernelOutput(session.runs[key], frame.type, frame.content) + if (next !== session.runs[key]) { + updateSession(filePath, ({ runs }) => ({ runs: { ...runs, [key]: next } })) + } } // Subscribe lazily with the notebook viewer, which owns kernel sessions. diff --git a/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.ts b/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.ts index 73ac76fe9bb..26afc582bfe 100644 --- a/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.ts +++ b/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.ts @@ -10,12 +10,8 @@ import { withIpynbCellIds } from '../document/ipynb-cell-mutations' import { toStoredOutputs } from './ipynb-kernel-outputs' -import { - forgetFinishedRuns, - markRunCommitted, - runCells, - trustNotebook -} from './ipynb-kernel-session' +import { forgetFinishedRuns, markRunCommitted } from './ipynb-kernel-runs' +import { runCells, trustNotebook } from './ipynb-kernel-session' import { getCellRun, getSession, diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.ts index 7db20db55bd..9043114fa87 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-auto-focus.ts @@ -11,11 +11,17 @@ export function autoFocusRichEditor( if (force && !nextEditor.isDestroyed && shouldFocus()) { nextEditor.view?.dom?.focus?.({ preventScroll: true }) } + const scheduled = nextEditor.state let frameId: number | null = requestAnimationFrame(() => { frameId = null if (nextEditor.isDestroyed || !shouldFocus()) { return } + // Why: a late frame (hidden windows paint at 1Hz) must not move a caret the user already placed or typed at. + const { doc, selection } = nextEditor.state + if (nextEditor.isFocused && (doc !== scheduled.doc || !selection.eq(scheduled.selection))) { + return + } const active = document.activeElement // Only explicit opens may steal focus from unrelated inputs or dialogs. const canTakeFocus = diff --git a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-images.test.tsx b/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-images.test.tsx deleted file mode 100644 index 9481396ed28..00000000000 --- a/src/renderer/src/components/github-item-dialog/discuss-item/conversation-tab-images.test.tsx +++ /dev/null @@ -1,110 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' - -const mocks = vi.hoisted(() => ({ update: vi.fn().mockResolvedValue(undefined) })) -vi.mock('@/components/github/github-work-item-edit-mutations', () => ({ - runWorkItemBodyUpdate: mocks.update -})) -vi.mock('@/store', () => ({ - useAppStore: { getState: () => ({ recordFeatureInteraction: () => {} }) } -})) -vi.mock('@/lib/pr-bot-author-overrides', () => ({ usePRBotAuthorOverrides: () => ({}) })) -vi.mock('./conversation-tab-activity', () => ({ ConversationTabActivity: () => null })) -vi.mock('./conversation-tab-pr-sidebar', () => ({ ConversationTabPRSidebar: () => null })) -vi.mock('./gh-comment-composer', () => ({ GHCommentComposer: () => null })) -vi.mock('@/components/github/GitHubMarkdownComposer', () => ({ - GitHubMarkdownComposer: ({ - value, - onChange - }: { - value: string - onChange: (value: string) => void - }) => ( -