mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 03:45:08 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/hosts-popover-minimal
# Conflicts: # src/renderer/src/i18n/locales/de.json # src/renderer/src/i18n/locales/en.json # src/renderer/src/i18n/locales/es.json # src/renderer/src/i18n/locales/fr.json # src/renderer/src/i18n/locales/ja.json # src/renderer/src/i18n/locales/ko.json # src/renderer/src/i18n/locales/pt.json # src/renderer/src/i18n/locales/ru.json # src/renderer/src/i18n/locales/tr.json # src/renderer/src/i18n/locales/zh-Hant.json # src/renderer/src/i18n/locales/zh.json
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'
|
||||
|
||||
@@ -12,6 +12,9 @@ export const CLI_MAIN_ENTRY_NAMES = [
|
||||
'orcad/orcad-stale-lock-reclaim',
|
||||
'orcad/orcad-host-identity-reset',
|
||||
'plugins/plugin-authoring-checks',
|
||||
// `orca vm env doctor` runs its checks in the CLI process.
|
||||
'environment-doctor/environment-doctor',
|
||||
'environment-doctor/environment-doctor-host',
|
||||
...[
|
||||
'access',
|
||||
'active-location',
|
||||
|
||||
@@ -359,6 +359,8 @@ module.exports = {
|
||||
'out/main/orca-profiles/profile-index-store.js',
|
||||
'out/main/persistence/profile-state/**',
|
||||
'out/main/plugins/plugin-authoring-checks.js',
|
||||
'out/main/environment-doctor/environment-doctor.js',
|
||||
'out/main/environment-doctor/environment-doctor-host.js',
|
||||
// `orca plugin test` and `orca plugin check` load the runtime, kit and hooks in Node.
|
||||
'resources/plugins/declarative/*.mjs',
|
||||
'out/main/skills/bundled-skill-install/bundled-skill-local-host.js',
|
||||
|
||||
@@ -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'])
|
||||
})
|
||||
})
|
||||
@@ -32,6 +32,8 @@ export const dictationSetupSchema = z.looseObject({
|
||||
enabled: salvagedOptional('enabled', z.boolean()),
|
||||
selectedModelId: salvagedOptional('selectedModelId', z.string()),
|
||||
dictationMode: salvagedOptional('dictationMode', z.string()),
|
||||
// Absent from older hosts, which remove no fillers either; the phone then keeps them on, the host default.
|
||||
removeFillerWords: salvagedOptional('removeFillerWords', z.boolean()),
|
||||
models: salvagingArray(speechModelSchema)
|
||||
})
|
||||
|
||||
|
||||
@@ -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'
|
||||
)
|
||||
})
|
||||
@@ -11,6 +11,8 @@ export type UseMobileDictationOptions = {
|
||||
enabled: boolean
|
||||
onTranscript: (text: string) => void
|
||||
onError?: (error: Error) => void
|
||||
// The computer's filler switch, for text the phone recognizes itself; unknown means on.
|
||||
removeFillerWords?: boolean
|
||||
}
|
||||
|
||||
export type UseMobileDictationResult = {
|
||||
|
||||
@@ -33,10 +33,10 @@ export type { UseMobileDictationResult } from './mobile-dictation-session-state'
|
||||
|
||||
export function useMobileDictation(options: UseMobileDictationOptions): UseMobileDictationResult {
|
||||
useMobileTranslation()
|
||||
const { client, enabled, onTranscript, onError } = options
|
||||
const { client, enabled, onTranscript, onError, removeFillerWords } = options
|
||||
// Both capture seams hold the screen while the microphone is open; native uses the device directly and page uses shell audio verbs.
|
||||
const capture = useDictationCapture()
|
||||
const speech = useOnDeviceSpeech()
|
||||
const speech = useOnDeviceSpeech(removeFillerWords)
|
||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [transcriptSoFar, setTranscriptSoFar, keptTranscript] = useMobileDictationTranscriptSoFar()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { OnDeviceSpeech } from './on-device-speech-contract'
|
||||
|
||||
// The session screen is a page in the shell (on-device-speech.web.ts); native screens dictate through the computer.
|
||||
export function useOnDeviceSpeech(): OnDeviceSpeech | null {
|
||||
export function useOnDeviceSpeech(_removeFillerWords?: boolean): OnDeviceSpeech | null {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Text the phone recognizes itself gets the computer's filler removal, in the language the recognizer started in.
|
||||
import { createElement } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { OnDeviceSpeech } from './on-device-speech-contract'
|
||||
|
||||
vi.mock('../mobile-web-shell/bridge/use-native-verbs', () => {
|
||||
const verbs = {
|
||||
canRecognizeSpeech: true,
|
||||
speechStatus: async () => ({ status: 'ready', locale: 'de-DE', preference: 'automatic' }),
|
||||
speechStart: async () => ({ started: true, locale: 'de-DE', reason: null }),
|
||||
speechRead: async () => ({
|
||||
revision: 1,
|
||||
committed: 'Äh, das ist um fünf Uhr.',
|
||||
tentative: 'ähm',
|
||||
failure: null
|
||||
}),
|
||||
speechFinish: async () => ({
|
||||
text: 'Äh, das ist, ähm, um fünf Uhr fertig.',
|
||||
failure: null
|
||||
}),
|
||||
speechCancel: async () => ({})
|
||||
}
|
||||
return { useNativeVerbs: () => verbs }
|
||||
})
|
||||
|
||||
vi.mock('./on-device-speech-locale', () => ({ onDeviceSpeechLocale: () => 'de-DE' }))
|
||||
|
||||
import { useOnDeviceSpeech } from './on-device-speech.web'
|
||||
|
||||
function mountSpeech(removeFillerWords: boolean): OnDeviceSpeech {
|
||||
let speech: OnDeviceSpeech | null = null
|
||||
function Probe(): null {
|
||||
speech = useOnDeviceSpeech(removeFillerWords)
|
||||
return null
|
||||
}
|
||||
act(() => {
|
||||
create(createElement(Probe))
|
||||
})
|
||||
if (speech === null) {
|
||||
throw new Error('no on-device speech')
|
||||
}
|
||||
return speech
|
||||
}
|
||||
|
||||
describe('on-device dictation text', () => {
|
||||
it('drops the fillers of the language the recognizer started in', async () => {
|
||||
const speech = mountSpeech(true)
|
||||
await speech.start()
|
||||
|
||||
expect(await speech.read()).toMatchObject({ committed: 'Das ist um fünf Uhr.', tentative: '' })
|
||||
expect(await speech.finish()).toEqual({
|
||||
text: 'Das ist um fünf Uhr fertig.',
|
||||
failure: null
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps every word when the computer turned filler removal off', async () => {
|
||||
const speech = mountSpeech(false)
|
||||
await speech.start()
|
||||
|
||||
expect(await speech.finish()).toEqual({
|
||||
text: 'Äh, das ist, ähm, um fünf Uhr fertig.',
|
||||
failure: null
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,14 +1,43 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useLayoutEffect, useMemo, useRef } from 'react'
|
||||
import { createDictationTextPipeline } from '../../../src/shared/dictation-text-pipeline'
|
||||
import { useNativeVerbs, type NativeVerbs } from '../mobile-web-shell/bridge/use-native-verbs'
|
||||
import type { OnDeviceSpeech } from './on-device-speech-contract'
|
||||
import { onDeviceSpeechLocale } from './on-device-speech-locale'
|
||||
|
||||
function createPageOnDeviceSpeech(verbs: NativeVerbs): OnDeviceSpeech {
|
||||
const keepText = (text: string): string => text
|
||||
|
||||
// The phone's recognizer transcribes only the locale it started in, so that locale's language picks the fillers, as the host does for its model.
|
||||
function phoneDictationTextCleaner(
|
||||
locale: string | null,
|
||||
removeFillerWords: boolean
|
||||
): (text: string) => string {
|
||||
const language = locale?.split('-')[0].toLowerCase()
|
||||
const clean = createDictationTextPipeline(language ? { language } : undefined, {
|
||||
removeFillerWords
|
||||
})
|
||||
return clean ?? keepText
|
||||
}
|
||||
|
||||
function createPageOnDeviceSpeech(
|
||||
verbs: NativeVerbs,
|
||||
removeFillerWords: () => boolean
|
||||
): OnDeviceSpeech {
|
||||
let clean = keepText
|
||||
return {
|
||||
status: () => verbs.speechStatus(onDeviceSpeechLocale()),
|
||||
start: () => verbs.speechStart(onDeviceSpeechLocale()),
|
||||
read: verbs.speechRead,
|
||||
finish: verbs.speechFinish,
|
||||
start: async () => {
|
||||
const started = await verbs.speechStart(onDeviceSpeechLocale())
|
||||
clean = phoneDictationTextCleaner(started.locale, removeFillerWords())
|
||||
return started
|
||||
},
|
||||
read: async () => {
|
||||
const read = await verbs.speechRead()
|
||||
return { ...read, committed: clean(read.committed), tentative: clean(read.tentative) }
|
||||
},
|
||||
finish: async () => {
|
||||
const finished = await verbs.speechFinish()
|
||||
return finished.text === null ? finished : { ...finished, text: clean(finished.text) }
|
||||
},
|
||||
// Cancel has no reply anyone waits on; a shell that lost the session has nothing to stop.
|
||||
cancel: () => {
|
||||
void verbs.speechCancel().catch(() => undefined)
|
||||
@@ -17,7 +46,18 @@ function createPageOnDeviceSpeech(verbs: NativeVerbs): OnDeviceSpeech {
|
||||
}
|
||||
|
||||
// Null on a shell without the verb, so dictation stays on the computer exactly as before.
|
||||
export function useOnDeviceSpeech(): OnDeviceSpeech | null {
|
||||
// removeFillerWords is the computer's switch, read at each start.
|
||||
export function useOnDeviceSpeech(removeFillerWords = true): OnDeviceSpeech | null {
|
||||
const verbs = useNativeVerbs()
|
||||
return useMemo(() => (verbs.canRecognizeSpeech ? createPageOnDeviceSpeech(verbs) : null), [verbs])
|
||||
const removeFillerWordsRef = useRef(removeFillerWords)
|
||||
useLayoutEffect(() => {
|
||||
removeFillerWordsRef.current = removeFillerWords
|
||||
}, [removeFillerWords])
|
||||
return useMemo(
|
||||
() =>
|
||||
verbs.canRecognizeSpeech
|
||||
? createPageOnDeviceSpeech(verbs, () => removeFillerWordsRef.current)
|
||||
: null,
|
||||
[verbs]
|
||||
)
|
||||
}
|
||||
|
||||
+1
-36
@@ -3,14 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send'
|
||||
import type { MobileNativeChatInputLockReason } from '../MobileNativeChatView'
|
||||
import {
|
||||
readMobileNativeChatDraftInputs,
|
||||
updateMobileNativeChatDraftInputs
|
||||
} from './mobile-native-chat-draft-inputs'
|
||||
import {
|
||||
resetMobileNativeChatDraftStoreForTests,
|
||||
setMobileNativeChatDraftText
|
||||
} from './mobile-native-chat-draft-store'
|
||||
import { resetMobileNativeChatDraftStoreForTests } from './mobile-native-chat-draft-store'
|
||||
import {
|
||||
readMobileNativeChatOfflineSends,
|
||||
resetMobileNativeChatOfflineSendsForTests
|
||||
@@ -21,7 +14,6 @@ import {
|
||||
} from './use-mobile-native-chat-offline-sends'
|
||||
|
||||
const SCOPE = 'host\0worktree\0tab'
|
||||
const IMAGE = { id: 'chip-1', path: '/host/shot.png', previewUri: 'file:///shot.png' }
|
||||
|
||||
type Send = (text: string, intent?: MobileNativeChatSendIntent) => Promise<boolean>
|
||||
|
||||
@@ -57,33 +49,6 @@ describe('useMobileNativeChatOfflineQueue', () => {
|
||||
resetMobileNativeChatDraftStoreForTests()
|
||||
})
|
||||
|
||||
it('holds an offline send with its chips and sends it once on reconnect without touching the composer', async () => {
|
||||
const send = vi.fn<Send>().mockResolvedValue(true)
|
||||
await mount('disconnected', send)
|
||||
setMobileNativeChatDraftText(SCOPE, 'check the PR tab')
|
||||
updateMobileNativeChatDraftInputs(SCOPE, (inputs) => ({ ...inputs, images: [IMAGE] }))
|
||||
|
||||
let accepted: boolean | undefined
|
||||
await act(async () => {
|
||||
accepted = await queue?.send('check the PR tab')
|
||||
})
|
||||
|
||||
expect(accepted).toBe(true)
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
expect(readMobileNativeChatDraftInputs(SCOPE).images).toEqual([])
|
||||
expect(readMobileNativeChatOfflineSends(SCOPE).map((queued) => queued.text)).toEqual([
|
||||
'check the PR tab'
|
||||
])
|
||||
|
||||
setMobileNativeChatDraftText(SCOPE, 'a newer draft')
|
||||
await reconnect(send)
|
||||
|
||||
expect(send).toHaveBeenCalledOnce()
|
||||
expect(send.mock.calls[0][0]).toBe('check the PR tab')
|
||||
expect(send.mock.calls[0][1]?.queued?.images).toEqual([IMAGE])
|
||||
expect(readMobileNativeChatOfflineSends(SCOPE)).toEqual([])
|
||||
})
|
||||
|
||||
it('pauses a queued message whose send fails and holds later sends behind it until Resume', async () => {
|
||||
const send = vi.fn<Send>().mockResolvedValue(false)
|
||||
await mount('disconnected', send)
|
||||
|
||||
@@ -28,14 +28,6 @@ import type {
|
||||
AgentSessionQueuedMessageMoveResult
|
||||
} from '../../../../../src/shared/agent-session/requests/agent-session-queued-message-wire'
|
||||
import type { StructuredAgentSessionMutationResult } from '../../mobile-structured-agent-session-rpc'
|
||||
import {
|
||||
MobileAgentMessageContext,
|
||||
MobileAgentMessageOpenContext,
|
||||
createMobileAgentMessageSource
|
||||
} from '../transcript/mobile-agent-message-context'
|
||||
import type { AgentMessageSource } from '../../../../../src/shared/agent-session/agent-session-message-source'
|
||||
import { formatOrcaSessionAddress } from '../../../../../src/shared/orca-session-address'
|
||||
import { testOrcaSessionId } from '../../../../../src/shared/orca-session-address-test-fixture'
|
||||
|
||||
const rowRenders = vi.hoisted(() => ({ count: 0 }))
|
||||
vi.mock('../../MobileQueuedMessageCardRow', async (importOriginal) => {
|
||||
@@ -170,66 +162,6 @@ describe('MobileNativeChatQueuedMessages', () => {
|
||||
expect(sheet(mounted).props.visible).toBe(false)
|
||||
})
|
||||
|
||||
it("names a queued message's sender as its chat is now titled, and opens that chat", async () => {
|
||||
const coord = testOrcaSessionId('coord-chat')
|
||||
const from: AgentMessageSource = {
|
||||
kind: 'agent',
|
||||
senders: [
|
||||
{
|
||||
party: {
|
||||
address: formatOrcaSessionAddress(coord),
|
||||
terminalHandle: null,
|
||||
orcaSessionId: coord
|
||||
},
|
||||
name: 'Codex Chat',
|
||||
relation: 'coordinator'
|
||||
}
|
||||
],
|
||||
orchestration: null
|
||||
}
|
||||
const source = createMobileAgentMessageSource()
|
||||
source.update(
|
||||
[
|
||||
{
|
||||
type: 'agent-session',
|
||||
id: `agent-session:${coord}`,
|
||||
sessionId: coord,
|
||||
agent: 'codex',
|
||||
title: 'Release coordinator',
|
||||
isActive: false
|
||||
}
|
||||
],
|
||||
[],
|
||||
0
|
||||
)
|
||||
const open = vi.fn()
|
||||
const mounted = create(createElement('View'))
|
||||
renderer = mounted
|
||||
await act(async () => {
|
||||
mounted.update(
|
||||
createElement(
|
||||
MobileAgentMessageOpenContext.Provider,
|
||||
{ value: open },
|
||||
createElement(
|
||||
MobileAgentMessageContext.Provider,
|
||||
{ value: source },
|
||||
createElement(MobileNativeChatQueuedMessages, {
|
||||
cards: [card({ messageId: 'q', from })]
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
})
|
||||
const sender = mounted.root.find(
|
||||
(node) =>
|
||||
String(node.type) === 'Pressable' &&
|
||||
node.findAll((child) => child.children.includes('Release coordinator')).length > 0
|
||||
)
|
||||
expect(sender.props.accessibilityRole).toBe('button')
|
||||
await act(async () => sender.props.onPress())
|
||||
expect(open).toHaveBeenCalledWith(from, from.senders[0])
|
||||
})
|
||||
|
||||
it('the empty chord presses only the head card where its own button would, and offers it only while that press would act, across chat switches', async () => {
|
||||
let tray!: MobileNativeChatComposerTray
|
||||
function Tray(props: Parameters<typeof useMobileNativeChatComposerTray>[0]['queued']) {
|
||||
|
||||
@@ -160,38 +160,6 @@ describe('MobileNativeChatSessionOptionPickers', () => {
|
||||
renderer = null
|
||||
})
|
||||
|
||||
it('omits interaction mode from the drawer and model summary', async () => {
|
||||
mount(
|
||||
[
|
||||
MODEL_DESCRIPTOR,
|
||||
{
|
||||
id: 'interactionMode',
|
||||
label: 'Mode',
|
||||
category: 'mode',
|
||||
kind: {
|
||||
type: 'select',
|
||||
currentValue: 'default',
|
||||
choices: [
|
||||
{ value: 'default', label: 'Build' },
|
||||
{ value: 'plan', label: 'Plan' }
|
||||
]
|
||||
},
|
||||
valueSource: 'dispatched',
|
||||
transport: 'agent-session',
|
||||
settable: true
|
||||
}
|
||||
],
|
||||
true,
|
||||
'interactionMode'
|
||||
)
|
||||
expect(findAllByHostType(renderer!.root, 'BottomDrawer')).toHaveLength(0)
|
||||
expect(pill('Model').props.accessibilityLabel).not.toMatch(/Build|Plan/)
|
||||
act(() => pill('Model').props.onPress())
|
||||
expect(() => rowByText('Build')).toThrow('No row labeled Build')
|
||||
expect(() => rowByText('Plan')).toThrow('No row labeled Plan')
|
||||
expect(setOption).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('consumes a refused page without replay, then permits a fresh open and permission pick', async () => {
|
||||
const placeholder: SessionOptionDescriptor = {
|
||||
...MODEL_DESCRIPTOR,
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
|
||||
import {
|
||||
buildMobileNativeChatTransientData,
|
||||
foldMobileNativeChatMessages
|
||||
} from './mobile-native-chat-render-data'
|
||||
|
||||
function assistant(id: string, text: string): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp: 0,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
function user(id: string, text: string): NativeChatMessage {
|
||||
return { id, role: 'user', blocks: [{ type: 'text', text }], timestamp: 0, source: 'transcript' }
|
||||
}
|
||||
|
||||
const fold = (messages: NativeChatMessage[]) => foldMobileNativeChatMessages(messages, 'claude')
|
||||
|
||||
describe('buildMobileNativeChatTransientData', () => {
|
||||
it('keeps the phone-local image visible when the transcript replaces its optimistic echo', () => {
|
||||
const folded = fold([
|
||||
user('source', '[Image: source: /tmp/a.png]'),
|
||||
user('prompt', '[Image #1] look at this')
|
||||
])
|
||||
const result = buildMobileNativeChatTransientData({
|
||||
folded,
|
||||
streaming: null,
|
||||
pending: [],
|
||||
imagePreviewsByMessageId: { prompt: ['file:///phone-photo.jpg'] }
|
||||
})
|
||||
|
||||
expect(result.data).toHaveLength(1)
|
||||
expect(result.data[0]?.blocks).toEqual([
|
||||
{ type: 'image-ref', path: '/tmp/a.png', url: 'file:///phone-photo.jpg' },
|
||||
{ type: 'text', text: 'look at this' }
|
||||
])
|
||||
})
|
||||
|
||||
it('restores the local preview onto a marker-only transcript turn', () => {
|
||||
const result = buildMobileNativeChatTransientData({
|
||||
folded: fold([user('prompt', '[Image #1]')]),
|
||||
streaming: null,
|
||||
pending: [],
|
||||
imagePreviewsByMessageId: { prompt: ['file:///phone-photo.jpg'] }
|
||||
})
|
||||
|
||||
expect(result.data[0]?.blocks).toEqual([{ type: 'image-ref', url: 'file:///phone-photo.jpg' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('foldMobileNativeChatMessages', () => {
|
||||
function toolCall(id: string): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name: 'Bash', input: { command: 'command -v orca-ide' } }],
|
||||
timestamp: 0,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
function toolResult(id: string, output: string): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'tool',
|
||||
blocks: [{ type: 'tool-result', output }],
|
||||
timestamp: 0,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
function planFrame(head: string): NativeChatMessage {
|
||||
return {
|
||||
id: 'plan',
|
||||
role: 'system',
|
||||
timestamp: 0,
|
||||
source: 'transcript',
|
||||
blocks: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'codex · notification:turn/plan/updated',
|
||||
providerFrame: {
|
||||
provider: 'codex',
|
||||
kind: 'notification:turn/plan/updated',
|
||||
payload: { head, byteLength: head.length, digest: 'digest', truncated: false }
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
it('draws a Codex plan update where it happened, as an update_plan call', () => {
|
||||
const folded = fold([
|
||||
assistant('a1', 'Working.'),
|
||||
toolCall('c1'),
|
||||
toolResult('r1', 'ok'),
|
||||
planFrame('{"plan":[{"step":"Port rows","status":"inProgress"}]}'),
|
||||
toolCall('c2'),
|
||||
toolResult('r2', 'ok')
|
||||
])
|
||||
expect(folded.map((message) => message.id)).toEqual(['a1', 'plan', 'c2'])
|
||||
expect(folded[1]).toMatchObject({
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name: 'update_plan', state: 'completed' }]
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Claude may consume queued commands without a user record; unmatched echoes must stay at their send position rather than trail every later turn.
|
||||
describe("mobile shows the conversation, never a subagent's rows", () => {
|
||||
it("keeps the spawn's one line and drops what the subagent said and did", () => {
|
||||
const child = { agentId: 'task-1', producerKind: 'agent' as const }
|
||||
const folded = fold([
|
||||
user('ask', 'review the PR'),
|
||||
{
|
||||
id: 'spawn',
|
||||
role: 'system',
|
||||
blocks: [{ type: 'text', text: 'Kicked off 1 subagent' }],
|
||||
timestamp: 0,
|
||||
source: 'transcript'
|
||||
},
|
||||
{ ...assistant('child-said', 'The PR is CLEAN.'), ...child },
|
||||
{
|
||||
id: 'child-grep',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name: 'Grep', input: {} }],
|
||||
timestamp: 0,
|
||||
source: 'transcript',
|
||||
...child
|
||||
},
|
||||
assistant('answer', 'Delegated; nothing to fix.')
|
||||
])
|
||||
|
||||
expect(folded.map((message) => message.id)).toEqual(['ask', 'spawn', 'answer'])
|
||||
expect(folded[2]?.blocks).toEqual([{ type: 'text', text: 'Delegated; nothing to fix.' }])
|
||||
})
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
import '../../../../src/shared/agent-launch/startup/agent-tui-input-clear'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RpcClient } from '../../transport/rpc/rpc-client-contract'
|
||||
import {
|
||||
healMobileNativeChatStaleInput,
|
||||
isMobileNativeChatInputStale,
|
||||
markMobileNativeChatInputStale,
|
||||
resetMobileNativeChatStaleInputForTests
|
||||
} from './mobile-native-chat-stale-input'
|
||||
|
||||
function sendResult(accepted: boolean) {
|
||||
return {
|
||||
id: 'send',
|
||||
ok: true as const,
|
||||
result: { send: { accepted } },
|
||||
_meta: { runtimeId: 'runtime' }
|
||||
}
|
||||
}
|
||||
|
||||
function makeClient(accepted = true): Pick<RpcClient, 'sendRequest'> {
|
||||
return { sendRequest: vi.fn().mockResolvedValue(sendResult(accepted)) }
|
||||
}
|
||||
|
||||
describe('mobile native chat stale input markers', () => {
|
||||
beforeEach(() => {
|
||||
resetMobileNativeChatStaleInputForTests()
|
||||
})
|
||||
|
||||
it('writes nothing when the terminal is not marked', async () => {
|
||||
const client = makeClient()
|
||||
await expect(
|
||||
healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null })
|
||||
).resolves.toBe(true)
|
||||
expect(client.sendRequest).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the marker when the host rejects the clear', async () => {
|
||||
const client = makeClient(false)
|
||||
markMobileNativeChatInputStale('term-1')
|
||||
await expect(
|
||||
healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null })
|
||||
).resolves.toBe(false)
|
||||
expect(isMobileNativeChatInputStale('term-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the marker when the clear throws', async () => {
|
||||
const client = { sendRequest: vi.fn().mockRejectedValue(new Error('offline')) }
|
||||
markMobileNativeChatInputStale('term-1')
|
||||
await expect(
|
||||
healMobileNativeChatStaleInput({ client, terminal: 'term-1', deviceToken: null })
|
||||
).resolves.toBe(false)
|
||||
expect(isMobileNativeChatInputStale('term-1')).toBe(true)
|
||||
})
|
||||
})
|
||||
+1
-114
@@ -1,19 +1,12 @@
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalStatusItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
|
||||
import { isAdmissibleAgentJournalItemBody } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas'
|
||||
import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection'
|
||||
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
|
||||
import { agentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words'
|
||||
import { colors } from '../../../theme/mobile-theme'
|
||||
import { activateMobileUiLocale } from '../../../i18n/mobile-i18n'
|
||||
import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler'
|
||||
import {
|
||||
MobileNativeChatNoticeContext,
|
||||
type MobileNativeChatNoticeView
|
||||
} from '../../mobile-native-chat-notice-context'
|
||||
|
||||
vi.mock('react-native', async () => {
|
||||
const React = await import('react')
|
||||
@@ -94,11 +87,6 @@ describe('MobileNativeChatMessage status notices', () => {
|
||||
return renderer!
|
||||
}
|
||||
|
||||
const markdownIn = (node: ReactTestInstance): string[] =>
|
||||
node
|
||||
.findAll((child) => String(child.type) === 'MobileMarkdown')
|
||||
.map((markdown) => markdown.props.content)
|
||||
|
||||
const statusRow = (body: AgentJournalStatusItem): NativeChatMessage =>
|
||||
projectStructuredItemToNativeChat({
|
||||
itemId: 'status',
|
||||
@@ -107,20 +95,6 @@ describe('MobileNativeChatMessage status notices', () => {
|
||||
observedAt: 2,
|
||||
body
|
||||
})!
|
||||
const renderNotice = (body: AgentJournalStatusItem, names: MobileNativeChatNoticeView) => {
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(
|
||||
MobileNativeChatNoticeContext.Provider,
|
||||
{ value: names },
|
||||
createElement(MobileNativeChatMessage, { message: statusRow(body) })
|
||||
)
|
||||
)
|
||||
})
|
||||
return renderer!.root.findAll(
|
||||
(node) => String(node.type) === 'Text' && node.props.selectable === true
|
||||
)[0]!
|
||||
}
|
||||
|
||||
it('links a CI result line to its pull request and commit through the link sheet', () => {
|
||||
const openLink = vi.fn()
|
||||
@@ -164,93 +138,6 @@ describe('MobileNativeChatMessage status notices', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it.each(['with reset', 'from an old host'] as const)(
|
||||
'draws an OpenCode usage warning %s',
|
||||
(source) => {
|
||||
const hasReset = source === 'with reset'
|
||||
const resetsAt = new Date(2026, 9, 15, 15, 42).getTime()
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(new Date(2026, 9, 15, 12).getTime())
|
||||
try {
|
||||
const host = agentSessionFailureWords(
|
||||
agentSessionFailureFact('usageLimitReached', {
|
||||
detail: {
|
||||
text: 'Internal error: Rate limit exceeded. Please try again later.',
|
||||
audience: 'person'
|
||||
},
|
||||
...(hasReset ? { usageLimit: { resetsAt } } : {})
|
||||
}),
|
||||
{ surface: 'row', agentName: 'OpenCode' }
|
||||
)
|
||||
expect(host.text).toBe('OpenCode hit its usage limit.')
|
||||
const hostText =
|
||||
source === 'from an old host'
|
||||
? 'OpenCode hit its usage limit. Send a message once it resets to continue.'
|
||||
: host.text
|
||||
const body: unknown = { kind: 'status', tone: 'warning', ...host, text: hostText }
|
||||
if (!isAdmissibleAgentJournalItemBody(body) || body.kind !== 'status') {
|
||||
throw new Error('Status fixture was not admitted')
|
||||
}
|
||||
const text = renderNotice(body, { hostName: null, agentName: 'OpenCode' })
|
||||
const tree = renderer!
|
||||
// An old host's stored advice gives way to the headline from the fact; the reset sits below it.
|
||||
expect(text.props.children).toBe('OpenCode hit its usage limit.')
|
||||
expect(
|
||||
tree.root
|
||||
.findAll((node) => String(node.type) === 'Text')
|
||||
.some((node) => /^Resets at \S/u.test(String(node.props.children)))
|
||||
).toBe(hasReset)
|
||||
expect(Object.assign({}, ...text.props.style)).toMatchObject({ color: colors.statusAmber })
|
||||
expect(tree.root.find((node) => String(node.type) === 'AlertTriangle').props.color).toBe(
|
||||
colors.statusAmber
|
||||
)
|
||||
expect(markdownIn(tree.root)).toEqual([])
|
||||
const details = tree.root.find(
|
||||
(node) => String(node.type) === 'Pressable' && node.props.accessibilityLabel === 'Details'
|
||||
)
|
||||
expect(details.props['aria-expanded']).toBe(false)
|
||||
act(() => details.props.onPress())
|
||||
expect(
|
||||
tree.root
|
||||
.findAll((node) => String(node.type) === 'Text')
|
||||
.flatMap((node) => node.props.children)
|
||||
).toContain('Internal error: Rate limit exceeded. Please try again later.')
|
||||
} finally {
|
||||
now.mockRestore()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
['Claude', 'managed', 'claude auth login'],
|
||||
['Codex', 'system', 'codex login --device-auth'],
|
||||
['Codex', 'managed', null]
|
||||
] as const)(
|
||||
'offers %s (%s account) sign-in in a host terminal',
|
||||
(agentName, account, command) => {
|
||||
const onRunInTerminal = vi.fn()
|
||||
renderNotice(
|
||||
{
|
||||
kind: 'status',
|
||||
tone: 'error',
|
||||
...agentSessionFailureWords(
|
||||
agentSessionFailureFact('notSignedIn', account ? { account } : {}),
|
||||
{ surface: 'row', agentName }
|
||||
)
|
||||
},
|
||||
{ hostName: null, agentName, onRunInTerminal }
|
||||
)
|
||||
const signIn = renderer!.root.findAll(
|
||||
(node) => String(node.type) === 'Pressable' && node.props.accessibilityHint !== undefined
|
||||
)
|
||||
if (command === null) {
|
||||
expect(signIn).toHaveLength(0)
|
||||
return
|
||||
}
|
||||
act(() => signIn[0]!.props.onPress())
|
||||
expect(onRunInTerminal).toHaveBeenCalledWith(command)
|
||||
}
|
||||
)
|
||||
|
||||
// Protocol-shaped synthetic frames, not a live-provider reproduction.
|
||||
it.each([
|
||||
[
|
||||
|
||||
@@ -1,140 +0,0 @@
|
||||
import './mobile-agent-message-renderer.test-fixture'
|
||||
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
NativeChatBackgroundTaskBlock,
|
||||
NativeChatMessage
|
||||
} from '../../../../../src/shared/native-chat/native-chat-types'
|
||||
import { backgroundTaskJournalBody } from '../../../../../src/shared/native-chat/input/native-chat-background-task-row'
|
||||
import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection'
|
||||
|
||||
import type { NativeChatResolvedPrompt } from '../../../../../src/shared/native-chat/native-chat-resolution-receipt'
|
||||
|
||||
import type { AgentMessageSource } from '../../../../../src/shared/agent-session/agent-session-message-source'
|
||||
|
||||
import { MobileNativeChatMessage } from './MobileNativeChatMessage'
|
||||
|
||||
import { findAllByHostType } from '../../../test-support/react-test-renderer-host-nodes'
|
||||
|
||||
vi.mock('@react-native-async-storage/async-storage', () => ({
|
||||
default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
|
||||
}))
|
||||
|
||||
function userMessage(blocks: NativeChatMessage['blocks']): NativeChatMessage {
|
||||
return { id: 'u1', role: 'user', blocks, timestamp: null, source: 'transcript' }
|
||||
}
|
||||
|
||||
describe('MobileNativeChatMessage', () => {
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function render(
|
||||
message: NativeChatMessage,
|
||||
props: {
|
||||
fontScale?: number
|
||||
structuredActivityUi?: boolean
|
||||
activeTurnIsWorking?: boolean
|
||||
trailingRun?: boolean
|
||||
foldedAway?: boolean
|
||||
turnExpanded?: boolean
|
||||
turnStatus?: {
|
||||
startedAt: number | null
|
||||
thinking: boolean
|
||||
workedSeconds: number | null
|
||||
} | null
|
||||
onToggleTurn?: () => void
|
||||
reasoningIsLive?: boolean
|
||||
unsentNotice?: string
|
||||
receipt?: NativeChatResolvedPrompt
|
||||
userMessageOpen?: boolean
|
||||
onToggleUserMessage?: (messageId: string) => void
|
||||
awaiting?: boolean
|
||||
} = {}
|
||||
): ReactTestRenderer {
|
||||
act(() => {
|
||||
renderer = create(createElement(MobileNativeChatMessage, { message, ...props }))
|
||||
})
|
||||
return renderer!
|
||||
}
|
||||
|
||||
const markdownIn = (node: ReactTestInstance): string[] =>
|
||||
node
|
||||
.findAll((child) => String(child.type) === 'MobileMarkdown')
|
||||
.map((markdown) => markdown.props.content)
|
||||
const textIn = (node: ReactTestInstance): string[] =>
|
||||
findAllByHostType(node, 'Text').map((text) => String(text.children.join('')))
|
||||
|
||||
it.each(['task', 'generic'] as const)(
|
||||
'expands and refolds %s messages and preserves old-server body',
|
||||
(kind) => {
|
||||
const from: AgentMessageSource = {
|
||||
kind: 'agent',
|
||||
orchestration:
|
||||
kind === 'task' ? { message: 'task', runId: 'r', taskId: 't', dispatchId: 'd' } : null,
|
||||
senders: []
|
||||
}
|
||||
const message = {
|
||||
...userMessage([
|
||||
{ type: 'text' as const, text: 'Long paragraph wrapped over many native lines.' }
|
||||
]),
|
||||
from
|
||||
}
|
||||
const tree = render(message)
|
||||
const toggle = () =>
|
||||
findAllByHostType(tree.root, 'Pressable').find(
|
||||
(node) => node.props.accessibilityState?.expanded !== undefined
|
||||
)!
|
||||
expect(markdownIn(tree.root)).toEqual([])
|
||||
expect(toggle().props.accessibilityState.expanded).toBe(false)
|
||||
act(() => toggle().props.onPress())
|
||||
expect(markdownIn(tree.root)).toEqual(['Long paragraph wrapped over many native lines.'])
|
||||
expect(toggle().props.accessibilityState.expanded).toBe(true)
|
||||
act(() => toggle().props.onPress())
|
||||
expect(markdownIn(tree.root)).toEqual([])
|
||||
act(() => tree.unmount())
|
||||
const oldServer = render({ ...message, from: undefined })
|
||||
expect(oldServer.root.findAllByProps({ testID: 'agent-message-card' })).toHaveLength(0)
|
||||
expect(markdownIn(oldServer.root)).toEqual([
|
||||
message.blocks[0].type === 'text' ? message.blocks[0].text : ''
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
it('draws a background task as its row, not the plain sentence written for older clients', () => {
|
||||
const task = (overrides: Partial<NativeChatBackgroundTaskBlock>): NativeChatMessage =>
|
||||
projectStructuredItemToNativeChat({
|
||||
itemId: 'task',
|
||||
revision: 1,
|
||||
sequence: 1,
|
||||
observedAt: 1,
|
||||
body: backgroundTaskJournalBody({
|
||||
type: 'background-task',
|
||||
taskId: 'b1',
|
||||
kind: 'command',
|
||||
label: 'pnpm test',
|
||||
state: 'working',
|
||||
startedAt: 1_000,
|
||||
outputFile: '/tmp/b1.output',
|
||||
...overrides
|
||||
})
|
||||
})!
|
||||
const run = () => render(task({})).root.findByProps({ testID: 'background-task-run' })
|
||||
expect(textIn(run())).toEqual(['pnpm test', 'working', 'Output: /tmp/b1.output'])
|
||||
act(() => renderer?.unmount())
|
||||
const settled = render(
|
||||
task({ state: 'blocked', settledAt: 66_000, summary: 'Exited with code 1' })
|
||||
)
|
||||
expect(textIn(settled.root)).toEqual([
|
||||
'pnpm test',
|
||||
'blocked · failed · 1m 5s',
|
||||
'Exited with code 1',
|
||||
'Output: /tmp/b1.output'
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,6 @@ import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'rea
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { NativeChatBlock } from '../../../../../src/shared/native-chat/native-chat-types'
|
||||
import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler'
|
||||
|
||||
const scrolls = vi.hoisted(() => ({ toEnd: vi.fn(), to: vi.fn() }))
|
||||
|
||||
@@ -66,8 +65,6 @@ vi.mock('../../../components/MobileSourceCopyButton', () => ({
|
||||
}))
|
||||
vi.mock('../../../platform/external-link', () => ({ openExternalLink: vi.fn() }))
|
||||
vi.mock('../../../components/inline-text-selection', () => ({ INLINE_TEXT_SELECTION: false }))
|
||||
|
||||
import { openExternalLink } from '../../../platform/external-link'
|
||||
import { ToolRun } from './MobileNativeChatToolRun'
|
||||
import {
|
||||
MobileNativeChatDisclosureContext,
|
||||
@@ -82,20 +79,6 @@ describe('ToolRun', () => {
|
||||
renderer = null
|
||||
})
|
||||
|
||||
function render(blocks: NativeChatBlock[], onOpenLink: (url: string) => void): ReactTestRenderer {
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(
|
||||
MarkdownLinkHandlerContext.Provider,
|
||||
{ value: onOpenLink },
|
||||
createElement(ToolRun, { blocks })
|
||||
)
|
||||
)
|
||||
})
|
||||
openRun(renderer!)
|
||||
return renderer!
|
||||
}
|
||||
|
||||
function openRun(tree: ReactTestRenderer): void {
|
||||
act(() => {
|
||||
tree.root.findAll((node) => String(node.type) === 'Pressable')[0]!.props.onPress()
|
||||
@@ -107,40 +90,6 @@ describe('ToolRun', () => {
|
||||
.findAll((node) => String(node.type) === 'Text')
|
||||
.map((text) => String(text.children.join('')))
|
||||
|
||||
describe('web search hits, handed to the chat link sheet', () => {
|
||||
const openRow = (tree: ReactTestRenderer, label: string): void => {
|
||||
act(() => {
|
||||
tree.root
|
||||
.findAll((node) => String(node.type) === 'Pressable')
|
||||
.findLast((node) => textIn(node).includes(label))!
|
||||
.props.onPress()
|
||||
})
|
||||
}
|
||||
|
||||
it('hands a web search hit to the chat link sheet when one is provided', () => {
|
||||
vi.mocked(openExternalLink).mockClear()
|
||||
const onOpenLink = vi.fn()
|
||||
const tree = render(
|
||||
[
|
||||
{
|
||||
type: 'tool-call',
|
||||
name: 'web_search',
|
||||
input: { query: 'FlatList docs' },
|
||||
webSearchResults: [{ title: 'FlatList', url: 'https://reactnative.dev/docs/flatlist' }]
|
||||
}
|
||||
],
|
||||
onOpenLink
|
||||
)
|
||||
openRow(tree, 'FlatList docs')
|
||||
const hit = tree.root.findAll(
|
||||
(node) => String(node.type) === 'Text' && node.props.accessibilityRole === 'link'
|
||||
)[0]!
|
||||
act(() => hit.props.onPress())
|
||||
expect(onOpenLink).toHaveBeenCalledWith('https://reactnative.dev/docs/flatlist')
|
||||
expect(openExternalLink).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe("what the reader opened, kept above the list's recycled rows", () => {
|
||||
const blocks: NativeChatBlock[] = [
|
||||
{ type: 'tool-call', name: 'Bash', input: { command: 'ls' }, state: 'completed' },
|
||||
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { quantizeFontScale } from './mobile-native-chat-message-text'
|
||||
|
||||
const handlers: { start?: () => void; update?: (e: { scale: number }) => void } = {}
|
||||
|
||||
vi.mock('react-native-gesture-handler', () => {
|
||||
const pinch = {
|
||||
runOnJS: () => pinch,
|
||||
onStart: (cb: () => void) => {
|
||||
handlers.start = cb
|
||||
return pinch
|
||||
},
|
||||
onUpdate: (cb: (e: { scale: number }) => void) => {
|
||||
handlers.update = cb
|
||||
return pinch
|
||||
}
|
||||
}
|
||||
return {
|
||||
Gesture: { Simultaneous: (...g: unknown[]) => g, Native: () => ({}), Pinch: () => pinch }
|
||||
}
|
||||
})
|
||||
|
||||
import { useMobileNativeChatPinchGesture } from './use-mobile-native-chat-pinch-gesture'
|
||||
|
||||
describe('quantizeFontScale', () => {
|
||||
it('snaps to the commit step and stays inside the supported range', () => {
|
||||
expect(quantizeFontScale(1)).toBe(1)
|
||||
expect(quantizeFontScale(1.01)).toBe(1)
|
||||
expect(quantizeFontScale(1.024)).toBe(1)
|
||||
expect(quantizeFontScale(1.03)).toBe(1.05)
|
||||
expect(quantizeFontScale(5)).toBe(1.8)
|
||||
expect(quantizeFontScale(0.1)).toBe(0.8)
|
||||
expect(quantizeFontScale(Number.NaN)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useMobileNativeChatPinchGesture', () => {
|
||||
let renderer: ReturnType<typeof create> | null = null
|
||||
let latest = 1
|
||||
|
||||
function Probe({ chat }: { chat: string }): null {
|
||||
latest = useMobileNativeChatPinchGesture(chat).fontScale
|
||||
return null
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
latest = 1
|
||||
act(() => {
|
||||
renderer = create(createElement(Probe, { chat: 'a' }))
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
// Each committed scale remeasures the whole list; raw/inadvertent pinches expose recycled-paragraph clipping, so commits must be quantized.
|
||||
it('commits nothing for gesture noise the user cannot see', () => {
|
||||
act(() => handlers.start?.())
|
||||
for (const scale of [1.001, 0.995, 1.008, 1.02, 0.982]) {
|
||||
act(() => handlers.update?.({ scale }))
|
||||
}
|
||||
expect(latest).toBe(1)
|
||||
})
|
||||
|
||||
it('commits a real pinch, on the step grid', () => {
|
||||
act(() => handlers.start?.())
|
||||
act(() => handlers.update?.({ scale: 1.34 }))
|
||||
expect(latest).toBe(1.35)
|
||||
act(() => handlers.update?.({ scale: 1.37 }))
|
||||
expect(latest).toBe(1.35)
|
||||
act(() => handlers.update?.({ scale: 1.42 }))
|
||||
expect(latest).toBe(1.4)
|
||||
})
|
||||
|
||||
it('starts another chat in the same view at the default size', () => {
|
||||
act(() => handlers.start?.())
|
||||
act(() => handlers.update?.({ scale: 1.34 }))
|
||||
expect(latest).toBe(1.35)
|
||||
act(() => renderer?.update(createElement(Probe, { chat: 'b' })))
|
||||
expect(latest).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -1,17 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isRenderableImageUri } from './mobile-native-chat-image-preview'
|
||||
|
||||
describe('isRenderableImageUri', () => {
|
||||
it('rejects bare host paths (not loadable on the device) and empty values', () => {
|
||||
for (const uri of [
|
||||
'/tmp/orca-attach.png',
|
||||
'C:\\tmp\\a.png',
|
||||
'orca-attach.png',
|
||||
'',
|
||||
undefined
|
||||
]) {
|
||||
expect(isRenderableImageUri(uri)).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -12,35 +12,6 @@ function browserTab(id: string, isActive: boolean): Tab {
|
||||
}
|
||||
|
||||
describe('resolveActiveSessionTab', () => {
|
||||
it('keeps the device on its browser tab when a republication flags the agent terminal active', () => {
|
||||
const result = resolveActiveSessionTab(
|
||||
[terminalTab('agent', true), browserTab('browser', false)],
|
||||
{
|
||||
pendingActiveSessionTabId: null,
|
||||
selectedSessionTabId: 'browser'
|
||||
}
|
||||
)
|
||||
|
||||
expect(result.activeTab?.id).toBe('browser')
|
||||
expect(result.selectionSource).toBe('selected-tab')
|
||||
expect(result.retainSelectedSessionTabId).toBe(false)
|
||||
})
|
||||
|
||||
it('follows the host when it explicitly navigates this device', () => {
|
||||
const result = resolveActiveSessionTab(
|
||||
[terminalTab('agent', true), browserTab('browser', false)],
|
||||
{
|
||||
pendingActiveSessionTabId: null,
|
||||
selectedSessionTabId: 'browser',
|
||||
navigationIntent: 'follow'
|
||||
}
|
||||
)
|
||||
|
||||
expect(result.activeTab?.id).toBe('agent')
|
||||
expect(result.selectionSource).toBe('navigation-intent')
|
||||
expect(result.retainSelectedSessionTabId).toBe(false)
|
||||
})
|
||||
|
||||
it('lets explicit follow supersede an in-flight local activation', () => {
|
||||
const result = resolveActiveSessionTab(
|
||||
[terminalTab('agent', true), browserTab('browser', false)],
|
||||
@@ -71,41 +42,4 @@ describe('resolveActiveSessionTab', () => {
|
||||
)
|
||||
expect(restored.activeTab?.id).toBe('browser')
|
||||
})
|
||||
|
||||
it('lets a pending activation win until the snapshot catches up', () => {
|
||||
const result = resolveActiveSessionTab(
|
||||
[terminalTab('agent', true), browserTab('browser', false)],
|
||||
{
|
||||
pendingActiveSessionTabId: 'browser',
|
||||
selectedSessionTabId: 'agent'
|
||||
}
|
||||
)
|
||||
|
||||
expect(result.activeTab?.id).toBe('browser')
|
||||
expect(result.selectionSource).toBe('pending-tab')
|
||||
expect(result.clearPendingActiveSessionTabId).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the pending marker once the snapshot acknowledges it', () => {
|
||||
const result = resolveActiveSessionTab(
|
||||
[terminalTab('agent', false), browserTab('browser', true)],
|
||||
{
|
||||
pendingActiveSessionTabId: 'browser',
|
||||
selectedSessionTabId: 'agent'
|
||||
}
|
||||
)
|
||||
|
||||
expect(result.activeTab?.id).toBe('browser')
|
||||
expect(result.clearPendingActiveSessionTabId).toBe(true)
|
||||
})
|
||||
|
||||
it('clears a stale pending marker whose tab is gone', () => {
|
||||
const result = resolveActiveSessionTab([terminalTab('agent', true)], {
|
||||
pendingActiveSessionTabId: 'removed',
|
||||
selectedSessionTabId: null
|
||||
})
|
||||
|
||||
expect(result.activeTab?.id).toBe('agent')
|
||||
expect(result.clearPendingActiveSessionTabId).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createMobileSessionCreateWarningState,
|
||||
dismissMobileSessionCreateWarningState,
|
||||
reconcileMobileSessionCreateWarningState
|
||||
} from './mobile-session-create-warning-state'
|
||||
|
||||
describe('mobile session create warning state', () => {
|
||||
it('preserves a dismissed warning while the route warning is unchanged', () => {
|
||||
const dismissed = dismissMobileSessionCreateWarningState(
|
||||
createMobileSessionCreateWarningState('Created, but setup failed')
|
||||
)
|
||||
|
||||
expect(dismissed).toEqual({ source: 'Created, but setup failed', visible: '' })
|
||||
expect(reconcileMobileSessionCreateWarningState(dismissed, 'Created, but setup failed')).toBe(
|
||||
dismissed
|
||||
)
|
||||
})
|
||||
|
||||
it('shows a new warning when the route warning changes', () => {
|
||||
const dismissed = dismissMobileSessionCreateWarningState(
|
||||
createMobileSessionCreateWarningState('Old warning')
|
||||
)
|
||||
|
||||
expect(reconcileMobileSessionCreateWarningState(dismissed, 'New warning')).toEqual({
|
||||
source: 'New warning',
|
||||
visible: 'New warning'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { selectBulkCloseTabs } from './mobile-tab-close-selection'
|
||||
|
||||
const tab = (id: string, isDirty?: boolean, isPinned?: boolean) => ({
|
||||
id,
|
||||
...(isDirty === undefined ? {} : { isDirty }),
|
||||
...(isPinned === undefined ? {} : { isPinned })
|
||||
})
|
||||
|
||||
describe('selectBulkCloseTabs', () => {
|
||||
it('skips dirty tabs so unsaved edits survive a bulk close', () => {
|
||||
const withDirty = [tab('a', true), tab('b'), tab('c', false), tab('d')]
|
||||
expect(selectBulkCloseTabs(withDirty, 'b').map((t) => t.id)).toEqual(['c', 'd'])
|
||||
})
|
||||
|
||||
it('skips pinned tabs', () => {
|
||||
const withPinned = [tab('a', undefined, true), tab('b'), tab('c', undefined, true), tab('d')]
|
||||
expect(selectBulkCloseTabs(withPinned, 'b').map((t) => t.id)).toEqual(['d'])
|
||||
})
|
||||
})
|
||||
@@ -1,66 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { shouldActivateOpenedMobileSessionTab } from './opened-mobile-session-tab'
|
||||
|
||||
describe('shouldActivateOpenedMobileSessionTab', () => {
|
||||
const currentTerminalState = {
|
||||
activationSeq: 2,
|
||||
latestActivationSeq: 2,
|
||||
sourceTerminalHandle: 'pty-1',
|
||||
activeTerminalHandle: 'pty-1',
|
||||
activeTabType: 'terminal'
|
||||
}
|
||||
|
||||
it('prevents an older tap from stealing focus from a newer tap', () => {
|
||||
expect(
|
||||
shouldActivateOpenedMobileSessionTab({
|
||||
...currentTerminalState,
|
||||
activated: false,
|
||||
activationSeq: 1
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('does not activate after the user leaves the source terminal', () => {
|
||||
expect(
|
||||
shouldActivateOpenedMobileSessionTab({
|
||||
...currentTerminalState,
|
||||
activated: false,
|
||||
activeTabType: 'file',
|
||||
activeTerminalHandle: null
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
shouldActivateOpenedMobileSessionTab({
|
||||
...currentTerminalState,
|
||||
activated: false,
|
||||
activeTerminalHandle: 'pty-2'
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('allows a structured agent-session tab to anchor chat file activation', () => {
|
||||
expect(
|
||||
shouldActivateOpenedMobileSessionTab({
|
||||
activated: false,
|
||||
activationSeq: 2,
|
||||
latestActivationSeq: 2,
|
||||
sourceTerminalHandle: null,
|
||||
activeTerminalHandle: null,
|
||||
sourceSessionTabId: 'agent-tab-1',
|
||||
activeSessionTabId: 'agent-tab-1',
|
||||
activeTabType: 'agent-session'
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
shouldActivateOpenedMobileSessionTab({
|
||||
...currentTerminalState,
|
||||
activated: false,
|
||||
sourceTerminalHandle: null,
|
||||
activeTerminalHandle: null,
|
||||
sourceSessionTabId: 'agent-tab-1',
|
||||
activeSessionTabId: 'agent-tab-2',
|
||||
activeTabType: 'agent-session'
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -9,19 +9,6 @@ import {
|
||||
type PendingSessionSelection
|
||||
} from './pending-session-selection'
|
||||
|
||||
function terminalTab(id: string, terminal: string): MobileSessionTab {
|
||||
const tab: MobileSessionTab = {
|
||||
type: 'terminal',
|
||||
id,
|
||||
parentTabId: id,
|
||||
leafId: 'leaf',
|
||||
title: 'Terminal',
|
||||
terminal,
|
||||
isActive: false
|
||||
}
|
||||
return tab
|
||||
}
|
||||
|
||||
function chatTab(id: string, sessionId: string): MobileSessionTab {
|
||||
const tab: MobileSessionTab = {
|
||||
type: 'agent-session',
|
||||
@@ -52,45 +39,12 @@ function reservedTerminalTab(terminal: string | null): MobileSessionTab {
|
||||
}
|
||||
|
||||
describe('resolveLaunchedSelection', () => {
|
||||
it('finds a launched chat by its session id, whatever its tab id is', () => {
|
||||
const tabs = [chatTab('opaque-tab-7', 'claude_s1')]
|
||||
expect(
|
||||
resolveLaunchedSelection(launchedSelection('l1', { sessionId: 'claude_s1' }), tabs)
|
||||
).toEqual({
|
||||
selection: { kind: 'tab', tabId: 'opaque-tab-7' },
|
||||
landedTabId: 'opaque-tab-7'
|
||||
})
|
||||
})
|
||||
|
||||
it('finds a launched terminal by the pane this device reserved, before any reply', () => {
|
||||
const selection = launchedSelection('l1', { pane: PANE }, null)
|
||||
expect(resolveLaunchedSelection(selection, [reservedTerminalTab('term_9')])).toEqual({
|
||||
selection: { kind: 'terminal', handle: 'term_9', tabId: `${PANE.tabId}::${PANE.leafId}` },
|
||||
landedTabId: `${PANE.tabId}::${PANE.leafId}`
|
||||
})
|
||||
expect(resolveLaunchedSelection(selection, [reservedTerminalTab(null)]).selection).toEqual({
|
||||
kind: 'tab',
|
||||
tabId: `${PANE.tabId}::${PANE.leafId}`
|
||||
})
|
||||
})
|
||||
|
||||
it('never takes a chat for the reserved pane: a chat is listed under its session', () => {
|
||||
const selection = launchedSelection('l1', { pane: PANE }, null)
|
||||
expect(
|
||||
resolveLaunchedSelection(selection, [chatTab(PANE.tabId, 'claude_other')]).landedTabId
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it("finds a terminal by the reply's handle when the host ignored the reservation", () => {
|
||||
const tabs = [terminalTab('tab-2', 'term_9')]
|
||||
const selection = withLaunchReply(launchedSelection('l1', { pane: PANE }, null), 'l1', {
|
||||
handle: 'term_9'
|
||||
})
|
||||
expect(resolveLaunchedSelection(selection, tabs)).toEqual({
|
||||
selection: { kind: 'terminal', handle: 'term_9', tabId: 'tab-2' },
|
||||
landedTabId: 'tab-2'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("a launch's own reply and end", () => {
|
||||
@@ -103,13 +57,6 @@ describe("a launch's own reply and end", () => {
|
||||
expect(withoutUnansweredLaunch(pick, 'l1')).toBe(pick)
|
||||
expect(withoutUnansweredLaunch(newer, 'l1')).toBe(newer)
|
||||
})
|
||||
|
||||
it('drops a launch that ended unanswered and keeps one its reply named', () => {
|
||||
const waiting = launchedSelection('l1', { pane: PANE }, null)
|
||||
expect(withoutUnansweredLaunch(waiting, 'l1')).toBeNull()
|
||||
const answered = withLaunchReply(waiting, 'l1', { handle: 'term_9' })
|
||||
expect(withoutUnansweredLaunch(answered, 'l1')).toBe(answered)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLaunchedSurfaceListed', () => {
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
acceptSessionSnapshot,
|
||||
applyClosedTabTombstones,
|
||||
type AppliedSnapshotMarker
|
||||
} from './session-tab-snapshot-gate'
|
||||
|
||||
describe('acceptSessionSnapshot', () => {
|
||||
it('rejects a strictly older version from the same publisher without moving the floor', () => {
|
||||
const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 42 }
|
||||
expect(
|
||||
acceptSessionSnapshot({ publicationEpoch: 'renderer:a', snapshotVersion: 41 }, marker)
|
||||
).toBe(false)
|
||||
expect(marker).toEqual({ epoch: 'renderer:a', version: 42 })
|
||||
})
|
||||
|
||||
it('accepts any version from a new publisher (epoch change) and resets the floor', () => {
|
||||
const marker: AppliedSnapshotMarker = { epoch: 'renderer:a', version: 99 }
|
||||
expect(
|
||||
acceptSessionSnapshot({ publicationEpoch: 'headless:b', snapshotVersion: 1 }, marker)
|
||||
).toBe(true)
|
||||
expect(marker).toEqual({ epoch: 'headless:b', version: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyClosedTabTombstones', () => {
|
||||
const tab = (id: string): { id: string } => ({ id })
|
||||
|
||||
it('suppresses a tombstoned tab while it is still present and not expired', () => {
|
||||
const tombstones = new Map([['a', 5000]])
|
||||
const result = applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 1000)
|
||||
expect(result.map((t) => t.id)).toEqual(['b'])
|
||||
expect(tombstones.has('a')).toBe(true)
|
||||
})
|
||||
|
||||
it('clears the tombstone once the publisher snapshot no longer includes the tab', () => {
|
||||
const tombstones = new Map([['a', 5000]])
|
||||
const result = applyClosedTabTombstones([tab('b')], tombstones, 1000)
|
||||
expect(result.map((t) => t.id)).toEqual(['b'])
|
||||
expect(tombstones.has('a')).toBe(false)
|
||||
})
|
||||
|
||||
it('stops suppressing and clears an expired tombstone even if still present', () => {
|
||||
const tombstones = new Map([['a', 5000]])
|
||||
expect(
|
||||
applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 4999).map((t) => t.id)
|
||||
).toEqual(['b'])
|
||||
expect(tombstones.has('a')).toBe(true)
|
||||
const result = applyClosedTabTombstones([tab('a'), tab('b')], tombstones, 5000)
|
||||
expect(result.map((t) => t.id)).toEqual(['a', 'b'])
|
||||
expect(tombstones.has('a')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,74 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../../platform/haptics', () => ({
|
||||
triggerSelection: vi.fn()
|
||||
}))
|
||||
import type {
|
||||
FileDocState,
|
||||
MarkdownDocState
|
||||
} from '../../files/session-documents/session-document-state'
|
||||
import type { MobileSessionTab } from './mobile-session-tabs'
|
||||
import { isCachedActiveDocumentRetap } from '../../files/session-documents/mobile-session-active-document-retap'
|
||||
|
||||
const markdownTab: MobileSessionTab = {
|
||||
type: 'markdown',
|
||||
id: 'md',
|
||||
title: 'Notes',
|
||||
filePath: '/Notes.md',
|
||||
relativePath: 'Notes.md',
|
||||
isDirty: false,
|
||||
isActive: true,
|
||||
documentVersion: 'v1'
|
||||
}
|
||||
|
||||
const fileTab: MobileSessionTab = {
|
||||
type: 'file',
|
||||
id: 'file',
|
||||
title: 'Main',
|
||||
filePath: '/Main.ts',
|
||||
relativePath: 'Main.ts',
|
||||
isDirty: false,
|
||||
isActive: true
|
||||
}
|
||||
|
||||
const readyMarkdown: MarkdownDocState = {
|
||||
status: 'ready',
|
||||
content: '# Notes',
|
||||
localContent: '# Notes',
|
||||
baseVersion: 'v1',
|
||||
isDirty: false,
|
||||
editable: true
|
||||
}
|
||||
|
||||
describe('isCachedActiveDocumentRetap', () => {
|
||||
it('ignores a retap only while the open markdown or file document is already on screen', () => {
|
||||
const docs = {
|
||||
markdownDocs: new Map<string, MarkdownDocState>([['md', readyMarkdown]]),
|
||||
fileDocs: new Map<string, FileDocState>([
|
||||
['file', { status: 'ready', kind: 'html', content: '<p>Hi</p>' }]
|
||||
])
|
||||
}
|
||||
expect(isCachedActiveDocumentRetap(markdownTab, 'md', docs)).toBe(true)
|
||||
expect(isCachedActiveDocumentRetap(fileTab, 'file', docs)).toBe(true)
|
||||
expect(isCachedActiveDocumentRetap(markdownTab, 'other', docs)).toBe(false)
|
||||
expect(
|
||||
isCachedActiveDocumentRetap(markdownTab, 'md', {
|
||||
...docs,
|
||||
markdownDocs: new Map([['md', { status: 'error', message: 'Missing' }]])
|
||||
})
|
||||
).toBe(false)
|
||||
expect(
|
||||
isCachedActiveDocumentRetap(
|
||||
{
|
||||
type: 'terminal',
|
||||
id: 'term',
|
||||
title: 'Shell',
|
||||
terminal: 'pty-1',
|
||||
isActive: true
|
||||
},
|
||||
'term',
|
||||
docs
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -146,17 +146,6 @@ describe('the page pane hook', () => {
|
||||
expect(switched.map((tab) => tab.id)).toEqual(['second'])
|
||||
})
|
||||
|
||||
it('switches to a pane the host document hands the session already showing', () => {
|
||||
// A notification for the session on top reaches it as URL params, since a second copy is never pushed.
|
||||
bridge.route = { pathname: '/h/host-1' }
|
||||
const tree = render(true)
|
||||
pageUrl.params = { paneKey: `tab-b:${LEAF}` }
|
||||
act(() => {
|
||||
tree.update(createElement(Probe, { terminalsLoaded: true }))
|
||||
})
|
||||
expect(switched.map((tab) => tab.id)).toEqual(['second'])
|
||||
})
|
||||
|
||||
it('switches to the agent row tapped in the host list when the page opened the session itself', () => {
|
||||
// #34235: the shell route stays the host list, so the tapped pane is only in the page URL.
|
||||
bridge.route = { pathname: '/h/host-1' }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useCallback, useRef } from 'react'
|
||||
import { useEffect, useCallback, useRef, useState } from 'react'
|
||||
import { AppState } from 'react-native'
|
||||
import { useFocusEffect } from 'expo-router'
|
||||
import { useMobileDictation } from '../hooks/use-mobile-dictation'
|
||||
@@ -136,9 +136,12 @@ export function useMobileSessionNativeChatDictation(
|
||||
const dictationCanStart = showNativeChat
|
||||
? connState === 'connected' || phoneDictation.ready
|
||||
: canSend
|
||||
// The host's filler switch, kept from its last setup read; on until one says otherwise.
|
||||
const [removeFillerWords, setRemoveFillerWords] = useState(true)
|
||||
const dictation = useMobileDictation({
|
||||
client,
|
||||
enabled: (showNativeChat || canCompose) && dictationEnabled,
|
||||
removeFillerWords,
|
||||
onTranscript: (text) => {
|
||||
// Chat dictation is inserted locally; a terminal's words are typed into it live.
|
||||
if (destination.landsInChat(showNativeChatRef.current)) {
|
||||
@@ -246,6 +249,7 @@ export function useMobileSessionNativeChatDictation(
|
||||
const setup = await fetchDictationSetup(client)
|
||||
if (read === dictationSettingsReadRef.current) {
|
||||
setDictationMode(setup.dictationMode)
|
||||
setRemoveFillerWords(setup.removeFillerWords !== false)
|
||||
setDictationEnabled(!dictationMicHidden(setup))
|
||||
dictationNeedsSetupRef.current = dictationNeedsSetup(setup)
|
||||
}
|
||||
|
||||
@@ -26,29 +26,6 @@ import {
|
||||
BASE
|
||||
} from './use-mobile-structured-agent-options.test-fixture'
|
||||
|
||||
describe('useMobileStructuredAgentOptions post-write refresh', () => {
|
||||
it.each([true, false])(
|
||||
'revalidates an accepted operation with sameFence=%s',
|
||||
async (sameFence) => {
|
||||
const client = optionsClient(queuedReads(FAST_OPTIONS, FAST_OPTIONS_ON))
|
||||
// The reply settles the operation; only the query installs the chat's selection.
|
||||
const { mutate } = recordingMutate(async () =>
|
||||
accepted({ key: 'fastMode', value: 'true', options: {} }, sameFence)
|
||||
)
|
||||
const harness = await mountOptions({ ...BASE, client: client.client, mutate })
|
||||
expect(client.optionReads()).toBe(1)
|
||||
expect(currentValueOf(harness.current().optionSnapshot, 'fastMode')).toBe(false)
|
||||
await act(async () => {
|
||||
await harness.current().setStructuredOption('fastMode', true)
|
||||
})
|
||||
await settle()
|
||||
expect(client.optionReads()).toBe(2)
|
||||
expect(currentValueOf(harness.current().optionSnapshot, 'fastMode')).toBe(true)
|
||||
await harness.unmount()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
describe('useMobileStructuredAgentOptions generation fencing', () => {
|
||||
it('drops an options read a later write superseded', async () => {
|
||||
const stale = deferred<AgentSessionOptionsResult>()
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
import { createElement, useState } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MobileSourceControlContent } from './MobileSourceControlContent'
|
||||
import { MobileSourceControlNextStepBar } from './MobileSourceControlNextStepBar'
|
||||
import type { MobileSourceControlPrimaryAction } from './mobile-source-control-primary-action'
|
||||
|
||||
import type { MobileSourceControlState } from './use-mobile-source-control-state'
|
||||
|
||||
type MobileSourceControlContentState = Omit<MobileSourceControlState, 'primaryActionArgs'> & {
|
||||
primaryAction: MobileSourceControlPrimaryAction
|
||||
}
|
||||
import type { SectionListProps } from 'react-native'
|
||||
import type {
|
||||
MobileBranchEntryView,
|
||||
MobileGitStatusEntryView
|
||||
} from './mobile-source-control-screen-state'
|
||||
|
||||
vi.mock('react-native', () => ({
|
||||
AccessibilityInfo: {
|
||||
isReduceMotionEnabled: async () => false,
|
||||
addEventListener: () => ({ remove: () => {} })
|
||||
},
|
||||
ActivityIndicator: 'ActivityIndicator',
|
||||
Pressable: 'Pressable',
|
||||
ScrollView: 'ScrollView',
|
||||
SectionList: (props: SectionListProps<MobileBranchEntryView | MobileGitStatusEntryView>) =>
|
||||
createElement(
|
||||
'SectionList',
|
||||
{ ...props, ListHeaderComponent: undefined },
|
||||
typeof props.ListHeaderComponent === 'function' ? null : props.ListHeaderComponent,
|
||||
typeof props.ListFooterComponent === 'function'
|
||||
? createElement(props.ListFooterComponent)
|
||||
: props.ListFooterComponent,
|
||||
props.sections.map((section) =>
|
||||
createElement(
|
||||
'Section',
|
||||
{ key: section.key },
|
||||
props.renderSectionHeader?.({ section }),
|
||||
section.data.slice(0, 20).map((item, index) =>
|
||||
createElement(
|
||||
'Row',
|
||||
{ key: item.path },
|
||||
props.renderItem?.({
|
||||
item,
|
||||
index,
|
||||
section,
|
||||
separators: { highlight: noop, unhighlight: noop, updateProps: noop }
|
||||
})
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
),
|
||||
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
|
||||
Text: 'Text',
|
||||
TextInput: 'TextInput',
|
||||
View: 'View'
|
||||
}))
|
||||
vi.mock('expo-clipboard', () => ({ setStringAsync: async () => {} }))
|
||||
// Counts row renders: every file row draws its line stats once.
|
||||
const rowRenders = vi.hoisted(() => ({ count: 0 }))
|
||||
vi.mock('../components/MobileDiffReviewFileSummary', () => ({
|
||||
MobileDiffLineStats: () => {
|
||||
rowRenders.count += 1
|
||||
return null
|
||||
}
|
||||
}))
|
||||
vi.mock('react-native-gesture-handler', async () => {
|
||||
const chain = new Proxy({}, { get: () => () => chain })
|
||||
return {
|
||||
Gesture: { Pan: () => chain },
|
||||
GestureDetector: ({ children }: { children: unknown }) => children
|
||||
}
|
||||
})
|
||||
vi.mock('react-native-reanimated', () => ({
|
||||
default: { View: ({ children }: { children: unknown }) => children },
|
||||
Easing: { bezier: () => () => 0 },
|
||||
ReduceMotion: { Never: 'never' },
|
||||
useAnimatedStyle: () => ({}),
|
||||
useReducedMotion: () => false,
|
||||
useSharedValue: (value: number) => ({ value }),
|
||||
withTiming: (value: number) => value
|
||||
}))
|
||||
vi.mock('../components/ConfirmModal', () => ({ ConfirmModal: () => null }))
|
||||
vi.mock('lucide-react-native', () => ({
|
||||
ArrowDown: 'ArrowDown',
|
||||
ArrowDownUp: 'ArrowDownUp',
|
||||
ArrowUp: 'ArrowUp',
|
||||
Check: 'Check',
|
||||
ChevronDown: 'ChevronDown',
|
||||
ChevronRight: 'ChevronRight',
|
||||
CloudUpload: 'CloudUpload',
|
||||
FileText: 'FileText',
|
||||
GitBranch: 'GitBranch',
|
||||
GitCommitHorizontal: 'GitCommitHorizontal',
|
||||
GitMerge: 'GitMerge',
|
||||
GitPullRequest: 'GitPullRequest',
|
||||
GitPullRequestArrow: 'GitPullRequestArrow',
|
||||
History: 'History',
|
||||
Minus: 'Minus',
|
||||
MoreHorizontal: 'MoreHorizontal',
|
||||
Plus: 'Plus',
|
||||
RefreshCw: 'RefreshCw',
|
||||
Sparkles: 'Sparkles',
|
||||
Trash2: 'Trash2',
|
||||
TriangleAlert: 'TriangleAlert',
|
||||
Undo2: 'Undo2'
|
||||
}))
|
||||
|
||||
const noop = () => {}
|
||||
const unusedAsync = async (): Promise<never> => {
|
||||
throw new Error('unused action')
|
||||
}
|
||||
|
||||
function initialState(): MobileSourceControlContentState {
|
||||
const branchEntries = Array.from({ length: 20 }, (_, index) => ({
|
||||
path: `src/file-${index}.ts`,
|
||||
status: 'modified' as const,
|
||||
added: 3,
|
||||
removed: 1,
|
||||
canOpen: true
|
||||
}))
|
||||
const branchCompareResult = {
|
||||
entries: branchEntries,
|
||||
summary: {
|
||||
status: 'ready' as const,
|
||||
baseRef: 'main',
|
||||
changedFiles: 20,
|
||||
commitsAhead: undefined,
|
||||
errorMessage: undefined
|
||||
}
|
||||
}
|
||||
return {
|
||||
client: null,
|
||||
connState: 'connected',
|
||||
forceReconnect: null,
|
||||
rebaseBaseRef: 'main',
|
||||
refreshing: false,
|
||||
insets: { top: 0, bottom: 0, left: 0, right: 0 },
|
||||
router: {
|
||||
back: noop,
|
||||
push: noop,
|
||||
replace: noop,
|
||||
navigate: noop,
|
||||
dismiss: noop,
|
||||
dismissAll: noop,
|
||||
dismissTo: noop,
|
||||
prefetch: noop,
|
||||
canGoBack: () => false,
|
||||
canDismiss: () => false,
|
||||
setParams: noop,
|
||||
reload: noop
|
||||
},
|
||||
setRootRef: noop,
|
||||
worktreeLabel: 'fixture',
|
||||
screenState: { kind: 'loading' },
|
||||
branchCompareState: { kind: 'ready', result: branchCompareResult },
|
||||
busyAction: null,
|
||||
commitMessage: '',
|
||||
setCommitMessage: noop,
|
||||
generatingMessage: false,
|
||||
showBranchPicker: false,
|
||||
setShowBranchPicker: noop,
|
||||
localBranches: null,
|
||||
createdPrUrl: null,
|
||||
setCreatedPrUrl: noop,
|
||||
createdPrWarning: null,
|
||||
setCreatedPrWarning: noop,
|
||||
discardTarget: null,
|
||||
setDiscardTarget: noop,
|
||||
showActionSheet: false,
|
||||
setShowActionSheet: noop,
|
||||
actionError: null,
|
||||
commitFailureRecovery: null,
|
||||
commitFailureRecoveryAction: {
|
||||
summary: null,
|
||||
hasDetails: false,
|
||||
launching: false,
|
||||
availability: 'available',
|
||||
launchError: null,
|
||||
launchWarning: null,
|
||||
launchSuccess: null,
|
||||
undeliveredPrompt: null,
|
||||
launch: unusedAsync
|
||||
},
|
||||
keyboardLift: 0,
|
||||
status: null,
|
||||
sections: [],
|
||||
branchCompareResult,
|
||||
branchEntries,
|
||||
shouldShowBranchCompareSection: true,
|
||||
hasVisibleChanges: true,
|
||||
stageablePaths: [],
|
||||
unstageablePaths: [],
|
||||
stagedCount: 1,
|
||||
unstagedCount: 0,
|
||||
branchLabel: 'fixture',
|
||||
upstreamKnown: false,
|
||||
primaryAction: {
|
||||
kind: 'commit',
|
||||
label: 'Commit',
|
||||
accessibilityLabel: 'Commit',
|
||||
accessibilityHint: '',
|
||||
disabled: false,
|
||||
loading: false,
|
||||
onPress: noop
|
||||
},
|
||||
createPrAction: {
|
||||
visible: false,
|
||||
label: 'Create Pull Request',
|
||||
reviewLabel: 'pull request',
|
||||
disabled: true,
|
||||
loading: false,
|
||||
pushFirst: false,
|
||||
onPress: noop
|
||||
},
|
||||
loadStatus: unusedAsync,
|
||||
openDiffForFile: noop,
|
||||
runGitAction: unusedAsync,
|
||||
stageAll: unusedAsync,
|
||||
unstageAll: unusedAsync,
|
||||
commit: unusedAsync,
|
||||
generateCommitMessage: unusedAsync,
|
||||
cancelGenerateCommitMessage: noop,
|
||||
createPr: unusedAsync,
|
||||
openBranchPicker: noop,
|
||||
openHistory: noop,
|
||||
checkoutBranch: unusedAsync,
|
||||
abortConflictOperation: unusedAsync,
|
||||
resolveConflict: unusedAsync,
|
||||
completeMerge: unusedAsync,
|
||||
runActionSheetCommit: unusedAsync,
|
||||
runActionSheetCommitSequence: unusedAsync,
|
||||
runActionSheetCommitSync: unusedAsync,
|
||||
runActionSheetGitSequence: unusedAsync,
|
||||
runActionSheetGitSync: unusedAsync,
|
||||
runActionSheetRebase: unusedAsync
|
||||
}
|
||||
}
|
||||
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
const controls: { patch: ((patch: Partial<MobileSourceControlContentState>) => void) | null } = {
|
||||
patch: null
|
||||
}
|
||||
|
||||
function Fixture({ initial }: { initial: MobileSourceControlContentState }) {
|
||||
const [state, setState] = useState(initial)
|
||||
controls.patch = (patch) => setState((previous) => ({ ...previous, ...patch }))
|
||||
const liveState = {
|
||||
...state,
|
||||
setCommitMessage: (next: string | ((previous: string) => string)) =>
|
||||
setState((previous) => ({
|
||||
...previous,
|
||||
commitMessage: typeof next === 'function' ? next(previous.commitMessage) : next
|
||||
}))
|
||||
}
|
||||
// Laid out as the panel does: the commit box lives in the bar beside the list.
|
||||
return createElement(
|
||||
'View',
|
||||
null,
|
||||
createElement(MobileSourceControlContent, {
|
||||
state: liveState,
|
||||
stageAllInBar: state.primaryAction.kind === 'stage',
|
||||
bottomInset: 0,
|
||||
onOpenCommits: noop
|
||||
}),
|
||||
createElement(MobileSourceControlNextStepBar, {
|
||||
view: { kind: 'composer' },
|
||||
notice: null,
|
||||
agentNotice: null,
|
||||
mergeConfirm: null,
|
||||
composer: liveState,
|
||||
primaryAction: state.primaryAction,
|
||||
keyboardLift: state.keyboardLift,
|
||||
bottomInset: 0,
|
||||
onHeightChange: noop
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function render(initial = initialState()) {
|
||||
act(() => {
|
||||
renderer = create(createElement(Fixture, { initial }))
|
||||
})
|
||||
}
|
||||
function patch(values: Partial<MobileSourceControlContentState>) {
|
||||
act(() => {
|
||||
controls.patch?.(values)
|
||||
})
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
controls.patch = null
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('next-step bar and the keyboard', () => {
|
||||
function input() {
|
||||
return renderer?.root.findAll((node) => String(node.type) === 'TextInput')[0] ?? null
|
||||
}
|
||||
|
||||
it('rides the keyboard for its own commit box and steps aside for any other field', () => {
|
||||
render()
|
||||
// Another field (a PR comment) raised the keyboard: the bar must not cover it.
|
||||
patch({ keyboardLift: 300 })
|
||||
expect(input()).toBeNull()
|
||||
patch({ keyboardLift: 0 })
|
||||
act(() => {
|
||||
const onFocus = input()?.props.onFocus
|
||||
if (typeof onFocus !== 'function') {
|
||||
throw new Error('missing focus handler')
|
||||
}
|
||||
onFocus()
|
||||
})
|
||||
patch({ keyboardLift: 300 })
|
||||
expect(input()).not.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,32 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildMobileDiffLines } from './mobile-diff-lines'
|
||||
|
||||
describe('buildMobileDiffLines', () => {
|
||||
it('marks added, deleted, and unchanged lines', () => {
|
||||
const result = buildMobileDiffLines('one\ntwo\nthree\n', 'one\nTWO\nthree\nfour\n')
|
||||
|
||||
expect(result.truncated).toBe(false)
|
||||
expect(result.lines).toEqual([
|
||||
{ kind: 'context', text: 'one', oldLineNumber: 1, newLineNumber: 1 },
|
||||
{ kind: 'delete', text: 'two', oldLineNumber: 2 },
|
||||
{ kind: 'add', text: 'TWO', newLineNumber: 2 },
|
||||
{ kind: 'context', text: 'three', oldLineNumber: 3, newLineNumber: 3 },
|
||||
{ kind: 'add', text: 'four', newLineNumber: 4 }
|
||||
])
|
||||
})
|
||||
|
||||
it('hides a re-indent unless whitespace is shown, like desktop', () => {
|
||||
const original = 'if (a) {\n run()\n}\n'
|
||||
const modified = 'if (a) {\n run()\n}\n'
|
||||
const kinds = (lines: { kind: string }[]) => lines.map((line) => line.kind)
|
||||
expect(
|
||||
kinds(buildMobileDiffLines(original, modified, { ignoreTrimWhitespace: true }).lines)
|
||||
).toEqual(['context', 'context', 'context'])
|
||||
expect(kinds(buildMobileDiffLines(original, modified).lines)).toEqual([
|
||||
'context',
|
||||
'delete',
|
||||
'add',
|
||||
'context'
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||
import type { PRComment } from '../../../../src/shared/github/comment-types'
|
||||
import type { GitHubWorkItemDetails } from '../../../../src/shared/github/work-item-types'
|
||||
import { buildMobileDiffReviewQueue } from './mobile-diff-review-queue'
|
||||
import {
|
||||
applyMobileDiffReviewGitHubViewed,
|
||||
buildMobileDiffReviewGitHub,
|
||||
canCommentOnGitHub
|
||||
} from './mobile-diff-review-github'
|
||||
import { buildMobileDiffReviewGitHub, canCommentOnGitHub } from './mobile-diff-review-github'
|
||||
|
||||
function comment(overrides: Partial<PRComment>): PRComment {
|
||||
return {
|
||||
@@ -79,35 +75,6 @@ describe('the diff screen’s GitHub pull request', () => {
|
||||
expect(threads?.get(12)?.[0]?.replies.map((reply) => reply.id)).toEqual([2])
|
||||
})
|
||||
|
||||
it('takes viewed state for the PR’s files from GitHub', () => {
|
||||
const github = buildMobileDiffReviewGitHub({
|
||||
prNumber: 1,
|
||||
prRepo: null,
|
||||
localHeadOid: 'head',
|
||||
details: details({})
|
||||
})
|
||||
expect(applyMobileDiffReviewGitHubViewed(branchItem, github)[0]).toMatchObject({
|
||||
isReviewed: false,
|
||||
changedSinceReview: true
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves viewed state on the phone when GitHub sent none for the file', () => {
|
||||
const github = buildMobileDiffReviewGitHub({
|
||||
prNumber: 1,
|
||||
prRepo: null,
|
||||
localHeadOid: 'head',
|
||||
details: details({
|
||||
pullRequestId: undefined,
|
||||
files: [
|
||||
{ path: 'src/a.ts', status: 'modified', additions: 2, deletions: 1, isBinary: false }
|
||||
]
|
||||
})
|
||||
})
|
||||
const viewedLocally = branchItem.map((item) => ({ ...item, isReviewed: true }))
|
||||
expect(applyMobileDiffReviewGitHubViewed(viewedLocally, github)[0]?.isReviewed).toBe(true)
|
||||
})
|
||||
|
||||
it('offers Comment on GitHub only on commentable lines while the branch is at the PR head', () => {
|
||||
const atHead = buildMobileDiffReviewGitHub({
|
||||
prNumber: 1,
|
||||
|
||||
@@ -39,23 +39,6 @@ function comment(overrides: Partial<DiffComment> & Pick<DiffComment, 'id'>): Dif
|
||||
}
|
||||
|
||||
describe('mobile diff review queue', () => {
|
||||
it('leaves out a status entry whose staging area it does not know', () => {
|
||||
const queue = buildMobileDiffReviewQueue({
|
||||
worktreeId: 'wt-1',
|
||||
statusEntries: [
|
||||
statusEntry({ path: 'placed.ts', area: 'unstaged' }),
|
||||
statusEntry({ path: 'placeless.ts', area: undefined })
|
||||
],
|
||||
branchEntries: [],
|
||||
branchHeadOid: 'head',
|
||||
branchMergeBase: 'base',
|
||||
comments: [],
|
||||
reviewState: emptyReviewState
|
||||
})
|
||||
|
||||
expect(queue.map((item) => item.filePath)).toEqual(['placed.ts'])
|
||||
})
|
||||
|
||||
it('keeps scope, rename, and source matching when notes share a path', () => {
|
||||
const queue = buildMobileDiffReviewQueue({
|
||||
worktreeId: 'wt-1',
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
moveMobileDiffReviewSelection,
|
||||
resolveMobileDiffReviewSelection,
|
||||
selectMobileDiffReviewIndex
|
||||
} from './mobile-diff-review-selection'
|
||||
|
||||
const queue = (...keys: string[]) => keys.map((key) => ({ key }))
|
||||
|
||||
describe('mobile diff review selection', () => {
|
||||
it('follows the open file when files before it leave the queue', () => {
|
||||
const selection = selectMobileDiffReviewIndex(queue('a', 'b', 'c', 'd'), 1)
|
||||
expect(resolveMobileDiffReviewSelection(queue('b', 'c', 'd'), selection)).toBe(0)
|
||||
})
|
||||
|
||||
it('lands on the file that took its place when the open file leaves', () => {
|
||||
const selection = selectMobileDiffReviewIndex(queue('a', 'b', 'c'), 1)
|
||||
expect(resolveMobileDiffReviewSelection(queue('a', 'c'), selection)).toBe(1)
|
||||
const last = selectMobileDiffReviewIndex(queue('a', 'b', 'c'), 2)
|
||||
expect(resolveMobileDiffReviewSelection(queue('a', 'b'), last)).toBe(1)
|
||||
})
|
||||
|
||||
it('wraps next and previous', () => {
|
||||
const files = queue('a', 'b', 'c')
|
||||
const last = selectMobileDiffReviewIndex(files, 2)
|
||||
expect(moveMobileDiffReviewSelection(files, last, 'next').key).toBe('a')
|
||||
expect(
|
||||
moveMobileDiffReviewSelection(files, selectMobileDiffReviewIndex(files, 0), 'previous').key
|
||||
).toBe('c')
|
||||
})
|
||||
})
|
||||
@@ -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,49 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildUpdatePRTitleParams,
|
||||
canEditPRTitle,
|
||||
createPrTextEditOwnership
|
||||
} from './pr-title-edit'
|
||||
|
||||
describe('canEditPRTitle', () => {
|
||||
it('allows editing on open and draft PRs', () => {
|
||||
expect(canEditPRTitle('open')).toBe(true)
|
||||
expect(canEditPRTitle('draft')).toBe(true)
|
||||
})
|
||||
it('disallows editing on closed/merged/unknown', () => {
|
||||
expect(canEditPRTitle('closed')).toBe(false)
|
||||
expect(canEditPRTitle('merged')).toBe(false)
|
||||
expect(canEditPRTitle(null)).toBe(false)
|
||||
expect(canEditPRTitle(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildUpdatePRTitleParams', () => {
|
||||
it('returns null for empty/unchanged drafts (no host round-trip)', () => {
|
||||
expect(buildUpdatePRTitleParams(7, '', 'Current')).toBeNull()
|
||||
expect(buildUpdatePRTitleParams(7, ' ', 'Current')).toBeNull()
|
||||
expect(buildUpdatePRTitleParams(7, ' Current ', 'Current')).toBeNull()
|
||||
})
|
||||
it('trims the draft and carries the PR number', () => {
|
||||
expect(buildUpdatePRTitleParams(7, ' New title ', 'Current')).toEqual({
|
||||
prNumber: 7,
|
||||
title: 'New title'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('createPrTextEditOwnership', () => {
|
||||
it('keeps a newer edit open when an older Save succeeds after its deferred reread', async () => {
|
||||
const ownership = createPrTextEditOwnership()
|
||||
// First Save's write succeeded; its reread is still pending, so Save has not resolved.
|
||||
const firstReread = Promise.withResolvers<boolean>()
|
||||
const first = ownership.save(() => firstReread.promise)
|
||||
// The user edits again and the newer Save fails.
|
||||
ownership.touch()
|
||||
await expect(ownership.save(async () => false)).resolves.toBe(false)
|
||||
firstReread.resolve(true)
|
||||
await expect(first).resolves.toBe(false)
|
||||
// With no newer edit, a successful Save still closes the editor.
|
||||
await expect(ownership.save(async () => true)).resolves.toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes'
|
||||
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
|
||||
|
||||
import { createWorktreeWithNameRetry } from './worktree-create-retry'
|
||||
|
||||
type Attempt = { method: string; params: unknown }
|
||||
|
||||
function scriptedClient(
|
||||
outcomes: ({ id: string; displayName?: string; warning?: string } | { errorMessage: string })[],
|
||||
attempts: Attempt[]
|
||||
): RpcClient {
|
||||
let call = 0
|
||||
const client = new FakeSession('connected')
|
||||
client.sendRequest.mockImplementation(async (method: string, params?: unknown) => {
|
||||
attempts.push({ method, params: params ?? {} })
|
||||
const outcome = outcomes[Math.min(call, outcomes.length - 1)]!
|
||||
call += 1
|
||||
if ('errorMessage' in outcome) {
|
||||
return {
|
||||
id: '1',
|
||||
ok: false,
|
||||
error: { code: 'x', message: outcome.errorMessage },
|
||||
_meta: { runtimeId: 'r' }
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: '1',
|
||||
ok: true,
|
||||
result: {
|
||||
worktree: {
|
||||
id: outcome.id,
|
||||
...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {})
|
||||
},
|
||||
...(outcome.warning !== undefined ? { warning: outcome.warning } : {})
|
||||
},
|
||||
_meta: { runtimeId: 'r' }
|
||||
}
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
describe('createWorktreeWithNameRetry', () => {
|
||||
it('falls back to the client candidate when an older host omits displayName', async () => {
|
||||
const attempts: Attempt[] = []
|
||||
const client = scriptedClient(
|
||||
[{ errorMessage: 'already exists locally' }, { id: 'wt-legacy' }],
|
||||
attempts
|
||||
)
|
||||
|
||||
await expect(
|
||||
createWorktreeWithNameRetry({
|
||||
client,
|
||||
baseName: 'topic',
|
||||
buildParams: (name) => ({ repo: 'id:r', name }),
|
||||
worktreeCreateIdempotency: false
|
||||
})
|
||||
).resolves.toEqual({ worktreeId: 'wt-legacy', name: 'topic-2' })
|
||||
})
|
||||
})
|
||||
@@ -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[] = []
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveTerminalPaneHandles, terminalPaneViewport } from './mobile-terminal-pane-layout'
|
||||
|
||||
describe('mobile terminal split selection', () => {
|
||||
it('keeps pane order when focus moves and collapses a closed companion', () => {
|
||||
expect(resolveTerminalPaneHandles('b', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['a', 'b'])
|
||||
expect(resolveTerminalPaneHandles('a', ['a', 'b'], ['a', 'c'])).toEqual(['a'])
|
||||
expect(resolveTerminalPaneHandles('c', ['a', 'b'], ['a', 'b', 'c'])).toEqual(['c', 'a'])
|
||||
expect(resolveTerminalPaneHandles(null, ['a', 'b'], ['a', 'b'])).toEqual([])
|
||||
})
|
||||
it('never shares geometry ownership across terminal handles', () => {
|
||||
const states = new Map()
|
||||
const a = terminalPaneViewport(states, 'a')
|
||||
const b = terminalPaneViewport(states, 'b')
|
||||
a.viewportRef.current = { cols: 40, rows: 30 }
|
||||
expect(b.viewportRef.current).toBeNull()
|
||||
expect(terminalPaneViewport(states, 'a')).toBe(a)
|
||||
})
|
||||
})
|
||||
@@ -1,61 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { RelayReconnectController } from './mobile-relay-reconnect-controller'
|
||||
|
||||
vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }))
|
||||
vi.mock('expo-crypto', () => ({
|
||||
getRandomBytes: (length: number) => new Uint8Array(length)
|
||||
}))
|
||||
|
||||
describe('relay reconnect controller', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('lifts the fresh-credential gate when a durable bundle carries a new version', () => {
|
||||
const onRetry = vi.fn()
|
||||
const reconnect = createController(onRetry)
|
||||
|
||||
reconnect.recordRejectedCredential(2)
|
||||
reconnect.armCredentialReprobe()
|
||||
expect(reconnect.shouldDefer()).toBe(true)
|
||||
|
||||
reconnect.acceptFreshCredential(2)
|
||||
expect(reconnect.shouldDefer()).toBe(true)
|
||||
|
||||
reconnect.acceptFreshCredential(3)
|
||||
expect(reconnect.shouldDefer()).toBe(false)
|
||||
expect(
|
||||
reconnect.eligibleCredentials(
|
||||
{ token: 'fresh', version: 3, expiresAt: Number.MAX_SAFE_INTEGER },
|
||||
null
|
||||
)
|
||||
).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
function createController(
|
||||
onRetry: () => void,
|
||||
reportFailureCount: (count: number) => void = () => {},
|
||||
reportPairingRejected: (rejected: boolean) => void = () => {}
|
||||
): RelayReconnectController {
|
||||
const controller = new RelayReconnectController(
|
||||
{
|
||||
now: Date.now,
|
||||
randomBytes: () => new Uint8Array([128, 0]),
|
||||
setTimer: (handler, ms) => setTimeout(handler, ms),
|
||||
clearTimer: (handle) => clearTimeout(handle)
|
||||
},
|
||||
onRetry
|
||||
)
|
||||
controller.reportRecoveryTo({
|
||||
setRecoveryAttempt: reportFailureCount,
|
||||
setPairingRejected: reportPairingRejected,
|
||||
setRelayHostReachability: () => {}
|
||||
})
|
||||
return controller
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../encryption/mobile-e2ee-v2-client-session', () => ({
|
||||
MobileE2EEV2ClientSession: { create: () => ({}) }
|
||||
}))
|
||||
|
||||
vi.mock('../encryption/mobile-e2ee-v2-physical-channel', () => ({
|
||||
MobileE2EEAuthenticationError: class extends Error {},
|
||||
MobileE2EEV2PhysicalChannel: class {}
|
||||
}))
|
||||
|
||||
import { MOBILE_RELAY_CLOSE_CODE } from '../../../../src/shared/remote-runtime/relay/mobile-relay-close-codes'
|
||||
import { RelayOuterError } from '../encryption/mobile-relay-e2ee-link'
|
||||
import { RelayHostReachabilityLatch } from './relay-host-reachability-latch'
|
||||
|
||||
const closed = (code: number) => new RelayOuterError(code)
|
||||
const OFFLINE = MOBILE_RELAY_CLOSE_CODE.HOST_OFFLINE
|
||||
|
||||
describe('RelayHostReachabilityLatch', () => {
|
||||
// A 4408 between two 4404s is not evidence the desktop came back.
|
||||
|
||||
it('reports an asserted verdict immediately and pins it against later failures', () => {
|
||||
const latch = new RelayHostReachabilityLatch()
|
||||
const reporter = vi.fn()
|
||||
latch.reportTo(reporter)
|
||||
|
||||
latch.assert('signed-out')
|
||||
expect(latch.current()).toBe('signed-out')
|
||||
|
||||
latch.record(closed(OFFLINE))
|
||||
latch.record(closed(OFFLINE))
|
||||
expect(latch.current()).toBe('signed-out')
|
||||
expect(reporter.mock.calls.map(([value]) => value)).toEqual(['connecting', 'signed-out'])
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
|
||||
@@ -374,6 +374,12 @@ Run it as a loop: read the `provisionTranscript` in the failed result, fix the s
|
||||
`ok` is `true`. Do not wait for the user to paste errors. How to read the transcript is in
|
||||
`references/failure-modes.md`.
|
||||
|
||||
Once a workspace runs on the environment, check the environment itself from a terminal inside it:
|
||||
`ORCA vm env doctor --json` reports required CLIs (git plus what the repo manifests imply), agent
|
||||
CLIs and their sign-in, Git fetch and a dry-run push, the `orca.yaml` setup script, and free disk.
|
||||
Add `--run-setup` to re-run `scripts.setup` and gate on its exit code. Loop on it the same way: fix
|
||||
`orca.yaml` or the image, re-run, until no check fails and every `warn` is resolved or explained.
|
||||
|
||||
The self-test sees only what the scripts print, so confirm separately that state holds an
|
||||
**authenticated** `snapshotId` and that `destroy` is implemented and tested. With `destroy: none`
|
||||
the self-test tears nothing down and you must clean up by hand.
|
||||
|
||||
@@ -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",
|
||||
@@ -2170,6 +2158,12 @@ const ORCA_PER_WORKSPACE_ENV_MARKDOWN = [
|
||||
"`ok` is `true`. Do not wait for the user to paste errors. How to read the transcript is in",
|
||||
"`references/failure-modes.md`.",
|
||||
"",
|
||||
"Once a workspace runs on the environment, check the environment itself from a terminal inside it:",
|
||||
"`ORCA vm env doctor --json` reports required CLIs (git plus what the repo manifests imply), agent",
|
||||
"CLIs and their sign-in, Git fetch and a dry-run push, the `orca.yaml` setup script, and free disk.",
|
||||
"Add `--run-setup` to re-run `scripts.setup` and gate on its exit code. Loop on it the same way: fix",
|
||||
"`orca.yaml` or the image, re-run, until no check fails and every `warn` is resolved or explained.",
|
||||
"",
|
||||
"The self-test sees only what the scripts print, so confirm separately that state holds an",
|
||||
"**authenticated** `snapshotId` and that `destroy` is implemented and tested. With `destroy: none`",
|
||||
"the self-test tears nothing down and you must clean up by hand.",
|
||||
@@ -3971,7 +3965,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 +4122,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 {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { resolve } from 'node:path'
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import {
|
||||
formatEnvironmentDoctorChecks,
|
||||
type EnvironmentDoctorResult
|
||||
} from '../../shared/environment-doctor-types'
|
||||
import { runEnvironmentDoctor } from '../../main/environment-doctor/environment-doctor'
|
||||
import { createHostEnvironmentDoctorDeps } from '../../main/environment-doctor/environment-doctor-host'
|
||||
|
||||
export const VM_ENV_HANDLERS: Record<string, CommandHandler> = {
|
||||
'vm env doctor': async ({ flags, cwd, json }) => {
|
||||
const pathFlag = flags.get('path')
|
||||
const worktreePath = resolve(cwd, typeof pathFlag === 'string' && pathFlag ? pathFlag : '.')
|
||||
const result = await runEnvironmentDoctor(
|
||||
{ worktreePath, runSetup: flags.get('run-setup') === true },
|
||||
createHostEnvironmentDoctorDeps()
|
||||
)
|
||||
console.log(json ? JSON.stringify(result, null, 2) : formatEnvironmentDoctorResult(result))
|
||||
if (!result.ok) {
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatEnvironmentDoctorResult(result: EnvironmentDoctorResult): string {
|
||||
const counts = { pass: 0, warn: 0, fail: 0 }
|
||||
for (const check of result.checks) {
|
||||
counts[check.status] += 1
|
||||
}
|
||||
const lines = [`path: ${result.worktreePath}`, ...formatEnvironmentDoctorChecks(result.checks)]
|
||||
lines.push(`${counts.pass} passed, ${counts.warn} warnings, ${counts.fail} failed`)
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -35,8 +35,8 @@ export const HOST_HANDLER_GROUPS: readonly HandlerGroup[] = [
|
||||
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
|
||||
name: 'vm-env',
|
||||
keys: ['vm env doctor'],
|
||||
load: async () => (await import('./handlers/vm-env.js')).VM_ENV_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,8 +77,8 @@ 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',
|
||||
' vm env doctor Check that this environment can run agents',
|
||||
'',
|
||||
'Automations:',
|
||||
' automations list List scheduled Orca 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
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user