diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index cd3ba1dfa3a..2af8bb94c6f 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -31,7 +31,6 @@ on: - 'src/main/usage/jsonl-file-reader.test.ts' - 'src/main/usage/jsonl-file-snapshot.test.ts' - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' - - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' diff --git a/config/mobile-ci.vitest.config.mjs b/config/mobile-ci.vitest.config.mjs index 23b80145a37..61ddb17f32e 100644 --- a/config/mobile-ci.vitest.config.mjs +++ b/config/mobile-ci.vitest.config.mjs @@ -3,7 +3,6 @@ import original from '../mobile/vitest.config.ts' // Keep real process, native, and runtime-specific contracts on Node. const nodeFiles = [ - 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', 'scripts/check-tests-typecheck-incremental-cache.test.ts', 'src/mock-server-key-pair.test.ts', 'src/mobile-release/prepare-android-release-script.test.ts', diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 85d6225d4a7..89669f71704 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -1,38 +1,28 @@ -# Existing production source files importing child_process outside @orca/process-host. +# Existing production source files importing child_process at runtime outside @orca/process-host. # Migration debt: this list may only shrink; new callers use the package public API. src/cli/handlers/core.ts src/cli/handlers/interactive-login-interruption.ts src/cli/runtime/launch.ts src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts -src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts -src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts -src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts -src/main/ai-vault/scan-service/session-scanner-service-client-state.ts -src/main/ai-vault/scan-service/session-scanner-service-client.ts src/main/ai-vault/scan-service/session-scanner-service-spawn.ts src/main/window/desktop-integration/app-icon.ts src/main/automations/precheck-runner.ts src/main/browser/agent-browser/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 src/main/codex-accounts/service.ts -src/main/codex/app-server/codex-app-server-session.ts src/main/computer/desktop-script-provider-bridge.ts src/main/computer/macos-computer-use-permission-status.ts src/main/computer/macos-computer-use-permissions.ts src/main/computer/macos-native-provider-transport.ts src/main/computer/sidecar-client.ts -src/main/daemon/launch/daemon-launched-child.ts src/main/daemon/endpoint/identity/daemon-process-identity-query.ts src/main/daemon/endpoint/identity/daemon-process-inspection.ts src/main/daemon/endpoint/identity/daemon-process-start-time.ts src/main/emulator/android/android-avd-boot.ts -src/main/emulator/android/scrcpy-stream-session.ts src/main/emulator/serve-sim-helper-processes.ts src/main/emulator/serve-sim-runtime-materializer.ts src/main/emulator/simctl-simulator-devices.ts @@ -49,33 +39,18 @@ src/main/git/wsl-git-read-environment.ts src/main/github/gh-utils.ts src/main/workspace-hooks/hooks.ts src/main/ipc/developer-permissions.ts -src/main/ipc/filesystem/filesystem-handler-context.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-restart.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-cancellation-tracker.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-child-messaging.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-child-recovery.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-child-termination.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-host-subscriptions.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-pending-cancellation.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-process-supervisor.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-disposal.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-message.ts -src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts -src/main/ipc/filesystem/watchers/wsl-watcher-process-exit.ts src/main/ipc/local-network-connection-test.ts src/main/ipc/macos-keyboard-input-source.ts src/main/ipc/macos-keyboard-layout-snapshot.ts src/main/ipc/notification-authorization-status.ts src/main/ipc/preflight-command-exec.ts -src/main/ipc/repos/repo-clone-lifecycle.ts src/main/ipc/worktree-apfs-clone.ts src/main/local-builds/local-build-candidate.ts src/main/macos-keychain/generic-password.ts src/main/power/macos-system-sleep-assertion.ts src/main/macos-permissions/macos-tcc-prompt-watch.ts src/main/memory/collector.ts -src/main/native-chat/wsl-transcript-fs-process-slot.ts src/main/native-chat/wsl-transcript-fs-process-spawn.ts src/main/network/macos-system-resolver-health.ts src/main/network/macos-tailscale-dns-diagnostic.ts @@ -85,21 +60,17 @@ src/main/ports/port-scan-command-execution.ts src/main/providers/macos-login-session-pty-probe.ts src/main/providers/process-cwd.ts src/main/pty/process-retirement/pty-descendant-fresh-table.ts -src/main/pty/environment/windows-environment-path.ts src/main/rate-limits/providers/gemini/gemini-cli-oauth-extractor.ts src/main/runtime/rpc/server/pairing/network/windows-default-route-interfaces.ts src/main/runtime/rpc/server/pairing/network/windows-mobile-firewall.ts -src/main/ssh/connection/ssh-connection.ts src/main/ssh/system-transport/ssh-proxy-command.ts src/main/ssh/system-transport/system-ssh-command.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.ts src/main/ssh/system-transport/file-transfer/system-ssh-file-transfer.ts -src/main/ssh/system-transport/system-ssh-operation-lifecycle.ts src/main/startup/ensure-virtual-display.ts src/main/pty/process-retirement/windows-process-tree-kill.ts src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts src/shared/ephemeral-vm-recipe-process.ts -src/shared/ephemeral-vm-recipe-runner.ts src/shared/fish-binary-requirement.ts src/shared/process-table-ps-capture.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.ts diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index 343b138c771..e48d5c80d66 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -39,6 +39,7 @@ 1 src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts 1 src/main/notifications/desktop-presence-reporter.ts 1 src/main/orcad/orcad-browser-install-park.ts +1 src/main/orcad/orcad-event-loop-watchdog.ts 1 src/main/orcad/orcad-lock-clone-machine.ts 1 src/main/orcad/orcad-stop-request-listener.ts 1 src/main/plugins/catalog/plugin-auto-updater.ts @@ -88,5 +89,6 @@ 1 src/renderer/src/lib/window-visibility-interval.ts 1 src/renderer/src/lib/worker-auto-close.ts 1 src/renderer/src/runtime/hosts/wsl/wsl-refused-read-watch.ts +1 src/shared/remote-runtime/control/remote-runtime-shared-control-app-heartbeat.ts 1 src/shared/remote-runtime/remote-runtime-socket-liveness.ts 1 src/shared/tmux-agent-hook-owner.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index faed2105a46..76de250ab2b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -7676,7 +7676,7 @@ "oracle": "Audit2371 reduces all-host-folder-workspace-catalogs.test.ts by removing the repeated offline compatibility-probe budget and its incidental local-fallback/restored-owner samples, and catalog-settlement-notifications.test.ts by removing the four-route ten-equal-refresh notification/reference matrix. Those probe, quietness, identity and fallback alarms are intentionally lost. Remaining stale-response and revision-fencing examples do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced sources; the four unrelated physical selected-runtime E2E receipts retain their original commands and scope. Historical prior account (preserved verbatim): Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/store/project-groups/nested-repository-operations.test.ts: routes local nested scan progress by scanId and unsubscribes after completion. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Start with Active Server=Local desktop, connect and navigate Windows 2, then reveal a local terminal and assert it succeeds while the persisted preference remains local before and after restart. Repeat transient routing and selected-runtime Add Project operations with exact-ID host decoys and completion reordering. Separately pair the real web client to an isolated headed host, then make its sole still-listed runtime compatibility-blocked and unavailable. Require a null authoritative selection, a disabled host option, and disabled Browse, Clone, and Create actions with no local fallback. Repeat against headless serve. Run the byte-identical selector/action contract on latest main, candidate, and candidate with the eligibility seam disabled.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/settings/settings.test.ts src/renderer/src/store/slices/browser/hosts/browser-session-host-selection.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" @@ -7689,7 +7689,6 @@ "src/renderer/src/web/web-preload-api-runtime-environment.test.ts", "src/renderer/src/components/sidebar/project-admission/dialog/AddRepoStartSteps.test.tsx", "src/renderer/src/lib/resolved-worktree-execution-host.test.ts", - "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts", "src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts", "src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts", "src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts", @@ -7809,6 +7808,8 @@ "Run the paired Add Project journey on Linux and native Windows, plus live SSH and WSL hosts." ], "knownGaps": [ + "Audit2680: Delete the whole supplied-state worktree-runtime-owner suite. Lose immutable collection-reference invalidation and per-worktree override/folder inheritance lookup alarms without replacement. Remove its prospective selector and file membership; unchanged independent Electron evidenceRuns remain historical and do not validate the reduced selector. No fresh execution or equivalent replacement is claimed.", + "Audit2680 historical original selector metadata, preserved verbatim; not current evidence: {\"command\":\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts src/renderer/src/store/repos/ssh-repo-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-readoption-drafts.test.ts src/renderer/src/store/repos/repo-catalog-readoption-drafts.test.ts src/renderer/src/store/folder-workspaces/all-host-folder-workspace-catalogs.test.ts src/renderer/src/store/host-catalog/catalog-settlement-notifications.test.ts src/renderer/src/store/repos/repos-stale-fetch.test.ts src/renderer/src/store/folder-workspaces/folder-workspace-routing.test.ts src/renderer/src/store/repos/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/worktrees/session/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts --maxWorkers=1\",\"testFiles\":\"src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts\"}", "Audit2360 removes src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts and its exclusive fake-effect harness. Lose local default-runtime persistence across navigation; focused/background terminal request/create/reveal and no-focus recovery; startup cwd/config/agent/view-mode forwarding; explicit runtime-session routing; remote/ambiguous/missing owner refusal; history focus; existing PTY reuse/title preservation; pending tab PTY/layout/identity adoption; split tree, focus, identity and telemetry samples. No equivalent replacement claimed. Changed selectors have no fresh execution or red/green credit. Unrelated retained receipt objects keep their original narrow scope. Retired assertion reference verbatim: {\n \"file\": \"src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts\",\n \"assertions\": [\n \"Local desktop remains the durable default after transient Windows 2 navigation and a focused local terminal reveal succeeds\",\n \"local and remote terminal create route by target workspace ownership instead of the durable preference\"\n ]\n }", "Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "The exact journey is deterministic contract coverage, not a packaged Windows UI automation run.", diff --git a/config/scripts/static-analysis/module-requests/static-module-specifiers.mjs b/config/scripts/static-analysis/module-requests/static-module-specifiers.mjs index 961b899301a..408f9cc232c 100644 --- a/config/scripts/static-analysis/module-requests/static-module-specifiers.mjs +++ b/config/scripts/static-analysis/module-requests/static-module-specifiers.mjs @@ -100,7 +100,7 @@ function collectBindings(source) { // Resolve file-wide static import/re-export/import()/require/module.require/createRequire aliases and getBuiltinModule; literals/const strings and literal property keys only. // No scope tracking, computed values/specifiers, imported parameters, object/argument loaders or eval/Function resolution. -export function collectModuleSpecifiers(file, contents) { +export function collectModuleSpecifiers(file, contents, { runtimeOnly = false } = {}) { const source = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, false) if (source.parseDiagnostics.length > 0) { throw new Error(`Cannot parse ${file}; the process-host import check must not skip it.`) @@ -226,6 +226,14 @@ export function collectModuleSpecifiers(file, contents) { } } for (const node of modules) { + if ( + runtimeOnly && + (ts.isImportTypeNode(node) || + node.isTypeOnly || + (ts.isImportDeclaration(node) && node.importClause?.isTypeOnly)) + ) { + continue + } if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { add(node.moduleSpecifier) } else if ( diff --git a/config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs b/config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs index b69c39fe070..3ac5874b986 100644 --- a/config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs @@ -59,6 +59,7 @@ export function assessProcessHostImports( ]) for (const [file, contents] of sources) { const ownSource = file.startsWith(PACKAGE_SOURCE) + let runtimeSpecifiers for (const sourceSpecifier of specifiersFor(file, contents)) { const specifier = normalized(sourceSpecifier) const local = packageRelativeImport(file, specifier) @@ -103,7 +104,12 @@ export function assessProcessHostImports( !isTestOnlySourcePath(file) && (specifier === 'child_process' || specifier === 'node:child_process') ) { - direct.add(file) + runtimeSpecifiers ??= new Set( + collectModuleSpecifiers(file, contents, { runtimeOnly: true }) + ) + if (runtimeSpecifiers.has(specifier)) { + direct.add(file) + } } } } diff --git a/config/scripts/static-analysis/process-boundaries/check-process-host-imports.test.mjs b/config/scripts/static-analysis/process-boundaries/check-process-host-imports.test.mjs new file mode 100644 index 00000000000..6c5cf811520 --- /dev/null +++ b/config/scripts/static-analysis/process-boundaries/check-process-host-imports.test.mjs @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' +import { assessProcessHostImports } from './check-process-host-imports.mjs' + +const file = 'src/main/process-consumer.ts' +const manifest = { exports: { '.': './dist/index.js' } } +const assess = (source) => assessProcessHostImports(new Map([[file, source]]), manifest, new Set()) + +describe('process-host runtime import boundary', () => { + it.each([ + "import type { ChildProcess } from 'node:child_process'", + "import type * as ChildProcess from 'child_process'", + "import type ChildProcess = require('node:child_process')", + "export type { ChildProcess } from 'node:child_process'", + "type Child = import('node:child_process').ChildProcess" + ])('allows erased Node type ownership: %s', (source) => { + expect(assess(source)).toMatchObject({ direct: [], added: [], violations: [] }) + }) + + it.each([ + "import { spawn } from 'node:child_process'", + "import 'child_process'", + "import { type ChildProcess } from 'node:child_process'", + "export { spawn } from 'node:child_process'", + "const child = require('node:child_process')", + "const child = import('node:child_process')", + "import type { ChildProcess } from 'node:child_process'; require('node:child_process')", + "import { createRequire } from 'node:module'; const load = createRequire(import.meta.url); load('node:child_process')", + "process.getBuiltinModule('child_process')" + ])('still rejects runtime access: %s', (source) => { + expect(assess(source)).toMatchObject({ direct: [file], added: [file] }) + }) + + it('keeps package export restrictions for type-only imports', () => { + expect(assess("import type { Private } from '@orca/process-host/private'").violations).toEqual([ + `${file}: @orca/process-host/private is not a public process-host export` + ]) + }) + + it('requires the WSL allowlist only for runtime child-process imports', () => { + const wsl = "const program = 'wsl.exe'" + expect( + assess(`import type { ChildProcess } from 'node:child_process'; ${wsl}`).violations + ).toEqual([]) + expect(assess(`import { spawn } from 'node:child_process'; ${wsl}`).violations).toEqual([ + `${file}: direct wsl.exe exec must call assertWslDistroAllowed` + ]) + }) +}) diff --git a/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts b/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts index 0a37c94dae4..1d1d44efe69 100644 --- a/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts +++ b/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts @@ -6,11 +6,11 @@ import { PassThrough } from 'node:stream' import { afterAll, afterEach, beforeAll, expect, it, onTestFinished, vi } from 'vitest' import { createVitest, type PoolOptions, type Vitest } from 'vitest/node' import * as processes from '@orca/process-host' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { nodeRuntimePool } from './vitest-node-runtime-pool' let context: Vitest -const children: ChildProcessHandle[] = [] +const children: ChildProcess[] = [] const spawn = processes.spawnProcess beforeAll(async () => { diff --git a/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.ts b/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.ts index b6914b161f0..16d79a56062 100644 --- a/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.ts +++ b/config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.ts @@ -1,7 +1,7 @@ import { isAbsolute, resolve } from 'node:path' import type { PoolOptions, PoolWorker, WorkerRequest } from 'vitest/node' import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { decodeNodeRuntimeMessage, encodeNodeRuntimeMessage @@ -10,7 +10,7 @@ import { class NodeRuntimeWorker implements PoolWorker { readonly name = 'node-runtime' readonly cacheFs = true - private child: ChildProcessHandle | undefined + private child: ChildProcess | undefined constructor(private readonly options: PoolOptions) {} @@ -125,7 +125,7 @@ class NodeRuntimeWorker implements PoolWorker { } } - private get worker(): ChildProcessHandle { + private get worker(): ChildProcess { if (!this.child) { throw new Error('Node Vitest worker is not running') } diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 00967828447..a29424675e5 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -19,7 +19,6 @@ const contracts = [ 'src/main/usage/jsonl-file-reader.test.ts', 'src/main/usage/jsonl-file-snapshot.test.ts', 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts', - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts', 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs index 8066911e602..b4545dc56ef 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.mjs +++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs @@ -14,12 +14,7 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/ // Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass // that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks. -export const TESTS_OUTSIDE_PROGRAM = new Map([ - [ - 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', - 'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks' - ] -]) +export const TESTS_OUTSIDE_PROGRAM = new Map([]) // Normalize tsc’s host separators to POSIX baseline paths or Windows reports every entry stale and added. const toPosix = (filePath) => filePath.replaceAll('\\', '/') diff --git a/mobile/scripts/check-tests-typecheck-ratchet.test.ts b/mobile/scripts/check-tests-typecheck-ratchet.test.ts index e0d100035c6..cb326066f34 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.test.ts +++ b/mobile/scripts/check-tests-typecheck-ratchet.test.ts @@ -59,15 +59,6 @@ describe('the @ts-nocheck guard', () => { }) describe('checked transfers', () => { - it('accepts an empty checked cohort while retaining legacy runtime allowances', () => { - expect( - checkTransfers( - { ok: true, expected: [], programTestFiles: [], failures: [], problems: [] }, - new Map([['legacy.test.ts', 'Legacy runtime-only: no checked transfer']]) - ) - ).toEqual([]) - }) - it('rejects a declared checked transfer missing from the configured roots', () => { expect( checkTransfers( diff --git a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts b/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts deleted file mode 100644 index 409b2896269..00000000000 --- a/mobile/src/accounts/mobile-accounts-screen-reset-credit.test.ts +++ /dev/null @@ -1,253 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ConfirmModal } from '../components/ConfirmModal' -import { MobileAccountsScreen } from './MobileAccountsScreen' - -const dependencies = vi.hoisted(() => ({ - back: vi.fn(), - loadHosts: vi.fn(), - uuid: vi.fn<() => string>(), - resetRequest: vi.fn(), - selectRequest: vi.fn(), - statusCapabilities: vi.fn(), - subscriptionListeners: new Array<(payload: unknown) => void>() -})) - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Animated: { View: 'View' }, - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - RefreshControl: 'RefreshControl', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) - -vi.mock('react-native-safe-area-context', () => ({ - SafeAreaView: 'SafeAreaView', - useSafeAreaInsets: () => ({ bottom: 0, left: 0, right: 0, top: 0 }) -})) - -vi.mock('expo-router', async () => { - const React = await import('react') - return { - useFocusEffect(effect: () => void | (() => void)): void { - React.useEffect(effect, [effect]) - }, - useLocalSearchParams: () => ({ hostId: 'host-1' }) - } -}) - -// The page's Back: the handoff pops the shell's stack, where expo-router's own `back()` goes nowhere. -vi.mock('../navigation/route-handoff', () => ({ - useRouteHandoff: () => ({ back: dependencies.back }) -})) - -// The dialogs are read off `ConfirmModal`'s props; the drawer under them needs a native runtime. -vi.mock('../components/bottom-drawer/BottomDrawer', () => ({ BottomDrawer: () => null })) - -vi.mock('../platform/random-v4-uuid', () => ({ randomV4Uuid: dependencies.uuid })) - -vi.mock('lucide-react-native', () => ({ - Check: 'Check', - ChevronLeft: 'ChevronLeft', - RefreshCw: 'RefreshCw', - RotateCcw: 'RotateCcw', - User: 'User' -})) - -vi.mock('../transport/hosts/host-store', () => ({ - loadHosts: dependencies.loadHosts, - peekHosts: () => null -})) - -vi.mock('../transport/connection/host-client-hooks', () => { - const client = { - sendRequest: async (method: string, params?: unknown, options?: unknown) => { - if (method === 'status.get') { - return { - id: 'status', - ok: true, - result: { capabilities: dependencies.statusCapabilities() }, - _meta: { runtimeId: 'runtime-1' } - } - } - if (method === 'accounts.consumeCodexResetCredit') { - return dependencies.resetRequest(params, options) - } - if ( - method === 'accounts.selectCodex' || - method === 'accounts.selectCodexForTarget' || - method === 'accounts.selectClaude' - ) { - return dependencies.selectRequest(method, params) - } - if (method === 'accounts.list') { - return { id: 'list', ok: true, result: AVAILABLE_SNAPSHOT } - } - throw new Error(`Unexpected request: ${method}`) - }, - subscribe: (_method: string, _params: unknown, onData: (payload: unknown) => void) => { - dependencies.subscriptionListeners.push(onData) - onData({ type: 'ready', snapshot: AVAILABLE_SNAPSHOT }) - return vi.fn() - } - } - return { - useForceReconnect: () => null, - useHostClient: () => ({ client, state: 'connected' }) - } -}) - -vi.mock('../components/AgentIcons', () => ({ - ClaudeIcon: 'ClaudeIcon', - OpenAIIcon: 'OpenAIIcon' -})) - -const AVAILABLE_SNAPSHOT = { - claude: { accounts: [], activeAccountId: null }, - codex: { - accounts: [ - { - id: 'codex-1', - email: 'dev@example.com', - managedHomeRuntime: 'host', - wslDistro: null, - updatedAt: 10 - } - ], - activeAccountId: 'codex-1', - activeAccountIdsByRuntime: { host: 'codex-1', wsl: {} } - }, - rateLimits: { - claude: null, - codex: { - provider: 'codex', - session: { - usedPercent: 100, - windowMinutes: 300, - resetsAt: 2_000_000_000_000, - resetDescription: null - }, - weekly: null, - rateLimitResetCredits: { availableCount: 1, nextExpiresAt: null }, - updatedAt: 100, - error: null, - status: 'ok' - }, - claudeTarget: { runtime: 'host', wslDistro: null }, - codexTarget: { runtime: 'host', wslDistro: null }, - inactiveClaudeAccounts: [], - inactiveCodexAccounts: [] - } -} as const - -const RESET_SNAPSHOT = { - ...AVAILABLE_SNAPSHOT, - rateLimits: { - ...AVAILABLE_SNAPSHOT.rateLimits, - codex: { - ...AVAILABLE_SNAPSHOT.rateLimits.codex, - session: { ...AVAILABLE_SNAPSHOT.rateLimits.codex.session, usedPercent: 0 }, - rateLimitResetCredits: { availableCount: 0, nextExpiresAt: null }, - updatedAt: 101 - } - } -} as const - -async function renderAccountsRoute(): Promise { - let renderer: ReactTestRenderer | null = null - await act(async () => { - renderer = create(createElement(MobileAccountsScreen)) - await Promise.resolve() - }) - if (!renderer) { - throw new Error('Accounts route did not render') - } - return renderer -} - -/** Host components are strings under the mock above, so they are found by what they carry. */ -function pressables(renderer: ReactTestRenderer, label: string) { - return renderer.root.findAll( - (node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === label - ) -} - -function resetButtons(renderer: ReactTestRenderer) { - return pressables(renderer, 'Use Codex rate-limit reset') -} - -async function findResetButton(renderer: ReactTestRenderer) { - await vi.waitFor(() => expect(resetButtons(renderer)).toHaveLength(1)) - return resetButtons(renderer)[0]! -} - -/** The open dialog, read off `ConfirmModal` the way a user reads the drawer. */ -function openDialog(renderer: ReactTestRenderer) { - const open = renderer.root - .findAllByType(ConfirmModal) - .map((node) => node.props) - .filter((props) => props.visible) - if (open.length > 1) { - throw new Error(`expected at most one open dialog, found ${open.length}`) - } - return open[0] ?? null -} - -/** Presses the dialog's confirm button, which closes it after its action as `ConfirmContent` does. */ - -const KEY = '11111111-1111-4111-8111-111111111111' - -describe('accounts route Codex reset credit', () => { - beforeEach(() => { - dependencies.loadHosts.mockReset().mockResolvedValue([ - { - id: 'host-1', - name: 'Desk', - endpoint: 'ws://127.0.0.1:6768', - deviceToken: 'token', - publicKeyB64: 'public-key', - lastConnected: 1 - } - ]) - dependencies.uuid.mockReset().mockReturnValue(KEY) - dependencies.back.mockReset() - dependencies.statusCapabilities.mockReset().mockReturnValue(['accounts.codex-reset-credit.v1']) - dependencies.resetRequest.mockReset().mockImplementation((params) => ({ - id: 'reset', - ok: true, - result: { - outcome: 'reset', - scope: (params as { expectedScope: unknown }).expectedScope, - snapshot: RESET_SNAPSHOT - }, - _meta: { runtimeId: 'runtime-1' } - })) - dependencies.selectRequest.mockReset().mockResolvedValue({ - id: 'select', - ok: true, - result: AVAILABLE_SNAPSHOT.codex - }) - dependencies.subscriptionListeners.length = 0 - }) - - afterEach(() => { - vi.restoreAllMocks() - }) - - it('sends nothing when the confirmation is cancelled', async () => { - const renderer = await renderAccountsRoute() - const button = await findResetButton(renderer) - await act(async () => button.props.onPress()) - act(() => openDialog(renderer)?.onCancel()) - - expect(openDialog(renderer)).toBeNull() - expect(dependencies.resetRequest).not.toHaveBeenCalled() - act(() => renderer.unmount()) - }) -}) diff --git a/mobile/src/agent-history/agent-history-scope-paths.test.ts b/mobile/src/agent-history/agent-history-scope-paths.test.ts deleted file mode 100644 index 018129e9013..00000000000 --- a/mobile/src/agent-history/agent-history-scope-paths.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - deriveMobileAiVaultScopePaths, - mobileAiVaultScanScopeArgs -} from './agent-history-scope-paths' - -const worktree = (worktreeId: string, path: string) => ({ worktreeId, path, repoId: 'repo-1' }) - -describe('mobile AI Vault scope paths', () => { - const active = worktree('w1', '/Users/ada/repo/app') - const siblings = Array.from({ length: 200 }, (_, index) => - worktree(`w-sib-${index}`, `/Users/ada/repo/app-${index}`) - ) - - it('caps only the scan hints, so an older host accepts them and Project still shows every sibling', () => { - const scopePaths = deriveMobileAiVaultScopePaths('project', active, [active, ...siblings]) - const scan = mobileAiVaultScanScopeArgs('project', scopePaths) - - expect(scopePaths).toHaveLength(201) - expect(scan.scopePaths).toHaveLength(64) - // Active worktree is seeded first, so it survives truncation. - expect(scan.scopePaths?.[0]).toBe('/Users/ada/repo/app') - // A capped scope can't answer alone, so the host keeps its recency scan. - expect(scan.scopeOnly).toBeUndefined() - }) -}) diff --git a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts b/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts deleted file mode 100644 index dfceecbc797..00000000000 --- a/mobile/src/browser/browser-screencast-budget-at-the-shell.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { utf8ByteLength } from '../mobile-web-shell/bridge/bridge-caps' -import { clientFrame } from '../mobile-web-shell/bridge-host-test-fakes' -import { harness, ID } from '../mobile-web-shell/bridge-host-test-harness' -import { BrowserScreencastOpcode, type BrowserScreencastFrame } from './browser-screencast-protocol' -import { - binaryEventEnvelopeBytes, - mobileBrowserFrameAreaBudget, - WORST_CASE_JPEG_BYTES_PER_PIXEL -} from './browser-screencast-request.web' - -// Use all nine Chromium metadata fields and real epoch/microsecond timestamp; toy integer understates envelope width. -const CDP_METADATA = { - offsetTop: 0, - pageScaleFactor: 1, - deviceWidth: 390, - deviceHeight: 712, - imageWidth: 780, - imageHeight: 1424, - scrollOffsetX: 0, - scrollOffsetY: 2048.5, - timestamp: 1_758_326_400.123456 -} - -// Deterministic unstructured noise exercises JPEG worst case reproducibly. -function noise(byteLength: number): Uint8Array { - const bytes = new Uint8Array(byteLength) - let state = 0x9e37_79b9 - for (let index = 0; index < byteLength; index += 1) { - state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0 - bytes[index] = (state >>> 24) & 0xff - } - return bytes -} - -function screencastFrame(image: Uint8Array): BrowserScreencastFrame { - return { - opcode: BrowserScreencastOpcode.Frame, - seq: FRAME_SEQ, - format: 'jpeg', - metadata: CDP_METADATA, - image - } -} - -// Exercise a noninitial screencast frame counter. -const FRAME_SEQ = 4_096 - -/** The one frame the shell posted for this image, and what it cost besides the image. */ -function postedFrame(image: Uint8Array): { bytes: number; envelope: number; posts: number } { - const bridge = harness({ ready: true }) - bridge.host.receive( - clientFrame({ - type: 'subscribe', - id: ID, - method: 'browser.screencast', - params: { worktree: 'id:w', page: 'p' }, - wantsBinary: true - }) - ) - const before = bridge.posted.length - // Fail if no binary lane opened; optional chaining would otherwise look like a correctly dropped frame. - const emitBinary = bridge.client.streams[0]?.emitBinary - if (emitBinary === null || emitBinary === undefined) { - throw new Error('the subscribe opened no binary stream') - } - emitBinary(screencastFrame(image)) - const json = bridge.posted.at(-1) ?? '' - const posts = bridge.posted.length - before - const event = posts === 0 ? null : bridge.last() - const b64 = event !== null && 'binary' in event ? event.binary.b64 : '' - return { bytes: utf8ByteLength(json), envelope: utf8ByteLength(json) - b64.length, posts } -} - -// These synthetic bytes prove base64 arithmetic/drop rules, not JPEG bytes-per-pixel assumption. -describe('a frame at exactly the budgeted area', () => { - /** The image the budget says the mobile view's worst case produces, to the byte. */ - const BUDGETED_IMAGE_BYTES = Math.floor( - mobileBrowserFrameAreaBudget() * WORST_CASE_JPEG_BYTES_PER_PIXEL - ) - - it('is a ceiling: an image past it is dropped by the shell, not sent over the cap', () => { - // Unexpected worst-case overflow must be dropped at shell boundary (C6 ruling 1). - const { posts } = postedFrame(noise(BUDGETED_IMAGE_BYTES + binaryEventEnvelopeBytes())) - - expect(posts).toBe(0) - }) -}) diff --git a/mobile/src/browser/browser-screencast-request.web.ts b/mobile/src/browser/browser-screencast-request.web.ts index 30dfe33a956..dacb72fb90e 100644 --- a/mobile/src/browser/browser-screencast-request.web.ts +++ b/mobile/src/browser/browser-screencast-request.web.ts @@ -37,7 +37,7 @@ const WIDEST_JSON_DOUBLE_CHARS = 25 const NARROWEST_JSON_DOUBLE_CHARS = 1 // Derive envelope bound from real protocol shape: longest correlation id, MAX_SAFE_INTEGER counters and every metadata field widened to finite-double maximum. -// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames. browser-screencast-budget-at-the-shell.test.ts reconstructs bound from real encoded/serialized event. +// Budget cannot predict unknown loose metadata or letterboxed web frames; shell drops over-cap frames. export function binaryEventEnvelopeBytes(): number { const skeleton = JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, diff --git a/mobile/src/components/MobileMarkdown.rendering.test.tsx b/mobile/src/components/MobileMarkdown.rendering.test.tsx deleted file mode 100644 index b01e4830d69..00000000000 --- a/mobile/src/components/MobileMarkdown.rendering.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { MobileMarkdown } from './MobileMarkdown' -import { MarkdownLinkHandlerContext } from './markdown-link-handler' - -const openURL = vi.fn((_url: string) => Promise.resolve()) - -vi.mock('react-native', () => ({ - Linking: { openURL: (url: string) => openURL(url) }, - Platform: { OS: 'ios' }, - Pressable: 'Pressable', - ScrollView: 'ScrollView', - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' -})) -vi.mock('./pr-sidebar/MermaidDiagram', () => ({ MermaidDiagram: 'MermaidDiagram' })) -vi.mock('./MobileSourceCopyButton', () => ({ MobileSourceCopyButton: 'MobileSourceCopyButton' })) - -let renderer: ReactTestRenderer | null = null - -afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - openURL.mockClear() -}) - -function render(content: string, growing = false): ReactTestRenderer { - act(() => { - renderer = create(createElement(MobileMarkdown, { content, growing })) - }) - return renderer! -} - -function flatten(node: ReactTestInstance | string): string { - return typeof node === 'string' ? node : node.children.map(flatten).join('') -} - -const isText = (node: ReactTestInstance): boolean => String(node.type) === 'Text' - -/** Every Text not inside another Text, in reading order: what the reader sees, block by block. */ -function texts(tree: ReactTestRenderer): string[] { - return tree.root - .findAll((node) => isText(node) && !(node.parent && hasTextAncestor(node.parent))) - .map(flatten) -} - -function hasTextAncestor(node: ReactTestInstance): boolean { - return isText(node) || (node.parent !== null && hasTextAncestor(node.parent)) -} - -function press(tree: ReactTestRenderer, label: string): void { - const target = tree.root.find( - (node) => isText(node) && typeof node.props.onPress === 'function' && flatten(node) === label - ) - act(() => target.props.onPress()) -} - -describe('MobileMarkdown rendering', () => { - it('C21: closes open markup while a reply grows, and never links a half-written address', () => { - expect(texts(render('2 * 3 is six.\n\nRead **src/main/ses', true))).toEqual([ - '2 * 3 is six.', - 'Read src/main/ses' - ]) - const tree = render('See [config loader](https://exa', true) - expect(texts(tree)).toEqual(['See config loader']) - expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toEqual([]) - }) - - it('hands a web link to the screen that offers choices; mail and file links still open directly', () => { - const onOpenLink = vi.fn() - const onOpenFile = vi.fn() - act(() => { - renderer = create( - createElement( - MarkdownLinkHandlerContext.Provider, - { value: onOpenLink }, - createElement(MobileMarkdown, { - content: '[docs](https://x.com/a), [mail](mailto:a@x.com) and [file](src/a.ts)', - onOpenFile - }) - ) - ) - }) - press(renderer!, 'docs') - press(renderer!, 'mail') - press(renderer!, 'file') - - expect(onOpenLink).toHaveBeenCalledTimes(1) - expect(onOpenLink).toHaveBeenCalledWith('https://x.com/a') - expect(openURL).toHaveBeenCalledTimes(1) - expect(openURL).toHaveBeenCalledWith('mailto:a@x.com') - expect(onOpenFile).toHaveBeenCalledWith('src/a.ts') - }) -}) - -it('draws every image in a paragraph and keeps the text around them, leaving declined images as links', () => { - const renderImage = vi.fn((href: string, alt: string) => - href.startsWith('/') ? createElement('View', { testID: `image:${href}`, alt }) : null - ) - act(() => { - renderer = create( - createElement(MobileMarkdown, { - content: - 'Before and after: \n![one](/tmp/a.png)\n![two](/tmp/b.png)\n![three](rel.png) done', - renderImage - }) - ) - }) - const images = renderer!.root.findAll((node) => String(node.props.testID).startsWith('image:')) - expect(images.map((node) => node.props.testID)).toEqual(['image:/tmp/a.png', 'image:/tmp/b.png']) - expect(texts(renderer!)).toEqual(['Before and after:', 'three done']) -}) diff --git a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx b/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx deleted file mode 100644 index a8043236b5d..00000000000 --- a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, expect, it, vi } from 'vitest' -import { clearDisclosuresForTests } from '../worktree/agent-child-disclosure' -import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { WorktreeAgentSummary } from './WorktreeAgentSummary' -import { WorktreeAgentList } from './WorktreeAgentList' - -// Disclosures persist in a module cache across list remounts; isolate each test. -beforeEach(clearDisclosuresForTests) - -vi.mock('react-native', () => ({ - AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, - Pressable: 'Pressable', - StyleSheet: { create: (styles: T) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('lucide-react-native', () => ({ - ChevronDown: 'ChevronDown', - ChevronRight: 'ChevronRight' -})) -vi.mock('./AgentStateDot', () => ({ AgentStateDot: () => null })) -vi.mock('./MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) - -it('renders production-built canonical assignments as nested rows and groups only roots', async () => { - const clock = vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../src/main/runtime/workspaces/process-listing/runtime-agent-lineage.test-fixture') - const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') - const f = publicLineageFixture() - let tree: ReactTestRenderer | undefined - try { - const agents = f.build().agents - expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - await act(async () => { - tree = create( - createElement(WorktreeAgentList, { - agents, - unvisited: false, - statusLive: true - }) - ) - }) - const toggle = tree?.root.find( - (node) => node.props.accessibilityLabel === 'Show 1 child agent' && node.props.onPress - ) - await act(async () => toggle?.props.onPress({ stopPropagation: vi.fn() })) - expect( - tree?.root - .findAll((node) => node.props.agent !== undefined) - .map((node) => [node.props.agent.paneKey, node.props.depth]) - ).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) - expect(agents[1].taskTitle).toBe('Build the worker result') - expect(JSON.stringify(tree?.toJSON())).toContain('Coordinate work') - expect(JSON.stringify(tree?.toJSON())).toContain('Implement work') - expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) - const orphan = { - ...agents[1], - paneKey: 'missing-parent-worker', - parentPaneKey: 'missing-parent' - } - await act(async () => - tree?.update( - createElement(WorktreeAgentList, { - agents: [...agents, orphan], - unvisited: false - }) - ) - ) - expect( - tree?.root - .findByType(WorktreeAgentSummary) - .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) - ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) - } finally { - await act(async () => tree?.unmount()) - f.db.close() - clock.mockRestore() - } -}) diff --git a/mobile/src/components/mobile-markdown-visual-lines.test.ts b/mobile/src/components/mobile-markdown-visual-lines.test.ts deleted file mode 100644 index 62dd3318518..00000000000 --- a/mobile/src/components/mobile-markdown-visual-lines.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE } from '../../../src/shared/native-chat/native-chat-visual-directive' -import { plainText } from './mobile-markdown-plain-text' -import { parseMobileMarkdownTree } from './mobile-markdown-tree' -import { - mobileMarkdownVisualPlaceholderIndex, - protectMobileMarkdownVisualLines -} from './mobile-markdown-visual-lines' - -/** The top-level blocks drawn, with a lone placeholder paragraph read as its visual. */ -function topLevelBlocks(text: string, visualCount: number) { - return parseMobileMarkdownTree(text, false).children.map((node) => { - const visual = - node.type === 'paragraph' - ? mobileMarkdownVisualPlaceholderIndex(plainText(node), visualCount) - : null - if (visual !== null) { - return { type: 'visual', index: visual } - } - return node.type === 'code' - ? { type: 'code', text: node.value, language: node.lang } - : { type: node.type, text: plainText(node) } - }) -} - -/** The same steps MobileMarkdown runs when a transcript renders visuals. */ -function blocksOf(content: string) { - const { text, directives } = protectMobileMarkdownVisualLines(content) - return { directives, blocks: topLevelBlocks(text, directives.length) } -} - -describe('native-chat visual lines in mobile markdown', () => { - it('turns a directive line into its own block between prose', () => { - const { directives, blocks } = blocksOf( - 'Here is the chart.\n::orca-visual{file="usage-3f2a.html" title="Usage"}\nIt shows a dip.' - ) - expect(directives).toEqual([{ file: 'usage-3f2a.html', title: 'Usage' }]) - expect(blocks).toEqual([ - { type: 'paragraph', text: 'Here is the chart.' }, - { type: 'visual', index: 0 }, - { type: 'paragraph', text: 'It shows a dip.' } - ]) - }) - - it('keeps the title exactly as written, before entity decoding and tag stripping', () => { - const { directives } = blocksOf('::orca-visual{file="a.html" title="Q1 & Q2"}') - expect(directives).toEqual([{ file: 'a.html', title: 'Q1 & Q2' }]) - }) - - it('accepts CRLF line endings and up to three leading spaces', () => { - const { blocks } = blocksOf('intro\r\n ::orca-visual{file="a.html"}\r\nend') - expect(blocks.map((block) => block.type)).toEqual(['paragraph', 'visual', 'paragraph']) - }) - - it('leaves directives inside fenced code, quotes, list items and inline code as text', () => { - const fenced = blocksOf('```md\n::orca-visual{file="a.html"}\n```') - expect(fenced.directives).toEqual([]) - expect(fenced.blocks).toEqual([ - { type: 'code', text: '::orca-visual{file="a.html"}', language: 'md' } - ]) - expect(blocksOf('> ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('- ::orca-visual{file="a.html"}').directives).toEqual([]) - expect(blocksOf('see `::orca-visual{file="a.html"}`').directives).toEqual([]) - expect(blocksOf(' ::orca-visual{file="a.html"}').directives).toEqual([]) - }) - - it('resumes recognizing directives after a fence closes', () => { - const { directives } = blocksOf('```\ncode\n```\n::orca-visual{file="after.html"}') - expect(directives).toEqual([{ file: 'after.html', title: null }]) - }) - - it('renders directives past the per-message cap as text', () => { - const lines = Array.from( - { length: NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE + 1 }, - (_, index) => `::orca-visual{file="v${index}.html"}` - ) - const { directives, blocks } = blocksOf(lines.join('\n')) - expect(directives).toHaveLength(NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE) - expect(blocks.at(-1)).toEqual({ type: 'paragraph', text: lines.at(-1) }) - }) - - it('renders no visuals for text that already spells a placeholder', () => { - const { directives } = blocksOf('\uE000ORCA_VISUAL_0\uE000\n::orca-visual{file="a.html"}') - expect(directives).toEqual([]) - }) - - it('never treats a placeholder-looking line as a visual when none were protected', () => { - expect(topLevelBlocks('\uE000ORCA_VISUAL_0\uE000', 0)).toEqual([ - { type: 'paragraph', text: '\uE000ORCA_VISUAL_0\uE000' } - ]) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts b/mobile/src/components/pr-sidebar/pr-actions-state.test.ts deleted file mode 100644 index dfc489ea490..00000000000 --- a/mobile/src/components/pr-sidebar/pr-actions-state.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { summarizeProviderChecks } from '../../../../src/shared/source-control/checks/provider-check-summary' -import { describe, expect, it } from 'vitest' -import type { PRInfo } from '../../../../src/shared/github/pull-request-types' -import { presentPrMerge } from './pr-actions-state' - -describe('presentPrMerge', () => { - const pr: PRInfo = { - number: 202, - title: 'API', - state: 'open', - url: 'https://example.test/202', - checksStatus: 'success', - updatedAt: '', - mergeable: 'CONFLICTING' - } - const entry = { - title: '', - url: '', - state: 'open' as const, - checksStatus: 'success' as const, - mergeable: 'MERGEABLE' as const - } - - it('lets a complete stack merge through, and names a blocking downstack PR', () => { - const stack = { - number: 51, - position: 2, - size: 3, - baseRefName: 'main', - entries: [ - { ...entry, position: 1, number: 201 }, - { ...entry, position: 2, number: 202 } - ] - } - expect(presentPrMerge({ ...pr, stack }, 'squash')).toMatchObject({ - enabled: true, - label: 'Merge through #202 · 2 PRs' - }) - const blocked = { - ...stack, - entries: [{ ...entry, position: 1, number: 201, state: 'draft' as const }, stack.entries[1]] - } - expect(presentPrMerge({ ...pr, stack: blocked }, 'squash')).toMatchObject({ - enabled: false, - hint: '#201 is still a draft.' - }) - }) - it('keeps the provider-authorized merge action available with cancelled checks', () => { - const checksSummary = summarizeProviderChecks([ - { status: 'completed', conclusion: 'success' }, - { status: 'completed', conclusion: 'cancelled' } - ]) - expect( - presentPrMerge( - { - ...pr, - mergeable: 'MERGEABLE', - mergeStateStatus: 'CLEAN', - checksStatus: 'failure', - checksSummary - }, - 'squash' - ) - ).toMatchObject({ - label: 'Squash and merge', - hint: null, - enabled: true - }) - }) -}) diff --git a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts b/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts deleted file mode 100644 index f34823dcdf1..00000000000 --- a/mobile/src/components/pr-sidebar/pr-checks-presentation.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { expect, it } from 'vitest' -import type { PRCheckDetail } from '../../../../src/shared/github/check-types' -import { summarizePRChecks } from './pr-checks-presentation' - -function check(over: Partial): PRCheckDetail { - return { - name: 'ci', - status: 'completed', - conclusion: 'success', - url: null, - ...over - } -} - -it('presents cancellations without hiding real failure or pending checks', () => { - const cancelled = check({ conclusion: 'cancelled' }) - expect(summarizePRChecks([cancelled, check({})])).toMatchObject({ - outcome: 'cancelled', - failed: 0, - cancelled: 1, - label: '1 Cancelled · 1 passed' - }) - expect(summarizePRChecks([cancelled, check({ conclusion: 'pending' })]).outcome).toBe('pending') - expect(summarizePRChecks([cancelled, check({ conclusion: 'failure' })]).outcome).toBe('failure') -}) diff --git a/mobile/src/components/use-connected-host-picker.test.ts b/mobile/src/components/use-connected-host-picker.test.ts index 40e23a8f684..052c1b4a5f2 100644 --- a/mobile/src/components/use-connected-host-picker.test.ts +++ b/mobile/src/components/use-connected-host-picker.test.ts @@ -50,21 +50,6 @@ describe('useConnectedHostPicker', () => { act(() => handle.current!.pickHost(action, hosts)) } - it('disambiguates path-routed hosts without exposing endpoint paths', () => { - render([ - host('desk-a', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-a'), - host('desk-b', 'Desk', 'wss://gateway.example.com/v1/connect/bearer-secret-b') - ]) - - pickHost(vi.fn()) - - expect(picker().options).toEqual([ - { value: 'desk-a', label: 'Desk', subtitle: 'gateway.example.com · desk-a' }, - { value: 'desk-b', label: 'Desk', subtitle: 'gateway.example.com · desk-b' } - ]) - expect(JSON.stringify(picker().options)).not.toContain('bearer-secret') - }) - it('closes a stale picker when an offered host disconnects', () => { const rerender = render([desk, laptop]) diff --git a/mobile/src/components/use-detail-card-scope.web.test.tsx b/mobile/src/components/use-detail-card-scope.web.test.tsx deleted file mode 100644 index e615d52d926..00000000000 --- a/mobile/src/components/use-detail-card-scope.web.test.tsx +++ /dev/null @@ -1,193 +0,0 @@ -// @vitest-environment happy-dom -import { act, useRef } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { - DetailCardHostProvider, - DetailCardLayer, - DetailCardFocusBoundary -} from './detail-card-host.web' -import { useDetailCardScope } from './use-detail-card-scope.web' - -it('keeps outside actions and finite focus order while releasing a retained visual', () => { - const root = document.createElement('div') - document.body.append(root) - const node = (id: string) => { - const value = document.getElementById(id) - if (!(value instanceof HTMLElement)) { - throw new Error(id) - } - return value - } - const renderer = createRoot(root) - const dismiss = vi.fn() - const action = vi.fn() - function Scope({ active, obscured = false }: { active: boolean; obscured?: boolean }) { - const contentRef = useRef(null) - const boundaryRefs = useRef([]) - const openerRef = useRef(null) - const backRef = useRef(null) - useDetailCardScope({ active, obscured, openerRef, backRef, contentRef, boundaryRefs, dismiss }) - return ( - <> - - - - - - - - -
-
- Details -
-
- -
- - ) - } - const render = (active: boolean, obscured = false) => - act(() => - renderer.render( - - - - ) - ) - const focusBoundary = (id: string, backwards: boolean) => { - const boundary = backwards ? node(id).previousElementSibling : node(id).nextElementSibling - if (!(boundary instanceof HTMLElement)) { - throw new Error(`Missing focus boundary beside ${id}`) - } - boundary.focus() - } - - const key = (type: string, name: string, shiftKey = false) => - document.activeElement?.dispatchEvent( - new KeyboardEvent(type, { key: name, shiftKey, bubbles: true, cancelable: true }) - ) - const terminalKeys = vi.fn() - window.addEventListener('keydown', terminalKeys) - try { - render(false) - expect(document.activeElement).toBe(document.body) - const opener = node('opener') - const host = node('card').parentElement - expect(host?.parentElement).toBe(document.body) - node('terminal').focus() - render(true) - expect(node('terminal').inert).toBe(false) - expect(document.activeElement).toBe(node('terminal')) - node('back').click() - expect(dismiss).not.toHaveBeenCalled() - key('keydown', 'Escape') - key('keyup', 'Escape') - expect(terminalKeys).not.toHaveBeenCalled() - key('keydown', 'a') - expect(terminalKeys).toHaveBeenCalledTimes(1) - render(false) - expect(node('card').inert).toBe(true) - expect(opener.previousElementSibling).toBe(node('back')) - expect(opener.nextElementSibling).toBe(node('files')) - expect(node('card').nextElementSibling).toBeNull() - expect(document.activeElement).toBe(node('terminal')) - render(true) - key('keydown', 'Tab') - focusBoundary('opener', false) - expect(document.activeElement).toBe(node('scroll')) - key('keydown', 'Tab', true) - focusBoundary('card', true) - expect(document.activeElement).toBe(opener) - key('keydown', 'Tab', true) - focusBoundary('opener', true) - expect(document.activeElement).toBe(node('back')) - render(false) - render(true) - key('keydown', 'Tab') - focusBoundary('card', false) - expect(document.activeElement).toBe(node('files')) - expect(dismiss).toHaveBeenCalledTimes(3) - render(false) - render(true) - node('files').click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).toHaveBeenCalledTimes(4) - node('files').focus() - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - node('files').focus() - expect(dismiss).toHaveBeenCalledTimes(5) - render(false) - expect(document.activeElement).toBe(node('files')) - render(true) - render(false, true) - expect(node('card').inert).toBe(true) - expect(node('opener')).toBe(opener) - act(() => renderer.unmount()) - expect(host?.isConnected).toBe(false) - } finally { - window.removeEventListener('keydown', terminalKeys) - root.remove() - } -}) - -it('yields to a higher sheet while an earlier card contact is still in flight', () => { - const root = document.createElement('div') - document.body.append(root) - const mount = document.createElement('div') - root.append(mount) - const renderer = createRoot(mount) - const dismiss = vi.fn() - const action = vi.fn() - const openerRef = { current: document.createElement('button') } - const contentRef = { current: document.createElement('div') } - const backRef = { current: document.createElement('button') } - const boundaryRefs = { current: [] } - const sheet = document.createElement('button') - contentRef.current.tabIndex = -1 - sheet.addEventListener('click', action) - root.append(openerRef.current, backRef.current, contentRef.current, sheet) - function Scope({ obscured }: { obscured: boolean }) { - useDetailCardScope({ - active: !obscured, - obscured, - openerRef, - contentRef, - backRef, - boundaryRefs, - dismiss - }) - return null - } - const contact = (target: HTMLElement, type: string, pointerId: number) => - target.dispatchEvent( - new PointerEvent(type, { pointerId, pointerType: 'touch', bubbles: true, cancelable: true }) - ) - try { - openerRef.current.focus() - act(() => renderer.render()) - expect(contact(contentRef.current, 'pointerdown', 1)).toBe(true) - act(() => renderer.render()) - sheet.focus() - expect(contentRef.current.inert).toBe(true) - expect(contact(sheet, 'pointerdown', 2)).toBe(true) - expect(contact(contentRef.current, 'pointerup', 1)).toBe(true) - expect(contact(sheet, 'pointerup', 2)).toBe(true) - sheet.click() - expect(action).toHaveBeenCalledTimes(1) - expect(dismiss).not.toHaveBeenCalled() - expect(document.activeElement).toBe(sheet) - } finally { - act(() => renderer.unmount()) - root.remove() - } -}) diff --git a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts index 631d5af747b..39712e28e54 100644 --- a/mobile/src/diagnostics/connection/connection-log-buffer.test.ts +++ b/mobile/src/diagnostics/connection/connection-log-buffer.test.ts @@ -31,64 +31,6 @@ describe('connection log buffer', () => { expect(JSON.stringify(save.mock.calls)).not.toContain('legacy-secret') }) - it('redacts quoted credential values when the object key is unquoted', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: `resumeToken: 'secret-one' deviceToken="secret-two"` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe( - `resumeToken: '[redacted]' deviceToken="[redacted]"` - ) - }) - - it('redacts the full quoted credential when its value contains an escaped quote', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - detail: String.raw`{"token":"secret\"tail"} token: 'secret\'tail'` - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]?.detail).toBe(`{"token":"[redacted]"} token: '[redacted]'`) - }) - - it('redacts unterminated quoted credentials', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'token="secret', - detail: '{"authorization":"Bearer also-secret' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'token="[redacted]', - detail: '{"authorization":"[redacted]' - }) - }) - - it('redacts URL userinfo through the last authority separator', async () => { - const store = createConnectionLogStore(3, { load: async () => [], save: async () => {} }) - - store.append('host-a', { - ...entry(1), - message: 'wss://user:p@ss@example.com/x', - detail: 'https://user:pass@example.com/x' - }) - await store.hydrate('host-a') - - expect(store.get('host-a')[0]).toMatchObject({ - message: 'wss://[redacted]@example.com/x', - detail: 'https://[redacted]@example.com/x' - }) - }) - it('does not overwrite persisted history when hydration fails and retries later', async () => { const load = vi .fn<() => Promise>() diff --git a/mobile/src/diagnostics/native-diagnostics-operations.test.ts b/mobile/src/diagnostics/native-diagnostics-operations.test.ts index f87c0f062bc..38cbb6e3ab2 100644 --- a/mobile/src/diagnostics/native-diagnostics-operations.test.ts +++ b/mobile/src/diagnostics/native-diagnostics-operations.test.ts @@ -60,23 +60,4 @@ describe('native connection diagnostic reports', () => { expect(report).toContain('Host Orca version: unknown') expect(report).not.toContain('1.4.197') }) - - it('does not promote a disconnected version when a connection opens during hydration', async () => { - let finishHydration = () => {} - logStore.hydrate.mockReturnValue( - new Promise((resolve) => { - finishHydration = resolve - }) - ) - const context = createContext() - context.setConnection('disconnected', 1_000) - const device = createNativeDiagnosticsOperations(host, context, '1.4.197') - const pendingReport = device.report() - context.setConnection('connected', 1_000) - finishHydration() - const { report } = await pendingReport - expect(report).toContain('State: connected') - expect(report).toContain('Host Orca version: unknown') - expect(report).not.toContain('1.4.197') - }) }) diff --git a/mobile/src/diagnostics/native-render-log.test.ts b/mobile/src/diagnostics/native-render-log.test.ts index b6a82eb4b6f..fb00974e5af 100644 --- a/mobile/src/diagnostics/native-render-log.test.ts +++ b/mobile/src/diagnostics/native-render-log.test.ts @@ -1,6 +1,5 @@ import AsyncStorage from '@react-native-async-storage/async-storage' import { beforeEach, expect, it, vi } from 'vitest' -import type { HostProfile } from '../transport/hosts/host-profile' vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) vi.mock('expo-constants', () => ({ default: { expoConfig: { version: '0.0.60' } } })) @@ -8,22 +7,6 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(), setItem: vi.fn() } })) -const context = { - getState: () => 'disconnected' as const, - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - getActivePath: () => 'lan' as const, - getPendingPath: () => null -} -const pairedHost: HostProfile = { - id: 'desktop', - name: 'Desktop', - endpoint: 'ws://desktop.invalid:6768', - deviceToken: 'device-secret', - publicKeyB64: 'key', - lastConnected: 0 -} - beforeEach(() => { vi.resetModules() const storage = new Map() @@ -33,30 +16,6 @@ beforeEach(() => { }) }) -it.each([null, pairedHost])( - 'retains a native render failure in the copied report after restart, host %s', - async (host) => { - const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') - const { connectionLogStore } = await import('./connection/persisted-connection-log-store') - const failure = new Error('Private prompt\n at PRIVATE PROMPT\ntoken=do-not-share') - failure.stack = `${failure.name}: ${failure.message}\n at UnauthorizedAboutRoute (/Users/private/project/about.tsx:12:3)` - recordNativeRenderError(failure, 'about') - await connectionLogStore.hydrate(NATIVE_APP_LOG_ID) - await connectionLogStore.flush() - vi.resetModules() - - const { createNativeDiagnosticsOperations } = await import('./native-diagnostics-operations') - const { report, incidentId } = await createNativeDiagnosticsOperations(host, context).report() - expect(report).toContain('Native screen failed to render') - expect(report).toContain('UnauthorizedAboutRoute') - expect(report).not.toContain('Private prompt') - expect(report).not.toContain('PRIVATE PROMPT') - expect(report).not.toContain('do-not-share') - expect(report).not.toContain('/Users/private') - expect(incidentId).toBeNull() - } -) - it('keeps a log entry when the thrown error has an unreadable stack', async () => { const { recordNativeRenderError, NATIVE_APP_LOG_ID } = await import('./native-render-log') const failure = new Error('bad stack') diff --git a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx b/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx deleted file mode 100644 index b1c00c11225..00000000000 --- a/mobile/src/diagnostics/use-troubleshoot-diagnostics.test.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as HostReachability from './host-reachability' - -const hosts = vi.hoisted(() => ({ - catalog: vi.fn<() => Promise<{ endpoint: string }[]>>(), - profiles: vi.fn<() => Promise<{ name: string; endpoint: string }[]>>() -})) -vi.mock('react-native', () => ({ Platform: { OS: 'ios', Version: '27' } })) -vi.mock('../transport/hosts/host-store', () => ({ - loadHostCatalog: hosts.catalog, - loadHosts: hosts.profiles -})) -vi.mock('./host-reachability', async (importOriginal) => ({ - ...(await importOriginal()), - testHostReachability: async () => true -})) - -import { useTroubleshootDiagnostics } from './use-troubleshoot-diagnostics' - -let tree: ReactTestRenderer | undefined -const state: { current: ReturnType | null } = { current: null } -function Harness() { - state.current = useTroubleshootDiagnostics() - return null -} - -afterEach(async () => { - await act(async () => tree?.unmount()) - state.current = null - vi.resetAllMocks() - vi.unstubAllGlobals() -}) - -describe('troubleshooting paired endpoints', () => { - it('retains saved port advice after a run when the host credential is unavailable', async () => { - hosts.catalog.mockResolvedValue([{ endpoint: 'ws://desktop.local:6769' }]) - hosts.profiles.mockResolvedValue([]) - vi.stubGlobal('fetch', async () => ({ ok: true })) - await act(async () => { - tree = create(createElement(Harness)) - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - await act(async () => { - await state.current?.runDiagnostics() - }) - expect(state.current?.hostEndpoints).toEqual(['ws://desktop.local:6769']) - }) -}) diff --git a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx b/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx deleted file mode 100644 index 89981c8538c..00000000000 --- a/mobile/src/dictation/use-mobile-dictation-silence-stop.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createMobileDictationMeter } from '../hooks/mobile-dictation-meter' -import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop' - -// 16 kHz 16-bit little-endian PCM, as both shells deliver it. -function pcm(milliseconds: number, amplitude: number): Uint8Array { - const samples = (16_000 * milliseconds) / 1000 - const bytes = new Uint8Array(samples * 2) - const view = new DataView(bytes.buffer) - for (let index = 0; index < samples; index += 1) { - view.setInt16(index * 2, index % 2 === 0 ? amplitude : -amplitude, true) - } - return bytes -} - -function record(dictationMode: string) { - const meter = createMobileDictationMeter() - meter.start() - const dictation = { isRecording: true, meter } - const stop = vi.fn() - const showToast = vi.fn() - function Probe() { - useMobileDictationSilenceStop(dictation, dictationMode, stop, showToast) - return null - } - let renderer: ReactTestRenderer | undefined - act(() => { - renderer = create(createElement(Probe)) - }) - // Feed the mic the way the page shell drains it: 500 ms batches at the given amplitude. - const play = (seconds: number, amplitude: number) => { - for (let batch = 0; batch < seconds * 2; batch += 1) { - act(() => { - meter.push(pcm(500, amplitude)) - vi.advanceTimersByTime(500) - }) - } - } - return { stop, showToast, play, unmount: () => act(() => renderer?.unmount()) } -} - -describe('dictation silence stop', () => { - beforeEach(() => vi.useFakeTimers()) - afterEach(() => vi.useRealTimers()) - - it('never stops a hold-mode recording', () => { - const { stop, unmount } = record('hold') - act(() => { - vi.advanceTimersByTime(120_000) - }) - expect(stop).not.toHaveBeenCalled() - unmount() - }) -}) diff --git a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx b/mobile/src/files/MobileMarkdownPreviewImage.test.tsx deleted file mode 100644 index 3bd696f63bd..00000000000 --- a/mobile/src/files/MobileMarkdownPreviewImage.test.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { createElement } from 'react' -import type { ImageProps } from 'react-native' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, expect, it, vi } from 'vitest' -import { MobileMarkdownPreviewImage } from './MobileMarkdownPreviewImage' - -vi.mock('react-native', () => ({ - ActivityIndicator: 'ActivityIndicator', - Image: Object.assign((props: ImageProps) => createElement('Image', props), { - getSize: (_uri: string, loaded: (width: number, height: number) => void) => loaded(600, 220) - }), - Pressable: 'Pressable', - StyleSheet: { create: (styles: unknown) => styles }, - Text: 'Text', - View: 'View' -})) -vi.mock('../components/MobileStateView', () => ({ MobileLoadErrorState: 'LoadError' })) -vi.mock('../session/native-chat/visual/MobileNativeChatImageViewer', () => ({ - MobileNativeChatImageViewer: 'ImageViewer' -})) -vi.mock('../session/native-chat/visual/MobileImageViewerActions', () => ({ - MobileImageViewerActions: 'ImageViewerActions' -})) -const loader = vi.hoisted(() => vi.fn()) -vi.mock('./mobile-markdown-image-source', () => ({ loadMarkdownPreviewImage: loader })) -let tree: ReactTestRenderer | null = null -afterEach(() => { - act(() => tree?.unmount()) - tree = null - vi.resetAllMocks() -}) -const props = { - client: null, - worktreeId: 'wt', - documentPath: 'notes.md', - href: 'a.png', - alt: 'Architecture' -} - -it('retries a refused image without hiding the surrounding document', async () => { - loader - .mockRejectedValueOnce(new Error('Unable to reach the desktop filesystem')) - .mockResolvedValueOnce('data:image/png;base64,cG5n') - await act(async () => { - tree = create(createElement(MobileMarkdownPreviewImage, props)) - }) - expect(tree!.root.find((node) => String(node.type) === 'LoadError').props.error).toContain( - 'Unable to reach' - ) - await act(async () => - tree!.root.find((node) => String(node.type) === 'LoadError').props.onRetry() - ) - expect(tree!.root.find((node) => String(node.type) === 'Image').props.source.uri).toBe( - 'data:image/png;base64,cG5n' - ) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-state.test.ts b/mobile/src/source-control/review/mobile-diff-review-state.test.ts index e5a4fbdd4a3..20e73ecedc3 100644 --- a/mobile/src/source-control/review/mobile-diff-review-state.test.ts +++ b/mobile/src/source-control/review/mobile-diff-review-state.test.ts @@ -31,14 +31,4 @@ describe('mobile diff review state', () => { expect(merged.completedAt).toBeUndefined() }) - - it('keeps completion when refreshed identities are unchanged', () => { - const reviewed = markMobileDiffReviewFileReviewed(createMobileDiffReviewState(1), descriptor, 5) - const completed = completeMobileDiffReviewState(reviewed, 6) - - const merged = mergeMobileDiffReviewState(completed, [descriptor], 8) - - expect(merged.completedAt).toBe(6) - expect(merged.files[descriptor.key]?.reviewedAt).toBe(5) - }) }) diff --git a/mobile/src/source-control/review/optimistic-write-sequence.test.ts b/mobile/src/source-control/review/optimistic-write-sequence.test.ts deleted file mode 100644 index 68e619cf5ad..00000000000 --- a/mobile/src/source-control/review/optimistic-write-sequence.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createOptimisticField } from './optimistic-write-sequence' - -describe('OptimisticField — last-intent-wins', () => { - it('reverts only the latest write on failure', () => { - const field = createOptimisticField() - const seqA = field.begin(true) - const seqB = field.begin(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqA)).toBe(false) - expect(field.resolve(false)).toBe(false) - - expect(field.settleFailure(seqB)).toBe(true) - expect(field.resolve(true)).toBe(true) - }) - - it('a stale failure does not clear a newer optimistic value', () => { - const field = createOptimisticField() - const seqOld = field.begin('old') - field.begin('new') - expect(field.resolve('auth')).toBe('new') - expect(field.settleFailure(seqOld)).toBe(false) - expect(field.resolve('auth')).toBe('new') - }) -}) diff --git a/mobile/src/stats/home-stats-total.test.ts b/mobile/src/stats/home-stats-total.test.ts deleted file mode 100644 index daff818e1fa..00000000000 --- a/mobile/src/stats/home-stats-total.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { totalHomeStats } from './home-stats-total' - -describe('totalHomeStats', () => { - it('sums every desktop instead of letting the last reply win', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - }, - ['host-1', 'host-2'] - ) - expect(total).toEqual({ totalAgentsSpawned: 15, totalPRsCreated: 3, totalAgentTimeMs: 90_000 }) - }) - - it('leaves out a desktop that is no longer paired', () => { - const byHost = { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': { totalAgentsSpawned: 5, totalPRsCreated: 1, totalAgentTimeMs: 30_000 } - } - expect(totalHomeStats(byHost, ['host-1'])?.totalAgentsSpawned).toBe(10) - expect(totalHomeStats(byHost, [])).toBeNull() - }) - - it('has no stats until a desktop sends a number', () => { - expect(totalHomeStats({}, ['host-1'])).toBeNull() - // A desktop without stats answers `{}`; that is not a row of zeros. - expect(totalHomeStats({ 'host-1': {} }, ['host-1'])).toBeNull() - }) - - it('skips a malformed reply and keeps the other desktops', () => { - const total = totalHomeStats( - { - 'host-1': { totalAgentsSpawned: 10, totalPRsCreated: 2, totalAgentTimeMs: 60_000 }, - 'host-2': null, - 'host-3': { totalAgentsSpawned: 'lots' }, - 'host-4': { totalAgentsSpawned: Number.NaN, totalPRsCreated: 1 } - }, - ['host-1', 'host-2', 'host-3', 'host-4'] - ) - expect(total).toEqual({ totalAgentsSpawned: 10, totalPRsCreated: 3, totalAgentTimeMs: 60_000 }) - }) -}) diff --git a/mobile/src/tasks/github-pr-file-diff.test.ts b/mobile/src/tasks/github-pr-file-diff.test.ts index 99e1f0ac6c4..5120187262b 100644 --- a/mobile/src/tasks/github-pr-file-diff.test.ts +++ b/mobile/src/tasks/github-pr-file-diff.test.ts @@ -3,44 +3,6 @@ import { describe, expect, it } from 'vitest' import { buildGitHubPrFileDiffLines, buildGitHubPrFileDiffPreview } from './github-pr-file-diff' describe('buildGitHubPrFileDiffLines', () => { - it('preserves context and marks added and removed lines', () => { - expect(buildGitHubPrFileDiffLines('one\ntwo\nthree\n', 'one\ntoo\nthree\n')).toEqual([ - { - key: '0:context:1:1', - kind: 'context', - oldLineNumber: 1, - newLineNumber: 1, - text: 'one' - }, - { - key: '1:removed:2', - kind: 'removed', - oldLineNumber: 2, - text: 'two' - }, - { - key: '2:added:2', - kind: 'added', - newLineNumber: 2, - text: 'too' - }, - { - key: '3:context:3:3', - kind: 'context', - oldLineNumber: 3, - newLineNumber: 3, - text: 'three' - } - ]) - }) - - it('shows added files without a fake empty original line', () => { - expect(buildGitHubPrFileDiffLines('', 'first\nsecond')).toEqual([ - { key: '0:added:1', kind: 'added', newLineNumber: 1, text: 'first' }, - { key: '1:added:2', kind: 'added', newLineNumber: 2, text: 'second' } - ]) - }) - it('keeps all lines for large files without exact diff truncation', () => { const original = Array.from({ length: 500 }, (_, index) => `old-${index}`).join('\n') const modified = Array.from({ length: 500 }, (_, index) => `new-${index}`).join('\n') diff --git a/mobile/src/tasks/jira-mobile-connection.test.ts b/mobile/src/tasks/jira-mobile-connection.test.ts deleted file mode 100644 index d6674d69455..00000000000 --- a/mobile/src/tasks/jira-mobile-connection.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { extractJiraConnection, reconcileJiraConnection } from './jira-mobile-connection' - -const siteA = { - id: 'site-a', - siteUrl: 'https://a.atlassian.net', - email: 'me@example.com', - displayName: 'Site A', - accountId: 'acc-1' -} -const siteB = { ...siteA, id: 'site-b', siteUrl: 'https://b.atlassian.net', displayName: 'Site B' } - -describe('Jira connection compatibility', () => { - it('keeps the phone selection when desktop status is refreshed', () => { - const next = extractJiraConnection({ - connected: true, - sites: [siteA, siteB], - selectedSiteId: 'site-a' - }) - expect(reconcileJiraConnection({ ...next, selection: 'site-b' }, next).selection).toBe('site-b') - expect(reconcileJiraConnection({ ...next, selection: 'all' }, next).selection).toBe('all') - expect(reconcileJiraConnection({ ...next, selection: 'gone' }, next).selection).toBe('site-a') - }) -}) diff --git a/mobile/src/tasks/mobile-jira-task-source.test.ts b/mobile/src/tasks/mobile-jira-task-source.test.ts index 80d09b629f6..7056fbe0009 100644 --- a/mobile/src/tasks/mobile-jira-task-source.test.ts +++ b/mobile/src/tasks/mobile-jira-task-source.test.ts @@ -40,19 +40,4 @@ describe('mobile Jira task requests', () => { ).resolves.toEqual({ issue, comments: [] }) } }) - - it('surfaces issue failures even when comments can be read', async () => { - const sendRequest = vi.fn(async (method: string) => - method === 'jira.getIssue' - ? { - id: 'jira-test', - ok: false as const, - error: { code: 'UNAVAILABLE', message: 'Issue permission denied' } - } - : { id: 'jira-test', ok: true as const, result: [] } - ) - await expect(fetchJiraIssueDetail({ sendRequest }, { key: issue.key })).rejects.toThrow( - 'Issue permission denied' - ) - }) }) diff --git a/mobile/src/tasks/setup-hook-trust.test.ts b/mobile/src/tasks/setup-hook-trust.test.ts deleted file mode 100644 index 326cd96862b..00000000000 --- a/mobile/src/tasks/setup-hook-trust.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { isSetupHookTrusted } from './setup-hook-trust' -import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types' - -describe('setup hook trust', () => { - it('trusts a setup script only when the approved hash matches', () => { - const trust: PersistedTrustedOrcaHooks = { - 'repo-1': { setup: { contentHash: 'hash-1', approvedAt: 1000 } } - } - - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-1')).toBe(true) - expect(isSetupHookTrusted(trust, [{ id: 'repo-1' }], 'repo-1', 'hash-2')).toBe(false) - }) -}) diff --git a/mobile/src/tasks/smart-source-paste-intent.test.ts b/mobile/src/tasks/smart-source-paste-intent.test.ts deleted file mode 100644 index 39c53a499b7..00000000000 --- a/mobile/src/tasks/smart-source-paste-intent.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { deriveRepoSlug, resolvePasteIntent } from './smart-source-paste-intent' - -describe('resolvePasteIntent', () => { - it('rejects oversized paste intents before any exact lookup', () => { - expect( - resolvePasteIntent(`https://github.com/acme/widgets/issues/12/${'x'.repeat(2048)}`) - ).toBeNull() - }) -}) - -describe('deriveRepoSlug', () => { - it('preserves an Enterprise upstream host', () => { - expect( - deriveRepoSlug({ - upstream: { owner: 'up', repo: 'stream', host: 'github.corp.example' } - }) - ).toEqual({ owner: 'up', repo: 'stream', host: 'github.corp.example' }) - }) -}) diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts index 52ce8faf499..ba31171486e 100644 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ b/mobile/src/tasks/worktree-create-retry.test.ts @@ -40,25 +40,6 @@ function scriptedClient( return client } -describe('createWorktreeWithNameRetry', () => { - it('falls back to the client candidate when an older host omits displayName', async () => { - const attempts: Attempt[] = [] - const client = scriptedClient( - [{ errorMessage: 'already exists locally' }, { id: 'wt-legacy' }], - attempts - ) - - await expect( - createWorktreeWithNameRetry({ - client, - baseName: 'topic', - buildParams: (name) => ({ repo: 'id:r', name }), - worktreeCreateIdempotency: false - }) - ).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' }) - }) -}) - describe('createWorktreeWithNameRetry parent', () => { it('attaches every collision candidate to the same parent', async () => { const attempts: Attempt[] = [] diff --git a/mobile/src/terminal/mobile-terminal-query-reply.test.ts b/mobile/src/terminal/mobile-terminal-query-reply.test.ts deleted file mode 100644 index 2bda14d11d5..00000000000 --- a/mobile/src/terminal/mobile-terminal-query-reply.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' - -import { PROGRAM_STATUS_QUERY_REPLY } from '../../../src/shared/program-status/protocol' -import { sendMobileTerminalQueryReply } from './mobile-terminal-query-reply' - -function createClient() { - return { - sendRequest: vi.fn().mockResolvedValue({ - id: '1', - ok: true, - result: { send: { accepted: true, bytesWritten: 6 } }, - _meta: { runtimeId: 'runtime-1' } - }), - subscribe: () => () => {}, - updateTerminalSubscriptionViewport: () => {}, - getState: () => 'connected', - getReconnectAttempt: () => 0, - getLastConnectedAt: () => null, - onStateChange: () => () => {}, - notifyForeground: () => {}, - close: () => {} - } satisfies RpcClient -} - -describe('sendMobileTerminalQueryReply', () => { - it.each([ - ['disconnected', false, new Set(['terminal-1']), '\x1b[3;4R', 'terminal-1'], - ['unsubscribed', true, new Set(), '\x1b[3;4R', 'terminal-1'], - ['stale handle', true, new Set(['terminal-2']), '\x1b[3;4R', 'terminal-1'], - ['ordinary input', true, new Set(['terminal-1']), 'a', 'terminal-1'] - ])('does not send %s data', async (_case, connected, subscribedTerminals, bytes, handle) => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes, - client, - clientId: 'mobile-1', - connected, - handle, - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: true, - subscribedTerminals - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - // Older hosts strip inputKind and would treat query replies as floor-taking user input. - it('does not send to a host that has not advertised query-reply input support', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: '\x1b[3;4R', - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: false, - hostSupportsProgramStatus: true, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - it('does not answer program status for a host that cannot read its reports', async () => { - const client = createClient() - - await expect( - sendMobileTerminalQueryReply({ - bytes: PROGRAM_STATUS_QUERY_REPLY, - client, - clientId: 'mobile-1', - connected: true, - handle: 'terminal-1', - hostSupportsQueryReplyInput: true, - hostSupportsProgramStatus: false, - subscribedTerminals: new Set(['terminal-1']) - }) - ).resolves.toBe(false) - expect(client.sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts index 63611774fef..9b22756d32f 100644 --- a/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts +++ b/mobile/src/terminal/session/mobile-terminal-inventory-request.test.ts @@ -6,19 +6,6 @@ describe('MobileTerminalInventoryRequest', () => { vi.restoreAllMocks() }) - it('starts fresh after the shared request settles or rejects', async () => { - const requests = new MobileTerminalInventoryRequest() - const failure = new Error('transport lost') - - await expect( - requests.run(true, async () => { - throw failure - }) - ).rejects.toBe(failure) - await expect(requests.run(true, async () => true)).resolves.toBe(true) - await expect(requests.run(true, async () => false)).resolves.toBe(false) - }) - it('fences a response after its route activation is replaced', async () => { const oldResponse = Promise.withResolvers() const applied: string[] = [] diff --git a/mobile/tsconfig.test.json b/mobile/tsconfig.test.json index 2ccc0961a28..95df069b933 100644 --- a/mobile/tsconfig.test.json +++ b/mobile/tsconfig.test.json @@ -8,7 +8,6 @@ // Outside this RN program: RN's numeric timers and Expo's process.env break the desktop graphs these // tests import. The roots of tsconfig.test.node.json are checked there against emitted // declarations; the others are legacy runtime-only coverage whose test bodies nothing typechecks. - "src/components/WorktreeAgentList.runtime-lineage.test.tsx", "src/transport/mobile-relay-browser-cancel-budget.test.ts" ] } diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift index b9987fb3521..e848fe93135 100644 --- a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/AuthenticatedConnectionHangupMonitorTests.swift @@ -5,21 +5,6 @@ import XCTest final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { - func testRegistrationFailureClosesEventQueueOnce() { - let closes = DescriptorCloseRecorder() - - XCTAssertThrowsError( - try AuthenticatedConnectionHangupMonitor( - fileDescriptor: 42, - registerEvents: { _, _, _ in .EBADF }, - closeDescriptor: { descriptor in - closes.recordAndClose(descriptor) - }, - onHangup: {} - ) - ) - XCTAssertEqual(closes.count, 1) - } func testReportsPeerCloseWhileRequestHandlingIsBlocked() throws { let descriptors = try makeSocketPair() @@ -52,54 +37,7 @@ final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { close(descriptors.local) } - func testReadableDataDoesNotLookLikeHangup() throws { - let descriptors = try makeSocketPair() - let hangup = expectation(description: "peer hangup") - let callbacks = CallbackRecorder() - let events = CallbackRecorder() - let monitor = try AuthenticatedConnectionHangupMonitor( - fileDescriptor: descriptors.local, - onEvent: { - events.record() - }, - onHangup: { - callbacks.record() - hangup.fulfill() - } - ) - monitor.start() - var byte: UInt8 = 7 - XCTAssertEqual(write(descriptors.peer, &byte, 1), 1) - usleep(50_000) - XCTAssertEqual(callbacks.count, 0) - XCTAssertEqual(events.count, 0) - close(descriptors.peer) - wait(for: [hangup], timeout: 1) - XCTAssertEqual(events.count, 1) - - monitor.cancel() - close(descriptors.local) - } - - func testCancelPreventsLaterHangupCallback() throws { - let descriptors = try makeSocketPair() - let hangup = expectation(description: "peer hangup") - hangup.isInverted = true - let monitor = try AuthenticatedConnectionHangupMonitor( - fileDescriptor: descriptors.local, - onHangup: { - hangup.fulfill() - } - ) - monitor.start() - - monitor.cancel() - close(descriptors.peer) - - wait(for: [hangup], timeout: 0.1) - close(descriptors.local) - } func testStartReportsHangupQueuedAfterSuccessfulSetup() throws { let descriptors = try makeSocketPair() @@ -120,43 +58,7 @@ final class AuthenticatedConnectionHangupMonitorTests: XCTestCase { } } -private final class CallbackRecorder: @unchecked Sendable { - private let lock = NSLock() - private var recordedCount = 0 - var count: Int { - lock.lock() - defer { lock.unlock() } - return recordedCount - } - - func record() { - lock.lock() - recordedCount += 1 - lock.unlock() - } -} - -private final class DescriptorCloseRecorder: @unchecked Sendable { - private let lock = NSLock() - private var closeCount = 0 - - var count: Int { - lock.lock() - defer { lock.unlock() } - return closeCount - } - - func recordAndClose(_ descriptor: Int32) { - lock.lock() - closeCount += 1 - let shouldClose = closeCount == 1 - lock.unlock() - if shouldClose { - close(descriptor) - } - } -} private func makeSocketPair() throws -> (local: Int32, peer: Int32) { var descriptors: [Int32] = [0, 0] diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift deleted file mode 100644 index 4a512b7bd58..00000000000 --- a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/SyntheticMouseClickDeliveryTests.swift +++ /dev/null @@ -1,231 +0,0 @@ -import XCTest -@testable import OrcaComputerUseMacOSCore - -final class SyntheticMouseClickDeliveryTests: XCTestCase { - func testScrollAndDragFenceTheOriginBeforeMoveAndBeforeMutation() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let sibling = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 202) - for drag in [false, true] { - for loss in [SyntheticMouseClickDelivery.RecipientObservation.focused(sibling), .unavailable, .dismissed] { - for afterMove in [false, true] { - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = afterMove ? [.focused(target), loss] : [loss] - var posted: [String] = [] - let observe = { observations.isEmpty ? .unavailable : observations.removeFirst() } - XCTAssertThrowsError(try { - if drag { - try SyntheticMouseClickDelivery.deliverDrag( - move: "move", down: "down", dragged: ["drag"], up: "up", - target: target, currentObservation: observe, - post: { posted.append($0) }, pause: { _ in } - ) - } else { - try SyntheticMouseClickDelivery.deliverScroll( - move: "move", wheel: "wheel", - target: target, currentObservation: observe, - post: { posted.append($0) }, pause: { _ in } - ) - } - }()) - XCTAssertEqual(posted, afterMove ? ["move"] : []) - } - } - } - } - - func testRecipientChangeBeforeMouseDownPostsNoClickAndReportsBothWindows() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { .focused(intruder) }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 0) - ) - } - XCTAssertEqual(posted, [.move]) - } - - func testFinalMouseUpMayDismissTheTargetWithoutFailingTheClick() throws { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = [.focused(target), .dismissed] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { observations.removeFirst() }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testFinalUnavailableObservationRemainsFailClosed() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var observations: [SyntheticMouseClickDelivery.RecipientObservation] = [.focused(target), .unavailable] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { observations.removeFirst() }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: nil, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testFinalMouseUpRejectsADifferentFocusedRecipient() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [.move, .buttonDown(pressIndex: 1), .buttonUp(pressIndex: 1)]) - } - - func testRecipientChangeBeforeLaterPressReportsCompletedPresses() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients = [target, target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - .focused(recipients.removeFirst()) - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testRecipientChangeAfterIntermediateMouseUpStopsBeforeNextPress() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - let intruder = SyntheticMouseClickDelivery.Recipient(ownerPID: 52, windowID: 202) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, intruder] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: intruder, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testIntermediateMouseUpDismissalStopsBeforeNextPress() { - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var recipients: [SyntheticMouseClickDelivery.Recipient?] = [target, nil] - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError( - try SyntheticMouseClickDelivery.deliver( - clickCount: 2, - target: target, - currentObservation: { - recipients.removeFirst().map(SyntheticMouseClickDelivery.RecipientObservation.focused) ?? .dismissed - }, - makeEvent: { $0 }, - post: { posted.append($0) }, - pause: { _ in } - ) - ) { error in - XCTAssertEqual( - error as? SyntheticMouseClickDelivery.FenceFailure, - .recipientChanged(expected: target, actual: nil, deliveredPresses: 1) - ) - } - XCTAssertEqual(posted, [ - .move, - .buttonDown(pressIndex: 1), - .buttonUp(pressIndex: 1), - ]) - } - - func testButtonPairIsPreparedBeforeMouseDownPosts() { - enum PreparationFailure: Error { case mouseUp } - let target = SyntheticMouseClickDelivery.Recipient(ownerPID: 41, windowID: 101) - var posted: [SyntheticMouseClickDelivery.Step] = [] - - XCTAssertThrowsError(try SyntheticMouseClickDelivery.deliver( - clickCount: 1, - target: target, - currentObservation: { .focused(target) }, - makeEvent: { step in - if case .buttonUp = step { throw PreparationFailure.mouseUp } - return step - }, - post: { posted.append($0) }, - pause: { _ in } - )) - XCTAssertEqual(posted, [.move]) - } -} diff --git a/skill-guides/orca-cli.md b/skill-guides/orca-cli.md index bbf93088124..523f0ec335b 100644 --- a/skill-guides/orca-cli.md +++ b/skill-guides/orca-cli.md @@ -153,18 +153,6 @@ Lineage rules: - To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`. - `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or "branch from current". -Per-workspace environment recipes: `ORCA vm recipe list --repo id: --json` lists the -recipes `--recipe` accepts. `ORCA worktree create --name task --recipe --no-parent --json` -runs the recipe's create step and creates the workspace on the new environment's Orca server. Run -it on the computer whose Orca desktop app owns the recipe; omit `--environment` and `--pairing-code`. -It can take minutes; without `--json`, named progress steps print to stderr. Provisioned-root recipes -own setup, so `--setup run` and `--run-hooks` are refused for them. Add `--agent`, `--prompt`, -`--model`, or `--effort` to launch on the new environment. The result's `recipe.environmentId` is the -environment for follow-up commands (`--environment id:`). On failure the error code is -`recipe_workspace_create_failed`; `data.phase` names the failed step and `data.environment` says -whether Orca destroyed the new environment. Never retry with `--retry-launch`; after a failed agent -launch, use the returned `agent launch` recovery command against the existing workspace. - Agent/setup flags: ```text diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 8187a43ec48..cd92e95fc84 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -36,7 +36,8 @@ ORCA orchestration worker-start --spec "" --worktree current --agent codex - If a receipt has `next`, follow it. When Orca has nothing for you, end your turn. - `--worktree current` uses your workspace. Use a new one only when the user - asks or sharing would conflict: + asks or sharing would conflict: `--worktree new-child --name ` + nests it under yours. For one with no parent, use `--worktree new-top-level --repo id: --name ` (`ORCA repo list --json` gives the id). If nothing needs to come back to you (the user will work in those chats), don't start workers; per workspace run diff --git a/skill-guides/orchestration/references/placement-and-remote.md b/skill-guides/orchestration/references/placement-and-remote.md index e633f12bd90..1ea5a060559 100644 --- a/skill-guides/orchestration/references/placement-and-remote.md +++ b/skill-guides/orchestration/references/placement-and-remote.md @@ -17,11 +17,11 @@ when requesting a child of the current workspace. # Child of the current worktree. ORCA orchestration worker-start --task --worktree new-child --agent codex --setup run -# On a connected server; the Run stays on yours. -ORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run +# On a connected server, nested under your workspace; the Run stays on yours. +ORCA orchestration worker-start --task --on --worktree new-child --repo --name --agent codex --setup run -# On a connected server, nested under your workspace in the sidebar. -ORCA orchestration worker-start --task --on --worktree new-child --repo --name --agent codex --setup run +# On a connected server, with no parent. +ORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run ``` With `--on`, both `new-child` and `new-top-level` need `--repo` naming a diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 4d3bb13d694..9c75ce5f704 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -381,18 +381,6 @@ const ORCA_CLI_MARKDOWN = [ "- To move an existing worktree under a different parent, or make it top-level, use `worktree set` with `--parent-worktree ` or `--no-parent`.", "- `--no-parent` only controls Orca lineage; it does not choose the Git base. For independent top-level work, omit `--base-branch` so Orca uses the repo default base, or explicitly pass the repo default base. Never base it on the current feature branch unless the user asks for stacked work or \"branch from current\".", "", - "Per-workspace environment recipes: `ORCA vm recipe list --repo id: --json` lists the", - "recipes `--recipe` accepts. `ORCA worktree create --name task --recipe --no-parent --json`", - "runs the recipe's create step and creates the workspace on the new environment's Orca server. Run", - "it on the computer whose Orca desktop app owns the recipe; omit `--environment` and `--pairing-code`.", - "It can take minutes; without `--json`, named progress steps print to stderr. Provisioned-root recipes", - "own setup, so `--setup run` and `--run-hooks` are refused for them. Add `--agent`, `--prompt`,", - "`--model`, or `--effort` to launch on the new environment. The result's `recipe.environmentId` is the", - "environment for follow-up commands (`--environment id:`). On failure the error code is", - "`recipe_workspace_create_failed`; `data.phase` names the failed step and `data.environment` says", - "whether Orca destroyed the new environment. Never retry with `--retry-launch`; after a failed agent", - "launch, use the returned `agent launch` recovery command against the existing workspace.", - "", "Agent/setup flags:", "", "```text", @@ -3971,7 +3959,8 @@ const ORCHESTRATION_MARKDOWN = [ "- If a receipt has `next`, follow it. When Orca has nothing for you, end your", " turn.", "- `--worktree current` uses your workspace. Use a new one only when the user", - " asks or sharing would conflict:", + " asks or sharing would conflict: `--worktree new-child --name `", + " nests it under yours. For one with no parent, use", " `--worktree new-top-level --repo id: --name `", " (`ORCA repo list --json` gives the id). If nothing needs to come back to you", " (the user will work in those chats), don't start workers; per workspace run", @@ -4127,11 +4116,11 @@ const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = [ "# Child of the current worktree.", "ORCA orchestration worker-start --task --worktree new-child --agent codex --setup run", "", - "# On a connected server; the Run stays on yours.", - "ORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run", + "# On a connected server, nested under your workspace; the Run stays on yours.", + "ORCA orchestration worker-start --task --on --worktree new-child --repo --name --agent codex --setup run", "", - "# On a connected server, nested under your workspace in the sidebar.", - "ORCA orchestration worker-start --task --on --worktree new-child --repo --name --agent codex --setup run", + "# On a connected server, with no parent.", + "ORCA orchestration worker-start --task --on --worktree new-top-level --repo --name --agent codex --setup run", "```", "", "With `--on`, both `new-child` and `new-top-level` need `--repo` naming a", diff --git a/src/cli/handlers/opencode-account-login-command.ts b/src/cli/handlers/opencode-account-login-command.ts index eb9a88f9113..52eeac1cdd2 100644 --- a/src/cli/handlers/opencode-account-login-command.ts +++ b/src/cli/handlers/opencode-account-login-command.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { spawnProcess } from '@orca/process-host' import { forceTerminateProcessTree, @@ -212,7 +212,7 @@ async function waitForProbe(promise: Promise, ms: number): Promise clearTimeout(timer)) } -function killProbeRoot(child: ChildProcessHandle, signal?: NodeJS.Signals): void { +function killProbeRoot(child: ChildProcess, signal?: NodeJS.Signals): void { try { child.kill(signal) } catch { diff --git a/src/cli/handlers/vm-recipe-list.ts b/src/cli/handlers/vm-recipe-list.ts deleted file mode 100644 index f481fcebb49..00000000000 --- a/src/cli/handlers/vm-recipe-list.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { CommandHandler } from '../dispatch' -import type { RecipeCatalogListing } from '../../shared/recipe-workspace-create-progress' -import { assertRecipeHost } from './worktree-create-recipe' -import { getOptionalStringFlag } from '../flags' -import { printResult } from '../format' - -export function formatRecipeListing(result: { repos: RecipeCatalogListing[] }): string { - if (result.repos.length === 0) { - return 'No environment recipes. Add environmentRecipes to a repo orca.yaml.' - } - const lines: string[] = [] - for (const repo of result.repos) { - lines.push(`${repo.repoName} (${repo.repoPath})`) - if (repo.recipes.length === 0) { - lines.push(' no recipes') - } - for (const recipe of repo.recipes) { - const destroy = recipe.destroyDisabled - ? 'destroy disabled' - : recipe.steps.includes('destroy') - ? 'destroys on removal' - : 'no destroy step' - const timeouts = recipe.timeoutSeconds - ? Object.entries(recipe.timeoutSeconds) - .map(([step, seconds]) => `${step} ${seconds}s`) - .join(', ') - : '' - lines.push( - ` ${recipe.id} ${recipe.name} [${recipe.checkoutMode}; ${destroy}${timeouts ? `; timeouts ${timeouts}` : ''}]` - ) - if (recipe.description) { - lines.push(` ${recipe.description}`) - } - } - for (const diagnostic of repo.diagnostics) { - lines.push( - ` warning: environmentRecipes[${diagnostic.index}]${diagnostic.field ? `.${diagnostic.field}` : ''}: ${diagnostic.message}` - ) - } - } - return lines.join('\n') -} - -export const VM_RECIPE_LIST_HANDLERS: Record = { - 'vm recipe list': async ({ flags, client, json }) => { - await assertRecipeHost(client) - const repo = getOptionalStringFlag(flags, 'repo') - const result = await client.call<{ repos: RecipeCatalogListing[] }>( - 'vmRecipe.list', - repo ? { repo } : {} - ) - printResult(result, json, formatRecipeListing) - } -} diff --git a/src/cli/handlers/worktree-create-recipe.ts b/src/cli/handlers/worktree-create-recipe.ts deleted file mode 100644 index 5082f02f2ea..00000000000 --- a/src/cli/handlers/worktree-create-recipe.ts +++ /dev/null @@ -1,191 +0,0 @@ -import type { RuntimeStatus, RuntimeWorktreeCreateResult } from '../../shared/runtime-types' -import { WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY } from '../../shared/host-runtime-capabilities' -import { - RECIPE_WORKSPACE_CREATE_FAILED_CODE, - RECIPE_WORKSPACE_CREATE_PHASES, - isRecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import { RuntimeClient, RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client' -import { - callAgentLaunch, - formatAgentLaunch, - getAgentLaunchCapabilities, - type CliAgentLaunch -} from '../agent-launch-request' -import { formatWorktreeShow, printResult } from '../format' -import { printHookWarning } from './worktree-removal-warnings' -import { printLineageSummary } from './worktree-lineage-summary' - -// Idle bound only: the host sends a keepalive every few seconds while the recipe runs, and the -// recipe's own timeoutSeconds (orca.yaml) bounds the whole create. -const RECIPE_CREATE_IDLE_TIMEOUT_MS = 600_000 - -type RecipeWorktreeCreateResult = RuntimeWorktreeCreateResult & { - recipe: { id: string; runtimeId: string; environmentId: string; checkoutMode: string } - environmentWarnings?: string[] -} - -function formatRecipeCreated(value: RecipeWorktreeCreateResult): string { - return [ - formatWorktreeShow(value), - `recipe: ${value.recipe.id} (${value.recipe.checkoutMode})`, - `environment: ${value.recipe.environmentId}`, - ...(value.environmentWarnings ?? []).map((warning) => `warning: ${warning}`) - ].join('\n') -} - -/** Recipes run only where the Orca desktop app owns them; refuse before anything is created. */ -export async function assertRecipeHost(client: RuntimeClient): Promise { - if (client.isRemote) { - throw new RuntimeClientError( - 'invalid_argument', - 'Run recipe commands on the computer whose Orca provisions the recipe, without --environment or --pairing-code.' - ) - } - const status = await client.call('status.get') - if (!status.result.capabilities?.includes(WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY)) { - throw new RuntimeClientError( - 'incompatible_runtime', - 'This Orca cannot create workspaces from recipes. Use the Orca desktop app on this computer, updated to the latest version.' - ) - } -} - -/** `orca worktree create --recipe`: the host that owns the recipe provisions, then adopts. */ -export async function createWorktreeOnRecipe(args: { - client: RuntimeClient - flags: Map - create: Record - recipeId: string - launch?: CliAgentLaunch - json: boolean -}): Promise { - const { client, create, recipeId, launch, json, flags } = args - const parentFlag = ['parent-worktree', 'parent-environment'].find((name) => flags.has(name)) - if (parentFlag) { - throw new RuntimeClientError( - 'invalid_argument', - `--${parentFlag} is not supported with --recipe yet: the new workspace lives on another host, so Orca records no parent for it.` - ) - } - if (flags.get('activate') === true) { - throw new RuntimeClientError( - 'invalid_argument', - '--activate is not supported with --recipe yet; open the new workspace from the Orca sidebar.' - ) - } - if (launch?.operationId) { - throw new RuntimeClientError( - 'invalid_argument', - 'Retry the agent with `orca agent launch` on the recipe environment and existing workspace; --retry-launch would provision another machine.' - ) - } - await assertRecipeHost(client) - if (!json) { - console.error( - `Creating "${String(create.name)}" on a new environment from recipe "${recipeId}". This can take several minutes; Ctrl+C stops it.` - ) - } - let created: RuntimeRpcSuccess - try { - created = await client.call( - 'worktree.create', - { - // --run-hooks implies activation, which a recipe workspace on another host cannot do yet. - ...create, - activate: false, - navigation: undefined, - recipeId, - ...(launch ? { createdWithAgent: launch.agent } : {}) - }, - { - timeoutMs: RECIPE_CREATE_IDLE_TIMEOUT_MS, - onProgress: ({ phase }) => { - if (!json && isRecipeWorkspaceCreatePhase(phase)) { - console.error(`- ${RECIPE_WORKSPACE_CREATE_PHASES[phase]}...`) - } - } - } - ) - } catch (error) { - if (error instanceof RuntimeClientError && error.code === RECIPE_WORKSPACE_CREATE_FAILED_CODE) { - throw new RuntimeClientError(error.code, error.message, { - ...(typeof error.data === 'object' && error.data !== null ? error.data : {}), - nextSteps: [ - `Validate the recipe with \`orca vm recipe doctor ${recipeId}\`.`, - 'Check Settings > Cloud VMs in Orca for an environment that still needs cleanup.' - ] - }) - } - throw error - } - printHookWarning(created.result, json) - if (!launch) { - printLineageSummary(created.result, json) - printResult(created, json, formatRecipeCreated) - return - } - const environmentId = created.result.recipe.environmentId - const worktree = `id:${created.result.worktree.id}` - const remote = new RuntimeClient( - client.userDataPath, - RECIPE_CREATE_IDLE_TIMEOUT_MS, - null, - `id:${environmentId}` - ) - const recoveryArgs = [ - 'agent', - 'launch', - '--agent', - launch.agent, - '--worktree', - worktree, - '--environment', - `id:${environmentId}` - ] - for (const name of ['model', 'effort', 'surface']) { - const value = flags.get(name) - if (typeof value === 'string') { - recoveryArgs.push(`--${name}`, value) - } - } - if (launch.prompt) { - recoveryArgs.push('--prompt', launch.prompt.text) - } - try { - const capabilities = await getAgentLaunchCapabilities(remote) - if (!capabilities) { - throw new RuntimeClientError( - 'incompatible_runtime', - 'Update Orca on the recipe-created environment to launch an agent.' - ) - } - const launched = await callAgentLaunch( - remote, - launch, - { - target: { kind: 'existing', worktree }, - presentation: 'background' - }, - capabilities, - recoveryArgs - ) - const result = { ...created.result, launch: launched.result } - printLineageSummary(result, json) - printResult( - { ...created, result }, - json, - (value) => `${formatRecipeCreated(value)}\n${formatAgentLaunch(value.launch)}` - ) - } catch (error) { - // The workspace and its environment exist; say so instead of implying nothing happened. - if (error instanceof RuntimeClientError) { - throw new RuntimeClientError(error.code, error.message, { - ...(typeof error.data === 'object' && error.data !== null ? error.data : {}), - recipeEnvironmentId: environmentId, - worktreeId: created.result.worktree.id - }) - } - throw error - } -} diff --git a/src/cli/handlers/worktree-create-startup-agent.ts b/src/cli/handlers/worktree-create-startup-agent.ts deleted file mode 100644 index 0bb226549af..00000000000 --- a/src/cli/handlers/worktree-create-startup-agent.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { parseCliAgent } from '../agent-launch-request' -import { getPresentStringFlag } from '../flags' -import { RuntimeClientError } from '../runtime-client' - -export function getOptionalStartupAgent( - flags: Map -): TuiAgent | undefined { - const agent = getPresentStringFlag(flags, 'agent') - if (agent === undefined) { - const needsAgent = ['prompt', 'model', 'effort', 'surface', 'retry-launch'].find((name) => - flags.has(name) - ) - if (needsAgent) { - throw new RuntimeClientError('invalid_argument', `--${needsAgent} requires --agent`) - } - return undefined - } - return parseCliAgent(agent) -} diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.ts index 14962514d51..d1ff9d7bf72 100644 --- a/src/cli/handlers/worktree.ts +++ b/src/cli/handlers/worktree.ts @@ -28,9 +28,8 @@ import { resolveWorktreeCreateCwdContext, resolveCurrentWorktreeSelector } from '../selectors' -import { readCliAgentLaunch } from '../agent-launch-request' -import { getOptionalStartupAgent } from './worktree-create-startup-agent' -import { createWorktreeOnRecipe } from './worktree-create-recipe' +import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import { parseCliAgent, readCliAgentLaunch } from '../agent-launch-request' import { createWorktreeWithAgent } from './worktree-create-agent-launch' import { printLineageSummary, printSetParentLine } from './worktree-lineage-summary' import { resolveCreateParentFields, resolveSetParentFields } from './worktree-parent-fields' @@ -63,6 +62,20 @@ import { resolveReferenceInputs } from '../reference-input' +function getOptionalStartupAgent(flags: Map): TuiAgent | undefined { + const agent = getPresentStringFlag(flags, 'agent') + if (agent === undefined) { + const needsAgent = ['prompt', 'model', 'effort', 'surface', 'retry-launch'].find((name) => + flags.has(name) + ) + if (needsAgent) { + throw new RuntimeClientError('invalid_argument', `--${needsAgent} requires --agent`) + } + return undefined + } + return parseCliAgent(agent) +} + export const WORKTREE_HANDLERS: Record = { 'worktree ps': async ({ flags, client, json }) => { const result = await client.call>( @@ -105,7 +118,6 @@ export const WORKTREE_HANDLERS: Record = { }, 'worktree create': async (context) => { const { flags, client, cwd, json, rawArgs } = context - const recipeId = flags.has('recipe') ? getRequiredStringFlag(flags, 'recipe') : undefined const referenceInputs = getCreateReferenceInputs(flags) assertWorktreeParentFlagsCompatible(flags) assertWorkspaceTargetFlagsCompatible(flags) @@ -188,10 +200,6 @@ export const WORKTREE_HANDLERS: Record = { // Always request CLI provenance, including hand-typed creates without a terminal handle. cliProvenanceRequest: callerTerminalHandle ? { callerTerminalHandle } : {} } - if (recipeId) { - await createWorktreeOnRecipe({ client, flags, create, recipeId, launch: agentLaunch, json }) - return - } if (agentLaunch) { await createWorktreeWithAgent({ client, flags, create, launch: agentLaunch, json, rawArgs }) return diff --git a/src/cli/host-handler-groups.ts b/src/cli/host-handler-groups.ts index 80055c0c2e5..160656e60ba 100644 --- a/src/cli/host-handler-groups.ts +++ b/src/cli/host-handler-groups.ts @@ -33,10 +33,5 @@ export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [ name: 'vm', keys: ['vm recipe doctor'], load: async () => (await import('./handlers/vm.js')).VM_HANDLERS - }, - { - name: 'vm-recipe-list', - keys: ['vm recipe list'], - load: async () => (await import('./handlers/vm-recipe-list.js')).VM_RECIPE_LIST_HANDLERS } ] diff --git a/src/cli/index-worktree-create-recipe.test.ts b/src/cli/index-worktree-create-recipe.test.ts deleted file mode 100644 index a683f2c606a..00000000000 --- a/src/cli/index-worktree-create-recipe.test.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock -} = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'), - addEnvironmentFromPairingCodeMock: vi.fn(), - listEnvironmentsMock: vi.fn(), - spawnMock: vi.fn() -})) - -vi.mock('./runtime-client', async () => { - const { createRuntimeClientModuleMock } = await import('./index-test-harness.js') - return createRuntimeClientModuleMock({ - callMock, - runtimeClientConstructorMock, - serveOrcaAppMock, - getDefaultUserDataPathMock - }) -}) - -vi.mock('./runtime/environments', () => ({ - addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock, - listEnvironments: listEnvironmentsMock, - removeEnvironment: vi.fn(), - resolveEnvironment: vi.fn() -})) - -vi.mock('child_process', async () => { - const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) -}) - -import { main } from './index' -import { buildWorktree, okFixture, queueFixtures } from './test-fixtures' -import { useWorktreeAwarenessEnvironment } from './index-test-harness' - -import { agentLaunchFixture, agentLaunchHostFixture } from './agent-launch-test-fixtures' -import { WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY } from '../shared/host-runtime-capabilities' - -// main() never clears exitCode, so a failing test would otherwise satisfy later exitCode checks. -const originalExitCode = process.exitCode -beforeEach(() => { - process.exitCode = undefined -}) -afterEach(() => { - process.exitCode = originalExitCode -}) - -describe('CLI worktree create --recipe', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - const command = [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--no-parent', - '--json' - ] - const sourceStatus = () => - okFixture('source', { capabilities: [WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY] }) - const created = () => - okFixture('create', { - worktree: buildWorktree('/checkout', 'task', 'head', 'remote'), - recipe: { - id: 'sandbox', - runtimeId: 'vm', - environmentId: 'env-vm', - checkoutMode: 'orca-worktree' - } - }) - - it('selects the recipe only after verifying the provisioning host supports it', async () => { - queueFixtures(callMock, sourceStatus(), created()) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main(command, '/outside') - expect(callMock).toHaveBeenNthCalledWith(1, 'status.get') - expect(callMock).toHaveBeenNthCalledWith( - 2, - 'worktree.create', - expect.objectContaining({ repo: 'id:source', recipeId: 'sandbox' }), - expect.objectContaining({ timeoutMs: 600_000, onProgress: expect.any(Function) }) - ) - expect(log.mock.calls.flat().join('')).toContain('"environmentId": "env-vm"') - }) - it('prints named progress steps to stderr without touching stdout', async () => { - callMock.mockImplementationOnce(async () => sourceStatus()) - callMock.mockImplementationOnce( - async ( - _method: string, - _params: unknown, - options?: { onProgress?: (p: unknown) => void } - ) => { - options?.onProgress?.({ phase: 'running-create' }) - options?.onProgress?.({ phase: 'not-a-known-phase' }) - return created() - } - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - command.filter((arg) => arg !== '--json'), - '/outside' - ) - const stderr = error.mock.calls.flat().join('\n') - expect(stderr).toContain('from recipe "sandbox"') - expect(stderr).toContain("- Running the recipe's create step...") - expect(stderr).not.toContain('not-a-known-phase') - expect(log.mock.calls.flat().join('')).toContain('environment: env-vm') - }) - it('adds next steps to a failed create and keeps the failure data', async () => { - callMock.mockImplementationOnce(async () => sourceStatus()) - callMock.mockImplementationOnce(async () => { - const { RuntimeClientError } = await import('./runtime-client.js') - throw new RuntimeClientError( - 'recipe_workspace_create_failed', - 'Boom. Orca destroyed the new environment.', - { - phase: 'checking-host', - environment: 'destroyed' - } - ) - }) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(command, '/outside') - expect(process.exitCode).toBe(1) - const output = log.mock.calls.flat().join('') - expect(output).toContain('recipe_workspace_create_failed') - expect(output).toContain('checking-host') - expect(output).toContain('orca vm recipe doctor sandbox') - }) - it('refuses an older host before creating a local checkout', async () => { - queueFixtures(callMock, okFixture('old', { capabilities: [] })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(command, '/outside') - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) - it.each([{ recipe: ['--recipe'] }, { recipe: ['--recipe', ''] }])( - 'rejects a missing recipe value: %j', - async ({ recipe }) => { - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--no-parent', - ...recipe, - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(callMock).not.toHaveBeenCalled() - } - ) - it('launches the agent on the new environment using the adopted workspace', async () => { - queueFixtures( - callMock, - sourceStatus(), - created(), - agentLaunchHostFixture(), - agentLaunchFixture('remote::/checkout') - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - await main( - [ - ...command, - '--agent', - 'codex', - '--model', - 'gpt-6-astra', - '--effort', - 'high', - '--prompt', - 'Work here' - ], - '/outside' - ) - expect(runtimeClientConstructorMock).toHaveBeenCalledWith(null, 'id:env-vm') - const launch = callMock.mock.calls.find( - ([method]) => method === 'agent.launch' || method === 'agent.launchReplay' - ) - expect(launch?.[1]).toMatchObject({ - agent: 'codex', - target: { kind: 'existing', worktree: 'id:remote::/checkout' }, - prompt: { text: 'Work here' } - }) - }) -}) - -describe('CLI vm recipe list', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - const listing = { - repos: [ - { - repoId: 'source', - repoName: 'orca', - repoPath: '/src/orca', - recipes: [ - { - id: 'sandbox', - name: 'Sandbox', - checkoutMode: 'orca-worktree', - steps: ['destroy'], - destroyDisabled: false, - timeoutSeconds: { create: 600 } - } - ], - diagnostics: [{ index: 1, field: 'create', message: 'Missing create command.' }] - } - ] - } - - it('lists one repo after checking the host can run recipes', async () => { - queueFixtures( - callMock, - okFixture('host', { capabilities: [WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY] }), - okFixture('list', listing) - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - await main(['vm', 'recipe', 'list', '--repo', 'id:source'], '/outside') - expect(callMock).toHaveBeenNthCalledWith(2, 'vmRecipe.list', { repo: 'id:source' }) - const output = log.mock.calls.flat().join('\n') - expect(output).toContain( - 'sandbox Sandbox [orca-worktree; destroys on removal; timeouts create 600s]' - ) - expect(output).toContain('warning: environmentRecipes[1].create: Missing create command.') - }) - - it('refuses a host that cannot run recipes without calling the list method', async () => { - queueFixtures(callMock, okFixture('old', { capabilities: [] })) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main(['vm', 'recipe', 'list', '--json'], '/outside') - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'vmRecipe.list')).toBe(false) - }) -}) - -describe('CLI worktree create --recipe refusals', () => { - useWorktreeAwarenessEnvironment({ - callMock, - serveOrcaAppMock, - getDefaultUserDataPathMock, - addEnvironmentFromPairingCodeMock, - listEnvironmentsMock, - spawnMock - }) - - it('refuses an explicit parent, which another host cannot record', async () => { - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--parent-worktree', - 'active', - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) - it('refuses --activate before asking the host anything', async () => { - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - await main( - [ - 'worktree', - 'create', - '--repo', - 'id:source', - '--name', - 'task', - '--recipe', - 'sandbox', - '--no-parent', - '--activate', - '--json' - ], - '/outside' - ) - expect(process.exitCode).toBe(1) - expect(log.mock.calls.flat().join('')).toContain('--activate is not supported with --recipe') - expect(callMock.mock.calls.some(([method]) => method === 'worktree.create')).toBe(false) - }) -}) diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index b3afbce38f9..6ad30800fca 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -77,7 +77,6 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' plugin dev unload Remove a development folder', '', 'Environment Recipes:', - ' vm recipe list List environment recipes for worktree create --recipe', ' vm recipe doctor Validate a per-workspace environment recipe', '', 'Automations:', diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index ca4647c5435..1425d23af36 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -194,8 +194,7 @@ export class RuntimeClient { effectiveTimeoutMs, envelope, expectedRuntimeSource, - // Only requestSelection and onProgress reach the socket; the rest shaped the envelope above. - options + options?.requestSelection ? { requestSelection: options.requestSelection } : undefined ) } catch (error) { // A pre-send refusal has no outcome to recover; retry advice would resend the same bytes. diff --git a/src/cli/runtime/serve-recipe-json.ts b/src/cli/runtime/serve-recipe-json.ts index c2aae3397c3..45eec9683e9 100644 --- a/src/cli/runtime/serve-recipe-json.ts +++ b/src/cli/runtime/serve-recipe-json.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { StringDecoder } from 'node:string_decoder' import { getEphemeralVmRecipeResultConnection, @@ -8,7 +8,7 @@ import { RuntimeClientError } from './types' const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout' -export function waitForRecipeJson(child: ChildProcessHandle): Promise { +export function waitForRecipeJson(child: ChildProcess): Promise { return new Promise((resolve, reject) => { let output = '' let settled = false diff --git a/src/cli/runtime/serve-update-supervisor.ts b/src/cli/runtime/serve-update-supervisor.ts index 40924bd8023..41bf2b9c335 100644 --- a/src/cli/runtime/serve-update-supervisor.ts +++ b/src/cli/runtime/serve-update-supervisor.ts @@ -1,4 +1,5 @@ -import type { ChildProcessHandle, ProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' +import type { ProcessSpec } from '@orca/process-host/process-spec' import { readFileSync } from 'node:fs' import { readFile, rename, unlink, writeFile } from 'node:fs/promises' import { @@ -34,7 +35,7 @@ export const SERVE_CHILD_FORCE_KILL_GRACE_MS = type ServeSupervisorArgs = { /** Respawned on update; `program` is also the bundle whose installed version a handoff awaits. */ spec: ProcessSpec - spawnChild: (spec: ProcessSpec) => ChildProcessHandle + spawnChild: (spec: ProcessSpec) => ChildProcess handoffPath: string | null } @@ -76,7 +77,7 @@ async function awaitInstalledHandoff( export async function superviseForegroundServe( args: ServeSupervisorArgs & { - child: ChildProcessHandle + child: ChildProcess expectedHandoff: InstallRequestedHandoff | null } ): Promise { @@ -129,7 +130,7 @@ export async function superviseForegroundServe( } function waitForForegroundChild( - child: ChildProcessHandle, + child: ChildProcess, expected: { handoffPath: string; handoff: InstallRequestedHandoff } | null ): Promise<{ code: number | null diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.ts index 077bb13a588..31871e1b96f 100644 --- a/src/cli/runtime/transport.test.ts +++ b/src/cli/runtime/transport.test.ts @@ -349,48 +349,6 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => { expect(vi.getTimerCount()).toBe(0) }) - it('hands progress notes on keepalive frames to the caller and ignores malformed ones', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) - roots.push(userDataPath) - const endpoint = join(userDataPath, 'runtime.sock') - const server = createServer((socket) => { - sockets.add(socket) - socket.once('close', () => sockets.delete(socket)) - socket.once('data', (data) => { - const request: { id: string } = JSON.parse(String(data).trim()) - socket.write('{"_keepalive":true,"progress":{"phase":"running-create"}}\n') - socket.write('{"_keepalive":true,"progress":{"phase":42}}\n') - socket.write('{"_keepalive":true}\n') - socket.write( - `${JSON.stringify({ id: request.id, ok: true, result: { created: true }, _meta: { runtimeId: 'runtime-1' } })}\n` - ) - }) - }) - servers.add(server) - await new Promise((resolve) => server.listen(endpoint, resolve)) - const metadata: RuntimeMetadata = { - runtimeId: 'runtime-1', - pid: 123, - transports: [{ kind: 'unix', endpoint }], - authToken: 'token', - startedAt: 1 - } - const onProgress = vi.fn() - const response = await sendRequest( - metadata, - 'worktree.create', - {}, - 60_000, - undefined, - undefined, - { - onProgress - } - ) - expect(response).toMatchObject({ ok: true, result: { created: true } }) - expect(onProgress.mock.calls).toEqual([[{ phase: 'running-create' }]]) - }) - it('rejects promptly when the runtime closes the socket before responding', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-')) roots.push(userDataPath) diff --git a/src/cli/runtime/transport.ts b/src/cli/runtime/transport.ts index afb9f7c8835..eafc4672ff8 100644 --- a/src/cli/runtime/transport.ts +++ b/src/cli/runtime/transport.ts @@ -4,8 +4,7 @@ import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootst import type { ExpectedRuntimeSource, RuntimeOrchestrationEnvelope, - RuntimeRequestSelection, - RuntimeRpcProgress + RuntimeRequestSelection } from '../../shared/runtime-rpc-envelope' import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema' import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } from './types' @@ -25,10 +24,9 @@ export async function sendRequest( options: { classifySocketError?: (error: Error) => RuntimeClientError | null requestSelection?: RuntimeRequestSelection - onProgress?: (progress: RuntimeRpcProgress) => void } = {} ): Promise> { - const { classifySocketError = runtimeAccessDeniedError, requestSelection, onProgress } = options + const { classifySocketError = runtimeAccessDeniedError, requestSelection } = options if (!isSafeTimerDelayMs(timeoutMs)) { throw new RuntimeClientError( 'invalid_argument', @@ -158,11 +156,6 @@ export async function sendRequest( // Keepalives refresh the idle timeout without a full envelope validation. if (isKeepaliveFrame(raw)) { timeout.refresh() - // Parse only for a caller that listens; every other long poll skips the work. - const progress = onProgress ? RuntimeRpcEnvelopeSchema.safeParse(raw) : null - if (progress?.success && 'progress' in progress.data && progress.data.progress) { - onProgress?.(progress.data.progress) - } continue } diff --git a/src/cli/runtime/types.ts b/src/cli/runtime/types.ts index 6791da106c4..2a48c7bfc99 100644 --- a/src/cli/runtime/types.ts +++ b/src/cli/runtime/types.ts @@ -1,8 +1,7 @@ import type { RuntimeOrchestrationEnvelope, RuntimeRequestSelection, - RuntimeRpcFailure, - RuntimeRpcProgress + RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope' import { redactOrchestrationCompatibilitySecrets } from '../../shared/orchestration/orchestration-compatibility-evidence' @@ -17,8 +16,6 @@ export type RuntimeCallOptions = { legacyTerminalPrompt?: true terminalPromptPreflight?: { runtimeId: string | null } requestSelection?: RuntimeRequestSelection - /** Local socket only: named steps a long-running request reports while it runs. */ - onProgress?: (progress: RuntimeRpcProgress) => void } & RuntimeOrchestrationEnvelope export class RuntimeClientError extends Error { diff --git a/src/cli/specs/vm.ts b/src/cli/specs/vm.ts index ed687b218fc..fb98c7d7674 100644 --- a/src/cli/specs/vm.ts +++ b/src/cli/specs/vm.ts @@ -1,19 +1,7 @@ import type { CommandSpec } from '../args' -import { GLOBAL_FLAGS, LOCAL_COMMAND_FLAGS } from '../args' +import { LOCAL_COMMAND_FLAGS } from '../args' export const VM_COMMAND_SPECS: CommandSpec[] = [ - { - path: ['vm', 'recipe', 'list'], - summary: 'List the environment recipes `orca worktree create --recipe` can use', - usage: 'orca vm recipe list [--repo ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'repo'], - notes: [ - "Lists recipes from each repo's orca.yaml plus approved plugin recipes, as the Orca desktop app on this computer sees them. Pass --repo to list one repo.", - 'Each recipe shows its checkout mode, whether removing its workspace destroys the environment, and any per-step timeouts from timeoutSeconds.', - 'orca.yaml problems that hid a recipe are listed as warnings; run `orca vm recipe doctor ` for details.' - ], - examples: ['orca vm recipe list', 'orca vm recipe list --repo id: --json'] - }, { path: ['vm', 'recipe', 'doctor'], summary: 'Validate a per-workspace environment recipe without provisioning by default', diff --git a/src/cli/specs/worktree-create.ts b/src/cli/specs/worktree-create.ts index e620cd05832..743f4b68504 100644 --- a/src/cli/specs/worktree-create.ts +++ b/src/cli/specs/worktree-create.ts @@ -6,7 +6,7 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { repeatableFlags: ['reference'], summary: 'Create a new Orca-managed worktree', usage: - 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--recipe ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', + 'orca worktree create --name [--repo |--project [--host ]|--project-host-setup ] [--agent ] [--prompt ] [--model ] [--effort ] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch ] [--branch ] [--reference ...] [--reference-site ] [--issue ] [--pr ] [--linear-issue ] [--gitlab-issue ] [--gitlab-mr ] [--comment ] [--parent-worktree [--parent-environment ]] [--no-parent] [--run-hooks] [--activate] [--retry-launch ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'repo', @@ -14,7 +14,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'host', 'project-host-setup', 'name', - 'recipe', 'agent', 'prompt', 'model', @@ -58,8 +57,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'Repo-defined setup hooks follow the repository setup policy; pass --setup run to force them.', 'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.', 'Passing --run-hooks is kept as a legacy alias for --setup run and reveals the worktree.', - "Pass --recipe to create the workspace on a new environment from one of the repo's environment recipes (`orca vm recipe list` shows them). The Orca desktop app on this computer runs the recipe's create step, then creates the workspace on the environment's own Orca server; progress steps print to stderr and --json prints only the result. Ctrl+C stops it and destroys an environment that finished its create step; one interrupted mid-create stays in Settings > Cloud VMs for you to destroy. The recipe's timeoutSeconds bounds each step. If a later step fails, Orca destroys the new environment and the error (code recipe_workspace_create_failed) says which step failed and whether the destroy finished.", - '--recipe runs from the provisioning computer only: it cannot be combined with --environment, --pairing-code or --retry-launch. With --agent, the agent starts on the new environment after creation. --activate, --parent-worktree and --parent-environment are not supported with --recipe yet, and the workspace is recorded without a parent. Provisioned-root recipes run setup in their create step, so --setup run, --run-hooks and sparse checkout are refused for them.', 'Use --pr for GitHub pull requests; --gitlab-issue and --gitlab-mr write separate GitLab links. GitLab URLs must match the stored source project or remote; they cannot select a foreign project.' ], examples: [ @@ -72,7 +69,6 @@ export const WORKTREE_CREATE_COMMAND_SPEC: CommandSpec = { 'orca worktree create --repo id: --name folder-child --parent-worktree folder: --json', 'orca worktree create --repo id: --name related-task --parent-worktree active --json', 'orca worktree create --environment --repo id: --name child --parent-environment local --parent-worktree folder: --json', - 'orca worktree create --repo id: --name independent-task --no-parent --json', - 'orca worktree create --repo id: --name sandboxed-task --recipe cloud-sandbox --agent codex --prompt "hi" --json' + 'orca worktree create --repo id: --name independent-task --no-parent --json' ] } diff --git a/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts index 47458275181..e36305bd325 100644 --- a/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts @@ -1,4 +1,4 @@ -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { spawnProcess } from '@orca/process-host' @@ -102,7 +102,7 @@ export function spawnWslRelayProcess( distro: string, env: NodeJS.ProcessEnv, version: string -): PipedChildProcess { +): ChildProcessWithoutNullStreams { // --exec bypasses login-shell rewriting and passes $HOME verbatim for guest-side expansion. const command = `exec sh "${guestRelayDirExpr(version)}/launch.sh"` return spawnProcess({ @@ -153,10 +153,10 @@ export async function launchWslRelayWithInstall(options: { version: string io: WslRelayLaunchIo isDisposed: () => boolean - onChild: (child: PipedChildProcess) => void + onChild: (child: ChildProcessWithoutNullStreams) => void onNoNode: () => void onFailure: (message: string) => void - connect: (transport: MultiplexerTransport, child: PipedChildProcess) => Promise + connect: (transport: MultiplexerTransport, child: ChildProcessWithoutNullStreams) => Promise }): Promise { const { distro, env, bundleJsPath, version, io } = options let installTried = false diff --git a/src/main/browser/backends/offscreen-browser-backend.ts b/src/main/browser/backends/offscreen-browser-backend.ts index cc186c029a1..bfc4e8b0369 100644 --- a/src/main/browser/backends/offscreen-browser-backend.ts +++ b/src/main/browser/backends/offscreen-browser-backend.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto' import { BrowserWindow } from 'electron' -import { ORCA_BROWSER_PARTITION } from '../../../shared/constants' +import '../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../shared/browser/browser-session-partition' 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' 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 3059c59b0bf..2457e919576 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 @@ -1,6 +1,7 @@ import { app, BaseWindow, BrowserWindow, protocol, ipcMain, session } from 'electron' import { renameSync, writeFileSync } from 'node:fs' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' 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 32e8638c2c9..36c5c85afaa 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 @@ -1,7 +1,8 @@ import { app, BaseWindow, BrowserWindow, protocol, session, webContents } from 'electron' import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' diff --git a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts index 64e93895c0c..590d100b79a 100644 --- a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts +++ b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process-backpressure.test.ts @@ -2,13 +2,13 @@ import { once } from 'node:events' import { PassThrough, Writable } from 'node:stream' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' import { NATIVE_HOST_ERRORS } from './browser-extension-native-host-errors' import { startNativeHost, type NativeHostConnection } from './browser-extension-native-host-process' const owned: { - child: PipedChildProcess + child: ChildProcessWithoutNullStreams connection: NativeHostConnection closed: Promise }[] = [] @@ -23,7 +23,7 @@ async function controlledHost(script = 'setInterval(() => {}, 1000);', bufferStd } }) const write = vi.spyOn(stdin, 'write') - const children: PipedChildProcess[] = [] + const children: ChildProcessWithoutNullStreams[] = [] const closes: string[] = [] const messages: string[] = [] let closed: Promise = Promise.resolve() diff --git a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.test.ts b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.test.ts index 0ed456a0c07..8b69a504ca6 100644 --- a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.test.ts +++ b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { once } from 'node:events' import { build } from 'esbuild' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { killAllNativeHosts, @@ -160,7 +160,7 @@ describe('native host process', () => { it('waits for the Windows supervisor to start the host before exposing its connection', async () => { const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }) - const children: PipedChildProcess[] = [] + const children: ChildProcessWithoutNullStreams[] = [] const messages: string[] = [] let resolved = false try { diff --git a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.ts b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.ts index e48be3b1ba6..bb72af2747f 100644 --- a/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.ts +++ b/src/main/browser/extensions/native-messaging/browser-extension-native-host-process.ts @@ -1,6 +1,7 @@ import { dirname } from 'node:path' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess, PipedProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpec } from '@orca/process-host/process-spec' import { childProcessHasExited, forceTerminateProcessTree, @@ -38,9 +39,9 @@ export type NativeHostConnection = { close: () => void } -export type NativeHostSpawner = (spec: PipedProcessSpec) => PipedChildProcess +export type NativeHostSpawner = (spec: PipedProcessSpec) => ChildProcessWithoutNullStreams -const liveHosts = new Map void>() +const liveHosts = new Map void>() /** Quit: kill every host now; a pending grace timer would never fire. */ export function killAllNativeHosts(): void { @@ -55,7 +56,7 @@ export function killAllNativeHosts(): void { liveHosts.clear() } -function forwardStderr(name: string, child: PipedChildProcess): void { +function forwardStderr(name: string, child: ChildProcessWithoutNullStreams): void { let budget = STDERR_LOG_BUDGET_BYTES child.stderr.on('data', (chunk: Buffer) => { if (budget <= 0) { @@ -77,7 +78,7 @@ export function startNativeHost( spawn: NativeHostSpawner = spawnProcess ): Promise { return new Promise((resolve, reject) => { - let child: PipedChildProcess + let child: ChildProcessWithoutNullStreams const supervised = process.platform === 'win32' try { child = spawn( 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 81d752dfed8..74b1ccbcfe3 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 @@ -1,7 +1,8 @@ import { app, BaseWindow, BrowserWindow, protocol, session } from 'electron' import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' 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 37f7d63079c..211b8fa78fe 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 @@ -1,6 +1,7 @@ import { app, BaseWindow, protocol, session } from 'electron' import { renameSync, writeFileSync } from 'node:fs' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' import { initializeBrowserExtensionSupport } from '../browser-extension-startup' 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 3634015a353..35ca7f99861 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 @@ -1,7 +1,8 @@ import { app, BaseWindow, BrowserWindow, protocol, session } from 'electron' import { renameSync, writeFileSync } from 'node:fs' import { createServer } from 'node:http' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { applyBackgroundActivationPolicy } from '../../../window/foreground-activation-policy' import { browserManager } from '../../guest-lifecycle/manager/browser-manager' import { browserSessionRegistry } from '../../sessions/profiles/browser-session-registry' diff --git a/src/main/browser/guest-lifecycle/manager/browser-manager.ts b/src/main/browser/guest-lifecycle/manager/browser-manager.ts index acb3a3bfa71..e5dec3f9cbf 100644 --- a/src/main/browser/guest-lifecycle/manager/browser-manager.ts +++ b/src/main/browser/guest-lifecycle/manager/browser-manager.ts @@ -1,6 +1,7 @@ import { webContents } from 'electron' import { BrowserCertificateTrustController } from '../../certificate-trust/browser-certificate-trust-controller' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import { BrowserManagerEventForwarding } from './browser-manager-event-forwarding' diff --git a/src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts b/src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts index 712bddadd6d..9e51f08fc70 100644 --- a/src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts +++ b/src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts @@ -1,7 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { BrowserHostLeaseAuthority } from '../../../../shared/browser/client-hosting/browser-client-host-protocol' import { browserNetworkExecutionHostStorageIdentity } from '../../routing/identity/browser-execution-host-storage-identity' -import { browserNetworkExecutionHostKey } from '../execution-routes/browser-network-execution-route' +import '../execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import { BrowserClientNetworkRouteRegistry } from './browser-client-network-route-registry' const authority: BrowserHostLeaseAuthority = { diff --git a/src/main/browser/network/client-routes/browser-client-network-route-registry.ts b/src/main/browser/network/client-routes/browser-client-network-route-registry.ts index f474f3fefd2..467277b4c91 100644 --- a/src/main/browser/network/client-routes/browser-client-network-route-registry.ts +++ b/src/main/browser/network/client-routes/browser-client-network-route-registry.ts @@ -12,7 +12,8 @@ import { } from '../../routing/identity/browser-execution-host-storage-identity' import { createRouteRetirement, waitForRoute } from './browser-client-network-route-settlement' import { resolveBrowserHostReconnectDelay } from '../../client-hosts/leases/browser-host-lease-reconnect-delay' -import { parseBrowserNetworkExecutionHostKey } from '../execution-routes/browser-network-execution-route' +import '../execution-routes/browser-network-execution-route' +import { parseBrowserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' type BrowserClientNetworkRoute = { start(): Promise<{ host: string; port: number }> diff --git a/src/main/browser/network/execution-routes/browser-network-execution-route-contract.ts b/src/main/browser/network/execution-routes/browser-network-execution-route-contract.ts new file mode 100644 index 00000000000..e3e5ba37c0e --- /dev/null +++ b/src/main/browser/network/execution-routes/browser-network-execution-route-contract.ts @@ -0,0 +1,22 @@ +import type { BrowserNetworkExecutionHost } from '../../../../shared/browser/client-hosting/browser-network-execution-host' +import type { BrowserNetworkTunnelOpen } from '../../../../shared/browser-network-tunnel-protocol' +import type { BrowserNetworkTunnelSocket } from '../tunnels/browser-network-tunnel-stream-state' + +export type BrowserNetworkExecutionRoute = { + key: string + connect: (target: BrowserNetworkTunnelOpen) => BrowserNetworkTunnelSocket + whenInvalidated?: Promise + isValid: () => boolean + close: () => void | Promise +} + +export type BrowserNetworkExecutionRouteContext = { + executionHost: BrowserNetworkExecutionHost + runtimeId: string + runtimeRevision: number + signal?: AbortSignal +} + +export type BrowserNetworkExecutionRouteResolver = ( + context: BrowserNetworkExecutionRouteContext +) => Promise diff --git a/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts b/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts index 756629b0d6f..904e2813da7 100644 --- a/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts +++ b/src/main/browser/network/execution-routes/browser-network-execution-route-dispatch.ts @@ -1,7 +1,5 @@ -import { - resolveNativeBrowserNetworkExecutionRoute, - type BrowserNetworkExecutionRouteResolver -} from './browser-network-execution-route' +import { resolveNativeBrowserNetworkExecutionRoute } from './browser-network-execution-route' +import type { BrowserNetworkExecutionRouteResolver } from './browser-network-execution-route-contract' // Keep SSH imports lazy and use the registry: ipc/ssh would pull Electron into the plain-Node runtime. export const resolveBrowserNetworkExecutionRoute: BrowserNetworkExecutionRouteResolver = async ( diff --git a/src/main/browser/network/execution-routes/browser-network-execution-route.test.ts b/src/main/browser/network/execution-routes/browser-network-execution-route.test.ts index 30935ababf8..cf9eeae143e 100644 --- a/src/main/browser/network/execution-routes/browser-network-execution-route.test.ts +++ b/src/main/browser/network/execution-routes/browser-network-execution-route.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' +import { resolveNativeBrowserNetworkExecutionRoute } from './browser-network-execution-route' import { browserNetworkExecutionHostKey, - parseBrowserNetworkExecutionHostKey, - resolveNativeBrowserNetworkExecutionRoute -} from './browser-network-execution-route' + parseBrowserNetworkExecutionHostKey +} from '../../../../shared/browser/client-hosting/browser-network-execution-host' describe('browser network execution route', () => { it('uses structural keys for delimiter-containing execution-host identities', () => { diff --git a/src/main/browser/network/execution-routes/browser-network-execution-route.ts b/src/main/browser/network/execution-routes/browser-network-execution-route.ts index 112f870719e..85a19b6ad8c 100644 --- a/src/main/browser/network/execution-routes/browser-network-execution-route.ts +++ b/src/main/browser/network/execution-routes/browser-network-execution-route.ts @@ -1,5 +1,5 @@ -import { connect, type Socket } from 'node:net' -import { BrowserNetworkExecutionHost } from '../../../../shared/browser/client-hosting/browser-network-execution-host' +import { connect } from 'node:net' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import type { BrowserNetworkTunnelOpen } from '../../../../shared/browser-network-tunnel-protocol' import type { BrowserNetworkTunnelSocket } from '../tunnels/browser-network-tunnel-stream-state' import { readNetworkProxySettings } from './browser-network-proxy-settings-source' @@ -8,62 +8,11 @@ import { connectThroughBrowserNetworkTunnelProxy, type BrowserNetworkTunnelDialer } from '../tunnels/browser-network-tunnel-proxy-connect' - -export type BrowserNetworkExecutionRoute = { - key: string - connect: (target: BrowserNetworkTunnelOpen) => BrowserNetworkTunnelSocket - whenInvalidated?: Promise - isValid: () => boolean - close: () => void | Promise -} - -export type BrowserNetworkExecutionRouteContext = { - executionHost: BrowserNetworkExecutionHost - runtimeId: string - runtimeRevision: number - signal?: AbortSignal -} - -export type BrowserNetworkExecutionRouteResolver = ( - context: BrowserNetworkExecutionRouteContext -) => Promise - -export function browserNetworkExecutionHostKey(host: BrowserNetworkExecutionHost): string { - if (host.kind === 'native') { - return JSON.stringify(['native', host.runtimeId, host.revision]) - } - if (host.kind === 'wsl') { - return JSON.stringify(['wsl', host.runtimeId, host.revision, host.distro]) - } - return JSON.stringify(['ssh', host.targetId, host.providerEpoch, host.connectionGeneration]) -} - -export function parseBrowserNetworkExecutionHostKey(key: string): BrowserNetworkExecutionHost { - let tuple: unknown - try { - tuple = JSON.parse(key) - } catch { - throw new Error('browser_tunnel_execution_host_key_invalid') - } - const candidate = - Array.isArray(tuple) && tuple[0] === 'native' && tuple.length === 3 - ? { kind: 'native', runtimeId: tuple[1], revision: tuple[2] } - : Array.isArray(tuple) && tuple[0] === 'wsl' && tuple.length === 4 - ? { kind: 'wsl', runtimeId: tuple[1], revision: tuple[2], distro: tuple[3] } - : Array.isArray(tuple) && tuple[0] === 'ssh' && tuple.length === 4 - ? { - kind: 'ssh', - targetId: tuple[1], - providerEpoch: tuple[2], - connectionGeneration: tuple[3] - } - : null - const parsed = BrowserNetworkExecutionHost.safeParse(candidate) - if (!parsed.success || browserNetworkExecutionHostKey(parsed.data) !== key) { - throw new Error('browser_tunnel_execution_host_key_invalid') - } - return parsed.data -} +import type { + BrowserNetworkExecutionRoute, + BrowserNetworkExecutionRouteContext +} from './browser-network-execution-route-contract' +import { openConnectedSocket } from '../tunnels/browser-network-connected-socket' export function resolveNativeBrowserNetworkExecutionRoute( context: BrowserNetworkExecutionRouteContext @@ -89,31 +38,6 @@ const nativeDialer: BrowserNetworkTunnelDialer = { openTransport: openConnectedSocket } -// Settle on connect so an immediate dial error (emitted on nextTick) cannot outrun its listener. -export function openConnectedSocket( - endpoint: BrowserNetworkTunnelOpen, - signal: AbortSignal -): Promise { - return new Promise((resolve, reject) => { - const socket = connect({ ...endpoint, allowHalfOpen: true }) - const abandon = (): void => { - socket.destroy() - reject(new Error('browser_tunnel_proxy_connect_abandoned')) - } - const fail = (error: Error): void => { - signal.removeEventListener('abort', abandon) - reject(error) - } - signal.addEventListener('abort', abandon, { once: true }) - socket.on('error', fail) - // Keep fail attached: an error between connect and the caller's listeners must not go uncaught. - socket.once('connect', () => { - signal.removeEventListener('abort', abandon) - resolve(socket) - }) - }) -} - export function connectNativeBrowserNetworkTarget( target: BrowserNetworkTunnelOpen, env: Record = process.env diff --git a/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts b/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts index 2c8602d54bb..197ed26261a 100644 --- a/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts +++ b/src/main/browser/network/execution-routes/ssh-browser-network-execution-route.ts @@ -12,12 +12,13 @@ import { type SystemSshDynamicForwardProcess } from '../../../ssh/system-transport/forwarding/system-ssh-dynamic-forward-process' import { BrowserNetworkDeferredSocket } from './browser-network-deferred-socket' -import { - browserNetworkExecutionHostKey, - type BrowserNetworkExecutionRoute, - type BrowserNetworkExecutionRouteContext, - openConnectedSocket -} from './browser-network-execution-route' +import './browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' +import type { + BrowserNetworkExecutionRoute, + BrowserNetworkExecutionRouteContext +} from './browser-network-execution-route-contract' +import { openConnectedSocket } from '../tunnels/browser-network-connected-socket' import { connectThroughBrowserNetworkTunnelProxy, type BrowserNetworkTunnelDialer diff --git a/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts b/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts index 27af4bd4590..337bc6e9452 100644 --- a/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts +++ b/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts @@ -9,7 +9,7 @@ import { BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES, type BrowserNetworkTunnelSocket } from '../tunnels/browser-network-tunnel-stream-state' -import type { BrowserNetworkExecutionRoute } from './browser-network-execution-route' +import type { BrowserNetworkExecutionRoute } from './browser-network-execution-route-contract' import { BrowserNetworkTunnelStreamFrameDecoder, BrowserNetworkTunnelStreamFrameWriter diff --git a/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.ts b/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.ts index f07db699663..ebdd3d14320 100644 --- a/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.ts +++ b/src/main/browser/network/execution-routes/wsl-browser-network-execution-route.ts @@ -5,11 +5,12 @@ import { } from '../../../../shared/browser-network-tunnel-stream-framing' import { BrowserNetworkDeferredSocket } from './browser-network-deferred-socket' import { BrowserNetworkTunnelClient } from '../tunnels/browser-network-tunnel-client' -import { - browserNetworkExecutionHostKey, - type BrowserNetworkExecutionRoute, - type BrowserNetworkExecutionRouteContext -} from './browser-network-execution-route' +import './browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' +import type { + BrowserNetworkExecutionRoute, + BrowserNetworkExecutionRouteContext +} from './browser-network-execution-route-contract' type WslBrowserNetworkExecutionRouteDependencies = { launchRelay?: (distro: string, signal: AbortSignal) => Promise diff --git a/src/main/browser/network/tunnels/browser-network-connected-socket.ts b/src/main/browser/network/tunnels/browser-network-connected-socket.ts new file mode 100644 index 00000000000..a74eb5b6dfa --- /dev/null +++ b/src/main/browser/network/tunnels/browser-network-connected-socket.ts @@ -0,0 +1,27 @@ +import { connect, type Socket } from 'node:net' +import type { BrowserNetworkTunnelOpen } from '../../../../shared/browser-network-tunnel-protocol' + +// Settle on connect so an immediate dial error (emitted on nextTick) cannot outrun its listener. +export function openConnectedSocket( + endpoint: BrowserNetworkTunnelOpen, + signal: AbortSignal +): Promise { + return new Promise((resolve, reject) => { + const socket = connect({ ...endpoint, allowHalfOpen: true }) + const abandon = (): void => { + socket.destroy() + reject(new Error('browser_tunnel_proxy_connect_abandoned')) + } + const fail = (error: Error): void => { + signal.removeEventListener('abort', abandon) + reject(error) + } + signal.addEventListener('abort', abandon, { once: true }) + socket.on('error', fail) + // Keep fail attached: an error between connect and the caller's listeners must not go uncaught. + socket.once('connect', () => { + signal.removeEventListener('abort', abandon) + resolve(socket) + }) + }) +} diff --git a/src/main/browser/routing/guest-authority/browser-route-guest-guard.ts b/src/main/browser/routing/guest-authority/browser-route-guest-guard.ts index 07aec26f212..dcf9f9c38a4 100644 --- a/src/main/browser/routing/guest-authority/browser-route-guest-guard.ts +++ b/src/main/browser/routing/guest-authority/browser-route-guest-guard.ts @@ -1,6 +1,7 @@ import type { Session, WebContents } from 'electron' import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { isValidBrowserRoutePageOwnerIdentity, type BrowserRoutePageAuthorityRetirement, diff --git a/src/main/browser/routing/guest-authority/browser-route-guest-lifecycle.ts b/src/main/browser/routing/guest-authority/browser-route-guest-lifecycle.ts index d772053a9a3..7686e59ee9d 100644 --- a/src/main/browser/routing/guest-authority/browser-route-guest-lifecycle.ts +++ b/src/main/browser/routing/guest-authority/browser-route-guest-lifecycle.ts @@ -1,5 +1,6 @@ import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import type { WebContents } from 'electron' import { browserRoutePageKey, 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 f77a9f5877a..cee8fde28a3 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 @@ -1,5 +1,6 @@ import type { Session, WebContents } from 'electron' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { isBlankBrowserPopupUrl, normalizeBrowserPopupUrl diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.test.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.test.ts index 404a4b1acaf..a0305f35543 100644 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.test.ts +++ b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { BrowserNetworkExecutionRoute, BrowserNetworkExecutionRouteContext -} from '../../network/execution-routes/browser-network-execution-route' +} from '../../network/execution-routes/browser-network-execution-route-contract' import type { BrowserNetworkTunnelSocket } from '../../network/tunnels/browser-network-tunnel-stream-state' import { closeAllLocalSshBrowserRoutes, diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts index 63c995ca7e7..238756b218b 100644 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts +++ b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route.ts @@ -1,5 +1,5 @@ import type { Duplex } from 'node:stream' -import type { BrowserNetworkExecutionRouteResolver } from '../../network/execution-routes/browser-network-execution-route' +import type { BrowserNetworkExecutionRouteResolver } from '../../network/execution-routes/browser-network-execution-route-contract' import type { BrowserNetworkTunnelOpen } from '../../../../shared/browser-network-tunnel-protocol' import type { SshTargetSummary } from '../../../../shared/ssh-types' import { openExecutionRouteSocketAsDuplex } from '../../network/tunnels/execution-route-socket-duplex' diff --git a/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts index 58e39a1df16..edccd0a8004 100644 --- a/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts +++ b/src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts @@ -106,6 +106,7 @@ describe('installBrowserSessionPartitionPolicies proxy wiring', () => { }) afterEach(() => { + setBrowserNetworkProxySettingsResolver(null) vi.unstubAllEnvs() identityState.unavailable = false }) diff --git a/src/main/browser/sessions/profiles/browser-session-registry.ts b/src/main/browser/sessions/profiles/browser-session-registry.ts index 3b9bde71fde..2a4d78d8545 100644 --- a/src/main/browser/sessions/profiles/browser-session-registry.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry.ts @@ -1,7 +1,8 @@ import { app, session } from 'electron' import { randomUUID } from 'node:crypto' import { join } from 'node:path' -import { ORCA_BROWSER_PARTITION } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../shared/browser/browser-session-partition' import { DEFAULT_LOCAL_ORCA_PROFILE_ID, getOrcaProfileBrowserDefaultPartition, diff --git a/src/main/claude-accounts/claude-login-process-termination.ts b/src/main/claude-accounts/claude-login-process-termination.ts index f0a9195b84b..633ebc34236 100644 --- a/src/main/claude-accounts/claude-login-process-termination.ts +++ b/src/main/claude-accounts/claude-login-process-termination.ts @@ -1,5 +1,5 @@ import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import type { WindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn' import { recordSelfInitiatedTreeKill } from '../crash-reporting/self-initiated-tree-kill-log' import { admitSelfInitiatedTreeKill } from '../pty/process-retirement/own-chromium-tree-kill-guard' @@ -7,7 +7,7 @@ import { admitSelfInitiatedTreeKill } from '../pty/process-retirement/own-chromi const WINDOWS_TASKKILL_TIMEOUT_MS = 5_000 export function terminateClaudeProcess( - child: ChildProcessHandle, + child: ChildProcess, interactiveLogin: WindowsHostInteractiveLoginSpawn | null, afterKill: () => void ): void { diff --git a/src/main/claude/claude-agent-sdk-exit-proof.test.ts b/src/main/claude/claude-agent-sdk-exit-proof.test.ts index f2da6be21cf..c71e8743aa6 100644 --- a/src/main/claude/claude-agent-sdk-exit-proof.test.ts +++ b/src/main/claude/claude-agent-sdk-exit-proof.test.ts @@ -1,5 +1,4 @@ -import type { PipedChildProcess } from '@orca/process-host/process-spec' -import { execFileSync } from 'node:child_process' +import { execFileSync, type ChildProcessWithoutNullStreams } from 'node:child_process' import { describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' import { proveClaudeChildExit } from './claude-agent-sdk-exit-proof' @@ -71,7 +70,7 @@ async function proveExitWithRetries( return proveClaudeChildExit(input) } -function spawnScript(script: string): PipedChildProcess { +function spawnScript(script: string): ChildProcessWithoutNullStreams { const child = spawnProcess({ program: process.execPath, args: ['-e', script], @@ -81,7 +80,7 @@ function spawnScript(script: string): PipedChildProcess { return child } -function firstStdoutLine(child: PipedChildProcess): Promise { +function firstStdoutLine(child: ChildProcessWithoutNullStreams): Promise { return new Promise((resolve) => { child.stdout.setEncoding('utf8').once('data', (chunk: string) => resolve(chunk.trim())) }) diff --git a/src/main/claude/claude-agent-sdk-exit-proof.ts b/src/main/claude/claude-agent-sdk-exit-proof.ts index a279ab00e26..7587f8798fa 100644 --- a/src/main/claude/claude-agent-sdk-exit-proof.ts +++ b/src/main/claude/claude-agent-sdk-exit-proof.ts @@ -1,4 +1,4 @@ -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { terminateDescendantSnapshotWithVerdict, type DescendantTreeVerdict @@ -23,7 +23,7 @@ const TREE_VERDICT_TRUST: Record = { exited: 2 } -type ReapableChild = Pick +type ReapableChild = Pick // A missing or exited root may have reparented descendants; its walk cannot prove an empty tree. function admissibleTree( diff --git a/src/main/claude/claude-agent-sdk-process-spawn.ts b/src/main/claude/claude-agent-sdk-process-spawn.ts index d04cd9e2551..a5eb7f49e55 100644 --- a/src/main/claude/claude-agent-sdk-process-spawn.ts +++ b/src/main/claude/claude-agent-sdk-process-spawn.ts @@ -1,4 +1,5 @@ -import type { PipedChildProcess, PipedProcessSpawner } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import type { SpawnOptions as ClaudeAgentSdkSpawnOptions } from '@anthropic-ai/claude-agent-sdk' import { spawnProcess } from '@orca/process-host' import { @@ -9,8 +10,8 @@ import { claudeChildClosePolicy, claudeChildCloseProven } from './claude-child-e export type ClaudeCodeProcessSpawn = { /** SDK spawn hook; Orca retains process ownership. */ - spawn: (options: ClaudeAgentSdkSpawnOptions) => PipedChildProcess - readonly child: PipedChildProcess | null + spawn: (options: ClaudeAgentSdkSpawnOptions) => ChildProcessWithoutNullStreams + readonly child: ChildProcessWithoutNullStreams | null readonly managed: ManagedProviderProcess | null /** Supervisor pid on POSIX; lease ownership also requires start time and spawn token. */ readonly pid: number | undefined @@ -30,7 +31,7 @@ function definedEnv(env: Record): Record void ): void { const onSubscribe = (event: string | symbol): void => { diff --git a/src/main/claude/claude-agent-sdk-root-kill-fallback.test.ts b/src/main/claude/claude-agent-sdk-root-kill-fallback.test.ts index 91e65460a52..d8417965fd4 100644 --- a/src/main/claude/claude-agent-sdk-root-kill-fallback.test.ts +++ b/src/main/claude/claude-agent-sdk-root-kill-fallback.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import { describe, expect, it, vi } from 'vitest' -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import type { DescendantSnapshot } from '../pty/process-retirement/pty-descendant-termination' import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' @@ -11,7 +11,7 @@ const ROOT_STARTED_AT = 'Mon Jan 1 00:00:00 2026' const ROOT_FORK_MS = Date.parse(ROOT_STARTED_AT) function mockChild(): EventEmitter & - Pick & { kill: ReturnType } { + Pick & { kill: ReturnType } { return Object.assign(new EventEmitter(), { pid: ROOT_PID, stdin: new PassThrough(), diff --git a/src/main/claude/claude-child-exit-proof-fixture.ts b/src/main/claude/claude-child-exit-proof-fixture.ts index b5330be0577..f157807d036 100644 --- a/src/main/claude/claude-child-exit-proof-fixture.ts +++ b/src/main/claude/claude-child-exit-proof-fixture.ts @@ -1,4 +1,4 @@ -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { spawnManagedProviderProcess, type ManagedProviderProcess @@ -9,7 +9,7 @@ const managedChildren = new WeakMap() /** `closePlatform` picks the close rules; the spawn itself always skips the POSIX supervisor. */ export function managedChild( - child: PipedChildProcess, + child: ChildProcessWithoutNullStreams, closePlatform: NodeJS.Platform = 'linux' ): ManagedProviderProcess { const existing = managedChildren.get(child) diff --git a/src/main/claude/claude-child-root-termination.ts b/src/main/claude/claude-child-root-termination.ts index 7633d42838f..1a8b431e4c9 100644 --- a/src/main/claude/claude-child-root-termination.ts +++ b/src/main/claude/claude-child-root-termination.ts @@ -1,7 +1,7 @@ -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' type RootTerminationInput = { - child: Pick + child: Pick exited: () => boolean } diff --git a/src/main/claude/claude-stream-json-connection.test.ts b/src/main/claude/claude-stream-json-connection.test.ts index 1cc57ba3545..17b63de60f7 100644 --- a/src/main/claude/claude-stream-json-connection.test.ts +++ b/src/main/claude/claude-stream-json-connection.test.ts @@ -1,11 +1,11 @@ -import { execFileSync } from 'node:child_process' +import { execFileSync, type ChildProcess } from 'node:child_process' import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { providerDiagnosticOf } from '../../shared/agent-session/failures/agent-session-failure' import { afterEach, describe, expect, it, vi } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { SpawnedProcess, ProcessSpec } from '@orca/process-host/process-spec' +import type { ProcessSpec } from '@orca/process-host/process-spec' import type { query, CanUseTool } from '@anthropic-ai/claude-agent-sdk' import { @@ -89,7 +89,7 @@ function launchFor( } const spawned: ProcessSpec[] = [] -const spawnedChildren: SpawnedProcess[] = [] +const spawnedChildren: ChildProcess[] = [] async function open( launch: ClaudeStreamJsonLaunch, diff --git a/src/main/claude/windows-native-hook-registration.test.ts b/src/main/claude/windows-native-hook-registration.test.ts index c62b41fcc4a..bf01e0fe34f 100644 --- a/src/main/claude/windows-native-hook-registration.test.ts +++ b/src/main/claude/windows-native-hook-registration.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { once } from 'node:events' import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -85,7 +85,7 @@ describe.skipIf(process.platform !== 'win32')('ClaudeHookService native hook ins `${join(hooksDir, EXE).replaceAll('\\', '/')} claude` // Holding stdin open keeps the hook image mapped to exercise locked-executable replacement. - function startHeldHook(program: string): PipedChildProcess { + function startHeldHook(program: string): ChildProcessWithoutNullStreams { return spawnProcess({ program, args: ['claude'], diff --git a/src/main/codex/app-server/codex-app-server-client.ts b/src/main/codex/app-server/codex-app-server-client.ts index 837aa52c124..484e164fde0 100644 --- a/src/main/codex/app-server/codex-app-server-client.ts +++ b/src/main/codex/app-server/codex-app-server-client.ts @@ -1,4 +1,5 @@ -import type { ChildProcessHandle, ProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' +import type { ProcessSpec } from '@orca/process-host/process-spec' import { spawnProcess } from '@orca/process-host' import '../trust/toml/config-toml-trust' import { normalizeCodexHookTrustLookupKey as normalizeHookTrustKeyForLookup } from '../trust/identity/codex-trust-identity' @@ -95,12 +96,11 @@ function collectHookListings(result: unknown): CodexHookListing[] { export async function runCodexHookTrustGrantSession( request: CodexHookTrustGrantRequest, - spawnImpl: ( - program: string, - args: string[], - options: Record - ) => ChildProcessHandle = (program, args, options) => - spawnProcess({ program, args, ...options } as ProcessSpec) + spawnImpl: (program: string, args: string[], options: Record) => ChildProcess = ( + program, + args, + options + ) => spawnProcess({ program, args, ...options } as ProcessSpec) ): Promise { return runCodexAppServerSession( request.invocation, diff --git a/src/main/codex/app-server/codex-app-server-process-tree-kill.ts b/src/main/codex/app-server/codex-app-server-process-tree-kill.ts index 80c8b5e1bd1..1e914eb7ff2 100644 --- a/src/main/codex/app-server/codex-app-server-process-tree-kill.ts +++ b/src/main/codex/app-server/codex-app-server-process-tree-kill.ts @@ -1,5 +1,6 @@ import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle, ProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' +import type { ProcessSpec } from '@orca/process-host/process-spec' import { admitProcessTreeKill } from '@orca/process-host/process-tree-kill-gate' /** Spawn seam for tests; production always goes through the hardened spawnProcess wrapper. */ @@ -7,13 +8,13 @@ export type CodexAppServerSpawn = ( program: string, args: string[], options: Record -) => ChildProcessHandle +) => ChildProcess export const spawnCodexAppServerProcess: CodexAppServerSpawn = (program, args, options) => spawnProcess({ program, args, ...options } as ProcessSpec) export function killCodexAppServerProcessTree( - child: Pick, + child: Pick, options: { platform?: NodeJS.Platform; spawnImpl?: CodexAppServerSpawn } = {} ): void { const platform = options.platform ?? process.platform diff --git a/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts b/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts index 793bff15c01..270d1f4d972 100644 --- a/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts +++ b/src/main/codex/history/index/codex-state-db-backfill-recovery-process.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' import { parseWslUncPath } from '../../../../shared/wsl-paths' import { buildWslCodexAppServerArgs } from '../../../codex-accounts/wsl-codex-command' @@ -18,7 +18,7 @@ const BACKFILL_RECOVERY_KILL_SITE = 'codex-state-db-backfill-recovery' const BACKFILL_RECOVERY_CLOSE_REQUEST: ProviderCloseRequest = 'stdin-end' export type CodexBackfillRecoveryProcess = { - child: ChildProcessHandle + child: ChildProcess supervised: boolean } @@ -71,7 +71,7 @@ export function spawnCodexBackfillRecoveryProcess( } export async function stopCodexBackfillRecoveryProcess( - child: ChildProcessHandle, + child: ChildProcess, supervised: boolean ): Promise { if (supervised) { diff --git a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts index 6f8dd5a232f..322ffe03649 100644 --- a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts +++ b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts @@ -6,7 +6,7 @@ import { parseWslUncPath } from '../../../../shared/wsl-paths' import { withManagedHookInstallLock } from '../../../agent-hooks/installation/locking/managed-hook-install-lock' import { readManagedHookHostIdentity } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveCodexCommand } from '../../../codex-cli/command' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { spawnCodexAppServerProcess, type CodexAppServerSpawn @@ -43,7 +43,7 @@ type RecoveryDependencies = { countSessions: (sessionsRoot: string, limit: number) => number now: () => number sleep: (ms: number, signal: AbortSignal) => Promise - terminate: (child: ChildProcessHandle, supervised: boolean) => Promise + terminate: (child: ChildProcess, supervised: boolean) => Promise } const defaultDependencies: RecoveryDependencies = { diff --git a/src/main/codex/structured/catalog/codex-structured-service-tier.ts b/src/main/codex/structured/catalog/codex-structured-service-tier.ts index 2124fce21f2..ff04c99f7f2 100644 --- a/src/main/codex/structured/catalog/codex-structured-service-tier.ts +++ b/src/main/codex/structured/catalog/codex-structured-service-tier.ts @@ -8,6 +8,7 @@ import type { CodexOpenedThread } from '../threads/codex-structured-thread-open' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' import { codexSessionCapabilities } from './codex-structured-catalog-entry' import { effectiveServiceTier } from '../../../../shared/agent-session/options/structured-agent-session-effective-tier' +import { isFastServiceTier } from '../../../../shared/agent-session/options/structured-agent-session-discovered-model' export const CODEX_DEFAULT_SERVICE_TIER = 'default' @@ -41,9 +42,7 @@ export function readCodexServiceTiers( export function codexFastServiceTier( model: Pick | undefined ): string | undefined { - return model?.serviceTiers?.find( - (tier) => tier.label.toLowerCase() === 'fast' || tier.value.toLowerCase() === 'fast' - )?.value + return model?.serviceTiers?.find(isFastServiceTier)?.value } /** Nonstandard tiers other than Fast have no legacy toggle value. */ diff --git a/src/main/computer/desktop-script-runtime-host.test.ts b/src/main/computer/desktop-script-runtime-host.test.ts index 7a49bf08d44..90a7a13dc48 100644 --- a/src/main/computer/desktop-script-runtime-host.test.ts +++ b/src/main/computer/desktop-script-runtime-host.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import { afterEach, describe, expect, it, vi } from 'vitest' import type { ProcessSpec } from '@orca/process-host/process-spec' -import type { RuntimeChildProcess } from './desktop-script-serve-channel' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { DesktopScriptRuntimeHost, isRuntimeHostUnavailable } from './desktop-script-runtime-host' class FakeRuntimeChild extends EventEmitter { @@ -96,7 +96,8 @@ function createHost( const child = new FakeRuntimeChild() child.deferWrites = options.deferWrites === true children.push(child) - return child as unknown as RuntimeChildProcess + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture implements the piped streams and events used by the runtime host. + return child as unknown as ChildProcessWithoutNullStreams } }) return { host, children, specs, warnings } diff --git a/src/main/computer/desktop-script-runtime-host.ts b/src/main/computer/desktop-script-runtime-host.ts index 7f4a49cc237..b9a12a9e467 100644 --- a/src/main/computer/desktop-script-runtime-host.ts +++ b/src/main/computer/desktop-script-runtime-host.ts @@ -4,11 +4,8 @@ import { reportComputerDiagnostic } from './computer-sidecar-diagnostics' import { isReplayableTool } from './desktop-script-action' import type { BridgeRequest, BridgeResponse } from './desktop-script-provider-types' import { DesktopScriptRequestQueue } from './desktop-script-request-queue' -import { - startServeChannel, - type DesktopScriptServeChannel, - type RuntimeProcessSpawn -} from './desktop-script-serve-channel' +import type { PipedProcessSpawner } from '@orca/process-host/process-spec' +import { startServeChannel, type DesktopScriptServeChannel } from './desktop-script-serve-channel' import { MAX_START_ATTEMPTS, RuntimeHostAvailability, @@ -27,7 +24,7 @@ const IDLE_SHUTDOWN_MS = 120_000 export const RUNTIME_HOST_UNAVAILABLE = 'runtime_host_unavailable' export type DesktopScriptRuntimeHostOptions = { - spawn?: RuntimeProcessSpawn + spawn?: PipedProcessSpawner powerShellPath?: () => string requestTimeoutMs?: number idleShutdownMs?: number diff --git a/src/main/computer/desktop-script-serve-channel.test.ts b/src/main/computer/desktop-script-serve-channel.test.ts index 6f2cf443eaa..a86a028a7b6 100644 --- a/src/main/computer/desktop-script-serve-channel.test.ts +++ b/src/main/computer/desktop-script-serve-channel.test.ts @@ -1,6 +1,7 @@ import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' -import { DesktopScriptServeChannel, type RuntimeChildProcess } from './desktop-script-serve-channel' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import { DesktopScriptServeChannel } from './desktop-script-serve-channel' class FakeChild extends EventEmitter { readonly stdout = new EventEmitter() @@ -36,7 +37,11 @@ class FakeChild extends EventEmitter { function createChannel() { const child = new FakeChild() const handlers = { onLine: vi.fn(), onGone: vi.fn(), onOverflow: vi.fn() } - const channel = new DesktopScriptServeChannel(child as unknown as RuntimeChildProcess, handlers) + const channel = new DesktopScriptServeChannel( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture implements the piped streams and events consumed by the channel. + child as unknown as ChildProcessWithoutNullStreams, + handlers + ) return { channel, child, handlers } } @@ -86,11 +91,15 @@ describe('DesktopScriptServeChannel', () => { const tails: string[] = [] const feed = (index: number): void => { const child = new FakeChild() - const channel = new DesktopScriptServeChannel(child as unknown as RuntimeChildProcess, { - onLine: () => {}, - onGone: () => {}, - onOverflow: () => {} - }) + const channel = new DesktopScriptServeChannel( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture implements the piped streams and events consumed by the channel. + child as unknown as ChildProcessWithoutNullStreams, + { + onLine: () => {}, + onGone: () => {}, + onOverflow: () => {} + } + ) const line = String.fromCharCode(65 + (index % 26)).repeat(1024 * 1024) child.stdout.emit('data', `${line}\n{"partial":${index}`) tails.push((channel as unknown as { buffer: string }).buffer) diff --git a/src/main/computer/desktop-script-serve-channel.ts b/src/main/computer/desktop-script-serve-channel.ts index 53eb8d90b81..816bbf76c07 100644 --- a/src/main/computer/desktop-script-serve-channel.ts +++ b/src/main/computer/desktop-script-serve-channel.ts @@ -1,15 +1,8 @@ import { StringDecoder } from 'node:string_decoder' -import type { - PipedChildProcess, - PipedProcessSpawner, - PipedProcessSpec -} from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpawner, PipedProcessSpec } from '@orca/process-host/process-spec' import { ownRetainedString } from '../../shared/own-retained-string' -export type RuntimeChildProcess = PipedChildProcess - -export type RuntimeProcessSpawn = PipedProcessSpawner - /** UTF-16 units, not bytes — this bounds the buffer, it is not a payload contract. */ const MAX_RESPONSE_CHARS = 20 * 1024 * 1024 const MAX_STDERR_CHARS = 4096 @@ -30,7 +23,7 @@ export class DesktopScriptServeChannel { private closed = false constructor( - private readonly child: RuntimeChildProcess, + private readonly child: ChildProcessWithoutNullStreams, private readonly handlers: ServeChannelHandlers ) { const onStdout = (chunk: Buffer | string): void => this.readStdout(chunk) @@ -135,7 +128,7 @@ export class DesktopScriptServeChannel { export function startServeChannel( spec: PipedProcessSpec, - spawn: RuntimeProcessSpawn, + spawn: PipedProcessSpawner, handlers: ServeChannelHandlers ): DesktopScriptServeChannel { return new DesktopScriptServeChannel(spawn(spec), handlers) diff --git a/src/main/computer/macos-computer-use-permission-status-cleanup.integration.test.ts b/src/main/computer/macos-computer-use-permission-status-cleanup.integration.test.ts index 4a78022c95b..a01de3fdffb 100644 --- a/src/main/computer/macos-computer-use-permission-status-cleanup.integration.test.ts +++ b/src/main/computer/macos-computer-use-permission-status-cleanup.integration.test.ts @@ -3,12 +3,12 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { afterEach, describe, expect, it } from 'vitest' import { stopMacOSPermissionStatusHelper } from './macos-computer-use-permission-status-cleanup' describe.skipIf(process.platform !== 'darwin')('real permission status helper cleanup', () => { - const children: ChildProcessHandle[] = [] + const children: ChildProcess[] = [] const directories: string[] = [] afterEach(async () => { @@ -27,7 +27,7 @@ describe.skipIf(process.platform !== 'darwin')('real permission status helper cl ) }) - async function startFixture(executablePath: string, args: string[]): Promise { + async function startFixture(executablePath: string, args: string[]): Promise { const child = spawnProcess({ program: process.execPath, args: [ diff --git a/src/main/computer/macos-native-provider-process-reaping.ts b/src/main/computer/macos-native-provider-process-reaping.ts index e0e28d196a3..e9a4cf4dba1 100644 --- a/src/main/computer/macos-native-provider-process-reaping.ts +++ b/src/main/computer/macos-native-provider-process-reaping.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle as ChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' export const PROVIDER_SIGKILL_GRACE_MS = 2_000 diff --git a/src/main/computer/macos-native-provider-reaping.integration.test.ts b/src/main/computer/macos-native-provider-reaping.integration.test.ts index 2ba3fe2c502..291415219fe 100644 --- a/src/main/computer/macos-native-provider-reaping.integration.test.ts +++ b/src/main/computer/macos-native-provider-reaping.integration.test.ts @@ -1,11 +1,11 @@ import { once } from 'node:events' import { afterEach, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { reapMacOSProviderProcess } from './macos-native-provider-process-reaping' describe.skipIf(process.platform === 'win32')('real macOS provider process reaping', () => { - const children: ChildProcessHandle[] = [] + const children: ChildProcess[] = [] afterEach(async () => { await Promise.all( diff --git a/src/main/daemon/launch/daemon-launched-child-spawn.ts b/src/main/daemon/launch/daemon-launched-child-spawn.ts index 4a2f49cf937..a4c103b1e6c 100644 --- a/src/main/daemon/launch/daemon-launched-child-spawn.ts +++ b/src/main/daemon/launch/daemon-launched-child-spawn.ts @@ -1,6 +1,6 @@ import { forkProcess, type ForkSpec } from '@orca/process-host/fork-process' import { spawnProcess } from '@orca/process-host' -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { getAppEnvironment } from '../../../shared/app-environment' import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromium-session-bus-env' import { hostMallocTunablesDaemonEnv } from '../../memory/host-malloc-tunables' @@ -79,7 +79,7 @@ export function buildDaemonScriptArgs( export function spawnDaemonChildProcess( options: DaemonChildSpawnOptions, useDurableScope: boolean -): SpawnedProcess { +): ChildProcess { const { forkEntryPath, relocatedExecPath, diff --git a/src/main/daemon/process-scopes/daemon-scope-death-watch.ts b/src/main/daemon/process-scopes/daemon-scope-death-watch.ts index 7dbc81f8454..c95f9b3a8bb 100644 --- a/src/main/daemon/process-scopes/daemon-scope-death-watch.ts +++ b/src/main/daemon/process-scopes/daemon-scope-death-watch.ts @@ -1,5 +1,6 @@ import { spawnProcess } from '@orca/process-host' -import type { ProcessSpec, SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' +import type { ProcessSpec } from '@orca/process-host/process-spec' // The pipe closes even on SIGKILL; a live/reused owner PID always vetoes cleanup. const SCOPE_DEATH_WATCH_SCRIPT = ` @@ -24,10 +25,10 @@ type ScopeDeathWatchOptions = { /** Stopping the owned daemon scope also reaps its bound terminal slice. */ daemonScope: string | null log: (event: string, details?: Record) => void - spawn?: (spec: ProcessSpec) => SpawnedProcess + spawn?: (spec: ProcessSpec) => ChildProcess } -export function startDaemonScopeDeathWatch(options: ScopeDeathWatchOptions): SpawnedProcess | null { +export function startDaemonScopeDeathWatch(options: ScopeDeathWatchOptions): ChildProcess | null { const { daemonScope: unit, log } = options if (!unit) { return null diff --git a/src/main/ephemeral-vm/cli-workspace-create.ts b/src/main/ephemeral-vm/cli-workspace-create.ts deleted file mode 100644 index 4bf16c62855..00000000000 --- a/src/main/ephemeral-vm/cli-workspace-create.ts +++ /dev/null @@ -1,179 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { Repo } from '../../shared/repo-types' -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { isFolderRepo } from '../../shared/repo-kind' -import { getProjectHostSetupForRepo } from '../../shared/project-host-setup-lookup' -import { getProjectIdentityKey } from '../../shared/project-host-setup-projection' -import type { - RecipeCatalogListing, - RecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import { sanitizeWorktreeName } from '../ipc/worktree-logic' -import { resolveCreateBranchName } from '../runtime/workspaces/creation/runtime-worktree-create-git' -import { resolveLocalGitUsername } from '../git/git-username' -import { getLocalProjectGitExecOptions } from '../workspaces/execution-host/project-runtime-git-options' -import { - listRecipeCatalog, - listRecipes, - resolveRecipeForRepo -} from '../ipc/ephemeral-vm-recipe-context' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' -import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' -import type { PluginService } from '../plugins/plugin-service' -import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' -import { provisionRecipeEnvironment } from './environment-provision' -import { attachEphemeralVmRuntimeToWorkspace } from './runtime-attachment' -import { cleanupOwnedEphemeralVmRuntime } from './owned-runtime-cleanup' -import { - createProvisionedRecipeWorkspace, - type RecipeWorkspaceCreateParams, - type RecipeWorkspaceCreation -} from './recipe-workspace-create' - -// Each call to the new environment's Orca is one short step; the recipe's own timeouts bound the create. -const ENVIRONMENT_STEP_TIMEOUT_MS = 600_000 - -/** `worktree.create` with a recipe id: the host that owns the recipe provisions and adopts. */ -export async function createCliRecipeWorkspace(args: { - store: Store - userDataPath: string - repo: Repo - params: RecipeWorkspaceCreateParams - pluginService: PluginService | null - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void -}): Promise { - const { store, userDataPath, repo, params } = args - if (isFolderRepo(repo) || getRepoExecutionHostId(repo) !== 'local') { - throw new Error('Environment recipes need a Git checkout on this computer.') - } - const pluginRecipes = await getApprovedPluginVmRecipes(args.pluginService ?? undefined) - const recipe = params.recipeId - ? resolveRecipeForRepo(repo.path, params.recipeId, pluginRecipes) - : null - if (!recipe) { - throw new Error( - `Recipe not found: ${params.recipeId ?? ''}. Run \`orca vm recipe list\` to see this repo's recipes.` - ) - } - const checkoutMode = recipe.checkoutMode ?? 'orca-worktree' - let branchName: string | undefined - if (checkoutMode === 'provisioned-root') { - const settings = store.getSettings() - const username = - settings.branchPrefix === 'git-username' ? await resolveLocalGitUsername(repo.path) : '' - branchName = await resolveCreateBranchName( - repo.path, - params.branchNameOverride, - sanitizeWorktreeName(params.name ?? ''), - settings, - username, - getLocalProjectGitExecOptions(store, repo) - ) - } - // Same project identity the desktop's recipe flow gives the environment: the portable GitHub key when there is one. - const portableProjectId = getProjectIdentityKey(repo) - const projectId = portableProjectId.startsWith('github:') - ? portableProjectId - : getProjectHostSetupForRepo(store.getProjectHostSetups(), repo).projectId - return createProvisionedRecipeWorkspace( - { - params, - recipeId: recipe.id, - checkoutMode, - ...(branchName ? { branchName } : {}), - projectId, - ...(args.signal ? { signal: args.signal } : {}), - ...(args.onPhase ? { onPhase: args.onPhase } : {}) - }, - { - provision: (onPhase) => - provisionRecipeEnvironment( - store, - userDataPath, - { - repoId: repo.id, - recipeId: recipe.id, - workspaceName: params.name, - projectId, - ...(branchName ? { branch: branchName } : {}), - ...(checkoutMode === 'provisioned-root' && params.baseBranch - ? { ref: params.baseBranch } - : {}) - }, - pluginRecipes, - { repo, recipe, signal: args.signal, onPhase } - ), - call: (environmentId, method, payload) => - callRuntimeEnvironment( - getRuntimeEnvironmentRegistryRoot(), - `id:${environmentId}`, - method, - payload, - ENVIRONMENT_STEP_TIMEOUT_MS, - undefined, - undefined, - // Ctrl+C on the CLI stops the step in flight, so the VM is destroyed right away. - args.signal ? { signal: args.signal } : undefined - ), - attach: (runtimeId, workspaceId) => { - attachEphemeralVmRuntimeToWorkspace({ userDataPath, runtimeId, workspaceId }) - }, - cleanup: async (runtimeId) => { - const runtime = await cleanupOwnedEphemeralVmRuntime(store, userDataPath, runtimeId) - if (runtime.status === 'cleaned') { - // A recipe without a destroy step is marked cleaned without running anything. - return { outcome: runtime.cleanupStatus === 'disabled' ? 'disabled' : 'destroyed' } - } - return { - outcome: 'failed', - ...(runtime.cleanupLastError ? { error: runtime.cleanupLastError } : {}) - } - } - } - ) -} - -function toListedRecipe(recipe: OrcaVmRecipe): RecipeCatalogListing['recipes'][number] { - return { - id: recipe.id, - name: recipe.name, - ...(recipe.description ? { description: recipe.description } : {}), - checkoutMode: recipe.checkoutMode ?? 'orca-worktree', - steps: (['suspend', 'resume', 'destroy'] as const).filter((step) => Boolean(recipe[step])), - destroyDisabled: recipe.destroyDisabled === true, - ...(recipe.timeoutSeconds ? { timeoutSeconds: recipe.timeoutSeconds } : {}) - } -} - -/** The recipes `worktree create --recipe` accepts: orca.yaml plus approved plugin recipes. */ -export async function listCliEnvironmentRecipes( - store: Store, - repo: Repo | null, - pluginService: PluginService | null -): Promise { - const pluginRecipes = await getApprovedPluginVmRecipes(pluginService ?? undefined) - if (repo) { - const listed = listRecipes(store, repo.id, pluginRecipes) - if (listed.status === 'error') { - throw new Error(listed.message ?? 'Could not read environment recipes for this repo.') - } - return [ - { - repoId: repo.id, - repoName: repo.displayName, - repoPath: repo.path, - recipes: listed.recipes.map(toListedRecipe), - diagnostics: listed.diagnostics ?? [] - } - ] - } - return listRecipeCatalog(store, pluginRecipes).map((entry) => ({ - repoId: entry.repoId, - repoName: entry.repoName, - repoPath: entry.repoPath, - recipes: entry.recipes.map(toListedRecipe), - diagnostics: entry.diagnostics ?? [] - })) -} diff --git a/src/main/ephemeral-vm/environment-provision-repo.test.ts b/src/main/ephemeral-vm/environment-provision-repo.test.ts deleted file mode 100644 index 119e89ae3fa..00000000000 --- a/src/main/ephemeral-vm/environment-provision-repo.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { provisionRecipeEnvironment } from './environment-provision' -import type { Repo } from '../../shared/repo-types' -import type { Store } from '../persistence/loading-store/store' - -function repoAt(path: string): Repo { - return { id: 'shared-id', path, displayName: 'Repo', badgeColor: '#000', addedAt: 0 } -} - -let userDataPath: string - -beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'orca-provision-repo-')) -}) - -afterEach(() => { - rmSync(userDataPath, { recursive: true, force: true }) -}) - -it('provisions against the repo the caller resolved, not another host’s twin with the same id', async () => { - const resolved: Repo = repoAt(join(userDataPath, 'resolved')) - const twin: Repo = repoAt(join(userDataPath, 'twin')) - const getRepo = vi.fn(() => twin) - - // No recipes exist at either path, so the run stops at recipe lookup after choosing its repo. - const result = await provisionRecipeEnvironment( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: provisioning reads only getRepo from the store before it stops at recipe lookup. - { getRepo } as unknown as Store, - userDataPath, - { repoId: 'shared-id', recipeId: 'missing' }, - [], - { repo: resolved } - ) - - expect(getRepo).not.toHaveBeenCalled() - expect(result).toMatchObject({ ok: false, errorCode: 'recipeNotFound' }) -}) diff --git a/src/main/ephemeral-vm/environment-provision.ts b/src/main/ephemeral-vm/environment-provision.ts deleted file mode 100644 index ba1d2f79694..00000000000 --- a/src/main/ephemeral-vm/environment-provision.ts +++ /dev/null @@ -1,234 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import type { Repo } from '../../shared/repo-types' -import { getEphemeralVmRecipeResultConnection } from '../../shared/ephemeral-vm-recipes' -import { - getEphemeralVmRecipeResultWarnings, - redactEphemeralVmRecipeDiagnosticText, - type EphemeralVmRecipeResultWarning -} from '../../shared/ephemeral-vm-recipe-diagnostics' -import { getProvisionedRootRecipeRepoUrl } from '../../shared/ephemeral-vm-recipe-repo-url' -import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' -import { - requireEphemeralVmRecipeResult, - type EphemeralVmProvisionedRuntimeRecord -} from '../../shared/ephemeral-vm-runtimes' -import { addEnvironmentFromPairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-store' -import { - redactRuntimeEnvironment, - type PublicKnownRuntimeEnvironment -} from '../../shared/remote-runtime/host-catalog/runtime-environments' -import { - ephemeralVmFailure, - pickEphemeralVmFailureCode, - type EphemeralVmFailure -} from '../../shared/ephemeral-vm-failure-copy' -import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' -import { getRecipeRepo, resolveRecipeForRepo } from '../ipc/ephemeral-vm-recipe-context' -import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' -import { cleanupEphemeralVmRuntime, provisionEphemeralVmRuntime } from './runtime-service' -import { connectRuntimeOwnedSshTarget } from './runtime-ssh' -import { resolveProvisionedRootSource } from './provisioned-root-source' - -export type EphemeralVmProvisionIpcResult = - | { - ok: true - connectionType: 'orca-server' - runtime: EphemeralVmProvisionedRuntimeRecord - environment: PublicKnownRuntimeEnvironment - stderr: string - warnings: EphemeralVmRecipeResultWarning[] - } - | { - ok: true - connectionType: 'ssh' - runtime: EphemeralVmProvisionedRuntimeRecord - sshTargetId: string - /** The managed Orca server the host runs; its workspace lives there. */ - environmentId?: string - expectedRefHead?: string - stderr: string - warnings: EphemeralVmRecipeResultWarning[] - } - | ({ - ok: false - stderr: string - stdout: string - /** Set when the create step had already started a VM that this failure then destroyed. */ - runtimeId?: string - environmentCleanup?: 'destroyed' | 'failed' | 'disabled' - } & EphemeralVmFailure) - -/** Named steps of provisioning, reported to callers that show progress. */ -export type RecipeEnvironmentProvisionPhase = - | 'resolving-start-ref' - | 'running-create' - | 'connecting' - -export type RecipeEnvironmentProvisionArgs = { - repoId: string - recipeId: string - workspaceName?: string - projectId?: string - workspaceId?: string - branch?: string - ref?: string -} - -function provisionFailure(failure: EphemeralVmFailure): EphemeralVmProvisionIpcResult { - return { ok: false, ...failure, stdout: '', stderr: '' } -} - -/** Shared by the desktop IPC handler and CLI `worktree create --recipe`. */ -export async function provisionRecipeEnvironment( - store: Store, - userDataPath: string, - args: RecipeEnvironmentProvisionArgs, - pluginRecipes: readonly OrcaVmRecipe[], - options: { - /** A caller that already resolved the repo by host passes it; an id lookup could pick another host's twin. */ - repo?: Repo - /** A caller that already resolved the recipe passes it, so one orca.yaml read decides the run. */ - recipe?: OrcaVmRecipe - signal?: AbortSignal - onPhase?: (phase: RecipeEnvironmentProvisionPhase) => void - onStdout?: (chunk: string) => void - onStderr?: (chunk: string) => void - } = {} -): Promise { - const repo = options.repo - ? ({ ok: true, repo: options.repo } as const) - : getRecipeRepo(store, args.repoId) - if (!repo.ok) { - return provisionFailure(repo.failure) - } - const recipe = - options.recipe ?? resolveRecipeForRepo(repo.repo.path, args.recipeId, pluginRecipes) - if (!recipe) { - return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) - } - let recipeRepoUrl = repo.repo.gitRemoteIdentity?.remoteUrl - let sourceRef = args.ref - let expectedRefHead: string | undefined - if (recipe.checkoutMode === 'provisioned-root') { - options.onPhase?.('resolving-start-ref') - const source = await resolveProvisionedRootSource(store, repo.repo, args.ref, options.signal) - if (options.signal?.aborted) { - return provisionFailure(ephemeralVmFailure('provisionCancelled')) - } - if (!source) { - return provisionFailure( - args.ref - ? ephemeralVmFailure('startRefUnresolved', { ref: args.ref }) - : ephemeralVmFailure('defaultStartRefUnresolved') - ) - } - sourceRef = source.ref - expectedRefHead = source.head - recipeRepoUrl = source.remoteUrl ?? recipeRepoUrl - } - const repoUrl = getProvisionedRootRecipeRepoUrl(recipe.checkoutMode, recipeRepoUrl) - options.onPhase?.('running-create') - const result = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath: repo.repo.path, - repoId: repo.repo.id, - recipe, - projectId: args.projectId, - workspaceId: args.workspaceId, - workspaceName: args.workspaceName, - ...(repoUrl ? { repoUrl } : {}), - ...(args.branch ? { branch: args.branch } : {}), - ...(sourceRef ? { ref: sourceRef } : {}), - ...(expectedRefHead ? { expectedRefHead } : {}), - ...(options.signal ? { signal: options.signal } : {}), - onStdout: options.onStdout, - onStderr: options.onStderr - }) - if (!result.ok) { - return { - ok: false, - error: result.start.error, - ...pickEphemeralVmFailureCode(result.start), - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } - } - const cleanupAndFail = async (error: unknown): Promise => { - const cleaned = await cleanupEphemeralVmRuntime({ - userDataPath, - repoPath: repo.repo.path, - recipe, - runtimeId: result.runtime.id - }).catch(() => null) - return { - ok: false, - error: error instanceof Error ? error.message : String(error), - runtimeId: result.runtime.id, - environmentCleanup: !cleaned?.ok ? 'failed' : cleaned.skipped ? 'disabled' : 'destroyed', - stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) - } - } - options.onPhase?.('connecting') - const connection = getEphemeralVmRecipeResultConnection(result.start.result) - if (connection.type === 'ssh') { - try { - const ssh = await connectRuntimeOwnedSshTarget({ - runtimeId: result.runtime.id, - connection - }) - const runtime = requireEphemeralVmRecipeResult( - updateEphemeralVmRuntimeStatus(userDataPath, result.runtime.id, { - sshTargetId: ssh.targetId, - runtimeEnvironmentId: ssh.environmentId - }) - ) - return { - ok: true, - connectionType: 'ssh', - runtime, - sshTargetId: ssh.targetId, - environmentId: ssh.environmentId, - ...(expectedRefHead ? { expectedRefHead } : {}), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), - warnings: getEphemeralVmRecipeResultWarnings(result.start.result) - } - } catch (error) { - return cleanupAndFail(error) - } - } - - let environment: ReturnType - try { - environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { - name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), - pairingCode: connection.pairingCode, - source: 'ephemeral-vm' - }) - } catch (error) { - return cleanupAndFail(error) - } - let runtime: EphemeralVmProvisionedRuntimeRecord - try { - runtime = requireEphemeralVmRecipeResult( - updateEphemeralVmRuntimeStatus(userDataPath, result.runtime.id, { - runtimeEnvironmentId: environment.id - }) - ) - } catch (error) { - // The create step already started a VM; a failed record update must still destroy it. - return cleanupAndFail(error) - } - return { - ok: true, - connectionType: 'orca-server', - runtime, - environment: redactRuntimeEnvironment(environment), - stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), - warnings: getEphemeralVmRecipeResultWarnings(result.start.result) - } -} - -function buildEphemeralEnvironmentName(repoName: string, runtimeId: string): string { - return `${repoName} VM ${runtimeId.slice(-8)}` -} diff --git a/src/main/ephemeral-vm/owned-runtime-cleanup.ts b/src/main/ephemeral-vm/owned-runtime-cleanup.ts deleted file mode 100644 index e15bc719d46..00000000000 --- a/src/main/ephemeral-vm/owned-runtime-cleanup.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type { Store } from '../persistence/loading-store/store' -import { - listEphemeralVmRuntimes, - updateEphemeralVmRuntimeStatus -} from '../../shared/ephemeral-vm-runtime-store' -import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' -import { ephemeralVmFailureFromError } from '../../shared/ephemeral-vm-failure-copy' -import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' -import { invalidateRuntimeEnvironmentTransport } from '../ipc/runtime-environments/runtime-environments' -import { retireRemovedRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-removal-cleanup' -import { releaseEphemeralVmRuntimeEnvironments } from './runtime-environment-release' -import { cleanupEphemeralVmRuntime } from './runtime-service' -import { removeEphemeralVmRuntimeSshTarget } from './runtime-ssh-cleanup' -import { removeRuntimeOwnedSshTarget } from './runtime-ssh' -import { isEphemeralVmProvisionLive } from './runtime-provisioning-persistence' - -/** Destroys a recorded VM and releases what Orca holds for it. The one path for the desktop's - * cleanup and a failed CLI create; concurrent calls share one destroy run. */ -export async function cleanupOwnedEphemeralVmRuntime( - store: Store, - userDataPath: string, - runtimeId: string -): Promise { - const runtime = listEphemeralVmRuntimes(userDataPath).find((entry) => entry.id === runtimeId) - if (!runtime) { - throw new Error(`Unknown ephemeral VM runtime: ${runtimeId}`) - } - if (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) { - // Why: don't mark a create in flight as cleanup_failed; its own outcome settles the row. - throw new Error(`Ephemeral VM runtime is still provisioning: ${runtime.id}`) - } - let result - if (runtime.cleanupStatus === 'succeeded') { - result = { ok: true as const, runtime, skipped: false } - } else { - let resolved: ReturnType - try { - resolved = getRuntimeRecipeContext(store, userDataPath, runtime.id) - } catch (error) { - const failed = updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { - status: 'cleanup_failed', - cleanupStatus: 'failed', - cleanupLastAttemptAt: Date.now(), - cleanupLastError: ephemeralVmFailureFromError(error) - }) - return removeEphemeralVmRuntimeSshTarget({ - userDataPath, - runtime: failed, - removeTarget: removeRuntimeOwnedSshTarget - }) - } - result = await cleanupEphemeralVmRuntime({ - userDataPath, - repoPath: resolved.repoPath, - recipe: resolved.recipe, - runtimeId: runtime.id - }) - } - if (result.ok) { - try { - await releaseEphemeralVmRuntimeEnvironments(userDataPath, runtime, (environmentId) => { - void retireRemovedRuntimeEnvironment( - environmentId, - invalidateRuntimeEnvironmentTransport, - store, - userDataPath - ) - }) - } catch { - // Cleanup of provider resources matters more than hiding a stale local - // environment row; users can still remove that manually. - } - } - if (!result.ok) { - return result.runtime - } - return removeEphemeralVmRuntimeSshTarget({ - userDataPath, - runtime: result.runtime, - removeTarget: removeRuntimeOwnedSshTarget - }) -} diff --git a/src/main/ephemeral-vm/recipe-workspace-create-params.ts b/src/main/ephemeral-vm/recipe-workspace-create-params.ts deleted file mode 100644 index 4b545ca1da7..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create-params.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { z } from 'zod' -import type { WorktreeCreate } from '../../shared/rpc-contract/worktree-create-params' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' - -// Kept apart from the orchestration so runtime types (and the mobile host-declaration program) -// do not pull in provisioning, the recipe runner and their imports. -export type RecipeWorkspaceCreateParams = z.infer - -export const RecipeWorkspaceResult = z - .object({ - worktree: z - .object({ - id: z.string().min(1), - repoId: z.string().min(1), - path: z.string().min(1), - branch: z.string(), - instanceId: z.string().optional() - }) - .passthrough() - }) - .passthrough() -export type RecipeWorkspaceCreation = z.infer & { - recipe: { - id: string - runtimeId: string - environmentId: string - checkoutMode: EphemeralVmCheckoutMode - } - environmentWarnings?: string[] -} - -// Fields a normal create on the environment's own Orca understands; lineage, activation and the -// caller's terminal stay on this host, which records them after the environment answers. -const FORWARDED_CREATE_FIELDS = [ - 'name', - 'nameWasGenerated', - 'displayName', - 'displayNameKind', - 'baseBranch', - 'compareBaseRef', - 'branchNameOverride', - 'linkedIssue', - 'linkedPR', - 'linkedLinearIssue', - 'linkedLinearIssueWorkspaceId', - 'linkedLinearIssueOrganizationUrlKey', - 'linkedGitLabMR', - 'linkedGitLabIssue', - 'linkedBitbucketPR', - 'linkedAzureDevOpsPR', - 'linkedGiteaPR', - 'linkedWorkItem', - 'linkedItems', - 'linkedTaskSourceContext', - 'comment', - 'workspaceStatus', - 'sparseCheckout', - 'pushTarget', - 'runHooks', - 'setupDecision', - 'createdWithAgent' -] as const satisfies readonly (keyof RecipeWorkspaceCreateParams)[] - -export function forwardedCreateFields( - params: RecipeWorkspaceCreateParams -): Record { - const forwarded: Record = {} - for (const field of FORWARDED_CREATE_FIELDS) { - if (params[field] !== undefined) { - forwarded[field] = params[field] - } - } - return forwarded -} - -/** Refuses what a recipe create cannot honor before any machine is started. */ -export function assertRecipeWorkspaceCreateSupported( - params: RecipeWorkspaceCreateParams, - checkoutMode: EphemeralVmCheckoutMode -): void { - if (!params.name?.trim()) { - throw new Error('A recipe workspace requires a name.') - } - if (params.startupAgent || params.startupCommand || params.startupDraft) { - throw new Error( - 'Launch the agent on the recipe-created workspace with agent.launch after creation.' - ) - } - if (params.automationProvenanceRequest) { - throw new Error('Recipe workspace creation does not support automation provenance requests.') - } - if (checkoutMode === 'provisioned-root') { - if (params.sparseCheckout) { - throw new Error('Provisioned-root recipes do not support sparse checkout.') - } - if (params.runHooks || params.setupDecision === 'run') { - throw new Error("Provisioned-root recipes run setup in the recipe's create step.") - } - } -} diff --git a/src/main/ephemeral-vm/recipe-workspace-create.test.ts b/src/main/ephemeral-vm/recipe-workspace-create.test.ts deleted file mode 100644 index 33a19b87617..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create.test.ts +++ /dev/null @@ -1,387 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { WorktreeCreate } from '../../shared/rpc-contract/worktree-create-params' -import { - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -} from '../../shared/protocol-version' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' -import type { RecipeWorkspaceCreatePhase } from '../../shared/recipe-workspace-create-progress' -import { - createProvisionedRecipeWorkspace, - RecipeWorkspaceCreateError -} from './recipe-workspace-create' -import type { EphemeralVmProvisionIpcResult } from './environment-provision' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import { mapRuntimeError } from '../runtime/rpc/errors' - -const runtimeRecord = { - id: 'vm', - recipeId: 'sandbox', - repoId: 'source', - status: 'running' as const, - cleanupStatus: 'not_started' as const, - createdAt: 1, - updatedAt: 1 -} -const provisionedRoot: EphemeralVmProvisionIpcResult = { - ok: true, - connectionType: 'ssh', - sshTargetId: 'runtime-ssh-vm', - environmentId: 'env-vm', - expectedRefHead: 'source-head', - stderr: '', - warnings: [], - runtime: { - ...runtimeRecord, - recipeResult: { - schemaVersion: 2, - checkoutMode: 'provisioned-root', - connection: { - type: 'ssh', - projectRoot: '/checkout', - target: { host: 'vm', label: 'VM', username: 'orca', port: 22 } - } - } - } -} -// A VM whose SSH host runs a managed Orca server, with an ordinary (orca-worktree) checkout. -const managedServer: EphemeralVmProvisionIpcResult = { - ok: true, - connectionType: 'ssh', - sshTargetId: 'runtime-ssh-vm', - environmentId: 'env-server', - stderr: '', - warnings: [{ id: 'note', message: 'Using a shared image.' }], - runtime: { - ...runtimeRecord, - recipeResult: { - schemaVersion: 1, - connection: { - type: 'ssh', - projectRoot: '/repo', - target: { host: 'vm', label: 'VM', username: 'orca', port: 22 } - } - } - } -} -const remoteCapabilities = [ - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -] -function okCall( - _env: string, - method: string, - _params: unknown -): Promise> { - const result = - method === 'status.get' - ? { capabilities: remoteCapabilities } - : method === 'projectHostSetup.setupExistingFolder' - ? { result: { repo: { id: 'remote-repo', path: '/checkout' } } } - : { - worktree: { - id: 'remote-repo::/checkout', - repoId: 'remote-repo', - path: '/checkout', - branch: 'refs/heads/user/task', - instanceId: 'instance' - } - } - return Promise.resolve({ id: 'req', ok: true, result, _meta: { runtimeId: 'remote' } }) -} -function makePorts(provisioned: EphemeralVmProvisionIpcResult = provisionedRoot) { - return { - provision: vi.fn(async (onPhase: (phase: RecipeWorkspaceCreatePhase) => void) => { - onPhase('running-create') - onPhase('connecting') - return provisioned - }), - call: vi.fn(okCall), - attach: vi.fn(), - cleanup: vi.fn( - async (): Promise<{ outcome: 'destroyed' | 'failed' | 'disabled'; error?: string }> => ({ - outcome: 'destroyed' - }) - ) - } -} -let ports = makePorts() -function request( - extra: Record = {}, - checkoutMode: EphemeralVmCheckoutMode = 'provisioned-root' -) { - return { - params: WorktreeCreate.parse({ - repo: 'id:source', - name: 'task', - recipeId: 'sandbox', - ...extra - }), - recipeId: 'sandbox', - checkoutMode, - ...(checkoutMode === 'provisioned-root' ? { branchName: 'user/task' } : {}), - projectId: 'git:project' - } -} -async function failure(promise: Promise): Promise { - const error = await promise.then( - () => null, - (caught: unknown) => caught - ) - if (!(error instanceof RecipeWorkspaceCreateError)) { - throw new Error(`expected a RecipeWorkspaceCreateError, got ${String(error)}`) - } - return error -} -beforeEach(() => { - ports = makePorts() -}) - -describe('provisioned-root recipe workspace creation', () => { - it('registers and adopts the pinned root on its server, then attaches the owner record', async () => { - const result = await createProvisionedRecipeWorkspace(request({ comment: 'handoff' }), ports) - expect(ports.call).toHaveBeenNthCalledWith( - 2, - 'env-vm', - 'projectHostSetup.setupExistingFolder', - { - projectId: 'git:project', - hostId: 'local', - path: '/checkout', - kind: 'git', - setupMethod: 'imported-existing-folder' - } - ) - expect(ports.call).toHaveBeenNthCalledWith( - 3, - 'env-vm', - 'worktree.adoptProvisionedRoot', - expect.objectContaining({ - repo: 'id:remote-repo', - branchNameOverride: 'user/task', - expectedPath: '/checkout', - expectedRefHead: 'source-head' - }) - ) - expect(ports.call.mock.calls.map(([, method]) => method)).toEqual([ - 'status.get', - 'projectHostSetup.setupExistingFolder', - 'worktree.adoptProvisionedRoot' - ]) - expect(ports.call.mock.calls[2]?.[2]).toMatchObject({ comment: 'handoff' }) - expect(ports.attach).toHaveBeenCalledWith('vm', 'remote-repo::/checkout') - expect(result).toMatchObject({ - recipe: { - id: 'sandbox', - runtimeId: 'vm', - environmentId: 'env-vm', - checkoutMode: 'provisioned-root' - }, - worktree: { hostId: 'runtime:env-vm' } - }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it.each([ - { sparseCheckout: { directories: ['src'] } }, - { runHooks: true }, - { setupDecision: 'run' }, - { startupAgent: 'codex' }, - { name: '' } - ])('refuses unsupported inputs before provisioning: %j', async (extra) => { - await expect(createProvisionedRecipeWorkspace(request(extra), ports)).rejects.toThrow() - expect(ports.provision).not.toHaveBeenCalled() - }) - it('keeps lineage and the caller terminal out of the payload sent to the environment', async () => { - await createProvisionedRecipeWorkspace( - request({ - linkedGitLabIssue: 42, - parentWorkspace: 'id:local-parent', - cliProvenanceRequest: { callerTerminalHandle: 'term-local' } - }), - ports - ) - const adopt = ports.call.mock.calls.find( - ([, method]) => method === 'worktree.adoptProvisionedRoot' - ) - expect(adopt?.[2]).toMatchObject({ linkedGitLabIssue: 42, cliProvenanceRequest: {} }) - expect(adopt?.[2]).not.toHaveProperty('parentWorkspace') - }) -}) - -describe('orca-worktree recipe workspace creation', () => { - it('creates an ordinary worktree on the environment server, with setup and sparse checkout allowed', async () => { - ports = makePorts(managedServer) - const result = await createProvisionedRecipeWorkspace( - request( - { setupDecision: 'run', sparseCheckout: { directories: ['src'] }, comment: 'c' }, - 'orca-worktree' - ), - ports - ) - expect(ports.call.mock.calls.map(([, method]) => method)).toEqual([ - 'status.get', - 'projectHostSetup.setupExistingFolder', - 'worktree.create' - ]) - expect(ports.call).toHaveBeenLastCalledWith( - 'env-server', - 'worktree.create', - expect.objectContaining({ - repo: 'id:remote-repo', - name: 'task', - setupDecision: 'run', - sparseCheckout: { directories: ['src'] }, - comment: 'c' - }) - ) - expect(ports.call.mock.calls.at(-1)?.[2]).not.toHaveProperty('recipeId') - expect(result).toMatchObject({ - recipe: { environmentId: 'env-server', checkoutMode: 'orca-worktree' }, - worktree: { hostId: 'runtime:env-server' }, - environmentWarnings: ['Using a shared image.'] - }) - expect(ports.attach).toHaveBeenCalledWith('vm', 'remote-repo::/checkout') - }) - it('refuses an environment without an Orca server and destroys it', async () => { - const sshOnly = { ...provisionedRoot, environmentId: undefined } - ports = makePorts(sshOnly) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toContain('only the desktop app') - expect(ports.cleanup).toHaveBeenCalledWith('vm') - }) -}) - -describe('recipe create failures', () => { - it('reaches RPC callers with its code and failure data intact', () => { - const data = { - phase: 'checking-host' as const, - recipeId: 'sandbox', - environment: 'destroyed' as const - } - const response = mapRuntimeError( - 'req', - { runtimeId: 'host' }, - new RecipeWorkspaceCreateError('Boom.', data) - ) - expect(response.error).toEqual({ - code: 'recipe_workspace_create_failed', - message: 'Boom.', - data - }) - }) - it('reports the recipe failure code from the create step without a destroy', async () => { - ports.provision.mockResolvedValueOnce({ - ok: false, - error: 'The recipe create step did not finish within 2 minutes.', - errorCode: 'recipeTimedOut', - errorParams: { mode: 'create', timeout: '2 minutes' }, - stdout: '', - stderr: '' - }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.data).toEqual({ - phase: 'running-create', - recipeId: 'sandbox', - failureCode: 'recipeTimedOut', - failureParams: { mode: 'create', timeout: '2 minutes' } - }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it('says whether the VM survived when the connect step fails after create', async () => { - ports.provision.mockResolvedValueOnce({ - ok: false, - error: 'SSH connect refused', - runtimeId: 'vm', - environmentCleanup: 'failed', - stdout: '', - stderr: '' - }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch(/SSH connect refused.*runtime vm\) may still be running/) - expect(error.data).toMatchObject({ runtimeId: 'vm', environment: 'destroy-failed' }) - expect(ports.cleanup).not.toHaveBeenCalled() - }) - it('names the failed step and confirms the destroy when the server lacks adoption support', async () => { - ports.call.mockImplementation(async () => ({ - id: 'req', - ok: true, - result: { capabilities: [] }, - _meta: { runtimeId: 'old' } - })) - const phases: RecipeWorkspaceCreatePhase[] = [] - const error = await failure( - createProvisionedRecipeWorkspace( - { ...request(), onPhase: (phase) => phases.push(phase) }, - ports - ) - ) - expect(error.message).toMatch(/Update Orca.*destroyed the new environment/) - expect(error.data).toMatchObject({ - phase: 'checking-host', - runtimeId: 'vm', - environment: 'destroyed' - }) - expect(phases).toEqual([ - 'running-create', - 'connecting', - 'checking-host', - 'destroying-after-failure' - ]) - expect(ports.attach).not.toHaveBeenCalled() - }) - it('says the machine may still run when its destroy also fails', async () => { - ports.call.mockImplementationOnce(async () => ({ - id: 'req', - ok: false, - error: { code: 'unreachable', message: 'Remote host unavailable' } - })) - ports.cleanup.mockResolvedValueOnce({ outcome: 'failed', error: 'Destroy exited with code 1.' }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch( - /Remote host unavailable.*runtime vm\) may still be running.*Destroy exited with code 1/ - ) - expect(error.data).toMatchObject({ environment: 'destroy-failed', phase: 'checking-host' }) - }) - it('never claims a destroy for a recipe without a destroy step', async () => { - ports.call.mockImplementationOnce(async () => { - throw new Error('socket closed') - }) - ports.cleanup.mockResolvedValueOnce({ outcome: 'disabled' }) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.message).toMatch(/no destroy step.*runtime vm\) is still running/) - expect(error.message).not.toContain('Orca destroyed') - expect(error.data.environment).toBe('destroy-disabled') - }) - it('treats a throwing destroy as a failed destroy, not a lost error', async () => { - ports.call.mockImplementationOnce(async () => { - throw new Error('socket closed') - }) - ports.cleanup.mockRejectedValueOnce(new Error('Unknown ephemeral VM runtime: vm')) - const error = await failure(createProvisionedRecipeWorkspace(request(), ports)) - expect(error.data).toMatchObject({ - environment: 'destroy-failed', - destroyError: 'Unknown ephemeral VM runtime: vm' - }) - }) - it('destroys the environment when the caller disconnects after provisioning', async () => { - const controller = new AbortController() - ports.provision.mockImplementationOnce(async () => { - controller.abort() - return provisionedRoot - }) - const error = await failure( - createProvisionedRecipeWorkspace({ ...request(), signal: controller.signal }, ports) - ) - expect(ports.call).not.toHaveBeenCalled() - expect(ports.cleanup).toHaveBeenCalledTimes(1) - expect(error.data.environment).toBe('destroyed') - }) - it('checks agent support on the created server before adopting an agent workspace', async () => { - const error = await failure( - createProvisionedRecipeWorkspace(request({ createdWithAgent: 'codex' }), ports) - ) - expect(error.message).toContain('Update Orca') - expect(ports.cleanup).toHaveBeenCalledWith('vm') - expect(ports.attach).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ephemeral-vm/recipe-workspace-create.ts b/src/main/ephemeral-vm/recipe-workspace-create.ts deleted file mode 100644 index 1c147fe3d52..00000000000 --- a/src/main/ephemeral-vm/recipe-workspace-create.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { toRuntimeExecutionHostId } from '../../shared/execution-host' -import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch/contracts/agent-launch-runtime-capability' -import { z } from 'zod' -import { WorktreeAdoptProvisionedRoot } from '../../shared/rpc-contract/worktree-provisioned-root-params' -import type { EphemeralVmCheckoutMode } from '../../shared/orca-yaml-hook-types' -import { - getEphemeralVmRecipeResultProjectRoot, - getEphemeralVmRecipeResultCheckoutMode -} from '../../shared/ephemeral-vm-recipes' -import { redactEphemeralVmRecipeDiagnosticText } from '../../shared/ephemeral-vm-recipe-diagnostics' -import { - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY -} from '../../shared/protocol-version' -import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' -import { - assertRecipeWorkspaceCreateSupported, - forwardedCreateFields, - RecipeWorkspaceResult as WorkspaceResult, - type RecipeWorkspaceCreateParams, - type RecipeWorkspaceCreation -} from './recipe-workspace-create-params' -import { - RECIPE_WORKSPACE_CREATE_FAILED_CODE, - type RecipeWorkspaceCreateFailureData, - type RecipeWorkspaceCreatePhase -} from '../../shared/recipe-workspace-create-progress' -import type { EphemeralVmProvisionIpcResult } from './environment-provision' - -export type { RecipeWorkspaceCreateParams, RecipeWorkspaceCreation } -const ENVIRONMENT_OUTCOME = { - destroyed: 'destroyed', - failed: 'destroy-failed', - disabled: 'destroy-disabled' -} as const satisfies Record> - -/** Never claim a destroy that did not happen: a failed or disabled one leaves a billed machine. */ -function environmentOutcomeSentence( - environment: NonNullable, - runtimeId: string, - destroyError?: string -): string { - if (environment === 'destroyed') { - return 'Orca destroyed the new environment.' - } - if (environment === 'destroy-disabled') { - return `The recipe has no destroy step, so the environment (runtime ${runtimeId}) is still running; remove it with your provider.` - } - return `The environment (runtime ${runtimeId}) may still be running because destroying it failed${destroyError ? `: ${destroyError}` : ''}. Retry the cleanup from Settings > Cloud VMs in Orca.` -} - -/** A failed recipe create; `data` says which step failed and whether its VM was destroyed. */ -export class RecipeWorkspaceCreateError extends Error { - readonly code = RECIPE_WORKSPACE_CREATE_FAILED_CODE - readonly data: RecipeWorkspaceCreateFailureData - - constructor(message: string, data: RecipeWorkspaceCreateFailureData) { - super(message) - this.data = data - } -} - -/** - * Creates a workspace on a fresh recipe environment: provision (through the same main-side - * provisioning the desktop uses), register the project on the environment's Orca, then create or - * adopt the workspace there. Any failure after the VM exists destroys it before rethrowing. - */ -export async function createProvisionedRecipeWorkspace( - args: { - params: RecipeWorkspaceCreateParams - recipeId: string - checkoutMode: EphemeralVmCheckoutMode - /** Provisioned-root recipes receive the branch up front; orca-worktree ones pick it on the VM. */ - branchName?: string - projectId: string - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void - }, - ports: { - provision: ( - onPhase: (phase: RecipeWorkspaceCreatePhase) => void - ) => Promise - call: ( - environmentId: string, - method: string, - params: unknown - ) => Promise> - attach: (runtimeId: string, workspaceId: string) => void - /** Destroys the VM; `disabled` means the recipe has no destroy step, so nothing ran. */ - cleanup: ( - runtimeId: string - ) => Promise<{ outcome: 'destroyed' | 'failed' | 'disabled'; error?: string }> - } -): Promise { - const { params, recipeId } = args - assertRecipeWorkspaceCreateSupported(params, args.checkoutMode) - let phase: RecipeWorkspaceCreatePhase = 'running-create' - const enter = (next: RecipeWorkspaceCreatePhase): void => { - phase = next - args.onPhase?.(next) - } - const provisioned = await ports.provision(enter) - if (!provisioned.ok) { - const error = redactEphemeralVmRecipeDiagnosticText(provisioned.error) - const environment = provisioned.environmentCleanup - ? ENVIRONMENT_OUTCOME[provisioned.environmentCleanup] - : undefined - const data: RecipeWorkspaceCreateFailureData = { - phase, - recipeId, - ...(provisioned.errorCode ? { failureCode: provisioned.errorCode } : {}), - ...(provisioned.errorParams ? { failureParams: provisioned.errorParams } : {}), - ...(provisioned.runtimeId ? { runtimeId: provisioned.runtimeId } : {}), - ...(environment ? { environment } : {}) - } - throw new RecipeWorkspaceCreateError( - provisioned.runtimeId && environment - ? `${error} ${environmentOutcomeSentence(environment, provisioned.runtimeId)}` - : error, - data - ) - } - const runtimeId = provisioned.runtime.id - try { - const checkoutMode = getEphemeralVmRecipeResultCheckoutMode(provisioned.runtime.recipeResult) - const environmentId = - provisioned.connectionType === 'orca-server' - ? provisioned.environment.id - : provisioned.environmentId - if (!environmentId) { - throw new Error( - "This recipe's environment does not run an Orca server, so only the desktop app can create workspaces on it." - ) - } - if (checkoutMode === 'provisioned-root' && provisioned.connectionType !== 'ssh') { - throw new Error('Provisioned-root recipes currently require a direct SSH connection.') - } - const call = async (method: string, payload: unknown): Promise => { - args.signal?.throwIfAborted() - const response = await ports.call(environmentId, method, payload) - if (!response.ok) { - throw new Error(redactEphemeralVmRecipeDiagnosticText(response.error.message)) - } - return response.result - } - enter('checking-host') - const status = z - .object({ capabilities: z.array(z.string()) }) - .parse(await call('status.get', undefined)) - const requiredCapabilities = [ - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - ...(checkoutMode === 'provisioned-root' - ? [WORKTREE_PROVISIONED_ROOT_RUNTIME_CAPABILITY] - : []), - // The CLI checks prompt and presentation support itself when it launches the agent. - ...(params.createdWithAgent ? [AGENT_LAUNCH_RUNTIME_CAPABILITY] : []) - ] - if (!requiredCapabilities.every((capability) => status.capabilities.includes(capability))) { - throw new Error( - 'Update Orca on the recipe-created environment before creating this workspace.' - ) - } - enter('registering-project') - const projectRoot = getEphemeralVmRecipeResultProjectRoot(provisioned.runtime.recipeResult) - const setup = z - .object({ result: z.object({ repo: z.object({ id: z.string(), path: z.string() }) }) }) - .parse( - await call('projectHostSetup.setupExistingFolder', { - projectId: args.projectId, - hostId: 'local', - path: projectRoot, - kind: 'git', - setupMethod: 'imported-existing-folder' - }) - ) - enter('creating-workspace') - const repo = `id:${setup.result.repo.id}` - let result: z.infer - if (checkoutMode === 'provisioned-root') { - if ( - !args.branchName || - provisioned.connectionType !== 'ssh' || - !provisioned.expectedRefHead - ) { - throw new Error('The provisioned-root recipe did not report its checked-out start ref.') - } - result = WorkspaceResult.parse( - await call( - 'worktree.adoptProvisionedRoot', - WorktreeAdoptProvisionedRoot.parse({ - ...forwardedCreateFields(params), - repo, - branchNameOverride: args.branchName, - expectedPath: projectRoot, - expectedRefHead: provisioned.expectedRefHead, - cliProvenanceRequest: {} - }) - ) - ) - } else { - result = WorkspaceResult.parse( - await call('worktree.create', { - ...forwardedCreateFields(params), - repo, - cliProvenanceRequest: {} - }) - ) - } - ports.attach(runtimeId, result.worktree.id) - const warnings = provisioned.warnings.map((entry) => entry.message) - return { - ...result, - worktree: { - ...result.worktree, - hostId: toRuntimeExecutionHostId(environmentId), - runtimeOwnerEnvironmentId: environmentId - }, - recipe: { id: recipeId, runtimeId, environmentId, checkoutMode }, - ...(warnings.length > 0 ? { environmentWarnings: warnings } : {}) - } - } catch (error) { - const failedPhase = phase - const original = redactEphemeralVmRecipeDiagnosticText( - error instanceof Error ? error.message : String(error) - ) - enter('destroying-after-failure') - const cleaned = await ports.cleanup(runtimeId).then( - (result) => result, - (cleanupError: unknown) => ({ - outcome: 'failed' as const, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) - }) - ) - const data: RecipeWorkspaceCreateFailureData = { - phase: failedPhase, - recipeId, - runtimeId, - environment: ENVIRONMENT_OUTCOME[cleaned.outcome], - ...(cleaned.error - ? { destroyError: redactEphemeralVmRecipeDiagnosticText(cleaned.error) } - : {}) - } - throw new RecipeWorkspaceCreateError( - `${original} ${environmentOutcomeSentence(data.environment ?? 'destroy-failed', runtimeId, data.destroyError)}`, - data - ) - } -} diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index af566602f62..95240974d55 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -5,16 +5,27 @@ import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' -import { cleanupOwnedEphemeralVmRuntime } from '../ephemeral-vm/owned-runtime-cleanup' +import { releaseEphemeralVmRuntimeEnvironments } from '../ephemeral-vm/runtime-environment-release' +import { cleanupEphemeralVmRuntime } from '../ephemeral-vm/runtime-service' import { stopEphemeralVmRuntimeCleanup } from '../ephemeral-vm/runtime-cleanup-control' +import { removeEphemeralVmRuntimeSshTarget } from '../ephemeral-vm/runtime-ssh-cleanup' import { buildEphemeralVmRecipeCleanupCommand, buildEphemeralVmRecipeCleanupPayload } from '../../shared/ephemeral-vm-recipe-lifecycle-payload' +import { removeRuntimeOwnedSshTarget } from '../ephemeral-vm/runtime-ssh' import { getRuntimeRecipeContext } from './ephemeral-vm-recipe-context' -import { ephemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' +import { + ephemeralVmFailure, + ephemeralVmFailureFromError +} from '../../shared/ephemeral-vm-failure-copy' +import { invalidateRuntimeEnvironmentTransport } from './runtime-environments/runtime-environments' +import { retireRemovedRuntimeEnvironment } from './runtime-environments/runtime-environment-removal-cleanup' import { attachEphemeralVmRuntimeToWorkspace } from '../ephemeral-vm/runtime-attachment' -import { forgetInterruptedEphemeralVmProvision } from '../ephemeral-vm/runtime-provisioning-persistence' +import { + forgetInterruptedEphemeralVmProvision, + isEphemeralVmProvisionLive +} from '../ephemeral-vm/runtime-provisioning-persistence' export type EphemeralVmCleanupCommandResult = { runtimeId: string @@ -50,7 +61,67 @@ export function registerEphemeralVmRuntimeHandlers(store: Store): void { ipcMain.handle( 'ephemeralVm:cleanup', async (_event, args: { runtimeId: string }): Promise => { - return cleanupOwnedEphemeralVmRuntime(store, app.getPath('userData'), args.runtimeId) + const userDataPath = app.getPath('userData') + const runtime = listEphemeralVmRuntimes(userDataPath).find( + (entry) => entry.id === args.runtimeId + ) + if (!runtime) { + throw new Error(`Unknown ephemeral VM runtime: ${args.runtimeId}`) + } + if (runtime.status === 'provisioning' && isEphemeralVmProvisionLive(runtime.id)) { + // Why: don't mark a create in flight as cleanup_failed; its own outcome settles the row. + throw new Error(`Ephemeral VM runtime is still provisioning: ${runtime.id}`) + } + let result + if (runtime.cleanupStatus === 'succeeded') { + result = { ok: true as const, runtime, skipped: false } + } else { + let resolved: ReturnType + try { + resolved = getRuntimeRecipeContext(store, userDataPath, runtime.id) + } catch (error) { + const failed = updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { + status: 'cleanup_failed', + cleanupStatus: 'failed', + cleanupLastAttemptAt: Date.now(), + cleanupLastError: ephemeralVmFailureFromError(error) + }) + return removeEphemeralVmRuntimeSshTarget({ + userDataPath, + runtime: failed, + removeTarget: removeRuntimeOwnedSshTarget + }) + } + result = await cleanupEphemeralVmRuntime({ + userDataPath, + repoPath: resolved.repoPath, + recipe: resolved.recipe, + runtimeId: runtime.id + }) + } + if (result.ok) { + try { + await releaseEphemeralVmRuntimeEnvironments(userDataPath, runtime, (environmentId) => { + void retireRemovedRuntimeEnvironment( + environmentId, + invalidateRuntimeEnvironmentTransport, + store, + userDataPath + ) + }) + } catch { + // Cleanup of provider resources matters more than hiding a stale local + // environment row; users can still remove that manually. + } + } + if (!result.ok) { + return result.runtime + } + return removeEphemeralVmRuntimeSshTarget({ + userDataPath, + runtime: result.runtime, + removeTarget: removeRuntimeOwnedSshTarget + }) } ) diff --git a/src/main/ipc/ephemeral-vm.ts b/src/main/ipc/ephemeral-vm.ts index 369a69d289e..e322668b02e 100644 --- a/src/main/ipc/ephemeral-vm.ts +++ b/src/main/ipc/ephemeral-vm.ts @@ -1,27 +1,78 @@ import { app, ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' -import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-recipes' -import { redactEphemeralVmRecipeDiagnosticText } from '../../shared/ephemeral-vm-recipe-diagnostics' +import { + getEphemeralVmRecipeResultConnection, + type EphemeralVmRecipeDoctorResult +} from '../../shared/ephemeral-vm-recipes' +import { + getEphemeralVmRecipeResultWarnings, + redactEphemeralVmRecipeDiagnosticText, + type EphemeralVmRecipeResultWarning +} from '../../shared/ephemeral-vm-recipe-diagnostics' +import { getProvisionedRootRecipeRepoUrl } from '../../shared/ephemeral-vm-recipe-repo-url' // Import the Node-only doctor directly so browser consumers of the barrel do not bundle fs/path. import { doctorEphemeralVmRecipe } from '../../shared/ephemeral-vm-recipe-doctor' -import { reconcileInterruptedEphemeralVmProvisionsOnStartup } from '../ephemeral-vm/runtime-provisioning-persistence' +import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' import { - provisionRecipeEnvironment, - type EphemeralVmProvisionIpcResult -} from '../ephemeral-vm/environment-provision' + requireEphemeralVmRecipeResult, + type EphemeralVmProvisionedRuntimeRecord +} from '../../shared/ephemeral-vm-runtimes' +import { addEnvironmentFromPairingCode } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { + redactRuntimeEnvironment, + type PublicKnownRuntimeEnvironment +} from '../../shared/remote-runtime/host-catalog/runtime-environments' +import { + cleanupEphemeralVmRuntime, + provisionEphemeralVmRuntime +} from '../ephemeral-vm/runtime-service' +import { connectRuntimeOwnedSshTarget } from '../ephemeral-vm/runtime-ssh' +import { reconcileInterruptedEphemeralVmProvisionsOnStartup } from '../ephemeral-vm/runtime-provisioning-persistence' import { getRecipeRepo, listRecipeCatalog, listRecipes, + resolveRecipeForRepo, type EphemeralVmRecipeCatalogEntry } from './ephemeral-vm-recipe-context' import { registerEphemeralVmRuntimeHandlers } from './ephemeral-vm-runtime-handlers' import type { PluginService } from '../plugins/plugin-service' import { getApprovedPluginVmRecipes } from '../plugins/plugin-approved-vm-recipes' +import { resolveProvisionedRootSource } from '../ephemeral-vm/provisioned-root-source' +import { getRuntimeEnvironmentRegistryRoot } from './runtime-environments/runtime-environment-registry-root' +import { + ephemeralVmFailure, + pickEphemeralVmFailureCode, + type EphemeralVmFailure +} from '../../shared/ephemeral-vm-failure-copy' const activeProvisionControllers = new Map() -export type { EphemeralVmProvisionIpcResult } +export type EphemeralVmProvisionIpcResult = + | { + ok: true + connectionType: 'orca-server' + runtime: EphemeralVmProvisionedRuntimeRecord + environment: PublicKnownRuntimeEnvironment + stderr: string + warnings: EphemeralVmRecipeResultWarning[] + } + | { + ok: true + connectionType: 'ssh' + runtime: EphemeralVmProvisionedRuntimeRecord + sshTargetId: string + /** The managed Orca server the host runs; its workspace lives there. */ + environmentId?: string + expectedRefHead?: string + stderr: string + warnings: EphemeralVmRecipeResultWarning[] + } + | ({ + ok: false + stderr: string + stdout: string + } & EphemeralVmFailure) export function registerEphemeralVmHandlers(store: Store, pluginService?: PluginService): void { ipcMain.removeHandler('ephemeralVm:listRecipes') @@ -78,6 +129,18 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin provisionId?: string } ): Promise => { + const repo = getRecipeRepo(store, args.repoId) + if (!repo.ok) { + return provisionFailure(repo.failure) + } + const recipe = resolveRecipeForRepo( + repo.repo.path, + args.recipeId, + await getApprovedPluginVmRecipes(pluginService) + ) + if (!recipe) { + return provisionFailure(ephemeralVmFailure('recipeNotFound', { recipeId: args.recipeId })) + } const controller = args.provisionId ? new AbortController() : null if (args.provisionId && controller) { activeProvisionControllers.set(args.provisionId, controller) @@ -94,17 +157,129 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin } // Retain cancellation registration until every signal-consuming provisioning phase settles. try { - return await provisionRecipeEnvironment( - store, - app.getPath('userData'), - args, - await getApprovedPluginVmRecipes(pluginService), - { - signal: controller?.signal, - onStdout: (chunk) => sendProvisionEvent('stdout', chunk), - onStderr: (chunk) => sendProvisionEvent('stderr', chunk) + let recipeRepoUrl = repo.repo.gitRemoteIdentity?.remoteUrl + let sourceRef = args.ref + let expectedRefHead: string | undefined + if (recipe.checkoutMode === 'provisioned-root') { + const source = await resolveProvisionedRootSource( + store, + repo.repo, + args.ref, + controller?.signal + ) + if (controller?.signal.aborted) { + return provisionFailure(ephemeralVmFailure('provisionCancelled')) } + if (!source) { + return provisionFailure( + args.ref + ? ephemeralVmFailure('startRefUnresolved', { ref: args.ref }) + : ephemeralVmFailure('defaultStartRefUnresolved') + ) + } + sourceRef = source.ref + expectedRefHead = source.head + recipeRepoUrl = source.remoteUrl ?? recipeRepoUrl + } + const repoUrl = getProvisionedRootRecipeRepoUrl(recipe.checkoutMode, recipeRepoUrl) + const result = await provisionEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + repoId: repo.repo.id, + recipe, + projectId: args.projectId, + workspaceId: args.workspaceId, + workspaceName: args.workspaceName, + ...(repoUrl ? { repoUrl } : {}), + ...(args.branch ? { branch: args.branch } : {}), + ...(sourceRef ? { ref: sourceRef } : {}), + ...(expectedRefHead ? { expectedRefHead } : {}), + ...(controller ? { signal: controller.signal } : {}), + onStdout: (chunk) => sendProvisionEvent('stdout', chunk), + onStderr: (chunk) => sendProvisionEvent('stderr', chunk) + }) + if (!result.ok) { + return { + ok: false, + error: result.start.error, + ...pickEphemeralVmFailureCode(result.start), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + const connection = getEphemeralVmRecipeResultConnection(result.start.result) + if (connection.type === 'ssh') { + try { + const ssh = await connectRuntimeOwnedSshTarget({ + runtimeId: result.runtime.id, + connection + }) + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { + sshTargetId: ssh.targetId, + runtimeEnvironmentId: ssh.environmentId + }) + ) + return { + ok: true, + connectionType: 'ssh', + runtime, + sshTargetId: ssh.targetId, + environmentId: ssh.environmentId, + ...(expectedRefHead ? { expectedRefHead } : {}), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), + warnings: getEphemeralVmRecipeResultWarnings(result.start.result) + } + } catch (error) { + await cleanupEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + recipe, + runtimeId: result.runtime.id + }).catch(() => undefined) + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + } + + let environment: ReturnType + try { + environment = addEnvironmentFromPairingCode(getRuntimeEnvironmentRegistryRoot(), { + name: buildEphemeralEnvironmentName(repo.repo.displayName, result.runtime.id), + pairingCode: connection.pairingCode, + source: 'ephemeral-vm' + }) + } catch (error) { + await cleanupEphemeralVmRuntime({ + userDataPath: app.getPath('userData'), + repoPath: repo.repo.path, + recipe, + runtimeId: result.runtime.id + }).catch(() => undefined) + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + stdout: redactEphemeralVmRecipeDiagnosticText(result.start.stdout), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr) + } + } + const runtime = requireEphemeralVmRecipeResult( + updateEphemeralVmRuntimeStatus(app.getPath('userData'), result.runtime.id, { + runtimeEnvironmentId: environment.id + }) ) + return { + ok: true, + connectionType: 'orca-server', + runtime, + environment: redactRuntimeEnvironment(environment), + stderr: redactEphemeralVmRecipeDiagnosticText(result.start.stderr), + warnings: getEphemeralVmRecipeResultWarnings(result.start.result) + } } finally { if (args.provisionId) { activeProvisionControllers.delete(args.provisionId) @@ -126,3 +301,11 @@ export function registerEphemeralVmHandlers(store: Store, pluginService?: Plugin } ) } + +function buildEphemeralEnvironmentName(repoName: string, runtimeId: string): string { + return `${repoName} VM ${runtimeId.slice(-8)}` +} + +function provisionFailure(failure: EphemeralVmFailure): EphemeralVmProvisionIpcResult { + return { ok: false, ...failure, stdout: '', stderr: '' } +} diff --git a/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts b/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts index c752933a5bc..39e40eb1fbf 100644 --- a/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts +++ b/src/main/ipc/filesystem/filesystem-listing-process-cleanup.ts @@ -1,8 +1,8 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { killSpawnedRipgrepProcess } from '../../../shared/ripgrep/ripgrep-process-availability' export type FilesystemListingProcess = { - child: ChildProcessHandle + child: ChildProcess isDone: () => boolean finish: (error?: Error) => void } diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts index c88c0797a94..bb1108690bc 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-child-slot.ts @@ -1,16 +1,16 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { removeWatcherCanaryDirectory } from './parcel-watcher-canary-directory' export class WatcherChildSlot { - child: ChildProcessHandle | null = null - terminating: ChildProcessHandle | null = null + child: ChildProcess | null = null + terminating: ChildProcess | null = null canaryDir: string | null = null removeCanary(): void { this.canaryDir = removeWatcherCanaryDirectory(this.canaryDir) } - beginTermination(proc: ChildProcessHandle): void { + beginTermination(proc: ChildProcess): void { this.terminating = proc this.removeCanary() } diff --git a/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts b/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts index 1d1c33e7a66..550cda225de 100644 --- a/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts +++ b/src/main/ipc/filesystem/watcher-process/parcel-watcher-owned-children.ts @@ -1,14 +1,14 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { watcherChildPhysicalExit, requireWatcherChildTermination } from './parcel-watcher-child-termination' export class WatcherOwnedChildren { - private readonly children = new Set() + private readonly children = new Set() private disposal: Promise | null = null - track(child: ChildProcessHandle): ChildProcessHandle { + track(child: ChildProcess): ChildProcess { this.children.add(child) // Reuse launch-owned physical-exit evidence, including close without exit after spawn failure. void watcherChildPhysicalExit(child).then(() => { diff --git a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts index db7dd96a81c..3c499f85538 100644 --- a/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts +++ b/src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.ts @@ -1,5 +1,5 @@ /** Poll inside WSL so distro shutdown kills the watcher instead of Windows UNC polling repeatedly waking it. */ -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { StringDecoder } from 'node:string_decoder' import type { WebContents } from 'electron' import type { Event as WatcherEvent } from '@parcel/watcher' @@ -234,7 +234,7 @@ export async function createWslWatcher( } } - let child: PipedChildProcess + let child: ChildProcessWithoutNullStreams const releaseChildReservation = watcherChildRegistry.reserveWatcherChild() if (!releaseChildReservation) { throw new watcherChildRegistry.WatcherChildCapacityError() diff --git a/src/main/ipc/filesystem/watchers/wsl-watcher-spawn.ts b/src/main/ipc/filesystem/watchers/wsl-watcher-spawn.ts index 88db2150c2f..dd5c599ad03 100644 --- a/src/main/ipc/filesystem/watchers/wsl-watcher-spawn.ts +++ b/src/main/ipc/filesystem/watchers/wsl-watcher-spawn.ts @@ -1,9 +1,12 @@ import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { resolveWslInteropSpawnCwd } from '../../../wsl/execution/wsl-interop-spawn-directory' /** Start the in-distro poll script; process-host applies the internal distro allowlist. */ -export function spawnWslWatcherProcess(distro: string, linuxPath: string): PipedChildProcess { +export function spawnWslWatcherProcess( + distro: string, + linuxPath: string +): ChildProcessWithoutNullStreams { return spawnProcess({ program: 'wsl.exe', args: ['-d', distro, '--exec', 'sh', '-s', '--', linuxPath], diff --git a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts b/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts index ffbbcd28194..1cb89348790 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-request-connections.ts @@ -280,6 +280,8 @@ function getSharedControlConnection( environmentId, clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, ...sharedControlEnvironmentPolicy(environmentId), + // Ws pongs can come from a relay hop or a runtime whose request path is stuck (#39785). + appHeartbeat: {}, // R39: every ready socket, including after a reconnect, re-declares this installation. onReady: () => declareWslHostClient(environmentId, (method, params, timeoutMs) => diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index feded50d21b..42f92f7445e 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -1,4 +1,10 @@ -import { ipcMain, BrowserWindow, systemPreferences, type MessagePortMain } from 'electron' +import { + ipcMain, + BrowserWindow, + systemPreferences, + type IpcMainInvokeEvent, + type MessagePortMain +} from 'electron' import { abortWhenRendererGone } from './renderer-lifetime-abort' import { join } from 'node:path' import { writeFile, unlink } from 'node:fs/promises' @@ -260,12 +266,16 @@ export function registerSpeechHandlers(store: Store): void { } ) - ipcMain.handle('speech:stopDictation', async (_event, sessionId = 'desktop') => { - const owner = getDesktopOwner(_event.sender.id, sessionId) - const listener = dictationListeners.get(_event.sender.id) - await getSpeechSttService(store).stopDictation(owner) - if (listener?.owner === owner) { - listener.cleanup() + const handleStop = + (discard: boolean) => + async (event: IpcMainInvokeEvent, sessionId = 'desktop'): Promise => { + const owner = getDesktopOwner(event.sender.id, sessionId) + const listener = dictationListeners.get(event.sender.id) + await getSpeechSttService(store).stopDictation(owner, { discard }) + if (listener?.owner === owner) { + listener.cleanup() + } } - }) + ipcMain.handle('speech:stopDictation', handleStop(false)) + ipcMain.handle('speech:cancelDictation', handleStop(true)) } diff --git a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts index 918193203a8..dda2f33008f 100644 --- a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts @@ -1,11 +1,10 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' -import { spawnSync } from 'node:child_process' +import { spawnSync, type ChildProcessWithoutNullStreams } from 'node:child_process' import { createServer, type Server, type Socket } from 'node:net' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess as Bridge } from '@orca/process-host/process-spec' import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge' import { orcadBashStdioBridgeCommand } from './orcad-stdio-bridge-script' @@ -39,7 +38,10 @@ afterAll(() => { rmSync(scratch, { recursive: true, force: true }) }) -function spawnBridge(port: number, env: Partial = {}): Bridge { +function spawnBridge( + port: number, + env: Partial = {} +): ChildProcessWithoutNullStreams { return spawnProcess({ program: '/bin/sh', args: ['-c', orcadBashStdioBridgeCommand(port)], @@ -51,7 +53,7 @@ function realCat(): string { return spawnSync('sh', ['-c', 'command -v cat'], { encoding: 'utf8' }).stdout.trim() } -function exitOf(child: Bridge): Promise { +function exitOf(child: ChildProcessWithoutNullStreams): Promise { return new Promise((resolve) => child.once('exit', (code) => resolve(code))) } diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-attach-publish.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-attach-publish.ts index a46da09f7d8..9e859841a29 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-attach-publish.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-attach-publish.ts @@ -12,7 +12,8 @@ import type { DeferredStructuredAgentSessionEventSink } from '../journal-ingress import { indexProviderChild } from '../host/structured-agent-session-provider-child' import { noteStructuredAgentSessionProviderStarted } from '../startup/structured-agent-session-provider-started' import type { StructuredAgentSessionStartupAttempt } from '../startup/structured-agent-session-startup-attempt-contract' -import { structuredAgentSessionEndedEventExit } from '../termination/structured-agent-session-child-exit' +import '../termination/structured-agent-session-child-exit' +import { structuredAgentSessionEndedEventExit } from '../termination/structured-agent-session-child-exit-record' import { applyStructuredRewindRecovery, readStructuredRewindRecovery, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-start-telemetry.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-start-telemetry.test.ts similarity index 68% rename from src/main/native-chat/agent-session-wire/structured-agent-session-start-telemetry.test.ts rename to src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-start-telemetry.test.ts index 31d95661f38..91decedd1c8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-start-telemetry.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-start-telemetry.test.ts @@ -1,13 +1,9 @@ import { beforeEach, expect, it, vi } from 'vitest' -import { track } from '../../telemetry/client' -import { - CALLER, - attachParams, - hostTestState -} from './host/testing/structured-agent-session-host-test-harness' -import './host/testing/structured-agent-session-create-test-fixture' +import { track } from '../../../../telemetry/client' +import { CALLER, attachParams, hostTestState } from './structured-agent-session-host-test-harness' +import './structured-agent-session-create-test-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) beforeEach(() => vi.mocked(track).mockClear()) it('keeps a proved process live when telemetry capture fails', async () => { diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts index 66b8e459c31..3b58914e51a 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-child-exit.ts @@ -106,8 +106,6 @@ export function settleStructuredAgentSessionChildExit< }) } -export { structuredAgentSessionEndedEventExit, type StructuredAgentSessionChildExit } - export async function endExitedStructuredAgentSessionChildUnderSerialize< TSession extends StructuredAgentSessionChildExitSession >( diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-event-recovery.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-event-recovery.ts index 2f6d3c981d9..c9b24de2696 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-event-recovery.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-event-recovery.ts @@ -13,10 +13,10 @@ import { settleStructuredAgentSessionOptionsReported } from '../startup/structur import { endExitedStructuredAgentSessionChildUnderSerialize, settleStructuredAgentSessionChildExit, - type StructuredAgentSessionChildExit, type StructuredAgentSessionChildExitContext, type StructuredAgentSessionGenerationEnded } from './structured-agent-session-child-exit' +import type { StructuredAgentSessionChildExit } from './structured-agent-session-child-exit-record' import type { StructuredAgentSessionHostRuntimeState } from '../host/structured-agent-session-host-runtime-state' import { openStructuredAgentSessionProviderChild, diff --git a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime.ts b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime.ts index 64654f8d098..5eef08027b8 100644 --- a/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime.ts +++ b/src/main/native-chat/agent-session-wire/termination/structured-agent-session-host-lifetime.ts @@ -23,7 +23,7 @@ import type { StructuredAgentSessionHostSession, StructuredAgentSessionProviderChild } from '../host/structured-agent-session-host-types' -import type { StructuredAgentSessionChildExit } from './structured-agent-session-child-exit' +import type { StructuredAgentSessionChildExit } from './structured-agent-session-child-exit-record' import { structuredAgentSessionConversationFence } from '../host/structured-agent-session-provider-child' import { markStructuredQueueReopen } from '../delivery/structured-agent-session-queued-pause' import type { StructuredAgentSessionStopCause } from './structured-agent-session-stop-cause' diff --git a/src/main/opencode/opencode-launch-model-context.ts b/src/main/opencode/opencode-launch-model-context.ts index 08d2dc8854e..2d46321dc10 100644 --- a/src/main/opencode/opencode-launch-model-context.ts +++ b/src/main/opencode/opencode-launch-model-context.ts @@ -10,7 +10,7 @@ import { withTimeout } from '../../shared/promise-timeout-fallback' import { createOutputSink } from '@orca/process-host/bounded-output-sink' import { readFetchResponseJsonWithinLimit } from '../../shared/fetch-response-body' import { cancelUnreadResponseBody } from '../lib/unread-response-body' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { createProviderSpawnSpec } from '../provider-process/provider-process-supervisor' import { stopSupervisedChildProcess } from '../provider-process/supervised-child-process-stop' import { guardSupervisedProviderGroup } from '../provider-process/provider-group-orphan-guard' @@ -172,7 +172,7 @@ export async function probeOpenCodeLaunchModelContext(options: { /** Only the supervisor’s normal stop/relayed exit proves its detached server group is gone. * Forced supervisor teardown and failed group reap (exit 1) prove nothing. */ async function stopSupervisedPreflight( - child: ChildProcessHandle, + child: ChildProcess, closed: Promise ): Promise { if (!child.pid) { diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index b305803b629..0f463081e63 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -28,6 +28,8 @@ import { createOrcadStartupTiming } from './orcad-startup-timing' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { restoreOrcadTerminalAuthority } from './orcad-restored-terminal-authority' import { installOrcadFeatureReadiness } from '../runtime/rpc/orcad-feature-readiness' +import { ORCA_SERVE_SUPERVISED_ENV } from '../../shared/serve-supervised-terminal-durability' +import { startOrcadEventLoopWatchdog } from './orcad-event-loop-watchdog' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' let closeOrcadObservability = (): Promise => Promise.resolve() @@ -63,6 +65,11 @@ async function startOrcadRuntime( registerCleanup: (cleanup: OrcadRuntimeCleanup) => void ): Promise> { const { time: timed, report: reportStartupTiming } = createOrcadStartupTiming() + // Read before startOrcadDaemon consumes the supervised flag; only a supervised server exits on a long stall. + const eventLoopWatchdog = startOrcadEventLoopWatchdog({ + supervised: process.env[ORCA_SERVE_SUPERVISED_ENV] === '1' + }) + registerCleanup(() => eventLoopWatchdog?.stop()) // Overlap login-shell probing with imports and store startup. const loginEnvironment = adoptWslHostLoginEnvironmentLogged() const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision') diff --git a/src/main/orcad/orcad-event-loop-watchdog.test.ts b/src/main/orcad/orcad-event-loop-watchdog.test.ts new file mode 100644 index 00000000000..837e200033e --- /dev/null +++ b/src/main/orcad/orcad-event-loop-watchdog.test.ts @@ -0,0 +1,83 @@ +import { spawn } from 'node:child_process' +import { afterEach, expect, it } from 'vitest' +import { + ORCAD_EVENT_LOOP_WATCHDOG_ENV, + ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE, + startOrcadEventLoopWatchdog, + type OrcadEventLoopWatchdog, + type OrcadEventLoopWatchdogMessage +} from './orcad-event-loop-watchdog' + +const watchdogs: OrcadEventLoopWatchdog[] = [] +afterEach(() => watchdogs.splice(0).forEach((watchdog) => watchdog.stop())) + +/** Models a synchronous call that never yields the event loop; the worker's clock cannot be faked. */ +function blockMainThread(ms: number): void { + // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread + const until = Date.now() + ms + // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread + while (Date.now() < until) { + // Busy-wait. + } +} + +it('reports a blocked event loop from a thread the block cannot starve, then its recovery (#34410)', async () => { + const watchdog = startOrcadEventLoopWatchdog({ + supervised: false, + env: {}, + timings: { beatIntervalMs: 20, checkIntervalMs: 50, warnAfterMs: 300 } + }) + expect(watchdog).not.toBeNull() + watchdogs.push(watchdog!) + const messages: OrcadEventLoopWatchdogMessage[] = [] + watchdog!.worker.on('message', (message: OrcadEventLoopWatchdogMessage) => messages.push(message)) + await expect.poll(() => messages.map((message) => message.type)).toEqual(['started']) + + blockMainThread(900) + + await expect + .poll(() => messages.map((message) => message.type), { timeout: 2000 }) + .toEqual(['started', 'stalled', 'recovered']) + const stalled = messages[1] + expect(stalled.type === 'stalled' && stalled.blockedMs >= 300).toBe(true) +}) + +it('can be turned off', () => { + expect( + startOrcadEventLoopWatchdog({ supervised: true, env: { [ORCAD_EVENT_LOOP_WATCHDOG_ENV]: '0' } }) + ).toBeNull() +}) + +// Why the longer timeout: the child must boot a runtime and a worker before its loop blocks. +it('ends a supervised process whose event loop stays blocked past the exit bound', async () => { + // A child process stands in for orcad so the test runner survives the kill. + const script = ` + const { Worker } = require('node:worker_threads') + const worker = new Worker(process.env.WATCHDOG_SOURCE, { + eval: true, + workerData: { + beat: new SharedArrayBuffer(4), + checkIntervalMs: 50, + warnAfterMs: 100, + exitAfterMs: 300 + } + }) + worker.once('message', () => { + const until = Date.now() + 10000 + while (Date.now() < until) {} + process.exit(0) + }) + ` + const child = spawn(process.execPath, ['-e', script], { + env: { ...process.env, WATCHDOG_SOURCE: ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE }, + stdio: ['ignore', 'ignore', 'pipe'] + }) + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) + const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( + // close, not exit: stderr may still hold the worker's last line when exit fires. + (resolve) => child.once('close', (code, signal) => resolve({ code, signal })) + ) + expect(exit.code === 0 && exit.signal === null).toBe(false) + expect(stderr).toContain('exiting so the service manager restarts it') +}, 20_000) diff --git a/src/main/orcad/orcad-event-loop-watchdog.ts b/src/main/orcad/orcad-event-loop-watchdog.ts new file mode 100644 index 00000000000..e2e87cb5690 --- /dev/null +++ b/src/main/orcad/orcad-event-loop-watchdog.ts @@ -0,0 +1,131 @@ +// A blocked orcad event loop keeps its process and listener alive while it accepts nothing (#34410). +// The check runs on a worker thread, which a blocked main thread cannot starve. +import inspector from 'node:inspector' +import type { Worker } from 'node:worker_threads' +import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' + +export const ORCAD_EVENT_LOOP_WATCHDOG_ENV = 'ORCA_ORCAD_EVENT_LOOP_WATCHDOG' +const BEAT_INTERVAL_MS = 1_000 +const CHECK_INTERVAL_MS = 5_000 +/** Logged so a support bundle shows the stall even when nothing else is written. */ +const WARN_AFTER_MS = 30_000 +/** Well beyond any legitimate synchronous work; only a supervised server, which its service manager restarts, exits. */ +const EXIT_AFTER_MS = 5 * 60_000 + +export type OrcadEventLoopWatchdogData = { + beat: SharedArrayBuffer + checkIntervalMs: number + warnAfterMs: number + /** Null never exits; the watchdog only reports. */ + exitAfterMs: number | null +} + +export type OrcadEventLoopWatchdogMessage = + | { type: 'started' } + | { type: 'stalled'; blockedMs: number } + | { type: 'recovered'; blockedMs: number } + +// Plain source, like other eval workers here, so bundling and minification cannot change what the worker runs. +export const ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE = ` +const { workerData: data, parentPort } = require('node:worker_threads') +const fs = require('node:fs') +const beat = new Int32Array(data.beat) +const log = (line) => { try { fs.writeSync(2, line + '\\n') } catch {} } +let lastBeat = Atomics.load(beat, 0) +let lastBeatSeenAt = Date.now() +let lastTickAt = lastBeatSeenAt +let stalled = false +parentPort.postMessage({ type: 'started' }) +setInterval(() => { + const now = Date.now() + const tickGapMs = now - lastTickAt + lastTickAt = now + const current = Atomics.load(beat, 0) + if (current !== lastBeat) { + lastBeat = current + if (stalled) { + stalled = false + parentPort.postMessage({ type: 'recovered', blockedMs: now - lastBeatSeenAt }) + } + lastBeatSeenAt = now + return + } + // System sleep pauses both threads; restart the silence window instead of blaming orcad. + if (tickGapMs < 0 || tickGapMs > data.checkIntervalMs * 3) { + lastBeatSeenAt = now + return + } + const blockedMs = now - lastBeatSeenAt + if (!stalled && blockedMs >= data.warnAfterMs) { + stalled = true + log('[orcad] event loop blocked for ' + Math.round(blockedMs / 1000) + 's; requests are not being answered') + parentPort.postMessage({ type: 'stalled', blockedMs }) + } + if (data.exitAfterMs !== null && blockedMs >= data.exitAfterMs) { + log('[orcad] event loop blocked for ' + Math.round(blockedMs / 1000) + 's; exiting so the service manager restarts it') + // A worker cannot run the main thread's exit handlers; a signal ends the whole process. + process.kill(process.pid, 'SIGKILL') + } +}, data.checkIntervalMs) +` + +export type OrcadEventLoopWatchdog = { stop: () => void; worker: Worker } + +export function startOrcadEventLoopWatchdog(options: { + supervised: boolean + env?: NodeJS.ProcessEnv + timings?: Partial< + Pick + > & { + beatIntervalMs?: number + } +}): OrcadEventLoopWatchdog | null { + const env = options.env ?? process.env + // Debugger pauses block the loop by design. + if (env[ORCAD_EVENT_LOOP_WATCHDOG_ENV] === '0' || inspector.url()) { + return null + } + const beat = new SharedArrayBuffer(4) + const beats = new Int32Array(beat) + const data: OrcadEventLoopWatchdogData = { + beat, + checkIntervalMs: options.timings?.checkIntervalMs ?? CHECK_INTERVAL_MS, + warnAfterMs: options.timings?.warnAfterMs ?? WARN_AFTER_MS, + exitAfterMs: + options.timings?.exitAfterMs !== undefined + ? options.timings.exitAfterMs + : options.supervised + ? EXIT_AFTER_MS + : null + } + let worker: Worker + try { + worker = spawnWorkerThread(ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE, { + eval: true, + name: 'orcad-event-loop-watchdog', + workerData: data + }) + } catch (error) { + console.warn('[orcad] could not start the event loop watchdog', error) + return null + } + worker.on('message', (message: OrcadEventLoopWatchdogMessage) => { + if (message.type === 'recovered') { + console.warn(`[orcad] event loop recovered after ${Math.round(message.blockedMs / 1000)}s`) + } + }) + worker.on('error', (error) => console.warn('[orcad] event loop watchdog failed', error)) + worker.unref() + const timer = setInterval( + () => Atomics.add(beats, 0, 1), + options.timings?.beatIntervalMs ?? BEAT_INTERVAL_MS + ) + timer.unref() + return { + worker, + stop: () => { + clearInterval(timer) + void worker.terminate() + } + } +} diff --git a/src/main/orcad/orcad-managed-idle-exit-host.ts b/src/main/orcad/orcad-managed-idle-exit-host.ts index 9700765063b..cf8c9eb7608 100644 --- a/src/main/orcad/orcad-managed-idle-exit-host.ts +++ b/src/main/orcad/orcad-managed-idle-exit-host.ts @@ -1,5 +1,5 @@ import { getAppEnvironment } from '../../shared/app-environment' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc-shutdown' +import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' import type { OrcadIdleExitEvidence } from './orcad-idle-exit-monitor' import { activationFenceExists, diff --git a/src/main/orcad/orcad-managed-idle-exit.ts b/src/main/orcad/orcad-managed-idle-exit.ts index f655d746ce5..cc77791741b 100644 --- a/src/main/orcad/orcad-managed-idle-exit.ts +++ b/src/main/orcad/orcad-managed-idle-exit.ts @@ -3,7 +3,7 @@ import { stat } from 'node:fs/promises' import { join } from 'node:path' import { RELAY_INSTALL_LOCK_NAME } from '../../shared/relay-install-lock-name' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc-shutdown' +import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' import { ORCAD_IDLE_EXIT_TIMEOUT_MS, diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-left-behind-session-rows.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-left-behind-session-rows.ts index c56864fe0e7..40f365b7988 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-left-behind-session-rows.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-left-behind-session-rows.ts @@ -1,6 +1,7 @@ import type { BrowserWorkspace } from '../../../shared/browser-workspace-types' import type { TabGroup } from '../../../shared/tab-types' -import { ORCA_BROWSER_PARTITION } from '../../../shared/constants' +import '../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../shared/browser/browser-session-partition' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { ownedEditorFileId } from '../../../shared/workspace-session/workspace-session-pane-ownership' import { isOrcadSourceTabHost } from './orcad-source-workspace-session-eligibility' diff --git a/src/main/ports/advertised-url-watcher-pid-validation.test.ts b/src/main/ports/advertised-url-watcher-pid-validation.test.ts index 21b2efb87e7..423d8454261 100644 --- a/src/main/ports/advertised-url-watcher-pid-validation.test.ts +++ b/src/main/ports/advertised-url-watcher-pid-validation.test.ts @@ -146,3 +146,33 @@ describe('AdvertisedUrlWatcher.lookup PID validation', () => { expect(watcher.lookup(WORKTREE, 3001, 200)).toBeUndefined() }) }) + +describe('workspace-grouped listener reconciliation', () => { + it('keeps snapshots isolated and expires changed or absent listeners', () => { + const watcher = new AdvertisedUrlWatcher() + const initial = new Map([ + ['a', [{ port: 3001, pid: 100 }]], + ['b', [{ port: 3001, pid: 200 }]], + ['c', [{ port: 3002, pid: 300 }]] + ]) + watcher.reconcileWorkspaces(initial) + watcher.bindPty('a-pty', 'a') + watcher.bindPty('b-pty', 'b') + watcher.bindPty('c-pty', 'c') + watcher.ingest('a-pty', 'http://a.local:3001/\n') + watcher.ingest('b-pty', 'http://b.local:3001/\n') + watcher.ingest('c-pty', 'http://c.local:3002/\n') + + watcher.reconcileWorkspaces( + new Map([ + ['a', [{ port: 3001, pid: 100 }]], + ['b', [{ port: 3001, pid: 201 }]], + ['c', []] + ]) + ) + + expect(watcher.lookup('a', 3001, 100)?.origin).toBe('http://a.local:3001') + expect(watcher.lookup('b', 3001, 201)).toBeUndefined() + expect(watcher.lookup('c', 3002)).toBeUndefined() + }) +}) diff --git a/src/main/ports/advertised-url-watcher.ts b/src/main/ports/advertised-url-watcher.ts index 2312bd7c7f2..ceb32aa3b5b 100644 --- a/src/main/ports/advertised-url-watcher.ts +++ b/src/main/ports/advertised-url-watcher.ts @@ -234,12 +234,26 @@ export class AdvertisedUrlWatcher { observations: readonly AdvertisedUrlListenerObservation[] ): void { const observedByPort = observedListenersByPort(observations) - const worktreeSet = new Set(worktreeIds) + this.reconcileObservedWorkspaces(new Map(worktreeIds.map((id) => [id, observedByPort]))) + } + + reconcileWorkspaces( + observations: ReadonlyMap + ): void { + this.reconcileObservedWorkspaces( + new Map([...observations].map(([id, listeners]) => [id, observedListenersByPort(listeners)])) + ) + } + + private reconcileObservedWorkspaces( + observations: ReadonlyMap> + ): void { const removedEvents: AdvertisedUrlChangeEvent[] = [] for (const [key, entry] of this.cache) { const worktreeId = worktreeIdFromCacheKey(key, entry.port) - if (!worktreeSet.has(worktreeId)) { + const observedByPort = observations.get(worktreeId) + if (!observedByPort) { continue } const current = observedByPort.has(entry.port) @@ -264,7 +278,7 @@ export class AdvertisedUrlWatcher { } } - for (const worktreeId of worktreeSet) { + for (const [worktreeId, observedByPort] of observations) { this.scanSnapshots.delete(worktreeId) this.scanSnapshots.set(worktreeId, new Map(observedByPort)) while (this.scanSnapshots.size > MAX_ADVERTISED_URL_SCAN_SNAPSHOTS) { diff --git a/src/main/ports/local-workspace-port-attribution.ts b/src/main/ports/local-workspace-port-attribution.ts index d08481278bb..07697006e8c 100644 --- a/src/main/ports/local-workspace-port-attribution.ts +++ b/src/main/ports/local-workspace-port-attribution.ts @@ -1,4 +1,5 @@ import path from 'node:path' +import { WorkspacePortPathIndex } from './workspace-port-path-index' import { realpath } from 'node:fs/promises' import { withTimeout } from '../../shared/promise-timeout-fallback' import { blockedWslDistroForPath } from '../wsl/filesystem/wsl-unc-access-gate' @@ -84,7 +85,10 @@ export function attributePortToWorkspace( port: Pick, worktrees: WorkspacePortProbe[] ): WorkspacePortOwner | undefined { - return attributePortToNormalizedWorkspaces(port, normalizeWorkspacePortProbes(worktrees)) + return attributePortToNormalizedWorkspaces( + port, + new WorkspacePortPathIndex(normalizeWorkspacePortProbes(worktrees)) + ) } export function normalizeWorkspacePortProbes( @@ -136,16 +140,12 @@ export async function resolveWorkspacePortProbes( function attributePortToNormalizedWorkspaces( port: Pick, - worktrees: readonly NormalizedWorkspacePortProbe[] + index: WorkspacePortPathIndex ): WorkspacePortOwner | undefined { const cwd = port.cwd ? normalizeComparablePath(port.cwd) : null const commandLine = port.commandLine ? normalizeComparableText(port.commandLine) : null - const cwdMatch = cwd - ? pickDeepestMatching(worktrees, ({ normalizedPath }) => - isSameOrDescendant(cwd, normalizedPath) - ) - : undefined + const cwdMatch = cwd ? index.findCwd(cwd) : undefined if (cwdMatch) { return toOwner(cwdMatch.worktree, 'cwd') } @@ -154,17 +154,32 @@ function attributePortToNormalizedWorkspaces( return undefined } - const commandMatch = pickDeepestMatching(worktrees, ({ normalizedPath }) => - includesPathBoundary(commandLine, normalizedPath) - ) + const commandMatch = index.findCommand(commandLine) return commandMatch ? toOwner(commandMatch.worktree, 'command') : undefined } +type AttributedListeningPort = { port: RawListeningPort; owner: WorkspacePortOwner | undefined } + +export function attributePortsToWorkspaces( + ports: readonly RawListeningPort[], + worktrees: readonly NormalizedWorkspacePortProbe[] +): AttributedListeningPort[] { + let index: WorkspacePortPathIndex | undefined + return ports.map((port) => ({ + port, + owner: + port.cwd || port.commandLine + ? attributePortToNormalizedWorkspaces( + port, + (index ??= new WorkspacePortPathIndex(worktrees)) + ) + : undefined + })) +} + export function enrichPort( - port: RawListeningPort, - worktrees: readonly NormalizedWorkspacePortProbe[], + { port, owner }: AttributedListeningPort, urlWatcher: Pick ): WorkspacePort { - const owner = attributePortToNormalizedWorkspaces(port, worktrees) const base = { id: `${port.host}:${port.port}:${port.pid ?? 'unknown'}`, bindHost: port.host, @@ -193,25 +208,22 @@ export function enrichPort( } export function reconcileAdvertisedUrls( - ports: RawListeningPort[], + ports: readonly AttributedListeningPort[], worktrees: readonly NormalizedWorkspacePortProbe[], - urlWatcher: Pick + urlWatcher: Pick ): void { const observationsByWorktree = new Map() for (const worktree of worktrees) { observationsByWorktree.set(worktree.worktree.id, []) } - for (const port of ports) { - const owner = attributePortToNormalizedWorkspaces(port, worktrees) + for (const { port, owner } of ports) { if (!owner) { continue } observationsByWorktree.get(owner.worktreeId)?.push({ port: port.port, pid: port.pid }) } - for (const [worktreeId, observations] of observationsByWorktree) { - // Invalidate disappeared/changed listeners before lazy lookup can pin a stale banner. - urlWatcher.reconcileScan([worktreeId], observations) - } + // Invalidate disappeared/changed listeners before lazy lookup can pin a stale banner. + urlWatcher.reconcileWorkspaces(observationsByWorktree) } export function compareWorkspacePorts(a: WorkspacePort, b: WorkspacePort): number { @@ -250,41 +262,6 @@ function toOwner( } } -function pickDeepestMatching( - candidates: readonly T[], - predicate: (candidate: T) => boolean -): T | undefined { - let best: T | undefined - for (const candidate of candidates) { - if (!predicate(candidate)) { - continue - } - if (!best || candidate.normalizedPath.length > best.normalizedPath.length) { - best = candidate - } - } - return best -} - -function isSameOrDescendant(candidate: string, parent: string): boolean { - return candidate === parent || candidate.startsWith(`${parent}/`) -} - -function includesPathBoundary(commandLine: string, normalizedPath: string): boolean { - let index = commandLine.indexOf(normalizedPath) - while (index !== -1) { - const before = index === 0 ? '' : commandLine[index - 1] - const after = commandLine[index + normalizedPath.length] ?? '' - const startsOnBoundary = before === '' || /\s|["'=]/.test(before) - const endsOnBoundary = after === '' || /[\s"'/:]/.test(after) - if (startsOnBoundary && endsOnBoundary) { - return true - } - index = commandLine.indexOf(normalizedPath, index + normalizedPath.length) - } - return false -} - function normalizeComparablePath(input: string): string { if (input.startsWith('/')) { // Windows may evaluate remote POSIX paths; native resolve would reinterpret /repo as G:/repo. diff --git a/src/main/ports/local-workspace-port-scanner.test.ts b/src/main/ports/local-workspace-port-scanner.test.ts index a54ed0db7db..a9c88e6bf3c 100644 --- a/src/main/ports/local-workspace-port-scanner.test.ts +++ b/src/main/ports/local-workspace-port-scanner.test.ts @@ -2,7 +2,11 @@ import { afterEach, describe, expect, it, vi, type Mock } from 'vitest' import path from 'node:path' import type * as FsPromises from 'node:fs/promises' import { scanWorkspacePorts } from './local-workspace-port-scanner' -import { attributePortToWorkspace } from './local-workspace-port-attribution' +import { + attributePortToWorkspace, + attributePortsToWorkspaces, + normalizeWorkspacePortProbes +} from './local-workspace-port-attribution' import { resetWorkspacePortScanTimeoutBackoffForTests } from './local-workspace-port-scan-state' const runPortScanCommandMock = vi.hoisted(() => vi.fn()) @@ -26,8 +30,8 @@ vi.mock('node:fs/promises', async (importOriginal) => { const LSOF_LISTEN_OUTPUT = ['p123', 'cnode', 'd0x1', 'n127.0.0.1:5173'].join('\n') -function urlWatcherStub(): { lookup: () => undefined; reconcileScan: Mock } { - return { lookup: () => undefined, reconcileScan: vi.fn() } +function urlWatcherStub(): { lookup: () => undefined; reconcileWorkspaces: Mock } { + return { lookup: () => undefined, reconcileWorkspaces: vi.fn() } } const worktrees = [ @@ -91,3 +95,49 @@ describe('scanWorkspacePorts with delayed process creation', () => { expect(skipped.ports[0]?.kind).toBe('external') }) }) + +describe('scan-local workspace attribution', () => { + it('preserves cwd precedence, root boundaries and probe ties across a listener batch', () => { + const probes = normalizeWorkspacePortProbes([ + { id: 'first', repoId: 'r', displayName: 'first', path: '/repo/bb' }, + { id: 'second', repoId: 'r', displayName: 'second', path: '/repo/aa' }, + { id: 'root', repoId: 'r', displayName: 'root', path: '/' }, + { id: 'spaces', repoId: 'r', displayName: 'spaces', path: '/a /a' }, + { id: 'long', repoId: 'r', displayName: 'long', path: '/a /b' }, + { id: 'suffix', repoId: 'r', displayName: 'suffix', path: '/b' }, + { id: 'unicode', repoId: 'r', displayName: 'unicode', path: '/repo/🌊' } + ]) + probes.push({ ...probes[1], normalizedPath: '/repo/bb' }) + const listeners = [ + { cwd: '/repo/aa/server', commandLine: 'node /repo/bb/start' }, + { commandLine: 'node /repo/aa/x /repo/bb/y' }, + { cwd: '/outside' }, + { cwd: '/' }, + { commandLine: 'node /repo/bb-other/server' }, + { commandLine: 'node --dir=/repo/bb:5173' }, + { commandLine: 'z/a /a /a' }, + { commandLine: 'z/a /b' }, + { commandLine: 'node /a /b' }, + { commandLine: 'node --dir=/repo/🌊:3000' }, + { cwd: '/repo/🌊/server' } + ].map((evidence, i) => ({ host: '127.0.0.1', port: 3000 + i, ...evidence })) + + expect( + attributePortsToWorkspaces(listeners, probes).map(({ owner }) => + owner ? [owner.worktreeId, owner.confidence] : null + ) + ).toEqual([ + ['second', 'cwd'], + ['first', 'command'], + null, + ['root', 'cwd'], + null, + ['first', 'command'], + ['spaces', 'command'], + ['suffix', 'command'], + ['long', 'command'], + ['unicode', 'command'], + ['unicode', 'cwd'] + ]) + }) +}) diff --git a/src/main/ports/local-workspace-port-scanner.ts b/src/main/ports/local-workspace-port-scanner.ts index 29d502f7554..0f63b021084 100644 --- a/src/main/ports/local-workspace-port-scanner.ts +++ b/src/main/ports/local-workspace-port-scanner.ts @@ -1,6 +1,7 @@ import type { WorkspacePortProbe, WorkspacePortScanResult } from '../../shared/workspace-ports' import { advertisedUrlWatcher, type AdvertisedUrlWatcher } from './advertised-url-watcher' import { + attributePortsToWorkspaces, compareWorkspacePorts, enrichPort, resolveWorkspacePortProbes, @@ -20,7 +21,7 @@ const MAX_PORTS = 200 export async function scanWorkspacePorts( worktrees: WorkspacePortProbe[], - urlWatcher: Pick = advertisedUrlWatcher, + urlWatcher: Pick = advertisedUrlWatcher, options: WorkspacePortScanOptions = {} ): Promise { const cooldown = getWorkspacePortScanCooldown() @@ -39,12 +40,13 @@ export async function scanWorkspacePorts( worktrees, options.requireMetadata ) + const attributedPorts = attributePortsToWorkspaces(rawPorts, normalizedWorktrees) // Missing metadata cannot prove listener loss; eviction would discard URLs only PTY output can restore (#11161). if (metadataAvailable && complete) { - reconcileAdvertisedUrls(rawPorts, normalizedWorktrees, urlWatcher) + reconcileAdvertisedUrls(attributedPorts, normalizedWorktrees, urlWatcher) } - const ports = rawPorts - .map((port) => enrichPort(port, normalizedWorktrees, urlWatcher)) + const ports = attributedPorts + .map((port) => enrichPort(port, urlWatcher)) .sort(compareWorkspacePorts) .slice(0, MAX_PORTS) return { platform: process.platform, scannedAt: Date.now(), ports } diff --git a/src/main/ports/workspace-port-path-index.ts b/src/main/ports/workspace-port-path-index.ts new file mode 100644 index 00000000000..c09dd7b2c73 --- /dev/null +++ b/src/main/ports/workspace-port-path-index.ts @@ -0,0 +1,116 @@ +import type { NormalizedWorkspacePortProbe } from './local-workspace-port-scan-state' + +type IndexedProbe = { probe: NormalizedWorkspacePortProbe; order: number } +type PathNode = { + children: Map + value?: IndexedProbe + failure?: PathNode + best?: IndexedProbe +} + +// Encode valid starts so suffix winners never need a separate boundary-filter walk. +function pathSymbolAt(text: string, index: number): number { + const boundary = index === 0 || /[\s"'=]/.test(text[index - 1]) + return text.charCodeAt(index) + (boundary ? 0x10000 : 0) +} + +function preferredProbe( + current: IndexedProbe | undefined, + candidate: IndexedProbe | undefined +): IndexedProbe | undefined { + if ( + candidate && + (!current || + candidate.probe.normalizedPath.length > current.probe.normalizedPath.length || + (candidate.probe.normalizedPath.length === current.probe.normalizedPath.length && + candidate.order < current.order)) + ) { + return candidate + } + return current +} + +export class WorkspacePortPathIndex { + private readonly root: PathNode = { children: new Map() } + private commandPrepared = false + + constructor(probes: readonly NormalizedWorkspacePortProbe[]) { + probes.forEach((probe, order) => { + let node = this.root + for (let i = 0; i < probe.normalizedPath.length; i++) { + const symbol = pathSymbolAt(probe.normalizedPath, i) + let child = node.children.get(symbol) + if (!child) { + child = { children: new Map() } + node.children.set(symbol, child) + } + node = child + } + node.value ??= { probe, order } + }) + } + + findCwd(cwd: string): NormalizedWorkspacePortProbe | undefined { + let node = this.root + let best: IndexedProbe | undefined + for (let i = 0; i < cwd.length; i++) { + const child = node.children.get(pathSymbolAt(cwd, i)) + if (!child) { + break + } + node = child + if (node.value && (i + 1 === cwd.length || cwd[i + 1] === '/')) { + best = node.value + } + } + return best?.probe + } + + findCommand(command: string): NormalizedWorkspacePortProbe | undefined { + if (command.length === 0 || this.root.children.size === 0) { + return undefined + } + this.prepareCommandMatches() + let node = this.root + let best: IndexedProbe | undefined + for (let i = 0; i < command.length; i++) { + const symbol = pathSymbolAt(command, i) + let next = node.children.get(symbol) + while (!next && node !== this.root) { + node = node.failure ?? this.root + next = node.children.get(symbol) + } + node = next ?? this.root + if (node.best && (i + 1 === command.length || /[\s"'/:]/.test(command[i + 1]))) { + best = preferredProbe(best, node.best) + } + } + return best?.probe + } + + private prepareCommandMatches(): void { + if (this.commandPrepared) { + return + } + const queue = [...this.root.children.values()] + for (const child of queue) { + child.failure = this.root + child.best = child.value + } + for (let i = 0; i < queue.length; i++) { + const node = queue[i] + for (const [symbol, child] of node.children) { + let fallback = node.failure ?? this.root + let suffix = fallback.children.get(symbol) + while (!suffix && fallback !== this.root) { + fallback = fallback.failure ?? this.root + suffix = fallback.children.get(symbol) + } + child.failure = suffix ?? this.root + child.best = preferredProbe(child.value, child.failure.best) + queue.push(child) + } + } + this.commandPrepared = true + } +} diff --git a/src/main/provider-process/managed-provider-process.ts b/src/main/provider-process/managed-provider-process.ts index 3abd330609f..27ea3fadc04 100644 --- a/src/main/provider-process/managed-provider-process.ts +++ b/src/main/provider-process/managed-provider-process.ts @@ -1,4 +1,5 @@ -import type { PipedChildProcess, PipedProcessSpawner } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import { spawnProcess } from '@orca/process-host' import { RetryableProcessExitProof } from '@orca/process-host/retryable-process-exit-proof' import type { ProviderProcessLaunch } from './provider-process-launch' @@ -53,7 +54,7 @@ type ManagedProviderProcessOptions = { } export type ManagedProviderProcess = { - child: PipedChildProcess + child: ChildProcessWithoutNullStreams supervised: boolean /** The spawn failed before a process existed: absence is proven, but no exit was observed. */ readonly processless: boolean diff --git a/src/main/provider-process/provider-process-close.ts b/src/main/provider-process/provider-process-close.ts index f8f2dd21b8d..580ea37cbde 100644 --- a/src/main/provider-process/provider-process-close.ts +++ b/src/main/provider-process/provider-process-close.ts @@ -1,4 +1,4 @@ -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import type { DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' import { waitForProcessExitUntil } from './provider-process-exit-deadline' import { @@ -26,7 +26,7 @@ export type ProviderProcessClosePolicy = { } export type ProviderProcessCloseInput = { - child: Pick + child: Pick exitPromise: Promise rootVerdict: () => DescendantTreeVerdict supervised?: boolean diff --git a/src/main/provider-process/provider-process-teardown.ts b/src/main/provider-process/provider-process-teardown.ts index 259ea48963a..c751abeea98 100644 --- a/src/main/provider-process/provider-process-teardown.ts +++ b/src/main/provider-process/provider-process-teardown.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { captureDescendantSnapshot, type DescendantSnapshot @@ -19,7 +19,7 @@ export type ProviderProcessTeardownVerdict = const activeTeardowns = new WeakMap>() -type TeardownChild = Pick +type TeardownChild = Pick export type ProviderProcessTeardownDeps = { site: string diff --git a/src/main/provider-process/supervised-child-process-stop.ts b/src/main/provider-process/supervised-child-process-stop.ts index 308776f760b..d24d1353bef 100644 --- a/src/main/provider-process/supervised-child-process-stop.ts +++ b/src/main/provider-process/supervised-child-process-stop.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { closeProviderProcess, rootOnlyProviderClosePolicy, @@ -8,7 +8,7 @@ import type { ProviderCloseRequest } from './provider-process-supervisor' import { terminateProviderProcessTree } from './provider-process-teardown' type SupervisedChild = Pick< - ChildProcessHandle, + ChildProcess, 'pid' | 'kill' | 'stdin' | 'exitCode' | 'signalCode' | 'once' > diff --git a/src/main/providers/windows-console-attached-processes.ts b/src/main/providers/windows-console-attached-processes.ts index d6c7ef3c827..e74bcc32226 100644 --- a/src/main/providers/windows-console-attached-processes.ts +++ b/src/main/providers/windows-console-attached-processes.ts @@ -1,5 +1,5 @@ import { forkProcess } from '@orca/process-host/fork-process' -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' const CONPTY_PROCESS_LIST_TIMEOUT_MS = 3_000 @@ -9,7 +9,7 @@ type ForkConsoleListAgent = ( modulePath: string, args: string[], options: { silent: true } -) => SpawnedProcess +) => ChildProcess const forkConsoleListAgent: ForkConsoleListAgent = (modulePath, args) => forkProcess({ modulePath, args, stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }) @@ -33,7 +33,7 @@ export function readWindowsConsoleAttachedProcessIds( if (!Number.isSafeInteger(rootPid) || rootPid <= 0) { return Promise.resolve(null) } - let child: SpawnedProcess + let child: ChildProcess try { child = (deps.forkProcess ?? forkConsoleListAgent)( (deps.resolveAgentPath ?? resolveNodePtyConsoleListAgent)(), diff --git a/src/main/ripgrep/bundled-ripgrep-stop.ts b/src/main/ripgrep/bundled-ripgrep-stop.ts index 1f1166c7d74..ceaac0ff1c5 100644 --- a/src/main/ripgrep/bundled-ripgrep-stop.ts +++ b/src/main/ripgrep/bundled-ripgrep-stop.ts @@ -1,10 +1,10 @@ import { signalProcessTree } from '@orca/process-host/process-tree-termination' import { killSpawnedRipgrepProcess } from '../../shared/ripgrep/ripgrep-process-availability' -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' -const stoppingChildren = new WeakSet() +const stoppingChildren = new WeakSet() -export function stopBundledRipgrep(child: ChildProcessHandle, wsl = false): void { +export function stopBundledRipgrep(child: ChildProcess, wsl = false): void { if (stoppingChildren.has(child)) { return } diff --git a/src/main/ripgrep/bundled-ripgrep-text-search.ts b/src/main/ripgrep/bundled-ripgrep-text-search.ts index b4cd60b9809..7fca8a88f3b 100644 --- a/src/main/ripgrep/bundled-ripgrep-text-search.ts +++ b/src/main/ripgrep/bundled-ripgrep-text-search.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import type { SearchOptions, SearchResult } from '../../shared/file-search/code-search-types' import { RipgrepSearchDiagnostics } from '../../shared/ripgrep/ripgrep-search-diagnostics' import { SearchSubprocessLineAccumulator } from '../../shared/search-subprocess-lines' @@ -45,7 +45,7 @@ export function runBundledRipgrepTextSearch({ wslDistro?: string wslDistroForOutput?: string signal?: AbortSignal - onSpawn: (child: ChildProcessHandle) => () => void + onSpawn: (child: ChildProcess) => () => void }): Promise { throwIfSignalAborted(signal) const maxResults = Math.max( @@ -65,7 +65,7 @@ export function runBundledRipgrepTextSearch({ let resolved = false let processErrorObserved = false let unavailableExitObserved = false - let child: ChildProcessHandle | null = null + let child: ChildProcess | null = null let killTimeout: ReturnType | undefined let releaseChild: (() => void) | undefined diff --git a/src/main/runtime/browser/client-pages/browser-client-page-opening.ts b/src/main/runtime/browser/client-pages/browser-client-page-opening.ts index b743d3fe08d..45152468354 100644 --- a/src/main/runtime/browser/client-pages/browser-client-page-opening.ts +++ b/src/main/runtime/browser/client-pages/browser-client-page-opening.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto' import { BrowserError } from '../../../browser/browser-error' -import { browserNetworkExecutionHostKey } from '../../../browser/network/execution-routes/browser-network-execution-route' +import '../../../browser/network/execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import type { RuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import { BROWSER_CLIENT_AUTOMATION_HOST_CAPABILITY } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' import { diff --git a/src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.ts b/src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.ts index f719714575e..766492fb220 100644 --- a/src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.ts +++ b/src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.ts @@ -1,6 +1,7 @@ import type { BrowserNetworkExecutionHost } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import { BROWSER_CLIENT_AUTOMATION_HOST_CAPABILITY } from '../../../../shared/browser/client-hosting/browser-client-automation-protocol' -import { browserNetworkExecutionHostKey } from '../../../browser/network/execution-routes/browser-network-execution-route' +import '../../../browser/network/execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import type { BrowserHostLeaseRegistry } from '../../browser-host/leases/browser-host-lease-registry' import type { RuntimeBrowserClientPlacement } from '../../../../shared/runtime-browser-placement' diff --git a/src/main/runtime/browser/client-pages/runtime-browser-workspace-routing.ts b/src/main/runtime/browser/client-pages/runtime-browser-workspace-routing.ts index c1f6f83e68b..e3d2dd00ad8 100644 --- a/src/main/runtime/browser/client-pages/runtime-browser-workspace-routing.ts +++ b/src/main/runtime/browser/client-pages/runtime-browser-workspace-routing.ts @@ -1,6 +1,7 @@ import type { ResolvedWorktree } from '../../workspaces/catalog/runtime-worktree-path-identity' import type { BrowserExecutionHostKeyResolution } from './runtime-browser-client-page-adoption' -import { browserNetworkExecutionHostKey } from '../../../browser/network/execution-routes/browser-network-execution-route' +import '../../../browser/network/execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../shared/browser/client-hosting/browser-network-execution-host' import { type ClientHostedBrowserRpcRoute, routeRuntimeBrowserClientAutomation diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 88ea3651bc1..7126bd28a12 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -25,8 +25,7 @@ import { import { MANAGED_SERVER_RUNTIME_CAPABILITY, - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY, - WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY + REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../shared/host-runtime-capabilities' import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../shared/session-tabs-runtime-capabilities' import { @@ -62,11 +61,6 @@ import { supportsDurableTerminalPromptDelivery } from '../terminal/input/durable import { RuntimeWorkspaceChangeEvents } from '../workspaces/catalog/runtime-workspace-change-events' export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEvents { - /** Only a host wired with a recipe runner (the desktop) advertises recipe workspace creation. */ - supportsRecipeWorkspaceCreation(): boolean { - return false - } - getStatus(): RuntimeStatus { // Advertise screencast for renderer/offscreen backends; headless ownership prevents client-local fallback. const hasRenderer = Boolean(this.getAvailableAuthoritativeWindow()) @@ -99,9 +93,6 @@ export abstract class OrcaRuntimeWithGetStatus extends RuntimeWorkspaceChangeEve // Only hosts running their own usage poller can consume saved keys. (capability !== USAGE_CREDENTIALS_RUNTIME_CAPABILITY || this.getUsageRateLimits() !== null) ) - if (this.supportsRecipeWorkspaceCreation()) { - capabilities.push(WORKTREE_RECIPE_CREATE_RUNTIME_CAPABILITY) - } if (hasOffscreen || hasHeadlessCommands) { capabilities.push(BROWSER_HEADLESS_RUNTIME_CAPABILITY) } diff --git a/src/main/runtime/repositories/runtime-remote-fetch-operations.ts b/src/main/runtime/repositories/runtime-remote-fetch-operations.ts index 7ffaf6644f5..dd805312c6b 100644 --- a/src/main/runtime/repositories/runtime-remote-fetch-operations.ts +++ b/src/main/runtime/repositories/runtime-remote-fetch-operations.ts @@ -1,8 +1,8 @@ import type { LocalGitExecOptions } from '../../git/repo-default-base-ref' import type { RemoteFetchResult, RemoteTrackingBase } from './runtime-remote-fetch-controller' -import { RuntimeRecipeWorkspaceCreation } from '../workspaces/creation/runtime-recipe-workspace-creation' +import { RuntimeProvisionedWorkspaceAdoption } from '../workspaces/creation/runtime-provisioned-workspace-adoption' -export abstract class RuntimeRemoteFetchOperations extends RuntimeRecipeWorkspaceCreation { +export abstract class RuntimeRemoteFetchOperations extends RuntimeProvisionedWorkspaceAdoption { async getCanonicalFetchKey( repoPath: string, remote: string, diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 27e129a00cc..e252387ad04 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -2,7 +2,6 @@ import type { RuntimeClientCapabilities } from './runtime-client-capabilities' import type { ZodError, ZodType } from 'zod' import type { TerminalStreamFrame } from '../../../shared/terminal/stream/terminal-stream-protocol' import type { OrcaRuntimeService } from '../orca-runtime' -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' import type { OrchestrationCompatibilityCallerAuthority } from '../orchestration/terminal-authority/orchestration-compatibility-authority' import type { StructuredAgentCliSourceEvidence } from '../../native-chat/structured-agent-cli-source' import type { @@ -137,8 +136,6 @@ export type RpcContext = { markWorkerDoneMutationEffectFree?: () => void // Prompt retries stop once PTY write effects become ambiguous. markMutationEffectPossible?: () => void - // Long polls on a local socket may report named progress steps to the waiting client. - reportProgress?: (progress: RuntimeRpcProgress) => void // Commit operation identity with worker-start so crash recovery can inspect it. orchestrationMutation?: { callerFingerprint: string diff --git a/src/main/runtime/rpc/dispatcher-stream-options.ts b/src/main/runtime/rpc/dispatcher-stream-options.ts index b4b8f7db0e3..551b7db074d 100644 --- a/src/main/runtime/rpc/dispatcher-stream-options.ts +++ b/src/main/runtime/rpc/dispatcher-stream-options.ts @@ -27,7 +27,6 @@ export type RpcDispatchStreamingOptions = Pick< | 'sendBinary' | 'registerBinaryStreamHandler' | 'registerBinaryMessageHandler' - | 'reportProgress' > & { /** What the transport proved the caller may do; absent means this host's owner. */ callerScope?: RpcCallerScope @@ -81,7 +80,6 @@ export function rpcContextFromTransport( sendBinary: options?.sendBinary, registerBinaryStreamHandler: options?.registerBinaryStreamHandler, registerBinaryMessageHandler: options?.registerBinaryMessageHandler, - reportProgress: options?.reportProgress, orchestrationCaller } } diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index 38504a90d6a..4fe418b297c 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -40,7 +40,6 @@ import { PLUGIN_CLI_ERROR_CODES } from '../../../shared/plugins/approval/plugin- import { GIT_DIFF_TOO_LARGE_CODE } from '../../../shared/git/diff/git-diff-transport-budget' import { AUTOMATION_OWNER_CONFLICT_CODES } from '../../../shared/automations/ownership/automation-owner-conflict' import { ARCHIVE_HOOK_FAILED_REMOVAL_CODE } from '../../../shared/worktree/archive-hook-removal-gate' -import { RECIPE_WORKSPACE_CREATE_FAILED_CODE } from '../../../shared/recipe-workspace-create-progress' import { NESTED_WORKER_DEPTH_EXCEEDED_CODE } from '../../../shared/orchestration/workers/nested-worker-depth' import { PROJECT_RUNTIME_REPAIR_REQUIRED_CODE } from '../../../shared/project-runtime-repair-message' import { @@ -176,8 +175,6 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ 'invalid_argument', // Preserve archive-hook failure so callers can retry, waive or skip it (#19334). ARCHIVE_HOOK_FAILED_REMOVAL_CODE, - // The failed step, the recipe failure code and whether the new VM was destroyed ride in data. - RECIPE_WORKSPACE_CREATE_FAILED_CODE, // Paired-only method refusal must match the mobile transport allowlist's forbidden code. 'forbidden', NESTED_WORKER_DEPTH_EXCEEDED_CODE, @@ -242,8 +239,21 @@ export function mapRuntimeError(id: string, meta: RpcEnvelopeMeta, error: unknow error instanceof Error && 'code' in error && typeof (error as { code: unknown }).code === 'string' && - (LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) || - STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code)) + LINEAR_PASSTHROUGH_CODES.has((error as { code: string }).code) + ) { + return errorResponse( + id, + meta, + (error as { code: string }).code, + message, + (error as { data?: unknown }).data + ) + } + if ( + error instanceof Error && + 'code' in error && + typeof (error as { code: unknown }).code === 'string' && + STRUCTURED_RUNTIME_PASSTHROUGH_CODES.has((error as { code: string }).code) ) { return errorResponse( id, diff --git a/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts b/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts index 1e6c8d13ca8..d511aa5067a 100644 --- a/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts +++ b/src/main/runtime/rpc/methods/agent-launch/agent-launch-target-authorization.ts @@ -12,20 +12,9 @@ const CREATE_METHOD_BY_TARGET_KIND = { } as const satisfies Record, string> export function assertAgentLaunchTargetAuthorized( - target: Pick & { create?: unknown }, + target: Pick, context: Pick ): void { - if ( - target.kind === 'create-worktree' && - typeof target.create === 'object' && - target.create !== null && - 'recipeId' in target.create && - target.create.recipeId !== undefined - ) { - throw new Error( - 'Create the recipe workspace first, then launch the agent on its execution host.' - ) - } // `clientKind` is the paired device's scope, stamped from its validated token. if (target.kind === 'existing' || context.clientKind !== 'mobile') { return diff --git a/src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts b/src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts index 1c9485a80ac..d646a97274c 100644 --- a/src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts +++ b/src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts @@ -9,11 +9,12 @@ import { getBrowserHostLeaseRegistry } from '../../../browser-host/leases/browse import type { BrowserHostLease } from '../../../browser-host/leases/browser-host-lease-records' import type { OrcaRuntimeService } from '../../../orca-runtime' import { BrowserNetworkTunnelOutboundMemoryBudgetRegistry } from '../../../../browser/network/tunnels/browser-network-tunnel-outbound-memory-budget' -import { - browserNetworkExecutionHostKey, - type BrowserNetworkExecutionRoute, - type BrowserNetworkExecutionRouteResolver -} from '../../../../browser/network/execution-routes/browser-network-execution-route' +import '../../../../browser/network/execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../../shared/browser/client-hosting/browser-network-execution-host' +import type { + BrowserNetworkExecutionRoute, + BrowserNetworkExecutionRouteResolver +} from '../../../../browser/network/execution-routes/browser-network-execution-route-contract' import { RpcDispatcher } from '../../dispatcher' import { BROWSER_NETWORK_TUNNEL_METHODS, diff --git a/src/main/runtime/rpc/methods/browser/browser-network-tunnel.ts b/src/main/runtime/rpc/methods/browser/browser-network-tunnel.ts index 42e0d37a279..5584c9e0b4e 100644 --- a/src/main/runtime/rpc/methods/browser/browser-network-tunnel.ts +++ b/src/main/runtime/rpc/methods/browser/browser-network-tunnel.ts @@ -4,10 +4,9 @@ import { BROWSER_NETWORK_TUNNEL_LEGACY_FLOW_CONTROL, BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL } from '../../../../browser/network/tunnels/browser-network-tunnel-stream-state' -import { - browserNetworkExecutionHostKey, - type BrowserNetworkExecutionRouteResolver -} from '../../../../browser/network/execution-routes/browser-network-execution-route' +import '../../../../browser/network/execution-routes/browser-network-execution-route' +import { browserNetworkExecutionHostKey } from '../../../../../shared/browser/client-hosting/browser-network-execution-host' +import type { BrowserNetworkExecutionRouteResolver } from '../../../../browser/network/execution-routes/browser-network-execution-route-contract' import { resolveBrowserNetworkExecutionRoute } from '../../../../browser/network/execution-routes/browser-network-execution-route-dispatch' import { BrowserNetworkTunnelAttachParams } from '../../../../../shared/browser/client-hosting/browser-client-host-protocol' import '../../../../../shared/protocol-version' diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts index a61d23827de..0a3b9d07f9f 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-agent-launch.ts @@ -102,7 +102,12 @@ export async function launchFederatedWorkerAgent(args: { activate: false, ...(args.creatorProvenance ? { creatorProvenance: args.creatorProvenance } : {}), lineage: params.crossStoreParent - ? { crossStoreParent: params.crossStoreParent } + ? { + crossStoreParent: params.crossStoreParent, + ...(params.crossStoreParentInferredFrom + ? { crossStoreParentInferredFrom: params.crossStoreParentInferredFrom } + : {}) + } : { noParent: true } }) created = result.worktree diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts index 9fb931fcac9..8c90bf47eac 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-child-parent.ts @@ -25,7 +25,10 @@ export async function resolveFederatedChildParent(args: { callerSession: OrchestrationSessionCaller | undefined serverCapabilities: readonly string[] | undefined serverName: string -}): Promise<{ crossStoreParent: CrossStoreParentRef } | { warning: string }> { +}): Promise< + | { crossStoreParent: CrossStoreParentRef; crossStoreParentInferredFrom: 'orchestration-context' } + | { warning: string } +> { const { runtime } = args // Orchestration's caller authority picks the workspace; the shared builder verifies and names it. const callerId = await resolveDispatchCallerWorktreeId(runtime, args.from, args.callerSession) @@ -48,5 +51,8 @@ export async function resolveFederatedChildParent(args: { `--worktree new-child can't nest under this workspace: ${resolved.reason} Use --worktree new-top-level.` ) } - return { crossStoreParent: resolved.parent } + return { + crossStoreParent: resolved.parent, + crossStoreParentInferredFrom: 'orchestration-context' + } } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts index 83f641642da..1cb692c1d60 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.ts @@ -184,7 +184,10 @@ export async function startFederatedWorker(args: FederatedWorkerStartRequest): P // A server creates new-child as top-level plus this parent, so older servers parse it too. worktree: createsWorktree ? 'new-top-level' : worktree, ...(childParent && 'crossStoreParent' in childParent - ? { crossStoreParent: childParent.crossStoreParent } + ? { + crossStoreParent: childParent.crossStoreParent, + crossStoreParentInferredFrom: childParent.crossStoreParentInferredFrom + } : {}), name: params.name, repo: params.repo, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts new file mode 100644 index 00000000000..90e78bd74fd --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-child-lineage-origin.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import '../../../../orchestration/db/contract-constants' +import '../../../../orchestration/db/messages/mailbox-routing-page' +import '../../../../orchestration/db/dispatch-row-writer' +import '../../../../orchestration/db/attempt-outcome-projection' +import { crossStoreCreateLineage } from '../../../../workspaces/lineage/runtime-worktree-lineage-recording' +import { ORCHESTRATION_METHODS } from '../orchestration' + +const PARENT = { + installationId: 'home-install', + workspaceKey: 'worktree:repo::/home/parent', + instanceId: 'parent-instance' +} + +describe('a server nesting an orchestration worker under a workspace on another machine', () => { + let db: OrchestrationDb | undefined + + afterEach(() => db?.close()) + + async function createdLineage(attach: Record) { + db = new OrchestrationDb(':memory:') + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: worktree-creation support reads only id and kind. + vi.spyOn(runtime, 'showRepo').mockResolvedValue({ id: 'repo', kind: 'git' } as never) + const create = vi + .spyOn(runtime, 'createManagedWorktree') + .mockRejectedValue(new Error('stop after create args')) + const method = ORCHESTRATION_METHODS.find( + (candidate) => candidate.name === 'orchestration.federationAttachStart' + )! + await method + .handler( + method.params!.parse({ + runId: 'run-home', + dispatchId: 'ctx_child', + taskId: 'task_child', + taskSpec: 'work on the server', + protocolVersion: 3, + worktree: 'new-top-level', + repo: 'repo', + name: 'child', + agent: 'codex', + crossStoreParent: PARENT, + ...attach + }), + { + runtime, + orchestrationMutation: { + callerFingerprint: 'home_peer', + requestId: 'request_child', + method: 'orchestration.federationAttachStart', + payloadHash: 'child_payload' + } + } + ) + .catch(() => undefined) + const lineage = create.mock.calls[0]?.[0].lineage + if (!lineage?.crossStoreParent) { + throw new Error('the server created no nested worktree') + } + return crossStoreCreateLineage({ ...lineage, crossStoreParent: lineage.crossStoreParent }) + } + + it('records orchestration as the origin when orchestration picked the parent', async () => { + await expect( + createdLineage({ crossStoreParentInferredFrom: 'orchestration-context' }) + ).resolves.toEqual({ + kind: 'crossStore', + parent: PARENT, + origin: 'orchestration', + capture: { source: 'orchestration-context', confidence: 'inferred' } + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts b/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts deleted file mode 100644 index 0f7073b5f4e..00000000000 --- a/src/main/runtime/rpc/methods/workspaces/vm-recipe-list-method.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { VmRecipeList } from '../../../../../shared/rpc-contract/vm-recipe-params' -import { defineMethod } from '../../core' - -/** The environment recipes `worktree.create` with `recipeId` accepts on this host. */ -export const VM_RECIPE_LIST_METHOD = defineMethod({ - name: 'vmRecipe.list', - permission: 'workspace', - params: VmRecipeList, - handler: async (params, { runtime }) => ({ - repos: await runtime.listEnvironmentRecipes(params.repo) - }) -}) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts index 0de28320769..d5f43b17663 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree-provisioned-root-method.ts @@ -1,4 +1,3 @@ -import { buildCliWorkspaceProvenance } from '../../../../../shared/cli-workspace-provenance' import { getLocalWorktreeCatalogVersion } from '../../../../workspaces/catalog/local-worktree-scan-generation' import { WorktreeAdoptProvisionedRoot } from '../../../../../shared/rpc-contract/worktree-provisioned-root-params' import { defineMethod } from '../../core' @@ -8,22 +7,10 @@ export const WORKTREE_PROVISIONED_ROOT_METHOD = defineMethod({ permission: 'workspace', params: WorktreeAdoptProvisionedRoot, handler: async (params, { runtime }) => { - const { - repo, - linkedIssue, - linkedPR, - linkedGitLabMR, - linkedGitLabIssue, - cliProvenanceRequest, - ...request - } = params + const { repo, linkedIssue, linkedPR, linkedGitLabMR, linkedGitLabIssue, ...request } = params // Why: null clears a link on update; a fresh adoption has nothing to clear. const result = await runtime.adoptManagedProvisionedRoot(repo, { ...request, - cliProvenance: buildCliWorkspaceProvenance(cliProvenanceRequest, { - startupAgent: request.createdWithAgent, - createdAt: Date.now() - }), linkedIssue: linkedIssue ?? undefined, linkedPR: linkedPR ?? undefined, linkedGitLabMR: linkedGitLabMR ?? undefined, diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts deleted file mode 100644 index 6084c9bd658..00000000000 --- a/src/main/runtime/rpc/methods/workspaces/worktree-recipe-create-method.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import '../../unused-default-rpc-methods.test-fixture' -import { expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../../dispatcher' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { WORKTREE_METHODS } from './worktree' -import { assertAgentLaunchTargetAuthorized } from '../agent-launch/agent-launch-target-authorization' -import { classifyRuntimeLongPoll } from '../../server/runtime-rpc-long-poll' - -function makeRuntime() { - const createManagedRecipeWorkspace = vi.fn( - async (_params: unknown, options: { onPhase?: (phase: string) => void }) => { - options.onPhase?.('running-create') - return { recipe: { environmentId: 'vm-host' } } - } - ) - const createManagedWorktree = vi.fn() - const dedupeWorktreeCreate = vi.fn( - async (_repo: string, _mutation: string | undefined, run: () => Promise) => run() - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this branch only reads the runtime id, deduplication and recipe creation ports supplied below. - const runtime = { - getRuntimeId: () => 'source-host', - dedupeWorktreeCreate, - createManagedRecipeWorkspace, - createManagedWorktree - } as unknown as OrcaRuntimeService - return { runtime, createManagedRecipeWorkspace, createManagedWorktree } -} - -const recipeCreate = { - id: 'req', - authToken: 'token', - method: 'worktree.create', - params: { repo: 'id:source', name: 'task', recipeId: 'sandbox' } -} - -it('reports named progress steps to a local caller', async () => { - const { runtime } = makeRuntime() - const reportProgress = vi.fn() - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - await dispatcher.dispatch(recipeCreate, { reportProgress }) - expect(reportProgress).toHaveBeenCalledWith({ phase: 'running-create' }) -}) - -it('refuses a recipe create from a paired device before provisioning', async () => { - const { runtime, createManagedRecipeWorkspace, createManagedWorktree } = makeRuntime() - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - const response = await dispatcher.dispatch(recipeCreate, { clientKind: 'mobile' }) - expect(response).toMatchObject({ ok: false, error: { code: 'forbidden' } }) - expect(createManagedRecipeWorkspace).not.toHaveBeenCalled() - expect(createManagedWorktree).not.toHaveBeenCalled() -}) - -it('dispatches recipe creation through the host recipe service and deduplicates it', async () => { - const createManagedRecipeWorkspace = vi - .fn() - .mockResolvedValue({ recipe: { environmentId: 'vm-host' } }) - const createManagedWorktree = vi.fn() - const dedupeWorktreeCreate = vi.fn( - async (_repo: string, _mutation: string | undefined, run: () => Promise) => run() - ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this branch only reads the runtime id, deduplication and recipe creation ports supplied below. - const runtime = { - getRuntimeId: () => 'source-host', - dedupeWorktreeCreate, - createManagedRecipeWorkspace, - createManagedWorktree - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }) - const response = await dispatcher.dispatch({ - id: 'req', - authToken: 'token', - method: 'worktree.create', - params: { - repo: 'id:source', - name: 'task', - recipeId: 'sandbox', - clientMutationId: 'create-1' - } - }) - expect(response).toMatchObject({ ok: true, result: { recipe: { environmentId: 'vm-host' } } }) - expect(dedupeWorktreeCreate).toHaveBeenCalledWith( - expect.objectContaining({ repo: 'id:source' }), - 'create-1', - expect.any(Function) - ) - expect(createManagedRecipeWorkspace).toHaveBeenCalledWith( - expect.objectContaining({ recipeId: 'sandbox' }), - expect.any(Object) - ) - expect(createManagedWorktree).not.toHaveBeenCalled() -}) - -it('refuses a recipe embedded in agent.launch before it can become an ordinary local create', () => { - expect(() => - assertAgentLaunchTargetAuthorized( - { kind: 'create-worktree', create: { recipeId: 'sandbox' } }, - {} - ) - ).toThrow('Create the recipe workspace first') -}) - -it('keeps provisioning alive while preserving the ordinary create transport policy', () => { - const request = { id: 'req', authToken: 'token', method: 'worktree.create' } - expect(classifyRuntimeLongPoll({ ...request, params: { recipeId: 'sandbox' } })).toBe('wait') - expect(classifyRuntimeLongPoll({ ...request, params: { repo: 'id:repo' } })).toBeNull() -}) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree.ts b/src/main/runtime/rpc/methods/workspaces/worktree.ts index 67ad6037d56..4e408df70a0 100644 --- a/src/main/runtime/rpc/methods/workspaces/worktree.ts +++ b/src/main/runtime/rpc/methods/workspaces/worktree.ts @@ -34,7 +34,6 @@ import { } from '../../../../../shared/rpc-contract/worktree-params' import { WORKTREE_CATALOG_METHODS } from './worktree-catalog-methods' import { WORKTREE_PROVISIONED_ROOT_METHOD } from './worktree-provisioned-root-method' -import { VM_RECIPE_LIST_METHOD } from './vm-recipe-list-method' import { waitsForWorktreeRemoval } from '../../worktree-removal-marker-projection' import { queueWorkspaceDelete } from '../../../workspaces/lifecycle/workspace-lifecycle-commands' import { WORKTREE_SLEEP_METHOD } from './worktree-sleep-method' @@ -122,24 +121,6 @@ export const WORKTREE_METHODS = [ // Mobile retries after migration share clientMutationId; return the same pending/created worktree. Desktop/CLI without keys run plainly. context.runtime.dedupeWorktreeCreate(params, params.clientMutationId, async () => { const { runtime } = context - if (params.recipeId !== undefined) { - // Why: a recipe starts a billed machine from this computer's orca.yaml; paired devices - // do not get to start one until they have their own UI and confirmation for it. - if (context.clientKind !== undefined) { - throw Object.assign( - new Error( - "Recipe workspaces are created from this computer's Orca app or CLI, not from a paired device." - ), - { code: 'forbidden' } - ) - } - return runtime.createManagedRecipeWorkspace(params, { - ...(context.signal ? { signal: context.signal } : {}), - ...(context.reportProgress - ? { onPhase: (phase) => context.reportProgress?.({ phase }) } - : {}) - }) - } const repo = await runtime.showRepo(worktreeCreateRepoSelector(params)) const automationProvenance = resolveAutomationWorkspaceProvenance({ @@ -184,7 +165,6 @@ export const WORKTREE_METHODS = [ }) }), WORKTREE_PROVISIONED_ROOT_METHOD, - VM_RECIPE_LIST_METHOD, defineMethod({ name: 'worktree.prefetchCreateBase', permission: 'workspace', diff --git a/src/main/runtime/rpc/server/runtime-metadata.ts b/src/main/runtime/rpc/server/runtime-metadata.ts index d5aecee20c0..5aae7afe52b 100644 --- a/src/main/runtime/rpc/server/runtime-metadata.ts +++ b/src/main/runtime/rpc/server/runtime-metadata.ts @@ -5,7 +5,7 @@ import { writeSecureJsonFile } from '../../../../shared/secure-storage/secure-fi export function writeRuntimeMetadata(userDataPath: string, metadata: RuntimeMetadata): void { const metadataPath = getRuntimeMetadataPath(userDataPath) - writeMetadataFile(metadataPath, metadata) + writeSecureJsonFile(metadataPath, metadata) } export function readRuntimeMetadata(userDataPath: string): RuntimeMetadata | null { @@ -55,7 +55,3 @@ export function clearRuntimeMetadataIfOwned( } clearRuntimeMetadata(userDataPath) } - -function writeMetadataFile(path: string, metadata: RuntimeMetadata): void { - writeSecureJsonFile(path, metadata) -} diff --git a/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts b/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts index 37e078c80c4..13188f287ae 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-long-poll.ts @@ -73,14 +73,5 @@ export function classifyRuntimeLongPoll(request: RpcRequest): RuntimeLongPollCla const params = request.params as { wait?: unknown } | undefined return params?.wait === true ? 'wait' : null } - if ( - request.method === 'worktree.create' && - typeof request.params === 'object' && - request.params !== null && - 'recipeId' in request.params && - typeof request.params.recipeId === 'string' - ) { - return 'wait' - } return null } diff --git a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts index d19ad647b61..beb2c564224 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-request-admission.ts @@ -52,7 +52,6 @@ export class RuntimeRpcRequestAdmission extends RuntimeRpcBinaryRouting { ? context?.signal : undefined, connectionSignal: context?.signal, - ...(longPoll && context?.reportProgress ? { reportProgress: context.reportProgress } : {}), caller: LOCAL_CLI_RPC_CALLER, callerScope, pairingOffers: callerScope.kind === 'owner' ? this.ownerPairingOffers() : undefined diff --git a/src/main/runtime/rpc/server/runtime-rpc-shutdown.ts b/src/main/runtime/rpc/server/runtime-rpc-shutdown.ts deleted file mode 100644 index 67bb8d5bc2a..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-shutdown.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { RuntimeRpcMobilePairing } from './runtime-rpc-mobile-pairing' -import { publishHostDescriptor } from '../../hosts/platform-probe/host-descriptor' - -export type RuntimeRpcClientActivity = { - openConnections: number - requestsInFlight: number - lastRequestAt: number -} - -export class RuntimeRpcShutdown extends RuntimeRpcMobilePairing { - /** Why: test-only seam — runs one ownership check instead of waiting out the poll interval. */ - checkRuntimeMetadataOwnership(): Promise { - return this.metadataOwnershipWatch?.check() ?? Promise.resolve() - } - - /** What a host's idle exit reads to know whether any client is still using this server. */ - readClientActivity(): RuntimeRpcClientActivity { - return { - openConnections: this.mobileSocketWiring?.connectionCount ?? 0, - requestsInFlight: this.clientRequestsInFlight, - lastRequestAt: this.lastClientRequestAt - } - } - - async stop(): Promise { - // Fence new exposure and await pending rebind before snapshotting transports, or late wide listeners can leak into cleared arrays (STA-2370). - this.stopping = true - const pendingExposure = this.networkExposurePromise - if (pendingExposure) { - await pendingExposure.catch(() => { - // Failed widening already logged/recovered; await only its transport-array mutations. - }) - } - const transports = this.activeTransports - this.activeTransports = [] - this.transports = [] - this.metadataOwnershipWatch?.stop() - this.metadataOwnershipWatch = null - if (this.hostDescriptor) { - publishHostDescriptor(this.runtime.getRuntimeId(), null) - } - this.mobileSocketWiring?.dispose() - this.mobileSocketWiring = null - this.detachPairedServerRows?.() - this.detachPairedServerRows = null - this.detachWebSocketWiring = null - const stopResults = await Promise.allSettled( - transports.map(async (transport) => transport.stop()) - ) - // Relay input is fenced before quit; direct auth may still update lastSeen while transports close. - this.deviceRegistry?.flushPendingLastSeen() - const failedStop = stopResults.find((result) => result.status === 'rejected') - if (failedStop?.status === 'rejected') { - throw failedStop.reason - } - // Shared userData may describe another live runtime; do not erase its metadata. - } -} diff --git a/src/main/runtime/rpc/server/runtime-rpc.ts b/src/main/runtime/rpc/server/runtime-rpc.ts index 40911b9896a..628d7a20455 100644 --- a/src/main/runtime/rpc/server/runtime-rpc.ts +++ b/src/main/runtime/rpc/server/runtime-rpc.ts @@ -1,9 +1,64 @@ // Why: the single security boundary for the bundled CLI — auth-token enforcement, metadata publication, transport orchestration. -import { RuntimeRpcShutdown } from './runtime-rpc-shutdown' +import { RuntimeRpcMobilePairing } from './runtime-rpc-mobile-pairing' +import { publishHostDescriptor } from '../../hosts/platform-probe/host-descriptor' import type { OrcaRuntimeRpcServerOptions } from './runtime-rpc-pairing-types' -export class OrcaRuntimeRpcServer extends RuntimeRpcShutdown { +export type RuntimeRpcClientActivity = { + openConnections: number + requestsInFlight: number + lastRequestAt: number +} + +export class OrcaRuntimeRpcServer extends RuntimeRpcMobilePairing { constructor(options: OrcaRuntimeRpcServerOptions) { super(options) } + + /** Why: test-only seam — runs one ownership check instead of waiting out the poll interval. */ + checkRuntimeMetadataOwnership(): Promise { + return this.metadataOwnershipWatch?.check() ?? Promise.resolve() + } + + /** What a host's idle exit reads to know whether any client is still using this server. */ + readClientActivity(): RuntimeRpcClientActivity { + return { + openConnections: this.mobileSocketWiring?.connectionCount ?? 0, + requestsInFlight: this.clientRequestsInFlight, + lastRequestAt: this.lastClientRequestAt + } + } + + async stop(): Promise { + // Fence new exposure and await pending rebind before snapshotting transports, or late wide listeners can leak into cleared arrays (STA-2370). + this.stopping = true + const pendingExposure = this.networkExposurePromise + if (pendingExposure) { + await pendingExposure.catch(() => { + // Failed widening already logged/recovered; await only its transport-array mutations. + }) + } + const transports = this.activeTransports + this.activeTransports = [] + this.transports = [] + this.metadataOwnershipWatch?.stop() + this.metadataOwnershipWatch = null + if (this.hostDescriptor) { + publishHostDescriptor(this.runtime.getRuntimeId(), null) + } + this.mobileSocketWiring?.dispose() + this.mobileSocketWiring = null + this.detachPairedServerRows?.() + this.detachPairedServerRows = null + this.detachWebSocketWiring = null + const stopResults = await Promise.allSettled( + transports.map(async (transport) => transport.stop()) + ) + // Relay input is fenced before quit; direct auth may still update lastSeen while transports close. + this.deviceRegistry?.flushPendingLastSeen() + const failedStop = stopResults.find((result) => result.status === 'rejected') + if (failedStop?.status === 'rejected') { + throw failedStop.reason + } + // Shared userData may describe another live runtime; do not erase its metadata. + } } diff --git a/src/main/runtime/rpc/transport.ts b/src/main/runtime/rpc/transport.ts index 1bf2351737a..94ab65d151e 100644 --- a/src/main/runtime/rpc/transport.ts +++ b/src/main/runtime/rpc/transport.ts @@ -1,5 +1,3 @@ -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' - // Transports own connection lifecycle; RPC binds messages across Unix sockets, WebSockets and named pipes. // Rich message context (abort signals, authenticated sockets) requires each concrete transport type. @@ -7,8 +5,6 @@ import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' export type RpcMessageContext = { signal: AbortSignal startKeepalive: () => void - /** Long polls only: piggybacks a progress note on a keepalive frame; older clients ignore it. */ - reportProgress?: (progress: RuntimeRpcProgress) => void } export type RpcTransport = { diff --git a/src/main/runtime/rpc/unix-socket-transport.test.ts b/src/main/runtime/rpc/unix-socket-transport.test.ts index dc5ecad6347..2fe81c1a59b 100644 --- a/src/main/runtime/rpc/unix-socket-transport.test.ts +++ b/src/main/runtime/rpc/unix-socket-transport.test.ts @@ -102,27 +102,6 @@ describe('UnixSocketTransport', () => { expect(received).toEqual([oversized ? '' : message]) }) - it('writes progress as keepalive frames only until the reply is sent', () => { - const transport = new UnixSocketTransport({ - endpoint: '/tmp/orca-runtime-rpc-test.sock', - kind: 'unix' - }) - const socket = new FakeSocket() - transport.onMessage((_msg, reply, context) => { - context?.reportProgress?.({ phase: 'running-create' }) - reply('{"id":"req","ok":true}') - context?.reportProgress?.({ phase: 'too-late' }) - }) - ;(transport as unknown as UnixSocketTransportInternals).handleConnection( - socket as unknown as Socket - ) - socket.emit('data', '{"id":"req","method":"worktree.create"}\n') - expect(socket.writes).toEqual([ - '{"_keepalive":true,"progress":{"phase":"running-create"}}\n', - '{"id":"req","ok":true}\n' - ]) - }) - it('clears request keepalive timers when the socket closes before a reply', () => { const transport = new UnixSocketTransport({ endpoint: '/tmp/orca-runtime-rpc-test.sock', diff --git a/src/main/runtime/rpc/unix-socket-transport.ts b/src/main/runtime/rpc/unix-socket-transport.ts index d9bd7c8abee..01eaa2c36b2 100644 --- a/src/main/runtime/rpc/unix-socket-transport.ts +++ b/src/main/runtime/rpc/unix-socket-transport.ts @@ -3,7 +3,6 @@ import { createServer, type Server, type Socket } from 'node:net' import { chmodSync, existsSync, rmSync } from 'node:fs' import type { RpcMessageContext, RpcTransport } from './transport' -import type { RuntimeRpcProgress } from '../../../shared/runtime-rpc-envelope' import { MAX_LOCAL_RUNTIME_RPC_MESSAGE_BYTES } from '../../../shared/local-runtime-rpc-limits' const RUNTIME_RPC_SOCKET_IDLE_TIMEOUT_MS = 30_000 @@ -215,17 +214,9 @@ export class UnixSocketTransport implements RpcTransport { } } - const reportProgress = (progress: RuntimeRpcProgress): void => { - if (replied || socket.destroyed || !socket.writable) { - return - } - socket.write(`${JSON.stringify({ _keepalive: true, progress })}\n`) - } - this.messageHandler?.(rawMessage, reply, { signal: abortController.signal, - startKeepalive, - reportProgress + startKeepalive }) } } diff --git a/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts b/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts deleted file mode 100644 index 9e4afdaf5f1..00000000000 --- a/src/main/runtime/workspaces/creation/runtime-recipe-workspace-creation.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { Repo } from '../../../../shared/repo-types' -import type { - RecipeCatalogListing, - RecipeWorkspaceCreatePhase -} from '../../../../shared/recipe-workspace-create-progress' -import type { - RecipeWorkspaceCreateParams, - RecipeWorkspaceCreation -} from '../../../ephemeral-vm/recipe-workspace-create-params' -import { worktreeCreateRepoSelector } from '../../rpc/methods/workspaces/worktree-create-args' -import { RuntimeProvisionedWorkspaceAdoption } from './runtime-provisioned-workspace-adoption' - -export type RecipeWorkspaceCreateOptions = { - /** Aborts provisioning (and destroys a started VM) when the caller goes away. */ - signal?: AbortSignal - onPhase?: (phase: RecipeWorkspaceCreatePhase) => void -} - -/** Desktop-only wiring: orcad has no recipe runner, so it never sets one and never advertises it. */ -export type RecipeWorkspaceService = { - create: ( - params: RecipeWorkspaceCreateParams, - repo: Repo, - options: RecipeWorkspaceCreateOptions - ) => Promise - /** One repo's recipes, or every local repo that has any. */ - list: (repo: Repo | null) => Promise -} - -export abstract class RuntimeRecipeWorkspaceCreation extends RuntimeProvisionedWorkspaceAdoption { - private recipeWorkspaceService: RecipeWorkspaceService | null = null - - setRecipeWorkspaceService(service: RecipeWorkspaceService): void { - this.recipeWorkspaceService = service - } - - override supportsRecipeWorkspaceCreation(): boolean { - return this.recipeWorkspaceService !== null - } - - async listEnvironmentRecipes(repoSelector: string | undefined): Promise { - if (!this.recipeWorkspaceService) { - throw new Error('This Orca host cannot create workspaces from environment recipes.') - } - const repo = repoSelector ? await this.resolveRepoSelector(repoSelector) : null - return this.recipeWorkspaceService.list(repo) - } - - async createManagedRecipeWorkspace( - params: RecipeWorkspaceCreateParams, - options: RecipeWorkspaceCreateOptions = {} - ): Promise { - if (!this.recipeWorkspaceService) { - throw new Error('This Orca host cannot create workspaces from environment recipes.') - } - const repo = await this.resolveRepoSelector(worktreeCreateRepoSelector(params)) - const result = await this.recipeWorkspaceService.create(params, repo, options) - this.notifyReposChanged() - this.notifyWorktreesChanged(result.worktree.repoId) - // No lifecycle event: plugin events carry `path` as a path on this machine, and this one is inside the VM. - // No activation either: this host's window cannot resolve a workspace that lives on another host. - // No lineage: this host's store would record a parent edge to a workspace it does not hold, - // which the sidebar reads as a missing parent. - return { - ...result, - lineage: null, - workspaceLineage: null, - warnings: [], - worktree: { - ...result.worktree, - parentWorktreeId: null, - lineage: null, - workspaceLineage: null - } - } - } -} diff --git a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-recording.ts b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-recording.ts index ab7dc62c145..6b75b5ea9b7 100644 --- a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-recording.ts +++ b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-recording.ts @@ -59,7 +59,7 @@ export function crossStoreManualLineage(parent: CrossStoreParentRef): CrossStore } } -/** App picks are manual; otherwise the CLI's --parent-worktree, or the caller workspace it inferred. */ +/** App picks are manual; an orchestration-picked parent is orchestration's; else the CLI's flag or inferred caller. */ export function crossStoreCreateLineage(input: { crossStoreParent: CrossStoreParentRef parentWorkspaceOrigin?: 'manual' @@ -71,7 +71,8 @@ export function crossStoreCreateLineage(input: { return { kind: 'crossStore', parent: input.crossStoreParent, - origin: 'cli', + origin: + input.crossStoreParentInferredFrom === 'orchestration-context' ? 'orchestration' : 'cli', capture: input.crossStoreParentInferredFrom ? { source: input.crossStoreParentInferredFrom, confidence: 'inferred' } : { source: 'explicit-cli-flag', confidence: 'explicit' } diff --git a/src/main/speech/stt-session-stop.ts b/src/main/speech/stt-session-stop.ts index a1154526e37..1480be40b54 100644 --- a/src/main/speech/stt-session-stop.ts +++ b/src/main/speech/stt-session-stop.ts @@ -27,6 +27,10 @@ export function stopSttDictation( return Promise.resolve() } if (session.phase === 'stopping') { + // A cancel after Finish still aborts the cloud upload whose text it would throw away. + if (options.discard) { + session.cloud?.cancel() + } return session.stopPromise ?? Promise.resolve() } session.phase = 'stopping' diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts index 00873182918..207fc8eb1fb 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.ts @@ -1,4 +1,4 @@ -import type { ChildProcessHandle as ChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { spawnProcess } from '@orca/process-host' import { connect } from 'node:net' import { createSshOperationAbortError } from '../../connection/ssh-exec-options' diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts index 3beed7c4017..ed9baf9fc0d 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-loopback-route.ts @@ -1,5 +1,5 @@ /** On Windows, hold a proxied ssh -N -L once; route later execs through loopback to avoid repeated proxy handshakes without ControlMaster. */ -import type { ChildProcessHandle as ChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { childProcessHasExited, signalProcessTree diff --git a/src/main/startup/hydrate-shell-path.ts b/src/main/startup/hydrate-shell-path.ts index 6ef5377c07a..95f1e25ef1c 100644 --- a/src/main/startup/hydrate-shell-path.ts +++ b/src/main/startup/hydrate-shell-path.ts @@ -1,4 +1,4 @@ -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { delimiter, win32 as pathWin32 } from 'node:path' import { spawnProcess } from '@orca/process-host' import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' @@ -154,7 +154,7 @@ function spawnShellAndReadPath(shell: string): Promise { let stdout = '' let timer: ReturnType | null = null - let child: SpawnedProcess + let child: ChildProcess try { child = spawnProcess({ program: shell, diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index a8adba0c0b6..bcc8198f35e 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -61,10 +61,6 @@ import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-b import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' import { openOffscreenBrowserPageLink } from '../runtime/browser/commands/offscreen-browser-page-link' -import { - createCliRecipeWorkspace, - listCliEnvironmentRecipes -} from '../ephemeral-vm/cli-workspace-create' export function getDesktopWindowStatus(): RuntimeDesktopWindowStatus { const activation = state.desktopActivationGate @@ -149,18 +145,6 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { applySessionSearchSettings: applySessionSearchSettingsChange, skillTransactionRecovery: state.skillTransactionRecovery }) - runtime.setRecipeWorkspaceService({ - create: (params, repo, options) => - createCliRecipeWorkspace({ - store, - userDataPath: app.getPath('userData'), - repo, - params, - pluginService: state.pluginService, - ...options - }), - list: (repo) => listCliEnvironmentRecipes(store, repo, state.pluginService) - }) // Both desktop and headless serve own a host-local search service. const sessionSearch = installChildSessionSearchService({ dataRoot: getCanonicalUserDataPath(), diff --git a/src/main/startup/shell-probe-lifetime.ts b/src/main/startup/shell-probe-lifetime.ts index 133a4f661ee..4480edc8250 100644 --- a/src/main/startup/shell-probe-lifetime.ts +++ b/src/main/startup/shell-probe-lifetime.ts @@ -1,5 +1,5 @@ /** A detached login-shell probe gets no terminal signals, so its owner ends it: on timeout and when the owner exits. */ -import type { SpawnedProcess } from '@orca/process-host/process-spec' +import type { ChildProcess } from 'node:child_process' import { signalProcessTree } from '@orca/process-host/process-tree-termination' export type ShellProbeLifetime = { @@ -10,7 +10,7 @@ export type ShellProbeLifetime = { } // No signal listeners: one would replace Electron's graceful signal quit, and every owner turns INT/TERM into an exit. -export function bindShellProbeLifetime(child: SpawnedProcess): ShellProbeLifetime { +export function bindShellProbeLifetime(child: ChildProcess): ShellProbeLifetime { const kill = (): void => { if (process.platform === 'win32') { // Windows probes stay attached, and a tree kill would spawn taskkill from an exit hook. diff --git a/src/main/window/main-window-webview-security.ts b/src/main/window/main-window-webview-security.ts index f598a5dedc1..5c46e57ba14 100644 --- a/src/main/window/main-window-webview-security.ts +++ b/src/main/window/main-window-webview-security.ts @@ -12,7 +12,8 @@ import { browserRouteSessionRegistry, browserRouteWebContentsRegistry } from '../browser/routing/sessions/browser-route-session-runtime' -import { ORCA_BROWSER_BLANK_URL } from '../../shared/constants' +import '../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../shared/browser/browser-blank-page' import { DOC_PREVIEW_PARTITION, parseDocPreviewUrl diff --git a/src/main/worker-thread-child-process/worker-thread-child-process-server.ts b/src/main/worker-thread-child-process/worker-thread-child-process-server.ts index 94ed6e9a95c..99d57da2fae 100644 --- a/src/main/worker-thread-child-process/worker-thread-child-process-server.ts +++ b/src/main/worker-thread-child-process/worker-thread-child-process-server.ts @@ -1,4 +1,4 @@ -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { spawnProcess } from '@orca/process-host' import type { WorkerThreadChildErrorPayload, @@ -24,10 +24,13 @@ function toErrorPayload(error: unknown): WorkerThreadChildErrorPayload { } export function serveWorkerThreadChildProcesses(port: WorkerThreadChildPort): void { - const children = new Map() + const children = new Map< + number, + { child: ChildProcessWithoutNullStreams; pendingOutputBytes: number } + >() const spawnChild = ({ id, spec }: Extract): void => { - let child: PipedChildProcess + let child: ChildProcessWithoutNullStreams try { child = spawnProcess({ ...spec, stdio: ['pipe', 'pipe', 'pipe'] }) } catch (error) { diff --git a/src/main/workspaces/catalog/provisioned-root-checkout.ts b/src/main/workspaces/catalog/provisioned-root-checkout.ts index c1a9615f963..0243d931385 100644 --- a/src/main/workspaces/catalog/provisioned-root-checkout.ts +++ b/src/main/workspaces/catalog/provisioned-root-checkout.ts @@ -8,11 +8,7 @@ import type { CrossStoreParentRef } from '../../../shared/worktree/lineage-types' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import type { - AutomationWorkspaceProvenance, - CliWorkspaceProvenance, - GitWorktreeInfo -} from '../../../shared/worktree/types' +import type { AutomationWorkspaceProvenance, GitWorktreeInfo } from '../../../shared/worktree/types' import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' import { getProjectHostSetupWorktreeMeta } from '../../../shared/project-host-setup-lookup' import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' @@ -59,7 +55,6 @@ export type ProvisionedRootRequest = Pick< crossStoreParentInferredFrom?: CrossStoreInferredSource expectedRefHead?: string automationProvenance?: AutomationWorkspaceProvenance - cliProvenance?: CliWorkspaceProvenance } export function provisionedRootPathsEqual(left: string, right: string): boolean { @@ -149,7 +144,6 @@ export function buildProvisionedRootMeta( orcaCreatedAt: now, orcaCreationSource: options.source, creatorProvenance: { kind: 'host' }, - ...(args.cliProvenance ? { cliProvenance: args.cliProvenance } : {}), orcaCreationWorkspaceLayout: getWorktreeCreationLayout(repo, store.getSettings()), ...(args.automationProvenance ? { automationProvenance: args.automationProvenance } : {}), ...(args.compareBaseRef || args.baseBranch diff --git a/src/main/wsl/execution/wsl-command-channel.test.ts b/src/main/wsl/execution/wsl-command-channel.test.ts index cc4dc186f19..2e0d8ec0ade 100644 --- a/src/main/wsl/execution/wsl-command-channel.test.ts +++ b/src/main/wsl/execution/wsl-command-channel.test.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { killWslChannelsInCloseGrace, WSL_CHANNEL_CLOSE_GRACE_MS, @@ -25,7 +25,7 @@ function fakeChild() { child.emit('exit', code, null) } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the channel reads only these members. - return { child: child as unknown as PipedChildProcess, fake: child, exit } + return { child: child as unknown as ChildProcessWithoutNullStreams, fake: child, exit } } beforeEach(() => { diff --git a/src/main/wsl/execution/wsl-command-channel.ts b/src/main/wsl/execution/wsl-command-channel.ts index a677ca506ac..db67ffa2fa5 100644 --- a/src/main/wsl/execution/wsl-command-channel.ts +++ b/src/main/wsl/execution/wsl-command-channel.ts @@ -1,12 +1,12 @@ import { Duplex } from 'node:stream' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { RemoteCommandChannel } from '../../managed-server/install/remote-install-transport' /** How long a closed channel's guest gets to exit on stdin EOF before wsl.exe is killed. */ export const WSL_CHANNEL_CLOSE_GRACE_MS = 2_000 // wsl.exe children inside their close grace; quit kills them so none outlives Orca. -const closingChildren = new Set() +const closingChildren = new Set() /** App quit: no grace left, so a guest still running after close must not keep wsl.exe up. */ export function killWslChannelsInCloseGrace(): void { @@ -19,7 +19,7 @@ export function killWslChannelsInCloseGrace(): void { } /** Expose wsl.exe stdio as an SSH-style channel; exit reports status and close follows stdio teardown. */ -export function wrapWslCommandProcess(child: PipedChildProcess): RemoteCommandChannel { +export function wrapWslCommandProcess(child: ChildProcessWithoutNullStreams): RemoteCommandChannel { // Only the child emits close, once after exit status, like ssh2. const duplex = new Duplex({ emitClose: false, diff --git a/src/main/wsl/execution/wsl-command-loop-pool.ts b/src/main/wsl/execution/wsl-command-loop-pool.ts index 68b67d17ffd..066883d9768 100644 --- a/src/main/wsl/execution/wsl-command-loop-pool.ts +++ b/src/main/wsl/execution/wsl-command-loop-pool.ts @@ -1,4 +1,4 @@ -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { RemoteCommandChannel } from '../../managed-server/install/remote-install-transport' import { createSshOperationAbortError } from '../../ssh/connection/ssh-exec-options' import { startWslCommandLoop, wslCommandLoopMarker, type WslCommandLoop } from './wsl-command-loop' @@ -11,7 +11,7 @@ export type WslCommandLoopPool = { type WslCommandLoopPoolOptions = { /** Starts `wsl.exe --exec sh -c `. */ - spawnLoop: (marker: string) => PipedChildProcess + spawnLoop: (marker: string) => ChildProcessWithoutNullStreams /** Concurrent commands beyond this run on their own wsl.exe, as before. */ maxLoops?: number idleMs?: number diff --git a/src/main/wsl/execution/wsl-command-loop.test.ts b/src/main/wsl/execution/wsl-command-loop.test.ts index 10756004375..ac746c861f9 100644 --- a/src/main/wsl/execution/wsl-command-loop.test.ts +++ b/src/main/wsl/execution/wsl-command-loop.test.ts @@ -3,14 +3,14 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { WSL_COMMAND_LOOP_ARGV0, WSL_COMMAND_LOOP_SCRIPT } from './wsl-command-loop' import { createWslCommandLoopPool, type WslCommandLoopPool } from './wsl-command-loop-pool' // The guest side is plain POSIX sh, so a local sh stands in for `wsl.exe --exec sh`. const posix = process.platform !== 'win32' -const spawned: PipedChildProcess[] = [] +const spawned: ChildProcessWithoutNullStreams[] = [] const pools: WslCommandLoopPool[] = [] function pool(options: { maxLoops?: number; script?: string } = {}) { diff --git a/src/main/wsl/execution/wsl-command-loop.ts b/src/main/wsl/execution/wsl-command-loop.ts index 15c580b60ad..8265657feca 100644 --- a/src/main/wsl/execution/wsl-command-loop.ts +++ b/src/main/wsl/execution/wsl-command-loop.ts @@ -1,7 +1,7 @@ /** Reuse one wsl.exe for sequential stdin-free probes (~180ms startup each on win-lowspec). Isolate each sh command in its own session with /dev/null stdin; base64-frame output/status with per-loop markers. */ import { randomUUID } from 'node:crypto' import { Duplex, PassThrough, Writable } from 'node:stream' -import type { PipedChildProcess } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' import type { RemoteCommandChannel } from '../../managed-server/install/remote-install-transport' // setsid preserves per-command process-group isolation. Fresh output files keep background writers attached to old inodes, never the next command. @@ -53,7 +53,10 @@ export function wslCommandLoopMarker(): string { return `__ORCA_WSL_EXEC_${randomUUID().replaceAll('-', '')}__` } -export function startWslCommandLoop(child: PipedChildProcess, marker: string): WslCommandLoop { +export function startWslCommandLoop( + child: ChildProcessWithoutNullStreams, + marker: string +): WslCommandLoop { let pending: PendingCommand | null = null let alive = true let buffered = '' diff --git a/src/main/wsl/filesystem/wsl-directory-upload.test.ts b/src/main/wsl/filesystem/wsl-directory-upload.test.ts index 4713614a565..6524ed13059 100644 --- a/src/main/wsl/filesystem/wsl-directory-upload.test.ts +++ b/src/main/wsl/filesystem/wsl-directory-upload.test.ts @@ -1,4 +1,4 @@ -import { execFileSync } from 'node:child_process' +import { execFileSync, type ChildProcessWithoutNullStreams } from 'node:child_process' import { chmodSync, existsSync, @@ -14,7 +14,6 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess } from '@orca/process-host/process-spec' import { uploadDirectoryIntoWsl } from './wsl-directory-upload' import { createWslOrcadHostTransport, @@ -37,7 +36,7 @@ describe.skipIf(process.platform === 'win32' || !hasSha256sum())('uploadDirector let dest: string let commands: string[] const transports: WslOrcadHostTransport[] = [] - const children: PipedChildProcess[] = [] + const children: ChildProcessWithoutNullStreams[] = [] const getTransport = (): WslOrcadHostTransport => { const transport = transports.at(-1) diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts index 441ab6a6ca4..7cc6a162c56 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-bridge-test-child.ts @@ -2,7 +2,8 @@ import { EventEmitter } from 'node:events' import { connect } from 'node:net' import { PassThrough } from 'node:stream' -import type { PipedChildProcess, PipedProcessSpawner } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpawner } from '@orca/process-host/process-spec' import { ORCAD_STDIO_BRIDGE_READY, ORCAD_STDIO_BRIDGE_REFUSED, @@ -78,7 +79,7 @@ export function fakeWslBridgeChildren(): FakeWslBridgeChildren { socket.on('close', () => finish(0)) process.nextTick(() => child.emit('spawn')) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the WSL channel reads only the streams, exit state, kill and events assigned above. - return child as unknown as PipedChildProcess + return child as unknown as ChildProcessWithoutNullStreams } return { spawn, commands, live: () => live, maxLive: () => maxLive } } diff --git a/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts b/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts index ecf40e11877..615893291f7 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-transport-loops.test.ts @@ -1,12 +1,13 @@ import { Readable } from 'node:stream' import { afterEach, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { PipedChildProcess, PipedProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpec } from '@orca/process-host/process-spec' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { createWslOrcadHostTransport, type WslOrcadHostTransport } from './wsl-orcad-host-transport' const posix = process.platform !== 'win32' -const children: PipedChildProcess[] = [] +const children: ChildProcessWithoutNullStreams[] = [] const transports: WslOrcadHostTransport[] = [] /** Runs what follows `--exec` with the local sh, as wsl.exe would inside the distro. */ diff --git a/src/main/wsl/orcad/wsl-orcad-host-transport.test.ts b/src/main/wsl/orcad/wsl-orcad-host-transport.test.ts index 79af2088e4b..9d79590ff15 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-transport.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-transport.test.ts @@ -1,7 +1,8 @@ import { EventEmitter } from 'node:events' import { PassThrough, Readable } from 'node:stream' import { describe, expect, it, vi } from 'vitest' -import type { PipedChildProcess, PipedProcessSpec } from '@orca/process-host/process-spec' +import type { ChildProcessWithoutNullStreams } from 'node:child_process' +import type { PipedProcessSpec } from '@orca/process-host/process-spec' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { WSL_CHANNEL_CLOSE_GRACE_MS } from '../execution/wsl-command-channel' @@ -61,7 +62,7 @@ function transportWith(children: FakeChild[]) { throw new Error('no fake child left') } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the channel reads only the streams, exit state, kill and events the fake provides. - return next as unknown as PipedChildProcess + return next as unknown as ChildProcessWithoutNullStreams } }) return { transport, specs } @@ -172,7 +173,7 @@ describe('a transport with an abort signal', () => { commandLoops: false, signal: controller.signal, // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the channel reads only the streams, exit state, kill and events the fake provides. - spawn: () => child as unknown as PipedChildProcess + spawn: () => child as unknown as ChildProcessWithoutNullStreams }) const channel = await transport.exec('sleep 60') channel.on('error', () => {}) diff --git a/src/packages/process-host/README.md b/src/packages/process-host/README.md index 5b6919ae7c6..eb633609104 100644 --- a/src/packages/process-host/README.md +++ b/src/packages/process-host/README.md @@ -4,7 +4,7 @@ This Node package owns subprocess spawning, forked children, bounded output, can Import `runProcess`, `runProcessSync`, and `spawnProcess` from `@orca/process-host`. Import their contracts and default limits from `@orca/process-host/process-spec`. Other explicit subpaths expose forking, termination, Windows arguments, and bounded output. Application code must use public exports. -`spawnProcess` guarantees three stream pipes when `stdio` is omitted, is `'pipe'`, or starts with `['pipe', 'pipe', 'pipe']`. Other specifications return a child with nullable streams. Use `PipedProcessSpec` and `PipedChildProcess` when a stream-owning interface requires pipes. +`spawnProcess` guarantees three stream pipes when `stdio` is omitted, is `'pipe'`, or starts with `['pipe', 'pipe', 'pipe']`. Other specifications return a child with nullable streams. Use `PipedProcessSpec` from `@orca/process-host/process-spec` and `ChildProcessWithoutNullStreams` from `node:child_process` when a stream-owning interface requires pipes. The application supplies policy through `process-tree-kill-gate` and diagnostics through `spawn-observer`. Register these before starting managed children. Each process must load one package instance so registration and execution share state. The production exports use one CommonJS output for both import and require callers. The `orca-source` condition supports tests, dependency analysis, and Node tooling that runs TypeScript through `tsx`. Source tooling runs in a separate process and must use that condition for every package import; mixing source and compiled output would split the registration state. diff --git a/src/packages/process-host/src/fork-process.ts b/src/packages/process-host/src/fork-process.ts index 804b8d4aeb6..0a53bc2448d 100644 --- a/src/packages/process-host/src/fork-process.ts +++ b/src/packages/process-host/src/fork-process.ts @@ -2,9 +2,9 @@ import { fork as nodeFork, type ForkOptions, - type SpawnOptions as NodeSpawnOptions + type SpawnOptions as NodeSpawnOptions, + type ChildProcess } from 'node:child_process' -import type { SpawnedProcess } from './process-spec' // Preserve fork semantics for module resolution, execPath overrides, and inherited execArgv. export type ForkSpec = { @@ -23,7 +23,7 @@ export type ForkSpec = { serialization?: ForkOptions['serialization'] } -export function forkProcess(spec: ForkSpec): SpawnedProcess { +export function forkProcess(spec: ForkSpec): ChildProcess { const options: ForkOptions = { cwd: spec.cwd, env: spec.env, diff --git a/src/packages/process-host/src/process-spec.ts b/src/packages/process-host/src/process-spec.ts index 1137d5f3a55..34e4c1a1b61 100644 --- a/src/packages/process-host/src/process-spec.ts +++ b/src/packages/process-host/src/process-spec.ts @@ -5,10 +5,6 @@ import type { StdioOptions } from 'node:child_process' -export type ChildProcessHandle = ChildProcess - -export type SpawnedProcess = ChildProcess - export type ProcessSpec = { /** Prefer an absolute Windows path; stripped Electron PATHs may not resolve bare names. */ program: string @@ -42,13 +38,11 @@ export type ProcessSpec = { onStderr?: (chunk: Buffer | string) => void } -export type PipedChildProcess = ChildProcessWithoutNullStreams - export type PipedProcessSpec = Omit & { stdio?: 'pipe' | ['pipe', 'pipe', 'pipe', ...Exclude] } -export type PipedProcessSpawner = (spec: PipedProcessSpec) => PipedChildProcess +export type PipedProcessSpawner = (spec: PipedProcessSpec) => ChildProcessWithoutNullStreams export type ProcessTerminationBarrier = { observeStderr?: (chunk: Buffer | string) => void diff --git a/src/packages/process-host/src/run-process.ts b/src/packages/process-host/src/run-process.ts index 6e634fb5d46..c8b699fa62e 100644 --- a/src/packages/process-host/src/run-process.ts +++ b/src/packages/process-host/src/run-process.ts @@ -1,7 +1,8 @@ import { spawn as nodeSpawn, spawnSync as nodeSpawnSync, - type ChildProcess + type ChildProcess, + type ChildProcessWithoutNullStreams } from 'node:child_process' import { resolveSpawn, type ResolvedSpawn } from './spawn-resolution' import { forceTerminateProcessTree, signalProcessTree } from './process-tree-termination' @@ -13,12 +14,7 @@ import { createChildTerminationReporter } from './child-termination-reporter' export { WindowsCmdLineBreakError } from './windows-command-line' -import type { - PipedChildProcess, - PipedProcessSpec, - ProcessSpec, - ProcessResult -} from './process-spec' +import type { PipedProcessSpec, ProcessSpec, ProcessResult } from './process-spec' import { DEFAULT_PROCESS_TIMEOUT_MS, DEFAULT_MAX_OUTPUT_BYTES } from './process-spec' // Bound waits for children that ignore termination and never emit close. const PROCESS_EXIT_GRACE_MS = 2_000 @@ -26,7 +22,7 @@ const PROCESS_EXIT_GRACE_MS = 2_000 const BARRIER_UNVERIFIED_EXIT_GRACE_MS = 10_000 /** Callers own stream error handling; unhandled stream errors can crash the host process. */ -export function spawnProcess(spec: PipedProcessSpec): PipedChildProcess +export function spawnProcess(spec: PipedProcessSpec): ChildProcessWithoutNullStreams export function spawnProcess(spec: ProcessSpec): ChildProcess export function spawnProcess(spec: ProcessSpec): ChildProcess { const resolved = resolveSpawn(spec, process.platform) diff --git a/src/packages/process-host/src/spawn-process-stdio.test.ts b/src/packages/process-host/src/spawn-process-stdio.test.ts index cfa9613e4aa..501e0c5d63c 100644 --- a/src/packages/process-host/src/spawn-process-stdio.test.ts +++ b/src/packages/process-host/src/spawn-process-stdio.test.ts @@ -1,9 +1,10 @@ import { once } from 'node:events' import { describe, expect, expectTypeOf, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import type { ChildProcessHandle, PipedChildProcess, ProcessSpec } from './process-spec' +import type { ChildProcess, ChildProcessWithoutNullStreams } from 'node:child_process' +import type { ProcessSpec } from './process-spec' -async function waitForClose(child: ChildProcessHandle): Promise { +async function waitForClose(child: ChildProcess): Promise { try { await once(child, 'close', { signal: AbortSignal.timeout(5_000) }) } finally { @@ -18,7 +19,7 @@ async function waitForClose(child: ChildProcessHandle): Promise { describe('public spawn stream contracts', () => { it('returns three pipes by default', async () => { const child = spawnProcess({ program: process.execPath, args: ['-e', ''] }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).not.toBeNull() expect(child.stdout).not.toBeNull() @@ -27,7 +28,7 @@ describe('public spawn stream contracts', () => { it('returns three pipes for an explicit pipe mode', async () => { const child = spawnProcess({ program: process.execPath, args: ['-e', ''], stdio: 'pipe' }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).not.toBeNull() expect(child.stdout).not.toBeNull() @@ -40,7 +41,7 @@ describe('public spawn stream contracts', () => { args: ['-e', ''], stdio: ['pipe', 'pipe', 'pipe'] }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).not.toBeNull() expect(child.stdout).not.toBeNull() @@ -53,7 +54,7 @@ describe('public spawn stream contracts', () => { args: ['-e', 'process.disconnect()'], stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).not.toBeNull() expect(child.stdout).not.toBeNull() @@ -62,7 +63,7 @@ describe('public spawn stream contracts', () => { it.each(['ignore', 'inherit'] as const)('returns nullable streams for %s', async (stdio) => { const child = spawnProcess({ program: process.execPath, args: ['-e', ''], stdio }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).toBeNull() expect(child.stdout).toBeNull() @@ -75,7 +76,7 @@ describe('public spawn stream contracts', () => { args: ['-e', ''], stdio: ['ignore', 'pipe', 'pipe'] }) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) expect(child.stdin).toBeNull() expect(child.stdout).not.toBeNull() @@ -85,7 +86,7 @@ describe('public spawn stream contracts', () => { it('keeps the general contract when the specification does not guarantee pipes', async () => { const spec: ProcessSpec = { program: process.execPath, args: ['-e', ''] } const child = spawnProcess(spec) - expectTypeOf(child).toEqualTypeOf() + expectTypeOf(child).toEqualTypeOf() await waitForClose(child) }) }) diff --git a/src/preload/api/speech-api.ts b/src/preload/api/speech-api.ts index 2acb2d35da1..8acba71dcc2 100644 --- a/src/preload/api/speech-api.ts +++ b/src/preload/api/speech-api.ts @@ -27,6 +27,8 @@ export type SpeechApi = { /** Resolves true when this chunk filled a cloud session's upload cap. */ feedAudio: (samples: Float32Array, sampleRate: number, sessionId?: string) => Promise stopDictation: (sessionId?: string) => Promise + /** Drops the session's audio and any text it hasn't returned yet, without transcribing the rest. */ + cancelDictation: (sessionId: string) => Promise onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onFinalTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onDownloadProgress: ( diff --git a/src/preload/api/speech-bridge.ts b/src/preload/api/speech-bridge.ts index 8222c564422..a0b38154039 100644 --- a/src/preload/api/speech-bridge.ts +++ b/src/preload/api/speech-bridge.ts @@ -84,6 +84,11 @@ export const speechApi = { } return ipcRenderer.invoke('speech:stopDictation', sessionId) }, + cancelDictation: (sessionId: string): Promise => { + audioPorts.get(sessionId)?.close() + audioPorts.delete(sessionId) + return ipcRenderer.invoke('speech:cancelDictation', sessionId) + }, onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: SpeechTranscriptEvent): void => diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx index 36d87c34689..600c39a0a09 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx @@ -4,7 +4,8 @@ import { cn } from '@/lib/utils' import { getConnectionIdFromState } from '@/lib/connection-context' import { useAppStore } from '@/store' import { useShortcutLabel } from '@/hooks/useShortcutLabel' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' import { normalizeExternalBrowserUrl } from '../../../../../shared/browser-url' import { getLiveBrowserUrl } from '../describe-page/live-browser-url-registry' diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-menu-dropdown.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-menu-dropdown.tsx index 56d78e43be7..73bf34d5145 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-menu-dropdown.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-menu-dropdown.tsx @@ -18,7 +18,8 @@ import { BrowserCookieImportDisclosure } from '@/components/BrowserCookieImportD import { BrowserCookieImportMachineNotice } from '@/components/BrowserCookieImportMachineNotice' import { useAppStore } from '@/store' import { formatOptionalShortcutLabel } from '@/hooks/useShortcutLabel' -import { BROWSER_FAMILY_LABELS } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { BROWSER_FAMILY_LABELS } from '../../../../../shared/browser/browser-family-labels' import type { BrowserSessionProfile, BrowserViewportPresetId diff --git a/src/renderer/src/components/browser-pane/browser-reopen-on-server.ts b/src/renderer/src/components/browser-pane/browser-reopen-on-server.ts index 2b8f361d20b..1dedf3115d1 100644 --- a/src/renderer/src/components/browser-pane/browser-reopen-on-server.ts +++ b/src/renderer/src/components/browser-pane/browser-reopen-on-server.ts @@ -1,5 +1,6 @@ import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' -import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants' +import '../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page' import { createWebRuntimeSessionBrowserTab } from '@/runtime/browser/creation/web-runtime-browser-creation' /** Restore only committed web URLs across engines; other destinations reopen blank and request bodies are never reconstructed. */ diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts index f89de082b8c..81b9d45c0c2 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { getBrowserPageRuntimeEnvironmentId, retryBrowserTabLoad, diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.ts index 88994d66246..1bc914c21d1 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-url-display.ts @@ -1,5 +1,6 @@ import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { normalizeBrowserNavigationUrl, normalizeExternalBrowserUrl, diff --git a/src/renderer/src/components/browser-pane/host-guest/bind-browser-page-webview-listeners.ts b/src/renderer/src/components/browser-pane/host-guest/bind-browser-page-webview-listeners.ts index a943258c98c..3280ae9d5c2 100644 --- a/src/renderer/src/components/browser-pane/host-guest/bind-browser-page-webview-listeners.ts +++ b/src/renderer/src/components/browser-pane/host-guest/bind-browser-page-webview-listeners.ts @@ -1,6 +1,7 @@ import { publishNativeChatVisualGuestTheme } from '@/components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher' import { normalizeBrowserGuestSrc } from '../../../../../shared/browser/extensions/browser-extension-url' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { parkBrowserPageViewport } from './browser-page-viewport' import { subscribeBrowserSystemResume } from './browser-system-resume' import { diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-loading-handlers.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-loading-handlers.ts index 85125c75e41..2fc659aad36 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-loading-handlers.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview-loading-handlers.ts @@ -4,7 +4,8 @@ import { redactKagiSessionToken } from '../../../../../shared/browser-url' import type { BrowserLoadError } from '../../../../../shared/browser-workspace-types' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { isBrowserLoadBlockedByExtension } from '../../../../../shared/browser-load-failure' import { translate } from '@/i18n/i18n' import { BROWSER_GUEST_RECOVERY_ERROR_CODE } from './browser-page-guest-recovery' diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview.ts index 63f4d6ed6ce..c19a3756f4b 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-webview.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-webview.ts @@ -1,4 +1,5 @@ -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { ORCA_BROWSER_PAGE_GUEST_WEB_PREFERENCES_ATTRIBUTE } from '../../../../../shared/browser-guest-web-preferences' import { destroyPersistentWebview, diff --git a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.ts b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.ts index 722a89b1ffa..f6bccbb0d79 100644 --- a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.ts +++ b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.ts @@ -1,5 +1,6 @@ import { useAppStore } from '@/store' -import { ORCA_BROWSER_PARTITION } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_PARTITION } from '../../../../../shared/browser/browser-session-partition' import { getOrcaProfileBrowserDefaultPartition } from '../../../../../shared/orca-profiles' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { unadmittedBrowserPartition } from '../../../../../shared/browser-profile-scope' diff --git a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts b/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts index 229f7481ab5..328c48e0f9e 100644 --- a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts +++ b/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts @@ -11,7 +11,8 @@ import { redactKagiSessionToken } from '../../../../../shared/browser-url' import type { BrowserLoadError } from '../../../../../shared/browser-workspace-types' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { BROWSER_GUEST_RECOVERY_ERROR_CODE } from '../host-guest/browser-page-guest-recovery' import { getBrowserDisplayTitle, diff --git a/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts b/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts index 579786005f2..e75edf5a5fa 100644 --- a/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts +++ b/src/renderer/src/components/browser-pane/navigate/use-browser-page-webview-url-sync.ts @@ -4,7 +4,8 @@ import { normalizeBrowserNavigationUrl, redactKagiSessionToken } from '../../../../../shared/browser-url' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { normalizeBrowserGuestSrc } from '../../../../../shared/browser/extensions/browser-extension-url' import { applyBrowserPageViewportLayout, diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts index 63e11721aa0..759ffbdb4a3 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.ts @@ -1,5 +1,6 @@ import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../shared/layout-owner-switch' import type { BrowserTabInfo } from '../../../../../shared/runtime-types' import { isRemoteBrowserPageMissingError } from './remote-browser-stream-errors' diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index d509b0ef504..bdd6c08abce 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -1,23 +1,31 @@ -import { useEffect, useRef, useCallback, useState } from 'react' +import { useRef, useCallback, useState } from 'react' import { useAppStore } from '@/store' import { useAudioCapture } from '@/hooks/use-audio-capture' -import { toast } from 'sonner' import { DictationIndicator } from './DictationIndicator' import { captureInsertionTarget } from './dictation-insertion-target' +import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pill-anchor' +import { + canRetryDictation, + createDictationKeptRecording, + transcribeKeptRecording, + type DictationKeptRecording +} from './dictation-kept-recording' +import { useDictationControls } from './use-dictation-controls' import { createDictationTranscriptDelivery } from './dictation-transcript-delivery' import { recordStoppedSession, waitForStoppedSession } from './dictation-stopped-sessions' -import { translate } from '@/i18n/i18n' -import { useTranslate } from '@/i18n/use-translate' import { showDictationDisabledToast, showDictationNoModelToast, showCloudLimitToast, + dictationStartFailureKind, showDictationStartErrorToast, + type DictationFailureKind, showMicrophoneDisconnectedToast, - showMicrophoneFallbackToast + showMicrophoneFallbackToast, + showNoSpeechDetectedToast, + showSpeechErrorToast } from './dictation-toasts' import { useHoldDictationGesture } from './use-hold-dictation-gesture' -import { DICTATION_CONTROL_EVENT, type DictationControlAction } from './dictation-control-events' import { publishDictationMeter } from './dictation-meter-store' import { useDictationSilenceStop } from './use-dictation-silence-stop' import { useDictationSpeechEvents } from './use-dictation-speech-events' @@ -31,7 +39,6 @@ import { } from '../../../../shared/dictation-session-machine' export function DictationController() { - const t = useTranslate() const dictationState = useAppStore((s) => s.dictationState) const setDictationState = useAppStore((s) => s.setDictationState) const setPartialTranscript = useAppStore((s) => s.setPartialTranscript) @@ -56,6 +63,13 @@ export function DictationController() { // Push-to-talk restarts per utterance; report a missing preferred microphone once per preference. const micFallbackNotifiedForRef = useRef(null) const [captureLive, setCaptureLive] = useState(false) + // Holds the target pane only while the pill shows, so a closed pane isn't kept alive. + const [pillAnchor, setPillAnchor] = useState(null) + // The session's audio, kept until it lands, is retried, dismissed or replaced. + const keptRef = useRef(null) + const [failure, setFailure] = useState(null) + // A new recording gets a fresh pill (timer and all); a retry keeps the one it failed in. + const [recordingKey, setRecordingKey] = useState(0) const dispatch = useCallback( (event: DictationSessionEvent): DictationSession => { @@ -67,9 +81,16 @@ export function DictationController() { } if (next.phase !== previous.phase) { setDictationState(next.phase) - if (next.phase === 'idle') { + if (next.phase !== 'listening' && next.phase !== 'stopping') { setPartialTranscript('') } + if (next.phase === 'idle') { + setPillAnchor(null) + keptRef.current = null + } + if (next.phase !== 'error') { + setFailure(null) + } } return next }, @@ -81,7 +102,7 @@ export function DictationController() { }, []) const finishDictationSession = useCallback( - async ({ run, sessionId }: DictationSession) => { + async ({ run, sessionId }: DictationSession, beforeEnd?: () => void) => { if (sessionId === null) { return } @@ -101,18 +122,43 @@ export function DictationController() { return } if (!sessionRef.current.heardFinalText && getCapturedChunkCount() > 0) { - toast.message( - translate( - 'auto.components.dictation.DictationController.5d2c3e7ae3', - 'No speech detected.' - ) - ) + showNoSpeechDetectedToast() } + beforeEnd?.() dispatch({ type: 'ended' }) }, [dispatch, finishCapture, getCapturedChunkCount] ) + /** The error pill when the recording can be retried; otherwise the toast, as nothing is left to retry. */ + const showFailure = useCallback( + (kind: DictationFailureKind | null, showToast: () => void) => { + dispatch({ type: 'fail' }) + if (kind && canRetryDictation(keptRef.current)) { + setFailure(kind) + return + } + showToast() + dispatch({ type: 'ended' }) + }, + [dispatch] + ) + + // Words that already landed stay; the engine drops the rest instead of transcribing it. + const cancelDictation = useCallback(() => { + if (sessionRef.current.phase === 'error') { + dispatch({ type: 'ended' }) + return + } + const previous = sessionRef.current + if (dispatch({ type: 'cancel' }) === previous || previous.sessionId === null) { + return + } + stopCapture() + void window.api.speech.cancelDictation(previous.sessionId).catch(() => undefined) + drainStoppedSession(previous.sessionId) + }, [dispatch, stopCapture, drainStoppedSession]) + const stopDictation = useCallback(async () => { const previous = sessionRef.current const next = dispatch({ type: 'stop' }) @@ -151,7 +197,11 @@ export function DictationController() { const insertionTarget = captureInsertionTarget() const deliver = createDictationTranscriptDelivery() deliverRef.current = (text) => deliver(text, insertionTarget) + const kept = createDictationKeptRecording(insertionTarget, deliver) + keptRef.current = kept + setRecordingKey((key) => key + 1) setCaptureLive(false) + setPillAnchor(dictationPillAnchorFor(insertionTarget)) // A stop that arrived while starting is still this run's stop. const stopQueued = (): boolean => isCurrent() && sessionRef.current.phase === 'stopping' @@ -161,7 +211,7 @@ export function DictationController() { stopCapture() } if (engineStarted) { - await window.api.speech.stopDictation(sessionId).catch(() => undefined) + await window.api.speech.cancelDictation(sessionId).catch(() => undefined) drainStoppedSession(sessionId) } } @@ -176,6 +226,7 @@ export function DictationController() { sessionId, microphoneDeviceId: preferredMicrophoneDeviceId, microphoneDeviceLabel: settings?.voice?.microphoneDeviceLabel ?? null, + onFrame: kept.keep, onCaptureLost: () => { if (isCurrent()) { showMicrophoneDisconnectedToast() @@ -183,6 +234,7 @@ export function DictationController() { } }, onAudioLimitReached: () => { + kept.reachedHostLimit() if (isCurrent()) { showCloudLimitToast() void stopDictation() @@ -237,9 +289,7 @@ export function DictationController() { dispatch({ type: 'cancel' }) return } - dispatch({ type: 'fail' }) - showDictationStartErrorToast(message) - dispatch({ type: 'ended' }) + showFailure(dictationStartFailureKind(message), () => showDictationStartErrorToast(message)) } }, [ settings, @@ -251,9 +301,37 @@ export function DictationController() { stopDictation, finishDictationSession, drainStoppedSession, - recordFeatureInteraction + recordFeatureInteraction, + showFailure ]) + // Sends the failed session's recording through the speech host again, into the same place. + const retryDictation = useCallback(async () => { + const kept = keptRef.current + const modelId = settings?.voice?.sttModel + if (sessionRef.current.phase !== 'error' || !modelId || !kept || !canRetryDictation(kept)) { + return + } + const { run, sessionId } = dispatch({ type: 'retry' }) + if (sessionId === null) { + return + } + await transcribeKeptRecording({ + recording: kept, + modelId, + sessionId, + isCurrent: () => sessionRef.current.run === run, + routeFinals: (sink) => { + deliverRef.current = sink + }, + finish: (beforeEnd) => finishDictationSession(sessionRef.current, beforeEnd), + fail: (message) => + showFailure(dictationStartFailureKind(message) ?? 'transcribe', () => + showDictationStartErrorToast(message) + ) + }) + }, [settings, dispatch, finishDictationSession, showFailure]) + const toggleDictation = useCallback(() => { if (isDictationUnderway(sessionRef.current.phase)) { void stopDictation() @@ -262,32 +340,16 @@ export function DictationController() { } }, [startDictation, stopDictation]) - // Main intercepts Toggle presses and Auto double taps so the chord never reaches xterm. - useEffect(() => { - const mode = settings?.voice?.dictationMode ?? 'auto' - if (mode === 'hold' || !settings?.voice?.enabled) { - return - } - return window.api.ui.onDictationKeyDown(toggleDictation) - }, [settings?.voice?.dictationMode, settings?.voice?.enabled, toggleDictation]) - - useEffect(() => { - if (!settings?.voice?.enabled) { - return - } - const handleControl = (event: Event): void => { - const action = (event as CustomEvent).detail - if (action === 'start') { - void startDictation() - } else if (action === 'stop') { - void stopDictation() - } else { - toggleDictation() - } - } - document.addEventListener(DICTATION_CONTROL_EVENT, handleControl) - return () => document.removeEventListener(DICTATION_CONTROL_EVENT, handleControl) - }, [settings?.voice?.enabled, startDictation, stopDictation, toggleDictation]) + useDictationControls(settings?.voice, dictationState, { + start: () => void startDictation(), + stop: () => void stopDictation(), + cancel: cancelDictation, + toggle: toggleDictation, + retry: () => void retryDictation(), + // The error pill leaves Esc to Settings and dialogs; only its ✕ discards the recording. + escCancels: () => + isDictationUnderway(sessionRef.current.phase) || sessionRef.current.phase === 'stopping' + }) useDictationSilenceStop( dictationState === 'listening', @@ -316,23 +378,26 @@ export function DictationController() { onStopped: (sessionId) => recordStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef), onError: (sessionId, error) => { - toast.error( - t('auto.components.dictation.DictationController.de136f1199', 'Speech error: {{value0}}', { - value0: error - }) - ) const { run } = dispatch({ type: 'abandon' }) stopCapture() discardBufferedAudio() void (async () => { await window.api.speech.stopDictation(sessionId).catch(() => undefined) await waitForStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef) - if (sessionRef.current.run === run) { - dispatch({ type: 'ended' }) + if (sessionRef.current.run !== run) { + return } + showFailure('transcribe', () => showSpeechErrorToast(error)) })() } }) - return + return ( + + ) } diff --git a/src/renderer/src/components/dictation/DictationGrapes.tsx b/src/renderer/src/components/dictation/DictationGrapes.tsx index a2629bf6392..8b80331c9b0 100644 --- a/src/renderer/src/components/dictation/DictationGrapes.tsx +++ b/src/renderer/src/components/dictation/DictationGrapes.tsx @@ -3,11 +3,12 @@ import { DICTATION_GRAPES } from '../../../../shared/dictation-audio-meter' type DictationGrapesProps = { level: number + /** Moves with the voice; otherwise the grapes rest and pulse. */ active: boolean - transitioning: boolean + className?: string } -export function DictationGrapes({ level, active, transitioning }: DictationGrapesProps) { +export function DictationGrapes({ level, active, className }: DictationGrapesProps) { const normalizedLevel = Math.min(1, Math.max(0, level)) return ( @@ -16,7 +17,8 @@ export function DictationGrapes({ level, active, transitioning }: DictationGrape aria-hidden="true" className={cn( 'flex h-6 w-11 shrink-0 items-center justify-center gap-px overflow-hidden', - transitioning && 'animate-pulse motion-reduce:animate-none' + !active && 'animate-pulse motion-reduce:animate-none', + className )} > {DICTATION_GRAPES.map((grape, index) => { diff --git a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx new file mode 100644 index 00000000000..edf4f98d700 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx @@ -0,0 +1,77 @@ +import { useMemo, useState } from 'react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { DictationIndicator } from './DictationIndicator' +import { publishDictationMeter, resetDictationMeter } from './dictation-meter-store' +import type { DictationFailureKind } from './dictation-toasts' + +function PaneWithPill({ + captureLive = true, + failure = null +}: { + captureLive?: boolean + failure?: DictationFailureKind | null +}) { + const [pane, setPane] = useState(null) + const anchor = useMemo( + () => (pane ? { element: pane, placement: 'over' as const } : null), + [pane] + ) + return ( +
+ {anchor ? ( + + ) : null} +
+ ) +} + +export const listening = defineFixture({ + width: 520, + store: { dictationState: 'listening' }, + setup: () => publishDictationMeter({ level: 0.5, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const startingBeforeMic = defineFixture({ + width: 520, + store: { dictationState: 'starting' }, + setup: resetDictationMeter, + render: () => +}) + +export const liveText = defineFixture({ + width: 520, + store: { + dictationState: 'listening', + partialTranscript: + 'It should go back to the page you came from. Check where returnTo gets dropped' + }, + setup: () => publishDictationMeter({ level: 0.6, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const tooLoud = defineFixture({ + width: 520, + store: { dictationState: 'listening' }, + setup: () => publishDictationMeter({ level: 1, isSpeaking: true, isClipping: true }), + render: () => +}) + +export const finishing = defineFixture({ + width: 520, + store: { dictationState: 'stopping' }, + setup: resetDictationMeter, + render: () => +}) + +export const transcribeFailed = defineFixture({ + width: 520, + store: { dictationState: 'error' }, + render: () => +}) + +export const modelFailed = defineFixture({ + width: 520, + store: { dictationState: 'error' }, + render: () => +}) diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index a231abedecf..c79bb3f903d 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -1,114 +1,231 @@ +import { useEffect, useRef, useState } from 'react' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useShortcutKeyDetails } from '@/hooks/useShortcutLabel' import { useTranslate } from '@/i18n/use-translate' +import { KEEPS_FOCUS_ATTRIBUTE } from '@/lib/focus-keeping-press' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' -import { Square } from 'lucide-react' +import { Check, Loader2 } from 'lucide-react' +import { isDictationPillShown } from '../../../../shared/dictation-session-machine' +import { CLOUD_DICTATION_MAX_SECONDS } from '../../../../shared/rpc-contract/speech-params' +import type { SpeechModelManifest } from '../../../../shared/speech-types' import { dispatchDictationControl } from './dictation-control-events' import { DictationGrapes } from './DictationGrapes' import { useDictationMeter } from './dictation-meter-store' +import { useDictationPillBox, type DictationPillAnchor } from './dictation-pill-anchor' +import { DictationPillCloseButton, DictationPillFailure } from './DictationPillFailure' +import type { DictationFailureKind } from './dictation-toasts' -// captureLive: the mic is recording (and buffering) while the speech engine is still starting. -export function DictationIndicator({ captureLive }: { captureLive: boolean }) { +// The finish button turns into a spinner only when finishing is slow enough to notice. +const FINISH_SPINNER_DELAY_MS = 200 +// The timer warns a minute before cloud dictation stops. +const CLOUD_LIMIT_WARNING_SECONDS = CLOUD_DICTATION_MAX_SECONDS - 60 + +type DictationIndicatorProps = { + /** The mic is recording (and buffering) while the speech engine is still starting. */ + captureLive: boolean + anchor: DictationPillAnchor | null + /** Set while the error pill shows a failed recording that can be retried. */ + failure: DictationFailureKind | null +} + +export function DictationIndicator(props: DictationIndicatorProps) { + const dictationState = useAppStore((state) => state.dictationState) + return isDictationPillShown(dictationState) ? : null +} + +function formatElapsed(seconds: number): string { + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` +} + +/** Seconds since `running` first turned on; holds still once it turns off. */ +function useElapsedSeconds(running: boolean): number { + const startedAtRef = useRef(null) + const [seconds, setSeconds] = useState(0) + useEffect(() => { + if (!running) { + return + } + if (startedAtRef.current === null) { + startedAtRef.current = performance.now() + } + const startedAt = startedAtRef.current + // Measured from the start, so ticks skipped while the window is hidden don't drift it. + return installWindowVisibilityInterval({ + run: () => setSeconds(Math.floor((performance.now() - startedAt) / 1000)), + intervalMs: 250 + }) + }, [running]) + return seconds +} + +// The catalog never changes while the app runs; the paired web client has none and its host caps itself. +let catalogRequest: Promise | null = null + +function useIsCloudModel(): boolean { + const modelId = useAppStore((state) => state.settings?.voice?.sttModel) + const [cloud, setCloud] = useState(false) + useEffect(() => { + let current = true + if (!catalogRequest) { + catalogRequest = Promise.resolve() + .then(() => window.api.speech.getCatalog()) + .catch(() => []) + } + void catalogRequest.then((catalog) => { + if (current) { + setCloud(catalog.some((model) => model.id === modelId && model.provider === 'openai')) + } + }) + return () => { + current = false + } + }, [modelId]) + return cloud +} + +function useDelayedFlag(on: boolean, delayMs: number): boolean { + const [delayed, setDelayed] = useState(false) + useEffect(() => { + if (!on) { + setDelayed(false) + return + } + const id = window.setTimeout(() => setDelayed(true), delayMs) + return () => window.clearTimeout(id) + }, [on, delayMs]) + return delayed +} + +// Only this re-renders per meter tick, not the whole pill. +function DictationPillMeter({ recording, status }: { recording: boolean; status: string }) { + const t = useTranslate() + const meter = useDictationMeter() + const clipping = recording && meter.isClipping + return ( + <> + + {clipping + ? t('auto.components.dictation.DictationIndicator.4977162383', 'Too loud') + : status} + + + + ) +} + +// Presses on the pill keep focus where the words are going. +const keepFocus = (event: React.MouseEvent): void => event.preventDefault() +const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } + +function DictationPill({ captureLive, anchor, failure }: DictationIndicatorProps) { const t = useTranslate() const dictationState = useAppStore((state) => state.dictationState) const partialTranscript = useAppStore((state) => state.partialTranscript) - const dictationMeter = useDictationMeter() const isHoldMode = useAppStore((state) => state.settings?.voice?.dictationMode === 'hold') const shortcut = useShortcutKeyDetails('voice.dictation') + const box = useDictationPillBox(anchor) + const cloudModel = useIsCloudModel() - const isVisible = ['listening', 'starting', 'stopping'].includes(dictationState) - if (!isVisible) { - return null - } - - const isLoadingModel = dictationState === 'starting' && captureLive - const isListening = dictationState === 'listening' || isLoadingModel - const isClipping = isListening && dictationMeter.isClipping - const isSpeaking = isListening && dictationMeter.isSpeaking && !isClipping - const lifecycleLabel = isListening - ? t('auto.components.dictation.DictationIndicator.3de5a129e7', 'Listening') - : dictationState === 'starting' - ? t('auto.components.dictation.DictationIndicator.7f3660a7ba', 'Starting mic…') - : t('auto.components.dictation.DictationIndicator.f082d0cb9d', 'Processing…') - const label = isClipping - ? t('auto.components.dictation.DictationIndicator.4977162383', 'Too loud') - : isSpeaking - ? t('auto.components.dictation.DictationIndicator.25f2b7a6a5', 'Speaking') - : lifecycleLabel - const announcedLabel = isClipping ? label : lifecycleLabel - const canStop = dictationState !== 'stopping' - const showShortcut = !isHoldMode && shortcut.keys.length > 0 + const finishing = dictationState === 'stopping' + const recording = dictationState === 'listening' || (dictationState === 'starting' && captureLive) + // Counts recorded time, so it waits for the mic to open. + const seconds = useElapsedSeconds(recording) + const showSpinner = useDelayedFlag(finishing, FINISH_SPINNER_DELAY_MS) + const nearCloudLimit = cloudModel && seconds >= CLOUD_LIMIT_WARNING_SECONDS + const failedKind = dictationState === 'error' ? failure : null const transcript = partialTranscript.trim() - const stopLabel = t('auto.components.dictation.DictationIndicator.335e1bc6cb', 'Stop dictation') + const status = finishing + ? t('auto.components.dictation.DictationIndicator.finishing', 'Finishing…') + : t('auto.components.dictation.DictationIndicator.listening', 'Listening…') + const announced = nearCloudLimit + ? `${status} ${t('auto.components.dictation.DictationIndicator.oneMinuteLeft', 'One minute left.')}` + : status + const cancelLabel = t('auto.components.dictation.DictationIndicator.cancel', 'Cancel') + const finishLabel = t('auto.components.dictation.DictationIndicator.finish', 'Finish') return (
-
- - - {label} - - {isLoadingModel ? ( - - {t( - 'auto.components.dictation.DictationIndicator.loadingModel', - 'Loading speech model…' + {failedKind ? ( + + ) : ( + <> + + + {transcript ? ( + + {transcript} + + ) : ( + + {status} + + )} + + {formatElapsed(seconds)} - ) : null} - - {announcedLabel} - - {canStop ? ( - <> - + {finishing ? ( + + {showSpinner ? ( + + ) : ( + + )} + + ) : ( - - {stopLabel} - {showShortcut ? ( - - ) : null} + + + {finishLabel} + {!isHoldMode && shortcut.keys.length > 0 ? ( + + ) : null} + - - ) : null} -
- {transcript ? ( -

- {transcript} -

- ) : null} + )} + + )}
) } diff --git a/src/renderer/src/components/dictation/DictationPillFailure.tsx b/src/renderer/src/components/dictation/DictationPillFailure.tsx new file mode 100644 index 00000000000..a1448b51608 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationPillFailure.tsx @@ -0,0 +1,68 @@ +import { Button } from '@/components/ui/button' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { useTranslate } from '@/i18n/use-translate' +import { CircleAlert, X } from 'lucide-react' +import { dispatchDictationControl } from './dictation-control-events' +import { openVoiceSettings, type DictationFailureKind } from './dictation-toasts' + +/** The pill's ✕: cancels a dictation, or discards a failed one's recording. */ +export function DictationPillCloseButton({ label }: { label: string }) { + return ( + + + + + + {label} + + + ) +} + +/** The error pill's row: it keeps the failed recording until Retry, ✕ or the next dictation. */ +export function DictationPillFailure({ kind }: { kind: DictationFailureKind }) { + const t = useTranslate() + const discardLabel = t( + 'auto.components.dictation.DictationPillFailure.discard', + 'Discard recording' + ) + const message = + kind === 'settings' + ? t( + 'auto.components.dictation.DictationPillFailure.modelFailed', + "Speech model couldn't load." + ) + : t( + 'auto.components.dictation.DictationPillFailure.transcribeFailed', + "Couldn't transcribe. Recording kept." + ) + + return ( + <> + + {message} + + + + + {message} + + {kind === 'settings' ? ( + + ) : null} + + + ) +} diff --git a/src/renderer/src/components/dictation/dictation-control-events.ts b/src/renderer/src/components/dictation/dictation-control-events.ts index df9ed811340..63db59807b7 100644 --- a/src/renderer/src/components/dictation/dictation-control-events.ts +++ b/src/renderer/src/components/dictation/dictation-control-events.ts @@ -3,7 +3,7 @@ export const DICTATION_CONTROL_EVENT = 'dictation:control' /** Dictation started with no text field focused; the pane that owns typing focuses its input. */ export const DICTATION_FOCUS_INPUT_EVENT = 'dictation:focusInput' -export type DictationControlAction = 'toggle' | 'start' | 'stop' +export type DictationControlAction = 'toggle' | 'start' | 'stop' | 'cancel' | 'retry' export function dispatchDictationControl(action: DictationControlAction): void { document.dispatchEvent( diff --git a/src/renderer/src/components/dictation/dictation-insertion-target.ts b/src/renderer/src/components/dictation/dictation-insertion-target.ts index ff4ff69141c..ace14f22e96 100644 --- a/src/renderer/src/components/dictation/dictation-insertion-target.ts +++ b/src/renderer/src/components/dictation/dictation-insertion-target.ts @@ -16,8 +16,8 @@ type ComposerInsert = (text: string) => boolean type TerminalInsert = (text: string, paneId: number) => Promise export type DictationInsertionTarget = - | { kind: 'composer'; insert: ComposerInsert } - | { kind: 'terminal'; tabId: string; paneId: number } + | { kind: 'composer'; insert: ComposerInsert; root: HTMLElement } + | { kind: 'terminal'; tabId: string; paneId: number; pane: HTMLElement } | { kind: 'text'; element: HTMLInputElement | HTMLTextAreaElement } | { kind: 'contentEditable'; element: HTMLElement } @@ -65,8 +65,8 @@ function readFocusedInsertionTarget(): DictationInsertionTarget | null { for (let root: Element | null = activeElement; root; root = root.parentElement) { const insert = root instanceof HTMLElement ? composerTargets.get(root) : undefined - if (insert) { - return { kind: 'composer', insert } + if (insert && root instanceof HTMLElement) { + return { kind: 'composer', insert, root } } } @@ -75,8 +75,8 @@ function readFocusedInsertionTarget(): DictationInsertionTarget | null { const tabElement = activeElement.closest('[data-terminal-tab-id]') as HTMLElement | null const paneId = Number(paneElement?.dataset.paneId) const tabId = tabElement?.dataset.terminalTabId - if (tabId && Number.isFinite(paneId)) { - return { kind: 'terminal', tabId, paneId } + if (paneElement && tabId && Number.isFinite(paneId)) { + return { kind: 'terminal', tabId, paneId, pane: paneElement } } return null } diff --git a/src/renderer/src/components/dictation/dictation-kept-recording.ts b/src/renderer/src/components/dictation/dictation-kept-recording.ts new file mode 100644 index 00000000000..9853bb5b438 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-kept-recording.ts @@ -0,0 +1,135 @@ +import { + CLOUD_DICTATION_MAX_SECONDS, + DICTATION_SAMPLE_RATE +} from '../../../../shared/rpc-contract/speech-params' +import type { DictationInsertionTarget } from './dictation-insertion-target' +import type { DictationTranscriptDelivery } from './dictation-transcript-delivery' +import { trimLandedOverlap } from './dictation-retry-overlap' +import { showRetryOverlapUnmatchedToast } from './dictation-toasts' + +// The cloud cap, ten minutes, is about 38 MB of 16 kHz float audio. +const MAX_KEPT_SAMPLES = CLOUD_DICTATION_MAX_SECONDS * DICTATION_SAMPLE_RATE + +/** A session's audio, in memory only, so a failed transcription can be retried into the same place. */ +export type DictationKeptRecording = { + chunks: Float32Array[] + /** False once audio past the cap was dropped; a retry would then lose words. */ + complete: boolean + target: DictationInsertionTarget | null + deliver: DictationTranscriptDelivery +} + +export function createDictationKeptRecording( + target: DictationInsertionTarget | null, + deliver: DictationTranscriptDelivery +): DictationKeptRecording & { + keep: (samples: Float32Array) => void + /** The host stopped accepting audio at its own cap, so the first ten minutes are all it would hear. */ + reachedHostLimit: () => void +} { + let samples = 0 + let hostLimited = false + const chunks: Float32Array[] = [] + const recording = { + chunks, + complete: true, + target, + deliver, + keep: (frame: Float32Array): void => { + const room = MAX_KEPT_SAMPLES - samples + if (room <= 0) { + recording.complete = hostLimited + return + } + const kept = frame.length > room ? frame.subarray(0, room) : frame + samples += kept.length + chunks.push(kept) + if (kept !== frame) { + recording.complete = hostLimited + } + }, + reachedHostLimit: (): void => { + hostLimited = true + recording.complete = true + } + } + return recording +} + +/** Whether a failure can offer Retry: some audio was kept, and all of it. */ +export function canRetryDictation(recording: DictationKeptRecording | null): boolean { + return recording !== null && recording.complete && recording.chunks.length > 0 +} + +// Ten-second blocks keep a retried recording to a few hundred feeds instead of one per 100 ms frame. +const RETRY_BLOCK_SAMPLES = 10 * DICTATION_SAMPLE_RATE + +/** Built one block at a time, so a retry never holds a second copy of the whole recording. */ +function* joinIntoBlocks(chunks: Float32Array[]): Generator { + let start = 0 + while (start < chunks.length) { + let end = start + let blockSamples = 0 + while (end < chunks.length && blockSamples < RETRY_BLOCK_SAMPLES) { + blockSamples += chunks[end].length + end += 1 + } + const block = new Float32Array(blockSamples) + let offset = 0 + for (let index = start; index < end; index += 1) { + block.set(chunks[index], offset) + offset += chunks[index].length + } + yield block + start = end + } +} + +// The retry repeats words that landed before the failure; only what follows them is typed. +function insertAfterLanded(recording: DictationKeptRecording, retried: string[]): void { + const { text, matched } = trimLandedOverlap(recording.deliver.landedText(), retried.join(' ')) + if (text) { + recording.deliver(text, recording.target) + } + if (!matched) { + showRetryOverlapUnmatchedToast() + } +} + +/** Runs a kept recording through a new speech session; `finish` stops it and waits for its words. */ +export async function transcribeKeptRecording(args: { + recording: DictationKeptRecording + modelId: string + sessionId: string + isCurrent: () => boolean + /** Where the retry's finals go until it ends. */ + routeFinals: (sink: (text: string) => void) => void + finish: (beforeEnd: () => void) => Promise + fail: (message: string) => void +}): Promise { + const { sessionId, isCurrent } = args + const retried: string[] = [] + args.routeFinals((text) => retried.push(text)) + try { + await window.api.speech.startDictation(args.modelId, undefined, sessionId) + for (const block of joinIntoBlocks(args.recording.chunks)) { + if (!isCurrent()) { + break + } + await window.api.speech.feedAudio(block, DICTATION_SAMPLE_RATE, sessionId) + } + if (!isCurrent()) { + await window.api.speech.cancelDictation(sessionId).catch(() => undefined) + return + } + await args.finish(() => insertAfterLanded(args.recording, retried)) + } catch (error) { + if (!isCurrent()) { + return + } + await window.api.speech.cancelDictation(sessionId).catch(() => undefined) + if (isCurrent()) { + args.fail(String(error)) + } + } +} diff --git a/src/renderer/src/components/dictation/dictation-pill-anchor.ts b/src/renderer/src/components/dictation/dictation-pill-anchor.ts new file mode 100644 index 00000000000..5fff470ecb1 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-pill-anchor.ts @@ -0,0 +1,63 @@ +import { useLayoutEffect, useState } from 'react' +import type { DictationInsertionTarget } from './dictation-insertion-target' + +/** The pane the words go to; the pill floats over its bottom edge, or just above a chat composer. */ +export type DictationPillAnchor = { element: HTMLElement; placement: 'over' | 'above' } + +/** Fixed-position box: `left` is the pill's centre, `bottom` its distance from the window's bottom edge. */ +type DictationPillBox = { left: number; bottom: number; width: number } + +const PILL_MAX_WIDTH = 440 +const PANE_INSET = 16 +const OVER_GAP = 12 +const ABOVE_GAP = 8 + +export function dictationPillAnchorFor( + target: DictationInsertionTarget | null +): DictationPillAnchor | null { + if (target?.kind === 'composer') { + return { element: target.root, placement: 'above' } + } + if (target?.kind === 'terminal') { + return { element: target.pane, placement: 'over' } + } + return null +} + +function readPillBox(anchor: DictationPillAnchor): DictationPillBox | null { + const { element, placement } = anchor + if (!element.isConnected || !element.checkVisibility({ visibilityProperty: true })) { + return null + } + const rect = element.getBoundingClientRect() + if (rect.width <= PANE_INSET * 2 || rect.height === 0) { + return null + } + const edge = placement === 'above' ? rect.top - ABOVE_GAP : rect.bottom - OVER_GAP + return { + left: rect.left + rect.width / 2, + bottom: window.innerHeight - edge, + width: Math.min(PILL_MAX_WIDTH, rect.width - PANE_INSET * 2) + } +} + +/** Follows the anchor pane's size; once it's hidden or gone, null puts the pill at the window's bottom centre. */ +export function useDictationPillBox(anchor: DictationPillAnchor | null): DictationPillBox | null { + const [box, setBox] = useState(null) + useLayoutEffect(() => { + if (!anchor) { + setBox(null) + return + } + const update = (): void => setBox(readPillBox(anchor)) + update() + const observer = new ResizeObserver(update) + observer.observe(anchor.element) + window.addEventListener('resize', update) + return () => { + observer.disconnect() + window.removeEventListener('resize', update) + } + }, [anchor]) + return box +} diff --git a/src/renderer/src/components/dictation/dictation-retry-overlap.test.ts b/src/renderer/src/components/dictation/dictation-retry-overlap.test.ts new file mode 100644 index 00000000000..7ddbdee0619 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-retry-overlap.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { trimLandedOverlap } from './dictation-retry-overlap' + +describe('trimLandedOverlap', () => { + it.each([ + { + name: 'drops the words that already landed', + landed: 'The login page sends you to the root after sign in.', + retried: + 'The login page sends you to the root after sign in. It should go back to the page you came from.', + expected: { text: 'It should go back to the page you came from.', matched: true } + }, + { + name: 'ignores case and punctuation differences in the re-decode', + landed: 'the login page sends you to the root after sign-in', + retried: + 'The login page sends you to the Root, after sign in. Check where returnTo gets dropped.', + expected: { text: 'Check where returnTo gets dropped.', matched: true } + }, + { + name: 'picks the match nearest where the landed text ends', + landed: 'go back to the page. Then go back to the page', + retried: 'Go back to the page. Then go back to the page. Done.', + expected: { text: 'Done.', matched: true } + }, + { + name: 'inserts nothing when everything already landed', + landed: 'It should go back to the page you came from.', + retried: 'It should go back to the page you came from.', + expected: { text: '', matched: true } + }, + { + name: 'inserts everything when nothing landed', + landed: '', + retried: ' Check where returnTo gets dropped. ', + expected: { text: 'Check where returnTo gets dropped.', matched: true } + }, + { + name: 'inserts everything when the landed words are not found', + landed: 'something entirely different was typed here', + retried: 'The login page sends you to the root.', + expected: { text: 'The login page sends you to the root.', matched: false } + } + ])('$name', ({ landed, retried, expected }) => { + expect(trimLandedOverlap(landed, retried)).toEqual(expected) + }) +}) diff --git a/src/renderer/src/components/dictation/dictation-retry-overlap.ts b/src/renderer/src/components/dictation/dictation-retry-overlap.ts new file mode 100644 index 00000000000..0001f22cde9 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-retry-overlap.ts @@ -0,0 +1,63 @@ +type Word = { key: string; end: number } + +// Long enough that a match is the landed text, not a common phrase; short enough to survive a re-decode's small differences. +const ANCHOR_WORDS = [5, 4, 3] + +// Transcripts aren't in the UI language; word breaks only need to be language-neutral. +const segmenter = new Intl.Segmenter('und', { granularity: 'word' }) + +/** Words compared case- and punctuation-blind, each with where it ends in the original text. */ +function readWords(text: string): Word[] { + const words: Word[] = [] + for (const part of segmenter.segment(text)) { + const key = part.segment.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '') + if (part.isWordLike && key) { + words.push({ key, end: part.index + part.segment.length }) + } + } + return words +} + +function endsAt(words: Word[], anchor: Word[], end: number): boolean { + return anchor.every((word, index) => words[end - anchor.length + index]?.key === word.key) +} + +/** + * A retry re-transcribes the whole recording, so its start repeats what already landed. + * Returns what comes after the landed text's last words; with no confident match, all of it. + */ +export function trimLandedOverlap( + landed: string, + retried: string +): { text: string; matched: boolean } { + const landedWords = readWords(landed) + if (landedWords.length === 0) { + return { text: retried.trim(), matched: true } + } + const retriedWords = readWords(retried) + const sizes = ANCHOR_WORDS.filter((size) => size <= landedWords.length) + for (const size of sizes.length > 0 ? sizes : [landedWords.length]) { + const anchor = landedWords.slice(-size) + let best: number | null = null + for (let end = size; end <= retriedWords.length; end += 1) { + // Several matches: the one nearest where the landed text should end wins. + if ( + endsAt(retriedWords, anchor, end) && + (best === null || Math.abs(end - landedWords.length) < Math.abs(best - landedWords.length)) + ) { + best = end + } + } + if (best !== null) { + const cut = retriedWords[best - 1].end + return { + text: retried + .slice(cut) + .replace(/^[^\p{L}\p{N}]+/u, '') + .trim(), + matched: true + } + } + } + return { text: retried.trim(), matched: false } +} diff --git a/src/renderer/src/components/dictation/dictation-toasts.test.ts b/src/renderer/src/components/dictation/dictation-toasts.test.ts new file mode 100644 index 00000000000..b22a3e0ab36 --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-toasts.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { dictationStartFailureKind } from './dictation-toasts' + +const startError = (detail: string): string => + `Error: Error invoking remote method 'speech:startDictation': Error: ${detail}` + +describe('dictationStartFailureKind', () => { + it.each([ + [startError('Model not ready: not-downloaded'), 'settings'], + [startError('The speech engine stopped unexpectedly. Try again.'), 'settings'], + ['NotAllowedError: Permission denied', null], + [startError('Microphone access not granted. Open System Settings.'), null], + ['Error: dictation_model_busy', null] + ])('%s → %s', (message, kind) => { + expect(dictationStartFailureKind(message)).toBe(kind) + }) +}) diff --git a/src/renderer/src/components/dictation/dictation-toasts.ts b/src/renderer/src/components/dictation/dictation-toasts.ts index 42c4a21d44c..a196f050220 100644 --- a/src/renderer/src/components/dictation/dictation-toasts.ts +++ b/src/renderer/src/components/dictation/dictation-toasts.ts @@ -4,16 +4,51 @@ import { translate } from '@/i18n/i18n' import { compactIpcErrorMessage } from '@/lib/ipc-error' import { hostDictationErrorMessage } from '../../../../shared/host-dictation-error-messages' +export function openVoiceSettings(): void { + useAppStore.getState().openSettingsTarget({ pane: 'voice', repoId: null }) + useAppStore.getState().openSettingsPage() +} + function openVoiceSettingsAction(): { label: string; onClick: () => void } { return { label: translate('auto.components.dictation.DictationController.bb7f599ee7', 'Open Settings'), - onClick: () => { - useAppStore.getState().openSettingsTarget({ pane: 'voice', repoId: null }) - useAppStore.getState().openSettingsPage() - } + onClick: openVoiceSettings } } +type DictationStartError = 'host' | 'microphone' | 'model-not-ready' | 'unknown-model' | 'other' + +function classifyDictationStartError(message: string): { + kind: DictationStartError + detail: string +} { + // A paired web client rejects with the host's bare code, which String(error) prefixes with "Error: ". + const detail = compactIpcErrorMessage(message)?.replace(/^Error:\s*/, '') ?? '' + const kind: DictationStartError = hostDictationErrorMessage(detail) + ? 'host' + : message.includes('Permission') || message.includes('NotAllowed') + ? 'microphone' + : message.includes('not ready') || detail.startsWith('voice_model_not_ready') + ? 'model-not-ready' + : message.includes('Unknown model') + ? 'unknown-model' + : 'other' + return { kind, detail } +} + +/** `settings` failures offer Open settings beside Retry. */ +export type DictationFailureKind = 'settings' | 'transcribe' + +/** A start that failed after recording began is a model that couldn't load; null keeps the toast. */ +export function dictationStartFailureKind(message: string): DictationFailureKind | null { + const { kind } = classifyDictationStartError(message) + // Main's macOS mic check fails before any audio could be transcribed. + if (kind === 'host' || kind === 'microphone' || message.includes('Microphone access')) { + return null + } + return 'settings' +} + export function showDictationNoModelToast(): void { toast( translate( @@ -54,6 +89,33 @@ export function showCloudLimitToast(): void { ) } +export function showRetryOverlapUnmatchedToast(): void { + toast.message( + translate( + 'auto.components.dictation.DictationController.retryUnmatched', + "Retry couldn't tell which words were already typed, so it inserted them all." + ) + ) +} + +export function showNoSpeechDetectedToast(): void { + toast.message( + translate('auto.components.dictation.DictationController.5d2c3e7ae3', 'No speech detected.') + ) +} + +export function showSpeechErrorToast(error: string): void { + toast.error( + translate( + 'auto.components.dictation.DictationController.de136f1199', + 'Speech error: {{value0}}', + { + value0: error + } + ) + ) +} + export function showMicrophoneDisconnectedToast(): void { toast.message( translate( @@ -64,19 +126,18 @@ export function showMicrophoneDisconnectedToast(): void { } export function showDictationStartErrorToast(message: string): void { - // A paired web client rejects with the host's bare code, which String(error) prefixes with "Error: ". - const detail = compactIpcErrorMessage(message)?.replace(/^Error:\s*/, '') ?? '' + const { kind, detail } = classifyDictationStartError(message) const hostMessage = hostDictationErrorMessage(detail) if (hostMessage) { toast.error(hostMessage) - } else if (message.includes('Permission') || message.includes('NotAllowed')) { + } else if (kind === 'microphone') { toast.error( translate( 'auto.components.dictation.DictationController.2d5b9fabf9', 'Microphone access denied. Grant access in system settings, then restart Orca.' ) ) - } else if (message.includes('not ready') || detail.startsWith('voice_model_not_ready')) { + } else if (kind === 'model-not-ready') { toast( translate( 'auto.components.dictation.DictationController.notReady', @@ -84,7 +145,7 @@ export function showDictationStartErrorToast(message: string): void { ), { action: openVoiceSettingsAction() } ) - } else if (message.includes('Unknown model')) { + } else if (kind === 'unknown-model') { toast( translate( 'auto.components.dictation.DictationController.unknownModel', diff --git a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts index bad8650e313..01b6446e139 100644 --- a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts +++ b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts @@ -4,27 +4,33 @@ import { describeClipboardWriteFailure } from '@/lib/clipboard-write-failure' import { dictationSeparators } from '../../../../shared/dictation-transcript-spacing' import { insertText, type DictationInsertionTarget } from './dictation-insertion-target' -export type DictationTranscriptDelivery = ( +export type DictationTranscriptDelivery = (( text: string, target: DictationInsertionTarget | null -) => void +) => void) & { + /** Everything this session has typed into its target so far. */ + landedText: () => string +} /** One session's finals, inserted in order; text that can't land goes to the clipboard so it isn't lost. */ export function createDictationTranscriptDelivery(): DictationTranscriptDelivery { let lastLanded = '' + let allLanded = '' let missed = '' let queue = Promise.resolve() - return (text, target) => { + const deliver = (text: string, target: DictationInsertionTarget | null): void => { queue = queue.then(async () => { const landed = target ? await insertText(text, target, lastLanded).catch(() => false) : false if (landed) { lastLanded = text + allLanded += `${dictationSeparators(allLanded, text, '').leading}${text}` return } missed += `${dictationSeparators(missed, text, '').leading}${text}` await copyMissedDictation(missed, target !== null) }) } + return Object.assign(deliver, { landedText: () => allLanded }) } async function copyMissedDictation(text: string, hadTarget: boolean): Promise { diff --git a/src/renderer/src/components/dictation/use-dictation-controls.ts b/src/renderer/src/components/dictation/use-dictation-controls.ts new file mode 100644 index 00000000000..9a3a09f27da --- /dev/null +++ b/src/renderer/src/components/dictation/use-dictation-controls.ts @@ -0,0 +1,56 @@ +import { useEffect, useEffectEvent } from 'react' +import { addAppKeyListener, removeAppKeyListener } from '@/lib/app-keyboard-router' +import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' +import { isPlainEscapeKeyEvent } from '../terminal-pane/input/keyboard/agent-interrupt-key-event' +import { DICTATION_CONTROL_EVENT, type DictationControlAction } from './dictation-control-events' +import type { DictationState } from '../../../../shared/speech-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' + +type DictationControlHandlers = Record void> & { + escCancels: () => boolean +} + +/** Routes the shortcut, the pill's buttons, the composer mic and Esc to the session controller. */ +export function useDictationControls( + voice: GlobalSettings['voice'] | undefined, + phase: DictationState, + handlers: DictationControlHandlers +): void { + const run = useEffectEvent((action: DictationControlAction) => handlers[action]()) + const escCancels = useEffectEvent(() => handlers.escCancels()) + // A failed recording stays retryable even after voice is turned off in Settings. + const enabled = voice?.enabled === true || phase !== 'idle' + const mainShortcut = voice?.enabled === true && (voice.dictationMode ?? 'auto') !== 'hold' + + // Main intercepts Toggle presses and Auto double taps so the chord never reaches xterm. + useEffect(() => { + if (!mainShortcut) { + return + } + return window.api.ui.onDictationKeyDown(() => run('toggle')) + }, [mainShortcut]) + + useEffect(() => { + if (!enabled) { + return + } + const handleControl = (event: Event): void => + run((event as CustomEvent).detail) + document.addEventListener(DICTATION_CONTROL_EVENT, handleControl) + return () => document.removeEventListener(DICTATION_CONTROL_EVENT, handleControl) + }, [enabled]) + + // Esc cancels a dictation and goes no further, so it can't also interrupt the agent. + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent): void => { + if (!isPlainEscapeKeyEvent(event) || isImeOwnedKeyboardEvent(event) || !escCancels()) { + return + } + event.preventDefault() + event.stopImmediatePropagation() + run('cancel') + } + addAppKeyListener('keydown', handleKeyDown, { first: true }) + return () => removeAppKeyListener('keydown', handleKeyDown) + }, []) +} diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts index b3091e66d6c..eee2d5b02b4 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-focus-lifecycle.ts @@ -1,5 +1,6 @@ import { useEffect } from 'react' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' +import { isFocusKeepingPress } from '@/lib/focus-keeping-press' import { clearFloatingPanelReclaimIntent } from '@/lib/floating-workspace-focus-reclaim' import { isFloatingWorkspaceTerminalInputTarget } from '@/lib/floating-workspace-terminal-actions' import { reportFloatingFocus } from './floating-terminal-focus-reporting' @@ -34,7 +35,12 @@ export function useFloatingTerminalFocusLifecycle({ } const handleOutsidePointerDown = (event: PointerEvent): void => { const panel = panelRef.current - if (!panel || !(event.target instanceof Node) || panel.contains(event.target)) { + if ( + !panel || + !(event.target instanceof Node) || + panel.contains(event.target) || + isFocusKeepingPress(event.target) + ) { return } reportFloatingFocus(null, true) diff --git a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts deleted file mode 100644 index a8eb0930cac..00000000000 --- a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalSubmissionKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionOptimisticMessage } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { structuredAgentSessionSendBody } from '../../../../../../shared/agent-session/requests/structured-agent-session-send-mutation' -import { projectStructuredAgentSessionMessages } from './structured-agent-session-message-projection' - -function optimisticMessage(args: { - clientMessageId: string - sessionId?: string - text: string - attachments: readonly { path: string; previewUri: string }[] - queuedAt: number -}): StructuredAgentSessionOptimisticMessage { - return { - clientMessageId: args.clientMessageId, - body: structuredAgentSessionSendBody(args.text, args.attachments), - queuedAt: args.queuedAt - } -} - -function submission(index: number): AgentJournalSubmission { - return { - clientMessageId: `client-${index}`, - fence: 1, - payloadFingerprint: `fingerprint-${index}`, - dispatchState: 'accepted', - providerItemId: `provider-${index}`, - reason: null, - submittedAt: index, - resolvedAt: index - } -} - -function item(index: number): AgentJournalRenderItem { - return { - itemId: `journal-${index}`, - revision: 1, - sequence: index, - observedAt: index, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: `send ${index}` }] } - } -} - -describe('structured agent session message projection', () => { - it("draws a send the host rejected from the host's row, not the outbox copy", () => { - const rejected = { ...submission(0), dispatchState: 'rejected' as const, providerItemId: null } - const refusedItem = { ...item(0), itemId: agentJournalSubmissionKey(rejected.clientMessageId) } - const draft = optimisticMessage({ - clientMessageId: rejected.clientMessageId, - sessionId: 'session-1', - text: 'An unsent draft', - attachments: [], - queuedAt: 1 - }) - expect(projectStructuredAgentSessionMessages([refusedItem], [draft], [rejected])).toEqual([ - expect.objectContaining({ - id: refusedItem.itemId, - blocks: [{ type: 'text', text: 'send 0' }], - unsent: true - }) - ]) - }) - - it.each([5, 10])('renders %i rapid accepted desktop sends exactly once', (sendCount) => { - const outbox = Array.from({ length: sendCount }, (_, index) => - optimisticMessage({ - clientMessageId: `client-${index}`, - sessionId: 'session-1', - text: `send ${index}`, - attachments: [], - queuedAt: index - }) - ) - const messages = projectStructuredAgentSessionMessages( - Array.from({ length: sendCount }, (_, index) => item(index)), - outbox, - Array.from({ length: sendCount }, (_, index) => submission(sendCount - index - 1)) - ) - - expect(messages.filter((message) => message.role === 'user')).toHaveLength(sendCount) - expect(messages.map((message) => message.id)).toEqual( - Array.from({ length: sendCount }, (_, index) => `journal-${index}`) - ) - }) - - it('renders one bubble while the submission is still dispatching', () => { - const outbox = [ - optimisticMessage({ - clientMessageId: 'client-pending', - sessionId: 'session-1', - text: 'Ok thanks', - attachments: [], - queuedAt: 1 - }) - ] - // The host's WAL row is on screen while the provider round trip is in flight. - const walItem: AgentJournalRenderItem = { - itemId: agentJournalSubmissionKey('client-pending'), - revision: 0, - sequence: 1, - observedAt: 1, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Ok thanks' }] } - } - const pending: AgentJournalSubmission = { - ...submission(0), - clientMessageId: 'client-pending', - dispatchState: 'pending', - providerItemId: null, - resolvedAt: null - } - - const messages = projectStructuredAgentSessionMessages([walItem], outbox, [pending]) - const optimistic = projectStructuredAgentSessionMessages([], outbox, []) - - expect(messages.filter((message) => message.role === 'user')).toHaveLength(1) - expect(messages.map((message) => message.id)).toEqual([walItem.itemId]) - expect(optimistic[0]?.id).toBe(messages[0]?.id) - }) -}) diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts deleted file mode 100644 index fddfb09510a..00000000000 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { beforeEach, describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import { - noteUserWorkspaceSwitch, - resetWorkspaceSwitchUserActsForTests -} from '@/lib/workspace-switch-user-act' -import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' -import { takeNativeChatOpenWake } from './native-chat-open-wake' - -const LEAF = '11111111-1111-4111-8111-111111111111' - -function tabs(entries: Record): AppState['tabsByWorktree'] { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the wake only reads each tab's id. - return Object.fromEntries( - Object.entries(entries).map(([worktreeId, ids]) => [worktreeId, ids.map((id) => ({ id }))]) - ) as unknown as AppState['tabsByWorktree'] -} - -describe('takeNativeChatOpenWake (E9)', () => { - beforeEach(() => resetWorkspaceSwitchUserActsForTests()) - - it('a chat in another workspace mounting inside the switch window neither wakes nor spends the switch', () => { - const byWorktree = tabs({ 'wt-a': ['tab-a'], 'wt-b': ['tab-b'] }) - noteUserWorkspaceSwitch('wt-a') - expect(takeNativeChatOpenWake(makePaneKey('tab-b', LEAF), 'chat-b', byWorktree)).toBe(false) - expect(takeNativeChatOpenWake(makePaneKey('tab-a', LEAF), 'chat-a', byWorktree)).toBe(true) - // Once per switch: a remount of the same chat does not wake again. - expect(takeNativeChatOpenWake(makePaneKey('tab-a', LEAF), 'chat-a', byWorktree)).toBe(false) - }) - - it('a chat whose tab belongs to no workspace never wakes', () => { - noteUserWorkspaceSwitch('wt-a') - expect(takeNativeChatOpenWake(makePaneKey('tab-x', LEAF), 'chat-x', tabs({}))).toBe(false) - expect(takeNativeChatOpenWake('not-a-pane-key', 'chat-x', tabs({ 'wt-a': ['tab-a'] }))).toBe( - false - ) - }) -}) diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionPickers.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionPickers.tsx index d39bcebf399..6a753a83b16 100644 --- a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionPickers.tsx +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionPickers.tsx @@ -261,8 +261,14 @@ function SessionOptionPopover(props: { onInteractOutside={focusReturn.onInteractOutside} onCloseAutoFocus={focusReturn.onCloseAutoFocus} // Close through a level tooltip’s first Escape; let Radix handle search Escape after IME. + // Escape from a portaled child (the speed list) closes only that child. onKeyDown={(event) => { - if (event.key === 'Escape' && !(event.target instanceof HTMLInputElement)) { + if ( + event.key === 'Escape' && + !(event.target instanceof HTMLInputElement) && + event.target instanceof Node && + event.currentTarget.contains(event.target) + ) { setOpen(false) } }} diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx index 7a78a28dc85..3c46c7fa97c 100644 --- a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionOptionRows.tsx @@ -125,8 +125,10 @@ function OptionRow(props: { ) } - if (descriptor.kind.type === 'boolean' && layout === 'inline' && descriptor.id === 'fastMode') { - return ( + // Every agent's speed is one button: Fast on/off for two modes, a list for more. + const speed = speedButtonTiers(descriptor) + const speedButton = + descriptor.kind.type === 'boolean' && descriptor.id === 'fastMode' ? ( {say('fast')} - ) - } - const speed = speedButtonTiers(descriptor) - if (speed && descriptor.kind.type === 'select') { - const button = ( + ) : speed && descriptor.kind.type === 'select' ? ( - ) + ) : null + if (speedButton) { return layout === 'inline' ? ( - button + speedButton ) : (
- {label} - {button} + {say('speed')} + {speedButton}
) } diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.test.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.test.tsx new file mode 100644 index 00000000000..5bf08723ca7 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.test.tsx @@ -0,0 +1,61 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import { fireEvent, getAllByRole, getByRole } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { NativeChatSessionSpeedButton } from './NativeChatSessionSpeedButton' + +const STANDARD = { value: 'default', label: 'Standard' } +const TIERS = [ + { value: 'priority', label: 'Fast' }, + { value: 'ultrafast', label: 'Ultrafast' } +] + +let unmount: (() => void) | undefined +afterEach(() => { + act(() => unmount?.()) + document.body.innerHTML = '' +}) + +function renderSpeed( + current: string | undefined, + tiers: { value: string; label: string }[] = TIERS +): HTMLElement { + const host = document.body.appendChild(document.createElement('div')) + const root = createRoot(host) + act(() => + root.render( + {}} + /> + ) + ) + unmount = () => root.unmount() + return getByRole(host, 'button') +} + +function checkedTiers(trigger: HTMLElement): string[] { + act(() => { + fireEvent.keyDown(trigger, { key: 'Enter' }) + }) + return getAllByRole(document.body, 'menuitemradio') + .filter((item) => item.getAttribute('aria-checked') === 'true') + .map((item) => item.textContent ?? '') +} + +it('names no tier when the current speed is unknown', () => { + const trigger = renderSpeed(undefined) + expect(trigger.getAttribute('aria-label')).toBe('Speed') + expect(checkedTiers(trigger)).toEqual([]) +}) + +it('opens a list for a lone Flex tier instead of a Fast toggle', () => { + const trigger = renderSpeed('flex', [{ value: 'flex', label: 'flex' }]) + expect(trigger.getAttribute('aria-pressed')).toBeNull() + expect(trigger.getAttribute('aria-label')).toBe('Speed: flex') +}) diff --git a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.tsx b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.tsx index 44922b9bd5f..c4cdcdba29f 100644 --- a/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.tsx +++ b/src/renderer/src/components/native-chat/session/options/controls/NativeChatSessionSpeedButton.tsx @@ -1,5 +1,4 @@ import { ChevronDown, Zap } from 'lucide-react' -import { cn } from '@/lib/utils' import { Toggle, toggleVariants } from '@/components/ui/toggle' import { DropdownMenu, @@ -14,37 +13,41 @@ import type { SessionOptionValue } from '../../../../../../../shared/native-chat/input/native-chat-session-options' import { nativeChatSessionChoiceLabel } from '../../../../../../../shared/native-chat/input/native-chat-session-option-labels' +import { isFastServiceTier } from '../../../../../../../shared/agent-session/options/structured-agent-session-discovered-model' import { sayNativeChatSessionOptionTranslated as say } from './native-chat-session-option-labels-text' const STANDARD_TIER = 'default' -/** Standard plus the faster tiers, or null when the select is not a speed choice with any. */ +/** Standard plus the other tiers, or null when the select is not a speed choice with any. */ export function speedButtonTiers( descriptor: SessionOptionDescriptor -): { standard: SessionOptionSelectChoice; faster: SessionOptionSelectChoice[] } | null { +): { standard: SessionOptionSelectChoice; tiers: SessionOptionSelectChoice[] } | null { if (descriptor.id !== 'serviceTier' || descriptor.kind.type !== 'select') { return null } const standard = descriptor.kind.choices.find((choice) => choice.value === STANDARD_TIER) - const faster = descriptor.kind.choices.filter((choice) => choice.value !== STANDARD_TIER) - return standard && faster.length > 0 ? { standard, faster } : null + const tiers = descriptor.kind.choices.filter((choice) => choice.value !== STANDARD_TIER) + return standard && tiers.length > 0 ? { standard, tiers } : null } -/** One faster tier toggles like Claude's Fast; several open a list instead of a segmented switcher. */ +/** A lone Fast tier toggles like Claude's Fast; anything else opens a list instead of a segmented switcher. */ export function NativeChatSessionSpeedButton(props: { label: string standard: SessionOptionSelectChoice - faster: SessionOptionSelectChoice[] + tiers: SessionOptionSelectChoice[] current: string | undefined disabled: boolean onSet: (value: SessionOptionValue) => void }): React.JSX.Element { - const { label, standard, faster, current, disabled, onSet } = props - const picked = faster.find((choice) => choice.value === current) + const { label, standard, tiers, current, disabled, onSet } = props + const picked = tiers.find((choice) => choice.value === current) + // An unknown tier names no choice, rather than claiming Standard. + const shown = picked ?? (current === standard.value ? standard : undefined) const nameOf = (choice: SessionOptionSelectChoice) => nativeChatSessionChoiceLabel(choice, say, 'serviceTier') - if (faster.length === 1) { - const only = faster[0] + // Only Fast takes the toggle and bolt; Flex and other tiers are picked from the list. + if (tiers.length === 1 && isFastServiceTier(tiers[0])) { + const only = tiers[0] return ( - - {[standard, ...faster].map((choice) => ( + + {[standard, ...tiers].map((choice) => ( {nameOf(choice)} diff --git a/src/renderer/src/components/settings/browser/BrowserHomePageSetting.tsx b/src/renderer/src/components/settings/browser/BrowserHomePageSetting.tsx index 1370c7d45e0..01f798ed994 100644 --- a/src/renderer/src/components/settings/browser/BrowserHomePageSetting.tsx +++ b/src/renderer/src/components/settings/browser/BrowserHomePageSetting.tsx @@ -1,5 +1,6 @@ import { toast } from 'sonner' -import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/constants' +import '../../../../../shared/constants' +import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' import { normalizeBrowserNavigationUrl } from '../../../../../shared/browser-url' import { Button } from '../../ui/button' import { Input } from '../../ui/input' diff --git a/src/renderer/src/components/settings/browser/profiles/BrowserProfileRow.tsx b/src/renderer/src/components/settings/browser/profiles/BrowserProfileRow.tsx index ff5cf922182..48356ca3a75 100644 --- a/src/renderer/src/components/settings/browser/profiles/BrowserProfileRow.tsx +++ b/src/renderer/src/components/settings/browser/profiles/BrowserProfileRow.tsx @@ -20,7 +20,8 @@ import { import { BrowserCookieImportDisclosure } from '../../../BrowserCookieImportDisclosure' import { BrowserCookieImportMachineNotice } from '../../../BrowserCookieImportMachineNotice' import { useAppStore } from '../../../../store/index' -import { BROWSER_FAMILY_LABELS } from '../../../../../../shared/constants' +import '../../../../../../shared/constants' +import { BROWSER_FAMILY_LABELS } from '../../../../../../shared/browser/browser-family-labels' import { useTranslate } from '@/i18n/use-translate' import { browserCookieImportFailureText } from '@/lib/browser/cookies/browser-cookie-import-error-copy' diff --git a/src/renderer/src/components/settings/browser/use/BrowserUsePane.tsx b/src/renderer/src/components/settings/browser/use/BrowserUsePane.tsx index cdfb200b9a4..9f841ad6936 100644 --- a/src/renderer/src/components/settings/browser/use/BrowserUsePane.tsx +++ b/src/renderer/src/components/settings/browser/use/BrowserUsePane.tsx @@ -8,7 +8,8 @@ import { import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { cn } from '@/lib/utils' import { useAppStore } from '../../../../store/index' -import { BROWSER_FAMILY_LABELS } from '../../../../../../shared/constants' +import '../../../../../../shared/constants' +import { BROWSER_FAMILY_LABELS } from '../../../../../../shared/browser/browser-family-labels' import { SearchableSetting } from '../../section-layout/SearchableSetting' import { matchesSettingsSearch } from '../../search/settings-search' import { getBrowserUsePaneSearchEntries } from './browser-use-search' diff --git a/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx new file mode 100644 index 00000000000..ade3681d1b0 --- /dev/null +++ b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.test.tsx @@ -0,0 +1,36 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { SetupScriptCodeBlock } from './SetupScriptCodeBlock' + +afterEach(cleanup) + +function script(lines: number): string { + return Array.from({ length: lines }, (_, index) => `echo step-${index + 1}`).join('\n') +} + +it('collapses a long script and toggles it open and closed', () => { + render() + const code = screen.getByLabelText('Setup script') + expect(code).toHaveTextContent('echo step-40') + + const toggle = screen.getByRole('button', { name: 'Show 35 more lines' }) + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(toggle).toHaveAttribute('aria-controls', code.id) + + fireEvent.click(toggle) + expect(toggle).toHaveAttribute('aria-expanded', 'true') + + code.scrollTop = 200 + fireEvent.click(toggle) + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(code.scrollTop).toBe(0) +}) + +it('shows a short script in full with no toggle', () => { + render() + expect(screen.getByLabelText('Setup script')).toHaveTextContent('echo step-5') + expect(screen.queryByRole('button')).toBeNull() +}) diff --git a/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx new file mode 100644 index 00000000000..5b56439d5a8 --- /dev/null +++ b/src/renderer/src/components/sidebar/SetupScriptCodeBlock.tsx @@ -0,0 +1,98 @@ +import React, { useId, useMemo, useRef, useState } from 'react' +import { ChevronDown } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { useTranslate } from '@/i18n/use-translate' +import { countScriptLines } from '@/lib/script-textarea-rows' + +export const SETUP_SCRIPT_COLLAPSED_LINES = 5 +const LINE_HEIGHT_PX = 20 +// py-1.5 plus room for a horizontal scrollbar, so the last line is never clipped. +const BLOCK_PADDING_PX = 20 + +export function SetupScriptCodeBlock({ + heading, + script +}: { + heading: string + script: string +}): React.JSX.Element { + const t = useTranslate() + const contentId = useId() + const lineCount = useMemo(() => countScriptLines(script), [script]) + const collapsible = lineCount > SETUP_SCRIPT_COLLAPSED_LINES + const [expanded, setExpanded] = useState(false) + const collapsed = collapsible && !expanded + const preRef = useRef(null) + + const toggleExpanded = (): void => { + if (expanded && preRef.current) { + // Collapsing keeps the scroll offset, so reset it to show the script's first lines. + preRef.current.scrollTop = 0 + } + setExpanded(!expanded) + } + + return ( +
+

+ {heading} +

+
+ {/* An exact target height keeps the max-height transition in step with the content; long scripts scroll inside 40vh so two blocks still fit. */} +
+          {script}
+        
+ {collapsed ? ( +
+ ) : null} +
+ {collapsible ? ( +
+ +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx index aeefe981a94..841eac011d4 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx @@ -238,24 +238,13 @@ function SetupScriptPromptCard(): React.JSX.Element | null { } if (mountedRef.current) { setPromptState((current) => markSetupScriptPromptSaved(current, importedRepoHostIdentity)) - const skippedCount = candidate.unsupportedFields?.length ?? 0 + // Skipped fields were listed in the review dialog before saving; the toast only confirms. showSavedInProjectSettingsToast({ onOpenSettings: () => openLocalCommandSettings(importedRepoId, importedHostId), - description: - skippedCount > 0 - ? translate( - 'auto.components.sidebar.SetupScriptPromptCard.savedWithSkippedFields', - '{{count}} unsupported fields skipped. Saved the setup command.', - { - count: skippedCount, - defaultValue_one: - '{{count}} unsupported field skipped. Saved the setup command.' - } - ) - : translate( - 'auto.components.sidebar.SetupScriptPromptCard.savedSetupCommand', - 'Saved the setup command.' - ) + description: translate( + 'auto.components.sidebar.SetupScriptPromptCard.savedSetupCommand', + 'Saved the setup command.' + ) }) } } catch (error) { diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx index 95ca136860f..c61e94e88f0 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.fixture.tsx @@ -3,18 +3,20 @@ import { SetupScriptPromptCardShell } from './SetupScriptPromptCardShell' const noop = (): void => {} -const longSetup = [ - 'corepack enable', - 'pnpm install --frozen-lockfile --prefer-offline --reporter=append-only --filter "./packages/**" --filter "./apps/web"', - 'cp "$CONDUCTOR_ROOT_PATH/.env.local" .env.local', - 'pnpm --filter @acme/db run migrate:dev -- --skip-seed', - 'pnpm --filter @acme/web run build:icons', - 'docker compose -f infra/docker-compose.dev.yml up -d postgres redis minio', - 'until pg_isready -h localhost -p 5432; do sleep 1; done', - 'pnpm --filter @acme/db run seed -- --profile=small', - 'pnpm --filter @acme/web exec playwright install chromium', - 'echo "Workspace ready on port $CONDUCTOR_PORT"' -].join('\n') +const shortSetup = ['pnpm install', 'cp "$CONDUCTOR_ROOT_PATH/.env.local" .env.local'].join('\n') + +const longSetup = Array.from({ length: 40 }, (_, index) => { + const step = index + 1 + return step % 7 === 0 + ? `docker compose -f infra/docker-compose.dev.yml run --rm --service-ports --name step-${step} toolbox ./scripts/bootstrap.sh --profile=full --skip-seed` + : `pnpm --filter @acme/pkg-${step} run setup` +}).join('\n') + +const hugeSetup = Array.from( + { length: 2000 }, + (_, index) => + `echo "step ${index + 1}" && ./scripts/run-step.sh --index=${index + 1} ${'--flag=value '.repeat(20)}` +).join('\n') const base = { repoBadgeColor: '#7c3aed', @@ -34,6 +36,21 @@ function Frame({ children }: { children: React.ReactNode }): React.JSX.Element { return
{children}
} +function clickButton(frame: HTMLElement | Document, label: string): void { + Array.from(frame.querySelectorAll('button')) + .find((button) => button.textContent?.includes(label)) + ?.click() +} + +async function openReview(frame: HTMLElement): Promise { + clickButton(frame, 'Review setup script') + // A mouse click never shows the auto-focus ring; drop the one a synthetic click leaves. + await new Promise((resolve) => requestAnimationFrame(resolve)) + if (document.activeElement instanceof HTMLElement) { + document.activeElement.blur() + } +} + export const conductor = defineFixture({ width: 303, render: () => ( @@ -41,12 +58,13 @@ export const conductor = defineFixture({ @@ -56,16 +74,74 @@ export const conductor = defineFixture({ export const conductorReview = defineFixture({ ...conductor, width: 720, - interact: async (frame) => { - Array.from(frame.querySelectorAll('button')) - .find((button) => button.textContent?.includes('Review setup script')) - ?.click() - // A mouse click never shows the auto-focus ring; drop the one a synthetic click leaves. - await new Promise((resolve) => requestAnimationFrame(resolve)) - if (document.activeElement instanceof HTMLElement) { - document.activeElement.blur() - } + interact: openReview +}) + +export const devcontainer = defineFixture({ + width: 303, + render: () => ( + + + + ) +}) + +export const devcontainerReview = defineFixture({ + ...devcontainer, + width: 720, + interact: openReview +}) + +async function openReviewExpanded(frame: HTMLElement): Promise { + await openReview(frame) + for (const toggle of document.querySelectorAll( + 'button[aria-expanded="false"][aria-controls]' + )) { + toggle.click() } + await new Promise((resolve) => setTimeout(resolve, 400)) + if (document.activeElement instanceof HTMLElement) { + document.activeElement.blur() + } +} + +export const devcontainerReviewExpanded = defineFixture({ + ...devcontainer, + width: 720, + interact: openReviewExpanded +}) + +// 2,000 long lines in setup and archive: the dialog must stay within the viewport with Save visible. +export const hugeReviewExpanded = defineFixture({ + width: 720, + render: () => ( + + `steps.${index}.uses`) + }} + /> + + ), + interact: openReviewExpanded }) export const packageManager = defineFixture({ @@ -77,7 +153,12 @@ export const packageManager = defineFixture({ isPackageManagerSuggestion candidateSource="package manager (pnpm-lock.yaml)" candidateProvenance="pnpm-lock.yaml" - detectedSetupPreview={{ setup: 'pnpm install', archive: null, editable: true }} + detectedSetupPreview={{ + setup: 'pnpm install', + archive: null, + editable: true, + skippedFields: [] + }} /> ) diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx index 49b588f882d..dbedf0b4257 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCardShell.tsx @@ -3,7 +3,6 @@ import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { ConfigureOnlyAction, DetectedSetupPreview, - DetectedSetupSummary, DismissButton, InspectionErrorActions, PackageManagerActions, @@ -52,6 +51,7 @@ export function SetupScriptPromptCardShell({ const t = useTranslate() const [reviewOpen, setReviewOpen] = useState(false) const showDetected = !isInspectionError && !sharedSetupIgnored && detectedSetupPreview !== null + const isImport = showDetected && !detectedSetupPreview.editable return (

- {t('auto.components.sidebar.SetupScriptPromptCard.ff1e819a11', 'Add a setup script')} + {isImport + ? t( + 'auto.components.sidebar.SetupScriptPromptCard.importTitle', + 'Import setup script' + ) + : t('auto.components.sidebar.SetupScriptPromptCard.ff1e819a11', 'Add a setup script')}

@@ -75,7 +80,7 @@ export function SetupScriptPromptCardShell({ isInspectionError={isInspectionError} sharedSetupIgnored={sharedSetupIgnored} isPackageManagerSuggestion={isPackageManagerSuggestion} - candidateSource={candidateSource} + candidateSource={candidateProvenance ?? candidateSource} />

@@ -85,11 +90,6 @@ export function SetupScriptPromptCardShell({ onSetupChange={onSetupDraftChange} provenance={candidateProvenance} /> - ) : showDetected ? ( - ) : null} {isInspectionError ? ( @@ -108,14 +108,15 @@ export function SetupScriptPromptCardShell({ ) : null}
- {/* Imported scripts are saved verbatim, so saving only happens after the full text is on screen. */} - {showDetected && !detectedSetupPreview.editable ? ( + {/* Imported scripts are saved verbatim, so saving happens from a dialog that can show all of the text. */} + {isImport ? ( void @@ -45,38 +44,7 @@ export type DetectedSetupPreviewProps = { provenance: string | null } -function DetectedSetupSection({ - provenance, - children -}: { - provenance: string | null - children: React.ReactNode -}): React.JSX.Element { - const t = useTranslate() - return ( -
-
- - {t('auto.components.sidebar.SetupScriptPromptCardViews.7275f674cc', 'Detected setup')} -
- {children} - {provenance ? ( -

- {{source}}' - )} - values={{ source: provenance }} - components={{ source: }} - /> -

- ) : null} -
- ) -} - +// Package-manager guesses only: imports are summarized in one line and reviewed in a dialog. export function DetectedSetupPreview({ setup, onSetupChange, @@ -84,7 +52,11 @@ export function DetectedSetupPreview({ }: DetectedSetupPreviewProps): React.JSX.Element { const t = useTranslate() return ( - +
+
+ + {t('auto.components.sidebar.SetupScriptPromptCardViews.7275f674cc', 'Detected setup')} +