mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 10:58:10 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/mobile-folder-create-worktree
# Conflicts: # mobile/src/tasks/worktree-create-retry.test.ts
This commit is contained in:
@@ -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'
|
||||
|
||||
@@ -3,7 +3,6 @@ import original from '../mobile/vitest.config.ts'
|
||||
|
||||
// Keep real process, native, and runtime-specific contracts on Node.
|
||||
const nodeFiles = [
|
||||
'src/components/WorktreeAgentList.runtime-lineage.test.tsx',
|
||||
'scripts/check-tests-typecheck-incremental-cache.test.ts',
|
||||
'src/mock-server-key-pair.test.ts',
|
||||
'src/mobile-release/prepare-android-release-script.test.ts',
|
||||
|
||||
@@ -1,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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`
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -14,12 +14,7 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/
|
||||
|
||||
// Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass
|
||||
// that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks.
|
||||
export const TESTS_OUTSIDE_PROGRAM = new Map([
|
||||
[
|
||||
'src/components/WorktreeAgentList.runtime-lineage.test.tsx',
|
||||
'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks'
|
||||
]
|
||||
])
|
||||
export const TESTS_OUTSIDE_PROGRAM = new Map([])
|
||||
|
||||
// Normalize tsc’s host separators to POSIX baseline paths or Windows reports every entry stale and added.
|
||||
const toPosix = (filePath) => filePath.replaceAll('\\', '/')
|
||||
|
||||
@@ -59,15 +59,6 @@ describe('the @ts-nocheck guard', () => {
|
||||
})
|
||||
|
||||
describe('checked transfers', () => {
|
||||
it('accepts an empty checked cohort while retaining legacy runtime allowances', () => {
|
||||
expect(
|
||||
checkTransfers(
|
||||
{ ok: true, expected: [], programTestFiles: [], failures: [], problems: [] },
|
||||
new Map([['legacy.test.ts', 'Legacy runtime-only: no checked transfer']])
|
||||
)
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a declared checked transfer missing from the configured roots', () => {
|
||||
expect(
|
||||
checkTransfers(
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ConfirmModal } from '../components/ConfirmModal'
|
||||
import { MobileAccountsScreen } from './MobileAccountsScreen'
|
||||
|
||||
const dependencies = vi.hoisted(() => ({
|
||||
back: vi.fn(),
|
||||
loadHosts: vi.fn(),
|
||||
uuid: vi.fn<() => string>(),
|
||||
resetRequest: vi.fn(),
|
||||
selectRequest: vi.fn(),
|
||||
statusCapabilities: vi.fn(),
|
||||
subscriptionListeners: new Array<(payload: unknown) => void>()
|
||||
}))
|
||||
|
||||
vi.mock('react-native', () => ({
|
||||
ActivityIndicator: 'ActivityIndicator',
|
||||
Animated: { View: 'View' },
|
||||
AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) },
|
||||
Platform: { OS: 'ios' },
|
||||
Pressable: 'Pressable',
|
||||
RefreshControl: 'RefreshControl',
|
||||
ScrollView: 'ScrollView',
|
||||
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
|
||||
Text: 'Text',
|
||||
View: 'View'
|
||||
}))
|
||||
|
||||
vi.mock('react-native-safe-area-context', () => ({
|
||||
SafeAreaView: 'SafeAreaView',
|
||||
useSafeAreaInsets: () => ({ bottom: 0, left: 0, right: 0, top: 0 })
|
||||
}))
|
||||
|
||||
vi.mock('expo-router', async () => {
|
||||
const React = await import('react')
|
||||
return {
|
||||
useFocusEffect(effect: () => void | (() => void)): void {
|
||||
React.useEffect(effect, [effect])
|
||||
},
|
||||
useLocalSearchParams: () => ({ hostId: 'host-1' })
|
||||
}
|
||||
})
|
||||
|
||||
// The page's Back: the handoff pops the shell's stack, where expo-router's own `back()` goes nowhere.
|
||||
vi.mock('../navigation/route-handoff', () => ({
|
||||
useRouteHandoff: () => ({ back: dependencies.back })
|
||||
}))
|
||||
|
||||
// The dialogs are read off `ConfirmModal`'s props; the drawer under them needs a native runtime.
|
||||
vi.mock('../components/bottom-drawer/BottomDrawer', () => ({ BottomDrawer: () => null }))
|
||||
|
||||
vi.mock('../platform/random-v4-uuid', () => ({ randomV4Uuid: dependencies.uuid }))
|
||||
|
||||
vi.mock('lucide-react-native', () => ({
|
||||
Check: 'Check',
|
||||
ChevronLeft: 'ChevronLeft',
|
||||
RefreshCw: 'RefreshCw',
|
||||
RotateCcw: 'RotateCcw',
|
||||
User: 'User'
|
||||
}))
|
||||
|
||||
vi.mock('../transport/hosts/host-store', () => ({
|
||||
loadHosts: dependencies.loadHosts,
|
||||
peekHosts: () => null
|
||||
}))
|
||||
|
||||
vi.mock('../transport/connection/host-client-hooks', () => {
|
||||
const client = {
|
||||
sendRequest: async (method: string, params?: unknown, options?: unknown) => {
|
||||
if (method === 'status.get') {
|
||||
return {
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: { capabilities: dependencies.statusCapabilities() },
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
}
|
||||
}
|
||||
if (method === 'accounts.consumeCodexResetCredit') {
|
||||
return dependencies.resetRequest(params, options)
|
||||
}
|
||||
if (
|
||||
method === 'accounts.selectCodex' ||
|
||||
method === 'accounts.selectCodexForTarget' ||
|
||||
method === 'accounts.selectClaude'
|
||||
) {
|
||||
return dependencies.selectRequest(method, params)
|
||||
}
|
||||
if (method === 'accounts.list') {
|
||||
return { id: 'list', ok: true, result: AVAILABLE_SNAPSHOT }
|
||||
}
|
||||
throw new Error(`Unexpected request: ${method}`)
|
||||
},
|
||||
subscribe: (_method: string, _params: unknown, onData: (payload: unknown) => void) => {
|
||||
dependencies.subscriptionListeners.push(onData)
|
||||
onData({ type: 'ready', snapshot: AVAILABLE_SNAPSHOT })
|
||||
return vi.fn()
|
||||
}
|
||||
}
|
||||
return {
|
||||
useForceReconnect: () => null,
|
||||
useHostClient: () => ({ client, state: 'connected' })
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../components/AgentIcons', () => ({
|
||||
ClaudeIcon: 'ClaudeIcon',
|
||||
OpenAIIcon: 'OpenAIIcon'
|
||||
}))
|
||||
|
||||
const AVAILABLE_SNAPSHOT = {
|
||||
claude: { accounts: [], activeAccountId: null },
|
||||
codex: {
|
||||
accounts: [
|
||||
{
|
||||
id: 'codex-1',
|
||||
email: 'dev@example.com',
|
||||
managedHomeRuntime: 'host',
|
||||
wslDistro: null,
|
||||
updatedAt: 10
|
||||
}
|
||||
],
|
||||
activeAccountId: 'codex-1',
|
||||
activeAccountIdsByRuntime: { host: 'codex-1', wsl: {} }
|
||||
},
|
||||
rateLimits: {
|
||||
claude: null,
|
||||
codex: {
|
||||
provider: 'codex',
|
||||
session: {
|
||||
usedPercent: 100,
|
||||
windowMinutes: 300,
|
||||
resetsAt: 2_000_000_000_000,
|
||||
resetDescription: null
|
||||
},
|
||||
weekly: null,
|
||||
rateLimitResetCredits: { availableCount: 1, nextExpiresAt: null },
|
||||
updatedAt: 100,
|
||||
error: null,
|
||||
status: 'ok'
|
||||
},
|
||||
claudeTarget: { runtime: 'host', wslDistro: null },
|
||||
codexTarget: { runtime: 'host', wslDistro: null },
|
||||
inactiveClaudeAccounts: [],
|
||||
inactiveCodexAccounts: []
|
||||
}
|
||||
} as const
|
||||
|
||||
const RESET_SNAPSHOT = {
|
||||
...AVAILABLE_SNAPSHOT,
|
||||
rateLimits: {
|
||||
...AVAILABLE_SNAPSHOT.rateLimits,
|
||||
codex: {
|
||||
...AVAILABLE_SNAPSHOT.rateLimits.codex,
|
||||
session: { ...AVAILABLE_SNAPSHOT.rateLimits.codex.session, usedPercent: 0 },
|
||||
rateLimitResetCredits: { availableCount: 0, nextExpiresAt: null },
|
||||
updatedAt: 101
|
||||
}
|
||||
}
|
||||
} as const
|
||||
|
||||
async function renderAccountsRoute(): Promise<ReactTestRenderer> {
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
await act(async () => {
|
||||
renderer = create(createElement(MobileAccountsScreen))
|
||||
await Promise.resolve()
|
||||
})
|
||||
if (!renderer) {
|
||||
throw new Error('Accounts route did not render')
|
||||
}
|
||||
return renderer
|
||||
}
|
||||
|
||||
/** Host components are strings under the mock above, so they are found by what they carry. */
|
||||
function pressables(renderer: ReactTestRenderer, label: string) {
|
||||
return renderer.root.findAll(
|
||||
(node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === label
|
||||
)
|
||||
}
|
||||
|
||||
function resetButtons(renderer: ReactTestRenderer) {
|
||||
return pressables(renderer, 'Use Codex rate-limit reset')
|
||||
}
|
||||
|
||||
async function findResetButton(renderer: ReactTestRenderer) {
|
||||
await vi.waitFor(() => expect(resetButtons(renderer)).toHaveLength(1))
|
||||
return resetButtons(renderer)[0]!
|
||||
}
|
||||
|
||||
/** The open dialog, read off `ConfirmModal` the way a user reads the drawer. */
|
||||
function openDialog(renderer: ReactTestRenderer) {
|
||||
const open = renderer.root
|
||||
.findAllByType(ConfirmModal)
|
||||
.map((node) => node.props)
|
||||
.filter((props) => props.visible)
|
||||
if (open.length > 1) {
|
||||
throw new Error(`expected at most one open dialog, found ${open.length}`)
|
||||
}
|
||||
return open[0] ?? null
|
||||
}
|
||||
|
||||
/** Presses the dialog's confirm button, which closes it after its action as `ConfirmContent` does. */
|
||||
|
||||
const KEY = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
describe('accounts route Codex reset credit', () => {
|
||||
beforeEach(() => {
|
||||
dependencies.loadHosts.mockReset().mockResolvedValue([
|
||||
{
|
||||
id: 'host-1',
|
||||
name: 'Desk',
|
||||
endpoint: 'ws://127.0.0.1:6768',
|
||||
deviceToken: 'token',
|
||||
publicKeyB64: 'public-key',
|
||||
lastConnected: 1
|
||||
}
|
||||
])
|
||||
dependencies.uuid.mockReset().mockReturnValue(KEY)
|
||||
dependencies.back.mockReset()
|
||||
dependencies.statusCapabilities.mockReset().mockReturnValue(['accounts.codex-reset-credit.v1'])
|
||||
dependencies.resetRequest.mockReset().mockImplementation((params) => ({
|
||||
id: 'reset',
|
||||
ok: true,
|
||||
result: {
|
||||
outcome: 'reset',
|
||||
scope: (params as { expectedScope: unknown }).expectedScope,
|
||||
snapshot: RESET_SNAPSHOT
|
||||
},
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
}))
|
||||
dependencies.selectRequest.mockReset().mockResolvedValue({
|
||||
id: 'select',
|
||||
ok: true,
|
||||
result: AVAILABLE_SNAPSHOT.codex
|
||||
})
|
||||
dependencies.subscriptionListeners.length = 0
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('sends nothing when the confirmation is cancelled', async () => {
|
||||
const renderer = await renderAccountsRoute()
|
||||
const button = await findResetButton(renderer)
|
||||
await act(async () => button.props.onPress())
|
||||
act(() => openDialog(renderer)?.onCancel())
|
||||
|
||||
expect(openDialog(renderer)).toBeNull()
|
||||
expect(dependencies.resetRequest).not.toHaveBeenCalled()
|
||||
act(() => renderer.unmount())
|
||||
})
|
||||
})
|
||||
@@ -1,26 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
deriveMobileAiVaultScopePaths,
|
||||
mobileAiVaultScanScopeArgs
|
||||
} from './agent-history-scope-paths'
|
||||
|
||||
const worktree = (worktreeId: string, path: string) => ({ worktreeId, path, repoId: 'repo-1' })
|
||||
|
||||
describe('mobile AI Vault scope paths', () => {
|
||||
const active = worktree('w1', '/Users/ada/repo/app')
|
||||
const siblings = Array.from({ length: 200 }, (_, index) =>
|
||||
worktree(`w-sib-${index}`, `/Users/ada/repo/app-${index}`)
|
||||
)
|
||||
|
||||
it('caps only the scan hints, so an older host accepts them and Project still shows every sibling', () => {
|
||||
const scopePaths = deriveMobileAiVaultScopePaths('project', active, [active, ...siblings])
|
||||
const scan = mobileAiVaultScanScopeArgs('project', scopePaths)
|
||||
|
||||
expect(scopePaths).toHaveLength(201)
|
||||
expect(scan.scopePaths).toHaveLength(64)
|
||||
// Active worktree is seeded first, so it survives truncation.
|
||||
expect(scan.scopePaths?.[0]).toBe('/Users/ada/repo/app')
|
||||
// A capped scope can't answer alone, so the host keeps its recency scan.
|
||||
expect(scan.scopeOnly).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
|
||||
@@ -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\n\n 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'])
|
||||
})
|
||||
@@ -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: <T,>(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()
|
||||
}
|
||||
})
|
||||
@@ -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="<b>Q1</b> & Q2"}')
|
||||
expect(directives).toEqual([{ file: 'a.html', title: '<b>Q1</b> & 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' }
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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>): 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')
|
||||
})
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -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<HTMLDivElement>(null)
|
||||
const boundaryRefs = useRef<unknown[]>([])
|
||||
const openerRef = useRef<HTMLButtonElement>(null)
|
||||
const backRef = useRef<HTMLButtonElement>(null)
|
||||
useDetailCardScope({ active, obscured, openerRef, backRef, contentRef, boundaryRefs, dismiss })
|
||||
return (
|
||||
<>
|
||||
<input id="terminal" />
|
||||
<button ref={backRef} id="back">
|
||||
Back
|
||||
</button>
|
||||
<DetailCardFocusBoundary refs={boundaryRefs} index={0} active={active} />
|
||||
<button ref={openerRef} id="opener">
|
||||
Title
|
||||
</button>
|
||||
<DetailCardFocusBoundary refs={boundaryRefs} index={1} active={active} />
|
||||
<button id="files" onClick={action}>
|
||||
Files
|
||||
</button>
|
||||
<DetailCardLayer>
|
||||
<DetailCardFocusBoundary refs={boundaryRefs} index={2} active={active} />
|
||||
<div ref={contentRef} id="card" tabIndex={-1} aria-hidden={!active}>
|
||||
<div id="scroll" tabIndex={active ? 0 : -1}>
|
||||
Details
|
||||
</div>
|
||||
</div>
|
||||
<DetailCardFocusBoundary refs={boundaryRefs} index={3} active={active} />
|
||||
</DetailCardLayer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
const render = (active: boolean, obscured = false) =>
|
||||
act(() =>
|
||||
renderer.render(
|
||||
<DetailCardHostProvider>
|
||||
<Scope active={active} obscured={obscured} />
|
||||
</DetailCardHostProvider>
|
||||
)
|
||||
)
|
||||
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(<Scope obscured={false} />))
|
||||
expect(contact(contentRef.current, 'pointerdown', 1)).toBe(true)
|
||||
act(() => renderer.render(<Scope obscured />))
|
||||
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()
|
||||
}
|
||||
})
|
||||
@@ -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<readonly ConnectionLogEntry[]>>()
|
||||
|
||||
@@ -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<void>((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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<string, string>()
|
||||
@@ -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')
|
||||
|
||||
@@ -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<typeof HostReachability>()),
|
||||
testHostReachability: async () => true
|
||||
}))
|
||||
|
||||
import { useTroubleshootDiagnostics } from './use-troubleshoot-diagnostics'
|
||||
|
||||
let tree: ReactTestRenderer | undefined
|
||||
const state: { current: ReturnType<typeof useTroubleshootDiagnostics> | 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'])
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
)
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<boolean>()
|
||||
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<string>()
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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 })
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -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[] = []
|
||||
|
||||
@@ -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<RpcClient['sendRequest']>().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()
|
||||
})
|
||||
})
|
||||
@@ -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<void>()
|
||||
const applied: string[] = []
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
|
||||
-98
@@ -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]
|
||||
|
||||
-231
@@ -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])
|
||||
}
|
||||
}
|
||||
@@ -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 <selector>` 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:<repoId> --json` lists the
|
||||
recipes `--recipe` accepts. `ORCA worktree create --name task --recipe <id> --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:<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
|
||||
|
||||
@@ -36,7 +36,8 @@ ORCA orchestration worker-start --spec "<task>" --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 <short-name>`
|
||||
nests it under yours. For one with no parent, use
|
||||
`--worktree new-top-level --repo id:<repoId> --name <short-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
|
||||
|
||||
@@ -17,11 +17,11 @@ when requesting a child of the current workspace.
|
||||
# Child of the current worktree.
|
||||
ORCA orchestration worker-start --task <task_id> --worktree new-child --agent codex --setup run
|
||||
|
||||
# On a connected server; the Run stays on yours.
|
||||
ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
|
||||
# On a connected server, nested under your workspace; the Run stays on yours.
|
||||
ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
|
||||
|
||||
# On a connected server, nested under your workspace in the sidebar.
|
||||
ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
|
||||
# On a connected server, with no parent.
|
||||
ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run
|
||||
```
|
||||
|
||||
With `--on`, both `new-child` and `new-top-level` need `--repo` naming a
|
||||
|
||||
@@ -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 <selector>` 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:<repoId> --json` lists the",
|
||||
"recipes `--recipe` accepts. `ORCA worktree create --name task --recipe <id> --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:<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 <short-name>`",
|
||||
" nests it under yours. For one with no parent, use",
|
||||
" `--worktree new-top-level --repo id:<repoId> --name <short-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 <task_id> --worktree new-child --agent codex --setup run",
|
||||
"",
|
||||
"# On a connected server; the Run stays on yours.",
|
||||
"ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
|
||||
"# On a connected server, nested under your workspace; the Run stays on yours.",
|
||||
"ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
|
||||
"",
|
||||
"# On a connected server, nested under your workspace in the sidebar.",
|
||||
"ORCA orchestration worker-start --task <task_id> --on <environment> --worktree new-child --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
|
||||
"# On a connected server, with no parent.",
|
||||
"ORCA orchestration worker-start --task <task_id> --on <server> --worktree new-top-level --repo <exact_remote_repo_selector> --name <name> --agent codex --setup run",
|
||||
"```",
|
||||
"",
|
||||
"With `--on`, both `new-child` and `new-top-level` need `--repo` naming a",
|
||||
|
||||
@@ -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<void>, ms: number): Promise<boolean
|
||||
]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
function killProbeRoot(child: ChildProcessHandle, signal?: NodeJS.Signals): void {
|
||||
function killProbeRoot(child: ChildProcess, signal?: NodeJS.Signals): void {
|
||||
try {
|
||||
child.kill(signal)
|
||||
} catch {
|
||||
|
||||
@@ -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<string, CommandHandler> = {
|
||||
'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)
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
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<RuntimeStatus>('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<string, string | boolean>
|
||||
create: Record<string, unknown>
|
||||
recipeId: string
|
||||
launch?: CliAgentLaunch
|
||||
json: boolean
|
||||
}): Promise<void> {
|
||||
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<RecipeWorktreeCreateResult>
|
||||
try {
|
||||
created = await client.call<RecipeWorktreeCreateResult>(
|
||||
'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
|
||||
}
|
||||
}
|
||||
@@ -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<string, string | boolean>
|
||||
): 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)
|
||||
}
|
||||
@@ -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<string, string | boolean>): 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<string, CommandHandler> = {
|
||||
'worktree ps': async ({ flags, client, json }) => {
|
||||
const result = await client.call<WithAnnotatedHostScope<RuntimeWorktreePsResult>>(
|
||||
@@ -105,7 +118,6 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
|
||||
},
|
||||
'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<string, CommandHandler> = {
|
||||
// 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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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:',
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<number> {
|
||||
export function waitForRecipeJson(child: ChildProcess): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = ''
|
||||
let settled = false
|
||||
|
||||
@@ -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<number> {
|
||||
@@ -129,7 +130,7 @@ export async function superviseForegroundServe(
|
||||
}
|
||||
|
||||
function waitForForegroundChild(
|
||||
child: ChildProcessHandle,
|
||||
child: ChildProcess,
|
||||
expected: { handoffPath: string; handoff: InstallRequestedHandoff } | null
|
||||
): Promise<{
|
||||
code: number | null
|
||||
|
||||
@@ -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<void>((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)
|
||||
|
||||
@@ -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<TResult>(
|
||||
options: {
|
||||
classifySocketError?: (error: Error) => RuntimeClientError | null
|
||||
requestSelection?: RuntimeRequestSelection
|
||||
onProgress?: (progress: RuntimeRpcProgress) => void
|
||||
} = {}
|
||||
): Promise<RuntimeRpcResponse<TResult>> {
|
||||
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<TResult>(
|
||||
// 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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+1
-13
@@ -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 <selector>] [--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 <recipe-id>` for details.'
|
||||
],
|
||||
examples: ['orca vm recipe list', 'orca vm recipe list --repo id:<repoId> --json']
|
||||
},
|
||||
{
|
||||
path: ['vm', 'recipe', 'doctor'],
|
||||
summary: 'Validate a per-workspace environment recipe without provisioning by default',
|
||||
|
||||
@@ -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 <name> [--repo <selector>|--project <id-or-name> [--host <host>]|--project-host-setup <id>] [--recipe <recipe-id>] [--agent <id>] [--prompt <text>] [--model <id>] [--effort <level>] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch <ref>] [--branch <name>] [--reference <url-or-jira-key>...] [--reference-site <id>] [--issue <number>] [--pr <number>] [--linear-issue <identifier-or-url>] [--gitlab-issue <number-or-url>] [--gitlab-mr <number-or-url>] [--comment <text>] [--parent-worktree <selector> [--parent-environment <environment>]] [--no-parent] [--run-hooks] [--activate] [--retry-launch <operationId>] [--json]',
|
||||
'orca worktree create --name <name> [--repo <selector>|--project <id-or-name> [--host <host>]|--project-host-setup <id>] [--agent <id>] [--prompt <text>] [--model <id>] [--effort <level>] [--surface chat|terminal] [--setup run|skip|inherit] [--base-branch <ref>] [--branch <name>] [--reference <url-or-jira-key>...] [--reference-site <id>] [--issue <number>] [--pr <number>] [--linear-issue <identifier-or-url>] [--gitlab-issue <number-or-url>] [--gitlab-mr <number-or-url>] [--comment <text>] [--parent-worktree <selector> [--parent-environment <environment>]] [--no-parent] [--run-hooks] [--activate] [--retry-launch <operationId>] [--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 <recipe-id> 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:<repoId> --name folder-child --parent-worktree folder:<folderId> --json',
|
||||
'orca worktree create --repo id:<repoId> --name related-task --parent-worktree active --json',
|
||||
'orca worktree create --environment <environment-id> --repo id:<repoId> --name child --parent-environment local --parent-worktree folder:<folderId> --json',
|
||||
'orca worktree create --repo id:<repoId> --name independent-task --no-parent --json',
|
||||
'orca worktree create --repo id:<repoId> --name sandboxed-task --recipe cloud-sandbox --agent codex --prompt "hi" --json'
|
||||
'orca worktree create --repo id:<repoId> --name independent-task --no-parent --json'
|
||||
]
|
||||
}
|
||||
|
||||
@@ -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<void>
|
||||
connect: (transport: MultiplexerTransport, child: ChildProcessWithoutNullStreams) => Promise<void>
|
||||
}): Promise<void> {
|
||||
const { distro, env, bundleJsPath, version, io } = options
|
||||
let installTried = false
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
+3
-3
@@ -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<unknown>
|
||||
}[] = []
|
||||
@@ -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<unknown> = Promise.resolve()
|
||||
|
||||
+2
-2
@@ -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 {
|
||||
|
||||
+6
-5
@@ -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<PipedChildProcess, () => void>()
|
||||
const liveHosts = new Map<ChildProcessWithoutNullStreams, () => 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<NativeHostConnection> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let child: PipedChildProcess
|
||||
let child: ChildProcessWithoutNullStreams
|
||||
const supervised = process.platform === 'win32'
|
||||
try {
|
||||
child = spawn(
|
||||
|
||||
+2
-1
@@ -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'
|
||||
|
||||
+2
-1
@@ -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'
|
||||
|
||||
+2
-1
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
+2
-1
@@ -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 = {
|
||||
|
||||
@@ -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 }>
|
||||
|
||||
@@ -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<void>
|
||||
isValid: () => boolean
|
||||
close: () => void | Promise<void>
|
||||
}
|
||||
|
||||
export type BrowserNetworkExecutionRouteContext = {
|
||||
executionHost: BrowserNetworkExecutionHost
|
||||
runtimeId: string
|
||||
runtimeRevision: number
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export type BrowserNetworkExecutionRouteResolver = (
|
||||
context: BrowserNetworkExecutionRouteContext
|
||||
) => Promise<BrowserNetworkExecutionRoute>
|
||||
+2
-4
@@ -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 (
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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<void>
|
||||
isValid: () => boolean
|
||||
close: () => void | Promise<void>
|
||||
}
|
||||
|
||||
export type BrowserNetworkExecutionRouteContext = {
|
||||
executionHost: BrowserNetworkExecutionHost
|
||||
runtimeId: string
|
||||
runtimeRevision: number
|
||||
signal?: AbortSignal
|
||||
}
|
||||
|
||||
export type BrowserNetworkExecutionRouteResolver = (
|
||||
context: BrowserNetworkExecutionRouteContext
|
||||
) => Promise<BrowserNetworkExecutionRoute>
|
||||
|
||||
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<Socket> {
|
||||
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<string, string | undefined> = process.env
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -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<WslBrowserNetworkRelayChild>
|
||||
|
||||
@@ -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<Socket> {
|
||||
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)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
+1
@@ -106,6 +106,7 @@ describe('installBrowserSessionPartitionPolicies proxy wiring', () => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
setBrowserNetworkProxySettingsResolver(null)
|
||||
vi.unstubAllEnvs()
|
||||
identityState.unavailable = false
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<string> {
|
||||
function firstStdoutLine(child: ChildProcessWithoutNullStreams): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
child.stdout.setEncoding('utf8').once('data', (chunk: string) => resolve(chunk.trim()))
|
||||
})
|
||||
|
||||
@@ -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<DescendantTreeVerdict, number> = {
|
||||
exited: 2
|
||||
}
|
||||
|
||||
type ReapableChild = Pick<SpawnedProcess, 'pid' | 'kill'>
|
||||
type ReapableChild = Pick<ChildProcess, 'pid' | 'kill'>
|
||||
|
||||
// A missing or exited root may have reparented descendants; its walk cannot prove an empty tree.
|
||||
function admissibleTree(
|
||||
|
||||
@@ -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<string, string | undefined>): Record<string, str
|
||||
|
||||
/** Subscribes alongside the SDK's reader: an earlier listener would drain output it never sees. */
|
||||
function observeStdoutWithReader(
|
||||
stdout: PipedChildProcess['stdout'],
|
||||
stdout: ChildProcessWithoutNullStreams['stdout'],
|
||||
onStdout: (chunk: Buffer | string) => void
|
||||
): void {
|
||||
const onSubscribe = (event: string | symbol): void => {
|
||||
|
||||
@@ -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<SpawnedProcess, 'pid' | 'kill' | 'stdin'> & { kill: ReturnType<typeof vi.fn> } {
|
||||
Pick<ChildProcess, 'pid' | 'kill' | 'stdin'> & { kill: ReturnType<typeof vi.fn> } {
|
||||
return Object.assign(new EventEmitter(), {
|
||||
pid: ROOT_PID,
|
||||
stdin: new PassThrough(),
|
||||
|
||||
@@ -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<object, ManagedProviderProcess>()
|
||||
|
||||
/** `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)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { SpawnedProcess } from '@orca/process-host/process-spec'
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
|
||||
type RootTerminationInput = {
|
||||
child: Pick<SpawnedProcess, 'kill'>
|
||||
child: Pick<ChildProcess, 'kill'>
|
||||
exited: () => boolean
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user