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/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/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/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index f94a7a2bf68..b0f4d7fe4d4 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -148,7 +148,6 @@ 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/installation/scripts/posix-hook-json-stdin-reader.test.ts -3 test-no-real-time-wait:src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.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 @@ -159,10 +158,10 @@ 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 @@ -710,7 +709,7 @@ 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 @@ -718,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 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/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 697cc84efe0..0eccabfb512 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -35,10 +35,10 @@ 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/agent-browser-bridge-process.ts -2 src/main/browser/agent-browser/agent-browser-dependency-binary.ts -2 src/main/browser/agent-browser/agent-browser-process-environment.ts -1 src/main/browser/agent-browser/agent-browser-session-reset.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 @@ -62,16 +62,16 @@ 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/browser-popup-background-cdp-probe.ts -2 src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts -1 src/main/browser/identity/browser-identity-mode-record.ts -2 src/main/browser/identity/browser-identity-mode-store.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/browser-session-meta-store.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 @@ -478,7 +478,6 @@ 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 -1 src/main/runtime/push/notifications/mobile-notification-dismissal-store.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 @@ -502,6 +501,8 @@ 1 src/main/speech/stt-worker-model-config.ts 2 src/main/speech/stt-worker-paths.ts 2 src/main/sqlite/harden-database-files.ts +1 src/main/sqlite/keyed-json-row-cache.ts +5 src/main/sqlite/legacy-json-source.ts 1 src/main/sqlite/sync-database.ts 2 src/main/sqlite/versioned-cache-database.ts 1 src/main/ssh/authentication/ssh-auth-resolution.ts 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/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 1799f04c983..04253a93e8e 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -13,10 +13,10 @@ 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/reliability-gates.jsonc b/config/reliability-gates.jsonc index 0f0ddbb7a88..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", diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 45c1aa25247..2a25d38facd 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -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, @@ -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/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/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 85b55c113ff..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 @@ -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-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 2e17a2ce5e2..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', 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/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index 0e3e52d24b7..4823302acd9 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." }, "fileReader": { diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 9fad7a8ed7b..92a11862440 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/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/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/skill-guides/orca-per-workspace-env.md b/skill-guides/orca-per-workspace-env.md index 76c94d8a566..56c62d01d93 100644 --- a/skill-guides/orca-per-workspace-env.md +++ b/skill-guides/orca-per-workspace-env.md @@ -290,6 +290,20 @@ 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. + The base result, which is what Orca-server mode prints: ```json diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 12f3f91b044..4be59c4941d 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2074,6 +2074,20 @@ 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.", + "", "The base result, which is what Orca-server mode prints:", "", "```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/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts b/src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts deleted file mode 100644 index 42c4dbf7c57..00000000000 --- a/src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -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', () => ({ - 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/testing/transcripts/server-transcript-result-retry.test.ts b/src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts deleted file mode 100644 index 6173fc19da4..00000000000 --- a/src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.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 '../../agent-hook-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/ai-vault/cached-session-list-scope-only.test.ts b/src/main/ai-vault/cached-session-list-scope-only.test.ts deleted file mode 100644 index ddcf56df19b..00000000000 --- a/src/main/ai-vault/cached-session-list-scope-only.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -const { scanAiVaultSessionsInService } = vi.hoisted(() => ({ - scanAiVaultSessionsInService: vi.fn() -})) - -vi.mock('./scan-service/session-scanner-service-spawn', async (importOriginal) => ({ - ...(await importOriginal()), - scanAiVaultSessionsInService -})) - -import { listAiVaultSessions, resetAiVaultSessionListCacheForTests } from './cached-session-list' - -beforeEach(() => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') - resetAiVaultSessionListCacheForTests() - scanAiVaultSessionsInService.mockResolvedValue({ sessions: [], issues: [], scannedAt: 'scan' }) -}) - -afterEach(() => { - resetAiVaultSessionListCacheForTests() - vi.restoreAllMocks() - scanAiVaultSessionsInService.mockReset() -}) - -it('answers a scope-only request from a cached full list for the same paths, never the reverse', async () => { - const scopePaths = ['/repo/app'] - - await listAiVaultSessions({ scopePaths }) - await listAiVaultSessions({ scopePaths, scopeOnly: true }) - expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(1) - - resetAiVaultSessionListCacheForTests() - await listAiVaultSessions({ scopePaths, scopeOnly: true }) - await listAiVaultSessions({ scopePaths }) - expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(3) -}) 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/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 97% 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..279663f28f2 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 { 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-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.ts b/src/main/browser/cdp/commands/cdp-bridge.ts index c56d1f5d367..a0083bf2220 100644 --- a/src/main/browser/cdp/commands/cdp-bridge.ts +++ b/src/main/browser/cdp/commands/cdp-bridge.ts @@ -33,10 +33,11 @@ import type { BrowserViewportResult, BrowserWaitResult } from '../../../../shared/runtime-browser-contracts' -import type { BrowserManager } from '../../browser-manager' +import type { BrowserManager } from '../../guest-lifecycle/manager/browser-manager' import type { CdpAuxiliaryCommands, CdpTabState } from './cdp-auxiliary-commands' 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-page-input-commands.ts b/src/main/browser/cdp/commands/cdp-page-input-commands.ts index d69a65caf74..dbe1ab8dc9b 100644 --- a/src/main/browser/cdp/commands/cdp-page-input-commands.ts +++ b/src/main/browser/cdp/commands/cdp-page-input-commands.ts @@ -12,11 +12,11 @@ import { import { dispatchPageKeyEvent, isEmbeddedGuest, - routePageTextInsertion, - type GuestCdpSender + routePageTextInsertion } from '../input/guest-direct-key-input' +import type { GuestSessionCdpSender } from '../input/guest-frame-input-sessions' import { withAgentInputInjection } from '../input/agent-input-injection' -import type { AgentPointerInput } from '../../guest-lifecycle/browser-agent-activity' +import type { AgentPointerInput } from '../../guest-lifecycle/page-activity/browser-agent-activity' import type { CapturePaintHold } from './cdp-screenshot' import { waitForGuestFirstPaint } from '../debugger/guest-first-paint' @@ -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/debugger/guest-first-paint.ts b/src/main/browser/cdp/debugger/guest-first-paint.ts index 6d3527147bb..21e84036817 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 { 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/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/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/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/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-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/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-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/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 ea8108e6c7e..eb0bb73c23a 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar.ts @@ -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 f603dd5cd73..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) diff --git a/src/main/browser/extensions/api/commands.ts b/src/main/browser/extensions/api/commands.ts index 8e21f2f3f33..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 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 96ff8bd8026..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', () => ({ diff --git a/src/main/browser/extensions/api/management.ts b/src/main/browser/extensions/api/management.ts index be6cf127186..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' diff --git a/src/main/browser/extensions/api/tabs-capture.test.ts b/src/main/browser/extensions/api/tabs-capture.test.ts index 407758f63b6..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 } })) diff --git a/src/main/browser/extensions/api/tabs-capture.ts b/src/main/browser/extensions/api/tabs-capture.ts index 976eeaa7b07..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' diff --git a/src/main/browser/extensions/browser-extension-management.test.ts b/src/main/browser/extensions/browser-extension-management.test.ts index f93accf963a..76cb80c9de7 100644 --- a/src/main/browser/extensions/browser-extension-management.test.ts +++ b/src/main/browser/extensions/browser-extension-management.test.ts @@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => { } }) -vi.mock('../sessions/browser-session-registry', () => ({ +vi.mock('../sessions/profiles/browser-session-registry', () => ({ browserSessionRegistry: { getEnabledExtensionIds: () => [], updateEnabledExtensionIds: vi.fn(), diff --git a/src/main/browser/extensions/browser-extension-management.ts b/src/main/browser/extensions/browser-extension-management.ts index 31267be9a85..dbd4c9e178d 100644 --- a/src/main/browser/extensions/browser-extension-management.ts +++ b/src/main/browser/extensions/browser-extension-management.ts @@ -4,7 +4,7 @@ import type { BrowserExtensionListResult, InstalledBrowserExtension } from '../../../shared/browser/extensions/browser-extension-types' -import { browserSessionRegistry } from '../sessions/browser-session-registry' +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' diff --git a/src/main/browser/extensions/browser-extension-startup.ts b/src/main/browser/extensions/browser-extension-startup.ts index 6a740be8901..d388a50d1e7 100644 --- a/src/main/browser/extensions/browser-extension-startup.ts +++ b/src/main/browser/extensions/browser-extension-startup.ts @@ -10,7 +10,7 @@ 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 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 138304fa1c3..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 @@ -29,7 +29,7 @@ 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 }), 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 095890c8e28..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 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-settings-prompt-lifetime.test.ts b/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts index 4ac6e47d000..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 @@ -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: () => [], 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 542207de588..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() })) 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 c7ecd3215b2..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' 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/tabs-and-windows/browser-extension-discarded-tabs.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts index d24ec8647ce..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, 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-tab-lifecycle.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts index 743584daf4b..1a1ad109e1a 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-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 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 9db54215557..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' 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 36408158c1a..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 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 454fe682ab4..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' 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..6d58e813a9a 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 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..0f232699aea 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() @@ -218,12 +212,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 93% 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..0d39ea34f57 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,16 @@ 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' export abstract class BrowserManagerGuestNavigationPolicy extends BrowserManagerGuestPopupPolicy { protected installGuestNavigationPolicy(guest: Electron.WebContents): () => void { 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 95% 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..25787d1c159 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 { 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/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/command-code/command-code-managed-script.ts b/src/main/command-code/command-code-managed-script.ts index 0c3894f44c3..34a41d97fa1 100644 --- a/src/main/command-code/command-code-managed-script.ts +++ b/src/main/command-code/command-code-managed-script.ts @@ -1,4 +1,5 @@ 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, @@ -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/ephemeral-vm/failed-start-cleanup.ts b/src/main/ephemeral-vm/failed-start-cleanup.ts index 878f59cebf9..c27bd207f4d 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 @@ -39,7 +40,7 @@ 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.projectId ? { projectId: args.projectId } : {}), ...(args.workspaceId ? { workspaceId: args.workspaceId } : {}), 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-provisioning-persistence.ts b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts index 8b561bb4692..3faeca9ad42 100644 --- a/src/main/ephemeral-vm/runtime-provisioning-persistence.ts +++ b/src/main/ephemeral-vm/runtime-provisioning-persistence.ts @@ -1,3 +1,4 @@ +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' @@ -49,7 +50,7 @@ export async function persistProvisionedEphemeralVmRuntime( return upsertEphemeralVmRuntime(args.userDataPath, { id: start.context.instanceId ?? start.context.recipeId, recipeId: args.recipe.id, - recipe: args.recipe, + recipe: toEphemeralVmRuntimeRecipeSnapshot(args.recipe), ...(args.repoId ? { repoId: args.repoId } : {}), ...(args.projectId ? { projectId: args.projectId } : {}), ...(args.workspaceId ? { workspaceId: args.workspaceId } : {}), 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/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index fe7e645ee6d..a8838ffea9b 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -9,13 +9,11 @@ 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, @@ -56,11 +54,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/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/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 55f722092e5..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' 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..6f389b225d9 100644 --- a/src/main/ipc/ephemeral-vm-recipe-context.ts +++ b/src/main/ipc/ephemeral-vm-recipe-context.ts @@ -110,12 +110,18 @@ export function getRuntimeRecipeContext( if (!repo.ok) { throw new EphemeralVmFailureError(repo.failure) } + 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. - const recipe = - runtime.recipe ?? - (loadHooks(repo.repo.path)?.environmentRecipes ?? []).find( - (entry) => entry.id === runtime.recipeId - ) + // 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 }) 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/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/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/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/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-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/settings-delayed-response.test.ts b/src/main/ipc/settings-delayed-response.test.ts index 28e78d6c573..e8aeaec8e63 100644 --- a/src/main/ipc/settings-delayed-response.test.ts +++ b/src/main/ipc/settings-delayed-response.test.ts @@ -33,14 +33,14 @@ 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() })) diff --git a/src/main/ipc/settings-ipc-test-fixture.ts b/src/main/ipc/settings-ipc-test-fixture.ts index e8323477db3..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 } })) diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index 95e191f1048..d5cd6411e85 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -18,9 +18,9 @@ import { applyAgentStatusHooksEnabled } from '../agent-hooks/installation/manage import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' 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/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/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..415e45854d9 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,9 @@ -import { mkdir, readFile, rename, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' +import { join } from 'node:path' +import { + readLegacyJsonSource, + removeImportedLegacyJsonSource +} from '../../sqlite/legacy-json-source' +import { KeyedJsonRowCache, type KeyedJsonRow } from '../../sqlite/keyed-json-row-cache' import type { AgentSessionModelOption, AgentSessionOptionChoice @@ -16,6 +20,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 +171,52 @@ 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)) + } +} + +/** Rows of an older build's file; bytes it cannot use (corrupt, other version) yield none. */ +function legacyRows(text: string): KeyedJsonRow[] { + let root: Record | null + try { + root = asRecord(JSON.parse(text)) + } catch { + return [] + } + if (!root || root.version !== SCHEMA_VERSION || !Array.isArray(root.entries)) { + return [] + } + return root.entries + .map(parseEntry) + .filter((entry): entry is AgentModelCatalogEntry => entry !== null) + .map(catalogRow) +} + +/** 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') + // Earlier builds rewrote this whole file (megabytes) per change; it is imported once, then removed. + const legacyPath = join(directory, 'agent-model-catalog.json') + // Stored state could not be read: this session makes no legacy-vs-stored decision and + // 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'), SCHEMA_VERSION) 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 +225,43 @@ 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 = Math.min(retryDelayMs * 2, 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 { + const source = readLegacyJsonSource(legacyPath) + // An unreadable file stays, as does the stored catalog; the next start tries again. + const legacy = + source.kind === 'read' + ? { rows: legacyRows(source.text), receipt: source.receipt } + : undefined + // A file still present came from an older build unless its receipt shows it was imported. + const loaded = cache.load(legacy) + if (loaded.kind === 'unreadable') { + cold = true return [] } + if (legacy) { + removeImportedLegacyJsonSource(legacyPath, legacy.receipt) + } + return parseEntries(loaded.values) }, 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-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/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/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/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/opencode/opencode-pty-launch.ts b/src/main/opencode/opencode-pty-launch.ts index 3a7b41df3a1..fc365a73472 100644 --- a/src/main/opencode/opencode-pty-launch.ts +++ b/src/main/opencode/opencode-pty-launch.ts @@ -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/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/persistence/loading-store/github-cache-database.test.ts b/src/main/persistence/loading-store/github-cache-database.test.ts index 50d130bc061..008ac4e59a7 100644 --- a/src/main/persistence/loading-store/github-cache-database.test.ts +++ b/src/main/persistence/loading-store/github-cache-database.test.ts @@ -35,18 +35,6 @@ const save = (dataFile: string, cache: Parameters { - it('reads back saved entries, including removals', () => { - const dataFile = profileDataFile() - save(dataFile, { pr: { 'o/r#1': pr(1), 'o/r#2': pr(2) }, issue: {} }) - save(dataFile, { pr: { 'o/r#2': pr(3) }, issue: { 'o/r#9': pr(4) } }) - - expect(readGitHubCacheDatabase(dataFile)).toEqual({ - cache: { pr: { 'o/r#2': pr(3) }, issue: { 'o/r#9': pr(4) } }, - fromSidecar: false, - sidecarHash: null - }) - }) - it('keeps an older build sidecar until its imported rows commit', async () => { const dataFile = profileDataFile() save(dataFile, { pr: { 'o/r#1': pr(1) }, issue: {} }) 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/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/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/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-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/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/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/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-liveness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts index 202d376fc46..aa103136bdb 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts @@ -24,29 +24,6 @@ describe('RelayControlLiveness keepalive', () => { return { instance, sendKeepalive, terminate, live } } - it('sends nothing until the relay offers, then one keepalive per interval while live', () => { - vi.useFakeTimers() - const { instance, sendKeepalive, terminate, live } = liveness() - instance.start() - vi.advanceTimersByTime(30_000) - expect(sendKeepalive).not.toHaveBeenCalled() - instance.startKeepalive(25_000) - vi.advanceTimersByTime(50_000) - expect(sendKeepalive).toHaveBeenCalledTimes(2) - // A second offer does not add a second timer. - instance.startKeepalive(1_000) - vi.advanceTimersByTime(25_000) - expect(sendKeepalive).toHaveBeenCalledTimes(3) - // Answered keepalives alone keep the control inside the silence bound. - vi.advanceTimersByTime(200_000) - expect(terminate).not.toHaveBeenCalled() - expect(sendKeepalive).toHaveBeenCalledTimes(11) - live.value = false - vi.advanceTimersByTime(25_000) - expect(sendKeepalive).toHaveBeenCalledTimes(11) - instance.stop() - }) - it('sends a keepalive instead of tearing down when its own timers were held back', () => { vi.useFakeTimers() const terminate = vi.fn() 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/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/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/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/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/push/notifications/mobile-notification-dismissal-entries.ts b/src/main/runtime/push/notifications/mobile-notification-dismissal-entries.ts new file mode 100644 index 00000000000..4ed5edbb929 --- /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/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..6977386ba24 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() + // Both the read-only snapshot and the writable open fail once. + failure.remainingOpens = 2 + 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..3270a8b70dd 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,12 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + statSync, + utimesSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -87,7 +95,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 +122,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 +136,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 +157,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' }) @@ -177,3 +191,24 @@ it('a targeted old delivery cannot retire a newer replacement with the same logi ]) expect(h.store.reconcile([shown, { ...shown, notificationSeq: 13 }])).toEqual([shown]) }) + +it('does not let an imported file left behind override later dismissals', async () => { + const h = fixture() + const legacyPath = join(h.path, 'mobile-notification-dismissals.json') + const legacy = JSON.stringify([ + { ...shown, dismissedThrough: -1, expiresAt: Date.now() + 86400_000 } + ]) + writeFileSync(legacyPath, legacy) + const { atimeMs, mtimeMs } = statSync(legacyPath) + const imported = new MobileNotificationDismissalStore(h.path) + imported.record({ type: 'dismiss', ...shown, notificationEpoch: 'now', dismissedDelivery: shown }) + await imported.close() + // The same bytes reappear, as when deleting the imported file failed. + writeFileSync(legacyPath, legacy) + utimesSync(legacyPath, atimeMs / 1000, mtimeMs / 1000) + + const restarted = new MobileNotificationDismissalStore(h.path) + stores.push(restarted) + expect(restarted.reconcile([shown])).toEqual([shown]) + expect(existsSync(legacyPath)).toBe(false) +}) 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..1b0581a9111 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, type KeyedJsonRowImport } from '../../../sqlite/keyed-json-row-cache' +import { + readLegacyJsonSource, + removeImportedLegacyJsonSource +} from '../../../sqlite/legacy-json-source' 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_DELAYS_MS = [100, 1_000, 5_000, 30_000, 60_000] as const function warnPersistFailed(error: unknown): void { console.warn('[notifications] Could not persist dismissal recovery state', error) } +type PendingEvent = { event: DismissalEvent & { notificationId: string }; at: number } +type LegacyHistory = KeyedJsonRowImport & { entries: DismissalRecordEntry[] } + +/** + * 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 retryAttempt = 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 + private readonly legacyPath: string + 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), 1) + this.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?.entries ?? [] + 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,82 @@ 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?: LegacyHistory } | undefined { + const source = readLegacyJsonSource(this.legacyPath) + if (source.kind === 'unreadable') { + console.warn('[notifications] Could not read dismissal recovery state', source.error) + return {} + } + const legacy = + source.kind === 'read' ? readLegacyHistory(source.text, source.receipt) : undefined + // A file still present came from an older build unless its receipt shows it was imported. + const loaded = this.cache.load(legacy) + if (loaded.kind === 'unreadable') { + console.warn('[notifications] Could not read dismissal recovery state', loaded.error) + return { legacy } + } + let entries = readDismissalEntries(loaded.values) + 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 + if (legacy) { + removeImportedLegacyJsonSource(this.legacyPath, legacy.receipt) + } + 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.retryAttempt = 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 + } + const delay = RETRY_DELAYS_MS[Math.min(this.retryAttempt, RETRY_DELAYS_MS.length - 1)] + this.retryAttempt += 1 + this.retryTimer = setTimeout(() => { + this.retryTimer = undefined + if (!this.attempt()) { + this.scheduleRetry() + } + }, delay) + this.retryTimer.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 +function readLegacyHistory(text: string, receipt: string): LegacyHistory { + let value: unknown + try { + value = JSON.parse(text) + } catch { + // Corrupt history establishes nothing, like missing history. + value = [] } - 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) - ) + const entries = readDismissalEntries(Array.isArray(value) ? value : []) + return { entries, rows: dismissalRows(entries), receipt } } 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/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..83d6b27877f --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/structured-worker-fleet-liveness.test.ts @@ -0,0 +1,204 @@ +// 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('reports a running Codex worker live and working, with nothing for the coordinator to do', () => { + installHost(record('codex'), true) + const worker = project([sessionStatus('working', NOW - 5 * 60 * 1000)]) + + expect(worker.liveness).toEqual({ verdict: 'live', observedAt: NOW, source: 'execution_host' }) + expect(worker.stage.activity).toBe('working') + expect(worker.evidence.lastObservedAt).toBe(NOW - 5 * 60 * 1000) + expect(worker.attention).toEqual({ categories: [], requiresAction: false }) + }) + + 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-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-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/server/runtime-rpc-metadata-lifecycle.test.ts b/src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts index e843e067e2d..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 @@ -3,7 +3,7 @@ import type * as WorktreeListingModule from '../../../git/worktrees/catalog/work import '../unused-default-rpc-methods.test-fixture' 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' @@ -160,6 +160,7 @@ describe('OrcaRuntimeRpcServer', () => { 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, '') 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/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 102523d2eff..a1260a785f3 100644 --- a/src/main/runtime/terminal/output/terminal-buffer-operations.ts +++ b/src/main/runtime/terminal/output/terminal-buffer-operations.ts @@ -15,8 +15,12 @@ import { import { hookLeadTurnState } from '../wait/tui-idle-hook-lane' 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/sqlite/keyed-json-row-cache.test.ts b/src/main/sqlite/keyed-json-row-cache.test.ts new file mode 100644 index 00000000000..0eaab068af5 --- /dev/null +++ b/src/main/sqlite/keyed-json-row-cache.test.ts @@ -0,0 +1,36 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { KeyedJsonRowCache } from './keyed-json-row-cache' + +const directories: string[] = [] +afterEach(() => { + for (const directory of directories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } +}) + +const row = (key: string, value: string) => ({ key, json: JSON.stringify(value) }) + +it('saves exactly its own rows after another connection committed in between', () => { + const directory = mkdtempSync(join(tmpdir(), 'orca-row-cache-')) + directories.push(directory) + const path = join(directory, 'cache.db') + const first = new KeyedJsonRowCache(path, 1) + const second = new KeyedJsonRowCache(path, 1) + try { + first.write([row('a', 'a1'), row('b', 'b1')]) + expect(second.load()).toEqual({ kind: 'rows', values: ['a1', 'b1'] }) + + first.write([row('a', 'a2'), row('b', 'b1')]) + second.write([row('a', 'a1'), row('b', 'b2')]) + + const reader = new KeyedJsonRowCache(path, 1) + expect(reader.load()).toEqual({ kind: 'rows', values: ['a1', 'b2'] }) + reader.close() + } finally { + first.close() + second.close() + } +}) diff --git a/src/main/sqlite/keyed-json-row-cache.ts b/src/main/sqlite/keyed-json-row-cache.ts new file mode 100644 index 00000000000..0a69a3eeab6 --- /dev/null +++ b/src/main/sqlite/keyed-json-row-cache.ts @@ -0,0 +1,299 @@ +import { existsSync } from 'node:fs' +import SyncDatabase from './sync-database' +import { + isUnusableDatabaseError, + openVersionedCacheDatabase, + removeVersionedCacheDatabase +} from './versioned-cache-database' +import { hardenSqliteDatabaseFiles } from './harden-database-files' + +export type KeyedJsonRow = { key: string; json: string } + +/** Rows of an older build's file plus the receipt identifying that file. */ +export type KeyedJsonRowImport = { rows: readonly KeyedJsonRow[]; receipt: string } + +export type KeyedJsonRowCacheLoad = + | { kind: 'rows'; values: unknown[] } + | { kind: 'unreadable'; error: unknown } + +type StoredRow = { seq: number; json: string } +type Snapshot = { + receipt: unknown + stored: Map + maxSeq: number + values: unknown[] +} + +// Callers run on the main thread: a lock held elsewhere must fail fast, not freeze the app. +const BUSY_TIMEOUT_MS = 25 +const RECEIPT_KEY = 'legacy_import_receipt' + +/** + * An ordered list of JSON values kept as one SQLite row each, so a save writes only the + * rows whose value or position changed instead of rewriting the whole list. Corruption + * rebuilds the file once; busy and unreadable files throw, 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 + + constructor( + private readonly path: string, + private readonly schemaVersion: number + ) {} + + /** + * Opens the database only when it exists or `legacy` must be imported, so an unused + * store creates no file. `legacy` replaces the rows unless its receipt shows it was + * already imported; the receipt commits with the rows, so its source may then be removed. + */ + load(legacy?: KeyedJsonRowImport): KeyedJsonRowCacheLoad { + if (!legacy && !existsSync(this.path)) { + return { kind: 'rows', values: [] } + } + let snapshot: Snapshot | undefined + try { + // A read-only connection is not blocked by another connection's write lock. + snapshot = this.readSnapshot() + } catch (error) { + if (isBusyError(error)) { + return { kind: 'unreadable', error } + } + // Missing tables, a stale schema or corruption: the writable path repairs those. + } + try { + if (snapshot && (!legacy || snapshot.receipt === legacy.receipt)) { + this.stored = snapshot.stored + this.maxSeq = snapshot.maxSeq + // That connection's version means nothing to ours; the first write re-reads. + this.dataVersion = undefined + return { kind: 'rows', values: snapshot.values } + } + return this.transient(() => + this.withRebuild(() => { + const db = this.database() + db.exec('BEGIN') + let values: unknown[] + let imported: boolean + try { + imported = legacy !== undefined && readReceipt(db) !== legacy.receipt + values = imported ? [] : this.readBaseline(db) + db.exec('COMMIT') + } catch (error) { + rollback(db) + throw error + } + if (imported && legacy) { + this.commit(legacy.rows, legacy.receipt) + values = legacy.rows.flatMap((row) => parse(row.json)) + } + return { kind: 'rows' as const, values } + }) + ) + } catch (error) { + this.closeDatabase() + return { kind: 'unreadable', error } + } + } + + /** + * Saves `rows` in order; `importReceipt` replaces every stored row and records the import. + * Throws on failure (busy included); the stored baseline is unchanged so a retry is exact. + */ + write(rows: readonly KeyedJsonRow[], importReceipt?: string): void { + this.transient(() => this.withRebuild(() => this.commit(rows, importReceipt))) + } + + /** Later writes still save, each opening and closing the database itself. */ + close(): void { + this.closed = true + this.closeDatabase() + } + + private commit(rows: readonly KeyedJsonRow[], importReceipt: string | undefined): void { + const db = this.database() + db.exec('BEGIN IMMEDIATE') + try { + const replaceAll = importReceipt !== undefined + // Another connection committed since our baseline: diff against what is on disk. + if (!replaceAll && db.pragma('data_version', { simple: true }) !== this.dataVersion) { + this.readBaseline(db) + } + const baseline = replaceAll ? new Map() : this.stored + const next = new Map() + let maxSeq = replaceAll ? 0 : 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 }) + } + if (replaceAll) { + db.prepare('DELETE FROM rows').run() + db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)').run( + RECEIPT_KEY, + importReceipt + ) + } + 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) + } + } + // 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 before the rows of the same snapshot. */ + private readBaseline(db: SyncDatabase): unknown[] { + const version = db.pragma('data_version', { simple: true }) + const { stored, maxSeq, values } = readRows(db) + this.stored = stored + this.maxSeq = maxSeq + this.dataVersion = version + return values + } + + /** Rows and import receipt from one read-only snapshot; throws if the schema needs work. */ + private readSnapshot(): Snapshot { + const db = new SyncDatabase(this.path, { readonly: true, fileMustExist: true }) + try { + db.pragma(`busy_timeout = ${BUSY_TIMEOUT_MS}`) + db.exec('BEGIN') + try { + const version = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() + if (version?.value !== String(this.schemaVersion)) { + throw new Error('Cache schema needs rebuilding') + } + return { receipt: readReceipt(db), ...readRows(db) } + } finally { + rollback(db) + } + } finally { + db.close() + } + } + + /** 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 (!isUnusableDatabaseError(error)) { + throw error + } + this.closeDatabase() + // Fail fast: a file held open elsewhere (Windows) throws, and the caller retries later. + removeVersionedCacheDatabase(this.path, 'fail-fast') + this.stored = new Map() + this.maxSeq = 0 + return operation() + } + } + + /** After close, each operation opens and closes the database itself. */ + private transient(operation: () => T): T { + const transient = this.closed && this.db === null + try { + return operation() + } finally { + if (transient) { + this.closeDatabase() + } + } + } + + private database(): SyncDatabase { + if (this.db) { + return this.db + } + const db = openVersionedCacheDatabase(this.path, { + version: this.schemaVersion, + busyTimeoutMs: BUSY_TIMEOUT_MS, + removal: 'fail-fast', + 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);` + }) + hardenSqliteDatabaseFiles(this.path) + this.db = db + // A fresh connection cannot vouch for a baseline read through an earlier one. + this.dataVersion = undefined + 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): Omit { + const stored = new Map() + const values: unknown[] = [] + 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) + values.push(...parse(value)) + } + } + return { stored, maxSeq, values } +} + +const BUSY_ERROR = /SQLITE_BUSY|SQLITE_LOCKED|database is locked|database table is locked/i + +function isBusyError(error: unknown): boolean { + if (!(error instanceof Error)) { + return false + } + const code = 'code' in error ? error.code : undefined + return (typeof code === 'string' && BUSY_ERROR.test(code)) || BUSY_ERROR.test(error.message) +} + +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') + } +} + +function parse(json: string): unknown[] { + try { + return [JSON.parse(json)] + } catch { + return [] + } +} diff --git a/src/main/sqlite/legacy-json-source.ts b/src/main/sqlite/legacy-json-source.ts new file mode 100644 index 00000000000..e0cdaca8575 --- /dev/null +++ b/src/main/sqlite/legacy-json-source.ts @@ -0,0 +1,46 @@ +import { createHash } from 'node:crypto' +import { closeSync, fstatSync, openSync, 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' } + | { kind: 'unreadable'; error: unknown } + | { kind: 'read'; text: string; receipt: string } + +/** `receipt` identifies these exact bytes, so a finished import is recognised next start. */ +export function readLegacyJsonSource(path: string): LegacyJsonSource { + let fd: number + try { + fd = openSync(path, 'r') + } catch (error) { + return isDefinitiveAbsence(error) ? { kind: 'absent' } : { kind: 'unreadable', error } + } + try { + const { mtimeMs } = fstatSync(fd) + const bytes = readFileSync(fd) + const hash = createHash('sha256').update(bytes).digest('hex') + return { + kind: 'read', + text: bytes.toString('utf8'), + receipt: `${bytes.length}:${Math.floor(mtimeMs)}:${hash}` + } + } catch (error) { + return { kind: 'unreadable', error } + } finally { + closeSync(fd) + } +} + +/** Removes the file only while it is still the import's source, never a newer rewrite. */ +export function removeImportedLegacyJsonSource(path: string, receipt: string): void { + const current = readLegacyJsonSource(path) + if (current.kind !== 'read' || current.receipt !== receipt) { + return + } + try { + rmSync(path, { force: true }) + } catch { + // The stored receipt marks it imported, so a leftover file cannot shadow newer rows. + } +} 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/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-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/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/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 ca19a2eefd5..f2e6f26462e 100644 --- a/src/main/startup/main-process-account-services.ts +++ b/src/main/startup/main-process-account-services.ts @@ -13,7 +13,7 @@ import { } from '../opencode/opencode-go-api-key-store' 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-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-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts index 8906147723b..95451a1393b 100644 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ b/src/main/startup/main-process-quit-pending-writer.test.ts @@ -43,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() }, @@ -57,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 21b1f2f336e..9a71b26cd7e 100644 --- a/src/main/startup/main-process-quit-update-veto.test.ts +++ b/src/main/startup/main-process-quit-update-veto.test.ts @@ -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 b02449fc599..6ab8794ad84 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -19,7 +19,7 @@ import { awaitRuntimeFileWatcherUnsubscribes } from '../runtime/files/watch/file 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 523f4b95458..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' @@ -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' 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 10594e38a3c..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(), @@ -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 aebdc22c647..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' 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 c2ce77b048c..3072867e660 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -12,8 +12,8 @@ import { getLocalPtyProvider } from '../ipc/pty/provider/registry' import { clearProviderPtyState } from '../ipc/pty/provider/state-cleanup' 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' 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/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/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.current-model.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx deleted file mode 100644 index efacd606b38..00000000000 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { fireEvent } from '@testing-library/react' -import { expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { - agentPickerDraft, - type AgentPickerEntry -} from '../../../../shared/agent-launch/picker/agent-launch-picker' -import { entry, root } from './agent-launch-setup-panel-test-fixture' -import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' - -const opencode: AgentPickerEntry = { - ...entry, - agent: 'opencode', - label: 'OpenCode', - rows: [{ agent: 'opencode', kind: 'cli', executionHostId: 'local' }], - arguments: '--model opencode/gpt-5.3-codex', - terminal: {}, - catalog: { origin: 'unknown' } -} -const listed: AgentPickerEntry = { - ...opencode, - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [ - 'github-copilot/claude-fable-5', - 'github-copilot/claude-opus-5', - 'opencode/gpt-5.3-codex' - ].map((id) => ({ id, label: id, efforts: [], isDefault: false })) - } -} -const draft = agentPickerDraft(opencode) -const onUse = vi.fn(() => true) -const onDraftChange = vi.fn() -const render = (own: AgentPickerEntry, mode?: 'select') => - act(() => - root.render( - - draft} - onDraftChange={onDraftChange} - onUse={onUse} - /> - - ) - ) -const highlighted = () => - document.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute('data-value') - -it('opens on the current model, not the first listed one', () => { - render(listed) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') -}) - -it('keeps the current model highlighted when the catalog arrives and lists it', () => { - render(opencode) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') - render(listed) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') -}) - -it('starts on the resolved model when defaults settle after the panel opens', () => { - render({ ...listed, arguments: undefined, defaultsPending: true }) - render(listed) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') -}) - -it('keeps an Arguments-owned text action on its default instead of the inherited model', () => { - render( - { - ...listed, - arguments: '', - terminal: { model: 'opencode/gpt-5.3-codex' }, - textGeneration: { - defaultLabel: 'Default', - modelInArguments: true, - effortInArguments: false, - modelArgumentsUnrecognized: false, - effortArgumentsUnrecognized: false, - effortInModel: false, - effortByModel: {} - } - }, - 'select' - ) - expect(highlighted()).toBe('__text_action_default__') -}) - -it('returns to the current model after a search is cleared, so Enter uses it', () => { - render(listed, 'select') - const search = document.querySelector('[cmdk-input]')! - fireEvent.change(search, { target: { value: 'opus' } }) - expect(highlighted()).toBe('github-copilot/claude-opus-5') - fireEvent.change(search, { target: { value: '' } }) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') - onUse.mockClear() - onDraftChange.mockClear() - fireEvent.keyDown(search, { key: 'Enter' }) - expect(onUse).toHaveBeenCalledTimes(1) - expect(onDraftChange).not.toHaveBeenCalled() -}) - -it('returns to the current model when a search is cleared without a key, as with Cut', async () => { - render(listed) - const search = document.querySelector('[cmdk-input]')! - fireEvent.change(search, { target: { value: 'opus' } }) - fireEvent.pointerMove(search) - await act(async () => {}) - fireEvent.change(search, { target: { value: '' } }) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') -}) - -it('keeps a hovered model through a rerender, so Enter picks it instead of using the current one', () => { - render(listed, 'select') - const opus = document.querySelector('[cmdk-item][data-value="github-copilot/claude-opus-5"]')! - fireEvent.pointerMove(opus) - render(listed, 'select') - expect(highlighted()).toBe('github-copilot/claude-opus-5') - onUse.mockClear() - onDraftChange.mockClear() - fireEvent.keyDown(document.querySelector('[cmdk-input]')!, { key: 'Enter' }) - expect(onUse).not.toHaveBeenCalled() - expect(onDraftChange).toHaveBeenCalledTimes(1) -}) - -it('returns to the current model after End at the last row and a keyless clear', () => { - render(listed) - const search = document.querySelector('[cmdk-input]')! - fireEvent.keyDown(search, { key: 'End' }) - fireEvent.change(search, { target: { value: 'opus' } }) - fireEvent.change(search, { target: { value: '' } }) - expect(highlighted()).toBe('opencode/gpt-5.3-codex') -}) diff --git a/src/renderer/src/components/mobile/MobileHero.tsx b/src/renderer/src/components/mobile/MobileHero.tsx index 3311fbe54a7..1282dc68fd3 100644 --- a/src/renderer/src/components/mobile/MobileHero.tsx +++ b/src/renderer/src/components/mobile/MobileHero.tsx @@ -1,15 +1,13 @@ import { useLayoutEffect, useRef, useState } from 'react' import { ArrowLeft, ArrowRight, Copy } from 'lucide-react' import { cn } from '../../lib/utils' -import type { MobileNetworkInterface } from '../settings/mobile/pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' import { AndroidLogo, IosBrandIcon } from './MobileBrandIcons' import type { InstallCopy } from './mobile-platform-copy' import type { MobilePairingConnectionMode } from '../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import type { MobileRelayMintFailure } from '../../../../shared/remote-runtime/relay/mobile-relay-mint-failure' import { MobileHeroPairingStep } from './MobileHeroPairingStep' import { MobileAndroidInstallHelp } from './MobileAndroidInstallHelp' -export { HeroIntro } from './MobileHeroIntro' -export { HeroPaired, type PairedDevice } from './MobileHeroPairedDevices' import { useTranslate } from '@/i18n/use-translate' export type Platform = 'ios' | 'android' @@ -38,7 +36,7 @@ type HeroFlowProps = { onRegeneratePairing: () => void canGeneratePairing: boolean onCopyPairingCode: () => void - networkInterfaces: readonly MobileNetworkInterface[] + networkInterfaces: readonly PairingNetworkInterface[] customAddresses: readonly string[] selectedAddress: string | undefined selectedAddressIsCustom: boolean diff --git a/src/renderer/src/components/mobile/MobileHeroPairedDevices.tsx b/src/renderer/src/components/mobile/MobileHeroPairedDevices.tsx index e2a9c4d3196..d42d39778cd 100644 --- a/src/renderer/src/components/mobile/MobileHeroPairedDevices.tsx +++ b/src/renderer/src/components/mobile/MobileHeroPairedDevices.tsx @@ -2,10 +2,8 @@ import { Smartphone, Trash2 } from 'lucide-react' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { PairedMobileDevice } from './paired-mobile-devices' -export type PairedDevice = PairedMobileDevice - type HeroPairedProps = { - devices: readonly PairedDevice[] + devices: readonly PairedMobileDevice[] onPairAnother: () => void onRevoke: (deviceId: string) => void revokingDeviceIds: readonly string[] diff --git a/src/renderer/src/components/mobile/MobileHeroPairingStep.tsx b/src/renderer/src/components/mobile/MobileHeroPairingStep.tsx index 44ac7a709c4..59fe071a152 100644 --- a/src/renderer/src/components/mobile/MobileHeroPairingStep.tsx +++ b/src/renderer/src/components/mobile/MobileHeroPairingStep.tsx @@ -3,10 +3,10 @@ import { Trans } from 'react-i18next' import { ChevronDown, CircleAlert, Copy, RefreshCw } from 'lucide-react' import { cn } from '../../lib/utils' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '../ui/collapsible' -import type { MobileNetworkInterface } from '../settings/mobile/pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' import { NetworkInterfacePicker } from './NetworkInterfacePicker' -import { MobilePairingConnectionOptions } from '../settings/mobile/pairing/MobilePairingConnectionOptions' -import { MobileRelayBetaNotice } from '../settings/mobile/pairing/MobileRelayBetaNotice' +import { MobilePairingConnectionOptions } from './pairing/MobilePairingConnectionOptions' +import { MobileRelayBetaNotice } from './pairing/MobileRelayBetaNotice' import { MachineNameField } from '../machine-identity/MachineNameField' import { MobileRelayMintFailureNotice } from './mobile-relay-mint-failure-notice' import { WindowsFirewallNotice } from './WindowsFirewallNotice' @@ -101,7 +101,7 @@ export function MobileHeroPairingStep({ onRegeneratePairing: () => void canGeneratePairing: boolean onCopyPairingCode: () => void - networkInterfaces: readonly MobileNetworkInterface[] + networkInterfaces: readonly PairingNetworkInterface[] customAddresses: readonly string[] selectedAddress: string | undefined selectedAddressIsCustom: boolean diff --git a/src/renderer/src/components/mobile/MobilePage.test.tsx b/src/renderer/src/components/mobile/MobilePage.test.tsx index 3f96484c8ca..7cd38fa2c40 100644 --- a/src/renderer/src/components/mobile/MobilePage.test.tsx +++ b/src/renderer/src/components/mobile/MobilePage.test.tsx @@ -38,7 +38,7 @@ vi.mock('sonner', () => ({ vi.mock('./use-mobile-install-qr', () => ({ useMobileInstallQr: () => null })) vi.mock('./use-mobile-page-escape', () => ({ useMobilePageEscape: vi.fn() })) -vi.mock('../settings/mobile/pairing/mobile-pairing-device-polling', () => ({ +vi.mock('./pairing/mobile-pairing-device-polling', () => ({ useMobilePairingDevicePolling: vi.fn() })) diff --git a/src/renderer/src/components/mobile/MobilePage.tsx b/src/renderer/src/components/mobile/MobilePage.tsx index bef2661d1ca..2db583ae633 100644 --- a/src/renderer/src/components/mobile/MobilePage.tsx +++ b/src/renderer/src/components/mobile/MobilePage.tsx @@ -3,7 +3,7 @@ import { toast } from 'sonner' import { useMountedRef } from '@/hooks/useMountedRef' import { useAppStore } from '@/store' import type { Platform, StepIndex } from './MobileHero' -import type { MobileNetworkInterface } from '../settings/mobile/pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' import { translate } from '@/i18n/i18n' import { useMobilePageEscape } from './use-mobile-page-escape' import { MobilePageContent } from './MobilePageContent' @@ -39,7 +39,7 @@ export default function MobilePage(): React.JSX.Element { const signedIn = useAppStore((state) => state.orcaProfileAuthStatus?.state === 'connected') const refreshAuthStatus = useAppStore((state) => state.fetchOrcaProfileAuthStatus) const [connectionMode, setConnectionMode] = useMobilePairingConnectionMode() - const [networkInterfaces, setNetworkInterfaces] = useState([]) + const [networkInterfaces, setNetworkInterfaces] = useState([]) const pairingAddressChangeRef = useRef<(change: MobilePairingAddressChange) => void>(() => {}) const notifyPairingAddressChange = useCallback( (change: MobilePairingAddressChange): void => pairingAddressChangeRef.current(change), diff --git a/src/renderer/src/components/mobile/MobilePageContent.tsx b/src/renderer/src/components/mobile/MobilePageContent.tsx index 6902533a708..a06bb3c4ef9 100644 --- a/src/renderer/src/components/mobile/MobilePageContent.tsx +++ b/src/renderer/src/components/mobile/MobilePageContent.tsx @@ -1,13 +1,9 @@ import { useTranslate } from '@/i18n/use-translate' -import type { MobileNetworkInterface } from '../settings/mobile/pairing/mobile-network-interface-selection' -import { - HeroFlow, - HeroIntro, - HeroPaired, - type PairedDevice, - type Platform, - type StepIndex -} from './MobileHero' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' +import { HeroFlow, type Platform, type StepIndex } from './MobileHero' +import { HeroIntro } from './MobileHeroIntro' +import { HeroPaired } from './MobileHeroPairedDevices' +import type { PairedMobileDevice } from './paired-mobile-devices' import { getInstallCopy } from './mobile-platform-copy' import type { MobilePageStage } from './mobile-page-stage' import { MobilePageToolbar } from './MobilePageToolbar' @@ -19,7 +15,7 @@ type MobilePageContentProps = { closeMobilePage: () => void copyInstallUrl: () => void copyPairingCode: () => void - devices: readonly PairedDevice[] + devices: readonly PairedMobileDevice[] enterFlow: () => void generatePairing: (rotate: boolean) => void canGeneratePairing: boolean @@ -33,7 +29,7 @@ type MobilePageContentProps = { handleContinue: () => void installQrUrl: string | null loadNetworkInterfaces: () => void - networkInterfaces: MobileNetworkInterface[] + networkInterfaces: PairingNetworkInterface[] openAndroidInstallGuide: () => void openInstallUrl: () => void pairAnotherDevice: () => void diff --git a/src/renderer/src/components/mobile/NetworkInterfacePicker.tsx b/src/renderer/src/components/mobile/NetworkInterfacePicker.tsx index 22862816eec..8969354a589 100644 --- a/src/renderer/src/components/mobile/NetworkInterfacePicker.tsx +++ b/src/renderer/src/components/mobile/NetworkInterfacePicker.tsx @@ -3,7 +3,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { AddressPicker, type AddressOption } from '../network/AddressPicker' import { parseManualNetworkAddress } from '../../../../shared/network/manual-address' -import type { MobileNetworkInterface } from '../settings/mobile/pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' function formatCustomAddressLabel(address: string): string { return translate( @@ -14,7 +14,7 @@ function formatCustomAddressLabel(address: string): string { } export type NetworkInterfacePickerProps = { - networkInterfaces: readonly MobileNetworkInterface[] + networkInterfaces: readonly PairingNetworkInterface[] customAddresses: readonly string[] selectedAddress: string | undefined selectedAddressIsCustom: boolean diff --git a/src/renderer/src/components/settings/mobile/pairing/MobilePairingConnectionOptions.tsx b/src/renderer/src/components/mobile/pairing/MobilePairingConnectionOptions.tsx similarity index 95% rename from src/renderer/src/components/settings/mobile/pairing/MobilePairingConnectionOptions.tsx rename to src/renderer/src/components/mobile/pairing/MobilePairingConnectionOptions.tsx index 3e42199a136..45af2745929 100644 --- a/src/renderer/src/components/settings/mobile/pairing/MobilePairingConnectionOptions.tsx +++ b/src/renderer/src/components/mobile/pairing/MobilePairingConnectionOptions.tsx @@ -1,18 +1,18 @@ import { useEffect, useRef, useState } from 'react' -import { Badge } from '../../../ui/badge' -import { translate } from '../../../../i18n/i18n' +import { Badge } from '../../ui/badge' +import { translate } from '../../../i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { useAppStore } from '../../../../store/index' +import { useAppStore } from '../../../store/index' import { useOrcaProfileAuthStatusRefresh } from '@/hooks/use-orca-profile-auth-status-refresh' import { cn } from '@/lib/utils' import type { MobileRelayStatus, MobileRelayStatusDetail -} from '../../../../../../shared/remote-runtime/relay/mobile-relay-status' -import type { MobilePairingConnectionMode } from '../../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' +} from '../../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import { MobilePairingPathOption } from './MobilePairingPathOption' import { MobileRelaySignInPanel } from './MobileRelaySignInPanel' -import { relayClockSkewMessage } from '../../../mobile/relay-clock-skew-message' +import { relayClockSkewMessage } from '../relay-clock-skew-message' function relayStatusLabel(status: MobileRelayStatus, t: Translate = translate): string { if (status === 'registered') { diff --git a/src/renderer/src/components/settings/mobile/pairing/MobilePairingPathOption.tsx b/src/renderer/src/components/mobile/pairing/MobilePairingPathOption.tsx similarity index 100% rename from src/renderer/src/components/settings/mobile/pairing/MobilePairingPathOption.tsx rename to src/renderer/src/components/mobile/pairing/MobilePairingPathOption.tsx diff --git a/src/renderer/src/components/settings/mobile/pairing/MobileRelayBetaNotice.tsx b/src/renderer/src/components/mobile/pairing/MobileRelayBetaNotice.tsx similarity index 100% rename from src/renderer/src/components/settings/mobile/pairing/MobileRelayBetaNotice.tsx rename to src/renderer/src/components/mobile/pairing/MobileRelayBetaNotice.tsx diff --git a/src/renderer/src/components/settings/mobile/pairing/MobileRelaySignInPanel.tsx b/src/renderer/src/components/mobile/pairing/MobileRelaySignInPanel.tsx similarity index 89% rename from src/renderer/src/components/settings/mobile/pairing/MobileRelaySignInPanel.tsx rename to src/renderer/src/components/mobile/pairing/MobileRelaySignInPanel.tsx index 411ecee2484..0d5bc6cb610 100644 --- a/src/renderer/src/components/settings/mobile/pairing/MobileRelaySignInPanel.tsx +++ b/src/renderer/src/components/mobile/pairing/MobileRelaySignInPanel.tsx @@ -1,6 +1,6 @@ -import { useTranslate } from '../../../../i18n/use-translate' -import { useAppStore } from '../../../../store/index' -import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress' +import { useTranslate } from '../../../i18n/use-translate' +import { useAppStore } from '../../../store/index' +import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../OrcaSignInProgress' export function MobileRelaySignInPanel({ reconnectRequired diff --git a/src/renderer/src/components/settings/mobile/pairing/mobile-network-interface-selection.ts b/src/renderer/src/components/mobile/pairing/mobile-network-interface-selection.ts similarity index 81% rename from src/renderer/src/components/settings/mobile/pairing/mobile-network-interface-selection.ts rename to src/renderer/src/components/mobile/pairing/mobile-network-interface-selection.ts index 7a7d5c9af55..0a29a04dce3 100644 --- a/src/renderer/src/components/settings/mobile/pairing/mobile-network-interface-selection.ts +++ b/src/renderer/src/components/mobile/pairing/mobile-network-interface-selection.ts @@ -1,17 +1,12 @@ import { isVirtualBridgeInterface, - selectAutoAdvertisedPairingAddress -} from '../../../../../../shared/pairing-address-auto-selection' - -export type MobileNetworkInterface = { - name: string - address: string - hasDefaultRoute?: boolean -} + selectAutoAdvertisedPairingAddress, + type PairingNetworkInterface +} from '../../../../../shared/pairing-address-auto-selection' export function selectRefreshedNetworkAddress( currentAddress: string | undefined, - interfaces: readonly MobileNetworkInterface[], + interfaces: readonly PairingNetworkInterface[], // Preserve explicitly manual addresses through refresh instead of snapping to discovered tailnet/LAN defaults. currentAddressIsManual: boolean = false, currentAddressWasExplicitlySelected: boolean = false diff --git a/src/renderer/src/components/settings/mobile/pairing/mobile-pairing-device-polling.ts b/src/renderer/src/components/mobile/pairing/mobile-pairing-device-polling.ts similarity index 100% rename from src/renderer/src/components/settings/mobile/pairing/mobile-pairing-device-polling.ts rename to src/renderer/src/components/mobile/pairing/mobile-pairing-device-polling.ts diff --git a/src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts b/src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts index 6efc315133d..703cf2f115b 100644 --- a/src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts +++ b/src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts @@ -21,7 +21,7 @@ vi.mock('sonner', () => ({ })) // Disable polling to isolate the listDevices calls made directly by this hook. -vi.mock('../settings/mobile/pairing/mobile-pairing-device-polling', () => ({ +vi.mock('./pairing/mobile-pairing-device-polling', () => ({ useMobilePairingDevicePolling: (): void => {} })) diff --git a/src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts b/src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts index 6e8eb43bcf4..f301b3dca79 100644 --- a/src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts +++ b/src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts @@ -1,8 +1,9 @@ import { useCallback, useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react' import { toast } from 'sonner' import { useMountedRef } from '@/hooks/useMountedRef' -import { useMobilePairingDevicePolling } from '../settings/mobile/pairing/mobile-pairing-device-polling' -import type { PairedDevice, StepIndex } from './MobileHero' +import { useMobilePairingDevicePolling } from './pairing/mobile-pairing-device-polling' +import type { PairedMobileDevice } from './paired-mobile-devices' +import type { StepIndex } from './MobileHero' import { shouldShowPairedAfterDeviceRefresh, type MobilePageStage as FlowStage @@ -21,7 +22,7 @@ export function useMobilePagePairedDevices({ stepIdx: StepIndex setStepIdx: Dispatch> }): { - devices: readonly PairedDevice[] + devices: readonly PairedMobileDevice[] stage: FlowStage | null revokingDeviceIds: readonly string[] enterFlow: () => void @@ -74,7 +75,7 @@ export function useMobilePagePairedDevices({ opts: { force?: boolean } = {} - ): Promise => { + ): Promise => { try { const nextDevices = await refreshDevices(opts) if (mountedRef.current) { @@ -130,7 +131,7 @@ export function useMobilePagePairedDevices({ throw new Error('mobile.revokeDevice returned revoked=false') } // Once revoked, reload failure must still report success; remove from last-known devices rather than treating failed loading as an empty list. - let remaining: readonly PairedDevice[] + let remaining: readonly PairedMobileDevice[] try { remaining = await refreshDevices({ force: true }) } catch (err) { diff --git a/src/renderer/src/components/mobile/use-mobile-pairing-address-preference.ts b/src/renderer/src/components/mobile/use-mobile-pairing-address-preference.ts index 16b23ad2d42..0880e0fd313 100644 --- a/src/renderer/src/components/mobile/use-mobile-pairing-address-preference.ts +++ b/src/renderer/src/components/mobile/use-mobile-pairing-address-preference.ts @@ -1,9 +1,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { useAppStore } from '@/store' -import { - selectRefreshedNetworkAddress, - type MobileNetworkInterface -} from '../settings/mobile/pairing/mobile-network-interface-selection' +import { selectRefreshedNetworkAddress } from './pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../shared/pairing-address-auto-selection' import { useMobilePairingCustomAddress, useMobilePairingCustomAddresses @@ -23,7 +21,7 @@ export type MobilePairingAddressChange = { } export function useMobilePairingAddressPreference(args: { - networkInterfaces: readonly MobileNetworkInterface[] + networkInterfaces: readonly PairingNetworkInterface[] onSelectionInvalidated: (change: MobilePairingAddressChange) => void }): { selectedAddress: string | undefined @@ -32,7 +30,7 @@ export function useMobilePairingAddressPreference(args: { selectAddress: (address: string) => void selectCustomAddress: (address: string) => void removeCustomAddress: (address: string) => void - selectAddressAfterRefresh: (interfaces: readonly MobileNetworkInterface[]) => void + selectAddressAfterRefresh: (interfaces: readonly PairingNetworkInterface[]) => void } { const { networkInterfaces, onSelectionInvalidated } = args const updateSettings = useAppStore((state) => state.updateSettings) @@ -51,7 +49,7 @@ export function useMobilePairingAddressPreference(args: { const pendingCustomAddressWritesRef = useRef<(string | undefined)[]>([]) const selectAddressAfterRefresh = useCallback( - (interfaces: readonly MobileNetworkInterface[]): void => { + (interfaces: readonly PairingNetworkInterface[]): void => { const nextAddress = selectRefreshedNetworkAddress( selectedAddressRef.current, interfaces, diff --git a/src/renderer/src/components/native-chat/composer/controls/NativeChatComposerToolbar.test.tsx b/src/renderer/src/components/native-chat/composer/controls/NativeChatComposerToolbar.test.tsx deleted file mode 100644 index 2542a48748d..00000000000 --- a/src/renderer/src/components/native-chat/composer/controls/NativeChatComposerToolbar.test.tsx +++ /dev/null @@ -1,251 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { Editor, EditorContent } from '@tiptap/react' -import StarterKit from '@tiptap/starter-kit' -import { focusMountedNativeChatEditor } from '../editor/native-chat-mounted-editor-view' -import { TooltipProvider } from '@/components/ui/tooltip' -import { NativeChatComposerActions } from './NativeChatComposerActions' -import type { - SessionOptionDescriptor, - SessionOptionsSurface -} from '../../../../../../shared/native-chat/input/native-chat-session-options' - -vi.mock('@/i18n/use-ui-language-revision', () => ({ useUiLanguageRevision: () => 0 })) -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - Object.entries(values ?? {}).reduce( - (text, [key, value]) => text.replaceAll(`{{${key}}}`, value), - fallback - ) -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) - -afterEach(() => { - cleanup() - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -it('keeps current mode, permissions and Goal reachable through overflow, including pending writes, then restores direct controls', async () => { - let width = 140 - const observers = new Set<() => void>() - vi.stubGlobal( - 'ResizeObserver', - class { - constructor(callback: ResizeObserverCallback) { - observers.add(() => callback([], this)) - } - observe() {} - unobserve() {} - disconnect() {} - } - ) - vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function ( - this: HTMLElement - ) { - return this.hasAttribute('data-compact') ? width : 0 - }) - vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function ( - this: HTMLElement - ) { - const compact = this.closest('[data-compact]')?.getAttribute('data-compact') === 'true' - const sizes: Record = { - attach: [32, 32], - plan: [56, 26], - permissions: [112, 26], - goal: [54, 24], - model: [260, 26], - dictation: [32, 32], - cancel: [60, 60] - } - const id = this.dataset.composerControl - const measured = id - ? (sizes[id]?.[Number(compact)] ?? 0) - : this.querySelector('button[aria-label="More chat controls"]') - ? 24 - : 48 - return { - x: 0, - y: 0, - width: measured, - height: 24, - top: 0, - left: 0, - bottom: 24, - right: measured, - toJSON() {} - } - }) - let settle = () => {} - const setOption = vi.fn().mockImplementation( - () => - new Promise((resolve) => { - settle = () => resolve({ snapshot: [] }) - }) - ) - const surface: SessionOptionsSurface = { - getSnapshot: () => [], - setOption, - invokeAction: async () => ({ snapshot: [] }), - subscribe: () => () => {} - } - const snapshot: SessionOptionDescriptor[] = [ - { - id: 'model', - label: 'Model', - category: 'model', - transport: 'agent-session', - valueSource: 'applied', - settable: true, - kind: { - type: 'select', - currentValue: 'first', - choices: [ - { value: 'first', label: 'Long provider model' }, - { value: 'second', label: 'Second model' } - ] - } - }, - { - id: 'interactionMode', - label: 'Mode', - category: 'mode', - transport: 'agent-session', - valueSource: 'applied', - settable: true, - kind: { - type: 'select', - currentValue: 'plan', - choices: [ - { value: 'default', label: 'Build' }, - { value: 'plan', label: 'Plan' } - ] - } - }, - { - id: 'permissionMode', - label: 'Permissions', - transport: 'agent-session', - valueSource: 'applied', - settable: true, - kind: { - type: 'select', - currentValue: 'full-access', - choices: [ - { value: 'ask', label: 'Ask' }, - { value: 'full-access', label: 'Full access' } - ] - } - } - ] - const exitGoal = vi.fn() - const editor = new Editor({ - extensions: [StarterKit], - editorProps: { attributes: { role: 'textbox', 'aria-label': 'Chat message' } } - }) - const focus = () => focusMountedNativeChatEditor(editor) - const resize = (next: number) => { - width = next - act(() => observers.forEach((observer) => observer())) - } - const view = render( - - - - - - ) - fireEvent.click(screen.getByRole('button', { name: 'More chat controls' })) - const partial = screen.getByRole('dialog') - const menuMode = within(partial).getByRole('button', { name: 'Exit plan mode' }) - const menuPermission = within(partial).getByRole('button', { name: 'Permissions Full access' }) - menuPermission.focus() - resize(1000) - expect(within(partial).getByRole('button', { name: 'Exit plan mode' })).toBe(menuMode) - expect(within(partial).getByRole('button', { name: 'Permissions Full access' })).toBe( - menuPermission - ) - expect(document.activeElement).toBe(menuPermission) - fireEvent.click(screen.getByRole('button', { name: 'More chat controls' })) - await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) - await waitFor(() => - expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Chat message' })) - ) - resize(100) - fireEvent.click(screen.getByRole('button', { name: 'More chat controls' })) - resize(1000) - const outside = screen.getByRole('textbox', { name: 'Outside composer' }) - fireEvent.pointerDown(outside) - outside.focus() - await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) - expect(document.activeElement).toBe(outside) - resize(100) - fireEvent.click(screen.getByRole('button', { name: 'More chat controls' })) - const popup = screen.getByRole('dialog') - await act(async () => - fireEvent.click(within(popup).getByRole('button', { name: 'Exit plan mode' })) - ) - expect(setOption).toHaveBeenLastCalledWith('interactionMode', 'default') - await waitFor(() => - expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Chat message' })) - ) - fireEvent.click(screen.getByRole('button', { name: 'More chat controls' })) - expect( - within(screen.getByRole('dialog')).getByRole('button', { name: 'Exit plan mode' }) - ).toHaveProperty('disabled', true) - await act(async () => settle()) - const permission = within(screen.getByRole('dialog')).getByRole('button', { - name: 'Permissions Full access' - }) - fireEvent.pointerDown(permission, { button: 0, ctrlKey: false }) - await act(async () => fireEvent.click(screen.getByRole('menuitemradio', { name: /Ask/ }))) - expect(setOption).toHaveBeenLastCalledWith('permissionMode', 'ask') - await act(async () => settle()) - fireEvent.click( - within(screen.getByRole('dialog')).getByRole('button', { name: 'Exit goal mode' }) - ) - expect(exitGoal).toHaveBeenCalledOnce() - resize(1000) - const buttons = screen - .getAllByRole('button') - .map((button) => button.getAttribute('aria-label') ?? button.textContent) - expect(buttons.slice(0, 4)).toEqual([ - 'Attach file', - 'Permissions Full access', - 'Exit plan mode', - 'Exit goal mode' - ]) - expect(screen.queryByRole('button', { name: 'More chat controls' })).toBeNull() - const model = screen.getByRole('button', { name: 'Model Long provider model' }) - fireEvent.click(model) - const modelPopup = screen.getByRole('dialog') - resize(50) - expect(screen.getByRole('button', { name: 'Model Long provider model' })).toBe(model) - expect(screen.getByRole('dialog')).toBe(modelPopup) - fireEvent.click(within(modelPopup).getByRole('option', { name: /Second model/ })) - expect(setOption).toHaveBeenLastCalledWith('model', 'second') - resize(1000) - expect(screen.getByRole('dialog')).toBe(modelPopup) - expect(screen.getByRole('button', { name: 'Model Second model' })).toBe(model) - await act(async () => settle()) - view.unmount() - editor.destroy() -}) diff --git a/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-input.ts b/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-input.ts index 6d83e8399e1..a551b5c7a34 100644 --- a/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-input.ts +++ b/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-input.ts @@ -1,5 +1,6 @@ import type { OrchestrationAgentReference } from '../../../../../../shared/orchestration/mailbox/orchestration-agent-reference' import type { HTMLAttributes, RefObject } from 'react' +import { linkedSelectionText } from '../../paste/native-chat-pasted-links' /** Text coordinates keep transport, attachments, and picker logic independent of the editor. */ export type NativeChatComposerInput = Pick< @@ -52,7 +53,12 @@ export function insertNativeChatPastedText( } // A paste routed from a hidden terminal or a transcript click must leave the caret in the composer. input.focus() - input.insertText(text) + const { selectionStart, selectionEnd } = input + const linked = + selectionStart !== null && selectionEnd !== null && selectionStart < selectionEnd + ? linkedSelectionText(input.value.slice(selectionStart, selectionEnd), text) + : null + input.insertText(linked ?? text) return true } diff --git a/src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.ts b/src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.ts index f480896f9cf..4ac26b9e9d3 100644 --- a/src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.ts +++ b/src/renderer/src/components/native-chat/messages/actions/native-chat-fork-launch.ts @@ -1,3 +1,5 @@ +import { agentSessionForkSourceFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-copy' +import { sayAgentSessionFailureTranslated } from '../notices/agent-session-failure-words-text' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' @@ -28,6 +30,8 @@ export type NativeChatForkRequest = { worktreeId: string target: RuntimeClientTarget forkFrom: StructuredAgentSessionForkSource + /** Client-only admission requirement; reacquired from the child after reload. */ + forkRequiresInheritedOriginal?: boolean surfaceAddress: StructuredLaunchSurfaceAddress } @@ -79,6 +83,7 @@ export async function launchNativeChatFork( requestId: newAgentLaunchRequestId(), executionHostId: executionHostIdFor(request.target), forkFrom: request.forkFrom, + forkRequiresInheritedOriginal: request.forkRequiresInheritedOriginal, // A side chat is selected once it sits beside its source. activate: request.side === undefined, surfaceAddress: request.surfaceAddress, @@ -200,6 +205,17 @@ function forkFailureDetail(agentLabel: string, error: unknown): string { if (code === 'structured_agent_session_host_permission') { return hostPermissionRefusedText(agentLabel, 'refused') } + const sourceFailure = + error instanceof StructuredAgentSessionCreateRefusalError + ? agentSessionForkSourceFailureWords( + error.message, + agentLabel, + sayAgentSessionFailureTranslated + ) + : null + if (sourceFailure) { + return sourceFailure + } const causeText = structuredLaunchFailure(error)?.causeText if (causeText) { return causeText diff --git a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts index 933d312caae..50fe5836ab7 100644 --- a/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts +++ b/src/renderer/src/components/native-chat/messages/actions/native-chat-side-chat-fork-point.test.ts @@ -1,9 +1,61 @@ -import { describe, expect, it } from 'vitest' +// @vitest-environment happy-dom +import { act, createElement } from 'react' +import { renderHook } from '@testing-library/react' +import { + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY +} from '../../../../../../shared/agent-session/agent-session-create-capabilities' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' +import { useAppStore } from '@/store' +import { runtimeEnvironmentStatusFromSnapshot } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' +import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' +import { launchNativeChatFork } from './native-chat-fork-launch' +import { useNativeChatFork } from './use-native-chat-fork' +import { useNativeChatSideChatForkOffer } from './use-native-chat-side-chat' +import { + NativeChatForkContext, + NativeChatSideChatForkPointContext +} from './native-chat-fork-context' +import { + nativeChatRowOffersFork, + nativeChatForkInventory +} from '../../../../../../shared/native-chat/native-chat-fork-offer' +import { describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' import type { NativeChatTranscriptSlotsInput } from '../../conversation/slots/native-chat-transcript-input' import { buildNativeChatTranscript } from '../../conversation/slots/native-chat-transcript-slots' +const host = vi.hoisted( + (): { + capabilities: Set + contacts: Set<() => void> + } => ({ + capabilities: new Set(), + contacts: new Set<() => void>() + }) +) +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ + runtimeEnvironmentSupportsCapability: (_environmentId: string, capability: string) => + Promise.resolve(host.capabilities.has(capability)) +})) +vi.mock('@/runtime/hosts/connections/runtime-host-contact-regained', () => ({ + subscribeRuntimeHostContactRegained: (_environmentId: string, listener: () => void) => { + host.contacts.add(listener) + return () => host.contacts.delete(listener) + } +})) +vi.mock('@/runtime/native-chat/agent-catalogs/use-host-structured-agent', () => ({ + useHostStructuredAgent: () => ({ capabilities: { fork: 'tip' } }) +})) +vi.mock('@/components/native-chat/messages/actions/native-chat-fork-launch', () => ({ + launchNativeChatFork: vi.fn(), + nativeChatForkSurfaceAddress: vi.fn() +})) +vi.mock('@/components/native-chat/messages/actions/native-chat-side-chat-placement', () => ({ + beginNativeChatSideChatPlacement: vi.fn() +})) + function row(id: string, role: 'user' | 'assistant', sequence: number): NativeChatMessage { return { id, @@ -91,3 +143,256 @@ describe('the side chat fork point the transcript finds while laying out', () => ).toEqual({ kind: 'no-reply' }) }) }) + +it('offers inherited ancestor replies in a fork of a fork while the child is running', () => { + const { input, latestTurnKey } = conversation( + [ + { ask: 'older-user', replies: [row('legacy:opencode:source:reply-0', 'assistant', 1)] }, + { + ask: 'inherited-user', + replies: [row('legacy:opencode:parent-fork:reply-1', 'assistant', 3)] + }, + { ask: 'own-user', replies: [row('legacy:opencode:child:reply-2', 'assistant', 6)] } + ], + true + ) + const inventory = nativeChatForkInventory([ + { + itemId: 'legacy:opencode:source:reply-0', + sequence: 1, + body: { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'older copied reply' }] + } + }, + { + itemId: 'legacy:opencode:parent-fork:reply-1', + sequence: 3, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'copied' }] } + }, + { + itemId: 'orca:forked-from', + sequence: 4, + body: { kind: 'status', text: 'Forked from source', presentation: 'forked-from' } + }, + { + itemId: 'legacy:opencode:child:reply-2', + sequence: 6, + body: { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'local partial' }] + } + } + ]) + const chat = { + support: { kind: 'known', fork: 'tip', inheritedOriginal: true }, + contextFloorSequence: 0, + ...inventory + } as const + const olderRow = { + message: row('legacy:opencode:source:reply-0', 'assistant', 1), + inSubagentSection: false, + turnWorking: false, + inLatestTurn: false + } + expect(nativeChatRowOffersFork(olderRow, chat)).toBe(true) + expect( + nativeChatRowOffersFork(olderRow, { + ...chat, + support: { kind: 'known', fork: 'tip' } + }) + ).toBe(false) + // Checkpoint providers still offer earlier inherited replies without original-tip support. + expect( + nativeChatRowOffersFork(olderRow, { + ...chat, + support: { kind: 'known', fork: 'checkpoint' } + }) + ).toBe(true) + expect( + buildNativeChatTranscript({ + ...input, + forkOffer: { chat: { ...chat, support: { kind: 'known', fork: 'tip' } }, latestTurnKey } + }).forkPoint + ).toEqual({ kind: 'reply-running' }) + expect( + buildNativeChatTranscript({ ...input, forkOffer: { chat, latestTurnKey } }).forkPoint + ).toEqual({ kind: 'ready', throughItemId: 'legacy:opencode:parent-fork:reply-1' }) + expect( + buildNativeChatTranscript({ + ...input, + forkOffer: { chat: { ...chat, contextFloorSequence: 4 }, latestTurnKey } + }).forkPoint + ).toEqual({ kind: 'reply-running' }) +}) + +it('carries current target-host proof into desktop response and side-chat offers', async () => { + const copied = row('legacy:opencode:source:reply-1', 'assistant', 1) + const own = row('legacy:opencode:child:reply-2', 'assistant', 4) + const { input, latestTurnKey } = conversation( + [ + { ask: 'inherited-user', replies: [copied] }, + { ask: 'own-user', replies: [own] } + ], + true + ) + const items: AgentJournalRenderItem[] = [ + { + itemId: 'inherited-user', + sequence: 0, + revision: 1, + observedAt: 0, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { + itemId: copied.id, + sequence: 1, + revision: 1, + observedAt: 1, + body: { kind: 'message', role: 'assistant', blocks: copied.blocks } + }, + { + itemId: 'orca:forked-from', + sequence: 1, + revision: 1, + observedAt: 1, + body: { kind: 'status', presentation: 'forked-from', text: 'Forked from source' } + }, + { + itemId: 'own-user', + sequence: 3, + revision: 1, + observedAt: 3, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { + itemId: own.id, + sequence: 4, + revision: 1, + observedAt: 4, + body: { kind: 'message', role: 'assistant', blocks: own.blocks } + } + ] + host.capabilities = new Set([AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY]) + publishStatus('verified') + const pane = renderHook(() => + useNativeChatFork({ + sessionId: 'child', + tabId: 'tab', + agent: 'opencode', + target: { kind: 'environment', environmentId: 'paired-host' }, + worktreeId: 'workspace', + items, + epoch: 'epoch', + contextFloor: undefined, + sessionForkSupport: 'supported' + }) + ) + await act(async () => {}) + const responseOffered = () => + nativeChatRowOffersFork( + { + message: copied, + inSubagentSection: false, + turnWorking: false, + inLatestTurn: false + }, + { ...pane.result.current!, support: pane.result.current!.rowAction.support } + ) + const side = renderHook(() => useNativeChatSideChatForkOffer(latestTurnKey), { + wrapper: ({ children }) => + createElement( + NativeChatForkContext.Provider, + { value: pane.result.current }, + createElement(NativeChatSideChatForkPointContext.Provider, { value: () => {} }, children) + ) + }) + const sidePoint = () => + buildNativeChatTranscript({ + ...input, + forkOffer: side.result.current + }).forkPoint + expect(responseOffered()).toBe(false) + expect(sidePoint()).toEqual({ kind: 'reply-running' }) + + host.capabilities.add(AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY) + await act(async () => { + publishStatus('verified') + host.contacts.forEach((listener) => listener()) + }) + side.rerender() + expect(responseOffered()).toBe(true) + expect(sidePoint()).toEqual({ kind: 'ready', throughItemId: 'legacy:opencode:source:reply-1' }) + + await act(async () => publishStatus('checking')) + side.rerender() + expect(responseOffered()).toBe(false) + expect(sidePoint()).toEqual({ kind: 'reply-running' }) + expect( + nativeChatRowOffersFork( + { message: own, inSubagentSection: false, turnWorking: false, inLatestTurn: true }, + pane.result.current! + ) + ).toBe(true) + await act(async () => publishStatus('unavailable')) + side.rerender() + expect(responseOffered()).toBe(false) + await act(async () => publishStatus('verified')) + side.rerender() + expect(responseOffered()).toBe(true) + expect(sidePoint()).toEqual({ kind: 'ready', throughItemId: 'legacy:opencode:source:reply-1' }) + + vi.mocked(launchNativeChatFork).mockResolvedValue({}) + await act(async () => { + await pane.result.current!.rowAction.request(copied.id, { question: 'Explain' }) + }) + expect(launchNativeChatFork).toHaveBeenLastCalledWith( + expect.objectContaining({ + forkFrom: { sessionId: 'child', throughItemId: 'legacy:opencode:source:reply-1' }, + forkRequiresInheritedOriginal: true, + side: { question: 'Explain' } + }) + ) + await act(async () => { + await pane.result.current!.rowAction.request(own.id) + }) + expect(launchNativeChatFork).toHaveBeenLastCalledWith( + expect.objectContaining({ forkRequiresInheritedOriginal: false }) + ) + + host.capabilities.delete(AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY) + await act(async () => { + publishStatus('verified') + host.contacts.forEach((listener) => listener()) + }) + side.rerender() + expect(responseOffered()).toBe(false) + expect(sidePoint()).toEqual({ kind: 'reply-running' }) +}) + +function publishStatus(verification: 'verified' | 'checking' | 'unavailable') { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only runtime identity/capabilities are read by these hooks. + const status = { runtimeId: 'runtime-a', capabilities: [...host.capabilities] } as RuntimeStatus + useAppStore.setState({ + runtimeStatusByEnvironmentId: new Map([ + [ + 'paired-host', + { + ...runtimeEnvironmentStatusFromSnapshot({ + environmentId: 'paired-host', + pairingRevision: 1, + sequence: 1, + checkedAt: 1, + status, + verification, + transport: verification === 'verified' ? 'ready' : 'disconnected' + }), + connectionGeneration: 1, + hostContactEpoch: 1 + } + ] + ]) + }) +} diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.ts b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.ts index f49740fbd96..22bb4c38b14 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.ts +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-fork.ts @@ -1,19 +1,27 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useHostStructuredAgent } from '@/runtime/native-chat/agent-catalogs/use-host-structured-agent' import { useStructuredAgentSessionHostCapabilityState } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-capability' -import { AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-create-capabilities' +import { + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY +} from '../../../../../../shared/agent-session/agent-session-create-capabilities' import { agentSessionContextFloorSequence, latestAgentSessionContextClearSequence } from '../../../../../../shared/agent-session/agent-session-context-clear' import type { AgentJournalCursor } from '../../../../../../shared/agent-session/journal/agent-session-journal-identity' -import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionLatestTurn } from '../../../../../../shared/agent-session/agent-session-wire' +import type { + AgentJournalSubmission, + AgentJournalRenderItem +} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { AgentSessionOptionsResult } from '../../../../../../shared/agent-session/options/agent-session-options-result' import type { AgentType } from '../../../../../../shared/agent-status/contracts/agent-status-types' import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import { - nativeChatForkableItemIds, + nativeChatForkInventory, + nativeChatForkRequiresInheritedOriginal, nativeChatForkSupport, nativeChatLatestForkItemId, type NativeChatForkSupport @@ -49,6 +57,7 @@ export type NativeChatForkLatestOutcome = 'started' | 'pending' | 'none' export type NativeChatForkSurface = NativeChatForkRowAction & { contextFloorSequence: number forkableItemIds: ReadonlySet + inheritedThroughSequence?: number /** Handed to offered rows, so a change in which rows offer it re-renders only those rows. */ rowAction: NativeChatForkRowAction } @@ -66,6 +75,8 @@ export function useNativeChatFork(input: { target: RuntimeClientTarget worktreeId: string | null items: readonly AgentJournalRenderItem[] + submissions?: readonly AgentJournalSubmission[] + latestTurn?: AgentSessionLatestTurn | null epoch: string | null contextFloor: AgentJournalCursor | undefined /** The chat's options read on its installed agent; the host's own discovery owns it. */ @@ -75,11 +86,21 @@ export function useNativeChatFork(input: { input.target, AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY ) + const inheritedOriginalHost = useStructuredAgentSessionHostCapabilityState( + input.target, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY, + true + ) const registered = useHostStructuredAgent(input.target, input.agent) - const support = nativeChatForkSupport(host, registered, input.sessionForkSupport) - const latest = useRef(input) + const support = nativeChatForkSupport( + host, + registered, + input.sessionForkSupport, + inheritedOriginalHost + ) + const latest = useRef({ ...input, support }) useLayoutEffect(() => { - latest.current = input + latest.current = { ...input, support } }) // Reserved at the click, before any await, so a second click never starts a second fork. const inFlight = useRef(false) @@ -102,6 +123,18 @@ export function useNativeChatFork(input: { worktreeId, target, forkFrom: { sessionId, throughItemId }, + forkRequiresInheritedOriginal: + latest.current.support.kind === 'known' + ? nativeChatForkRequiresInheritedOriginal( + latest.current.items, + latest.current.support.fork, + throughItemId, + { + submissions: latest.current.submissions ?? [], + latestTurn: latest.current.latestTurn + } + ) + : undefined, surfaceAddress: nativeChatForkSurfaceAddress(worktreeId, tabId), ...(side ? { side } : {}) }) @@ -122,13 +155,15 @@ export function useNativeChatFork(input: { // Streaming replaces the items array on every commit; keep the set while its members hold, so the // context and every offered row's `fork` stay the same objects. const forkableRef = useRef>(new Set()) + const inventory = useMemo(() => nativeChatForkInventory(input.items), [input.items]) + const { inheritedThroughSequence } = inventory const forkableItemIds = useMemo(() => { - const next = nativeChatForkableItemIds(input.items) + const next = inventory.forkableItemIds const previous = forkableRef.current return next.size === previous.size && [...next].every((id) => previous.has(id)) ? previous : next - }, [input.items]) + }, [inventory]) useLayoutEffect(() => { forkableRef.current = forkableItemIds }, [forkableItemIds]) @@ -142,7 +177,7 @@ export function useNativeChatFork(input: { latestAgentSessionContextClearSequence(items), agentSessionContextFloorSequence(contextFloor, epoch) ), - forkableItemIds: nativeChatForkableItemIds(items) + forkableItemIds: nativeChatForkInventory(items).forkableItemIds }) if (!throughItemId) { return 'none' @@ -152,23 +187,32 @@ export function useNativeChatFork(input: { }, [request]) const supportKind = support.kind const fork = support.kind === 'known' ? support.fork : undefined + const inheritedOriginal = support.kind === 'known' && support.inheritedOriginal === true const rowAction = useMemo( () => ({ - support: fork ? { kind: 'known', fork } : { kind: 'unknown' }, + support: fork ? { kind: 'known', fork, inheritedOriginal } : { kind: 'unknown' }, pendingItemId, request }), - [fork, pendingItemId, request] + [fork, inheritedOriginal, pendingItemId, request] ) return useMemo( () => supportKind === 'none' || !input.worktreeId || !isTuiAgent(input.agent) ? undefined - : { ...rowAction, contextFloorSequence, forkableItemIds, rowAction, forkLatest }, + : { + ...rowAction, + contextFloorSequence, + forkableItemIds, + inheritedThroughSequence, + rowAction, + forkLatest + }, [ contextFloorSequence, forkableItemIds, forkLatest, + inheritedThroughSequence, input.agent, input.worktreeId, rowAction, @@ -188,6 +232,8 @@ export function useNativeChatPaneFork( pane: Pick, chat: { journalItems: readonly AgentJournalRenderItem[] + submissions?: readonly AgentJournalSubmission[] + latestTurn?: AgentSessionLatestTurn | null epoch: string | null contextFloor: AgentJournalCursor | undefined forkSupport: AgentSessionOptionsResult['forkSupport'] @@ -201,6 +247,8 @@ export function useNativeChatPaneFork( target: pane.target, worktreeId, items: chat.journalItems, + submissions: chat.submissions, + latestTurn: chat.latestTurn, epoch: chat.epoch, contextFloor: chat.contextFloor, sessionForkSupport: chat.forkSupport diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx index 97f93abe0c5..6f87e672eef 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx @@ -99,6 +99,27 @@ describe('structured chat rewind', () => { expect([...(view.result.current.surface?.eligibleItemIds ?? [])]).toEqual(['later']) }) + it('offers rewind only below the fork divider', async () => { + const props = input() + const marker: AgentJournalRenderItem = { + ...item('orca:forked-from', 11), + body: { + kind: 'status', + presentation: 'forked-from', + text: 'Forked from Original', + forkedFrom: { sessionId: 'original' } + } + } + const view = render({ + ...props, + state: { ...props.state, items: [...props.state.items, marker] } + }) + expect([...(view.result.current.surface?.eligibleItemIds ?? [])]).toEqual(['later']) + const confirm = vi.fn().mockResolvedValue(true) + await act(() => view.result.current.request('user', confirm)) + expect(confirm).not.toHaveBeenCalled() + }) + it('awaits the suffix sequence in the same epoch before unblocking', async () => { const props = input() props.send.mockResolvedValue({ diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-side-chat.ts b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-side-chat.ts index 336c5fb3fb5..5b713eed9c6 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-side-chat.ts +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-side-chat.ts @@ -71,17 +71,33 @@ export function useNativeChatSideChatForkOffer( const fork = useContext(NativeChatForkContext) const listening = useContext(NativeChatSideChatForkPointContext) !== undefined const mode = fork?.support.kind === 'known' ? fork.support.fork : undefined + const inheritedOriginal = + fork?.support.kind === 'known' && fork.support.inheritedOriginal === true const forkableItemIds = fork?.forkableItemIds const contextFloorSequence = fork?.contextFloorSequence + const inheritedThroughSequence = fork?.inheritedThroughSequence return useMemo( () => listening && mode && forkableItemIds && contextFloorSequence !== undefined ? { - chat: { support: { kind: 'known', fork: mode }, contextFloorSequence, forkableItemIds }, + chat: { + support: { kind: 'known', fork: mode, inheritedOriginal }, + contextFloorSequence, + forkableItemIds, + inheritedThroughSequence + }, latestTurnKey } : undefined, - [contextFloorSequence, forkableItemIds, latestTurnKey, listening, mode] + [ + contextFloorSequence, + forkableItemIds, + inheritedThroughSequence, + inheritedOriginal, + latestTurnKey, + listening, + mode + ] ) } diff --git a/src/renderer/src/components/native-chat/messages/notices/agent-session-availability-words-text.ts b/src/renderer/src/components/native-chat/messages/notices/agent-session-availability-words-text.ts index 828cc3c9a56..994d8ce427e 100644 --- a/src/renderer/src/components/native-chat/messages/notices/agent-session-availability-words-text.ts +++ b/src/renderer/src/components/native-chat/messages/notices/agent-session-availability-words-text.ts @@ -7,6 +7,12 @@ import { type AvailabilityCopyId = Extract< AgentSessionFailureCopyId, + | 'forkOriginalMissing' + | 'forkOriginalUnavailable' + | 'forkOriginalMissingNamed' + | 'forkOriginalUnavailableNamed' + | 'forkOriginalLatestOnly' + | 'forkOriginalLatestOnlyNamed' | 'claudeSystemNotSignedIn' | 'claudeManagedNotSignedIn' | 'codexSystemNotSignedIn' @@ -29,6 +35,42 @@ export const AVAILABILITY_PIECES: Record< AvailabilityCopyId, (values: AgentSessionFailureCopyValues) => string > = { + forkOriginalMissing: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalMissing', + COPY.forkOriginalMissing, + values + ), + forkOriginalUnavailable: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalUnavailable', + COPY.forkOriginalUnavailable, + values + ), + forkOriginalMissingNamed: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalMissingNamed', + COPY.forkOriginalMissingNamed, + values + ), + forkOriginalUnavailableNamed: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalUnavailableNamed', + COPY.forkOriginalUnavailableNamed, + values + ), + forkOriginalLatestOnly: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalLatestOnly', + COPY.forkOriginalLatestOnly, + values + ), + forkOriginalLatestOnlyNamed: (values) => + translate( + 'components.native-chat.failureWords.forkOriginalLatestOnlyNamed', + COPY.forkOriginalLatestOnlyNamed, + values + ), agentCommandNotSignedIn: (values) => translate( 'components.native-chat.failureWords.agentCommandNotSignedIn', diff --git a/src/renderer/src/components/native-chat/paste/native-chat-clipboard-payload.ts b/src/renderer/src/components/native-chat/paste/native-chat-clipboard-payload.ts index 92dbddcb5be..f0997e84537 100644 --- a/src/renderer/src/components/native-chat/paste/native-chat-clipboard-payload.ts +++ b/src/renderer/src/components/native-chat/paste/native-chat-clipboard-payload.ts @@ -1,5 +1,9 @@ import { isMacPlatform } from '../pane/routing/native-chat-shortcut' -import { textOnlyLabelsCopiedFiles } from '../../../../../shared/native-chat/input/native-chat-clipboard-event' +import { + clipboardEventPromptText, + textOnlyLabelsCopiedFiles +} from '../../../../../shared/native-chat/input/native-chat-clipboard-event' +import { withPastedLinks } from './native-chat-pasted-links' /** Accept native pane clipboard events and React synthetic events. */ export type ClipboardEventLike = { @@ -33,6 +37,17 @@ export function clipboardEventCopiedFilePaths(event: ClipboardEventLike): string return copiesOnlyFiles(event.clipboardData?.getData('text/plain') ?? '', paths) ? paths : [] } +/** The event's prompt text, with any rich-text links kept as Markdown. */ +export function clipboardEventPastedText( + event: ClipboardEventLike, + attachingFile: boolean +): string { + return withPastedLinks( + clipboardEventPromptText(event, attachingFile), + event.clipboardData?.getData('text/html') + ) +} + function copiesOnlyFiles(text: string, filePaths: readonly string[]): boolean { return filePaths.length > 0 && (text === '' || textOnlyLabelsCopiedFiles(text, filePaths)) } @@ -42,13 +57,15 @@ export async function readClipboardPasteText( maxBytes: number, eventFilePaths?: string[] ): Promise<{ text: string; copiedFilePaths: string[] }> { - const [text, filePaths] = await Promise.all([ + const [text, filePaths, linkHtml] = await Promise.all([ window.api.ui.readClipboardText({ maxBytes }), // Without the file list the text is typed as-is. - eventFilePaths ?? window.api.ui.readClipboardFilePaths().catch(() => []) + eventFilePaths ?? window.api.ui.readClipboardFilePaths().catch(() => []), + // Links are optional: a failed HTML read still pastes the text. + (async () => window.api.ui.readClipboardLinkHtml())().catch(() => '') ]) if (!copiesOnlyFiles(text, filePaths)) { - return { text, copiedFilePaths: [] } + return { text: withPastedLinks(text, linkHtml), copiedFilePaths: [] } } // macOS lists a screenshot tool's saved file beside its picture; only Finder also names files. const picture = text === '' && isMacPlatform() && (await window.api.ui.clipboardHasImage()) diff --git a/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.test.ts b/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.test.ts new file mode 100644 index 00000000000..11eb52f9896 --- /dev/null +++ b/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.test.ts @@ -0,0 +1,34 @@ +// @vitest-environment happy-dom +import { describe, expect, it } from 'vitest' +import { linkedSelectionText, withPastedLinks } from './native-chat-pasted-links' + +describe('withPastedLinks', () => { + it('keeps rich-text links as Markdown around the plain text', () => { + const html = + '

Hey can you take a look at this\n FR and [the] docs?

' + expect(withPastedLinks('Hey can you take a look at this FR and [the] docs?', html)).toBe( + 'Hey can you take a look at [this FR](https://github.com/stablyai/orca/issues/39150) and [\\[the\\] docs](https://example.com/a%28b%29)?' + ) + }) + + it('leaves bare URLs, unsafe schemes and existing Markdown alone', () => { + const html = + 'https://example.com/ run x' + const text = 'https://example.com/ run [x](https://x.dev)' + expect(withPastedLinks(text, html)).toBe(text) + }) +}) + +describe('linkedSelectionText', () => { + it('links the selected words to a pasted URL', () => { + expect(linkedSelectionText('external links', ' https://example.com\n')).toBe( + '[external links](https://example.com)' + ) + }) + + it('replaces instead when the selection or paste is not a word-to-URL pair', () => { + expect(linkedSelectionText('https://old.dev', 'https://new.dev')).toBeNull() + expect(linkedSelectionText('two\nlines', 'https://new.dev')).toBeNull() + expect(linkedSelectionText('words', 'see https://new.dev')).toBeNull() + }) +}) diff --git a/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.ts b/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.ts new file mode 100644 index 00000000000..fda7e216ae2 --- /dev/null +++ b/src/renderer/src/components/native-chat/paste/native-chat-pasted-links.ts @@ -0,0 +1,102 @@ +import { clipboardHtmlMayHaveLinks } from '../../../../../shared/clipboard-link-html' + +const LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']) +// A page dump with more links than this pastes as plain text rather than paying a long scan. +const MAX_PASTED_LINKS = 256 + +function linkUrl(href: string): URL | null { + try { + const url = new URL(href) + return LINK_PROTOCOLS.has(url.protocol) ? url : null + } catch { + return null + } +} + +function markdownLink(label: string, href: string): string { + const escapedLabel = label.replace(/[\\[\]]/g, '\\$&') + const destination = href.replace( + /[\s()]/g, + (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}` + ) + return `[${escapedLabel}](${destination})` +} + +const WORD_CHAR = /[\p{L}\p{N}_]/u +// Total characters label searches may pass over in one paste; short labels that only occur inside words would otherwise rescan the text per anchor. +const MAX_SEARCHED_CHARS = 2 * 1024 * 1024 + +/** The label's next whole-word occurrence, so a short label cannot land inside a longer word. */ +function findLabel(text: string, label: string, from: number, budget: { left: number }): number { + const startsWord = WORD_CHAR.test(label[0]) + const endsWord = WORD_CHAR.test(label.at(-1) ?? '') + for (let start = from; budget.left > 0;) { + const at = text.indexOf(label, start) + budget.left -= (at === -1 ? text.length : at + 1) - start + if (at === -1) { + return -1 + } + const end = at + label.length + if ( + !(startsWord && at > 0 && WORD_CHAR.test(text[at - 1])) && + !(endsWord && end < text.length && WORD_CHAR.test(text[end])) + ) { + return at + } + start = at + 1 + } + return -1 +} + +/** Rich-text copies keep their links as Markdown; the plain text otherwise stays as the source wrote it. */ +export function withPastedLinks(text: string, html: string | null | undefined): string { + if (!text || !html || !clipboardHtmlMayHaveLinks(html)) { + return text + } + const anchors = new DOMParser().parseFromString(html, 'text/html').querySelectorAll('a[href]') + if (anchors.length > MAX_PASTED_LINKS) { + return text + } + let result = '' + let cursor = 0 + const budget = { left: MAX_SEARCHED_CHARS } + for (const anchor of anchors) { + if (budget.left <= 0) { + break + } + const label = (anchor.textContent ?? '').replace(/\s+/g, ' ').trim() + const at = label ? findLabel(text, label, cursor, budget) : -1 + if (at === -1) { + continue + } + const end = at + label.length + const href = anchor.getAttribute('href')?.trim() ?? '' + const url = linkUrl(href) + // Unlinked anchors still advance the cursor, so a later label cannot match inside them. + const linked = + url && + label !== href && + label !== url.href && + `mailto:${label}` !== href && + // The plain flavor may already carry Markdown links. + !(text[at - 1] === '[' && text.startsWith('](', end)) + result += text.slice(cursor, at) + (linked ? markdownLink(label, href) : label) + cursor = end + } + return result + text.slice(cursor) +} + +/** Pasting one URL over selected words links them, as most message editors do. */ +export function linkedSelectionText(selected: string, pasted: string): string | null { + const href = pasted.trim() + if ( + !selected.trim() || + /[\r\n]/.test(selected) || + /\s/.test(href) || + !linkUrl(href) || + linkUrl(selected.trim()) + ) { + return null + } + return markdownLink(selected, href) +} diff --git a/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.ts b/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.ts index dfa24f839d4..9f5f76c6efd 100644 --- a/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.ts +++ b/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.ts @@ -8,13 +8,11 @@ import { NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES } from './native-chat-context-paste import { isMacPlatform } from '../pane/routing/native-chat-shortcut' import { clipboardEventCopiedFilePaths, + clipboardEventPastedText, readClipboardPasteText, type ClipboardEventLike } from './native-chat-clipboard-payload' -import { - clipboardEventImageFile, - clipboardEventPromptText -} from '../../../../../shared/native-chat/input/native-chat-clipboard-event' +import { clipboardEventImageFile } from '../../../../../shared/native-chat/input/native-chat-clipboard-event' import { nativeChatLocalAttachmentUnsupportedNotice, nativeChatWorktreeNotReadyNotice @@ -133,7 +131,7 @@ export function useNativeChatComposerPaste({ const copiedFilePaths = clipboardEventCopiedFilePaths(event) const copiesFiles = copiedFilePaths.length > 0 const imageFile = copiesFiles ? null : clipboardEventImageFile(event) - const text = copiesFiles ? '' : clipboardEventPromptText(event, imageFile !== null) + const text = copiesFiles ? '' : clipboardEventPastedText(event, imageFile !== null) if (!copiesFiles && !imageFile && !text) { return } diff --git a/src/renderer/src/components/native-chat/tools/diffs/NativeChatTurnDiffRollup.test.tsx b/src/renderer/src/components/native-chat/tools/diffs/NativeChatTurnDiffRollup.test.tsx deleted file mode 100644 index f28cd80edf1..00000000000 --- a/src/renderer/src/components/native-chat/tools/diffs/NativeChatTurnDiffRollup.test.tsx +++ /dev/null @@ -1,186 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { toast } from 'sonner' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import type { GlobalSettings } from '../../../../../../shared/global-settings-types' -import { getDefaultSettings } from '../../../../../../shared/constants' -import { useAppStore } from '@/store' - -import { TooltipProvider } from '../../../ui/tooltip' - -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { - session, - stubLayout, - stubResizeObserver -} from '../../viewport/virtualization/native-chat-windowing-test-harness' -import { NativeChatLinkClickContext } from '../../links/actions/native-chat-link-click-context' - -vi.mock('sonner', () => ({ - toast: { success: vi.fn(), error: vi.fn(), dismiss: vi.fn() } -})) - -const messages: NativeChatMessage[] = [ - { - id: 'u', - role: 'user', - source: 'transcript', - timestamp: 1, - blocks: [{ type: 'text', text: 'Fix the greeting' }] - }, - { - id: 'work', - role: 'assistant', - source: 'transcript', - timestamp: 2, - blocks: [ - { - type: 'tool-call', - name: 'Bash', - input: { command: 'inspect-private-diagnostic' }, - state: 'completed' - }, - { type: 'tool-result', output: 'diagnostic-output' }, - { - type: 'tool-call', - name: 'Edit', - input: { - file_path: '/repo/greeting.ts', - old_string: 'helloOld()', - new_string: 'helloNew()' - }, - state: 'completed' - }, - { type: 'tool-result', output: 'The file /repo/greeting.ts has been updated successfully.' }, - { type: 'tool-call', name: 'Diff', input: { path: 'status.ts' } }, - { type: 'tool-result', output: '@@ -1 +1 @@\n-statusOld()\n+statusNew()' } - ] - }, - { - id: 'answer', - role: 'assistant', - source: 'transcript', - timestamp: 3, - blocks: [{ type: 'text', text: 'Updated the greeting.' }] - } -] -let restoreLayout = (): void => {} -let restoreResizeObserver = (): void => {} -beforeEach(() => { - restoreLayout = stubLayout({ scrollGeometry: true, offsetChain: true }) - restoreResizeObserver = stubResizeObserver() -}) -afterEach(() => { - cleanup() - restoreResizeObserver() - restoreLayout() -}) - -it('keeps landed files visible after work folds, opens a patch in one click and survives history remount', () => { - const onLinkClick = vi.fn() - const view = (working: boolean) => ( - - - - - - ) - const { rerender, unmount } = render(view(true)) - expect(screen.getByRole('button', { name: /\/repo\/greeting.ts/ })).toBeVisible() - rerender(view(false)) - expect(screen.getByRole('button', { name: /\/repo\/greeting.ts/ })).toBeVisible() - expect(screen.queryByText('diagnostic-output')).toBeNull() - expect(screen.queryByText('helloNew()')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: /\/repo\/greeting.ts/ })) - expect(screen.getByText('helloOld()')).toBeVisible() - expect(screen.getByText('helloNew()')).toBeVisible() - fireEvent.click(screen.getByRole('link', { name: '/repo/greeting.ts' })) - expect(onLinkClick).toHaveBeenCalledTimes(1) - expect(screen.getByText('helloNew()')).toBeVisible() - expect(screen.queryByText('statusNew()')).toBeNull() - unmount() - render(view(false)) - expect(screen.getByRole('button', { name: /status.ts/ })).toBeVisible() - expect(screen.queryByText('diagnostic-output')).toBeNull() -}) - -const hiddenList = ( - - - -) - -function withStore( - updateSettingsOrThrow: (updates: Partial) => Promise, - run: (actions: { openSettingsPage: () => void; openSettingsTarget: () => void }) => Promise -): Promise { - const original = useAppStore.getState() - const actions = { openSettingsPage: vi.fn(), openSettingsTarget: vi.fn() } - // Settings saved before this setting existed have no key; the card must still show for them. - const { nativeChatTurnDiffSummary: _absent, ...savedBeforeSetting } = getDefaultSettings('/tmp') - useAppStore.setState({ settings: savedBeforeSetting, updateSettingsOrThrow, ...actions }) - vi.mocked(toast.success).mockClear() - vi.mocked(toast.error).mockClear() - return run(actions).finally(() => useAppStore.setState(original, true)) -} - -it('Hide turns the changed-files card off in every chat and the toast links to its setting', () => - withStore( - async (updates) => { - useAppStore.setState((state) => ({ settings: { ...state.settings!, ...updates } })) - }, - async ({ openSettingsPage, openSettingsTarget }) => { - render(hiddenList) - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Hide' }))) - expect(useAppStore.getState().settings?.nativeChatTurnDiffSummary).toBe(false) - expect(screen.queryByRole('button', { name: /\/repo\/greeting.ts/ })).toBeNull() - expect(screen.getByText('Updated the greeting.')).toBeVisible() - - expect(toast.success).toHaveBeenCalledTimes(1) - const description = vi.mocked(toast.success).mock.calls[0]?.[1]?.description - cleanup() - render(<>{typeof description === 'function' ? description() : description}) - fireEvent.click(screen.getByRole('button')) - expect(openSettingsPage).toHaveBeenCalledTimes(1) - expect(openSettingsTarget).toHaveBeenCalledWith({ - pane: 'chat', - repoId: null, - sectionId: 'chat-turn-diff-summary' - }) - - // A chat opened later stays without the card until the setting is turned back on. - cleanup() - render(hiddenList) - expect(screen.queryByRole('button', { name: 'Hide' })).toBeNull() - act(() => { - useAppStore.setState((state) => ({ - settings: { ...state.settings!, nativeChatTurnDiffSummary: true } - })) - }) - expect(screen.getByRole('button', { name: /\/repo\/greeting.ts/ })).toBeVisible() - } - )) - -it('a Hide whose save fails keeps the card and says so instead of confirming', () => - withStore( - () => Promise.reject(new Error('settings write failed')), - async () => { - render(hiddenList) - await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Hide' }))) - expect(screen.getByRole('button', { name: /\/repo\/greeting.ts/ })).toBeVisible() - expect(toast.success).not.toHaveBeenCalled() - expect(toast.error).toHaveBeenCalledTimes(1) - } - )) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx index b30c5e1ccee..0e104397fea 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/panel/panel-content.tsx @@ -10,6 +10,7 @@ import { SourceControlCommitSurface } from './commit-surface' import { SourceControlForkPushNotice } from './fork-push-notice' import type { SourceControlPanelReadyProps } from './panel-props' import { useSourceControlScope } from './worktree-scope' +import { openGitGraph } from '@/lib/git-graph-tab' export function SourceControlPanelContent(props: SourceControlPanelReadyProps) { const { activeWorktree, currentWorktreeId, model, worktreePath } = props @@ -64,6 +65,7 @@ export function SourceControlPanelContent(props: SourceControlPanelReadyProps) { refreshBranchCompare, refreshGitHistory, repositoryHuge, + resolveSplitTargetGroupId, requestDiscardAllInArea, requestDiscardEntry, requestDiscardPaths, @@ -246,6 +248,11 @@ export function SourceControlPanelContent(props: SourceControlPanelReadyProps) { onLoadCommitFiles={loadCommitFiles} onOpenCommitFile={openCommitFile} onCommitAction={handleCommitAction} + onOpenGitGraph={(event) => { + if (currentWorktreeId) { + void openGitGraph(currentWorktreeId, () => resolveSplitTargetGroupId(event)) + } + }} /> )} diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/commits-header-icon-button.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/commits-header-icon-button.tsx new file mode 100644 index 00000000000..ddc37ec4a65 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/sync/commits-header-icon-button.tsx @@ -0,0 +1,17 @@ +import type React from 'react' +import { Button } from '@/components/ui/button' + +// Every Commits header action shares this so new ones keep the same size and muted color. +export function CommitsHeaderIconButton( + props: Omit, 'className' | 'variant' | 'size'> +): React.JSX.Element { + return ( + + + {support !== null && ( diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx index 1bc595f1a97..6c1e9b0dd21 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-history-panel.tsx @@ -1,8 +1,8 @@ import { useVirtualizer } from '@tanstack/react-virtual' import { GitGraphOpenButton } from './git-graph-open-button' +import { CommitsHeaderIconButton } from './commits-header-icon-button' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ChevronDown, CircleHelp, RefreshCw } from 'lucide-react' -import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import { ContextMenu, ContextMenuTrigger } from '@/components/ui/context-menu' @@ -55,7 +55,8 @@ export function GitHistoryPanel({ onOpenCommit, onLoadCommitFiles, onOpenCommitFile, - onCommitAction + onCommitAction, + onOpenGitGraph }: { worktreeId?: string state: GitHistoryPanelState @@ -70,6 +71,7 @@ export function GitHistoryPanel({ event?: SourceControlRowOpenEvent ) => void onCommitAction?: (action: GitHistoryCommitAction, item: GitHistoryItem) => void + onOpenGitGraph?: (event: SourceControlRowOpenEvent) => void }): React.JSX.Element | null { const t = useTranslate() const result = state.result @@ -267,14 +269,10 @@ export function GitHistoryPanel({ {result && {count}} {result?.hasMore && +} - {worktreeId && } + {worktreeId && } - + {t( @@ -295,11 +293,7 @@ export function GitHistoryPanel({ - + {t('auto.components.right.sidebar.GitHistoryPanel.d0fb0f4bf2', 'Refresh commits')} diff --git a/src/renderer/src/components/settings/mobile/MobilePane.test.tsx b/src/renderer/src/components/settings/mobile/MobilePane.test.tsx index 4dea4e560f1..5eb5691050b 100644 --- a/src/renderer/src/components/settings/mobile/MobilePane.test.tsx +++ b/src/renderer/src/components/settings/mobile/MobilePane.test.tsx @@ -61,7 +61,7 @@ vi.mock('sonner', () => ({ success: mocks.toastSuccess } })) -vi.mock('./pairing/mobile-pairing-device-polling', () => ({ +vi.mock('../../mobile/pairing/mobile-pairing-device-polling', () => ({ useMobilePairingDevicePolling: vi.fn() })) @@ -119,7 +119,7 @@ vi.mock('./pairing/MobilePairingSetupSection', () => ({ ) })) -vi.mock('./pairing/MobilePairingConnectionOptions', () => ({ +vi.mock('../../mobile/pairing/MobilePairingConnectionOptions', () => ({ MobilePairingConnectionOptions: (props: { onChange: (mode: MobilePairingConnectionMode) => void }) => ( diff --git a/src/renderer/src/components/settings/mobile/MobilePane.tsx b/src/renderer/src/components/settings/mobile/MobilePane.tsx index e5c1106d2f2..466f7ea4dde 100644 --- a/src/renderer/src/components/settings/mobile/MobilePane.tsx +++ b/src/renderer/src/components/settings/mobile/MobilePane.tsx @@ -6,14 +6,14 @@ import { getPairedMobileDevicesSnapshot, usePairedMobileDevices } from '../../mobile/paired-mobile-devices' -import { useMobilePairingDevicePolling } from './pairing/mobile-pairing-device-polling' +import { useMobilePairingDevicePolling } from '../../mobile/pairing/mobile-pairing-device-polling' import { useMobilePairedDeviceRevocation } from './pairing/use-mobile-paired-device-revocation' -import type { MobileNetworkInterface } from './pairing/mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../../shared/pairing-address-auto-selection' import { MachineNameField } from '../../machine-identity/MachineNameField' import { MobilePairingQrSection } from './pairing/MobilePairingQrSection' import { MobilePairedDevicesSection } from './pairing/MobilePairedDevicesSection' import { MobileAutoRestoreFitSection } from './MobileAutoRestoreFitSection' -import { MobilePairingConnectionOptions } from './pairing/MobilePairingConnectionOptions' +import { MobilePairingConnectionOptions } from '../../mobile/pairing/MobilePairingConnectionOptions' import { MobilePairingSetupSection } from './pairing/MobilePairingSetupSection' import { MobileRelayMintFailureNotice } from '../../mobile/mobile-relay-mint-failure-notice' import { WindowsFirewallNotice } from '../../mobile/WindowsFirewallNotice' @@ -42,7 +42,7 @@ export function MobilePane(): React.JSX.Element { const [endpoint, setEndpoint] = useState(null) const [loading, setLoading] = useState(false) const [qrEnlarged, setQrEnlarged] = useState(false) - const [networkInterfaces, setNetworkInterfaces] = useState([]) + const [networkInterfaces, setNetworkInterfaces] = useState([]) const [refreshingNetworkInterfaces, setRefreshingNetworkInterfaces] = useState(false) const [codeCopied, setCodeCopied] = useState(false) const [deviceCountAtQr, setDeviceCountAtQr] = useState(null) diff --git a/src/renderer/src/components/settings/mobile/MobileSettingsPane.tsx b/src/renderer/src/components/settings/mobile/MobileSettingsPane.tsx index 384a4d2e0de..66bd33dc5f8 100644 --- a/src/renderer/src/components/settings/mobile/MobileSettingsPane.tsx +++ b/src/renderer/src/components/settings/mobile/MobileSettingsPane.tsx @@ -8,7 +8,7 @@ import { } from './mobile-settings-search' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' -import { MobileRelayBetaNotice } from './pairing/MobileRelayBetaNotice' +import { MobileRelayBetaNotice } from '../../mobile/pairing/MobileRelayBetaNotice' import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open' const ORCA_IOS_APP_STORE_URL = 'https://apps.apple.com/app/orca-ide/id6766130217' diff --git a/src/renderer/src/components/settings/mobile/pairing/MobilePairedDevicesSection.tsx b/src/renderer/src/components/settings/mobile/pairing/MobilePairedDevicesSection.tsx index 478acd30cb2..307818c66b9 100644 --- a/src/renderer/src/components/settings/mobile/pairing/MobilePairedDevicesSection.tsx +++ b/src/renderer/src/components/settings/mobile/pairing/MobilePairedDevicesSection.tsx @@ -4,10 +4,8 @@ import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import type { PairedMobileDevice } from '../../../mobile/paired-mobile-devices' import { LegacyEncryptionNotice } from '../../legacy-encryption-notice' -export type PairedDevice = PairedMobileDevice - type MobilePairedDevicesSectionProps = { - devices: readonly PairedDevice[] + devices: readonly PairedMobileDevice[] hasQrCode: boolean onRevokeDevice: (deviceId: string) => void } diff --git a/src/renderer/src/components/settings/mobile/pairing/MobilePairingSetupSection.tsx b/src/renderer/src/components/settings/mobile/pairing/MobilePairingSetupSection.tsx index 220a9b54092..3fe3c960d37 100644 --- a/src/renderer/src/components/settings/mobile/pairing/MobilePairingSetupSection.tsx +++ b/src/renderer/src/components/settings/mobile/pairing/MobilePairingSetupSection.tsx @@ -6,7 +6,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '../../../ui/tooltip' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { NetworkInterfacePicker } from '../../../mobile/NetworkInterfacePicker' -import type { MobileNetworkInterface } from './mobile-network-interface-selection' +import type { PairingNetworkInterface } from '../../../../../../shared/pairing-address-auto-selection' import type { MobilePairingConnectionMode } from '../../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' type MobilePairingSetupSectionProps = { @@ -16,7 +16,7 @@ type MobilePairingSetupSectionProps = { /** Reveals the Relay address disclosure when a settings search matches it. */ addressDisclosureForcedOpen?: boolean connectionPathControl: ReactNode - networkInterfaces: MobileNetworkInterface[] + networkInterfaces: PairingNetworkInterface[] customAddresses: readonly string[] selectedAddress: string | undefined selectedAddressIsCustom: boolean diff --git a/src/renderer/src/components/settings/runtime-environments/catalog/runtime-environment-host-details.ts b/src/renderer/src/components/settings/runtime-environments/catalog/runtime-environment-host-details.ts index 1224d761f38..2836ca75b3b 100644 --- a/src/renderer/src/components/settings/runtime-environments/catalog/runtime-environment-host-details.ts +++ b/src/renderer/src/components/settings/runtime-environments/catalog/runtime-environment-host-details.ts @@ -17,7 +17,6 @@ import { TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY } from '../../../../../../shared import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' import '@/runtime/hosts/connections/runtime-host-connection-state' import { - isConnectedRuntimeHostState, runtimeHostConnectionState, type RuntimeHostConnectionState as RuntimeServerConnectionState } from '../../../../../../shared/remote-runtime/host-status/runtime-host-connection-state' @@ -211,10 +210,6 @@ export function getRuntimeServerConnectionState( }) } -export function isRuntimeServerTransportConnected(state: RuntimeServerConnectionState): boolean { - return isConnectedRuntimeHostState(state) -} - export function getRuntimeServerConnectionLabel( state: RuntimeServerConnectionState, t: Translate = translate diff --git a/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row-state.ts b/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row-state.ts index e237d1e4e14..d97d65aed99 100644 --- a/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row-state.ts +++ b/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row-state.ts @@ -18,7 +18,6 @@ import { evaluateHostDetails, getHostDetailsDescription, getRuntimeServerConnectionState, - isRuntimeServerTransportConnected, type RuntimeHostDetails } from '../catalog/runtime-environment-host-details' @@ -79,7 +78,7 @@ export function useRuntimeServerRowState( details?.status === 'loading' && !runtimeStatusEntry?.status ? 'checking' : getRuntimeServerConnectionState(effectiveDetails) - const isReachable = isRuntimeServerTransportConnected(connectionState) + const isReachable = isConnectedRuntimeHostState(connectionState) // Keep last verified descriptors across lost probes; latest status alone can be absent. const descriptorStatus = lastVerifiedRuntimeStatus(runtimeStatusEntry) const hostDisplay = resolveHostDisplay({ diff --git a/src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx b/src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx index ecc3129b6b2..e17b473fe69 100644 --- a/src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx +++ b/src/renderer/src/components/settings/session-history/SessionHistoryServerRow.tsx @@ -6,9 +6,9 @@ import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' import { getRuntimeServerConnectionState, - isRuntimeServerTransportConnected, type RuntimeHostDetails } from '../runtime-environments/catalog/runtime-environment-host-details' +import { isConnectedRuntimeHostState } from '../../../../../shared/remote-runtime/host-status/runtime-host-connection-state' import { SessionHistoryComputerRow } from './SessionHistoryComputerRow' import type { SessionSearchComputerState } from './session-search-computer-rollup' import { @@ -44,7 +44,7 @@ export function SessionHistoryServerRow({ const [tooOldOnSet, setTooOldOnSet] = useState(false) const [busy, setBusy] = useState(false) const connectionState = getRuntimeServerConnectionState(details) - const connected = isRuntimeServerTransportConnected(connectionState) + const connected = isConnectedRuntimeHostState(connectionState) const { status, failed, hostTooOld, adopt } = useSessionSearchStatus({ executionHostId: hostId, active: connected && !tooOldOnSet, diff --git a/src/renderer/src/components/settings/setup-guide/SettingsSetupGuidePane.tsx b/src/renderer/src/components/settings/setup-guide/SettingsSetupGuidePane.tsx index 23cccdf34b2..761bc286229 100644 --- a/src/renderer/src/components/settings/setup-guide/SettingsSetupGuidePane.tsx +++ b/src/renderer/src/components/settings/setup-guide/SettingsSetupGuidePane.tsx @@ -5,13 +5,13 @@ import { } from '../../../../../shared/feature-wall-setup-steps' import type { FeatureWallSetupStepId } from '../../../../../shared/feature-wall-setup-steps' import { FeatureWallSetupChecklist } from '../../feature-wall/FeatureWallSetupChecklist' -import { useSettingsSetupGuideFullProgress } from './settings-setup-guide-progress' +import { useSetupGuideProgress } from '../../setup-guide/use-setup-guide-progress' export function SettingsSetupGuidePane(): React.JSX.Element { const setupSteps = useMemo(() => getFeatureWallSetupSteps(), []) const [orchestrationSkillInstalled, setOrchestrationSkillInstalled] = useState(false) const [browserUseSkillInstalled, setBrowserUseSkillInstalled] = useState(false) - const progress = useSettingsSetupGuideFullProgress( + const progress = useSetupGuideProgress( true, orchestrationSkillInstalled, browserUseSkillInstalled diff --git a/src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts b/src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts index c13ce6ba04e..4c4625d946e 100644 --- a/src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts +++ b/src/renderer/src/components/settings/setup-guide/settings-setup-guide-progress.ts @@ -4,7 +4,6 @@ import { getFirstIncompleteFeatureWallSetupStepId, type FeatureWallSetupStepId } from '../../../../../shared/feature-wall-setup-steps' -import type { FeatureWallSetupProgress } from '../../feature-wall/feature-wall-setup-progress' import { useSetupGuideProgress } from '../../setup-guide/use-setup-guide-progress' export type SettingsSetupGuideProgress = { @@ -35,19 +34,7 @@ export function getSettingsSetupGuideProgress(progress: { export function useSettingsSetupGuideProgress( shouldRefreshCoreState: boolean ): SettingsSetupGuideProgress { - const fullProgress = useSettingsSetupGuideFullProgress(shouldRefreshCoreState, false, false) + const fullProgress = useSetupGuideProgress(shouldRefreshCoreState, false, false) return useMemo(() => getSettingsSetupGuideProgress(fullProgress), [fullProgress]) } - -export function useSettingsSetupGuideFullProgress( - shouldRefreshCoreState: boolean, - orchestrationSkillInstalled: boolean, - browserUseSkillInstalled: boolean -): FeatureWallSetupProgress { - return useSetupGuideProgress( - shouldRefreshCoreState, - orchestrationSkillInstalled, - browserUseSkillInstalled - ) -} diff --git a/src/renderer/src/components/settings/ssh/server-actions/SshTargetServerStatus.tsx b/src/renderer/src/components/settings/ssh/server-actions/SshTargetServerStatus.tsx index c7d2b22b0f6..a4b57a323dc 100644 --- a/src/renderer/src/components/settings/ssh/server-actions/SshTargetServerStatus.tsx +++ b/src/renderer/src/components/settings/ssh/server-actions/SshTargetServerStatus.tsx @@ -15,7 +15,7 @@ import { canMoveSshHostAnyway, SshHostMoveAnywayDialog } from './SshHostMoveAnyw import { canRestartSshHostServer, SshHostRestartServerDialog } from './SshHostRestartServerAction' import { canRecoverSshHostServer, SshHostRecoverServerDialog } from './SshHostRecoverServerAction' import { Button } from '../../../ui/button' -import { isSshTargetConnecting } from '../targets/ssh-target-action-state' +import { isConnectingSshStatus } from '../../../../ssh/ssh-connection-recoverability' import { getManagedOrcadApi } from '../../runtime-environments/managed-servers/use-managed-server-catalog' export type SshTargetServerDialog = @@ -61,7 +61,7 @@ export function SshTargetServerStatusLine({ size="xs" variant="default" // A connect in flight may clear the refusal; a click would start a second one. - disabled={state ? isSshTargetConnecting(state.status) : false} + disabled={state ? isConnectingSshStatus(state.status) : false} onClick={() => onOpenDialog('move-anyway')} > {t('auto.components.settings.moveAnyway.action', 'Move anyway…')} diff --git a/src/renderer/src/components/settings/ssh/targets/SshTargetCard.tsx b/src/renderer/src/components/settings/ssh/targets/SshTargetCard.tsx index f93f9bba58a..271182b6620 100644 --- a/src/renderer/src/components/settings/ssh/targets/SshTargetCard.tsx +++ b/src/renderer/src/components/settings/ssh/targets/SshTargetCard.tsx @@ -15,7 +15,8 @@ import { DropdownMenuSeparator, DropdownMenuTrigger } from '../../../ui/dropdown-menu' -import { isSshTargetConnecting, type SshTargetBusyAction } from './ssh-target-action-state' +import { isConnectingSshStatus } from '../../../../ssh/ssh-connection-recoverability' +import type { SshTargetBusyAction } from './ssh-target-action-state' import { sshIdentityFileName } from './ssh-target-list-model' import { isManagedServerSshHost } from './SshManagedHostRemoveDialog' import { @@ -173,7 +174,7 @@ export function SshTargetCard({ ) } - if (isSshTargetConnecting(status)) { + if (isConnectingSshStatus(status)) { return ( + + ) +} + +/** Re-measures on pane resize so the chip appears once a hidden pane is shown and clears once grids match. */ +export function HeldPaneRemoteViewportChip({ + pane, + ownerGrid, + onFitHere +}: { + pane: Pick + ownerGrid: Grid + onFitHere: (paneGrid: Grid) => void +}): ReactElement | null { + const [paneGrid, setPaneGrid] = useState(() => proposePaneGrid(pane)) + useEffect(() => { + const remeasure = (): void => { + const next = proposePaneGrid(pane) + setPaneGrid((prev) => (prev?.cols === next?.cols && prev?.rows === next?.rows ? prev : next)) + } + remeasure() + const observer = new ResizeObserver(remeasure) + observer.observe(pane.container) + return () => observer.disconnect() + }, [pane]) + if (!paneGrid || !shouldShowRemoteViewportHeldChip('remote-desktop-fit', ownerGrid, paneGrid)) { + return null + } + return onFitHere(paneGrid)} /> +} + +function proposePaneGrid(pane: Pick): Grid | null { + try { + const proposed = pane.fitAddon.proposeDimensions() + return proposed && proposed.cols > 0 && proposed.rows > 0 + ? { cols: proposed.cols, rows: proposed.rows } + : null + } catch { + return null + } +} diff --git a/src/renderer/src/components/terminal-pane/mobile-driver/TerminalPaneMobileDriverPortals.tsx b/src/renderer/src/components/terminal-pane/mobile-driver/TerminalPaneMobileDriverPortals.tsx index 5cc94719f08..b9e3d86403a 100644 --- a/src/renderer/src/components/terminal-pane/mobile-driver/TerminalPaneMobileDriverPortals.tsx +++ b/src/renderer/src/components/terminal-pane/mobile-driver/TerminalPaneMobileDriverPortals.tsx @@ -1,5 +1,6 @@ import { createPortal } from 'react-dom' import { MobileDriverOverlay } from './MobileDriverOverlay' +import { HeldPaneRemoteViewportChip } from './RemoteViewportHeldChip' import { getDriverForPty } from '../../../lib/pane-manager/mobile-driver-state' import { getFitOverrideForPty } from '../../../lib/pane-manager/mobile-fit-overrides' import { shouldShowMobileDriverOverlay } from './mobile-driver-overlay-visibility' @@ -12,12 +13,14 @@ export function TerminalPaneMobileDriverPortals({ controller: TerminalPaneController }): React.JSX.Element { const { + activePane, chatLeafId, effectiveChatViewMode, managedPanes, paneTransportsRef, restoreAllTerminalFits, - restorePaneTerminalFit + restorePaneTerminalFit, + searchOpen } = controller return ( <> @@ -27,13 +30,35 @@ export function TerminalPaneMobileDriverPortals({ return null } const driver = getDriverForPty(ptyId) - const fitMode = getFitOverrideForPty(ptyId)?.mode ?? null + const fitOverride = getFitOverrideForPty(ptyId) + const fitMode = fitOverride?.mode ?? null const hasFitOverride = fitMode === 'mobile-fit' - if (!shouldShowMobileDriverOverlay(driver.kind, fitMode)) { - return null - } const paneSurface = effectiveChatViewMode && pane.leafId === chatLeafId ? 'chat' : 'terminal' + if (!shouldShowMobileDriverOverlay(driver.kind, fitMode)) { + // Only held terminal panes mount the measuring chip; it yields the corner to an open find bar. + if ( + fitMode !== 'remote-desktop-fit' || + !fitOverride || + paneSurface !== 'terminal' || + (searchOpen && activePane?.id === pane.id) + ) { + return null + } + return createPortal( + { + paneTransportsRef.current.get(pane.id)?.claimViewport?.(grid.cols, grid.rows) + pane.terminal.focus() + }} + />, + pane.container, + `remote-viewport-held-${pane.id}` + ) + } if (shouldChatTakeOverMobileSurface(paneSurface)) { return null } diff --git a/src/renderer/src/components/terminal-pane/mobile-driver/remote-viewport-held-chip-portal.test.tsx b/src/renderer/src/components/terminal-pane/mobile-driver/remote-viewport-held-chip-portal.test.tsx new file mode 100644 index 00000000000..314bdb18325 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/mobile-driver/remote-viewport-held-chip-portal.test.tsx @@ -0,0 +1,137 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { setDriverForPty } from '@/lib/pane-manager/mobile-driver-state' +import { setFitOverride } from '@/lib/pane-manager/mobile-fit-overrides' +import { TerminalPaneMobileDriverPortals } from './TerminalPaneMobileDriverPortals' +import type { TerminalPaneController } from '../controller/use-terminal-pane-controller' +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const PTY_ID = 'held-pty' +let root: Root | null = null +const resizeCallbacks: (() => void)[] = [] + +class ResizeObserverStub { + constructor(private readonly callback: () => void) {} + observe(): void { + resizeCallbacks.push(this.callback) + } + disconnect(): void { + resizeCallbacks.splice(resizeCallbacks.indexOf(this.callback), 1) + } +} + +type Grid = { cols: number; rows: number } + +function renderPortals( + options: Partial<{ searchOpen: boolean; chatView: boolean; activePaneId: number }> = {} +) { + const container = document.createElement('div') + const host = document.createElement('div') + document.body.append(container, host) + const claimViewport = vi.fn(() => true) + const focus = vi.fn() + const measured: { grid: Grid | undefined } = { grid: { cols: 120, rows: 40 } } + const pane = { + id: 1, + leafId: 'leaf-1', + container, + terminal: { focus }, + fitAddon: { proposeDimensions: () => measured.grid } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the portal reads only these controller fields and these pane members. + const controller = { + activePane: { id: options.activePaneId ?? pane.id }, + chatLeafId: 'leaf-1', + effectiveChatViewMode: options.chatView ?? false, + managedPanes: [pane], + paneTransportsRef: { current: new Map([[1, { getPtyId: () => PTY_ID, claimViewport }]]) }, + restoreAllTerminalFits: vi.fn(), + restorePaneTerminalFit: vi.fn(), + searchOpen: options.searchOpen ?? false + } as unknown as TerminalPaneController + root = createRoot(host) + act(() => + root?.render( + + + + ) + ) + const fitHere = (): HTMLButtonElement | null => + Array.from(container.querySelectorAll('button')).find((b) => b.textContent === 'Fit here') ?? + null + const resizePane = (grid: Grid | undefined): void => { + measured.grid = grid + act(() => resizeCallbacks.forEach((callback) => callback())) + } + return { container, fitHere, resizePane, claimViewport, focus } +} + +function unmount(): void { + act(() => root?.unmount()) + root = null +} + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', ResizeObserverStub) +}) + +afterEach(() => { + unmount() + vi.unstubAllGlobals() + document.body.innerHTML = '' + setFitOverride(PTY_ID, 'desktop-fit', 0, 0) + setDriverForPty(PTY_ID, { kind: 'idle' }) +}) + +describe('remote viewport held chip in terminal panes', () => { + it('offers Fit here while another window holds the pane at a different grid', () => { + setFitOverride(PTY_ID, 'remote-desktop-fit', 200, 50) + const { fitHere, claimViewport, focus } = renderPortals() + + act(() => fitHere()!.click()) + + expect(claimViewport).toHaveBeenCalledWith(120, 40) + expect(focus).toHaveBeenCalled() + }) + + it('stays hidden when no other window holds the size', () => { + expect(renderPortals().fitHere()).toBeNull() + }) + + it('appears once a hidden pane gets a size, and clears once its grid matches the held one', () => { + setFitOverride(PTY_ID, 'remote-desktop-fit', 200, 50) + const { fitHere, resizePane } = renderPortals() + resizePane(undefined) + expect(fitHere()).toBeNull() + + resizePane({ cols: 120, rows: 40 }) + expect(fitHere()).not.toBeNull() + + resizePane({ cols: 200, rows: 50 }) + expect(fitHere()).toBeNull() + }) + + it('stays hidden on the chat surface', () => { + setFitOverride(PTY_ID, 'remote-desktop-fit', 200, 50) + expect(renderPortals({ chatView: true }).fitHere()).toBeNull() + }) + + it('gives way to the phone banner while a phone drives', () => { + setFitOverride(PTY_ID, 'remote-desktop-fit', 200, 50) + setDriverForPty(PTY_ID, { kind: 'mobile', clientId: 'phone' }) + const { container, fitHere } = renderPortals() + expect(fitHere()).toBeNull() + expect(container.textContent).toContain('Take back') + }) + + it('yields the corner only to a find bar open on the same pane', () => { + setFitOverride(PTY_ID, 'remote-desktop-fit', 200, 50) + expect(renderPortals({ searchOpen: true }).fitHere()).toBeNull() + unmount() + expect(renderPortals({ searchOpen: true, activePaneId: 2 }).fitHere()).not.toBeNull() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-routing.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-routing.spec.ts index 9e1095b1a54..8a63e2f4201 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-routing.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-routing.spec.ts @@ -65,118 +65,6 @@ export function registerPtyConnectionForegroundAgentRoutingTests(): void { await restoreTerminalTestGlobals() }) - it('drops agent status without retaining when OSC 133 reports the command finished', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - const transport = createMockTransport() - let currentPtyId: string | null = null - vi.mocked(transport.getPtyId).mockImplementation(() => currentPtyId) - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - currentPtyId = 'pty-local-1' - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-local-1' - } - ) - transportFactoryQueue.push(transport) - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState = { - ...mockStoreState, - agentStatusByPaneKey: { - [paneKey]: { - paneKey, - state: 'done', - prompt: 'hi', - updatedAt: 1000, - stateStartedAt: 1000, - agentType: 'codex', - stateHistory: [] - } - } - } - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps({ isVisibleRef: { current: false } }) - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks)) - ) - - capturedDataCallback.current?.('\x1b]133;D;130\x07thebr ~/repo $ ') - await flushAsyncTicks() - - expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey) - expect(mockStoreState.removeAgentStatus).not.toHaveBeenCalled() - }) - - it('clears pre-hook launch config when an Orca-started command exits', async () => { - vi.useFakeTimers({ toFake: ['setTimeout'] }) - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('zsh') - - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - const transport = createMockTransport() - let currentPtyId: string | null = null - vi.mocked(transport.getPtyId).mockImplementation(() => currentPtyId) - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - currentPtyId = 'pty-local-1' - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-local-1' - } - ) - transportFactoryQueue.push(transport) - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState = { - ...mockStoreState, - tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] }, - ptyIdsByTabId: { 'tab-1': [] } - } as StoreState - - connectPanePty( - ...mockPanePtyArgs( - createPane(1), - createManager(1), - bindPaneAgentTitleMocks( - createDeps({ - startup: { - command: "codex '--dangerously-bypass-approvals-and-sandbox'", - launchConfig: { - agentArgs: '--dangerously-bypass-approvals-and-sandbox', - agentEnv: {} - }, - launchAgent: 'codex' - }, - restoredPtyIdByLeafId: {} - }), - agentTitleMocks2 - ) - ) - ) - - expect(mockStoreState.registerAgentLaunchConfig).toHaveBeenCalledWith( - paneKey, - { - agentArgs: '--dangerously-bypass-approvals-and-sandbox', - agentEnv: {} - }, - expect.objectContaining({ agentType: 'codex' }) - ) - capturedDataCallback.current?.('\x1b]133;D;130\x07thebr ~/repo $ ') - await flushAsyncTicks() - await vi.advanceTimersByTimeAsync(350) - await flushAsyncTicks() - - expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(paneKey) - expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled() - }) - it('routes a manually typed Droid only after foreground enrichment confirms it', async () => { vi.useFakeTimers() const { connectPanePty } = await import('../connect-pane-pty') @@ -269,57 +157,6 @@ export function registerPtyConnectionForegroundAgentRoutingTests(): void { expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('csi-u') }) - it('confirms an Orca-launched Droid fresh spawn in a no-OSC shell (Git Bash)', async () => { - // No-OSC shells need fresh-spawn sampling to earn routing trust; otherwise Shift+Enter falls back to Esc+CR (#7620). - vi.useFakeTimers() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks5 = - await vi.importMock('@/lib/agent-status') - vi.mocked(window.api.pty.getForegroundProcess).mockResolvedValue('droid') - vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('droid') - const pane = createPane(1) - const ptyId = 'pty-launched-droid-no-osc' - const tabId = 'tab-launched-droid-no-osc' - const paneKey = makePaneKey(tabId, LEAF_1) - transportFactoryQueue.push(createMockTransport(ptyId)) - - connectPanePty( - ...mockPanePtyArgs( - pane, - createManager(1), - bindPaneAgentTitleMocks( - createDeps({ - tabId, - startup: { command: 'droid', launchAgent: 'droid' } - }), - agentTitleMocks5 - ) - ) - ) - await vi.advanceTimersByTimeAsync(20) - await flushAsyncTicks() - // The transport reports the fresh spawn; no OSC 133, no typed inference. - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Captured transport options expose onPtySpawn as an optional PTY-id callback. - const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as - | ((id: string) => void) - | undefined - expect(onPtySpawn).toBeTypeOf('function') - onPtySpawn?.(ptyId) - await vi.advanceTimersByTimeAsync( - VISIBLE_PTY_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS + SECOND_WRAPPER_RETRY_MS - ) - await flushAsyncTicks() - - expect(window.api.pty.confirmForegroundProcess).toHaveBeenCalledWith(ptyId) - expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ - agent: 'droid', - agentEvidence: 'process-read', - routingTrusted: true, - shellForeground: false - }) - expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('csi-u') - }) - it('trusts a launched Droid whose no-OSC boot only becomes foreground after retries', async () => { // Retry across Droid boot while early foreground reads still see its shell. vi.useFakeTimers() diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts index 625e913b7a5..6aa8ee78103 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-agent-sampling.spec.ts @@ -138,79 +138,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { .mock.calls.filter(([calledPtyId]) => calledPtyId === ptyId) } - it('does not inspect foreground process for a fresh visible spawn', async () => { - vi.useFakeTimers() - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-fresh-visible-no-sample' - transportFactoryQueue.push(createMockTransport(ptyId)) - mockStoreState = { - ...mockStoreState, - tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] }, - ptyIdsByTabId: { 'tab-1': [] }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: LEAF_1 }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: {} - } - } - } as StoreState - - connectPanePty( - createPane(1) as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks2) - ) - await vi.advanceTimersByTimeAsync(20) - await flushAsyncTicks(20) - const spawnHandler = createdTransportOptions[0]?.onPtySpawn as - | ((ptyId: string) => void) - | undefined - spawnHandler?.(ptyId) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) - - it('samples exactly one visible restored PTY with no stronger identity signal', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-restored-visible-sample' - - const { cacheKey } = await connectRestoredPaneForForegroundSampling({ ptyId }) - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toEqual([[ptyId]]) - expect(mockStoreState.setPaneForegroundAgent).toHaveBeenCalledWith(cacheKey, { - agent: 'codex', - agentEvidence: 'process-read', - shellForeground: false - }) - }) - - it('does not sample hidden restored PTYs', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-hidden-restored-no-sample' - - await connectRestoredPaneForForegroundSampling({ - ptyId, - isVisibleRef: { current: false } - }) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) - it('does not confirm foreground routing for a Windows WSL pane', async () => { vi.useFakeTimers() const restoreUserAgent = temporarilySetNavigatorUserAgent( @@ -395,23 +322,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { }) }) - it('samples once when an identityless hidden pane resumes visible', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const isVisibleRef = { current: false } - const ptyId = 'pty-hidden-then-visible-sample' - const { binding } = await connectRestoredPaneForForegroundSampling({ ptyId, isVisibleRef }) - await advanceVisibleForegroundRead() - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - - isVisibleRef.current = true - binding.noteVisibilityResume() - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toEqual([[ptyId]]) - }) - it('confirms daemon launch identity before restoring warm-reattach routing', async () => { vi.useFakeTimers() vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('droid') @@ -451,59 +361,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('csi-u') }) - it("keeps this session's process read when a parked pane re-attaches to the same agent", async () => { - vi.useFakeTimers() - const ptyId = 'pty-parked-reattach-keeps-read' - const tabId = `tab-${ptyId}` - const cacheKey = makePaneKey(tabId, LEAF_1) - mockStoreState.tabsByWorktree = { 'wt-1': [{ id: tabId, ptyId }] } - mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { - agent: 'codex', - agentEvidence: 'process-read', - routingTrusted: true, - shellForeground: false - } - - await connectRestoredPaneForForegroundSampling({ - ptyId, - tabId, - isVisibleRef: { current: false }, - launchAgent: 'codex' - }) - - expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ - agent: 'codex', - agentEvidence: 'process-read', - shellForeground: false - }) - }) - - it('seeds a launch record when the prior read named a different agent', async () => { - vi.useFakeTimers() - const ptyId = 'pty-parked-reattach-other-agent' - const tabId = `tab-${ptyId}` - const cacheKey = makePaneKey(tabId, LEAF_1) - mockStoreState.tabsByWorktree = { 'wt-1': [{ id: tabId, ptyId }] } - mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { - agent: 'claude', - agentEvidence: 'process-read', - shellForeground: false - } - - await connectRestoredPaneForForegroundSampling({ - ptyId, - tabId, - isVisibleRef: { current: false }, - launchAgent: 'codex' - }) - - expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ - agent: 'codex', - agentEvidence: 'launch-record', - shellForeground: false - }) - }) - it('retires stale daemon launch identity when warm reattach finds the shell', async () => { vi.useFakeTimers() vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('powershell.exe') @@ -534,21 +391,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') }) - it('fails closed when a warm reattach has no persisted launch identity', async () => { - vi.useFakeTimers() - const ptyId = 'pty-reattach-missing-launch-identity' - const tabId = `tab-${ptyId}` - - const { cacheKey } = await connectRestoredPaneForForegroundSampling({ - ptyId, - tabId, - isVisibleRef: { current: false } - }) - - expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toBeUndefined() - expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') - }) - it('does not let persisted args spoof pane identity without an allowlisted command', async () => { vi.useFakeTimers() const ptyId = 'pty-unknown-persisted-launch' @@ -636,58 +478,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { expect(foregroundReadCallsFor(ptyId)).toHaveLength(settledReadCount) }) - it('does not sample when a live hook row already supplies pane identity', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-hook-identity-no-sample' - const tabId = `tab-${ptyId}` - mockStoreState.agentStatusByPaneKey[makePaneKey(tabId, LEAF_1)] = { - state: 'working', - agentType: 'codex' - } - - await connectRestoredPaneForForegroundSampling({ ptyId, tabId }) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) - - it('does not sample when process identity is already known', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-process-identity-no-sample' - const tabId = `tab-${ptyId}` - mockStoreState.paneForegroundAgentByPaneKey[makePaneKey(tabId, LEAF_1)] = { - agent: 'codex', - routingTrusted: true, - shellForeground: false - } - - await connectRestoredPaneForForegroundSampling({ ptyId, tabId }) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) - - it('does not re-sample once 133;D proved the pane is at a shell prompt', async () => { - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'pty-shell-foreground-no-sample' - const tabId = `tab-${ptyId}` - mockStoreState.paneForegroundAgentByPaneKey[makePaneKey(tabId, LEAF_1)] = { - agent: null, - shellForeground: true - } - - await connectRestoredPaneForForegroundSampling({ ptyId, tabId }) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) - it('does not re-sample a shell-confirmed pane from stale launch metadata', async () => { vi.useFakeTimers() const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) @@ -823,19 +613,6 @@ export function registerPtyConnectionForegroundAgentSamplingTests(): void { shellForeground: false }) }) - - it('never probes the foreground for a visible remote/SSH restored pane', async () => { - // Why: foreground reads are local-only (expensive RPCs); keep remote/SSH panes off the recovery probe. - vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') - const ptyId = 'remote:web-env-1@@pty-remote-idle-agent' - - await connectRestoredPaneForForegroundSampling({ ptyId, tabId: 'tab-remote-idle-agent' }) - await advanceVisibleForegroundRead() - - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) - }) }) }) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-routing-confirmation.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-routing-confirmation.spec.ts index 39574cc2c50..b83558fc4ab 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-routing-confirmation.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-foreground-routing-confirmation.spec.ts @@ -158,39 +158,6 @@ export function registerPtyConnectionForegroundRoutingConfirmationTests(): void expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') }) - it('does not let a pending confirmation re-arm itself', async () => { - vi.useFakeTimers() - // Never resolves: the confirmation stays in flight for the whole test. - vi.mocked(window.api.pty.confirmForegroundProcess).mockReturnValue(new Promise(() => {})) - const ptyId = 'pty-pi-no-remint' - const tabId = `tab-${ptyId}` - const { binding, cacheKey } = await connectRestoredPaneForForegroundSampling({ - ptyId, - tabId - }) - mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { - agent: 'pi', - routingTrusted: true, - shellForeground: false - } - - binding.requestWindowsShiftEnterReconfirmation() - await vi.advanceTimersByTimeAsync(350) - await flushAsyncTicks() - expect( - mockStoreState.paneForegroundAgentByPaneKey[cacheKey]?.routingConfirmationPending - ).toBe(true) - const publishesAfterFirst = mockStoreState.setPaneForegroundAgent.mock.calls.length - - // A pending entry is not trusted evidence: further requests must not republish it. - binding.requestWindowsShiftEnterReconfirmation() - binding.requestWindowsShiftEnterReconfirmation() - await vi.advanceTimersByTimeAsync(1_000) - await flushAsyncTicks() - - expect(mockStoreState.setPaneForegroundAgent.mock.calls.length).toBe(publishesAfterFirst) - }) - it('does not reauthorize explicitly revoked routing before confirmation', async () => { vi.useFakeTimers() const ptyId = 'pty-pi-revoked-focus' diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-bell-arbitration.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-bell-arbitration.spec.ts deleted file mode 100644 index a8dc756594d..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-bell-arbitration.spec.ts +++ /dev/null @@ -1,369 +0,0 @@ -import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { - AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS, - AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS -} from '../test-fixtures/pty-connection-test-constants' -import { - LEAF_1, - createMockTransport, - createPane, - createManager, - type MockTransport -} from '../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../test-fixtures/pty-connection-test-deps' -import { - createInitialStoreState, - buildActiveRuntimeEnvironmentState -} from '../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - restoreTerminalTestGlobals -} from '../test-fixtures/pty-connection-test-environment' - -export function registerPtyConnectionHookCompletionBellArbitrationTests(): void { - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - - // Why: activeRuntimeEnvironmentId exercises the remote-runtime path where the renderer still owns OSC 9999 status. - function enableActiveRuntimeEnvironment(environmentId = 'env-1'): void { - mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, environmentId) - } - describe('connectPanePty', () => { - beforeEach(async () => { - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('lets delayed hook completion notifications win over concurrent terminal bells', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.ptyIdsByTabId = { 'tab-1': ['pty-hook'] } - mockStoreState.terminalLayoutsByTabId!['tab-1'].ptyIdsByLeafId = { [LEAF_1]: 'pty-hook' } - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks2) - ) - - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'working' | 'done' - prompt: string - agentType: 'codex' - lastAssistantMessage?: string - }) => void) - | undefined - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - if (!statusHandler || !bellHandler) { - throw new Error('Expected hook status and bell handlers to be registered') - } - - statusHandler({ - state: 'working', - prompt: 'finish the implementation', - agentType: 'codex' - }) - statusHandler({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'codex', - lastAssistantMessage: 'Done.' - }) - bellHandler() - - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - - vi.advanceTimersByTime( - AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS - ) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: 'codex', - paneKey: makePaneKey('tab-1', LEAF_1), - agentStatusSnapshot: expect.objectContaining({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'codex', - lastAssistantMessage: 'Done.' - }) - }) - ) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - }) - - it('restores a suppressed terminal bell when a delayed hook completion resumes work', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('tab-pty') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.ptyIdsByTabId = { 'tab-1': ['tab-pty'] } - mockStoreState.terminalLayoutsByTabId!['tab-1'].ptyIdsByLeafId = { [LEAF_1]: 'tab-pty' } - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks3) - ) - - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'working' | 'done' - prompt: string - agentType: 'codex' - lastAssistantMessage?: string - }) => void) - | undefined - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - if (!statusHandler || !bellHandler) { - throw new Error('Expected hook status and bell handlers to be registered') - } - - statusHandler({ - state: 'working', - prompt: 'finish the implementation', - agentType: 'codex' - }) - statusHandler({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'codex', - lastAssistantMessage: 'Done.' - }) - bellHandler() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - - statusHandler({ - state: 'working', - prompt: 'finish the implementation', - agentType: 'codex' - }) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - }) - - it('restores a suppressed terminal bell when a delayed hook completion resumes via title tracking', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks4 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.ptyIdsByTabId = { 'tab-1': ['pty-hook'] } - mockStoreState.terminalLayoutsByTabId!['tab-1'].ptyIdsByLeafId = { [LEAF_1]: 'pty-hook' } - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks4) - ) - - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'working' | 'done' - prompt: string - agentType: 'codex' - lastAssistantMessage?: string - }) => void) - | undefined - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as - | (() => void) - | undefined - if (!statusHandler || !bellHandler || !workingHandler) { - throw new Error('Expected hook status, bell, and working handlers to be registered') - } - - statusHandler({ - state: 'working', - prompt: 'finish the implementation', - agentType: 'codex' - }) - statusHandler({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'codex', - lastAssistantMessage: 'Milestone complete.' - }) - bellHandler() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - - workingHandler() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - }) - - it('restores a suppressed terminal bell when the pending agent completion is canceled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks5 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks5) - ) - - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as - | (() => void) - | undefined - if (!bellHandler || !idleHandler || !workingHandler) { - throw new Error('Expected bell, idle, and working handlers to be registered') - } - - bellHandler() - idleHandler('* Codex done') - workingHandler() - vi.advanceTimersByTime(250) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - }) - - it('cancels a title task-complete notification when the agent resumes before quiet', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks6 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks6) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as - | (() => void) - | undefined - if (!idleHandler || !workingHandler) { - throw new Error('Expected idle and working handlers to be registered') - } - - idleHandler('* Codex done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - - workingHandler() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - - idleHandler('* Codex done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - paneKey: makePaneKey('tab-1', LEAF_1), - ptyId: 'tab-pty' - }) - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-side-effects.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-side-effects.spec.ts index 503faad99ff..c9842a1bc74 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-side-effects.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-completion-side-effects.spec.ts @@ -3,10 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { RESET_TERMINAL_CURSOR_STYLE } from '../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles' import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async' -import { - AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS, - AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS -} from '../test-fixtures/pty-connection-test-constants' +import { AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS } from '../test-fixtures/pty-connection-test-constants' import { temporarilySetNavigatorUserAgent, sendTerminalInputThroughPane @@ -79,66 +76,6 @@ export function registerPtyConnectionHookCompletionSideEffectsTests(): void { await restoreTerminalTestGlobals() }) - it('preserves permission-title cursor and cache side effects through authoritative hook done', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState.agentStatusByPaneKey[paneKey] = { - state: 'waiting', - prompt: 'approve the tool call', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - agentType: 'claude', - paneKey, - stateHistory: [] - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks) - ) - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'done' - prompt: string - agentType: 'claude' - lastAssistantMessage: string - }) => void) - | undefined - if (!idleHandler || !statusHandler) { - throw new Error('Expected idle and hook status handlers to be registered') - } - - idleHandler('Claude Code permission') - - expect(deps.dispatchNotification).not.toHaveBeenCalled() - expect(deps.setCacheTimerStartedAt).not.toHaveBeenCalled() - expect(pane.terminal.write).toHaveBeenCalledWith( - RESET_TERMINAL_CURSOR_STYLE, - expect.any(Function) - ) - - statusHandler({ - state: 'done', - prompt: 'approve the tool call', - agentType: 'claude', - lastAssistantMessage: 'Done.' - }) - - expect(deps.setCacheTimerStartedAt).toHaveBeenCalledWith(paneKey, expect.any(Number)) - }) - it('preserves a genuine hook completion after suppressing an earlier idle title', async () => { // The completion settings subscription is shared per module load. await loadFreshTerminalModules() @@ -228,98 +165,6 @@ export function registerPtyConnectionHookCompletionSideEffectsTests(): void { expect(storeSubscribers).toHaveLength(1) }) - it('preserves accepted hook effects and shared completion with desktop banners and attention disabled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.ptyIdsByTabId = { 'tab-1': ['pty-hook'] } - mockStoreState.terminalLayoutsByTabId!['tab-1'].ptyIdsByLeafId = { [LEAF_1]: 'pty-hook' } - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - experimentalTerminalAttention: false, - notifications: { - enabled: true, - agentTaskComplete: false, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const paneKey = makePaneKey('tab-1', LEAF_1) - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks3) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'working' | 'done' - prompt: string - agentType: 'claude' - lastAssistantMessage?: string - }) => void) - | undefined - if (!idleHandler || !statusHandler) { - throw new Error('Expected idle and hook status handlers to be registered') - } - - statusHandler({ - state: 'working', - prompt: 'finish the implementation', - agentType: 'claude' - }) - idleHandler('Claude done') - - expect(deps.setCacheTimerStartedAt).not.toHaveBeenCalledWith(paneKey, expect.any(Number)) - expect(pane.terminal.write).not.toHaveBeenCalledWith( - RESET_TERMINAL_CURSOR_STYLE, - expect.any(Function) - ) - - statusHandler({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'claude', - lastAssistantMessage: 'Done.' - }) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).not.toHaveBeenCalled() - expect(deps.setCacheTimerStartedAt).toHaveBeenCalledWith(paneKey, expect.any(Number)) - expect(pane.terminal.write).toHaveBeenCalledWith( - RESET_TERMINAL_CURSOR_STYLE, - expect.any(Function) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - paneKey, - agentStatusSnapshot: expect.objectContaining({ - state: 'done', - agentType: 'claude', - lastAssistantMessage: 'Done.' - }) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) - it.each([ { name: 'delivers confirmed process exit despite the same stale working hook row', @@ -506,96 +351,6 @@ export function registerPtyConnectionHookCompletionSideEffectsTests(): void { ) }) - it('drops confirmed idle exit when a different hook owner appears between null samples', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks6 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-replaced-codex') - transportFactoryQueue.push(transport) - vi.useFakeTimers() - // Why: pin poll jitter so follow-up null samples cannot overtake replacement ownership. - const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0.5) - try { - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - // Why: one timer advance can start multiple reads; gate follow-up null samples until the replacement hook owner is installed. - let idleMode = false - let nullSamplesStarted = 0 - let releaseConfirmingNullSample: (() => void) | undefined - const confirmingNullSampleGate = new Promise((resolve) => { - releaseConfirmingNullSample = resolve - }) - getForegroundProcess.mockImplementation(async () => { - if (!idleMode) { - return 'codex' - } - nullSamplesStarted += 1 - if (nullSamplesStarted >= 2) { - await confirmingNullSampleGate - } - return null - }) - const paneKey = makePaneKey('tab-1', LEAF_1) - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks6) - ) - await flushAsyncTicks() - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!titleHandler || !idleHandler) { - throw new Error('Expected title and idle handlers to be registered') - } - - titleHandler('Codex working', 'Codex working') - await vi.advanceTimersByTimeAsync(2_500) - idleMode = true - for (let attempts = 0; nullSamplesStarted < 1; attempts += 1) { - if (attempts >= 10) { - throw new Error('Expected the first idle process inspection') - } - await vi.advanceTimersToNextTimerAsync() - } - // Why: let the first null sample record a pending process exit before the replacement owner is installed. - await flushAsyncTicks() - - mockStoreState.agentStatusByPaneKey[paneKey] = { - state: 'working', - prompt: 'replacement agent turn', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - agentType: 'claude', - paneKey, - stateHistory: [] - } - releaseConfirmingNullSample?.() - // Ignore cursor resets from setup so this assertion only covers the replacement idle event. - pane.terminal.write.mockClear() - idleHandler('Claude done') - await vi.advanceTimersByTimeAsync(800) - await vi.advanceTimersByTimeAsync(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).not.toHaveBeenCalledWith( - expect.objectContaining({ source: 'agent-task-complete' }) - ) - expect(pane.terminal.write).not.toHaveBeenCalledWith( - RESET_TERMINAL_CURSOR_STYLE, - expect.any(Function) - ) - } finally { - // Why: an assertion failure above must not leave Math.random pinned for later tests. - randomSpy.mockRestore() - } - }) - it('preserves replacement-agent title side effects through the process replacement veto', async () => { const { dispatchAgentHookTerminalLifecycle } = await import('../../agent-completion/agent-hook-terminal-lifecycle') diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts index 2093705eece..85b68256634 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-notification-settings-gating.spec.ts @@ -125,104 +125,6 @@ export function registerPtyConnectionNotificationSettingsGatingTests(): void { ) }) - it('does not suppress terminal bell notifications when agent-complete notifications are disabled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: false, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks2) - ) - - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!bellHandler || !idleHandler) { - throw new Error('Expected bell and idle handlers to be registered') - } - - bellHandler() - idleHandler('* Codex done') - vi.advanceTimersByTime(250) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ source: 'terminal-bell' }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete' - }) - ) - }) - - it('forwards agent completion to notification policy when desktop banners are disabled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - experimentalTerminalAttention: true, - notifications: { - enabled: true, - agentTaskComplete: false, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks3) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!idleHandler) { - throw new Error('Expected idle handler to be registered') - } - - idleHandler('* Codex done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - }) - it('shares one raw store subscriber for agent-complete notification settings across panes', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks4 = @@ -250,65 +152,6 @@ export function registerPtyConnectionNotificationSettingsGatingTests(): void { expect(storeSubscribers).toHaveLength(0) }) - it('offers generic title completions while desktop completion banners are disabled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks5 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: false, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const api = ( - globalThis as unknown as { - window: { api: { pty: { getForegroundProcess: ReturnType } } } - } - ).window.api - api.pty.getForegroundProcess.mockResolvedValue('codex') - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks5) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - - titleHandler('⠋ experimental-agent-observability', '⠋ experimental-agent-observability') - titleHandler('experimental-agent-observability', 'experimental-agent-observability') - await flushAsyncTicks() - expect(window.api.pty.inspectProcess).toHaveBeenCalledWith('pty-codex') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: 'experimental-agent-observability', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) - it('keeps an in-flight generic completion when desktop completion banners are enabled', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks6 = @@ -380,142 +223,6 @@ export function registerPtyConnectionNotificationSettingsGatingTests(): void { expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) }) - it('keeps raw title completion continuity across desktop banner changes', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks7 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks7) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - - titleHandler('Claude working', 'Claude working') - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: false - } - } - notifyStoreSubscribers() - titleHandler('Claude done', 'Claude done') - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: true - } - } - notifyStoreSubscribers() - titleHandler('Claude done', 'Claude done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: 'Claude done', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) - - it('keeps a scheduled agent completion across desktop banner changes', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks8 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks8) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!idleHandler) { - throw new Error('Expected onAgentBecameIdle to be registered') - } - - idleHandler('* Codex done') - vi.advanceTimersByTime(500) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: false - } - } - notifyStoreSubscribers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: true - } - } - notifyStoreSubscribers() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 500 - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) - it('restores a suppressed terminal bell when disabling pending agent completion', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks9 = @@ -573,137 +280,5 @@ export function registerPtyConnectionNotificationSettingsGatingTests(): void { expect.objectContaining({ source: 'terminal-bell' }) ) }) - - it('delivers completion after working and desktop banner changes', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks10 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks10) - ) - - const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as - | (() => void) - | undefined - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!workingHandler || !idleHandler) { - throw new Error('Expected working and idle handlers to be registered') - } - - workingHandler() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: false - } - } - notifyStoreSubscribers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: true - } - } - notifyStoreSubscribers() - idleHandler('* Codex done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) - - it('delivers completion after working starts with desktop banners disabled', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks11 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-codex') - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - enabled: true, - agentTaskComplete: false, - terminalBell: true, - suppressWhenFocused: false, - customSoundPath: null - } - } - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks11) - ) - - const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as - | (() => void) - | undefined - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!workingHandler || !idleHandler) { - throw new Error('Expected working and idle handlers to be registered') - } - - workingHandler() - mockStoreState.settings = { - ...mockStoreState.settings, - notifications: { - ...mockStoreState.settings.notifications, - agentTaskComplete: true - } - } - notifyStoreSubscribers() - idleHandler('* Codex done') - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 1) - expect(deps.dispatchNotification).not.toHaveBeenCalled() - vi.advanceTimersByTime(1) - expect(deps.dispatchNotification).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - expect(deps.dispatchNotification).toHaveBeenCalledTimes(1) - }) }) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts index 65e2a0e199c..aa5980cba17 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-task-complete-dispatch.spec.ts @@ -44,12 +44,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, environmentId) } - function notifyStoreSubscribers(): void { - for (const listener of storeSubscribers.slice()) { - listener(mockStoreState) - } - } - describe('connectPanePty', () => { beforeEach(async () => { vi.clearAllMocks() @@ -157,101 +151,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { ) }) - it('dispatches agent-task-complete from recognized hook completion events', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks3 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.ptyIdsByTabId = { 'tab-1': ['pty-hook'] } - mockStoreState.terminalLayoutsByTabId!['tab-1'].ptyIdsByLeafId = { [LEAF_1]: 'pty-hook' } - - vi.useFakeTimers() - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks3)) - ) - - const statusHandler = createdTransportOptions[0]?.onAgentStatus as - | ((payload: { - state: 'done' - prompt: string - agentType: 'codex' - lastAssistantMessage: string - }) => void) - | undefined - if (!statusHandler) { - throw new Error('Expected onAgentStatus to be registered') - } - - statusHandler({ - state: 'done', - prompt: 'finish the implementation', - agentType: 'codex', - lastAssistantMessage: 'Done.' - }) - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - - expect(deps.dispatchNotification).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: 'codex', - paneKey: makePaneKey('tab-1', LEAF_1) - }) - ) - }) - - it('preserves synthetic Codex permission titles', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks4 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-hook') - transportFactoryQueue.push(transport) - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { - launchConfig: { - agentArgs: '', - agentEnv: {} - } - } - - const pane = createPane(1) - const manager = createManager(1) - manager.getActivePane.mockReturnValue({ id: 1 }) - const deps = createDeps({ - startup: { - command: 'codex', - launchConfig: { - agentCommand: 'codex', - agentArgs: '', - agentEnv: {} - }, - launchToken: 'launch-manual', - launchAgent: 'codex' - } - }) - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks4)) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - - titleHandler('Codex - action required', 'Codex - action required') - - expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Codex - action required') - expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', 'Codex - action required') - }) - it('normalizes Pi-compatible remote titles to authoritative OMP launch identity', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks5 = @@ -335,61 +234,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { ) }) - it('keeps GPU rendering enabled for OMP titles whose cwd is Gemini', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks6 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-omp-gemini-cwd') - transportFactoryQueue.push(transport) - enableActiveRuntimeEnvironment() - mockStoreState.tabsByWorktree = { - 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty', launchAgent: 'omp' }] - } - - const pane = createPane(1) - const manager = createManager(1) - manager.getActivePane.mockReturnValue({ id: 1 }) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks6)) - ) - - const titleHandler = createdTransportOptions[0]?.onTitleChange as - | ((title: string, rawTitle: string) => void) - | undefined - if (!titleHandler) { - throw new Error('Expected onTitleChange to be registered') - } - - manager.setPaneGpuRendering.mockClear() - - titleHandler('\u280b Pi', '\u280b π: gemini') - - expect(manager.setPaneGpuRendering).toHaveBeenCalledTimes(1) - expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, true) - expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, '\u280b OMP') - expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', '\u280b OMP') - }) - - it('leaves local IPC OSC 9999 status ownership in the main runtime', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks7 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport('pty-local') - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks7)) - ) - - expect(createdTransportOptions[0]?.onAgentStatus).toBeUndefined() - }) - it('queues the idle cursor reset behind hidden agent output', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks8 = @@ -431,126 +275,6 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { expect(pane.terminal.write).toHaveBeenCalledWith(`\x1b[6 q${RESET_TERMINAL_CURSOR_STYLE}`) }) - it('waits briefly for delayed agent status before dispatching task-complete', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks9 = - await vi.importMock('@/lib/agent-status') - const { useNotificationDispatch } = await vi.importActual< - typeof UseNotificationDispatchModule - >('../../notifications/use-notification-dispatch') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - const dispatchNotification = useNotificationDispatch('wt-1') - const paneKey = makePaneKey('tab-1', LEAF_1) - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps({ dispatchNotification }) - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks9)) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!idleHandler) { - throw new Error('Expected onAgentBecameIdle to be registered') - } - - idleHandler('* Codex done') - expect(window.api.notifications.dispatch).not.toHaveBeenCalled() - - mockStoreState.agentStatusByPaneKey[paneKey] = { - state: 'done', - prompt: 'Use delayed hook status in notification', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - agentType: 'codex', - paneKey, - terminalTitle: '* Codex done', - stateHistory: [], - lastAssistantMessage: 'Delayed status arrived.' - } - - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) - await flushAsyncTicks() - - expect(window.api.notifications.dispatch).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - agentType: 'codex', - agentState: 'done', - agentPrompt: 'Use delayed hook status in notification', - agentLastAssistantMessage: 'Delayed status arrived.' - }) - ) - }) - - it('waits past the grace delay when the assistant message arrives shortly after it', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks10 = - await vi.importMock('@/lib/agent-status') - const { useNotificationDispatch } = await vi.importActual< - typeof UseNotificationDispatchModule - >('../../notifications/use-notification-dispatch') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - vi.useFakeTimers() - const dispatchNotification = useNotificationDispatch('wt-1') - const paneKey = makePaneKey('tab-1', LEAF_1) - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps({ dispatchNotification }) - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks10)) - ) - - const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as - | ((title: string) => void) - | undefined - if (!idleHandler) { - throw new Error('Expected onAgentBecameIdle to be registered') - } - - idleHandler('* Codex done') - vi.advanceTimersByTime(250) - await flushAsyncTicks() - expect(window.api.notifications.dispatch).not.toHaveBeenCalled() - - vi.advanceTimersByTime(100) - mockStoreState.agentStatusByPaneKey[paneKey] = { - state: 'done', - prompt: 'Use the late hook status in notification', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - agentType: 'codex', - paneKey, - terminalTitle: '* Codex done', - stateHistory: [], - lastAssistantMessage: 'Late status arrived.' - } - notifyStoreSubscribers() - await flushAsyncTicks() - vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS - 350) - await flushAsyncTicks() - - expect(window.api.notifications.dispatch).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: '* Codex done', - agentType: 'codex', - agentState: 'done', - agentPrompt: 'Use the late hook status in notification', - agentLastAssistantMessage: 'Late status arrived.' - }) - ) - }) - it('does not use stale agent status from an earlier turn in task-complete notifications', async () => { const { connectPanePty } = await import('../connect-pane-pty') const agentTitleMocks11 = @@ -610,90 +334,5 @@ export function registerPtyConnectionTaskCompleteDispatchTests(): void { expect('agentLastAssistantMessage' in dispatchArgs).toBe(false) expect('agentType' in dispatchArgs).toBe(false) }) - - it('does not attach agent fields to terminal-bell notifications', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks12 = - await vi.importMock('@/lib/agent-status') - const { useNotificationDispatch } = await vi.importActual< - typeof UseNotificationDispatchModule - >('../../notifications/use-notification-dispatch') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - const dispatchNotification = useNotificationDispatch('wt-1') - const paneKey = makePaneKey('tab-1', LEAF_1) - mockStoreState.agentStatusByPaneKey[paneKey] = { - state: 'done', - prompt: 'Should not leak into BEL', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - agentType: 'codex', - paneKey, - stateHistory: [] - } - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps({ dispatchNotification }) - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks12)) - ) - - const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined - if (!bellHandler) { - throw new Error('Expected onBell to be registered') - } - - vi.useFakeTimers() - bellHandler() - vi.advanceTimersByTime(250) - - const dispatchArgs = (window.api.notifications.dispatch as ReturnType).mock - .calls[0]?.[0] as Record | undefined - if (!dispatchArgs) { - throw new Error('Expected notification dispatch') - } - expect(dispatchArgs.source).toBe('terminal-bell') - expect('agentType' in dispatchArgs).toBe(false) - expect('agentState' in dispatchArgs).toBe(false) - expect('agentPrompt' in dispatchArgs).toBe(false) - expect('agentToolName' in dispatchArgs).toBe(false) - expect('agentToolInput' in dispatchArgs).toBe(false) - expect('agentLastAssistantMessage' in dispatchArgs).toBe(false) - expect('agentTurnOutcome' in dispatchArgs).toBe(false) - }) - - // Why: agent-row removal belongs to process/PTY lifecycle, not title reversion, so interrupts can't disappear the activity row. - it('clears the cache timer without removing agent status when the title tracker sees exit', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks13 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - ...mockPanePtyArgs(pane, manager, bindPaneAgentTitleMocks(deps, agentTitleMocks13)) - ) - - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Captured transport options expose onAgentExited as an optional zero-argument callback. - const agentExitedHandler = createdTransportOptions[0]?.onAgentExited as - | (() => void) - | undefined - if (!agentExitedHandler) { - throw new Error('Expected onAgentExited to be registered') - } - - agentExitedHandler() - - expect(deps.setCacheTimerStartedAt).toHaveBeenCalledWith(makePaneKey('tab-1', LEAF_1), null) - expect(deps.onAgentExitedRef.current).toHaveBeenCalledWith(LEAF_1) - expect(mockStoreState.removeAgentStatus).not.toHaveBeenCalled() - }) }) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-renderer-risk-repaint.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-renderer-risk-repaint.spec.ts deleted file mode 100644 index cecdb98ecc6..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-renderer-risk-repaint.spec.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { - bindPtyConnectionTestMocks, - ptyConnectionTestMocks -} from '../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async' -import { temporarilySetNavigatorUserAgent } from '../test-fixtures/pty-connection-test-dom' -import { - createMockTransport, - createPane, - createManager, - type ConnectCallbacks, - type MockTransport -} from '../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../test-fixtures/pty-connection-test-deps' -import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - loadFreshTerminalModules, - restoreTerminalTestGlobals -} from '../test-fixtures/pty-connection-test-environment' - -export function registerPtyConnectionRendererRiskRepaintTests(): void { - const { resetAndRefreshAllTerminalWebglAtlases, scheduleTerminalWebglAtlasRecovery } = - ptyConnectionTestMocks - - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - - function expectNoGlobalAtlasRecovery(): void { - // Why: the removed output path requested recovery 200ms before its global reset ran. - expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled() - expect(resetAndRefreshAllTerminalWebglAtlases).not.toHaveBeenCalled() - } - - describe('connectPanePty', () => { - beforeEach(async () => { - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('does not switch renderers for Arabic output', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('Arabic: السلام عليكم\r\n') - - expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled() - expect(pane.terminal.write).toHaveBeenCalledWith( - 'Arabic: السلام عليكم\r\n', - expect.any(Function) - ) - }) - - it('does not switch renderers across split background SGR PTY chunks', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks2) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('\x1b[4') - capturedDataCallback.current?.('8;2;52') - expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled() - - capturedDataCallback.current?.(';52;52m codex block \x1b[0m\r\n') - - expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled() - }) - - it('avoids atlas clears for captured redraw chunks split mid-sequence', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent('Mozilla/5.0 (Macintosh)') - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks10 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - ;(pane.terminal.buffer.active as { type: 'normal' | 'alternate' }).type = 'alternate' - const refresh = vi.fn() - let parseCallback: (() => void) | undefined - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - parseCallback = callback - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks10) - ) - await flushAsyncTicks(6) - - // Captured from a real vim session: a 1024-byte PTY read boundary cuts the cursor move \x1b[30;5H into "\x1b[30" + ";5H". - capturedDataCallback.current?.('"rules": {\x1b[29;15H\x1b[K\x1b[30') - parseCallback?.() - - capturedDataCallback.current?.( - ';5H "js-combine-iterations": "off"\r\n }\x1b[31;6H\x1b[K\x1b[33;1H\x1b[?25h' - ) - parseCallback?.() - expect(refresh).toHaveBeenCalled() - expectNoGlobalAtlasRecovery() - } finally { - restoreNavigator() - } - }) - }) -} - -export function registerPtyConnectionRendererDrawingGlyphTests(): void { - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - describe('connectPanePty', () => { - beforeEach(async () => { - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('keeps terminal UI drawing glyphs on the active renderer', async () => { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const manager = createManager(1) - const deps = createDeps() - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(deps as never, agentTitleMocks) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('⠋ Working ├─ file.ts █ progress \uE0B0 prompt\r\n') - - expect(manager.markPaneHasComplexScriptOutput).not.toHaveBeenCalled() - expect(pane.terminal.write).toHaveBeenCalledWith( - '⠋ Working ├─ file.ts █ progress \uE0B0 prompt\r\n', - expect.any(Function) - ) - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-windows-cjk-repaint.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-windows-cjk-repaint.spec.ts deleted file mode 100644 index 371a3ac098e..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-windows-cjk-repaint.spec.ts +++ /dev/null @@ -1,382 +0,0 @@ -import { - bindPtyConnectionTestMocks, - ptyConnectionTestMocks -} from '../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { flushAsyncTicks } from '../test-fixtures/pty-connection-test-async' -import { - temporarilySetNavigatorUserAgent, - sendTerminalInputThroughPane -} from '../test-fixtures/pty-connection-test-dom' -import { - createMockTransport, - createPane, - createManager, - type ConnectCallbacks, - type MockTransport -} from '../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../test-fixtures/pty-connection-test-deps' -import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - loadFreshTerminalModules, - restoreTerminalTestGlobals -} from '../test-fixtures/pty-connection-test-environment' - -export function registerPtyConnectionWindowsCjkRepaintTests(): void { - const { resetAndRefreshAllTerminalWebglAtlases, scheduleTerminalWebglAtlasRecovery } = - ptyConnectionTestMocks - - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - - function expectNoGlobalAtlasRecovery(): void { - // Why: the removed output path requested recovery 200ms before its global reset ran. - expect(scheduleTerminalWebglAtlasRecovery).not.toHaveBeenCalled() - expect(resetAndRefreshAllTerminalWebglAtlases).not.toHaveBeenCalled() - } - - describe('connectPanePty', () => { - beforeEach(async () => { - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - it('does not schedule WebGL atlas recovery for plain synchronized foreground frames', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent('Mozilla/5.0 (Macintosh)') - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks2 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - let parseCallback: (() => void) | undefined - pane.terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - parseCallback = callback - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks2) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('\x1b[?2026hplain claude frame\x1b[?2026l') - parseCallback?.() - expectNoGlobalAtlasRecovery() - } finally { - restoreNavigator() - } - }) - - it('forces a viewport refresh for native Windows CJK foreground output after terminal input', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent( - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' - ) - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks6 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const refresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - callback?.() - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks6) - ) - await flushAsyncTicks(6) - sendTerminalInputThroughPane(pane, '已经安装完成,软件已更新后重启。') - - capturedDataCallback.current?.('已经安装完成,软件已更新后重启。') - - expect(refresh).toHaveBeenCalledWith(0, 39, true) - } finally { - restoreNavigator() - } - }) - - it('forces the native Windows CJK repaint path for foreground agent output without recent terminal input', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent( - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' - ) - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks7 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const refresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - callback?.() - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks7) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('已经安装完成,软件已更新后重启。') - - expect(refresh).toHaveBeenCalledWith(0, 39, true) - } finally { - restoreNavigator() - } - }) - - it('does not force renderer-risk repaint for ordinary non-ASCII output', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent( - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' - ) - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks8 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const refresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - callback?.() - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks8) - ) - await flushAsyncTicks(6) - sendTerminalInputThroughPane(pane, 'abc 123 ✓') - - capturedDataCallback.current?.('abc 123 ✓') - - expect(refresh).not.toHaveBeenCalled() - } finally { - restoreNavigator() - } - }) - - it('does not repaint ordinary non-ASCII output on non-Windows clients', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent('Mozilla/5.0 (Macintosh)') - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks9 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const refresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - callback?.() - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks9) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('abc 123 ✓') - - expect(refresh).not.toHaveBeenCalled() - } finally { - restoreNavigator() - } - }) - - it('schedules a follow-up repaint for Claude-style in-place prompt redraws on native Windows', async () => { - // Why: issue #5656/#5653 — native Windows ConPTY paints Claude's in-place prompt redraw one frame late; needs a follow-up next-frame repaint. - const restoreNavigator = temporarilySetNavigatorUserAgent( - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' - ) - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks10 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const refresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof refresh } - } - terminal._core = { refresh } - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => { - callback?.() - }) - - connectPanePty( - pane as never, - createManager(1) as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks10) - ) - await flushAsyncTicks(6) - - // User typed into the prompt; Claude redraws the input line in place. - capturedDataCallback.current?.('\r\x1b[3Gzzzx\x1b[K') - - // One synchronous settle refresh + one follow-up next-frame refresh. - expect(refresh).toHaveBeenCalledTimes(2) - expect(refresh).toHaveBeenNthCalledWith(1, 0, 39, true) - expect(refresh).toHaveBeenNthCalledWith(2, 0, 39, true) - } finally { - restoreNavigator() - } - }) - - it('coalesces forced foreground refreshes when WebGL is live', async () => { - const restoreNavigator = temporarilySetNavigatorUserAgent('Mozilla/5.0 (Macintosh)') - await loadFreshTerminalModules() - try { - const { connectPanePty } = await import('../connect-pane-pty') - const agentTitleMocks12 = - await vi.importMock('@/lib/agent-status') - const transport = createMockTransport() - const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null } - transport.connect.mockImplementation( - async ({ callbacks }: { callbacks: ConnectCallbacks }) => { - capturedDataCallback.current = callbacks.onData ?? null - return 'pty-id' - } - ) - transportFactoryQueue.push(transport) - - const pane = createPane(1) - const synchronousRefresh = vi.fn() - const debouncedRefresh = vi.fn() - const terminal = pane.terminal as typeof pane.terminal & { - _core?: { refresh: typeof synchronousRefresh } - refresh: typeof debouncedRefresh - } - terminal._core = { refresh: synchronousRefresh } - terminal.refresh = debouncedRefresh - terminal.write = vi.fn((_data: string | Uint8Array, callback?: () => void) => callback?.()) - const manager = createManager(1) - manager.hasWebglRenderer.mockReturnValue(true) - - connectPanePty( - pane as never, - manager as never, - bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks12) - ) - await flushAsyncTicks(6) - - capturedDataCallback.current?.('\r\x1b[3Gzzzx\x1b[K') - - expect(debouncedRefresh).toHaveBeenCalledWith(0, 39) - expect(synchronousRefresh).not.toHaveBeenCalled() - } finally { - restoreNavigator() - } - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts index 2021a634238..0f56921a577 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts @@ -1,7 +1,6 @@ import { describe } from 'vitest' import { registerPtyConnectionCommandFinishedCleanupTests } from '../agent-identity/pty-connection-command-finished-cleanup.spec' import { registerPtyConnectionCommandFinishedInterruptArbitrationTests } from '../input/pty-connection-command-finished-interrupt-arbitration.spec' -import { registerPtyConnectionHookCompletionBellArbitrationTests } from '../notifications/pty-connection-hook-completion-bell-arbitration.spec' import { registerPtyConnectionBellQueryReplyAndStaleInputTests } from '../input/pty-connection-bell-query-reply-and-stale-input.spec' import { registerPtyConnectionHookCompletionSideEffectsTests } from '../notifications/pty-connection-hook-completion-side-effects.spec' import { registerPtyConnectionMainSideEffectAuthorityTests } from '../emulation/pty-connection-main-side-effect-authority.spec' @@ -13,7 +12,6 @@ describe('pty-connection-command-finished-cleanup', () => { registerPtyConnectionCommandFinishedInterruptArbitrationTests() }) describe('pty-connection-hook-completion-bell-arbitration', () => { - registerPtyConnectionHookCompletionBellArbitrationTests() registerPtyConnectionBellQueryReplyAndStaleInputTests() }) describe( diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts index cc231546ec5..897ff913c74 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts @@ -15,8 +15,6 @@ import { registerPtyConnectionRemoteWindowsFocusReportTests, registerPtyConnectionWindowsFocusReportAuthorityTests } from '../input/pty-connection-windows-focus-report-authority.spec' -import { registerPtyConnectionWindowsCjkRepaintTests } from '../output/pty-connection-windows-cjk-repaint.spec' -import { registerPtyConnectionRendererRiskRepaintTests } from '../output/pty-connection-renderer-risk-repaint.spec' import { registerPtyConnectionTerminalInputGatingTests } from '../input/pty-connection-terminal-input-gating.spec' // Main's answer to the window's layout commands, as a switch-on build sends them. @@ -40,6 +38,4 @@ describe('pty-connection-windows-keyboard-reset', () => { registerPtyConnectionWindowsFocusReportAuthorityTests() registerPtyConnectionWindowsCursorResetDisposalTests() }) -describe('pty-connection-windows-cjk-repaint', registerPtyConnectionWindowsCjkRepaintTests) -describe('pty-connection-renderer-risk-repaint', registerPtyConnectionRendererRiskRepaintTests) describe('pty-connection-terminal-input-gating', registerPtyConnectionTerminalInputGatingTests) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts index 4f5041d196a..8bac2e02429 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts @@ -1,4 +1,3 @@ -import { registerPtyConnectionRendererDrawingGlyphTests } from '../output/pty-connection-renderer-risk-repaint.spec' import { describe } from 'vitest' import { registerPtyConnectionPendingSpawnTests } from '../spawn/pty-connection-pending-spawn.spec' import { registerPtyConnectionFreshSpawnGuardsTests } from '../spawn/pty-connection-fresh-spawn-guards.spec' @@ -30,7 +29,6 @@ describe('pty-connection-startup-command-delivery', () => { describe('pty-connection-startup-draft-delivery', registerPtyConnectionStartupDraftDeliveryTests) describe('pty-connection-deliberate-sleep-guard', registerPtyConnectionDeliberateSleepGuardTests) describe('pty-connection-remote-runtime-attach', () => { - registerPtyConnectionRendererDrawingGlyphTests() registerPtyConnectionRemoteRuntimeAttachTests() registerPtyConnectionRuntimePaneTransportRoutingTests() }) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 0d665e9cff9..a973b81ce24 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1590,6 +1590,12 @@ "couldNotStopTheAgent": "Couldn't stop the agent.", "editSavedArguments": "Edit them in Settings > Agents > Arguments.", "emptyMessage": "This message is empty, so it was not sent.", + "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.", "fullAccessAsRoot": "{{agent}} won't use Full access while it runs as root. Choose another permission for {{agent}} in Settings → Agents for the computer running this chat, then start a new chat.", "historyInOtherAccount": "This chat's history is in another Claude account. Switch back to that account to continue it.", "historyTooLarge": "This conversation's history is too large to restore here.", @@ -2043,12 +2049,17 @@ "recipeResultNotJsonObject": "Recipe stdout must be one JSON object.", "recipeResultPairingCodeInvalid": "Recipe result pairingCode is not a valid Orca pairing code.", "recipeResultProjectRootNotAbsolute": "Recipe result projectRoot must be an absolute runtime path.", + "recipeTimedOut": "The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.", "remoteRepoUnsupported": "Ephemeral VM recipes run on the local desktop host in v1.", "repoNotFound": "Repo not found: {{repoId}}", + "resumeExited": "Resume exited with code {{exitCode}}.", + "resumeExitedWithoutCode": "Resume exited with code unknown.", "runtimeNotFound": "Unknown ephemeral VM runtime: {{runtimeId}}", "runtimeRepoMissing": "Ephemeral VM runtime has no repo id: {{runtimeId}}", "sshTargetRemoveFailed": "Failed to remove the hidden SSH target.", - "startRefUnresolved": "Could not resolve provisioned-root start ref: {{ref}}" + "startRefUnresolved": "Could not resolve provisioned-root start ref: {{ref}}", + "suspendExited": "Suspend exited with code {{exitCode}}.", + "suspendExitedWithoutCode": "Suspend exited with code unknown." } }, "jira": { diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 14616277c51..558e628ce53 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -4205,6 +4205,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Aktivieren" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Für ein anderes Fenster angepasst", + "fitHere": "Hier anpassen" } } }, diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 6cec9248af5..4a74bb1fb72 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4455,6 +4455,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Turn on" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Sized for another window", + "fitHere": "Fit here" } } }, @@ -19749,6 +19753,12 @@ }, "reasoning": "Reasoning", "failureWords": { + "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.", "theAgent": "The agent", "providerStartFailed": "{{agent}} stopped before it finished starting.", "savedConversationMissing": "{{agent}} couldn't find this chat's saved conversation.", @@ -22629,7 +22639,18 @@ "confirm": "Delete all listed worktrees", "preservedBranches": "Some nested worktree branches were kept" }, - "setupTerminalTitle": "Setup" + "setupTerminalTitle": "Setup", + "delete": { + "detachingChildren": "Detaching children...", + "childrenPreservedTitle": "Child workspaces will be kept", + "childrenCannotBeKeptTitle": "Child workspaces cannot be kept", + "childrenPreservedDescription": "Direct children will become top-level workspaces. Their files, terminals, and nested children will be kept.", + "detachChildren": "Detach and keep child workspaces", + "nestedChildrenCannotBeKept": "Child workspace folders inside this workspace must be moved outside it before they can be kept.", + "childrenChanged": "Child workspaces changed. Review the workspace list and try again.", + "childrenChangedClearPreserve": "Child workspaces changed. Clear this option to review deletion.", + "detachFailed": "Could not detach all child workspaces. The parent was not deleted. {{error}}" + } }, "projectBoard": { "noColumnField": "This board view has no single-select or iteration field to group by, so Orca is listing items instead.", @@ -24224,7 +24245,12 @@ "cleanupInterrupted": "Cleanup was interrupted. Retry cleanup to continue.", "sshTargetRemoveFailed": "Failed to remove the hidden SSH target.", "recipeExitedWithoutCode": "Recipe exited with code unknown.", - "destroyExitedWithoutCode": "Destroy exited with code unknown." + "destroyExitedWithoutCode": "Destroy exited with code unknown.", + "suspendExited": "Suspend exited with code {{exitCode}}.", + "suspendExitedWithoutCode": "Suspend exited with code unknown.", + "resumeExited": "Resume exited with code {{exitCode}}.", + "resumeExitedWithoutCode": "Resume exited with code unknown.", + "recipeTimedOut": "The recipe {{mode}} step did not finish within {{timeout}}, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer." } }, "installDirAcl": { diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index df52354cc2d..de16ce36a27 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -3735,6 +3735,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Activar" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Ajustado para otra ventana", + "fitHere": "Ajustar aquí" } } }, diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 3a957c16203..89ff347f348 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -3960,6 +3960,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Activer" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Dimensionné pour une autre fenêtre", + "fitHere": "Ajuster ici" } } }, diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 8ab72e589c4..a71d0ef7834 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -3667,6 +3667,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "オンにする" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "別のウィンドウに合わせたサイズ", + "fitHere": "ここに合わせる" } } }, diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 186b081bce4..196f742f9ee 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -3667,6 +3667,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "켜기" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "다른 창에 맞춘 크기", + "fitHere": "여기에 맞추기" } } }, diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 463218679ec..8d82c4b94e0 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -16654,6 +16654,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Ligar" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Dimensionado para outra janela", + "fitHere": "Ajustar aqui" } }, "quick": { diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index e398b7a83e4..66c2bfac9ad 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -4310,6 +4310,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Включить" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Размер задан другим окном", + "fitHere": "Подогнать здесь" } } }, diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 1552d74e8c5..0be9067070f 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -4178,6 +4178,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "Aç" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "Başka bir pencereye göre boyutlandı", + "fitHere": "Buraya sığdır" } } }, diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index 98c0e87b53f..27c0ac4d71b 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -4122,6 +4122,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "開啟" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "已依其他視窗調整大小", + "fitHere": "在此調整" } } }, diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 12b6c902094..aa5a22b0d91 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -3667,6 +3667,10 @@ }, "WslHostUnavailableBanner": { "turnOn": "开启" + }, + "RemoteViewportHeldChip": { + "sizedElsewhere": "已按其他窗口调整大小", + "fitHere": "在此适配" } } }, diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-callers.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-callers.ts index 0a66d5e4a40..8469ad2379a 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-callers.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-callers.ts @@ -27,6 +27,8 @@ export type StructuredAgentLaunchOptions = StructuredLaunchPromptOptions & { // Conversation adoption is launch identity, not a preference; see launchIdentity. resumeFrom?: StructuredAgentSessionResumeSource forkFrom?: StructuredAgentSessionForkSource + /** Client-only admission requirement; reacquired from the child after reload. */ + forkRequiresInheritedOriginal?: boolean /** The host the route decided on; read only by the caller that starts the launch. */ executionHostId?: ExecutionHostId /** The saved selection a paired host reported it will seed; read only by the starting caller. */ diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-call.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-call.ts index 6cc1c8f07df..ab487d4d727 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-call.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-call.ts @@ -1,6 +1,5 @@ import { structuredAgentSessionSettledSends } from '../../../../../shared/agent-session/requests/structured-agent-session-send-settlement' import { - AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_SELECTION_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_SKILLS_RUNTIME_CAPABILITY } from '../../../../../shared/agent-session/agent-session-create-capabilities' @@ -11,6 +10,7 @@ import type { import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code' import { isAgentSessionCreateAdmissionRefusal, + isAgentSessionForkSourceAdmissionRefusal, isDefinitiveAgentSessionCreateRefusal } from '../../../../../shared/agent-session/failures/agent-session-definitive-refusal' import { readAgentSessionRefusalReference } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals' @@ -18,7 +18,6 @@ import { readAgentSessionErrorRefusal } from '../../../../../shared/agent-sessio import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { supportsStructuredAgentSessionCreateOptionsMode, - structuredAgentSessionHostCapabilityState, structuredAgentSessionHostSupports, supportsStructuredAgentSessionCreateMessage } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-support' @@ -39,6 +38,17 @@ import { StructuredAgentSessionCreateUnknownOutcomeError } from './structured-agent-session-launch-errors' +import { + requireHostForkSupport, + inheritedForkCreateOptions, + refuseUnsentInheritedFork +} from './structured-agent-session-launch-fork-support' +import { + RuntimeConnectionChangedBeforeSendError, + RuntimeRpcCallError +} from '@/runtime/rpc/calls/runtime-rpc-result' +export { STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL } from './structured-agent-session-launch-fork-support' + type LaunchSeed = Readonly> | undefined const DEFINITIVE_CREATE_FAILURE_CODES = [ 'structured_agent_session_unsupported', @@ -90,35 +100,6 @@ async function requireHostCreateSupport( return support.seedOptions } -/** The refusal a fork gets from a host that does not advertise forks; nothing was sent to it. */ -export const STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL = - 'structured_agent_session_fork_unsupported' - -async function requireHostForkSupport(intent: StructuredAgentSessionLaunchIntent): Promise { - if (!intent.params.forkFrom) { - return - } - const support = await structuredAgentSessionHostCapabilityState( - intent.target, - AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY - ) - if (support === 'supported') { - return - } - // An unanswered probe may follow a create whose reply was lost, so it settles nothing. - if (support === 'unknown') { - throw new StructuredAgentSessionCreateUnknownOutcomeError( - 'The host could not say whether it forks chats.', - 'runtime_unavailable' - ) - } - abandonStructuredAgentSessionLaunchIntent(intent) - throw new StructuredAgentSessionCreateRefusalError( - STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL, - STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL - ) -} - /** Refuse paired hosts that would grant more access than requested; the chat permission gate owns the explanation. */ const STRUCTURED_LAUNCH_HOST_PERMISSION_REFUSAL = 'structured_agent_session_host_permission' @@ -165,6 +146,14 @@ export async function launchStructuredAgentSession( } delete intent.createAfter } + let forkOptions: Awaited> + if (intent.params.forkFrom) { + try { + forkOptions = await inheritedForkCreateOptions(intent) + } catch (error) { + refuseUnsentInheritedFork(intent, priorCreateOutcomeUnknown, error) + } + } await requireHostForkSupport(intent) const hostSeed = await requireHostCreateSupport(intent) if (intent.target.kind !== 'local') { @@ -212,9 +201,17 @@ export async function launchStructuredAgentSession( result = await callStructuredAgentSession>( intent.target, 'agentSession.create', - params + params, + ...(forkOptions ? ([forkOptions] as const) : ([] as const)) ) } catch (error) { + if ( + forkOptions?.expectedEnvironmentRuntimeId && + (error instanceof RuntimeConnectionChangedBeforeSendError || + (error instanceof RuntimeRpcCallError && error.code === 'runtime_environment_changed')) + ) { + refuseUnsentInheritedFork(intent, priorCreateOutcomeUnknown) + } const code = definitiveStructuredAgentSessionCreateErrorCode(error) if (code) { abandonStructuredAgentSessionLaunchIntent(intent) @@ -233,7 +230,8 @@ export async function launchStructuredAgentSession( !priorCreateOutcomeUnknown && result.refusal.createAttemptRefusedBeforeCommit === true && refusal !== undefined && - isAgentSessionCreateAdmissionRefusal(refusal) + (isAgentSessionCreateAdmissionRefusal(refusal) || + (!!intent.params.forkFrom && isAgentSessionForkSourceAdmissionRefusal(refusal))) // Attempt proof cannot settle an earlier create whose reply was lost. if ( !attemptRefusedBeforeCommit && diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork-support.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork-support.ts new file mode 100644 index 00000000000..f2ea40992fc --- /dev/null +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork-support.ts @@ -0,0 +1,176 @@ +import { + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY +} from '../../../../../shared/agent-session/agent-session-create-capabilities' +import { + AGENT_SESSION_AGENTS_METHOD, + decodeAgentSessionAgentsResult +} from '../../../../../shared/agent-session/agent-session-registered-agents' +import type { + AgentSessionHistoryPage, + AgentSessionHistoryResult +} from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import { nativeChatForkRequiresInheritedOriginal } from '../../../../../shared/native-chat/native-chat-fork-offer' +import { runtimeEnvironmentCapabilityProof } from '@/runtime/rpc/compatibility/runtime-capability-proof' +import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' +import { structuredAgentSessionHostCapabilityState } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-support' +import { + abandonStructuredAgentSessionLaunchIntent, + type StructuredAgentSessionLaunchIntent +} from '../../launch-structured-agent-session' +import { + StructuredAgentSessionCreateRefusalError, + StructuredAgentSessionCreateUnknownOutcomeError +} from './structured-agent-session-launch-errors' + +/** The refusal a fork gets from a host that does not advertise forks; nothing was sent to it. */ +export const STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL = + 'structured_agent_session_fork_unsupported' + +export async function requireHostForkSupport( + intent: StructuredAgentSessionLaunchIntent +): Promise { + if (!intent.params.forkFrom) { + return + } + const support = await structuredAgentSessionHostCapabilityState( + intent.target, + AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY + ) + if (support === 'supported') { + return + } + // An unanswered probe may follow a create whose reply was lost, so it settles nothing. + if (support === 'unknown') { + throw new StructuredAgentSessionCreateUnknownOutcomeError( + 'The host could not say whether it forks chats.', + 'runtime_unavailable' + ) + } + abandonStructuredAgentSessionLaunchIntent(intent) + throw new StructuredAgentSessionCreateRefusalError( + STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL, + STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL + ) +} + +/** A no-send this attempt cannot settle a preceding lost create. */ +export function refuseUnsentInheritedFork( + intent: StructuredAgentSessionLaunchIntent, + priorUnknown: boolean, + error?: unknown +): never { + if (priorUnknown) { + throw new StructuredAgentSessionCreateUnknownOutcomeError( + 'The host could not confirm the fork.', + 'runtime_unavailable' + ) + } + const code = + error instanceof StructuredAgentSessionCreateRefusalError && + error.code === STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL + ? STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL + : 'runtime_unavailable' + abandonStructuredAgentSessionLaunchIntent(intent) + throw new StructuredAgentSessionCreateRefusalError(code, code) +} + +/** Restored intents have no row context; read only the requested child's saved journal. */ +async function requiresInheritedOriginal( + intent: StructuredAgentSessionLaunchIntent +): Promise { + const source = intent.params.forkFrom + if (!source) { + return false + } + if (intent.forkRequiresInheritedOriginal !== undefined) { + return intent.forkRequiresInheritedOriginal + } + const agents = decodeAgentSessionAgentsResult( + await callStructuredAgentSession(intent.target, AGENT_SESSION_AGENTS_METHOD, {}) + ) + const fork = agents?.find((row) => row.agent === intent.agent)?.capabilities.fork + if (!fork) { + throw new Error('Fork support is unavailable') + } + if (fork === 'checkpoint') { + return false + } + const pages: AgentSessionHistoryPage[] = [] + let history = await callStructuredAgentSession( + intent.target, + 'agentSession.history', + { sessionId: source.sessionId, direction: 'tail', limit: 200 } + ) + for (;;) { + if (!history.ok) { + throw new Error('Child history is unavailable') + } + pages.push(history.page) + if (!history.page.hasOlder) { + break + } + history = await callStructuredAgentSession( + intent.target, + 'agentSession.history', + { + sessionId: source.sessionId, + direction: 'before', + cursor: history.page.window.oldest ?? undefined, + limit: 200 + } + ) + } + const items: AgentJournalRenderItem[] = pages.toReversed().flatMap((page) => page.items) + if (!items.some((item) => item.itemId === source.throughItemId)) { + throw new Error('Child response is unavailable') + } + return nativeChatForkRequiresInheritedOriginal(items, fork, source.throughItemId, { + submissions: pages.toReversed().flatMap((page) => page.submissions), + latestTurn: pages[0]?.latestTurn + }) +} + +/** The proof stays ephemeral; the actual create is pinned to its runtime on the sending socket. */ +export async function inheritedForkCreateOptions( + intent: StructuredAgentSessionLaunchIntent +): Promise< + | { expectedEnvironmentRuntimeId: string; expectedEnvironmentPairingRevision: number | undefined } + | undefined +> { + const required = await requiresInheritedOriginal(intent) + intent.forkRequiresInheritedOriginal = required + if (!required) { + return undefined + } + const support = + intent.target.kind === 'local' + ? await structuredAgentSessionHostCapabilityState( + intent.target, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY + ) + : undefined + if (support === 'unknown') { + throw new Error('Original fork support is unavailable') + } + const proof = + intent.target.kind === 'environment' + ? await runtimeEnvironmentCapabilityProof( + intent.target.environmentId, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY + ) + : undefined + if (support === 'unsupported' || proof?.supported === false) { + throw new StructuredAgentSessionCreateRefusalError( + STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL, + STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL + ) + } + return proof + ? { + expectedEnvironmentRuntimeId: proof.runtimeId, + expectedEnvironmentPairingRevision: proof.pairingRevision + } + : undefined +} diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork.test.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork.test.ts index 1b3b0fc3803..d4b06325f99 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork.test.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-fork.test.ts @@ -1,17 +1,39 @@ // @vitest-environment happy-dom -import { afterEach, beforeEach, expect, it } from 'vitest' +import { CreateIntentParams } from '../../../../../shared/rpc-contract/structured-agent-session-params' +import type { AgentSessionWireRefusal } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { getStructuredAgentSessionLaunchLifecycle } from './structured-agent-session-launch-registry' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { mocks, resetCreateMessageFixture, - cleanupCreateMessageFixture + cleanupCreateMessageFixture, + created } from './structured-agent-session-launch-create-message.test-fixture' import { startStructuredAgentLaunch } from './structured-agent-session-launch' +const browserSession = vi.hoisted(() => ({ + client: { connectionEpoch: 1, call: vi.fn() }, + environment: { id: 'paired', createdAt: 7, pairingRevision: 7 } +})) +vi.mock('@/web/preload-api/web-runtime-session', () => ({ + getClientForEnvironment: () => browserSession.client, + manuallyDisconnectedEnvironmentIds: new Set(), + manuallyDisconnectedResponse: () => ({ ok: false }), + resolveEnvironment: () => browserSession.environment, + runtimeCallQueuePool: { enqueue: (_id: string, _method: string, run: () => unknown) => run() }, + updateEnvironmentFromResponse: () => undefined +})) +import { callWebRuntimeEnvironment } from '@/web/preload-api/web-runtime-calls' + let restore: (() => void) | undefined beforeEach(() => { restore = resetCreateMessageFixture() }) -afterEach(() => cleanupCreateMessageFixture(restore)) +afterEach(() => { + cleanupCreateMessageFixture(restore) + vi.unstubAllGlobals() + clearRuntimeCompatibilityCache() +}) const forkFrom = { sessionId: 'codex_source', throughItemId: 'item-reply-2' } @@ -20,10 +42,405 @@ it('sends no fork to a host that does not advertise forks', async () => { const launch = startStructuredAgentLaunch('workspace-fork', 'codex', { requestId: 'fork-action', executionHostId: 'local', - forkFrom + forkFrom, + forkRequiresInheritedOriginal: false }) await expect(launch.launchResult).rejects.toMatchObject({ code: 'structured_agent_session_fork_unsupported' }) expect(mocks.call.mock.calls.some(([, method]) => method === 'agentSession.create')).toBe(false) }) + +const copiedReply = { + sessionId: 'copied-chat', + throughItemId: 'codex:019e6b26-18e2-7103-b7a0-7ba6bb071124:completed-turn:1' +} +function forkLaunch(requestId: string) { + vi.useRealTimers() + mocks.exactSupport.mockResolvedValue(true) + mocks.inventory.mockResolvedValue([]) + return startStructuredAgentLaunch('workspace-fork', 'codex', { + requestId, + executionHostId: 'local', + forkFrom: copiedReply, + forkRequiresInheritedOriginal: false + }) +} + +// Recorded create replies from the host's fork source-admission and post-copy paths. +const missingOriginal = { + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' }, + createAttemptRefusedBeforeCommit: true, + message: 'Codex could not find this response in the original chat. Open it and fork from there.' + } +} as const +const changedOriginal = { + ok: false, + refusal: { + code: 'agent_session_operation_invalid', + details: { reason: 'savedConversationMissing' }, + message: 'Codex could not find this response in the original chat. Open it and fork from there.' + } +} as const + +function returnCreateRefusal(refusal: { ok: false; refusal: AgentSessionWireRefusal }) { + mocks.call.mockImplementation(async (_target, method) => { + if (method !== 'agentSession.create') { + throw new Error('No destination published') + } + return refusal + }) +} + +it('settles proven missing and rewound-original refusals without an unknown destination', async () => { + returnCreateRefusal(missingOriginal) + const missing = forkLaunch('missing-original') + await expect(missing.launchResult).rejects.toMatchObject({ + code: 'agent_session_identity_required', + refusal: { details: { reason: 'recordMissing' } } + }) + expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', missing.sessionId)).toBe( + 'failed' + ) + expect(missing.isVisibilityUnknown()).toBe(false) + returnCreateRefusal({ + ...changedOriginal, + refusal: { ...changedOriginal.refusal, createAttemptRefusedBeforeCommit: true } + }) + const removed = forkLaunch('removed-original-reply') + await expect(removed.launchResult).rejects.toMatchObject({ + code: 'agent_session_operation_invalid', + refusal: { details: { reason: 'savedConversationMissing' } } + }) + expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', removed.sessionId)).toBe( + 'failed' + ) + expect(removed.isVisibilityUnknown()).toBe(false) +}) + +it('keeps a post-copy source refusal uncertain without source-admission proof', async () => { + returnCreateRefusal(changedOriginal) + const launch = forkLaunch('post-copy-source-change') + await expect(launch.launchResult).rejects.toMatchObject({ + code: 'agent_session_operation_invalid' + }) + expect(launch.isVisibilityUnknown()).toBe(true) + expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe( + 'visibility-unknown' + ) +}) + +it('keeps an earlier lost create unknown when the retry proves the original is missing', async () => { + returnCreateRefusal(missingOriginal) + mocks.call.mockRejectedValueOnce(new Error('create reply lost')) + const launch = forkLaunch('lost-before-source-refusal') + await expect(launch.launchResult).rejects.toMatchObject({ + code: 'agent_session_identity_required' + }) + expect(launch.isVisibilityUnknown()).toBe(true) + expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe( + 'visibility-unknown' + ) +}) + +import type { callStructuredAgentSession as StructuredCall } from '@/runtime/native-chat/requests/structured-agent-session-call' +import type { callRuntimeRpc as RuntimeCall } from '@/runtime/rpc/calls/runtime-rpc-call' +// Real launch, capability cache, structured-call wrapper and RPC options, up to the IPC boundary. +import { + compatibilityEntry, + runtimeCompatibilityChecks, + clearRuntimeCompatibilityCache +} from '@/runtime/rpc/compatibility/runtime-compatibility-cache' +import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' +import { AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY } from '../../../../../shared/agent-session/agent-session-create-capabilities' +import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' +import type { RuntimeRpcResponse } from '../../../../../shared/runtime-rpc-envelope' +import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' +import { + launchAndReconcile, + reconcileUnknownLaunch +} from './structured-agent-session-launch-recovery' +import { + createStructuredAgentSessionLaunchIntent, + retryStructuredAgentSessionLaunchIntent, + restoreStructuredAgentSessionLaunchIntent +} from '@/lib/launch-structured-agent-session' + +const { callStructuredAgentSession } = await vi.importActual<{ + callStructuredAgentSession: typeof StructuredCall +}>('@/runtime/native-chat/requests/structured-agent-session-call') +const { callRuntimeRpc } = await vi.importActual<{ callRuntimeRpc: typeof RuntimeCall }>( + '@/runtime/rpc/calls/runtime-rpc-call' +) + +async function remoteForkTransport() { + vi.useRealTimers() + mocks.exactSupport.mockResolvedValue(true) + mocks.inventory.mockResolvedValue([]) + mocks.call.mockImplementation( + (target, method, params, ...options: [Parameters[3]?]) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the production wrapper receives the typed launch target. + return callStructuredAgentSession(target as RuntimeClientTarget, method, params, ...options) + } + ) + mocks.rpc.mockImplementation(callRuntimeRpc) + replaceRuntimeEnvironmentRevisions([{ id: 'paired', createdAt: 7, pairingRevision: 7 }]) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the positive cache entry is consumed only for capability/compatibility. + const status = { + runtimeId: 'runtime-a', + capabilities: [AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY] + } as RuntimeStatus + runtimeCompatibilityChecks.set('paired', compatibilityEntry(status)) + const call = vi.fn(async (request): Promise> => { + if (request.method !== 'agentSession.create') { + throw new Error('No child read expected') + } + return { id: request.method, ok: true, result: created(), _meta: { runtimeId: 'runtime-a' } } + }) + vi.stubGlobal('window', { ...window, api: { ...window.api, runtimeEnvironments: { call } } }) + return call +} +function inheritedIntent() { + const intent = createStructuredAgentSessionLaunchIntent( + 'workspace-fork', + 'opencode', + 'runtime:paired', + undefined, + undefined, + true, + { sessionId: 'copied-chat', throughItemId: 'legacy:opencode:source:reply-1' } + ) + intent.forkRequiresInheritedOriginal = true + return intent +} +function recoveryState(intent = inheritedIntent()) { + return { + intent, + promise: Promise.resolve({ sessionId: '', fence: 0 }), + visibilityUnknown: false, + cancelled: false + } +} +const restartedRuntime = { + id: 'agentSession.create', + ok: false, + error: { + code: 'runtime_environment_changed', + message: 'Runtime environment identity changed; refresh and try again' + }, + _meta: { runtimeId: 'runtime-b' } +} as const + +it('settles a pinned pre-dispatch runtime replacement definitively, and keeps the requirement on Retry', async () => { + const call = await remoteForkTransport() + // Recorded no-send response from the sending-socket guard, exercised in the transport suites. + call.mockResolvedValueOnce(restartedRuntime) + const launch = startStructuredAgentLaunch('workspace-fork', 'opencode', { + requestId: 'bound-fork', + executionHostId: 'runtime:paired', + forkFrom: { sessionId: 'copied-chat', throughItemId: 'legacy:opencode:source:reply-1' }, + forkRequiresInheritedOriginal: true + }) + await expect(launch.launchResult).rejects.toMatchObject({ + code: 'runtime_unavailable' + }) + expect(launch.isVisibilityUnknown()).toBe(false) + expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe( + 'failed' + ) + expect(call).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'agentSession.create', + expectedEnvironmentRuntimeId: 'runtime-a', + expectedEnvironmentPairingRevision: 7 + }) + ) + + // Each retry must reacquire proof rather than retain the prior runtime tuple. + const current = runtimeCompatibilityChecks.get('paired')! + runtimeCompatibilityChecks.set( + 'paired', + compatibilityEntry({ ...current.status!, runtimeId: 'runtime-c' }) + ) + const state = recoveryState(retryStructuredAgentSessionLaunchIntent(inheritedIntent())) + await expect(launchAndReconcile(state)).resolves.toMatchObject({ fence: 1 }) + expect(call).toHaveBeenLastCalledWith( + expect.objectContaining({ + method: 'agentSession.create', + expectedEnvironmentRuntimeId: 'runtime-c', + expectedEnvironmentPairingRevision: 7, + params: expect.objectContaining({ + forkFrom: { sessionId: 'copied-chat', throughItemId: 'legacy:opencode:source:reply-1' } + }) + }) + ) + runtimeCompatibilityChecks.set( + 'paired', + compatibilityEntry({ ...current.status!, capabilities: [] }) + ) + await expect(launchAndReconcile(recoveryState(inheritedIntent()))).rejects.toMatchObject({ + code: 'structured_agent_session_fork_unsupported' + }) + const ordinary = createStructuredAgentSessionLaunchIntent( + 'workspace-fork', + 'opencode', + 'runtime:paired', + undefined, + undefined, + true, + { sessionId: 'child', throughItemId: 'legacy:opencode:child:reply-2' } + ) + ordinary.forkRequiresInheritedOriginal = false + await expect(launchAndReconcile(recoveryState(ordinary))).resolves.toMatchObject({ fence: 1 }) +}) + +it('reconciles a lost create first and retains uncertainty when a later proof cannot send', async () => { + const call = await remoteForkTransport() + const state = recoveryState() + call.mockImplementationOnce(async () => { + clearRuntimeCompatibilityCache() + throw new Error('create reply lost') + }) + await expect(launchAndReconcile(state)).rejects.toMatchObject({ code: 'runtime_unavailable' }) + expect(state.visibilityUnknown).toBe(true) + // Once publication arrives, recovery succeeds even though the capability read would still fail. + mocks.inventory.mockResolvedValue([ + { + worktree: 'workspace-fork', + tabs: [{ type: 'agent-session', sessionId: state.intent.sessionId }] + } + ]) + mocks.call.mockImplementation(async (_target, method) => { + if (method === 'agentSession.history') { + return { ok: true, page: { ...created().value.page, sessionId: state.intent.sessionId } } + } + throw new Error('No create or capability read during reconciliation') + }) + await expect(reconcileUnknownLaunch(state, true)).resolves.toMatchObject({ + sessionId: state.intent.sessionId, + fence: 1 + }) +}) + +it('rederives a restored ancestor fork requirement from the child before resubmitting', async () => { + const call = await remoteForkTransport() + const prior = inheritedIntent() + const restored = restoreStructuredAgentSessionLaunchIntent({ + worktreeId: prior.worktreeId, + executionHostId: prior.executionHostId, + agent: prior.agent, + ...prior.params.envelope, + forkFrom: prior.params.forkFrom + }) + const base = created(CreateIntentParams.parse(prior.params)).value.page + mocks.call.mockImplementation( + async (target, method, params, ...rest: [Parameters[3]?]) => { + if (method === 'agentSession.agents') { + return { agents: [{ agent: 'opencode', capabilities: { fork: 'tip' } }] } + } + if (method === 'agentSession.history') { + return { + ok: true, + page: { + ...base, + sessionId: 'copied-chat', + items: [ + { + itemId: 'source-u1', + sequence: 1, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { + itemId: 'legacy:opencode:source:reply-1', + sequence: 2, + body: { kind: 'message', role: 'assistant', blocks: [] } + }, + { + itemId: 'parent-fork-u2', + sequence: 3, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { + itemId: 'legacy:opencode:parent-fork:reply-2', + sequence: 4, + body: { kind: 'message', role: 'assistant', blocks: [] } + }, + { + itemId: 'orca:forked-from', + sequence: 5, + body: { kind: 'status', presentation: 'forked-from', text: 'Forked from source' } + }, + { + itemId: 'child-u3', + sequence: 6, + body: { kind: 'message', role: 'user', blocks: [] } + }, + { + itemId: 'legacy:opencode:child:reply-3', + sequence: 7, + body: { kind: 'message', role: 'assistant', blocks: [] } + } + ] + } + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the production wrapper receives the typed launch target. + return callStructuredAgentSession(target as RuntimeClientTarget, method, params, ...rest) + } + ) + await expect(reconcileUnknownLaunch(recoveryState(restored), true)).resolves.toMatchObject({ + fence: 1 + }) + expect(call).toHaveBeenLastCalledWith( + expect.objectContaining({ + expectedEnvironmentRuntimeId: 'runtime-a', + expectedEnvironmentPairingRevision: 7 + }) + ) +}) + +it('settles a browser pin refusal before dispatch but keeps a lost browser reply uncertain', async () => { + const call = await remoteForkTransport() + call.mockImplementation(callWebRuntimeEnvironment) + browserSession.client.connectionEpoch = 1 + browserSession.client.call.mockReset() + browserSession.client.call.mockImplementation(async (method) => { + if (method !== 'status.get') { + throw new Error('Unexpected create dispatch') + } + return { id: 'status', ok: true, result: {}, _meta: { runtimeId: 'runtime-b' } } + }) + const state = recoveryState() + await expect(launchAndReconcile(state)).rejects.toMatchObject({ + code: 'runtime_unavailable' + }) + expect(state.visibilityUnknown).toBe(false) + expect(browserSession.client.call.mock.calls.map(([method]) => method)).not.toContain( + 'agentSession.create' + ) + + // The same words in a failed reply are not pre-dispatch evidence. + browserSession.client.connectionEpoch = 2 + browserSession.client.call.mockImplementation(async (method) => { + if (method === 'status.get') { + return { id: 'status', ok: true, result: {}, _meta: { runtimeId: 'runtime-a' } } + } + throw new Error('Runtime connection changed; try again.') + }) + const lost = recoveryState() + await expect(launchAndReconcile(lost)).rejects.toThrow() + expect(lost.visibilityUnknown).toBe(true) +}) + +it('keeps a failed capability read definitive without classifying the host as unsupported', async () => { + const call = await remoteForkTransport() + clearRuntimeCompatibilityCache() + call.mockRejectedValue(new Error('status read failed')) + const state = recoveryState() + await expect(launchAndReconcile(state)).rejects.toMatchObject({ code: 'runtime_unavailable' }) + expect(state.visibilityUnknown).toBe(false) + expect(call.mock.calls.map(([request]) => request.method)).not.toContain('agentSession.create') +}) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts index 0428ef6fb4c..f0301d1d189 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch.ts @@ -205,6 +205,7 @@ function structuredAgentLaunchState( // A fork inherits its source's options. intent.explicitLaunchOptions = !options.forkFrom && options.launchOptions ? { ...options.launchOptions } : undefined + intent.forkRequiresInheritedOriginal = options.forkRequiresInheritedOriginal intent.beforeCreate = options.beforeCreate intent.createAfter = options.createAfter intent.surfaceAddress = options.surfaceAddress diff --git a/src/renderer/src/lib/browser/navigation/browser-link-destination.ts b/src/renderer/src/lib/browser/navigation/browser-link-destination.ts index b8e8fe4068c..3dadc8a3fdd 100644 --- a/src/renderer/src/lib/browser/navigation/browser-link-destination.ts +++ b/src/renderer/src/lib/browser/navigation/browser-link-destination.ts @@ -130,11 +130,8 @@ export function browserOpenResultForPage( workspaceId: string, pageId: string ): BrowserOpenResult | null { - const matchesHost = createBrowserLinkHostMatcher( - state, - destination.worktreeId, - destination.executionHostId - ) + const { worktreeId, executionHostId } = destination + const matchesHost = createBrowserLinkHostMatcher(state, worktreeId, executionHostId) const wrapper = (state.unifiedTabsByWorktree[destination.worktreeId] ?? []).find( (tab) => tab.contentType === 'browser' && @@ -209,6 +206,12 @@ export function selectBrowserLinkDestination( ) { return { status: 'refused' } } + const reusePage = + destination.resource.kind !== 'website' || + (destination.browserRuntimeEnvironmentId !== null && !!intent?.targetGroupId) + if (intent?.targetGroupId && !reusePage) { + return { status: 'ready', groupId: intent.targetGroupId, match: null } + } const workspaces = new Map( (state.browserTabsByWorktree[worktreeId] ?? []).map((tab) => [tab.id, tab]) ) @@ -226,12 +229,7 @@ export function selectBrowserLinkDestination( const matchingGroups = new Set() const liveGroups = liveLinkOpenGroupIds(state, worktreeId) for (const tab of wrappersByWorkspace.values()) { - if ( - !tab || - tab.contentType !== 'browser' || - !matchesHost(tab.executionHostId) || - !liveGroups.has(tab.groupId) - ) { + if (!tab || !matchesHost(tab.executionHostId) || !liveGroups.has(tab.groupId)) { continue } const workspace = workspaces.get(tab.entityId) @@ -300,10 +298,9 @@ export function selectBrowserLinkDestination( return { status: 'ready', ...placement, match: null } } const group = groups.find((item) => item.id === groupId) - const ids = group ? [group.activeTabId, ...group.tabOrder] : [] - for (const id of ids) { + for (const id of group ? [group.activeTabId, ...group.tabOrder] : []) { const match = id ? matchesByTab.get(id) : undefined - if (match && match.groupId === groupId) { + if (reusePage && match && match.groupId === groupId) { return { status: 'ready', groupId, match } } } diff --git a/src/renderer/src/lib/browser/navigation/browser-link-open.test.ts b/src/renderer/src/lib/browser/navigation/browser-link-open.test.ts index c9e36260a6c..c8caf3bd2a6 100644 --- a/src/renderer/src/lib/browser/navigation/browser-link-open.test.ts +++ b/src/renderer/src/lib/browser/navigation/browser-link-open.test.ts @@ -1,5 +1,4 @@ import type * as BrowserFocusModule from '@/components/browser-pane/host-guest/browser-focus' -import { requestBrowserFocus } from '@/components/browser-pane/host-guest/browser-focus' import { beforeEach, describe, expect, it, vi } from 'vitest' import { createStoreCascadesMockApi } from '@/store/testing/app-store-cascade-api.test-fixture' import '@/store/testing/app-store-test-fixture' @@ -16,7 +15,7 @@ import { URL_TO_OPEN, type BrowserLinkTestStore } from './browser-link-open.test-fixture' -import { openFileInBrowserTab } from '../../file-preview' + import { openWorkspaceBrowserTabForLink } from '../workspace/workspace-browser-tab-open' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../shared/constants' @@ -66,73 +65,6 @@ function browser(groupId: string, url = URL_TO_OPEN) { } describe('browser link placement and exact page activation', () => { - it('prefers an old inactive nonadjacent match over a nearby browser without navigation or creation', async () => { - store.getState().createBrowserTab(WORKSPACE, 'https://nearby.example/', { - targetGroupId: 'b', - executionHostId: 'local', - browserRuntimeEnvironmentId: null, - activate: true - }) - const existing = browser('c') - store.getState().createBrowserPage(existing.id, 'https://other.example/', { - activate: true, - browserRuntimeEnvironmentId: null - }) - const navigate = vi.spyOn(store.getState(), 'setBrowserPageUrl') - const create = vi.spyOn(store.getState(), 'createBrowserTab') - const result = await open() - expect(result).toMatchObject({ - status: 'opened', - result: { - browserWorkspaceId: existing.id, - browserPageId: existing.activePageId, - groupId: 'c' - } - }) - expect( - store.getState().browserTabsByWorktree[WORKSPACE]?.find((tab) => tab.id === existing.id) - ?.activePageId - ).toBe(existing.activePageId) - expect(navigate).not.toHaveBeenCalled() - expect(create).not.toHaveBeenCalled() - }) - - it('reusing a page clears a pending address-bar request and focuses the page', async () => { - const existing = browser('b') - const pageId = existing.activePageId - if (!pageId) { - throw new Error('Expected page') - } - store.setState({ - pendingAddressBarFocusByPageId: { [pageId]: true }, - pendingAddressBarFocusByTabId: { [existing.id]: true, [pageId]: true } - }) - expect(await open()).toMatchObject({ status: 'opened', result: { browserPageId: pageId } }) - expect(store.getState().pendingAddressBarFocusByPageId).toEqual({}) - expect(store.getState().pendingAddressBarFocusByTabId).toEqual({}) - expect(requestBrowserFocus).toHaveBeenLastCalledWith({ pageId, target: 'webview' }) - }) - - it('rechecks a reused page after workspace activation without navigating it back', async () => { - const existing = browser('b') - const pageId = existing.activePageId - if (!pageId) { - throw new Error('Expected page') - } - const outcome = await openLocalBrowserLink({ - destination: browserLinkTestDestination(), - context: context(), - url: URL_TO_OPEN, - ownsRoute: () => true, - reveal: () => store.getState().setBrowserPageUrl(pageId, 'https://navigated-away.example/') - }) - expect(outcome).toEqual({ status: 'refused' }) - expect(store.getState().browserPagesByWorkspace[existing.id]?.[0]?.url).toBe( - 'https://navigated-away.example/' - ) - expect(store.getState().activeGroupIdByWorktree[WORKSPACE]).toBe('c') - }) - it('removes a newly created tab after an activation error while preserving existing tabs', async () => { const existing = browser('c', 'https://unrelated.example/') const before = store.getState() @@ -154,55 +86,6 @@ describe('browser link placement and exact page activation', () => { expect(state.recentlyClosedBrowserTabsByWorktree[WORKSPACE] ?? []).toEqual([]) }) - it('follows source movement while an explicit request stays pinned', async () => { - const automatic = context() - store.setState({ - unifiedTabsByWorktree: { - [WORKSPACE]: store - .getState() - .unifiedTabsByWorktree[WORKSPACE]!.map((tab) => - tab.id === 'source' ? { ...tab, groupId: 'b' } : tab - ) - } - }) - const moved = await open(automatic) - expect(moved.status).toBe('opened') - if (moved.status !== 'opened') { - throw new Error('Expected open') - } - expect(moved.result.groupId).toBe('c') - expect(store.getState().groupsByWorktree[WORKSPACE]).toHaveLength(3) - const explicit = context(true) - store.setState({ - unifiedTabsByWorktree: { - [WORKSPACE]: store - .getState() - .unifiedTabsByWorktree[WORKSPACE]!.map((tab) => - tab.id === 'source' ? { ...tab, groupId: 'a' } : tab - ) - } - }) - expect(await open(explicit)).toMatchObject({ status: 'opened', result: { groupId: 'b' } }) - }) - - it('uses destination defaults after the source closes, instead of its captured group', async () => { - const captured = context() - store.setState({ - unifiedTabsByWorktree: { - [WORKSPACE]: store - .getState() - .unifiedTabsByWorktree[WORKSPACE]!.filter((tab) => tab.id !== 'source') - } - }) - const opened = await open(captured) - expect(opened.status).toBe('opened') - if (opened.status !== 'opened') { - throw new Error('Expected open') - } - expect(opened.result.groupId).toBe('b') - expect(store.getState().groupsByWorktree[WORKSPACE]).toHaveLength(3) - }) - it('refuses an expired explicit group before creating records or activating a destination', async () => { const captured = context(true) store.setState({ @@ -270,30 +153,6 @@ describe('existing open routes with link intent', () => { expect(store.getState().browserPagesByWorkspace).toEqual({}) }) - it('creates a pinned local HTML preview even when another group already shows the file', async () => { - const filePath = '/repo/index.html' - browser('b', 'file:///repo/index.html') - const outcome = vi.fn() - await new Promise((resolve) => - openFileInBrowserTab({ - filePath, - worktreeId: WORKSPACE, - linkContext: context(true), - onLinkOutcome: (result) => { - outcome(result) - resolve(result) - } - }) - ) - expect(outcome).toHaveBeenCalledWith( - expect.objectContaining({ - status: 'opened', - result: expect.objectContaining({ groupId: 'a' }) - }) - ) - expect(store.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(2) - }) - it('finds inactive document pages through page records rather than workspace mirrors', () => { const existing = browser('c', 'https://other.example/') const docLocation = { diff --git a/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts b/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts index fe7f2f5f6c8..d15daee5e3d 100644 --- a/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts +++ b/src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts @@ -120,8 +120,19 @@ describe.each(['repo', 'worktree'] as const)('%s browser profile isolation', (sc (workspace) => workspace.id === opened.result.browserWorkspaceId ) ).toMatchObject({ sessionProfileId: profile.id, sessionPartition: profile.partition }) - expect(await open(surface)).toEqual(opened) - expect(store.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(2) + const reopened = await open(surface) + if (surface === 'html') { + expect(reopened).toEqual(opened) + } else { + expect(reopened.status).toBe('opened') + if (reopened.status !== 'opened') { + throw new Error('Expected opened link') + } + expect(reopened.result.browserWorkspaceId).not.toBe(opened.result.browserWorkspaceId) + } + expect(store.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength( + surface === 'http' ? 3 : 2 + ) } ) }) diff --git a/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts b/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts index f85bba2193c..b7e481258ed 100644 --- a/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts +++ b/src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts @@ -248,7 +248,7 @@ it.each(['workspace', 'view'] as const)( ) it.each([false, true])( - 'reveals the tab layout for a foreground source-aware HTTP link (reuse: %s)', + 'reveals the tab layout for a foreground source-aware HTTP link (already open: %s)', async (reuse) => { if (reuse) { useAppStore.getState().createBrowserTab(WORKSPACE, URL_TO_OPEN, { @@ -275,7 +275,7 @@ it.each([false, true])( } expect(useAppStore.getState().activeView).toBe('terminal') expect(useAppStore.getState().activeGroupIdByWorktree[WORKSPACE]).toBe(outcome.result.groupId) - expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(1) + expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(reuse ? 2 : 1) } ) @@ -341,7 +341,7 @@ it('keeps the main view and workspace selected when revealing a floating HTTP li expect(useAppStore.getState().groupsByWorktree[floating]).toHaveLength(3) }) -it('reuses an exact page for an HTTP link without source context', async () => { +it('opens a new page for an HTTP link without source context', async () => { const browser = useAppStore.getState().createBrowserTab(WORKSPACE, URL_TO_OPEN, { targetGroupId: 'b', browserRuntimeEnvironmentId: null, @@ -350,9 +350,11 @@ it('reuses an exact page for an HTTP link without source context', async () => { }) const completed = observeBrowserLinkOpen() openHttpLink(URL_TO_OPEN, { worktreeId: WORKSPACE, sourceOwner: { kind: 'local' } }) - expect(await completed).toMatchObject({ - status: 'opened', - result: { browserWorkspaceId: browser.id, browserPageId: browser.activePageId } - }) - expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(1) + const outcome = await completed + expect(outcome.status).toBe('opened') + if (outcome.status !== 'opened') { + throw new Error('Expected opened link') + } + expect(outcome.result.browserWorkspaceId).not.toBe(browser.id) + expect(useAppStore.getState().browserTabsByWorktree[WORKSPACE]).toHaveLength(2) }) diff --git a/src/renderer/src/lib/ephemeral-vm-error-copy.ts b/src/renderer/src/lib/ephemeral-vm-error-copy.ts index 3d15f7e5cfb..69309727c1d 100644 --- a/src/renderer/src/lib/ephemeral-vm-error-copy.ts +++ b/src/renderer/src/lib/ephemeral-vm-error-copy.ts @@ -82,6 +82,29 @@ const COPY: Record strin translate('ephemeralVm.errors.provisionedRootResultRequired', EN.provisionedRootResultRequired), provisionedRootNotConfigured: () => translate('ephemeralVm.errors.provisionedRootNotConfigured', EN.provisionedRootNotConfigured), + suspendExited: (p) => { + const exitCode = num(p, 'exitCode') + return exitCode === null + ? null + : translate('ephemeralVm.errors.suspendExited', EN.suspendExited, { exitCode }) + }, + suspendExitedWithoutCode: () => + translate('ephemeralVm.errors.suspendExitedWithoutCode', EN.suspendExitedWithoutCode), + resumeExited: (p) => { + const exitCode = num(p, 'exitCode') + return exitCode === null + ? null + : translate('ephemeralVm.errors.resumeExited', EN.resumeExited, { exitCode }) + }, + resumeExitedWithoutCode: () => + translate('ephemeralVm.errors.resumeExitedWithoutCode', EN.resumeExitedWithoutCode), + recipeTimedOut: (p) => { + const mode = text(p, 'mode') + const timeout = text(p, 'timeout') + return mode === null || timeout === null + ? null + : translate('ephemeralVm.errors.recipeTimedOut', EN.recipeTimedOut, { mode, timeout }) + }, destroyExited: (p) => { const exitCode = num(p, 'exitCode') return exitCode === null diff --git a/src/renderer/src/lib/git-graph-tab.ts b/src/renderer/src/lib/git-graph-tab.ts index b1c08752e31..3c90a7bc570 100644 --- a/src/renderer/src/lib/git-graph-tab.ts +++ b/src/renderer/src/lib/git-graph-tab.ts @@ -119,7 +119,11 @@ export function gitGraphUpdateMessage(worktreeId: string, t: Translate = transla }) } -export async function openGitGraph(worktreeId: string): Promise { +export async function openGitGraph( + worktreeId: string, + // Lazy so a split is created only when a new tab actually opens. + resolveTargetGroupId?: () => string | undefined +): Promise { const supported = await probeGitGraphSupport(worktreeId) if (!supported) { return @@ -151,6 +155,6 @@ export async function openGitGraph(worktreeId: string): Promise { }, mode: 'git-graph' }, - { reopenId: id, preview: false } + { reopenId: id, preview: false, targetGroupId: resolveTargetGroupId?.() } ) } diff --git a/src/renderer/src/lib/launch-structured-agent-session.ts b/src/renderer/src/lib/launch-structured-agent-session.ts index 5992f53b5fc..61a54d29480 100644 --- a/src/renderer/src/lib/launch-structured-agent-session.ts +++ b/src/renderer/src/lib/launch-structured-agent-session.ts @@ -47,6 +47,8 @@ export type StructuredAgentSessionLaunchIntent = { agent: TuiAgent params: StructuredAgentSessionCreateParams sendSelectionSupport?: boolean + /** Client-only admission requirement; reacquired from the child after reload. */ + forkRequiresInheritedOriginal?: boolean sendSkillsSupport?: boolean createMessageSupport?: boolean createPrepared?: true @@ -183,6 +185,7 @@ export function retryStructuredAgentSessionLaunchIntent( intent.seedOptions, intent.params.forkFrom ), + forkRequiresInheritedOriginal: intent.forkRequiresInheritedOriginal, explicitLaunchOptions: intent.explicitLaunchOptions } } diff --git a/src/renderer/src/runtime/browser/creation/web-runtime-browser-link-session.test.ts b/src/renderer/src/runtime/browser/creation/web-runtime-browser-link-session.test.ts index c8037a92e82..3e193b641ff 100644 --- a/src/renderer/src/runtime/browser/creation/web-runtime-browser-link-session.test.ts +++ b/src/renderer/src/runtime/browser/creation/web-runtime-browser-link-session.test.ts @@ -93,7 +93,7 @@ function setDefaultProfiles( useAppStore.setState({ settings: { ...settings, browserDefaultProfileIdByHostId } }) } -function open() { +function open(explicit = false) { return openWorkspaceBrowserTabForLink({ workspaceId: WT, url: URL_TO_OPEN, @@ -102,7 +102,9 @@ function open() { placementPreference: 'server', selectWorktree: false, linkContext: { - linkIntent: captureLinkOpenIntent(useAppStore.getState(), WT, SOURCE.unifiedTabId) + linkIntent: captureLinkOpenIntent(useAppStore.getState(), WT, OTHER.unifiedTabId, { + explicitSourceGroup: explicit + }) } }) } @@ -141,22 +143,38 @@ function selectDestination() { ENV, HOST ), - captureLinkOpenIntent(state, WT, SOURCE.unifiedTabId) + captureLinkOpenIntent(state, WT, OTHER.unifiedTabId, { explicitSourceGroup: true }) ) } -it.each([null, 'remote-profile'])( - 'reuses the host-confirmed default or custom profile (%s)', - async (profileId) => { +it.each([ + { profileId: null, explicit: false }, + { profileId: 'remote-profile', explicit: false }, + { profileId: null, explicit: true }, + { profileId: 'remote-profile', explicit: true } +])( + 'opens with the host-confirmed profile ($profileId, explicit target: $explicit)', + async ({ profileId, explicit }) => { setDefaultProfiles(profileId ? { [HOST]: profileId } : {}) publishProfileSnapshot(profileId ?? 'default') - const creating = open() - pendingCreates[0]?.resolve('unexpected-new-page') - expect(await creating).toMatchObject({ - status: 'opened', - result: { browserPageId: OTHER.pageId } - }) - expect(pendingCreates).toHaveLength(0) + const creating = open(explicit) + pendingCreates[0]?.resolve('new-host-page') + const outcome = await creating + if (explicit) { + expect(outcome).toMatchObject({ + status: 'opened', + result: { browserPageId: OTHER.pageId } + }) + return + } + expect(outcome.status).toBe('opened') + if (outcome.status !== 'opened') { + throw new Error('Expected opened link') + } + expect(outcome.result.browserPageId).not.toBe(OTHER.pageId) + expect( + useAppStore.getState().remoteBrowserPageHandlesByPageId[outcome.result.browserPageId] + ).toMatchObject({ remotePageId: 'new-host-page', environmentId: ENV }) } ) diff --git a/src/renderer/src/runtime/native-chat/host-capabilities/structured-agent-session-host-capability.ts b/src/renderer/src/runtime/native-chat/host-capabilities/structured-agent-session-host-capability.ts index 1d7ac7e3be7..8999da7bc64 100644 --- a/src/renderer/src/runtime/native-chat/host-capabilities/structured-agent-session-host-capability.ts +++ b/src/renderer/src/runtime/native-chat/host-capabilities/structured-agent-session-host-capability.ts @@ -71,9 +71,11 @@ export function useStructuredAgentSessionOwnPermissionState( * host is asked again each time this client regains contact with it. */ export function useStructuredAgentSessionHostCapabilityState( target: RuntimeClientTarget | null, - capability: RuntimeCapability + capability: RuntimeCapability, + requireCurrentContact = false ): StructuredAgentSessionHostCapabilityState { const key = target ? structuredAgentSessionHostKey(target) : null + const [contact, setContact] = useState(0) const [answer, setAnswer] = useState<{ key: string | null state: StructuredAgentSessionHostCapabilityState @@ -82,15 +84,25 @@ export function useStructuredAgentSessionHostCapabilityState( state: target?.kind === 'local' ? localCapabilityState(capability) : 'unknown' })) const environmentId = target?.kind === 'environment' ? target.environmentId : null - const [contact, setContact] = useState(0) + const current = useAppStateValue((state): StructuredAgentSessionHostCapabilityState => { + const status = + environmentId === null || !requireCurrentContact + ? null + : state.runtimeStatusByEnvironmentId.get(environmentId)?.status + return !status + ? 'unknown' + : status.capabilities?.includes(capability) + ? 'supported' + : 'unsupported' + }) useEffect(() => { - if (environmentId === null) { + if (environmentId === null || requireCurrentContact) { return } return subscribeRuntimeHostContactRegained(environmentId, () => setContact((n) => n + 1)) - }, [environmentId]) + }, [environmentId, requireCurrentContact]) useEffect(() => { - if (key === null) { + if (key === null || (requireCurrentContact && environmentId !== null)) { return } let cancelled = false @@ -112,8 +124,12 @@ export function useStructuredAgentSessionHostCapabilityState( return () => { cancelled = true } - }, [capability, contact, environmentId, key]) - return answer.key === key ? answer.state : 'unknown' + }, [capability, contact, environmentId, key, requireCurrentContact]) + return requireCurrentContact && environmentId !== null + ? current + : answer.key === key + ? answer.state + : 'unknown' } function localCapabilityState( diff --git a/src/renderer/src/runtime/native-chat/requests/structured-agent-session-call.ts b/src/renderer/src/runtime/native-chat/requests/structured-agent-session-call.ts index 99643fdd6d1..6dbb815a8e4 100644 --- a/src/renderer/src/runtime/native-chat/requests/structured-agent-session-call.ts +++ b/src/renderer/src/runtime/native-chat/requests/structured-agent-session-call.ts @@ -18,6 +18,7 @@ export async function callStructuredAgentSession( options: { skipCompatibilityCheck?: true beforeSend?: () => void + expectedEnvironmentRuntimeId?: string expectedEnvironmentPairingRevision?: number } = {} ): Promise { diff --git a/src/renderer/src/runtime/rpc/calls/runtime-rpc-result.ts b/src/renderer/src/runtime/rpc/calls/runtime-rpc-result.ts index 432817b7afc..3c4213c71db 100644 --- a/src/renderer/src/runtime/rpc/calls/runtime-rpc-result.ts +++ b/src/renderer/src/runtime/rpc/calls/runtime-rpc-result.ts @@ -5,6 +5,14 @@ import type { // Why: the CLI reads the same flattened tokens, so the matcher lives in shared and both clients use one copy. +/** A local identity guard rejected the request before dispatch, not a lost reply. */ +export class RuntimeConnectionChangedBeforeSendError extends Error { + constructor(message: string) { + super(message) + this.name = 'RuntimeConnectionChangedBeforeSendError' + } +} + export class RuntimeRpcCallError extends Error { readonly code: string readonly response: RuntimeRpcFailure diff --git a/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts b/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts index e2e80bae143..143b266805d 100644 --- a/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts +++ b/src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts @@ -10,7 +10,6 @@ import { RUNTIME_PROTOCOL_VERSION } from '../../../../../shared/protocol-version' import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../shared/constants' const detectAgents = vi.fn() const refreshAgents = vi.fn() @@ -80,97 +79,6 @@ describe('createDetectedAgentsSlice WSL context', () => { }) }) - it('publishes a Floating-first host probe to a later ordinary local caller', async () => { - let resolveDetection: (agents: string[]) => void = () => {} - detectAgents.mockReturnValueOnce( - new Promise((resolve) => { - resolveDetection = resolve - }) - ) - const store = createTestStore() - - const floating = store.getState().ensureDetectedAgents(FLOATING_TERMINAL_WORKTREE_ID) - const ordinary = store.getState().ensureDetectedAgents() - - expect(detectAgents).toHaveBeenCalledTimes(1) - expect(store.getState().isDetectingAgents).toBe(true) - resolveDetection(['codex']) - await expect(Promise.all([floating, ordinary])).resolves.toEqual([['codex'], ['codex']]) - expect(store.getState().detectedAgentIds).toEqual(['codex']) - expect(store.getState().isDetectingAgents).toBe(false) - }) - - it('restores the legacy inventory when returning to a cached local context', async () => { - detectAgents.mockImplementation(async (context) => - context?.projectRuntime?.runtime.kind === 'wsl' ? ['claude'] : ['codex'] - ) - const store = createTestStore({ - repos: [makeRepo({ id: 'repo-1', path: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\repo' })], - activeRepoId: 'repo-1', - activeWorktreeId: null - }) - - await store.getState().ensureDetectedAgents() - store.setState({ activeRepoId: null }) - await store.getState().ensureDetectedAgents() - store.setState({ activeRepoId: 'repo-1' }) - - await expect(store.getState().ensureDetectedAgents()).resolves.toEqual(['claude']) - expect(store.getState().detectedAgentIds).toEqual(['claude']) - }) - - it('retries a local context after a transient detection failure', async () => { - detectAgents - .mockRejectedValueOnce(new Error('cold-start timeout')) - .mockResolvedValueOnce(['codex']) - const store = createTestStore() - - await expect(store.getState().ensureDetectedAgents()).resolves.toEqual([]) - await expect(store.getState().ensureDetectedAgents()).resolves.toEqual(['codex']) - - expect(store.getState().detectedAgentIds).toEqual(['codex']) - }) - - it('clears local agents when the project runtime requires repair before detection', async () => { - detectAgents.mockImplementation(async (context) => { - if (context?.projectRuntime?.status === 'repair-required') { - throw new Error('Project runtime requires repair before agent detection') - } - return ['claude'] - }) - const store = createTestStore({ - repos: [makeRepo({ id: 'repo-1', path: 'C:\\repo' })], - activeRepoId: 'repo-1', - activeWorktreeId: null - }) - - await expect(store.getState().ensureDetectedAgents()).resolves.toEqual(['claude']) - expect(store.getState().detectedAgentIds).toEqual(['claude']) - - store.setState({ - settings: { - terminalWindowsShell: 'wsl.exe' - } as AppState['settings'] - } as Partial) - - await expect(store.getState().ensureDetectedAgents()).resolves.toEqual([]) - expect(store.getState().detectedAgentIds).toEqual([]) - - expect(detectAgents).toHaveBeenCalledWith({ - enabledOnly: true, - projectRuntime: { - status: 'repair-required', - repair: { - projectId: 'repo-1', - preferredRuntime: { kind: 'wsl', distro: null }, - reason: 'wsl-distro-required', - source: 'global-default', - cacheKey: 'repo-1:repair:wsl-distro-required:default' - } - } - }) - }) - it('does not keep previous context agents when detection fails after a context switch', async () => { detectAgents .mockReset() @@ -196,28 +104,6 @@ describe('createDetectedAgentsSlice WSL context', () => { await expect(detected).resolves.toEqual([]) expect(store.getState().detectedAgentIds).toEqual([]) }) - - it('ignores in-flight local detection results after a project runtime switch', async () => { - let resolveDetection: (agents: string[]) => void = () => {} - detectAgents.mockReturnValueOnce( - new Promise((resolve) => { - resolveDetection = resolve - }) - ) - const store = createTestStore({ - repos: [makeRepo({ id: 'repo-1', path: 'C:\\repo' })], - activeRepoId: 'repo-1', - activeWorktreeId: null - }) - - const pending = store.getState().ensureDetectedAgents() - store.getState().clearLocalDetectedAgents() - resolveDetection(['claude']) - - await expect(pending).resolves.toEqual(['claude']) - expect(store.getState().detectedAgentIds).toBeNull() - expect(store.getState().isDetectingAgents).toBe(false) - }) }) describe('createDetectedAgentsSlice remote detection', () => { @@ -255,50 +141,6 @@ describe('createDetectedAgentsSlice remote detection', () => { }) }) - it('shares an in-flight SSH detection and publishes its settled inventory', async () => { - const store = createTestStore() - let resolveRemote: (ids: string[]) => void = () => {} - detectRemoteAgents.mockReturnValueOnce( - new Promise((resolve) => { - resolveRemote = resolve - }) - ) - - const first = store.getState().ensureRemoteDetectedAgents('ssh-1') - const second = store.getState().ensureRemoteDetectedAgents('ssh-1') - - expect(second).toBe(first) - - resolveRemote(['claude']) - - await expect(first).resolves.toEqual(['claude']) - await expect(second).resolves.toEqual(['claude']) - expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['claude']) - - await expect(store.getState().ensureRemoteDetectedAgents('ssh-1')).resolves.toEqual(['claude']) - }) - - it('deduplicates concurrent SSH refreshes', async () => { - const store = createTestStore() - store.setState({ remoteDetectedAgentIds: { 'ssh-1': ['claude'] } } as Partial) - let resolveRemote: (ids: string[]) => void = () => {} - detectRemoteAgents.mockReturnValueOnce( - new Promise((resolve) => { - resolveRemote = resolve - }) - ) - - const first = store.getState().refreshRemoteDetectedAgents('ssh-1') - const second = store.getState().refreshRemoteDetectedAgents('ssh-1') - - expect(second).toBe(first) - expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['claude']) - - resolveRemote(['codex']) - await expect(first).resolves.toEqual(['codex']) - expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['codex']) - }) - it('does not restore an SSH cache entry after it is cleared mid-detection', async () => { const store = createTestStore() let resolveRemote: (ids: string[]) => void = () => {} @@ -331,42 +173,6 @@ describe('createDetectedAgentsSlice remote detection', () => { expect(store.getState().remoteDetectedAgentIds['ssh-1']).toEqual(['kilo']) }) - it('re-runs runtime detection after an empty result instead of pinning it', async () => { - const store = createTestStore() - // Runtime Orca-serve path must retry empty detection after install/PATH fixes too, independently of SSH. - let detectCalls = 0 - runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { - let result: unknown - if (method === 'status.get') { - result = { - runtimeId: 'remote-runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION - } - } else { - detectCalls += 1 - result = detectCalls === 1 ? [] : ['kilo'] - } - return Promise.resolve({ - id: method, - ok: true, - result, - _meta: { runtimeId: 'remote-runtime' } - }) - }) - - await expect(store.getState().ensureRuntimeDetectedAgents('env-1')).resolves.toEqual([]) - expect(store.getState().runtimeDetectedAgentIds['env-1']).toEqual([]) - - await expect(store.getState().ensureRuntimeDetectedAgents('env-1')).resolves.toEqual(['kilo']) - expect(store.getState().runtimeDetectedAgentIds['env-1']).toEqual(['kilo']) - }) - it('keeps a late initial detect from overwriting a runtime refresh', async () => { const store = createTestStore() let resolveDetect: (value: unknown) => void = () => {} diff --git a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts index 015e9f51ea9..9142e5a3370 100644 --- a/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts +++ b/src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts @@ -192,45 +192,6 @@ describe('local detected agent context lifecycle', () => { expect(store.getState().isRefreshingAgents).toBe(false) }) - it('successful full refresh settles both modes with detects finishing first', async () => { - const store = createTestStore([]) - const enabledDetection = Promise.withResolvers() - const fullDetection = Promise.withResolvers() - const fullRefresh = Promise.withResolvers<{ agents: string[] }>() - detectAgents - .mockReturnValueOnce(enabledDetection.promise) - .mockReturnValueOnce(fullDetection.promise) - refreshAgents.mockReturnValueOnce(fullRefresh.promise) - const enabled = store.getState().ensureDetectedAgents() - const full = store.getState().ensureAllDetectedAgents() - const refreshed = store.getState().refreshAllDetectedAgents() - - expect(store.getState().isDetectingAgents).toBe(false) - expect(store.getState().isDetectingLocalAgentsByContext).toEqual({}) - expect(store.getState().isRefreshingLocalAgentsByContext).toEqual({ - host: true, - 'host\u0000all-agents': true - }) - const finishDetections = async () => { - enabledDetection.resolve(['claude']) - fullDetection.resolve(['claude', 'kiro']) - await Promise.all([enabled, full]) - } - await finishDetections() - expect(store.getState().isRefreshingAgents).toBe(true) - fullRefresh.resolve({ agents: ['codex', 'kiro'] }) - await refreshed - - expect(store.getState().localDetectedAgentIdsByContext).toEqual({ - host: ['codex', 'kiro'], - 'host\u0000all-agents': ['codex', 'kiro'] - }) - expect(store.getState().isDetectingLocalAgentsByContext).toEqual({}) - expect(store.getState().isRefreshingLocalAgentsByContext).toEqual({}) - expect(store.getState().isDetectingAgents).toBe(false) - expect(store.getState().isRefreshingAgents).toBe(false) - }) - it('failed full refresh settles both modes with detects finishing last', async () => { const store = createTestStore([]) const enabledDetection = Promise.withResolvers() @@ -269,45 +230,6 @@ describe('local detected agent context lifecycle', () => { expect(store.getState().isRefreshingAgents).toBe(false) }) - it('failed full refresh settles both modes with detects finishing first', async () => { - const store = createTestStore([]) - const enabledDetection = Promise.withResolvers() - const fullDetection = Promise.withResolvers() - const fullRefresh = Promise.withResolvers<{ agents: string[] }>() - detectAgents - .mockReturnValueOnce(enabledDetection.promise) - .mockReturnValueOnce(fullDetection.promise) - refreshAgents.mockReturnValueOnce(fullRefresh.promise) - const enabled = store.getState().ensureDetectedAgents() - const full = store.getState().ensureAllDetectedAgents() - const refreshed = store.getState().refreshAllDetectedAgents() - - expect(store.getState().isDetectingAgents).toBe(false) - expect(store.getState().isDetectingLocalAgentsByContext).toEqual({}) - expect(store.getState().isRefreshingLocalAgentsByContext).toEqual({ - host: true, - 'host\u0000all-agents': true - }) - const finishDetections = async () => { - enabledDetection.resolve(['claude']) - fullDetection.resolve(['claude', 'kiro']) - await Promise.all([enabled, full]) - } - await finishDetections() - expect(store.getState().isRefreshingAgents).toBe(true) - fullRefresh.reject(new Error('shell unavailable')) - await refreshed - - expect(store.getState().localDetectedAgentIdsByContext).toEqual({ - host: [], - 'host\u0000all-agents': [] - }) - expect(store.getState().isDetectingLocalAgentsByContext).toEqual({}) - expect(store.getState().isRefreshingLocalAgentsByContext).toEqual({}) - expect(store.getState().isDetectingAgents).toBe(false) - expect(store.getState().isRefreshingAgents).toBe(false) - }) - it('publishes a complete refresh to automatic readers without letting their late probe overwrite it', async () => { const store = createTestStore([]) store.setState({ settings: { ...store.getState().settings!, disabledTuiAgents: ['kiro'] } }) @@ -375,34 +297,6 @@ describe('local detected agent context lifecycle', () => { expect(store.getState().isRefreshingLocalAgentsByContext).toEqual({}) }) - it('deduplicates Floating-first callers without cached or settlement broadcast fanout', async () => { - let resolveDetection: (agents: string[]) => void = () => {} - detectAgents.mockReturnValueOnce( - new Promise((resolve) => { - resolveDetection = resolve - }) - ) - const store = createTestStore([]) - const listener = vi.fn() - const unsubscribe = store.subscribe(listener) - - const floating = store.getState().ensureDetectedAgents(FLOATING_TERMINAL_WORKTREE_ID) - const ordinary = store.getState().ensureDetectedAgents() - const joinedOrdinary = store.getState().ensureDetectedAgents() - - expect(ordinary).toBe(floating) - expect(joinedOrdinary).toBe(floating) - resolveDetection(['codex']) - await Promise.all([floating, ordinary, joinedOrdinary]) - expect(store.getState().detectedAgentIds).toEqual(['codex']) - - listener.mockClear() - await store.getState().ensureDetectedAgents() - await store.getState().ensureDetectedAgents() - expect(listener).not.toHaveBeenCalled() - unsubscribe() - }) - it('keeps native provider inventory across WSL selection and refresh', async () => { const store = createTestStore([makeRepo('repo-1')]) const projects = store.getState().projects diff --git a/src/renderer/src/store/slices/browser/browser.test.ts b/src/renderer/src/store/slices/browser/browser.test.ts index 9cee611df9b..12c79f59f46 100644 --- a/src/renderer/src/store/slices/browser/browser.test.ts +++ b/src/renderer/src/store/slices/browser/browser.test.ts @@ -1,13 +1,13 @@ import { describe, expect, it, vi } from 'vitest' -import type { AppState } from '../../types' + import { GRAB_BUDGET, type BrowserPageAnnotation } from '../../../../../shared/browser-grab-types' import { makeAnnotation } from './annotations/browser-annotation-test-fixture' -import { FLOATING_TERMINAL_WORKTREE_ID, getDefaultSettings } from '../../../../../shared/constants' +import { getDefaultSettings } from '../../../../../shared/constants' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import type { BrowserSessionProfile } from '../../../../../shared/browser-workspace-types' import type { ManagedBrowserProfileOwner } from '../../../../../shared/browser-profile-scope' import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture' -import { createBrowserMockApi, createTestStore } from './browser-slice-test-harness' +import { createBrowserMockApi } from './browser-slice-test-harness' import { createTestStoreDrawnFromMain } from './browser-slice-drawn-from-main.test-fixture' const createWebRuntimeSessionBrowserTabMock = vi.hoisted(() => vi.fn()) @@ -150,60 +150,6 @@ describe('createBrowserSlice annotations', () => { expect(store.getState().managedBrowserProfileStatusById['minted-by-main']).toBeUndefined() }) - it('puts a removed history page back as it was on Undo, unless a revisit already re-created it', () => { - const store = createTestStore() - store.getState().addBrowserHistoryEntry('https://example.com', 'Example') - store.getState().addBrowserHistoryEntry('https://example.com', 'Example') - const [visited] = store.getState().browserUrlHistory - - const removed = store.getState().removeBrowserHistoryEntry(visited!.normalizedUrl) - expect(removed).toBe(visited) - expect(store.getState().browserUrlHistory).toEqual([]) - store - .getState() - .restoreBrowserHistory({ browserUrlHistory: [removed!], workspaceDocHistory: [] }) - expect(store.getState().browserUrlHistory).toEqual([visited]) - - store.getState().removeBrowserHistoryEntry(visited!.normalizedUrl) - store.getState().addBrowserHistoryEntry('https://example.com', 'Example') - const revisited = store.getState().browserUrlHistory - store - .getState() - .restoreBrowserHistory({ browserUrlHistory: [removed!], workspaceDocHistory: [] }) - expect(store.getState().browserUrlHistory).toBe(revisited) - }) - - it('clears pages and documents visited since a time, and Undo puts back exactly those', () => { - vi.useFakeTimers() - try { - const store = createTestStore() - const doc = { kind: 'workspace-doc' as const, worktreeId: 'wt-1', filePath: '/repo/a.html' } - vi.setSystemTime(1_000) - store.getState().addBrowserHistoryEntry('https://old.example', 'Old') - vi.setSystemTime(5_000) - store.getState().addBrowserHistoryEntry('https://new.example', 'New') - store.getState().recordWorkspaceDocVisit(doc, 'Doc') - - const removed = store.getState().clearBrowserHistory(5_000) - expect(store.getState().browserUrlHistory.map((e) => e.title)).toEqual(['Old']) - expect(store.getState().workspaceDocHistory).toEqual([]) - - store.getState().restoreBrowserHistory(removed) - expect( - store - .getState() - .browserUrlHistory.map((e) => e.title) - .sort() - ).toEqual(['New', 'Old']) - expect(store.getState().workspaceDocHistory.map((e) => e.title)).toEqual(['Doc']) - - store.getState().clearBrowserHistory() - expect(store.getState().browserUrlHistory).toEqual([]) - } finally { - vi.useRealTimers() - } - }) - it('sanitizes persistent annotation payloads at the store boundary', async () => { const { store, main } = await createTestStoreDrawnFromMain() const tab = store.getState().createBrowserTab('wt-1', 'https://example.com') @@ -234,29 +180,6 @@ describe('createBrowserSlice annotations', () => { }) }) -describe('createBrowserSlice floating tabs', () => { - it('tracks new floating browser tabs without changing the main browser surface', async () => { - const { store, main } = await createTestStoreDrawnFromMain() - store.setState({ activeWorktreeId: 'wt-1', activeTabType: 'terminal' } as Partial) - const mainTab = store.getState().createBrowserTab('wt-1', 'https://example.com') - await main.settle() - const activeTabTypeBeforeFloating = store.getState().activeTabType - - const tab = store.getState().createBrowserTab(FLOATING_TERMINAL_WORKTREE_ID, 'about:blank', { - focusAddressBar: true - }) - await main.settle() - - expect(store.getState().activeBrowserTabId).toBe(mainTab.id) - expect(store.getState().activeBrowserTabIdByWorktree['wt-1']).toBe(mainTab.id) - expect(store.getState().activeBrowserTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toBe( - tab.id - ) - expect(store.getState().pendingAddressBarFocusByTabId[tab.id]).toBe(true) - expect(store.getState().activeTabType).toBe(activeTabTypeBeforeFloating) - }) -}) - describe('createBrowserSlice closed browser workspaces', () => { it('reopens duplicate-URL browser pages on the originally active page', async () => { const { store, main } = await createTestStoreDrawnFromMain() diff --git a/src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts b/src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts index 62b18a737fb..118ebf8998f 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts @@ -115,22 +115,6 @@ describe('convertBrowserPage doc→web', () => { expect(workspace?.docLocation ?? null).toBeNull() expect(workspace?.activePageId).toBe(converted?.id) }) - - it('refuses to convert a web page to web — that is navigation, not conversion', async () => { - const store = await createStoreWithWorktree() - const tab = store.getState().createBrowserTab(WORKTREE_ID, 'https://example.com/') - await settled() - const pageId = store.getState().browserPagesByWorkspace[tab.id]?.[0]?.id ?? '' - - const converted = store - .getState() - .convertBrowserPage(pageId, { kind: 'web', url: 'https://other.example/' }) - await settled() - - expect(converted).toBeNull() - expect(store.getState().browserPagesByWorkspace[tab.id]?.[0]?.id).toBe(pageId) - expect(store.getState().browserPagesByWorkspace[tab.id]?.[0]?.url).toBe('https://example.com/') - }) }) describe('convertBrowserPage doc→doc retarget', () => { @@ -188,36 +172,6 @@ describe('convertBrowserPage history legs', () => { const parsed = browserPageSchema.parse(store.getState().browserPagesByWorkspace[tabId]?.[0]) expect(parsed.convertedTo).toEqual(expectedForward) }) - - it('the advance leg re-records convertedFrom and consumes convertedTo — a two-entry ping-pong', async () => { - const store = await createStoreWithWorktree() - const { pageId } = await createDocTab(store) - const webPage = store - .getState() - .convertBrowserPage(pageId, { kind: 'web', url: 'https://example.com/' }) - await settled() - const docPage = store - .getState() - .convertBrowserPage( - webPage?.id ?? '', - { kind: 'workspace-doc', docLocation: DOC_LOCATION }, - { leg: 'history-return' } - ) - await settled() - - const advanced = store - .getState() - .convertBrowserPage( - docPage?.id ?? '', - { kind: 'web', url: 'https://example.com/' }, - { leg: 'history-advance' } - ) - await settled() - - expect(advanced?.url).toBe('https://example.com/') - expect(advanced?.convertedFrom).toEqual({ kind: 'workspace-doc', docLocation: DOC_LOCATION }) - expect(advanced?.convertedTo ?? null).toBeNull() - }) }) describe('convertBrowserPage placement and activation', () => { diff --git a/src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts b/src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts index bd87de25704..7ff6f5b1dc6 100644 --- a/src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts +++ b/src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts @@ -143,71 +143,6 @@ describe('a browser page that shows a workspace document', () => { expect(urlPage?.docLocation ?? null).toBeNull() }) - it('reopens a closed document tab with its document identity', async () => { - const store = await createStoreWithWorktree() - const tab = store.getState().createBrowserTab(WORKTREE_ID, LIVE_GRANT_URL, { - docLocation: DOC_LOCATION, - browserRuntimeEnvironmentId: null - }) - await settled() - - store.getState().closeBrowserTab(tab.id) - await settled() - const reopened = store.getState().reopenClosedBrowserTab(WORKTREE_ID) - await settled() - const page = reopened ? store.getState().browserPagesByWorkspace[reopened.id]?.[0] : undefined - - expect(page?.docLocation).toEqual(DOC_LOCATION) - expect(reopened?.docLocation).toEqual(DOC_LOCATION) - }) - - it('reopens a closed document page with its document identity', async () => { - const store = await createStoreWithWorktree() - const tab = store.getState().createBrowserTab(WORKTREE_ID, 'https://example.com/') - await settled() - const documentPage = store.getState().createBrowserPage(tab.id, LIVE_GRANT_URL, { - docLocation: DOC_LOCATION, - browserRuntimeEnvironmentId: null - }) - await settled() - if (!documentPage) { - throw new Error('Expected a document page') - } - - store.getState().closeBrowserPage(documentPage.id) - await settled() - const reopened = store.getState().reopenClosedBrowserPage(tab.id) - await settled() - - expect(reopened?.docLocation).toEqual(DOC_LOCATION) - }) - - it('restores as the document it was, still blank', async () => { - const store = await createStoreWithWorktree() - const tab = store.getState().createBrowserTab(WORKTREE_ID, LIVE_GRANT_URL, { - docLocation: DOC_LOCATION, - browserRuntimeEnvironmentId: null - }) - await settled() - const session = persistedSession(store) - - const restored = await createStoreWithWorktree() - restored.getState().hydrateBrowserSession({ - activeRepoId: 'repo1', - activeWorktreeId: WORKTREE_ID, - activeTabId: null, - tabsByWorktree: {}, - terminalLayoutsByTabId: {}, - ...session - }) - - const page = restored.getState().browserPagesByWorkspace[tab.id]?.[0] - expect(page?.docLocation).toEqual(DOC_LOCATION) - expect(restored.getState().browserTabsByWorktree[WORKTREE_ID]?.[0]?.docLocation).toEqual( - DOC_LOCATION - ) - }) - // Malformed pages salvage to empty arrays; hydration then rebuilds from tab chrome, so test that fallback. it('restores from the tab alone when its page row was salvaged away', async () => { const store = await createStoreWithWorktree() @@ -271,18 +206,4 @@ describe('conversion provenance at the session schema door', () => { browserRuntimeEnvironmentId: 'env-1' }) }) - - it('applies the same fence to convertedTo, Forward’s side of the crossing', () => { - const tainted = browserPageSchema.parse({ - ...PAGE_ROW, - convertedTo: { kind: 'url', url: LIVE_GRANT_URL } - }) - expect(tainted.convertedTo ?? null).toBeNull() - - const kept = browserPageSchema.parse({ - ...PAGE_ROW, - convertedTo: { kind: 'url', url: 'https://example.com/' } - }) - expect(kept.convertedTo).toEqual({ kind: 'url', url: 'https://example.com/' }) - }) }) diff --git a/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts b/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts index 280697e79fe..2338f8681f0 100644 --- a/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts +++ b/src/renderer/src/store/slices/browser/profiles/browser-session-profiles.test.ts @@ -1,12 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AppState } from '../../../types' -import type { BrowserCookieImportSummary } from '../../../../../../shared/browser-workspace-types' + import { getDefaultBrowserProfileForHost } from '../hosts/browser-host-state' import { createBrowserMockApi, createTestStore, - resetBrowserRuntimeMocks, - settingsWithRuntime + resetBrowserRuntimeMocks } from '../browser-slice-test-harness' const createWebRuntimeSessionBrowserTabMock = vi.hoisted(() => vi.fn()) @@ -35,119 +33,6 @@ describe('createBrowserSlice runtime guard', () => { vi.unstubAllGlobals() }) - it('keeps the default profile pick when a server profile fetch fails', async () => { - const store = createTestStore() - runtimeEnvironmentCall.mockRejectedValueOnce(new Error('timed out')) - store.setState({ - settings: { - ...settingsWithRuntime('env-1')!, - browserDefaultProfileIdByHostId: { 'runtime:env-1': 'work' } - } - }) - - await store.getState().fetchBrowserSessionProfiles() - - expect(getDefaultBrowserProfileForHost(store.getState(), 'runtime:env-1')).toBe('work') - }) - - it('keeps browser profile lists separate per host', async () => { - const store = createTestStore() - runtimeEnvironmentCall.mockResolvedValueOnce({ - id: 'rpc-remote', - ok: true, - result: { - profiles: [ - { - id: 'remote-default', - scope: 'default', - partition: 'persist:orca-remote', - label: 'Remote Default', - source: null - } - ] - }, - _meta: { runtimeId: 'runtime-remote' } - }) - store.setState({ settings: settingsWithRuntime('env-1') }) - - await store.getState().fetchBrowserSessionProfiles() - - mockApi.browser.sessionListProfiles.mockResolvedValueOnce([ - { - id: 'local-default', - scope: 'default', - partition: 'persist:orca-local', - label: 'Local Default', - source: null - } - ]) - store.setState({ settings: { activeRuntimeEnvironmentId: null } as AppState['settings'] }) - - await store.getState().fetchBrowserSessionProfiles() - - expect(store.getState().browserSessionProfilesByHostId['runtime:env-1']?.[0]?.id).toBe( - 'remote-default' - ) - expect(store.getState().browserSessionProfilesByHostId.local?.[0]?.id).toBe('local-default') - expect(store.getState().browserSessionProfiles[0]?.id).toBe('local-default') - }) - - it.each(['local IPC', 'client-hosted IPC', 'remote RPC'] as const)( - 'preserves the cookie import execution owner from %s through the store', - async (route) => { - const summary: BrowserCookieImportSummary = { - totalCookies: 5, - importedCookies: 0, - skippedCookies: 5, - domains: [], - warning: { - code: 'cookies-undecryptable', - reason: 'linux-keyring-unavailable', - failedCookies: 3, - otherFailedCookies: 2, - keyringFailure: { cause: 'secret-tool-missing', browser: 'Google Chrome' } - } - } - const importResult = { ok: true as const, profileId: 'default', summary } - const store = createTestStore() - if (route === 'local IPC') { - mockApi.browser.sessionImportFromBrowser.mockResolvedValueOnce(importResult) - } else { - store.setState({ settings: settingsWithRuntime('env-1') }) - mockApi.browser.sessionImportFromBrowserForClientHost.mockResolvedValueOnce( - route === 'client-hosted IPC' ? importResult : null - ) - if (route === 'remote RPC') { - runtimeEnvironmentCall.mockResolvedValueOnce({ - id: 'rpc-import', - ok: true, - result: importResult, - _meta: { runtimeId: 'runtime-1' } - }) - } - } - - const result = await store.getState().importCookiesFromBrowser('default', 'chrome', 'Default') - - expect(result.ok).toBe(true) - if (!result.ok) { - throw new Error(result.reason) - } - expect(result.summary).toEqual(summary) - expect(store.getState().browserSessionImportState).toEqual({ - profileId: 'default', - status: 'success', - summary, - error: null - }) - expect(result).toMatchObject({ - executionHostId: route === 'local IPC' ? 'local' : 'runtime:env-1', - executionMachine: route === 'remote RPC' ? 'remote' : 'client', - executionRemoteEnvironment: route !== 'local IPC' - }) - } - ) - it('drops the default profile pick once a refreshed list no longer has it', async () => { const store = createTestStore() const listed = (id: string) => ({ diff --git a/src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts b/src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts index b3e09fc3faf..af0dcd00a4c 100644 --- a/src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts +++ b/src/renderer/src/store/slices/browser/tabs/browser-tab-creation-placement.test.ts @@ -2,8 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as AgentStatusModule from '@/lib/agent-status' import type { Tab, TabGroup } from '../../../../../../shared/tab-types' import type { ExecutionHostId } from '../../../../../../shared/execution-host' -import type { FolderWorkspace } from '../../../../../../shared/folder-workspaces/folder-workspace-types' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' + import { createTestStore, seedStore } from '../../../testing/app-store-test-fixture' import { makeTabGroup, makeUnifiedTab } from '../../tabs/tab-group.test-fixture' import { makeWorktree } from '../../worktrees/worktree.test-fixture' @@ -137,26 +136,6 @@ describe('browser tab creation placement', () => { await main?.settle() } - it('opens Group New Browser Tab in a new split beside the invoking group', async () => { - seedSplit(store) - await drawFromMain() - await store.getState().openNewBrowserTabInActiveWorkspace(G1, 'right') - await settled() - const n = store - .getState() - .unifiedTabsByWorktree[WT]!.find((tab) => !['A', 'B', 'C', 'X'].includes(tab.id))! - expect(group(store, G1)?.tabOrder).toEqual(['A', 'B', 'C']) - expect(store.getState().layoutByWorktree[WT]).toMatchObject({ - first: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: G1 }, - second: { type: 'leaf', groupId: n.groupId } - }, - second: { type: 'leaf', groupId: G2 } - }) - }) - it('uses the invoking group workspace instead of the globally selected one', async () => { seedSplit(store) store.setState({ activeWorktreeId: 'repo1::/elsewhere' }) @@ -193,84 +172,6 @@ describe('browser tab creation placement', () => { expect(after.unifiedTabsByWorktree[WT]!.find((tab) => tab.id === 'B')?.lastFocusedAt).toBe(100) }) - it('lets an explicit destination win over the anchor group', async () => { - seedSplit(store) - await drawFromMain() - const workspace = store - .getState() - .createBrowserTab(WT, 'https://example.com', { afterTabId: 'B', targetGroupId: G2 }) - await settled() - expect(group(store, G2)?.tabOrder).toEqual(['X', createdUnifiedId(store, workspace.id)]) - expect(group(store, G1)?.tabOrder).toEqual(['A', 'B', 'C']) - }) - - it('falls back to the active group, not the first group, for an expired requested group', async () => { - seedSplit(store) - await drawFromMain() - const workspace = store - .getState() - .createBrowserTab(WT, 'https://example.com', { targetGroupId: 'deleted-group' }) - await settled() - expect(group(store, G2)?.tabOrder).toEqual(['X', createdUnifiedId(store, workspace.id)]) - }) - - it('keeps an unpinned tab from a pinned source after the pinned prefix', async () => { - seedSplit(store, { - tabs: [ - browserTab('P1', G1, { isPinned: true }), - browserTab('P2', G1, { isPinned: true }), - browserTab('C', G1), - browserTab('X', G2) - ], - groups: [ - makeTabGroup({ id: G1, worktreeId: WT, activeTabId: 'P1', tabOrder: ['P1', 'P2', 'C'] }), - makeTabGroup({ id: G2, worktreeId: WT, activeTabId: 'X', tabOrder: ['X'] }) - ] - }) - await drawFromMain() - const workspace = store - .getState() - .createBrowserTab(WT, 'https://example.com', { afterTabId: 'P1' }) - await settled() - expect(group(store, G1)?.tabOrder).toEqual([ - 'P1', - 'P2', - createdUnifiedId(store, workspace.id), - 'C' - ]) - }) - - it('appends in the partition when preview replacement removes the anchor', () => { - seedSplit(store, { - tabs: [ - browserTab('A', G1, { sortOrder: 0 }), - makeUnifiedTab({ - id: 'P', - worktreeId: WT, - groupId: G1, - contentType: 'editor', - isPreview: true, - sortOrder: 1 - }), - browserTab('C', G1, { sortOrder: 2 }), - browserTab('X', G2) - ], - groups: [ - makeTabGroup({ id: G1, worktreeId: WT, activeTabId: 'P', tabOrder: ['A', 'P', 'C'] }), - makeTabGroup({ id: G2, worktreeId: WT, activeTabId: 'X', tabOrder: ['X'] }) - ] - }) - const created = store - .getState() - .createUnifiedTab(WT, 'editor', { afterTabId: 'P', isPreview: true, targetGroupId: G1 }) - expect(group(store, G1)?.tabOrder).toEqual(['A', 'C', created.id]) - expect(created.sortOrder).toBe(2) - const sortOrderById = Object.fromEntries( - store.getState().unifiedTabsByWorktree[WT]!.map((tab) => [tab.id, tab.sortOrder]) - ) - expect(sortOrderById).toMatchObject({ A: 0, C: 1, [created.id]: 2 }) - }) - it('rejects an anchor owned by a foreign execution host', async () => { seedSplit(store, { tabs: [browserTab('A', G1, { executionHostId: 'ssh:other' }), browserTab('X', G2)], @@ -314,62 +215,4 @@ describe('browser tab creation placement', () => { await settled() expect(group(store, G1)?.tabOrder).toEqual(['A', createdUnifiedId(store, workspace.id), 'C']) }) - - it('places source actions in folder and floating workspaces', async () => { - const folderWt = 'folder:folder-1' - const folder: FolderWorkspace = { - id: 'folder-1', - projectGroupId: 'pg', - name: 'Folder', - folderPath: '/tmp/folder', - executionHostId: 'local', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } - for (const worktreeId of [folderWt, FLOATING_TERMINAL_WORKTREE_ID]) { - store.setState({ - folderWorkspaces: [folder], - unifiedTabsByWorktree: { - ...store.getState().unifiedTabsByWorktree, - [worktreeId]: ['A', 'B'].map((id) => - makeUnifiedTab({ - id: `${worktreeId}-${id}`, - worktreeId, - groupId: `${worktreeId}-g`, - contentType: 'browser' - }) - ) - }, - groupsByWorktree: { - ...store.getState().groupsByWorktree, - [worktreeId]: [ - makeTabGroup({ - id: `${worktreeId}-g`, - worktreeId, - activeTabId: `${worktreeId}-A`, - tabOrder: [`${worktreeId}-A`, `${worktreeId}-B`] - }) - ] - } - }) - await drawFromMain() - const workspace = store.getState().createBrowserTab(worktreeId, 'https://example.com', { - afterTabId: `${worktreeId}-A`, - browserRuntimeEnvironmentId: null - }) - await settled() - expect(group(store, `${worktreeId}-g`, worktreeId)?.tabOrder).toEqual([ - `${worktreeId}-A`, - createdUnifiedId(store, workspace.id, worktreeId), - `${worktreeId}-B` - ]) - } - }) }) diff --git a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts index e812b2246ea..4f25defa420 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts @@ -20,7 +20,7 @@ vi.mock('./web-runtime-session', () => ({ })) import { callEnvironmentEnvelope } from './web-runtime-calls' -import { RUNTIME_CONNECTION_CHANGED_MESSAGE } from '../web-runtime-request-registry' +import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result' describe('web runtime call pinned to the probed runtime', () => { beforeEach(() => { @@ -43,7 +43,7 @@ describe('web runtime call pinned to the probed runtime', () => { await expect( callEnvironmentEnvelope('env-1', 'files.write', {}, 15_000, undefined, 'runtime-a') - ).rejects.toThrow(RUNTIME_CONNECTION_CHANGED_MESSAGE) + ).rejects.toBeInstanceOf(RuntimeConnectionChangedBeforeSendError) expect(session.client.call).not.toHaveBeenCalledWith( 'files.write', expect.anything(), diff --git a/src/renderer/src/web/preload-api/web-runtime-calls.ts b/src/renderer/src/web/preload-api/web-runtime-calls.ts index 08f28a765ee..d59c7abeb3b 100644 --- a/src/renderer/src/web/preload-api/web-runtime-calls.ts +++ b/src/renderer/src/web/preload-api/web-runtime-calls.ts @@ -1,3 +1,4 @@ +import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result' import type { PreloadApi } from '../../../../preload/api-types' import type { WebRuntimeSubscribeOptions } from '../web-runtime-subscription-contract' import { parseExecutionHostId, toRuntimeExecutionHostId } from '../../../../shared/execution-host' @@ -58,7 +59,9 @@ export function assertEnvironmentPairing(selector: string, expectedRevision?: nu expectedRevision !== undefined && (current.pairingRevision ?? current.createdAt) !== expectedRevision ) { - throw new Error('The paired Orca server changed while the request was in progress.') + throw new RuntimeConnectionChangedBeforeSendError( + 'The paired Orca server changed while the request was in progress.' + ) } } @@ -112,7 +115,7 @@ async function callPinnedToRuntime( } const probed = probedConnections.get(client) if (probed?.runtimeId !== expectedEnvironmentRuntimeId) { - throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE) + throw new RuntimeConnectionChangedBeforeSendError(RUNTIME_CONNECTION_CHANGED_MESSAGE) } return client.call(method, params, { timeoutMs, expectedConnectionEpoch: probed.epoch }) } diff --git a/src/renderer/src/web/preload-api/web-ui-api.ts b/src/renderer/src/web/preload-api/web-ui-api.ts index 5f6b1e2ec31..6d962839dde 100644 --- a/src/renderer/src/web/preload-api/web-ui-api.ts +++ b/src/renderer/src/web/preload-api/web-ui-api.ts @@ -147,6 +147,8 @@ export function createWebUiApi(): NonNullable['ui']> { await (navigator.clipboard?.readText?.() ?? ''), options ), + // Browser paste events carry their own HTML; a programmatic read would prompt. + readClipboardLinkHtml: async () => '', readSelectionClipboardText: () => Promise.reject(new Error('Selection clipboard is unavailable in the web client')), saveClipboardImageAsTempFile: saveWebClipboardImageAsTempFile, diff --git a/src/renderer/src/web/web-runtime-request-registry-connection-pin.test.ts b/src/renderer/src/web/web-runtime-request-registry-connection-pin.test.ts index c1ea3bcf3e5..01ff43d5798 100644 --- a/src/renderer/src/web/web-runtime-request-registry-connection-pin.test.ts +++ b/src/renderer/src/web/web-runtime-request-registry-connection-pin.test.ts @@ -1,8 +1,6 @@ +import { RuntimeConnectionChangedBeforeSendError } from '../runtime/rpc/calls/runtime-rpc-result' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - RUNTIME_CONNECTION_CHANGED_MESSAGE, - WebRuntimeRequestRegistry -} from './web-runtime-request-registry' +import { WebRuntimeRequestRegistry } from './web-runtime-request-registry' describe('web runtime request connection pin', () => { beforeEach(() => { @@ -37,7 +35,7 @@ describe('web runtime request connection pin', () => { const write = registry.call('files.write', {}, { expectedConnectionEpoch: probedEpoch }) reconnect() - await expect(write).rejects.toThrow(RUNTIME_CONNECTION_CHANGED_MESSAGE) + await expect(write).rejects.toBeInstanceOf(RuntimeConnectionChangedBeforeSendError) expect(sendEncrypted).not.toHaveBeenCalled() }) }) diff --git a/src/renderer/src/web/web-runtime-request-registry.ts b/src/renderer/src/web/web-runtime-request-registry.ts index 26ad5ccff3d..075b5d84f83 100644 --- a/src/renderer/src/web/web-runtime-request-registry.ts +++ b/src/renderer/src/web/web-runtime-request-registry.ts @@ -1,3 +1,4 @@ +import { RuntimeConnectionChangedBeforeSendError } from '../runtime/rpc/calls/runtime-rpc-result' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import type { WebRuntimePendingRequest } from './web-runtime-connection-frame-router' @@ -55,7 +56,7 @@ export class WebRuntimeRequestRegistry { callOptions?.expectedConnectionEpoch !== undefined && callOptions.expectedConnectionEpoch !== this.connectionEpoch ) { - throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE) + throw new RuntimeConnectionChangedBeforeSendError(RUNTIME_CONNECTION_CHANGED_MESSAGE) } return new Promise((resolve, reject) => { const id = this.options.nextId() diff --git a/src/shared/agent-hook-listener/transport/agent-hook-suppression-env.ts b/src/shared/agent-hook-listener/transport/agent-hook-suppression-env.ts new file mode 100644 index 00000000000..41008b9dfc1 --- /dev/null +++ b/src/shared/agent-hook-listener/transport/agent-hook-suppression-env.ts @@ -0,0 +1 @@ +export const ORCA_AGENT_HOOKS_DISABLED_ENV = 'ORCA_AGENT_HOOKS_DISABLED' diff --git a/src/shared/agent-session/agent-session-create-capabilities.ts b/src/shared/agent-session/agent-session-create-capabilities.ts index dcf2438bd03..641cbd09ae4 100644 --- a/src/shared/agent-session/agent-session-create-capabilities.ts +++ b/src/shared/agent-session/agent-session-create-capabilities.ts @@ -1,6 +1,9 @@ // Strict create hosts must advertise native independent conversation forks. export const AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY = 'agentSession.create.fork.v1' as const +export const AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY = + 'agentSession.create.fork.original.v1' as const + // Create is strict: send reserved tabId only to hosts advertising support. export const AGENT_SESSION_CREATE_TAB_ID_RUNTIME_CAPABILITY = 'agentSession.create.tab-id.v1' as const @@ -41,6 +44,7 @@ export const AGENT_SESSION_SEND_SELECTION_RUNTIME_CAPABILITY = export const AGENT_SESSION_CREATE_RUNTIME_CAPABILITIES = [ AGENT_SESSION_CREATE_FORK_RUNTIME_CAPABILITY, + AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY, AGENT_SESSION_USAGE_LIMIT_AUTO_CONTINUE_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_SELECTION_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_USAGE_LIMIT_CONTINUATION_RUNTIME_CAPABILITY, diff --git a/src/shared/agent-session/agent-session-fork.ts b/src/shared/agent-session/agent-session-fork.ts index ec11504d7ae..250df26302a 100644 --- a/src/shared/agent-session/agent-session-fork.ts +++ b/src/shared/agent-session/agent-session-fork.ts @@ -1,2 +1,19 @@ +import type { AgentJournalRenderItem } from './journal/agent-session-journal-types' +import type { AgentSessionForkedFrom } from './lifecycle/agent-session-record' + /** The derived row after a fork's inherited history; clients draw it as a divider linking to the source. */ export const AGENT_SESSION_FORKED_FROM_PRESENTATION = 'forked-from' + +/** Inherited rows belong to the original chat's action scope. */ +export function isInheritedAgentSessionItem( + items: readonly Pick[], + boundary: AgentSessionForkedFrom['childBoundary'] | undefined, + itemId: string +): boolean { + if (boundary?.kind !== 'item') { + return false + } + const anchor = items.findIndex((item) => item.itemId === boundary.itemId) + const selected = items.findIndex((item) => item.itemId === itemId) + return selected !== -1 && selected <= anchor +} diff --git a/src/shared/agent-session/failures/agent-session-definitive-refusal.ts b/src/shared/agent-session/failures/agent-session-definitive-refusal.ts index d622a7a0714..4f504d2950a 100644 --- a/src/shared/agent-session/failures/agent-session-definitive-refusal.ts +++ b/src/shared/agent-session/failures/agent-session-definitive-refusal.ts @@ -19,6 +19,24 @@ export function isAgentSessionCreateAdmissionRefusal( ) } +/** Source admission can prove these refusals only before the native fork begins. */ +export function isAgentSessionForkSourceAdmissionRefusal( + refusal: Pick +): boolean { + return ( + (refusal.code === 'agent_session_identity_required' && + refusal.details?.reason === 'recordMissing') || + (refusal.code === 'agent_session_operation_invalid' && + [ + 'savedConversationMissing', + 'conversationCleared', + 'rewindUnconfirmed', + 'turnActive', + 'launchFolderMissing' + ].includes(refusal.details?.reason ?? '')) + ) +} + /** Proves the host neither created a session nor will on a retry. */ const DEFINITIVE_REFUSAL_CODES: ReadonlySet = new Set([ 'structured_agent_session_unsupported' diff --git a/src/shared/agent-session/failures/agent-session-failure-copy.ts b/src/shared/agent-session/failures/agent-session-failure-copy.ts index c59a106dd5b..c8ddccf4cab 100644 --- a/src/shared/agent-session/failures/agent-session-failure-copy.ts +++ b/src/shared/agent-session/failures/agent-session-failure-copy.ts @@ -20,6 +20,18 @@ export const AGENT_STILL_WORKING = 'The agent is still working.' /** Whole translatable pieces; the host fills agent (name or theAgent) and command (conversation command name) in English. */ export const AGENT_SESSION_FAILURE_COPY = { theAgent: 'The agent', + 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.', unconfirmed: "Couldn't confirm whether this was sent. It hasn't been resent.", providerStartFailed: '{{agent}} stopped before it finished starting.', savedConversationMissing: "{{agent}} couldn't find this chat's saved conversation.", @@ -259,3 +271,32 @@ export const sayAgentSessionFailureEnglish: AgentSessionFailureSay = (id, values (placeholder, name: string) => filled.get(name) ?? placeholder ) } + +/** Translate authored original-chat refusals without changing other fork failures. */ +export function agentSessionForkSourceFailureWords( + message: string, + agent: string, + say: AgentSessionFailureSay +): string | null { + for (const id of [ + 'forkOriginalMissing', + 'forkOriginalUnavailable', + 'forkOriginalMissingNamed', + 'forkOriginalUnavailableNamed', + 'forkOriginalLatestOnly', + 'forkOriginalLatestOnlyNamed' + ] as const) { + const [prefix, suffix] = sayAgentSessionFailureEnglish(id, { agent }).split('{{detail}}') + if ( + suffix === undefined + ? message === prefix + : message.startsWith(prefix) && message.endsWith(suffix) + ) { + return say(id, { + agent, + ...(suffix === undefined ? {} : { detail: message.slice(prefix.length, -suffix.length) }) + }) + } + } + return null +} diff --git a/src/shared/agent-session/lifecycle/agent-session-rewind-targets.ts b/src/shared/agent-session/lifecycle/agent-session-rewind-targets.ts index d297385584a..7f6d0215f8a 100644 --- a/src/shared/agent-session/lifecycle/agent-session-rewind-targets.ts +++ b/src/shared/agent-session/lifecycle/agent-session-rewind-targets.ts @@ -1,10 +1,11 @@ +import { AGENT_SESSION_FORKED_FROM_PRESENTATION } from '../agent-session-fork' import { isAgentSessionRewindTarget, savedRewindKeys } from './agent-session-rewind' import { readAgentJournalTurn } from './agent-session-turn-record' import type { StructuredAgentSessionState } from '../structured-agent-session-reducer' import type { AgentJournalCursor } from '../journal/agent-session-journal-identity' import { agentSessionContextFloorSequence, - latestAgentSessionContextClearSequence + isAgentSessionContextClear } from '../agent-session-context-clear' /** User messages past `floor` the host can rewind to. */ @@ -37,13 +38,20 @@ function turnOpeners(items: StructuredAgentSessionState['items']): Map, contextFloor: AgentJournalCursor | undefined ): number { - return Math.max( - latestAgentSessionContextClearSequence(state.items), - agentSessionContextFloorSequence(contextFloor, state.epoch) - ) + let floor = agentSessionContextFloorSequence(contextFloor, state.epoch) + for (const item of state.items) { + if ( + isAgentSessionContextClear(item.body) || + (item.body.kind === 'status' && + item.body.presentation === AGENT_SESSION_FORKED_FROM_PRESENTATION) + ) { + floor = Math.max(floor, item.sequence) + } + } + return floor } diff --git a/src/shared/agent-status/title/providers/hermes-terminal-title.test.ts b/src/shared/agent-status/title/providers/hermes-terminal-title.test.ts new file mode 100644 index 00000000000..fcc3caab0fb --- /dev/null +++ b/src/shared/agent-status/title/providers/hermes-terminal-title.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { hermesNativeTitleStatus } from './hermes-terminal-title' + +describe('Hermes native session title markers', () => { + it.each([ + ['hermes', '✓ Run Orca dispatched worker … · grok-4.7 · ~/workspace', 'idle'], + ['hermes', '⏳ Ready to deploy', 'working'], + ['hermes', '⚠ Finished the changes', 'permission'], + ['hermes', '⚠️ Waiting for approval', 'permission'], + ['hermes', 'user@host: ~/workspace', null], + ['hermes', '✓not a status marker', null], + ['codex', '✓ Run Orca dispatched worker …', null], + [null, '✓ Run Orca dispatched worker …', null] + ] as const)('classifies %s title %s as %s', (agent, title, expected) => { + expect(hermesNativeTitleStatus(title, agent)).toBe(expected) + }) +}) diff --git a/src/shared/agent-status/title/providers/hermes-terminal-title.ts b/src/shared/agent-status/title/providers/hermes-terminal-title.ts new file mode 100644 index 00000000000..039966ae4cb --- /dev/null +++ b/src/shared/agent-status/title/providers/hermes-terminal-title.ts @@ -0,0 +1,21 @@ +import type { AgentStatus } from '../agent-title-core' +import type { TerminalAgent } from '../../identity/terminal-agent' + +// Hermes TUI titles lead with ⚠ (approval or question), ⏳ (busy) or ✓ (idle), then the session name. +const HERMES_TITLE_MARKER_STATUS: Record = { + '\u2713': 'idle', + '\u23F3': 'working', + '\u26A0': 'permission' +} + +/** The markers are too generic to identify Hermes, so they count only in a Hermes pane. */ +export function hermesNativeTitleStatus( + title: string, + agent: TerminalAgent | null +): AgentStatus | null { + if (agent !== 'hermes') { + return null + } + const marker = title.match(/^(\u2713|\u23F3|\u26A0)\uFE0F?(?:\s|$)/u)?.[1] + return marker ? HERMES_TITLE_MARKER_STATUS[marker] : null +} diff --git a/src/shared/browser-cookie-import-sources.ts b/src/shared/browser-cookie-import-sources.ts index a1eb159ee6e..619c4f4eb27 100644 --- a/src/shared/browser-cookie-import-sources.ts +++ b/src/shared/browser-cookie-import-sources.ts @@ -1,5 +1,5 @@ /** Human-readable import sources aligned with CHROMIUM_BROWSERS in - * browser-cookie-import.ts plus Firefox/Safari detection. */ + * browser-cookie-source-profiles.ts plus Firefox/Safari detection. */ const CHROMIUM_COOKIE_IMPORT_SOURCES = [ { label: 'Google Chrome', mac: true, win: true, linux: true }, { label: 'Microsoft Edge', mac: true, win: true, linux: true }, diff --git a/src/shared/clipboard-link-html.ts b/src/shared/clipboard-link-html.ts new file mode 100644 index 00000000000..951c3035d80 --- /dev/null +++ b/src/shared/clipboard-link-html.ts @@ -0,0 +1,7 @@ +/** Bounds the HTML a composer paste parses for links; larger copies paste as plain text. */ +const CLIPBOARD_LINK_HTML_MAX_LENGTH = 1024 * 1024 + +/** Cheap pre-parse check: only HTML with an anchor can add links to a paste. */ +export function clipboardHtmlMayHaveLinks(html: string): boolean { + return html.length <= CLIPBOARD_LINK_HTML_MAX_LENGTH && / String(params[slot] ?? '') ) const errorParams = Object.fromEntries( @@ -65,18 +77,32 @@ export function ephemeralVmFailure( } } +const EXIT_FAILURE_CODES = { + recipe: ['recipeExited', 'recipeExitedWithoutCode'], + suspend: ['suspendExited', 'suspendExitedWithoutCode'], + resume: ['resumeExited', 'resumeExitedWithoutCode'], + destroy: ['destroyExited', 'destroyExitedWithoutCode'] +} as const satisfies Record + export function ephemeralVmExitFailure( - step: 'recipe' | 'destroy', + step: keyof typeof EXIT_FAILURE_CODES, exitCode: number | null ): EphemeralVmFailure { - if (step === 'recipe') { - return exitCode === null - ? ephemeralVmFailure('recipeExitedWithoutCode') - : ephemeralVmFailure('recipeExited', { exitCode }) - } + const [withCode, withoutCode] = EXIT_FAILURE_CODES[step] return exitCode === null - ? ephemeralVmFailure('destroyExitedWithoutCode') - : ephemeralVmFailure('destroyExited', { exitCode }) + ? ephemeralVmFailure(withoutCode) + : ephemeralVmFailure(withCode, { exitCode }) +} + +export function ephemeralVmTimeoutFailure( + mode: OrcaVmRecipeLifecycleMode, + timeoutSeconds: number +): EphemeralVmFailure { + return ephemeralVmFailure('recipeTimedOut', { + mode, + timeout: formatEphemeralVmRecipeTimeout(timeoutSeconds), + timeoutSeconds + }) } /** In-process carrier so a catch site can persist the code next to the English message. */ diff --git a/src/shared/ephemeral-vm-recipe-destroy-result.ts b/src/shared/ephemeral-vm-recipe-destroy-result.ts index e6fa7124994..0be3ae452e2 100644 --- a/src/shared/ephemeral-vm-recipe-destroy-result.ts +++ b/src/shared/ephemeral-vm-recipe-destroy-result.ts @@ -3,6 +3,7 @@ import { EPHEMERAL_VM_FAILURE_COPY, ephemeralVmExitFailure, ephemeralVmFailure, + ephemeralVmTimeoutFailure, type EphemeralVmFailure } from './ephemeral-vm-failure-copy' @@ -15,8 +16,17 @@ type FailedEphemeralVmRecipeDestroy = { ProcessRunResult export function getEphemeralVmRecipeDestroyFailure( - result: ProcessRunResult + result: ProcessRunResult, + timeoutSeconds: number ): FailedEphemeralVmRecipeDestroy | null { + if (result.timedOut) { + return { + ok: false, + skipped: false, + ...ephemeralVmTimeoutFailure('destroy', timeoutSeconds), + ...result + } + } if (result.aborted) { return { ok: false, diff --git a/src/shared/ephemeral-vm-recipe-process-win32-timeout.test.ts b/src/shared/ephemeral-vm-recipe-process-win32-timeout.test.ts new file mode 100644 index 00000000000..275376963d2 --- /dev/null +++ b/src/shared/ephemeral-vm-recipe-process-win32-timeout.test.ts @@ -0,0 +1,59 @@ +import type * as ChildProcess from 'node:child_process' +import { EventEmitter } from 'node:events' +import { PassThrough } from 'node:stream' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const spawnMock = vi.hoisted(() => vi.fn()) +vi.mock('node:child_process', async (importOriginal) => ({ + ...(await importOriginal()), + spawn: spawnMock +})) +vi.mock('@orca/process-host/process-tree-kill-gate', () => ({ + admitProcessTreeKill: () => true +})) + +const { runRecipeCommand } = await import('./ephemeral-vm-recipe-process') + +const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + +afterEach(() => { + vi.useRealTimers() + spawnMock.mockReset() + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } +}) + +describe('runRecipeCommand timeout on Windows', () => { + it('walks the whole process tree with taskkill when the timeout elapses', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + vi.useFakeTimers() + spawnMock.mockImplementation(() => Object.assign(new EventEmitter(), { unref: vi.fn() })) + const child = Object.assign(new EventEmitter(), { + pid: 4242, + stdin: new PassThrough(), + stdout: new PassThrough(), + stderr: new PassThrough(), + kill: vi.fn(), + unref: vi.fn() + }) + + const resultPromise = runRecipeCommand({ + command: 'create', + repoPath: process.cwd(), + mode: 'create', + resultSchemaVersion: 1, + context: { recipeId: 'cloud-sandbox', repoPath: process.cwd() }, + timeoutMs: 1_000, + spawnCommand: vi.fn(() => child) as never + }) + + await vi.advanceTimersByTimeAsync(1_000) + expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/pid', '4242', '/t', '/f'], { + windowsHide: true, + stdio: 'ignore' + }) + child.emit('close', 1, null) + await expect(resultPromise).resolves.toMatchObject({ timedOut: true, exitCode: 1 }) + }) +}) diff --git a/src/shared/ephemeral-vm-recipe-process.test.ts b/src/shared/ephemeral-vm-recipe-process.test.ts index 905923e45f8..3471cb66776 100644 --- a/src/shared/ephemeral-vm-recipe-process.test.ts +++ b/src/shared/ephemeral-vm-recipe-process.test.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'node:events' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { PassThrough } from 'node:stream' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -25,7 +25,105 @@ function nodeCommand(scriptPath: string): string { return `"${process.execPath}" "${scriptPath}"` } +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} + describe('runRecipeCommand', () => { + it.skipIf(process.platform === 'win32')( + 'stops the recipe process group when the timeout elapses', + async () => { + vi.useFakeTimers() + const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true) + const child = Object.assign(new EventEmitter(), { + pid: 4242, + stdin: new PassThrough(), + stdout: new PassThrough(), + stderr: new PassThrough(), + kill: vi.fn(), + unref: vi.fn() + }) + try { + const resultPromise = runRecipeCommand({ + command: 'create', + repoPath: makeRepo(), + mode: 'create', + resultSchemaVersion: 1, + context: { recipeId: 'cloud-sandbox', repoPath: makeRepo() }, + timeoutMs: 60_000, + spawnCommand: vi.fn(() => child) as never + }) + + await vi.advanceTimersByTimeAsync(59_999) + expect(killSpy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(killSpy).toHaveBeenCalledWith(-4242, 'SIGTERM') + + // The shell ignores SIGTERM, so the group is force-killed after the grace period. + await vi.advanceTimersByTimeAsync(5_000) + expect(killSpy).toHaveBeenCalledWith(-4242, 'SIGKILL') + const result = await resultPromise + expect(result).toMatchObject({ timedOut: true, exitCode: null }) + expect(result).not.toHaveProperty('aborted') + } finally { + killSpy.mockRestore() + } + } + ) + + it.skipIf(process.platform === 'win32')( + 'kills grandchildren of a recipe that outlives its timeout', + async () => { + const repoPath = makeRepo() + const sleeperPath = join(repoPath, 'sleeper.js') + const spawnerPath = join(repoPath, 'spawner.js') + const pidPath = join(repoPath, 'grandchild.pid') + writeFileSync(sleeperPath, 'setInterval(() => {}, 1000)\n') + writeFileSync( + spawnerPath, + [ + "const { spawn } = require('node:child_process')", + `const child = spawn(process.execPath, [${JSON.stringify(sleeperPath)}], { stdio: 'ignore' })`, + `require('node:fs').writeFileSync(${JSON.stringify(pidPath)}, String(child.pid))`, + "process.stderr.write('ready\\n')", + 'setInterval(() => {}, 1000)' + ].join('\n') + ) + // Fake only the deadline timers so the timeout fires after the grandchild exists, even under load. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const ready = Promise.withResolvers() + + const resultPromise = runRecipeCommand({ + command: nodeCommand(spawnerPath), + repoPath, + mode: 'create', + resultSchemaVersion: 1, + context: { recipeId: 'cloud-sandbox', repoPath }, + timeoutMs: 1_000, + onStderr: (chunk) => { + if (chunk.includes('ready')) { + ready.resolve() + } + } + }) + await ready.promise + await vi.advanceTimersByTimeAsync(1_000) + const result = await resultPromise + vi.useRealTimers() + + expect(result).toMatchObject({ timedOut: true }) + expect(result).not.toHaveProperty('aborted') + const grandchildPid = Number(readFileSync(pidPath, 'utf8')) + await vi.waitFor(() => expect(isAlive(grandchildPid)).toBe(false), { timeout: 2_000 }) + }, + 10_000 + ) + it('clears the force-kill timer when graceful termination closes synchronously', async () => { vi.useFakeTimers() const child = Object.assign(new EventEmitter(), { diff --git a/src/shared/ephemeral-vm-recipe-process.ts b/src/shared/ephemeral-vm-recipe-process.ts index 320a72cfca9..ec80ba1dd9c 100644 --- a/src/shared/ephemeral-vm-recipe-process.ts +++ b/src/shared/ephemeral-vm-recipe-process.ts @@ -14,6 +14,7 @@ export type ProcessRunResult = { exitCode: number | null signal: NodeJS.Signals | null aborted?: true + timedOut?: true } export function quoteShellToken(value: string): string { @@ -34,6 +35,8 @@ export async function runRecipeCommand(args: { env?: NodeJS.ProcessEnv maxCaptureBytes?: number signal?: AbortSignal + /** Wall-clock limit; on expiry the process tree is stopped like a cancel and the result has timedOut. */ + timeoutMs?: number onStdout?: (chunk: string) => void onStderr?: (chunk: string) => void spawnCommand?: typeof spawn @@ -59,43 +62,50 @@ export async function runRecipeCommand(args: { const stdout = new GrowingByteBuffer() const stderr = new GrowingByteBuffer() let settled = false - let aborted = false + // First reason wins so a cancel racing the deadline is reported as whichever stopped it. + let stopReason: 'aborted' | 'timedOut' | undefined let forceKillTimer: ReturnType | undefined + let deadlineTimer: ReturnType | undefined + const stopFlag = (): Pick => + stopReason === 'aborted' + ? { aborted: true } + : stopReason === 'timedOut' + ? { timedOut: true } + : {} + const settle = (): void => { + settled = true + clearTimeout(forceKillTimer) + clearTimeout(deadlineTimer) + args.signal?.removeEventListener('abort', abort) + } const finish = (result: Omit): void => { if (settled) { return } - settled = true - if (forceKillTimer) { - clearTimeout(forceKillTimer) - } - args.signal?.removeEventListener('abort', abort) + settle() resolve({ stdout: takeRetainedTail(stdout), stderr: takeRetainedTail(stderr), ...result }) } const fail = (error: Error): void => { if (settled) { return } - settled = true - if (forceKillTimer) { - clearTimeout(forceKillTimer) - } - args.signal?.removeEventListener('abort', abort) + settle() stdout.clear() stderr.clear() reject(error) } - const abort = (): void => { - if (settled) { + const stop = (reason: 'aborted' | 'timedOut'): void => { + if (settled || stopReason) { return } - aborted = true + stopReason = reason + clearTimeout(deadlineTimer) forceKillTimer = setTimeout(() => { if (settled) { return } killRecipeProcess(child, true) - finish({ exitCode: null, signal: null, aborted: true }) + finish({ exitCode: null, signal: null, ...stopFlag() }) child.stdin.destroy() child.stdout.destroy() child.stderr.destroy() @@ -104,6 +114,7 @@ export async function runRecipeCommand(args: { forceKillTimer.unref() killRecipeProcess(child) } + const abort = (): void => stop('aborted') // Keep retained output as raw bytes; StringDecoder matches setEncoding’s per-stream callback character boundaries. const stdoutDecoder = new StringDecoder('utf8') @@ -134,13 +145,17 @@ export async function runRecipeCommand(args: { fail(error) }) child.on('close', (exitCode, signal) => { - finish({ exitCode, signal, ...(aborted ? { aborted: true } : {}) }) + finish({ exitCode, signal, ...stopFlag() }) }) if (args.signal?.aborted) { abort() } else { args.signal?.addEventListener('abort', abort, { once: true }) + if (args.timeoutMs !== undefined && args.timeoutMs > 0) { + deadlineTimer = setTimeout(() => stop('timedOut'), args.timeoutMs) + deadlineTimer.unref() + } } if (args.stdin) { diff --git a/src/shared/ephemeral-vm-recipe-runner.ts b/src/shared/ephemeral-vm-recipe-runner.ts index ba3c9f82638..46aef359f0b 100644 --- a/src/shared/ephemeral-vm-recipe-runner.ts +++ b/src/shared/ephemeral-vm-recipe-runner.ts @@ -3,16 +3,10 @@ import { randomUUID } from 'node:crypto' import { statSync } from 'node:fs' import type { OrcaVmRecipe } from './orca-yaml-hook-types' import { parseEphemeralVmRecipeResult, type EphemeralVmRecipeResult } from './ephemeral-vm-recipes' -import { - getEphemeralVmRecipeCheckoutModeFailure, - getEphemeralVmRecipeResultSchemaVersion -} from './ephemeral-vm-recipe-checkout-mode' -import { runRecipeCommand } from './ephemeral-vm-recipe-process' -import { - ephemeralVmExitFailure, - pickEphemeralVmFailureCode, - type EphemeralVmFailure -} from './ephemeral-vm-failure-copy' +import { getEphemeralVmRecipeCheckoutModeFailure } from './ephemeral-vm-recipe-checkout-mode' +import { pickEphemeralVmFailureCode, type EphemeralVmFailure } from './ephemeral-vm-failure-copy' +import { getEphemeralVmRecipeTimeoutSeconds } from './ephemeral-vm-recipe-timeouts' +import { getRecipeStepFailure, runRecipeStep } from './ephemeral-vm-recipe-step' import { getEphemeralVmRecipeDestroyFailure } from './ephemeral-vm-recipe-destroy-result' import { buildEphemeralVmRecipeCleanupPayload, @@ -113,27 +107,11 @@ export async function runEphemeralVmRecipeStart( ): Promise { validateRepoPath(args.repoPath) const context = buildRecipeContext(args.recipe, args.repoPath, args.context) - const processResult = await runRecipeCommand({ - command: args.recipe.create, - repoPath: args.repoPath, - context, - mode: 'create', - resultSchemaVersion: getEphemeralVmRecipeResultSchemaVersion(args.recipe), - env: args.env, - maxCaptureBytes: args.maxCaptureBytes, - signal: args.signal, - onStdout: args.onStdout, - onStderr: args.onStderr, - spawnCommand: args.spawnCommand - }) + const processResult = await runRecipeStep(args, 'create', args.recipe.create, context) - if (processResult.exitCode !== 0) { - return { - ok: false, - context, - ...ephemeralVmExitFailure('recipe', processResult.exitCode), - ...processResult - } + const stepFailure = getRecipeStepFailure(args.recipe, 'create', processResult) + if (stepFailure) { + return { ok: false, context, ...stepFailure, ...processResult } } const parsed = parseEphemeralVmRecipeResult(processResult.stdout) @@ -175,22 +153,18 @@ export async function runEphemeralVmRecipeCleanup( } const payload = buildEphemeralVmRecipeCleanupPayload(args) - const processResult = await runRecipeCommand({ - command: args.recipe.destroy, - repoPath: args.repoPath, - context: args.context, - mode: 'destroy', - resultSchemaVersion: getEphemeralVmRecipeResultSchemaVersion(args.recipe), - stdin: `${JSON.stringify(payload)}\n`, - env: args.env, - maxCaptureBytes: args.maxCaptureBytes, - signal: args.signal, - onStdout: args.onStdout, - onStderr: args.onStderr, - spawnCommand: args.spawnCommand - }) + const processResult = await runRecipeStep( + args, + 'destroy', + args.recipe.destroy, + args.context, + `${JSON.stringify(payload)}\n` + ) - const failure = getEphemeralVmRecipeDestroyFailure(processResult) + const failure = getEphemeralVmRecipeDestroyFailure( + processResult, + getEphemeralVmRecipeTimeoutSeconds(args.recipe, 'destroy') ?? 0 + ) if (failure) { return failure } @@ -207,28 +181,17 @@ export async function runEphemeralVmRecipeSuspend( } const payload = buildEphemeralVmRecipeLifecyclePayload({ ...args, mode: 'suspend' }) - const processResult = await runRecipeCommand({ - command: args.recipe.suspend, - repoPath: args.repoPath, - context: args.context, - mode: 'suspend', - resultSchemaVersion: getEphemeralVmRecipeResultSchemaVersion(args.recipe), - stdin: `${JSON.stringify(payload)}\n`, - env: args.env, - maxCaptureBytes: args.maxCaptureBytes, - signal: args.signal, - onStdout: args.onStdout, - onStderr: args.onStderr, - spawnCommand: args.spawnCommand - }) + const processResult = await runRecipeStep( + args, + 'suspend', + args.recipe.suspend, + args.context, + `${JSON.stringify(payload)}\n` + ) - if (processResult.exitCode !== 0) { - return { - ok: false, - skipped: false, - error: `Suspend exited with code ${processResult.exitCode ?? 'unknown'}.`, - ...processResult - } + const stepFailure = getRecipeStepFailure(args.recipe, 'suspend', processResult) + if (stepFailure) { + return { ok: false, skipped: false, ...stepFailure, ...processResult } } return { ok: true, skipped: false, ...processResult } @@ -249,29 +212,17 @@ export async function runEphemeralVmRecipeResume( } const payload = buildEphemeralVmRecipeLifecyclePayload({ ...args, mode: 'resume' }) - const processResult = await runRecipeCommand({ - command: args.recipe.resume, - repoPath: args.repoPath, - context: args.context, - mode: 'resume', - resultSchemaVersion: getEphemeralVmRecipeResultSchemaVersion(args.recipe), - stdin: `${JSON.stringify(payload)}\n`, - env: args.env, - maxCaptureBytes: args.maxCaptureBytes, - signal: args.signal, - onStdout: args.onStdout, - onStderr: args.onStderr, - spawnCommand: args.spawnCommand - }) + const processResult = await runRecipeStep( + args, + 'resume', + args.recipe.resume, + args.context, + `${JSON.stringify(payload)}\n` + ) - if (processResult.exitCode !== 0) { - return { - ok: false, - skipped: false, - context: args.context, - error: `Resume exited with code ${processResult.exitCode ?? 'unknown'}.`, - ...processResult - } + const stepFailure = getRecipeStepFailure(args.recipe, 'resume', processResult) + if (stepFailure) { + return { ok: false, skipped: false, context: args.context, ...stepFailure, ...processResult } } const parsed = parseEphemeralVmRecipeResult(processResult.stdout) diff --git a/src/shared/ephemeral-vm-recipe-step.ts b/src/shared/ephemeral-vm-recipe-step.ts new file mode 100644 index 00000000000..d56d79991bf --- /dev/null +++ b/src/shared/ephemeral-vm-recipe-step.ts @@ -0,0 +1,67 @@ +import type { OrcaVmRecipe, OrcaVmRecipeLifecycleMode } from './orca-yaml-hook-types' +import type { + EphemeralVmRecipeContext, + EphemeralVmRecipeStartArgs +} from './ephemeral-vm-recipe-runner' +import { runRecipeCommand, type ProcessRunResult } from './ephemeral-vm-recipe-process' +import { getEphemeralVmRecipeResultSchemaVersion } from './ephemeral-vm-recipe-checkout-mode' +import { + ephemeralVmExitFailure, + ephemeralVmTimeoutFailure, + type EphemeralVmFailure +} from './ephemeral-vm-failure-copy' +import { getEphemeralVmRecipeTimeoutSeconds } from './ephemeral-vm-recipe-timeouts' + +type RecipeStepArgs = Pick< + EphemeralVmRecipeStartArgs, + | 'recipe' + | 'repoPath' + | 'env' + | 'maxCaptureBytes' + | 'signal' + | 'onStdout' + | 'onStderr' + | 'spawnCommand' +> + +export function runRecipeStep( + args: RecipeStepArgs, + mode: OrcaVmRecipeLifecycleMode, + command: string, + context: EphemeralVmRecipeContext, + stdin?: string +): Promise { + return runRecipeCommand({ + command, + repoPath: args.repoPath, + context, + mode, + resultSchemaVersion: getEphemeralVmRecipeResultSchemaVersion(args.recipe), + ...(stdin === undefined ? {} : { stdin }), + env: args.env, + maxCaptureBytes: args.maxCaptureBytes, + signal: args.signal, + timeoutMs: toTimeoutMs(getEphemeralVmRecipeTimeoutSeconds(args.recipe, mode)), + onStdout: args.onStdout, + onStderr: args.onStderr, + spawnCommand: args.spawnCommand + }) +} + +export function getRecipeStepFailure( + recipe: OrcaVmRecipe, + mode: 'create' | 'suspend' | 'resume', + result: ProcessRunResult +): EphemeralVmFailure | null { + if (result.timedOut) { + return ephemeralVmTimeoutFailure(mode, getEphemeralVmRecipeTimeoutSeconds(recipe, mode) ?? 0) + } + if (result.exitCode !== 0) { + return ephemeralVmExitFailure(mode === 'create' ? 'recipe' : mode, result.exitCode) + } + return null +} + +function toTimeoutMs(seconds: number | undefined): number | undefined { + return seconds === undefined ? undefined : seconds * 1000 +} diff --git a/src/shared/ephemeral-vm-recipe-timeouts.test.ts b/src/shared/ephemeral-vm-recipe-timeouts.test.ts new file mode 100644 index 00000000000..c618bf299c3 --- /dev/null +++ b/src/shared/ephemeral-vm-recipe-timeouts.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest' +import { + formatEphemeralVmRecipeTimeout, + getEphemeralVmRecipeTimeoutSeconds, + parseEphemeralVmRecipeTimeoutSeconds, + toEphemeralVmRuntimeRecipeSnapshot +} from './ephemeral-vm-recipe-timeouts' +import { ephemeralVmTimeoutFailure } from './ephemeral-vm-failure-copy' +import type { OrcaVmRecipe } from './orca-yaml-hook-types' +import { parseOrcaYaml } from './orca-yaml' + +describe('ephemeral VM recipe timeouts', () => { + it('applies no limit unless the recipe sets one', () => { + const recipe: OrcaVmRecipe = { id: 'r', name: 'R', create: './create.sh' } + for (const mode of ['create', 'suspend', 'resume', 'destroy'] as const) { + expect(getEphemeralVmRecipeTimeoutSeconds(recipe, mode)).toBeUndefined() + } + expect( + getEphemeralVmRecipeTimeoutSeconds({ ...recipe, timeoutSeconds: { create: 90 } }, 'create') + ).toBe(90) + expect( + getEphemeralVmRecipeTimeoutSeconds({ ...recipe, timeoutSeconds: { create: 90 } }, 'destroy') + ).toBeUndefined() + }) + + it('rejects values that are not whole seconds in range', () => { + for (const value of [0, -1, 1.5, 86_401, '60', [60], { create: '60' }, { create: 0 }]) { + expect(parseEphemeralVmRecipeTimeoutSeconds(value).ok).toBe(false) + } + expect(parseEphemeralVmRecipeTimeoutSeconds({})).toEqual({ ok: true }) + expect(parseEphemeralVmRecipeTimeoutSeconds(86_400)).toMatchObject({ ok: true }) + }) + + it('formats the limit compactly', () => { + expect(formatEphemeralVmRecipeTimeout(45)).toBe('45s') + expect(formatEphemeralVmRecipeTimeout(900)).toBe('15m') + expect(formatEphemeralVmRecipeTimeout(5_400)).toBe('1h 30m') + }) + + it('tells the user which step stopped and how to raise the limit', () => { + expect(ephemeralVmTimeoutFailure('create', 1_800)).toEqual({ + error: + 'The recipe create step did not finish within 30m, so Orca stopped it. Check the recipe output, or raise timeoutSeconds in orca.yaml if it needs longer.', + errorCode: 'recipeTimedOut', + errorParams: { mode: 'create', timeout: '30m', timeoutSeconds: 1_800 } + }) + }) + + it('drops timeoutSeconds from the persisted recipe snapshot', () => { + const snapshot = toEphemeralVmRuntimeRecipeSnapshot({ + id: 'r', + name: 'R', + create: './create.sh', + destroy: './destroy.sh', + timeoutSeconds: { create: 60 } + }) + expect(snapshot).toEqual({ id: 'r', name: 'R', create: './create.sh', destroy: './destroy.sh' }) + }) +}) + +describe('orca.yaml recipe timeoutSeconds', () => { + it('parses recipe timeoutSeconds as one limit or a per-step map', () => { + const yaml = [ + 'environmentRecipes:', + ' - id: all-steps', + ' name: All Steps', + ' create: ./create.sh', + ' timeoutSeconds: 120', + ' - id: per-step', + ' name: Per Step', + ' create: ./create.sh', + ' timeoutSeconds:', + ' create: 1800', + ' destroy: 60' + ].join('\n') + + expect(parseOrcaYaml(yaml)?.environmentRecipes).toEqual([ + { + id: 'all-steps', + name: 'All Steps', + create: './create.sh', + timeoutSeconds: { create: 120, suspend: 120, resume: 120, destroy: 120 } + }, + { + id: 'per-step', + name: 'Per Step', + create: './create.sh', + timeoutSeconds: { create: 1800, destroy: 60 } + } + ]) + }) + + it('keeps a recipe with an invalid timeoutSeconds without limits and reports it', () => { + const yaml = [ + 'environmentRecipes:', + ' - id: cloud-sandbox', + ' name: Cloud Sandbox', + ' create: ./create.sh', + ' timeoutSeconds:', + ' boot: 60' + ].join('\n') + + expect(parseOrcaYaml(yaml)).toEqual({ + scripts: {}, + environmentRecipes: [{ id: 'cloud-sandbox', name: 'Cloud Sandbox', create: './create.sh' }], + environmentRecipeDiagnostics: [ + { + index: 0, + field: 'timeoutSeconds', + message: + 'Recipe "cloud-sandbox" timeoutSeconds.boot is not a lifecycle step; use create, suspend, resume, or destroy. Steps keep no time limit.' + } + ] + }) + }) +}) diff --git a/src/shared/ephemeral-vm-recipe-timeouts.ts b/src/shared/ephemeral-vm-recipe-timeouts.ts new file mode 100644 index 00000000000..344c256f1b6 --- /dev/null +++ b/src/shared/ephemeral-vm-recipe-timeouts.ts @@ -0,0 +1,102 @@ +import type { + OrcaVmRecipe, + OrcaVmRecipeLifecycleMode, + OrcaVmRecipeTimeoutSeconds +} from './orca-yaml-hook-types' + +const LIFECYCLE_MODES: readonly OrcaVmRecipeLifecycleMode[] = [ + 'create', + 'suspend', + 'resume', + 'destroy' +] + +// No default limit: a step only times out when its recipe sets timeoutSeconds, so recipes that +// work today (including legitimately slow image builds) never start failing. Create and destroy +// already have a user-facing cancel. +// Bounds typos (e.g. milliseconds) while still allowing slow image builds. +export const MAX_EPHEMERAL_VM_RECIPE_TIMEOUT_SECONDS = 24 * 60 * 60 + +export function getEphemeralVmRecipeTimeoutSeconds( + recipe: Pick, + mode: OrcaVmRecipeLifecycleMode +): number | undefined { + return recipe.timeoutSeconds?.[mode] +} + +/** Runtime records keep a recipe snapshot under a strict schema that current and older builds + * share, so the snapshot never carries timeoutSeconds; lifecycle calls re-read the limit from + * the repo's orca.yaml instead (see getRuntimeRecipeContext). */ +export function toEphemeralVmRuntimeRecipeSnapshot( + recipe: OrcaVmRecipe +): Omit { + const { timeoutSeconds: _timeoutSeconds, ...snapshot } = recipe + return snapshot +} + +/** "15m", "1h 30m", "45s": compact enough to read the same in every locale. */ +export function formatEphemeralVmRecipeTimeout(seconds: number): string { + const hours = Math.floor(seconds / 3600) + const minutes = Math.floor((seconds % 3600) / 60) + const rest = seconds % 60 + const parts = [ + hours > 0 ? `${hours}h` : null, + minutes > 0 ? `${minutes}m` : null, + rest > 0 || seconds === 0 ? `${rest}s` : null + ] + return parts.filter((part): part is string => part !== null).join(' ') +} + +export type EphemeralVmRecipeTimeoutParse = + | { ok: true; timeoutSeconds?: OrcaVmRecipeTimeoutSeconds } + | { ok: false; message: string } + +/** Accepts one number for every mode, or a map keyed by create/suspend/resume/destroy. */ +export function parseEphemeralVmRecipeTimeoutSeconds( + value: unknown +): EphemeralVmRecipeTimeoutParse { + if (value === undefined || value === null) { + return { ok: true } + } + if (typeof value === 'number') { + if (!isValidTimeoutSeconds(value)) { + return { ok: false, message: invalidSecondsMessage('timeoutSeconds') } + } + return { + ok: true, + timeoutSeconds: Object.fromEntries(LIFECYCLE_MODES.map((mode) => [mode, value])) + } + } + if (typeof value !== 'object' || Array.isArray(value)) { + return { + ok: false, + message: 'timeoutSeconds must be a number or a map of create/suspend/resume/destroy.' + } + } + const timeoutSeconds: OrcaVmRecipeTimeoutSeconds = {} + for (const [key, seconds] of Object.entries(value)) { + if (!isLifecycleMode(key)) { + return { + ok: false, + message: `timeoutSeconds.${key} is not a lifecycle step; use create, suspend, resume, or destroy.` + } + } + if (typeof seconds !== 'number' || !isValidTimeoutSeconds(seconds)) { + return { ok: false, message: invalidSecondsMessage(`timeoutSeconds.${key}`) } + } + timeoutSeconds[key] = seconds + } + return Object.keys(timeoutSeconds).length > 0 ? { ok: true, timeoutSeconds } : { ok: true } +} + +function isLifecycleMode(value: string): value is OrcaVmRecipeLifecycleMode { + return LIFECYCLE_MODES.some((mode) => mode === value) +} + +function isValidTimeoutSeconds(value: number): boolean { + return Number.isInteger(value) && value >= 1 && value <= MAX_EPHEMERAL_VM_RECIPE_TIMEOUT_SECONDS +} + +function invalidSecondsMessage(field: string): string { + return `${field} must be a whole number of seconds from 1 to ${MAX_EPHEMERAL_VM_RECIPE_TIMEOUT_SECONDS}.` +} diff --git a/src/shared/native-chat/native-chat-fork-offer.ts b/src/shared/native-chat/native-chat-fork-offer.ts index 7691ae64de1..7cd0f25f753 100644 --- a/src/shared/native-chat/native-chat-fork-offer.ts +++ b/src/shared/native-chat/native-chat-fork-offer.ts @@ -4,21 +4,30 @@ import type { AgentSessionCapabilities } from '../agent-session/agent-session-ca import type { StructuredAgentSessionHostCapabilityState } from '../agent-session/structured-agent-session-host-capability' import { isRootAgentJournalItem } from '../agent-session/journal/agent-session-journal-producer' import type { AgentJournalRenderItem } from '../agent-session/journal/agent-session-journal-types' +import { projectStructuredAgentSessionMessages } from '../agent-session/view/structured-agent-session-message-projection' +import type { NativeChatTurnJournal } from './transcript/native-chat-turn-membership' import type { AgentSessionOptionsResult } from '../agent-session/options/agent-session-options-result' +import { AGENT_SESSION_FORKED_FROM_PRESENTATION } from '../agent-session/agent-session-fork' +import { nativeChatTurnMembership } from './transcript/native-chat-turn-membership' import type { NativeChatMessage } from './native-chat-types' /** What a chat can fork: nothing, not yet known (drawn disabled), or through which turns. */ export type NativeChatForkSupport = | { kind: 'none' } | { kind: 'unknown' } - | { kind: 'known'; fork: NonNullable } + | { + kind: 'known' + fork: NonNullable + inheritedOriginal?: boolean + } /** `agent` is the host's registered row for the chat's agent: undefined until the host has listed it. * `session` is the chat's options answer about its installed agent; absent until that read lands. */ export function nativeChatForkSupport( host: StructuredAgentSessionHostCapabilityState, agent: { capabilities: Pick } | undefined, - session: AgentSessionOptionsResult['forkSupport'] + session: AgentSessionOptionsResult['forkSupport'], + inheritedOriginal: StructuredAgentSessionHostCapabilityState = 'unknown' ): NativeChatForkSupport { const fork = agent?.capabilities.fork if ( @@ -29,25 +38,33 @@ export function nativeChatForkSupport( return { kind: 'none' } } return host === 'supported' && fork && session === 'supported' - ? { kind: 'known', fork } + ? { kind: 'known', fork, inheritedOriginal: inheritedOriginal === 'supported' } : { kind: 'unknown' } } /** The journal rows a fork can go through: the chat's own agent's messages. A displayed row that only * reads as a response (a tool call, or a status projected as a plan) maps to none of them. */ -export function nativeChatForkableItemIds( - items: readonly Pick[] -): ReadonlySet { - return new Set( - items - .filter( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - isRootAgentJournalItem(item) - ) - .map((item) => item.itemId) - ) +export function nativeChatForkInventory( + items: readonly Pick[] +): { forkableItemIds: ReadonlySet; inheritedThroughSequence: number } { + const forkableItemIds = new Set() + let inheritedThroughSequence = 0 + for (const item of items) { + if ( + item.body.kind === 'status' && + item.body.presentation === AGENT_SESSION_FORKED_FROM_PRESENTATION + ) { + inheritedThroughSequence = item.sequence + } + if ( + item.body.kind === 'message' && + item.body.role === 'assistant' && + isRootAgentJournalItem(item) + ) { + forkableItemIds.add(item.itemId) + } + } + return { forkableItemIds, inheritedThroughSequence } } /** The response `/fork` copies through: the chat's newest forkable one still in its current context. */ @@ -84,6 +101,7 @@ export function nativeChatRowOffersFork( support: NativeChatForkSupport contextFloorSequence: number forkableItemIds: ReadonlySet + inheritedThroughSequence?: number } ): boolean { const { message } = row @@ -100,6 +118,33 @@ export function nativeChatRowOffersFork( // Rows above a /clear are no longer in the agent's context. sequence !== undefined && sequence > chat.contextFloorSequence && - (chat.support.kind === 'unknown' || chat.support.fork === 'checkpoint' || row.inLatestTurn) + (chat.support.kind === 'unknown' || + chat.support.fork === 'checkpoint' || + row.inLatestTurn || + (chat.support.inheritedOriginal === true && sequence <= (chat.inheritedThroughSequence ?? 0))) + ) +} + +/** Nonlatest copied replies of tip-only agents need the host's original-resolution extension. */ +export function nativeChatForkRequiresInheritedOriginal( + items: readonly AgentJournalRenderItem[], + fork: 'tip' | 'checkpoint', + throughItemId: string, + journal: Omit = { submissions: [] } +): boolean { + if (fork !== 'tip') { + return false + } + const selected = items.find((item) => item.itemId === throughItemId) + if (!selected || selected.sequence > nativeChatForkInventory(items).inheritedThroughSequence) { + return false + } + const messages = projectStructuredAgentSessionMessages(items, [], journal.submissions).filter( + isRootAgentJournalItem + ) + const { turnKeys } = nativeChatTurnMembership(messages, { ...journal, items }) + const selectedTurn = turnKeys[messages.findIndex((message) => message.id === throughItemId)] + return ( + selectedTurn === undefined || selectedTurn !== turnKeys.findLast((key) => key !== undefined) ) } diff --git a/src/shared/native-chat/transcript/native-chat-message-time.test.ts b/src/shared/native-chat/transcript/native-chat-message-time.test.ts deleted file mode 100644 index d4978e2e962..00000000000 --- a/src/shared/native-chat/transcript/native-chat-message-time.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getNativeChatMessageTimeFormatter } from './native-chat-message-time' - -describe('native chat message time', () => { - it('includes the local date outside today and the year outside this year', () => { - const formatter = getNativeChatMessageTimeFormatter('en-US') - const now = new Date(2026, 10, 8, 0, 15) - - expect(formatter.format(new Date(2026, 10, 8, 0, 5), now)).toBe('12:05 AM') - expect(formatter.format(new Date(2026, 10, 7, 23, 42), now)).toMatch(/^Nov 7\b/) - expect(formatter.format(new Date(2025, 10, 7, 23, 42), now)).toMatch(/^Nov 7, 2025\b/) - }) -}) diff --git a/src/shared/orca-yaml-hook-types.ts b/src/shared/orca-yaml-hook-types.ts index 76c26ec6352..6206a270540 100644 --- a/src/shared/orca-yaml-hook-types.ts +++ b/src/shared/orca-yaml-hook-types.ts @@ -38,8 +38,14 @@ export type OrcaVmRecipe = { resume?: string destroy?: string destroyDisabled?: boolean + // Per-mode wall-clock limits; orca.yaml accepts one number for every mode or a per-mode map. + timeoutSeconds?: OrcaVmRecipeTimeoutSeconds } +export type OrcaVmRecipeLifecycleMode = 'create' | 'suspend' | 'resume' | 'destroy' + +export type OrcaVmRecipeTimeoutSeconds = Partial> + export type OrcaVmRecipeDiagnostic = { index: number field?: string diff --git a/src/shared/orca-yaml.ts b/src/shared/orca-yaml.ts index debf2584b4d..63c854f85b6 100644 --- a/src/shared/orca-yaml.ts +++ b/src/shared/orca-yaml.ts @@ -12,6 +12,7 @@ import { MAX_ORCA_YAML_ALIAS_COUNT, MAX_ORCA_YAML_COLLECTION_ENTRIES } from './orca-yaml-file-limit' +import { parseEphemeralVmRecipeTimeoutSeconds } from './ephemeral-vm-recipe-timeouts' function asRecord(value: unknown): Record | null { return value !== null && typeof value === 'object' && !Array.isArray(value) @@ -172,6 +173,15 @@ function normalizeVmRecipes(value: unknown): VmRecipeParseResult { const resume = asTrimmedString(record.resume) const destroyValue = asTrimmedString(record.destroy) ?? asTrimmedString(record.cleanup) const destroyDisabled = destroyValue === 'none' + const timeouts = parseEphemeralVmRecipeTimeoutSeconds(record.timeoutSeconds) + if (!timeouts.ok) { + // A bad limit should not hide the recipe; its steps stay unlimited. + diagnostics.push({ + index, + field: 'timeoutSeconds', + message: `Recipe "${id}" ${timeouts.message} Steps keep no time limit.` + }) + } return { id, name, @@ -181,7 +191,10 @@ function normalizeVmRecipes(value: unknown): VmRecipeParseResult { ...(suspend ? { suspend } : {}), ...(resume ? { resume } : {}), ...(destroyValue && !destroyDisabled ? { destroy: destroyValue } : {}), - ...(destroyDisabled ? { destroyDisabled: true } : {}) + ...(destroyDisabled ? { destroyDisabled: true } : {}), + ...(timeouts.ok && timeouts.timeoutSeconds + ? { timeoutSeconds: timeouts.timeoutSeconds } + : {}) } }) .filter((entry): entry is OrcaVmRecipe => entry !== null) diff --git a/src/shared/orchestration/fleet/orchestration-fleet-projection.ts b/src/shared/orchestration/fleet/orchestration-fleet-projection.ts index c6d1a87dcab..51a38821998 100644 --- a/src/shared/orchestration/fleet/orchestration-fleet-projection.ts +++ b/src/shared/orchestration/fleet/orchestration-fleet-projection.ts @@ -71,9 +71,18 @@ export type FleetLiveness = /** The Dispatch settled with no worker row, so no process was ever supervised. */ | 'unsupervised_settled' observedAt?: number + /** What the host could not verify, when it said. */ + detail?: string } | { verdict: 'exited'; source: 'resource_release' | 'worker_stop' | 'execution_host' } +/** The structured host's verdict on a chat-mode worker, which has no terminal hook stream. */ +export type FleetSessionObservation = + /** `activity` is the session's own status row: its turn state and when it last changed. */ + | { status: 'live'; activity?: FleetAgentStatusEvidence } + | { status: 'exited' } + | { status: 'unverifiable'; detail: string } + export type FleetResourceProjection = | { state: 'owned' | 'transferred' | 'user_owned' | 'external' | 'released' @@ -148,6 +157,8 @@ export function refreshOrchestrationFleetLivenessAttention(worker: Orchestration export function projectOrchestrationFleet(args: { workers: readonly FleetDurableWorker[] statuses: readonly FleetAgentStatusEvidence[] + /** Chat-mode workers' host verdicts; undefined selects the terminal path. */ + observeSession?: (worker: FleetDurableWorker) => FleetSessionObservation | undefined now?: number cursor?: string limit?: number @@ -164,7 +175,12 @@ export function projectOrchestrationFleet(args: { const statusIndex = createFleetStatusIndex(args.statuses, rows) const now = args.now ?? Date.now() const workers = rows.map((worker) => - projectOrchestrationFleetWorker(worker, statusForFleetWorker(worker, statusIndex), now) + projectOrchestrationFleetWorker( + worker, + statusForFleetWorker(worker, statusIndex), + now, + args.observeSession?.(worker) + ) ) const hasMore = start + workers.length < args.workers.length return { diff --git a/src/shared/orchestration/fleet/orchestration-fleet-worker-projection.ts b/src/shared/orchestration/fleet/orchestration-fleet-worker-projection.ts index f293b44ab34..b33211dc61e 100644 --- a/src/shared/orchestration/fleet/orchestration-fleet-worker-projection.ts +++ b/src/shared/orchestration/fleet/orchestration-fleet-worker-projection.ts @@ -11,6 +11,7 @@ import type { FleetLiveness, FleetNextAction, FleetResourceProjection, + FleetSessionObservation, OrchestrationFleetWorker } from './orchestration-fleet-projection' @@ -53,7 +54,8 @@ function hasCertifiedExit(worker: FleetLivenessSubject): boolean { export function projectLiveness( worker: FleetLivenessSubject, evidence: FleetAgentStatusEvidence | undefined, - now: number + now: number, + session?: FleetSessionObservation ): FleetLiveness { // Federated release proves terminal exit, independently of the worker outcome. if (worker.workerStage === DURABLE_EXIT_PROOF.workerStage) { @@ -69,6 +71,17 @@ export function projectLiveness( if (hasCertifiedExit(worker)) { return { verdict: 'exited', source: 'execution_host' } } + // Chat-mode workers have no hook stream; the structured host's own verdict is their liveness. + if (session) { + switch (session.status) { + case 'live': + return { verdict: 'live', observedAt: now, source: 'execution_host' } + case 'exited': + return { verdict: 'exited', source: 'execution_host' } + case 'unverifiable': + return { verdict: 'unverifiable', reason: 'host_unavailable', detail: session.detail } + } + } // Settled unsupervised dispatches have no process to miss, but absence still cannot certify exit. if (!evidence && isUnsupervisedSettledDispatch(worker)) { return { verdict: 'unverifiable', reason: 'unsupervised_settled' } @@ -99,6 +112,14 @@ export function projectLiveness( return { verdict: 'live', observedAt, source: 'agent_status' } } +/** A live chat-mode session's own status row, whatever its age; age dates activity, not liveness. */ +export function sessionActivityEvidence( + session: FleetSessionObservation +): FleetAgentStatusEvidence | undefined { + const activity = session.status === 'live' ? session.activity : undefined + return activity && !activity.activity.restoredUnconfirmed ? activity : undefined +} + function projectResource(worker: FleetDurableWorker): FleetResourceProjection { const resource = worker.resource if (!resource) { @@ -211,11 +232,14 @@ function projectHost( export function projectOrchestrationFleetWorker( worker: FleetDurableWorker, - evidence: FleetAgentStatusEvidence | undefined, - now: number + hookEvidence: FleetAgentStatusEvidence | undefined, + now: number, + session?: FleetSessionObservation ): OrchestrationFleetWorker { - const liveness = projectLiveness(worker, evidence, now) - const fresh = liveness.verdict === 'live' + const liveness = projectLiveness(worker, hookEvidence, now, session) + // A live session's own status row dates its last activity; its age never makes the worker stale. + const evidence = session ? sessionActivityEvidence(session) : hookEvidence + const fresh = liveness.verdict === 'live' && Boolean(evidence) const activity = evidence?.activity const workspaceId = activity?.worktreeId ?? worker.worktreeId ?? worker.resource?.worktreeId ?? null @@ -244,13 +268,17 @@ export function projectOrchestrationFleetWorker( liveness, evidence: { durable: true, - liveStatus: !evidence - ? 'unavailable' - : evidence.activity.restoredUnconfirmed - ? 'redacted_restore' - : fresh - ? 'fresh' - : 'stale', + liveStatus: session + ? liveness.verdict === 'live' + ? 'fresh' + : 'unavailable' + : !evidence + ? 'unavailable' + : evidence.activity.restoredUnconfirmed + ? 'redacted_restore' + : fresh + ? 'fresh' + : 'stale', lastObservedAt: evidence ? evidence.clock.at : null }, resource: projectResource(worker), diff --git a/src/shared/plugins/languages/protected-copy-keys.json b/src/shared/plugins/languages/protected-copy-keys.json index 0c5cd6391dc..4312ab3e4c9 100644 --- a/src/shared/plugins/languages/protected-copy-keys.json +++ b/src/shared/plugins/languages/protected-copy-keys.json @@ -1019,6 +1019,15 @@ "workspaceDeletion.moreActions", "workspaceDeletion.moreDeleteOptions", "workspaceDeletion.preferenceSaveFailed", + "worktree.delete.childrenCannotBeKeptTitle", + "worktree.delete.childrenChanged", + "worktree.delete.childrenChangedClearPreserve", + "worktree.delete.childrenPreservedDescription", + "worktree.delete.childrenPreservedTitle", + "worktree.delete.detachChildren", + "worktree.delete.detachFailed", + "worktree.delete.detachingChildren", + "worktree.delete.nestedChildrenCannotBeKept", "worktree.nestedRemoval.cancel", "worktree.nestedRemoval.confirm", "worktree.nestedRemoval.deleting", diff --git a/src/shared/remote-runtime/control/remote-runtime-shared-control-test-server.ts b/src/shared/remote-runtime/control/remote-runtime-shared-control-test-server.ts index cb4515dd6c0..412a1e42b5e 100644 --- a/src/shared/remote-runtime/control/remote-runtime-shared-control-test-server.ts +++ b/src/shared/remote-runtime/control/remote-runtime-shared-control-test-server.ts @@ -26,6 +26,7 @@ export type SharedControlTestServer = { } type ServerOptions = { + onClientClose?: () => void resultForRequest?: (method: string) => unknown delaySubscriptionReady?: boolean sendKeepaliveBeforeResponse?: boolean @@ -78,6 +79,9 @@ export async function createSharedControlTestServer( servers.push(wss) wss.on('connection', (ws) => { + if (options.onClientClose) { + ws.once('close', options.onClientClose) + } let sharedKey: Uint8Array | null = null let authenticated = false ws.on('message', (data, isBinary) => { diff --git a/src/shared/remote-runtime/host-catalog/runtime-environment-host-key-match.ts b/src/shared/remote-runtime/host-catalog/runtime-environment-host-key-match.ts index 16fdd759b7d..3db212001a8 100644 --- a/src/shared/remote-runtime/host-catalog/runtime-environment-host-key-match.ts +++ b/src/shared/remote-runtime/host-catalog/runtime-environment-host-key-match.ts @@ -12,6 +12,10 @@ export function findEnvironmentWithHostKey -function preferredEndpoint(environment: PreferredEndpointSource) { +export function preferredEndpoint(environment: PreferredEndpointSource) { const endpoint = environment.endpoints.find((entry) => entry.id === environment.preferredEndpointId) ?? environment.endpoints[0] diff --git a/src/shared/remote-runtime/host-store/runtime-environment-resume-pairing.ts b/src/shared/remote-runtime/host-store/runtime-environment-resume-pairing.ts new file mode 100644 index 00000000000..e88fff42b6e --- /dev/null +++ b/src/shared/remote-runtime/host-store/runtime-environment-resume-pairing.ts @@ -0,0 +1,97 @@ +import { + preferredEndpoint, + type KnownRuntimeEnvironment +} from '../host-catalog/runtime-environments' +import type { PairingOffer } from '../pairing/mobile-relay-pairing-offer' +import { + sameHostKeyB64, + savedHostKeySpelling +} from '../host-catalog/runtime-environment-host-key-match' +import { + readEnvironmentStore, + readPersistedEnvironmentStore, + writeEnvironmentStore +} from './runtime-environment-store-file' +import { assertNoIndependentSshAccess } from './runtime-environment-pairing-replace-guards' +import { + getPairingConnectionDependency, + parseRemotePairingCode, + replaceEnvironmentPairing, + resolveEnvironmentFromStore +} from './runtime-environment-store' + +export type ResumePairingRefreshOutcome = { + environment: KnownRuntimeEnvironment + /** The saved device token was kept because the resumed server kept its host key. */ + reusedPairing: boolean + endpointChanged: boolean + /** Adopts the resume's fresh pairing instead, for a saved token the server turns out to reject. */ + repairFromFreshOffer: () => KnownRuntimeEnvironment +} + +/** + * Applies a resumed VM's pairing code. Why: the code's token is a fresh pending offer; adopting + * it on every resume uses it up, so the server mints another device row on its next boot. Same + * host key means the same server state, so the saved token still authenticates. + */ +export function refreshEnvironmentFromResumePairingCode( + userDataPath: string, + selector: string, + args: { pairingCode: string; now?: number } +): ResumePairingRefreshOutcome { + const offer = parseRemotePairingCode(userDataPath, args.pairingCode) + const current = resolveEnvironmentFromStore(readEnvironmentStore(userDataPath), selector) + assertNoIndependentSshAccess(current) + const store = readPersistedEnvironmentStore(userDataPath) + const persisted = resolveEnvironmentFromStore(store, current.id) + const preferred = preferredEndpoint(persisted) + const now = args.now ?? Date.now() + const repairWith = (next: PairingOffer) => () => + replaceEnvironmentPairing(userDataPath, current.id, next, { + now, + connectionDependency: current.connectionDependency + }) + if (!sameHostKeyB64(preferred.publicKeyB64, offer.publicKeyB64)) { + // A new identity (rebuilt VM, cleared state) can only be authenticated by its fresh pairing. + const environment = repairWith(offer)() + return { + environment, + reusedPairing: false, + endpointChanged: true, + repairFromFreshOffer: () => environment + } + } + // Retain the saved key spelling: the fingerprint hashes its text. + const repairFromFreshOffer = repairWith({ + ...offer, + publicKeyB64: savedHostKeySpelling(persisted, offer) + }) + if (preferred.endpoint === offer.endpoint) { + return { + environment: current, + reusedPairing: true, + endpointChanged: false, + repairFromFreshOffer + } + } + // Why no pairingRevision bump: the credential is unchanged, so clients holding it stay valid. + const { connectionDependency: _previousDependency, ...rest } = persisted + const next = { + ...rest, + ...getPairingConnectionDependency(current.connectionDependency, offer), + updatedAt: now, + endpoints: persisted.endpoints.map((entry) => + entry.id === preferred.id ? { ...entry, endpoint: offer.endpoint } : entry + ) + } + writeEnvironmentStore(userDataPath, { + version: 1, + environments: store.environments.map((entry) => (entry.id === persisted.id ? next : entry)) + }) + return { + environment: resolveEnvironmentFromStore(readEnvironmentStore(userDataPath), current.id), + reusedPairing: true, + endpointChanged: true, + repairFromFreshOffer + } +} diff --git a/src/shared/remote-runtime/host-store/runtime-environment-store.ts b/src/shared/remote-runtime/host-store/runtime-environment-store.ts index dc225afe576..4c6f35bd1f0 100644 --- a/src/shared/remote-runtime/host-store/runtime-environment-store.ts +++ b/src/shared/remote-runtime/host-store/runtime-environment-store.ts @@ -119,7 +119,7 @@ function saveEnvironmentFromPairingCode( return { environment, updatedExisting: false } } -function parseRemotePairingCode(userDataPath: string, pairingCode: string): PairingOffer { +export function parseRemotePairingCode(userDataPath: string, pairingCode: string): PairingOffer { const offer = parsePairingCode(pairingCode) if (!offer) { throw remoteServerPairingStoreError('invalidPairingCode') @@ -159,7 +159,7 @@ export function updateEnvironmentFromPairingCode( } /** Swaps a saved server's pairing in place, keeping its id, name and history. */ -function replaceEnvironmentPairing( +export function replaceEnvironmentPairing( userDataPath: string, selector: string, offer: PairingOffer, @@ -193,7 +193,7 @@ function replaceEnvironmentPairing( return next } -function getPairingConnectionDependency( +export function getPairingConnectionDependency( dependency: 'ssh-tunnel' | undefined, offer: PairingOffer ): { connectionDependency?: 'ssh-tunnel' } { diff --git a/tests/e2e/cross-version-wire/cross-version-pairing-ticket.unit.test.ts b/tests/e2e/cross-version-wire/cross-version-pairing-ticket.unit.test.ts index abe951db5c2..ebf7622a58d 100644 --- a/tests/e2e/cross-version-wire/cross-version-pairing-ticket.unit.test.ts +++ b/tests/e2e/cross-version-wire/cross-version-pairing-ticket.unit.test.ts @@ -10,12 +10,14 @@ import '../../../src/shared/remote-runtime/pairing/remote-pairing-ticket-exchang import { importReleaseCheckoutModule, materializeReleaseCheckout, + releaseModuleExport, resolveBaselineReleaseRef } from './release-checkout' // Single-use pairing must survive a downgrade, accept rows an older host made, and stay invisible to old clients. const SUITE_TIMEOUT_MS = 180_000 const EXCHANGED = 'e'.repeat(48) +const PRE_TICKET_RELEASE_REF = 'v1.4.253' type ReleasedRegistryLike = { addDevice(name: string, scope: 'mobile' | 'runtime'): { deviceId: string; token: string } @@ -24,15 +26,25 @@ type ReleasedRegistryLike = { } let ReleasedRegistry: new (userDataPath: string) => ReleasedRegistryLike +let PreTicketRegistry: typeof ReleasedRegistry beforeAll(async () => { - const checkout = await materializeReleaseCheckout(resolveBaselineReleaseRef()) - const registryModule = await importReleaseCheckoutModule( - checkout, - 'src/main/runtime/rpc/server/pairing/device-registry.ts' + const [checkout, preTicketCheckout] = await Promise.all([ + materializeReleaseCheckout(resolveBaselineReleaseRef()), + materializeReleaseCheckout(PRE_TICKET_RELEASE_REF) + ]) + const [registryModule, preTicketModule] = await Promise.all([ + importReleaseCheckoutModule(checkout, 'src/main/runtime/rpc/server/pairing/device-registry.ts'), + importReleaseCheckoutModule( + preTicketCheckout, + 'src/main/runtime/rpc/server/pairing/device-registry.ts' + ) + ]) + ReleasedRegistry = releaseModuleExport(registryModule, 'DeviceRegistry') + PreTicketRegistry = releaseModuleExport( + preTicketModule, + 'DeviceRegistry' ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pinned release's DeviceRegistry class; a changed shape fails the assertions below. - ReleasedRegistry = registryModule.DeviceRegistry as typeof ReleasedRegistry }, SUITE_TIMEOUT_MS) function pairedTicket(registry: DeviceRegistry, name: string) { @@ -64,7 +76,7 @@ describe('cross-version: single-use pairing tickets', () => { it('rows an older host minted keep working and are never treated as single-use', () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-xv-ticket-')) - const released = new ReleasedRegistry(userDataPath) + const released = new PreTicketRegistry(userDataPath) const phone = released.addDevice('Phone', 'mobile') released.updateLastSeen(phone.deviceId) diff --git a/tests/e2e/cross-version-wire/release-module-locations.ts b/tests/e2e/cross-version-wire/release-module-locations.ts index 8cd4aa9fabf..2ef48e52e16 100644 --- a/tests/e2e/cross-version-wire/release-module-locations.ts +++ b/tests/e2e/cross-version-wire/release-module-locations.ts @@ -55,5 +55,18 @@ export function releaseModuleLocation( } const name = posix.basename(named) const moved = tree.list(sourceRoot).filter((path) => posix.basename(path) === name) - return moved.length === 1 ? moved[0]! : named + if (moved.length === 1) { + return moved[0]! + } + if ( + moved.length === 0 && + named === + 'src/renderer/src/runtime/hosted-terminals/streams/registry/remote-runtime-terminal-multiplexer-registry.ts' + ) { + const legacyRegistry = 'src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts' + if (tree.exists(legacyRegistry)) { + return legacyRegistry + } + } + return named } diff --git a/tests/e2e/cross-version-wire/versioned-terminal-wire.ts b/tests/e2e/cross-version-wire/versioned-terminal-wire.ts index c6dd1499234..aa62e24a840 100644 --- a/tests/e2e/cross-version-wire/versioned-terminal-wire.ts +++ b/tests/e2e/cross-version-wire/versioned-terminal-wire.ts @@ -119,7 +119,7 @@ async function loadReleaseBuild(checkout: ReleaseCheckout): Promise { - const saved = parseIpynb(await readFile(filePath, 'utf8')) + // Saves overwrite in place, so a read can land mid-write; expect.poll aborts on a throw. + let saved: ReturnType + try { + saved = parseIpynb(await readFile(filePath, 'utf8')) + } catch (error) { + if (error instanceof SyntaxError) { + return null + } + throw error + } return saved.cells.map(({ id, source }) => ({ id, source })) }) .toEqual(reload === 'source' ? [editedFirst, updatedSecond] : [updatedSecond, editedFirst])