diff --git a/.github/workflows/zcode-transcript-contract.yml b/.github/workflows/zcode-transcript-contract.yml index 859a6ec9823..c8272bc1e1e 100644 --- a/.github/workflows/zcode-transcript-contract.yml +++ b/.github/workflows/zcode-transcript-contract.yml @@ -41,4 +41,4 @@ jobs: bun-version-file: config/.bun-version no-cache: true - name: Verify SQLite ordering, legacy readers, and host routing - run: pnpm test src/main/native-chat/transcript-zcode.test.ts src/main/native-chat/transcript-opencode.test.ts src/main/native-chat/transcript-opencode-sqlite-query.test.ts src/main/native-chat/transcript-opencode2-sqlite.test.ts src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts src/main/native-chat/transcript-opencode-read-bounds.test.ts src/main/native-chat/transcript-opencode-subscribe.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/structured-agent-session-transcript-order.test.ts + run: pnpm test src/main/native-chat/transcript-zcode.test.ts src/main/native-chat/transcript-opencode-sqlite-query.test.ts src/main/native-chat/transcript-opencode-read-bounds.test.ts src/main/ai-vault/scanners/zcode/session-scanner-zcode.test.ts src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.test.ts src/shared/native-chat/transcript/native-chat-transcript-projection.test.ts src/renderer/src/components/native-chat/structured-agent-session-transcript-order.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 65a5922bf0b..6b272e2efc9 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -16,9 +16,7 @@ 1 test-no-in-test-import-actual:src/main/linear/client.test.ts 1 test-no-in-test-import-actual:src/main/linear/linear-description-images.test.ts 1 test-no-in-test-import-actual:src/main/linear/linear-workspace-registry.test.ts -1 test-no-in-test-import-actual:src/main/node-runtime/pinned-runtime-materializer.test.ts 1 test-no-in-test-import-actual:src/main/omp/omp-session-cwd-lookup.test.ts -6 test-no-in-test-import-actual:src/main/opencode/hook-service-legacy-acl.test.ts 1 test-no-in-test-import-actual:src/main/orcad/electron-serve-browser-process.test.ts 1 test-no-in-test-import-actual:src/main/orcad/electron-serve-provider-selection.test.ts 1 test-no-in-test-import-actual:src/main/providers/local-pty/local-pty-provider-foreground-process.test.ts @@ -70,7 +68,6 @@ 1 test-no-polling-loop:src/main/ipc/worktrees/creation/worktree-base-directory-poller-marker-fanout.test.ts 2 test-no-polling-loop:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts 1 test-no-polling-loop:src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts -1 test-no-polling-loop:src/main/native-chat/transcript-watch.test.ts 1 test-no-polling-loop:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 1 test-no-polling-loop:src/main/provider-process/provider-process-supervisor.integration.test.ts 1 test-no-polling-loop:src/main/providers/startup-line-typed-length.live-shell.test.ts @@ -264,12 +261,8 @@ 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-restart-cap.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-target-reconcile.test.ts -1 test-no-real-time-wait:src/main/native-chat/transcript-opencode2-sqlite.test.ts 1 test-no-real-time-wait:src/main/native-chat/transcript-watch-error.test.ts -11 test-no-real-time-wait:src/main/native-chat/transcript-watch.test.ts -1 test-no-real-time-wait:src/main/opencode/hook-plugin-legacy-tui-ownership.test.ts 6 test-no-real-time-wait:src/main/opencode/hook-plugin-module-contract.test.ts -1 test-no-real-time-wait:src/main/opencode/hook-plugin-opencode2-tui-ownership.test.ts 1 test-no-real-time-wait:src/main/opencode/opencode-startup-prompt-source.test.ts 1 test-no-real-time-wait:src/main/orcad/orcad-bundled-runtime.integration.test.ts 1 test-no-real-time-wait:src/main/orcad/orcad-daemon-teardown-linux.test.ts @@ -661,10 +654,8 @@ 4 test-no-wall-clock:src/main/managed-server/install/remote-node-runtime-store-lock-host-release.test.ts 3 test-no-wall-clock:src/main/managed-server/install/remote-node-runtime-store-windows.test.ts 1 test-no-wall-clock:src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts -1 test-no-wall-clock:src/main/native-chat/structured-chat-naming.test.ts 1 test-no-wall-clock:src/main/native-chat/transcript-watch-inplace-drain-race.test.ts -2 test-no-wall-clock:src/main/native-chat/transcript-watch.test.ts -10 test-no-wall-clock:src/main/observability/bundle.test.ts +1 test-no-wall-clock:src/main/observability/bundle.test.ts 1 test-no-wall-clock:src/main/opencode/opencode-launch-model-context-supervision.test.ts 1 test-no-wall-clock:src/main/opencode/overlay-dir-gc.test.ts 10 test-no-wall-clock:src/main/orca-profiles/profile-cloud-auth-characterization.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 9dc4b85fad5..f7dc441d673 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -423,55 +423,22 @@ "id": "native-chat.transcript-consumed-boundary", "title": "Transcript replacement remains visible when it races message publication", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "native-chat", "layer": "host-file-reader-and-renderer", "surfaces": ["native chat live transcript"], "platforms": ["macos", "linux", "windows"], "providers": ["local", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Real local JSONL files exercise the shared host reader with Claude records; hidden Electron proof traverses actual host IPC and chat rendering. No physical remote or Windows/Linux deployment claim.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "Audit1662 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real local JSONL files exercise the shared host reader with Claude records; hidden Electron proof traverses actual host IPC and chat rendering. No physical remote or Windows/Linux deployment claim.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/37524761640"], "invariant": "A retained transcript cursor fingerprint contains only bytes actually consumed at that cursor. A larger in-place rewrite during publication must be delivered, and subsequent ordinary appends arrive once. Closing or failing a test leaves no active watcher.", "oracle": "Synchronous larger rewrites during append, initial snapshot and replacement snapshot callbacks deliver new exactly once, followed by followup exactly once. A 4 MiB read retains an independent 64-byte backing allocation. Hidden Electron reproduces the same ordering at snapshot IPC publication and asserts the new rendered text replaces the old conversation.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/native-chat/transcript-watch-inplace-drain-race.test.ts src/main/native-chat/transcript-file-version.test.ts src/main/native-chat/transcript-watch.test.ts --maxWorkers=2", - "ORCA_BACKGROUND_LAUNCH=1 pnpm run test:e2e tests/e2e/native-chat-inplace-drain-race.spec.ts --workers=1" - ], - "testFiles": [ - "src/main/native-chat/transcript-watch-inplace-drain-race.test.ts", - "src/main/native-chat/transcript-file-version.test.ts", - "src/main/native-chat/transcript-watch.test.ts", - "tests/e2e/native-chat-inplace-drain-race.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/native-chat/transcript-watch-inplace-drain-race.test.ts", - "assertions": ["delivers a larger rewrite while publishing a completed %s"] - }, - { - "file": "src/main/native-chat/transcript-file-version.test.ts", - "assertions": ["owns only the final 64 bytes of a large read"] - }, - { - "file": "tests/e2e/native-chat-inplace-drain-race.spec.ts", - "assertions": [ - "renders a larger transcript rewrite during snapshot publication, then ordinary appends" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-10-06", - "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/native-chat/transcript-watch-inplace-drain-race.test.ts src/main/native-chat/transcript-file-version.test.ts src/main/native-chat/transcript-watch.test.ts --maxWorkers=2", - "result": "passed", - "durationSeconds": 2.85, - "summary": "32 tests in three files pass, including all three publication modes, replacement sizes, partial records and watcher teardown." - } - ], + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 30, "scope": "Focused local unit command; CI/platform soak not established." @@ -489,6 +456,7 @@ "evidence": "At most 64 owned, unpooled bytes per cursor. Fingerprint capture reuses already-read chunks and removes the post-publication filesystem read; no new timers, polls or subprocesses." }, "knownGaps": [ + "Audit1662 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Physical SSH/WSL/runtime hosts and native Linux/Windows remain unverified.", "This gate targets rewrites during publication, not atomic snapshots of arbitrary concurrent multi-chunk file overwrites." ], diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index da3f8c08cd0..4d3a23e4241 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -2978,22 +2978,14 @@ "src/main/native-chat/native-chat-inline-visuals-setting.test.ts": 751, "src/main/native-chat/native-chat-scratch-folder-migration.test.ts": 109, "src/main/native-chat/native-chat-visual-file-read.test.ts": 98, - "src/main/native-chat/native-chat-visuals-delivery.test.ts": 575, "src/main/native-chat/native-chat-visuals-sweep.test.ts": 123, "src/main/native-chat/session-file-resolver-wsl-scan-gate.test.ts": 156, - "src/main/native-chat/session-file-resolver-wsl.test.ts": 179, "src/main/native-chat/session-file-resolver.test.ts": 245, "src/main/native-chat/ssh-transcript-path.test.ts": 48, - "src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts": 2464, "src/main/native-chat/structured-agent-command-guest-path.test.ts": 128, "src/main/native-chat/structured-agent-command-resolution-wsl-host.test.ts": 108, "src/main/native-chat/structured-agent-command-resolution.test.ts": 223, "src/main/native-chat/structured-agent-configured-args.test.ts": 191, - "src/main/native-chat/structured-agent-session-history-adoption.test.ts": 285, - "src/main/native-chat/structured-agent-session-source-admission.test.ts": 1104, - "src/main/native-chat/structured-chat-naming-execution.test.ts": 6592, - "src/main/native-chat/structured-chat-naming-publication.test.ts": 5437, - "src/main/native-chat/structured-chat-naming.test.ts": 5203, "src/main/native-chat/subagent-entry-id-bounds.test.ts": 42, "src/main/native-chat/transcript-claude-read-image.test.ts": 389, "src/main/native-chat/transcript-file-version.test.ts": 121, @@ -3006,23 +2998,16 @@ "src/main/native-chat/transcript-line-decoders-claude-stop-hook.test.ts": 211, "src/main/native-chat/transcript-line-decoders.grok.test.ts": 283, "src/main/native-chat/transcript-line-decoders.omp.test.ts": 297, - "src/main/native-chat/transcript-opencode-database.test.ts": 128, "src/main/native-chat/transcript-opencode-read-bounds.test.ts": 426, - "src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts": 2048, "src/main/native-chat/transcript-opencode-sqlite-query.test.ts": 886, - "src/main/native-chat/transcript-opencode-subscribe.test.ts": 5546, - "src/main/native-chat/transcript-opencode.test.ts": 392, - "src/main/native-chat/transcript-opencode2-sqlite.test.ts": 1576, "src/main/native-chat/transcript-read-cache-refusal-recovery.test.ts": 536, "src/main/native-chat/transcript-read-cache-wsl-stall.test.ts": 402, "src/main/native-chat/transcript-read-cache.test.ts": 513, - "src/main/native-chat/transcript-reader-codex-history-mode.test.ts": 660, "src/main/native-chat/transcript-reader-wsl-stall.test.ts": 503, "src/main/native-chat/transcript-reader.test.ts": 565, "src/main/native-chat/transcript-stream-lines.test.ts": 79, "src/main/native-chat/transcript-tail-reader-cancellation.test.ts": 599, "src/main/native-chat/transcript-tail-reader-wsl-gate.test.ts": 420, - "src/main/native-chat/transcript-tool-result-identity.test.ts": 565, "src/main/native-chat/transcript-turn-lifecycle.test.ts": 258, "src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts": 508, "src/main/native-chat/transcript-watch-error.test.ts": 2306, @@ -3030,14 +3015,9 @@ "src/main/native-chat/transcript-watch-resolve-poll.test.ts": 541, "src/main/native-chat/transcript-watch-unflushed-settle.test.ts": 554, "src/main/native-chat/transcript-watch-unsubscribe-race.test.ts": 533, - "src/main/native-chat/transcript-watch-wsl-exact-path.test.ts": 465, - "src/main/native-chat/transcript-watch.test.ts": 2570, "src/main/native-chat/transcript-window-tool-attribution.test.ts": 523, "src/main/native-chat/transcript-zcode.test.ts": 814, "src/main/native-chat/wsl-session-path-scan.test.ts": 167, - "src/main/native-chat/wsl-transcript-fs-access.test.ts": 186, - "src/main/native-chat/wsl-transcript-fs-gate.test.ts": 567, - "src/main/native-chat/wsl-transcript-fs-process-client.test.ts": 99, "src/main/native-chat/wsl-transcript-fs-process-operations.test.ts": 43, "src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts": 62, "src/main/native-chat/wsl-transcript-running-admission.test.ts": 1178, @@ -3046,55 +3026,37 @@ "src/main/network/electron-proxy-request-guard.test.ts": 308, "src/main/network/macos-system-resolver-health.test.ts": 59, "src/main/network/macos-tailscale-dns-diagnostic.test.ts": 54, - "src/main/network/proxy-settings-session.test.ts": 858, - "src/main/network/proxy-settings.test.ts": 121, "src/main/node-runtime/linux-libc-probe.test.ts": 68, "src/main/node-runtime/managed-runtime-installation.test.ts": 427, "src/main/node-runtime/managed-runtime-release.test.ts": 82, "src/main/node-runtime/pinned-runtime-materializer-http-client.test.ts": 88, "src/main/node-runtime/pinned-runtime-materializer-mirror.test.ts": 115, - "src/main/node-runtime/pinned-runtime-materializer-node.test.ts": 157, - "src/main/node-runtime/pinned-runtime-materializer.test.ts": 3173, "src/main/node-runtime/runtime-archive-download.test.ts": 149, "src/main/notebook/notebook-kernel.test.ts": 151, "src/main/notebook/python-environments.test.ts": 85, "src/main/notifications/announced-notification-registry.test.ts": 142, "src/main/notifications/desktop-presence-reporter.test.ts": 790, - "src/main/notifications/notification-delivery-service.test.ts": 130, "src/main/observability/bundle.test.ts": 696, "src/main/observability/diagnostic-upload-http.test.ts": 56, - "src/main/observability/instrumentation.test.ts": 201, "src/main/observability/local-file-sink-memory.test.ts": 148, "src/main/observability/local-file-sink.test.ts": 1124, "src/main/observability/redactor-environment-lines.test.ts": 46, "src/main/observability/redactor.test.ts": 80, - "src/main/observability/stalled-log-disk.test.ts": 869, "src/main/omp/omp-session-cwd-lookup.test.ts": 232, "src/main/opencode-usage/cache-read-reproduction.test.ts": 366, "src/main/opencode-usage/cache-write-accounting.test.ts": 423, - "src/main/opencode-usage/opencode2-session-usage.test.ts": 825, "src/main/opencode-usage/scanner-windows-data-directory.test.ts": 464, "src/main/opencode-usage/scanner-wsl-gate.test.ts": 133, "src/main/opencode-usage/scanner.test.ts": 554, - "src/main/opencode-usage/store.test.ts": 364, "src/main/opencode/hook-plugin-background-child-completion.test.ts": 264, - "src/main/opencode/hook-plugin-child-attention.test.ts": 637, - "src/main/opencode/hook-plugin-fail-open-ownership.test.ts": 528, - "src/main/opencode/hook-plugin-legacy-tui-ownership.test.ts": 2041, - "src/main/opencode/hook-plugin-lifecycle-delivery.test.ts": 995, "src/main/opencode/hook-plugin-message-part-throttle.test.ts": 251, "src/main/opencode/hook-plugin-module-contract.test.ts": 608, - "src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts": 1023, - "src/main/opencode/hook-plugin-opencode2-setup.test.ts": 2248, - "src/main/opencode/hook-plugin-opencode2-tui-ownership.test.ts": 1494, "src/main/opencode/hook-plugin-run-process-session-start.test.ts": 227, "src/main/opencode/hook-service-invalid-tui-config.test.ts": 134, - "src/main/opencode/hook-service-legacy-acl.test.ts": 392, "src/main/opencode/hook-service-overlay-confinement.test.ts": 103, "src/main/opencode/hook-service-startup-refresh.test.ts": 111, "src/main/opencode/hook-service.test.ts": 262, "src/main/opencode/legacy-shared-config-dir.test.ts": 43, - "src/main/opencode/opencode-acp-connection.test.ts": 1205, "src/main/opencode/opencode-cli-version.test.ts": 54, "src/main/opencode/opencode-client-sweep.test.ts": 124, "src/main/opencode/opencode-go-api-key-store.test.ts": 128, @@ -3103,7 +3065,6 @@ "src/main/opencode/opencode-launch-model-context-supervision.test.ts": 2290, "src/main/opencode/opencode-launch-model-context.test.ts": 215, "src/main/opencode/opencode-model-catalog-listing.test.ts": 225, - "src/main/opencode/opencode-model-startup-plan.test.ts": 309, "src/main/opencode/opencode-overlay-manifest.test.ts": 48, "src/main/opencode/opencode-pty-launch.test.ts": 277, "src/main/opencode/opencode-session-binder.test.ts": 132, diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 0f464503323..421e819cfcf 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -42,7 +42,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts', 'src/main/ai-vault-search/session-search-dependent-transcripts.test.ts', 'src/main/ai-vault-search/session-search-list-reparse.test.ts', - 'src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts', 'src/main/runtime/orchestration-cli-subprocess.test.ts', 'src/main/runtime/orchestration-mailbox-delivery.test.ts', 'src/main/runtime/orchestration-mailbox-routing.test.ts', @@ -161,7 +160,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/native-chat/agent-session-wire/structured-agent-session-terminal-writer-acquire.test.ts', 'src/main/native-chat/agent-session-wire/structured-agent-session-status-feed.test.ts', 'src/main/native-chat/agent-session-wire/structured-agent-session-status-feed-conversation-name.test.ts', - 'src/main/native-chat/structured-chat-naming.test.ts', 'src/main/runtime/agent-session/records/agent-session-conversation-name-store.test.ts', 'src/main/runtime/rpc/ws-transport.test.ts', 'src/main/runtime/rpc/dispatcher-transport-parity.test.ts', diff --git a/src/main/native-chat/native-chat-visuals-delivery.test.ts b/src/main/native-chat/native-chat-visuals-delivery.test.ts deleted file mode 100644 index 5cf7e094ce6..00000000000 --- a/src/main/native-chat/native-chat-visuals-delivery.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - NATIVE_CHAT_VISUAL_MAX_BYTES, - NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE, - parseNativeChatVisualDirectiveLine -} from '../../shared/native-chat/native-chat-visual-directive' -import { NATIVE_CHAT_VISUAL_THEME_TOKENS } from '../../shared/native-chat/native-chat-visual-shell' -import { ORCAD_NATIVE_CHAT_VISUALS_ARTIFACTS } from '../../shared/orcad-artifacts' -import { - createNativeChatVisualsDelivery, - NATIVE_CHAT_SCRATCH_DIR_ENV, - withNativeChatVisualsEnv -} from './native-chat-visuals-delivery' -import { nativeChatScratchFolderFor, nativeChatScratchRootFor } from './native-chat-scratch-folder' -import { buildClaudeChildProcessEnv } from '../claude/claude-child-process-environment' -import { createCodexStructuredLaunchResolver } from '../runtime/agent-session/launch/structured-agent-launch-composition.test-support' -import { agentSessionRecordFixture } from './agent-session-record-test-fixture' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' -import { resolveProviderChildEnv } from '../provider-process/provider-process-launch' -import { - NATIVE_CHAT_VISUALS_SKILL_NAME, - resetNativeChatVisualsSkillLocationForTests, - resolveNativeChatVisualsSkillLocation -} from './native-chat-visuals-skill-location' - -const RESOURCE_DIR = join(__dirname, '..', '..', '..', 'resources', 'native-chat-visuals') -const SKILL_TEXT = readFileSync( - join(RESOURCE_DIR, 'skills', NATIVE_CHAT_VISUALS_SKILL_NAME, 'SKILL.md'), - 'utf8' -) -const SKILL = { pluginDir: '/app/plugin', skillsRoot: '/app/plugin/skills' } - -const scratch: string[] = [] -afterEach(() => { - resetNativeChatVisualsSkillLocationForTests() - for (const dir of scratch.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function tempDir(): string { - const dir = mkdtempSync(join(tmpdir(), 'orca-visuals-delivery-')) - scratch.push(dir) - return dir -} - -const logger = () => ({ warn: vi.fn(), error: vi.fn() }) - -describe('preparing a chat for visuals', () => { - it('reads the preference for each launch and prepares nothing while it is off', async () => { - const state = tempDir() - let enabled = false - const resolveSkill = vi.fn(async () => SKILL) - const prepare = createNativeChatVisualsDelivery({ - stateDirectory: state, - logger: logger(), - isEnabled: () => enabled, - resolveSkill - }) - await expect(prepare('disabled-chat')).resolves.toBeNull() - expect(resolveSkill).not.toHaveBeenCalled() - expect(existsSync(nativeChatScratchRootFor(state))).toBe(false) - enabled = true - const launched = await prepare('enabled-chat') - expect(launched).toEqual({ - folder: nativeChatScratchFolderFor(state, 'enabled-chat'), - skill: SKILL - }) - enabled = false - await expect(prepare('next-chat')).resolves.toBeNull() - expect(resolveSkill).toHaveBeenCalledOnce() - expect(existsSync(nativeChatScratchFolderFor(state, 'next-chat'))).toBe(false) - expect(existsSync(launched!.folder)).toBe(true) - }) - - it("creates the chat's own private folder and hands back the skill", async () => { - const state = tempDir() - const prepare = createNativeChatVisualsDelivery({ - stateDirectory: state, - logger: logger(), - resolveSkill: async () => SKILL - }) - const prepared = await prepare('chat-1') - expect(prepared).toEqual({ folder: nativeChatScratchFolderFor(state, 'chat-1'), skill: SKILL }) - const mode = statSync(prepared!.folder).mode & 0o777 - expect(process.platform === 'win32' || mode === 0o700).toBe(true) - await expect(prepare('chat-1')).resolves.toEqual(prepared) - }) - - it('leaves the chat without visuals when the skill is missing or the folder fails', async () => { - const missingSkill = logger() - await expect( - createNativeChatVisualsDelivery({ - stateDirectory: tempDir(), - logger: missingSkill, - resolveSkill: async () => null - })('chat-1') - ).resolves.toBeNull() - expect(missingSkill.warn).toHaveBeenCalledOnce() - const state = tempDir() - writeFileSync(nativeChatScratchRootFor(state), 'not a folder') - const failedFolder = logger() - await expect( - createNativeChatVisualsDelivery({ - stateDirectory: state, - logger: failedFolder, - resolveSkill: async () => SKILL - })('chat-1') - ).resolves.toBeNull() - expect(failedFolder.warn).toHaveBeenCalledWith( - 'native-chat scratch folder could not be prepared', - expect.objectContaining({ scope: 'nativeChatVisuals.folder', sessionId: 'chat-1' }) - ) - }) - - it("never hands a chat another chat's folder that Orca itself inherited", async () => { - const inherited = { PATH: '/bin', [NATIVE_CHAT_SCRATCH_DIR_ENV]: '/parent-chat' } - const visuals = { folder: '/mine', skill: SKILL } - for (const platform of ['darwin', 'win32'] as const) { - const claude = (configured: Record) => - buildClaudeChildProcessEnv(configured, { inheritedEnv: inherited, platform }) - expect(claude({})).not.toHaveProperty(NATIVE_CHAT_SCRATCH_DIR_ENV) - expect(claude(withNativeChatVisualsEnv({}, visuals))[NATIVE_CHAT_SCRATCH_DIR_ENV]).toBe( - '/mine' - ) - } - const record = agentSessionRecordFixture({ - sessionId: 'chat-1', - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: '/home/work/.codex' } - }) - const codex = async (withVisuals: boolean) => - resolveProviderChildEnv( - await createCodexStructuredLaunchResolver({ - store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, - resolveCommand: () => ({ command: 'codex', prefixArgs: [] }), - resolveLaunchArgs: () => [], - prepareVisuals: async () => (withVisuals ? visuals : null) - })({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a launch reads only the session id of its identity here. - identity: { sessionId: 'chat-1' } as AgentSessionJournalIdentity, - spawnToken: 'spawn-token' - }), - inherited - ) - expect(await codex(false)).not.toHaveProperty(NATIVE_CHAT_SCRATCH_DIR_ENV) - expect((await codex(true))[NATIVE_CHAT_SCRATCH_DIR_ENV]).toBe('/mine') - }) - - it('names only this chat folder to the agent', () => { - const inherited = { PATH: '/bin', [NATIVE_CHAT_SCRATCH_DIR_ENV]: '/other-chat' } - expect(withNativeChatVisualsEnv(inherited, { folder: '/mine', skill: SKILL })).toEqual({ - PATH: '/bin', - [NATIVE_CHAT_SCRATCH_DIR_ENV]: '/mine' - }) - expect(withNativeChatVisualsEnv(inherited, null)).toEqual({ PATH: '/bin' }) - }) -}) - -describe('the bundled skill', () => { - it('is found in a checkout, and a missing install is not remembered', async () => { - await expect(resolveNativeChatVisualsSkillLocation([tempDir()])).resolves.toBeNull() - await expect(resolveNativeChatVisualsSkillLocation([tempDir(), RESOURCE_DIR])).resolves.toEqual( - { pluginDir: RESOURCE_DIR, skillsRoot: join(RESOURCE_DIR, 'skills') } - ) - }) - - it('ships every file in the headless server build too', () => { - const shipped = ORCAD_NATIVE_CHAT_VISUALS_ARTIFACTS.map((file) => - file.slice('native-chat-visuals/'.length) - ) - expect(shipped).toEqual([ - '.claude-plugin/plugin.json', - `skills/${NATIVE_CHAT_VISUALS_SKILL_NAME}/SKILL.md` - ]) - const manifest = JSON.parse(readFileSync(join(RESOURCE_DIR, shipped[0]!), 'utf8')) - expect(manifest.name).toMatch(/^[a-z0-9-]+$/) - }) - - it('teaches the reply line the renderer parses, with its limits', () => { - const example = SKILL_TEXT.split('\n').find((line) => line.startsWith('::orca-visual{')) - expect(example && parseNativeChatVisualDirectiveLine(example)).toEqual({ - file: 'latency-by-region-7c1e.html', - title: 'Latency by region' - }) - expect(SKILL_TEXT).toContain(`At most ${NATIVE_CHAT_VISUAL_MAX_PER_MESSAGE} per reply`) - expect(SKILL_TEXT).toContain(`under ${NATIVE_CHAT_VISUAL_MAX_BYTES / 1024} KB`) - expect(SKILL_TEXT).toContain(NATIVE_CHAT_SCRATCH_DIR_ENV) - expect(SKILL_TEXT).toMatch(new RegExp(`^name: ${NATIVE_CHAT_VISUALS_SKILL_NAME}$`, 'm')) - }) - - it('names only theme variables the visual frame sets', () => { - const named = [...SKILL_TEXT.matchAll(/`(--[a-z0-9-]+)`/g)].map(([, name]) => name) - const ranges = [...SKILL_TEXT.matchAll(/`--chart-1` to `--chart-(\d)`/g)].flatMap(([, last]) => - Array.from({ length: Number(last) }, (_, index) => `--chart-${index + 1}`) - ) - expect(named.length).toBeGreaterThan(0) - const frameTokens: readonly string[] = NATIVE_CHAT_VISUAL_THEME_TOKENS - expect([...named, ...ranges].filter((name) => !frameTokens.includes(name))).toEqual([]) - }) -}) diff --git a/src/main/native-chat/session-file-resolver-wsl.test.ts b/src/main/native-chat/session-file-resolver-wsl.test.ts deleted file mode 100644 index d66c8d8b0bb..00000000000 --- a/src/main/native-chat/session-file-resolver-wsl.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFsPromisesModule from 'node:fs/promises' - -const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' -const WSL_MANAGED_SESSIONS_DIR = `${UBUNTU_HOME}\\.local\\share\\orca\\codex-runtime-home\\home\\sessions` -const ROLLOUT_LINUX = - '/home/ada/.local/share/orca/codex-runtime-home/home/sessions/2026/07/24/rollout-wsl-sess.jsonl' -const ROLLOUT_UNC = - '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\24\\rollout-wsl-sess.jsonl' -const DEBIAN_ROLLOUT_UNC = ROLLOUT_UNC.replace('Ubuntu', 'Debian') - -// These cases cover root and path policy; the E9 gate has its own suite. -vi.mock('./wsl-transcript-running-admission', () => ({ admitWslTranscriptPath: async () => {} })) -vi.mock('../wsl/discovery/wsl-home-unless-stopped', async () => { - const wsl = await import('../wsl/discovery/distro-catalog') - return { - wslHomeUnlessStopped: (distro: string) => wsl.getWslHomeAsync(distro), - listRunningWslHomeDirsUnlessStopped: () => wsl.listRunningWslHomeDirsAsync() - } -}) -vi.mock('../wsl/discovery/distro-catalog', () => ({ - listWslDistrosAsync: vi.fn(async () => ['Ubuntu', 'Debian']), - listRunningWslDistrosAsync: vi.fn(async () => ['Ubuntu', 'Debian']), - listRunningWslHomeDirsAsync: vi.fn(async () => [ - UBUNTU_HOME, - UBUNTU_HOME.replace('Ubuntu', 'Debian') - ]), - getWslHomeAsync: vi.fn(async (distro: string) => UBUNTU_HOME.replace('Ubuntu', distro)) -})) -vi.mock('../wsl/filesystem/unc-path-access', () => ({ - resolveWslGuestRealDirAsync: vi.fn(async (_distro: string, dir: string) => dir) -})) - -// Accept only exact UNC fixtures so wrong-distro resolutions fail; native paths use real filesystem checks. -const READABLE_WSL_UNC_PATHS = new Set([ROLLOUT_UNC]) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - access: async (path: string) => { - if (!path.startsWith('\\\\wsl.localhost\\')) { - await actual.access(path) - return - } - if (!READABLE_WSL_UNC_PATHS.has(path)) { - throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' }) - } - } - } -}) - -const HOST_ROLLOUT = 'C:\\host\\sessions\\rollout-wsl-sess.jsonl' -const scanned = vi.hoisted(() => { - const state: { dirs: string[]; hostRootHasRollout: boolean; wslHits: Record } = { - dirs: [], - hostRootHasRollout: false, - wslHits: {} - } - return state -}) -vi.mock('../ai-vault/session-scanner-discovery', () => ({ - walkSessionFiles: async (dir: string) => { - scanned.dirs.push(dir) - const wslHit = scanned.wslHits[dir] - if (wslHit) { - return [wslHit] - } - const isWslRoot = dir.startsWith('\\\\wsl.localhost\\') - return scanned.hostRootHasRollout && !isWslRoot - ? ['C:\\host\\sessions\\rollout-wsl-sess.jsonl'] - : [] - } -})) - -import { resetHostReadableTranscriptPathCacheForTests } from './host-readable-transcript-path' -import { resolveSessionFilePath } from './session-file-resolver' -import { - getWslHomeAsync, - listRunningWslHomeDirsAsync, - listWslDistrosAsync -} from '../wsl/discovery/distro-catalog' - -const realPlatform = process.platform - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -beforeEach(() => { - resetHostReadableTranscriptPathCacheForTests() - vi.mocked(getWslHomeAsync).mockClear() - vi.mocked(listWslDistrosAsync).mockClear() - vi.mocked(listRunningWslHomeDirsAsync).mockClear() - scanned.dirs = [] - scanned.hostRootHasRollout = false - scanned.wslHits = {} - READABLE_WSL_UNC_PATHS.clear() - READABLE_WSL_UNC_PATHS.add(ROLLOUT_UNC) - setPlatform('win32') -}) - -afterEach(() => { - setPlatform(realPlatform) -}) - -describe('resolveSessionFilePath on a Windows host with WSL', () => { - it('translates a WSL hook transcript path to its host-readable UNC twin (#10326)', async () => { - const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { - transcriptPath: ROLLOUT_LINUX, - codexSessionsDirs: [] - }) - expect(resolved).toBe(ROLLOUT_UNC) - }) - - it.each(['codex', 'omp'] as const)( - 'keeps an attested distro when another guest has the same transcript path (%s)', - async (agent) => { - READABLE_WSL_UNC_PATHS.add(DEBIAN_ROLLOUT_UNC) - - const resolved = await resolveSessionFilePath(agent, 'wsl-sess', { - transcriptPath: ROLLOUT_LINUX, - wslDistro: 'Ubuntu', - codexSessionsDirs: [] - }) - - expect(resolved).toBe(ROLLOUT_UNC) - expect(vi.mocked(listWslDistrosAsync)).not.toHaveBeenCalled() - expect(vi.mocked(getWslHomeAsync)).not.toHaveBeenCalled() - } - ) - - it.each(['codex', 'omp'] as const)( - 'does not fall through to another guest when the attested path is missing (%s)', - async (agent) => { - READABLE_WSL_UNC_PATHS.delete(ROLLOUT_UNC) - READABLE_WSL_UNC_PATHS.add(DEBIAN_ROLLOUT_UNC) - scanned.hostRootHasRollout = true - - await expect( - resolveSessionFilePath(agent, 'wsl-sess', { - transcriptPath: ROLLOUT_LINUX, - wslDistro: 'Ubuntu', - codexSessionsDirs: [] - }) - ).resolves.toBeNull() - expect(scanned.dirs).toEqual([]) - } - ) - - it('does not return a UNC twin that no distro actually has', async () => { - const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { - transcriptPath: '/home/ada/.codex/sessions/2026/07/24/rollout-gone.jsonl', - codexSessionsDirs: [] - }) - expect(resolved).toBeNull() - }) - - it.each(['codex', 'omp'] as const)( - 'does not fall back by id from an unattested guest hook path (%s)', - async (agent) => { - READABLE_WSL_UNC_PATHS.delete(ROLLOUT_UNC) - scanned.hostRootHasRollout = true - - await expect( - resolveSessionFilePath(agent, 'wsl-sess', { - transcriptPath: ROLLOUT_LINUX, - codexSessionsDirs: ['C:\\host\\sessions'] - }) - ).resolves.toBeNull() - expect(scanned.dirs).toEqual([]) - } - ) - - it('does not fall back to a host id match for an unattested guest hook path', async () => { - scanned.hostRootHasRollout = true - - const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { - transcriptPath: '/home/ada/.codex/sessions/2026/07/24/rollout-wsl-sess.jsonl', - codexSessionsDirs: [HOST_ROLLOUT] - }) - - expect(resolved).toBeNull() - expect(scanned.dirs).toEqual([]) - }) - - it('searches the WSL managed Codex sessions root when no hook path is known', async () => { - await resolveSessionFilePath('codex', 'wsl-sess') - expect(scanned.dirs).toContain(WSL_MANAGED_SESSIONS_DIR) - expect(scanned.dirs).toContain(`${UBUNTU_HOME}\\.codex\\sessions`) - }) - - it('does not enumerate WSL distros when a host Codex root already has the rollout', async () => { - scanned.hostRootHasRollout = true - - await expect(resolveSessionFilePath('codex', 'wsl-sess')).resolves.toBe(HOST_ROLLOUT) - - expect(scanned.dirs.some((dir) => dir.startsWith('\\\\wsl.localhost\\'))).toBe(false) - expect(vi.mocked(listWslDistrosAsync)).not.toHaveBeenCalled() - expect(vi.mocked(getWslHomeAsync)).not.toHaveBeenCalled() - }) - - it('leaves the guest path alone on non-Windows hosts', async () => { - setPlatform('darwin') - const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { - transcriptPath: ROLLOUT_LINUX, - codexSessionsDirs: [] - }) - expect(resolved).toBeNull() - }) - - it.each([ - ['claude', `${UBUNTU_HOME}\\.claude\\projects`, '-home-ada-repo\\wsl-sess.jsonl'], - ['omp', `${UBUNTU_HOME}\\.omp\\agent\\sessions`, '-home-ada-repo\\2026-07-24_wsl-sess.jsonl'], - [ - 'grok', - `${UBUNTU_HOME}\\.grok\\sessions`, - '%2Fhome%2Fada%2Frepo\\wsl-sess\\chat_history.jsonl' - ] - ] as const)( - 'finds a %s transcript that exists only in a running distro', - async (agent, root, relative) => { - const transcript = `${root}\\${relative}` - scanned.wslHits[root] = transcript - - await expect(resolveSessionFilePath(agent, 'wsl-sess')).resolves.toBe(transcript) - } - ) - - it('never searches the projects root of a distro that is not running', async () => { - vi.mocked(listRunningWslHomeDirsAsync).mockResolvedValueOnce([UBUNTU_HOME]) - - await expect(resolveSessionFilePath('claude', 'wsl-sess')).resolves.toBeNull() - - expect(scanned.dirs).toContain(`${UBUNTU_HOME}\\.claude\\projects`) - expect(scanned.dirs.some((dir) => dir.includes('Debian'))).toBe(false) - }) - - it('does not enumerate WSL distros when a host Claude root already has the session', async () => { - scanned.hostRootHasRollout = true - - await expect(resolveSessionFilePath('claude', 'wsl-sess')).resolves.toBe(HOST_ROLLOUT) - - expect(vi.mocked(listRunningWslHomeDirsAsync)).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/native-chat/session-file-resolver.test.ts b/src/main/native-chat/session-file-resolver.test.ts index c04f8dae5ee..6b51d501854 100644 --- a/src/main/native-chat/session-file-resolver.test.ts +++ b/src/main/native-chat/session-file-resolver.test.ts @@ -18,14 +18,6 @@ async function makeRoot(prefix: string): Promise { return root } -function restoreEnv(key: string, previous: string | undefined): void { - if (previous === undefined) { - delete process.env[key] - } else { - process.env[key] = previous - } -} - describe('resolveSessionFilePath', () => { it('globs Claude project subdirs for .jsonl', async () => { const root = await makeRoot('orca-native-chat-resolve-claude-') @@ -39,19 +31,6 @@ describe('resolveSessionFilePath', () => { expect(resolved).toBe(target) }) - it('resolves OpenClaude sessions from the Claude transcript layout', async () => { - const root = await makeRoot('orca-native-chat-resolve-openclaude-') - const claudeProjectsDir = join(root, 'claude-projects') - const projectDir = join(claudeProjectsDir, '-Users-ada-repo') - await mkdir(projectDir, { recursive: true }) - const target = join(projectDir, 'sess-openclaude.jsonl') - await writeFile(target, '{}\n') - - await expect( - resolveSessionFilePath('openclaude', 'sess-openclaude', { claudeProjectsDir }) - ).resolves.toBe(target) - }) - it('resolves Grok chat_history.jsonl under encodeURIComponent(cwd)/sessionId', async () => { const root = await makeRoot('orca-native-chat-resolve-grok-') const grokSessionsDir = join(root, 'grok-sessions') @@ -107,22 +86,6 @@ describe('resolveSessionFilePath', () => { ).resolves.toBeNull() }) - it('resolves Grok sessions under GROK_HOME when no override is passed', async () => { - const root = await makeRoot('orca-native-chat-resolve-grok-home-') - const sessionsDir = join(root, 'sessions') - const sessionDir = join(sessionsDir, encodeURIComponent('/repo'), 'sess-env-1') - await mkdir(sessionDir, { recursive: true }) - const target = join(sessionDir, 'chat_history.jsonl') - await writeFile(target, '{}\n') - const previous = process.env.GROK_HOME - process.env.GROK_HOME = root - try { - await expect(resolveSessionFilePath('grok', 'sess-env-1')).resolves.toBe(target) - } finally { - restoreEnv('GROK_HOME', previous) - } - }) - it('matches Codex rollout files by session id suffix', async () => { const root = await makeRoot('orca-native-chat-resolve-codex-') const codexSessionsDir = join(root, 'codex-sessions') @@ -137,18 +100,6 @@ describe('resolveSessionFilePath', () => { expect(resolved).toBe(target) }) - it('matches omp transcripts by session id suffix inside the per-cwd directory', async () => { - const root = await makeRoot('orca-native-chat-resolve-omp-') - const ompSessionsDir = join(root, 'omp-sessions') - const cwdDir = join(ompSessionsDir, '-Users-ada-repo') - await mkdir(cwdDir, { recursive: true }) - const target = join(cwdDir, '2026-07-16T00-27-02-222Z_sess-omp-1.jsonl') - await writeFile(target, '{}\n') - - const resolved = await resolveSessionFilePath('omp', 'sess-omp-1', { ompSessionsDir }) - expect(resolved).toBe(target) - }) - it('never descends into an omp session artifact dir', async () => { // Put the only match inside the artifact directory so success cannot depend on readdir ordering. const root = await makeRoot('orca-native-chat-resolve-omp-artifact-') @@ -167,78 +118,6 @@ describe('resolveSessionFilePath', () => { ).resolves.toBe(join(cwdDir, `${stem}.jsonl`)) }) - it('honors OMP_CODING_AGENT_DIR when resolving omp transcripts', async () => { - const root = await makeRoot('orca-native-chat-resolve-omp-env-') - const cwdDir = join(root, 'omp-sessions', '-Users-ada-repo') - await mkdir(cwdDir, { recursive: true }) - const target = join(cwdDir, '2026-07-16T00-27-02-222Z_sess-omp-env.jsonl') - await writeFile(target, '{}\n') - - const previous = process.env.OMP_CODING_AGENT_DIR - process.env.OMP_CODING_AGENT_DIR = join(root, 'omp-sessions') - try { - await expect(resolveSessionFilePath('omp', 'sess-omp-env')).resolves.toBe(target) - } finally { - restoreEnv('OMP_CODING_AGENT_DIR', previous) - } - }) - - it('resolves a rollout from the orca-managed Codex home (ORCA_USER_DATA_PATH)', async () => { - const root = await makeRoot('orca-native-chat-resolve-managed-') - const managedSessionsDir = join(root, 'codex-runtime-home', 'home', 'sessions') - const dayDir = join(managedSessionsDir, '2026', '06', '19') - await mkdir(dayDir, { recursive: true }) - const target = join(dayDir, 'rollout-2026-06-19T04-20-39-019edf9c-managed.jsonl') - await writeFile(target, '{}\n') - - const previous = process.env.ORCA_USER_DATA_PATH - process.env.ORCA_USER_DATA_PATH = root - try { - const resolved = await resolveSessionFilePath('codex', '019edf9c-managed') - expect(resolved).toBe(target) - } finally { - if (previous === undefined) { - delete process.env.ORCA_USER_DATA_PATH - } else { - process.env.ORCA_USER_DATA_PATH = previous - } - } - }) - - it('falls back to CODEX_HOME when the managed home has no match', async () => { - const root = await makeRoot('orca-native-chat-resolve-codex-home-') - const managedRoot = join(root, 'managed-userdata') - await mkdir(managedRoot, { recursive: true }) - const codexHome = join(root, 'custom-codex-home') - const dayDir = join(codexHome, 'sessions', '2026', '06', '05') - await mkdir(dayDir, { recursive: true }) - const target = join(dayDir, 'rollout-xyz-session.jsonl') - await writeFile(target, '{}\n') - - const previousCodex = process.env.CODEX_HOME - const previousUserData = process.env.ORCA_USER_DATA_PATH - process.env.CODEX_HOME = codexHome - process.env.ORCA_USER_DATA_PATH = managedRoot - try { - const resolved = await resolveSessionFilePath('codex', 'xyz-session') - expect(resolved).toBe(target) - } finally { - restoreEnv('CODEX_HOME', previousCodex) - restoreEnv('ORCA_USER_DATA_PATH', previousUserData) - } - }) - - it('returns null when no transcript matches', async () => { - const root = await makeRoot('orca-native-chat-resolve-missing-') - const claudeProjectsDir = join(root, 'claude-projects') - await mkdir(claudeProjectsDir, { recursive: true }) - expect(await resolveSessionFilePath('claude', 'nope', { claudeProjectsDir })).toBeNull() - }) - - it('returns null for unsupported agents', async () => { - expect(await resolveSessionFilePath('gemini', 'whatever')).toBeNull() - }) - it('prefers the hook transcriptPath when it exists (Claude id != file name)', async () => { const root = await makeRoot('orca-native-chat-resolve-path-') const claudeProjectsDir = join(root, 'claude-projects') @@ -286,37 +165,3 @@ describe('resolveSessionFilePath', () => { expect(resolved).toBe(target) }) }) - -// Mobile uses default roots, which must match the CLI’s CLAUDE_CONFIG_DIR or its transcript disappears. -describe('the default Claude transcript root mobile falls back to', () => { - it('follows CLAUDE_CONFIG_DIR, the same variable the pinned account home follows', async () => { - const configDir = await makeRoot('orca-native-chat-claude-config-dir-') - const slugDir = join(configDir, 'projects', '-repos-workspace-1') - await mkdir(slugDir, { recursive: true }) - const transcript = join(slugDir, 'session-under-config-dir.jsonl') - await writeFile(transcript, '', 'utf8') - const previous = process.env.CLAUDE_CONFIG_DIR - process.env.CLAUDE_CONFIG_DIR = configDir - - try { - await expect(resolveSessionFilePath('claude', 'session-under-config-dir')).resolves.toBe( - transcript - ) - } finally { - restoreEnv('CLAUDE_CONFIG_DIR', previous) - } - }) - - it('ignores a blank CLAUDE_CONFIG_DIR rather than resolving against the filesystem root', async () => { - const previous = process.env.CLAUDE_CONFIG_DIR - process.env.CLAUDE_CONFIG_DIR = ' ' - - try { - await expect( - resolveSessionFilePath('claude', 'session-that-does-not-exist') - ).resolves.toBeNull() - } finally { - restoreEnv('CLAUDE_CONFIG_DIR', previous) - } - }) -}) diff --git a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts b/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts deleted file mode 100644 index 3adb5d45c07..00000000000 --- a/src/main/native-chat/structured-agent-cli-conversation-adoption.test.ts +++ /dev/null @@ -1,452 +0,0 @@ -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -// Adoption forks the AI Vault service for the chat's title; naming is covered elsewhere. -vi.mock('../ai-vault/session-titles/session-title-resolver', () => ({ - resolveLocalAiVaultSessionTitles: async () => ({ titles: [] }) -})) -import { - adoptsCliConversations, - CLI_CONVERSATION_ADOPTING_AGENTS -} from '../../shared/structured-agent-cli-conversation-adoption' -import { - clearGrokSessionPathLookupCacheForTests, - findGrokChatHistoryBySessionId, - grokEncodedCwdDirName, - GROK_SESSION_GROUP_SCAN_MAX_ENTRIES, - setGrokSessionDirectoryOpenerForTests -} from '../../shared/grok-session-paths' -import { - STRUCTURED_AGENT_RUNTIME_REGISTRATIONS, - structuredAgentRuntimeRegistration -} from '../runtime/agent-session/installation/structured-agent-runtime-registrations' -import { resolveStructuredAgentSessionAdoptionForCreate } from '../runtime/agent-session/structured-agent-session-create-adoption' -import { prepareLegacyTranscriptImport } from './agent-session-journal/journal-legacy-import' -import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' -import { writeOpenCodeSqliteDatabase } from '../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-fixture' -import { resolveAcpLaunchInvocation } from '../acp/acp-structured-launch-resolution' -import { acpLaunchSpecFor } from '../acp/acp-launch-specs' -import { resolveOpenCodeDatabasePath } from '../opencode/opencode-data-directory' -import * as hostReadableTranscriptPath from './host-readable-transcript-path' - -vi.mock( - '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', - async (importOriginal) => { - const query = await import('./transcript-opencode-sqlite-query') - return { - ...(await importOriginal()), - readOpenCodeTranscriptPageViaWorker: async ( - args: Parameters[0] - ) => query.readOpenCodeTranscriptPage(args), - readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => - query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) - } - } -) - -const SESSION_ID = '0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a' -let root: string | null = null - -async function createAdoptionTestDirectory(prefix: string): Promise { - return realpath(await mkdtemp(prefix)) -} - -beforeEach(() => { - // Keep fallback history discovery away from real user homes. - vi.stubEnv('GROK_HOME', join(tmpdir(), 'orca-adopt-no-grok-home')) - vi.stubEnv('PI_CODING_AGENT_DIR', join(tmpdir(), 'orca-adopt-no-pi-home')) -}) - -afterEach(async () => { - vi.unstubAllEnvs() - vi.restoreAllMocks() - clearGrokSessionPathLookupCacheForTests() - if (root) { - await rm(root, { recursive: true, force: true }) - } - root = null -}) - -const RECORDED: Record<'grok' | 'omp' | 'pi', (home: string, text: string) => Promise> = { - grok: async (home, text) => { - const dir = join(home, 'sessions', encodeURIComponent('/repo/orca'), SESSION_ID) - await mkdir(dir, { recursive: true }) - const file = join(dir, 'chat_history.jsonl') - await writeFile( - file, - `${JSON.stringify({ type: 'user', content: [{ type: 'text', text }], timestamp: '2026-10-12T00:00:00.000Z' })}\n` - ) - return file - }, - omp: async (home, text) => { - const dir = join(home, 'sessions', '--repo-orca--') - await mkdir(dir, { recursive: true }) - const file = join(dir, `2026-10-12T00-00-00-000Z_${SESSION_ID}.jsonl`) - await writeFile( - file, - [ - { - type: 'session', - id: SESSION_ID, - cwd: '/repo/orca', - timestamp: '2026-10-12T00:00:00.000Z' - }, - { - type: 'message', - id: 'rec-1', - parentId: null, - timestamp: '2026-10-12T00:00:01.000Z', - message: { role: 'user', content: [{ type: 'text', text }] } - } - ] - .map((record) => JSON.stringify(record)) - .join('\n') - ) - return file - }, - // Pi system prompts live in sections with empty content. - pi: async (home, text) => { - const dir = join(home, 'sessions', '--repo-orca--') - await mkdir(dir, { recursive: true }) - const file = join(dir, `2026-10-12T00-00-00-000Z_${SESSION_ID}.jsonl`) - const records = [ - { type: 'session', version: 3, id: SESSION_ID, cwd: '/repo/orca' }, - { - type: 'message', - id: 'a0b1c2d3', - parentId: null, - message: { role: 'system', content: '', sections: { preamble: 'You are Pi' } } - }, - { - type: 'message', - id: 'a1b2c3d4', - parentId: 'a0b1c2d3', - message: { role: 'user', content: text, timestamp: 1_791_763_201_000 } - }, - { - type: 'message', - id: 'b2c3d4e5', - parentId: 'a1b2c3d4', - message: { role: 'assistant', content: [{ type: 'text', text: 'Hi!' }], stopReason: 'stop' } - } - ] - await writeFile(file, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`) - return file - } -} - -const ACCOUNT_VARIABLE = { - grok: 'GROK_HOME', - omp: 'PI_CODING_AGENT_DIR', - pi: 'PI_CODING_AGENT_DIR' -} - -function adopt( - agent: 'grok' | 'omp' | 'opencode' | 'pi', - selectedAccountHome: AgentSessionAccountHome, - providerSessionId = SESSION_ID, - launchEnv: NodeJS.ProcessEnv = process.env, - workspaceCwd = '/repo/orca' -) { - const transcriptImport = structuredAgentRuntimeRegistration(agent)?.transcriptImport - if (!transcriptImport) { - throw new Error(`${agent} registers no transcript import`) - } - return resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent, - transcriptImport, - providerSessionId, - selectedAccountHome, - launchEnv, - workspaceCwd - }) -} - -describe('which chats can take over a CLI conversation', () => { - it('names, for every row an importing chat lists, only chats that import and list it', () => { - const importing = STRUCTURED_AGENT_RUNTIME_REGISTRATIONS.filter( - (registration) => registration.transcriptImport - ) - const rows = new Set(importing.flatMap((registration) => registration.sessionHistory.rowAgents)) - expect(new Set(Object.keys(CLI_CONVERSATION_ADOPTING_AGENTS))).toEqual(rows) - for (const [row, agents] of Object.entries(CLI_CONVERSATION_ADOPTING_AGENTS)) { - for (const agent of agents) { - const registration = importing.find((entry) => entry.definition.agent === agent) - expect(registration?.sessionHistory.rowAgents, `${agent} takes over ${row}`).toContain(row) - } - } - for (const registration of importing) { - const { agent } = registration.definition - if (adoptsCliConversations(agent)) { - expect(CLI_CONVERSATION_ADOPTING_AGENTS[agent][0]).toBe(agent) - } - } - }) -}) - -it.each([false, true])( - 'finds a Grok cwd beyond the generic cap (long path: %s)', - async (longPath) => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-grok-adopt-cwd-')) - const workspaceCwd = join(root, longPath ? '中'.repeat(80) : 'workspace') - const recorded = await RECORDED.grok(root, 'CURRENT-WORKSPACE') - const group = grokEncodedCwdDirName(workspaceCwd) - if (!group) { - throw new Error('Expected a CLI cwd group') - } - const cwdRecorded = join(root, 'sessions', group, SESSION_ID) - await mkdir(cwdRecorded, { recursive: true }) - const currentFile = join(cwdRecorded, 'chat_history.jsonl') - await writeFile(currentFile, await readFile(recorded)) - setGrokSessionDirectoryOpenerForTests(async () => ({ - async *[Symbol.asyncIterator]() { - for (let index = 0; index <= GROK_SESSION_GROUP_SCAN_MAX_ENTRIES; index += 1) { - yield { - name: `earlier-${index}`, - isDirectory: () => true, - isSymbolicLink: () => false - } - } - }, - close: async () => {} - })) - - expect(await findGrokChatHistoryBySessionId(join(root, 'sessions'), SESSION_ID)).toBeNull() - expect( - ( - await adopt( - 'grok', - { variable: 'GROK_HOME', path: root }, - SESSION_ID, - process.env, - workspaceCwd - ) - ).transcriptPath - ).toBe(currentFile) - } -) - -it('looks up OMP history under the configured launch XDG and profile root', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-env-')) - const ambientData = join(root, 'ambient-data') - const launchData = join(root, 'launch-data') - const profile = 'work' - const ambientSessions = join(ambientData, 'omp', 'profiles', profile, 'sessions') - const launchSessions = join(launchData, 'omp', 'profiles', profile, 'sessions') - await mkdir(join(ambientData, 'omp', 'profiles', profile), { recursive: true }) - await mkdir(join(launchData, 'omp', 'profiles', profile), { recursive: true }) - const ambientFile = await RECORDED.omp(join(ambientData, 'omp', 'profiles', profile), 'AMBIENT') - const launchFile = await RECORDED.omp(join(launchData, 'omp', 'profiles', profile), 'LAUNCH') - vi.stubEnv('XDG_DATA_HOME', ambientData) - vi.stubEnv('OMP_PROFILE', profile) - const launchEnv = { - ...process.env, - HOME: root, - XDG_DATA_HOME: launchData, - OMP_PROFILE: profile, - OMP_CODING_AGENT_DIR: '' - } - const accountHome = join(root, '.omp', 'agent') - - expect(ambientFile.startsWith(ambientSessions)).toBe(true) - expect(launchFile.startsWith(launchSessions)).toBe(true) - expect( - ( - await adopt( - 'omp', - { variable: 'PI_CODING_AGENT_DIR', path: accountHome }, - SESSION_ID, - launchEnv - ) - ).transcriptPath - ).toBe(launchFile) -}) - -it('uses the configured OMP profile when the ambient profile names another session', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-profile-')) - const xdgData = join(root, 'data') - const ambientProfile = 'ambient' - const launchProfile = 'configured' - const ambientHome = join(xdgData, 'omp', 'profiles', ambientProfile) - const launchHome = join(xdgData, 'omp', 'profiles', launchProfile) - await mkdir(ambientHome, { recursive: true }) - await mkdir(launchHome, { recursive: true }) - await RECORDED.omp(ambientHome, 'AMBIENT-PROFILE') - const launchFile = await RECORDED.omp(launchHome, 'LAUNCH-PROFILE') - vi.stubEnv('XDG_DATA_HOME', xdgData) - vi.stubEnv('OMP_PROFILE', ambientProfile) - - const accountHome = join(root, '.omp', 'agent') - const launchEnv = { - ...process.env, - HOME: root, - OMP_PROFILE: launchProfile, - OMP_CODING_AGENT_DIR: '' - } - expect( - ( - await adopt( - 'omp', - { variable: 'PI_CODING_AGENT_DIR', path: accountHome }, - SESSION_ID, - launchEnv - ) - ).transcriptPath - ).toBe(launchFile) -}) - -it.each(['win32', 'linux', 'darwin'] as const)( - 'follows the child home precedence for a named OMP profile on %s', - async (platform) => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-home-')) - const home = join(root, 'home') - const userProfile = join(root, 'user-profile') - const profile = 'work' - const homeFile = await RECORDED.omp(join(home, '.omp', 'profiles', profile, 'agent'), 'HOME') - const userProfileFile = await RECORDED.omp( - join(userProfile, '.omp', 'profiles', profile, 'agent'), - 'USERPROFILE' - ) - const nativePlatform = process.platform - const needsWslResolution = hostReadableTranscriptPath.needsWslHostResolution - // Simulate home precedence while retaining fixture paths native to the actual host. - vi.spyOn(hostReadableTranscriptPath, 'needsWslHostResolution').mockImplementation((path) => - needsWslResolution(path, nativePlatform) - ) - vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) - - const adoption = await adopt( - 'omp', - { variable: 'PI_CODING_AGENT_DIR', path: join(root, 'account') }, - SESSION_ID, - { - HOME: home, - USERPROFILE: userProfile, - OMP_PROFILE: profile - } - ) - - expect(adoption.transcriptPath).toBe(platform === 'win32' ? userProfileFile : homeFile) - } -) - -it('refuses OMP history from another workspace without creating a blank chat', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-omp-adopt-other-cwd-')) - await RECORDED.omp(root, 'OTHER-WORKSPACE') - await expect( - adopt( - 'omp', - { variable: 'PI_CODING_AGENT_DIR', path: root }, - SESSION_ID, - process.env, - '/another/workspace' - ) - ).rejects.toMatchObject({ - refusal: { code: 'agent_session_identity_required' } - }) -}) - -describe.each(['grok', 'omp', 'pi'] as const)('adopting a %s CLI conversation', (agent) => { - it('finds the conversation under the chat account and imports its history', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), `orca-${agent}-adopt-`)) - const recorded = await RECORDED[agent](root, `ORCA-${agent}-ADOPT`) - if (agent === 'pi') { - vi.stubEnv('PI_CODING_AGENT_DIR', root) - } - - const accountHome = { variable: ACCOUNT_VARIABLE[agent], path: root } - const adoption = await adopt(agent, accountHome) - - expect(adoption).toEqual({ accountHome, transcriptPath: recorded }) - const imported = await prepareLegacyTranscriptImport({ - agent, - sessionId: SESSION_ID, - options: { filePath: adoption.transcriptPath } - }) - expect(imported.ok && JSON.stringify(imported.items)).toContain(`ORCA-${agent}-ADOPT`) - if (agent === 'pi' && imported.ok) { - expect(imported.items.map((item) => item.body.kind === 'message' && item.body.role)).toEqual([ - 'user', - 'assistant' - ]) - } - }) - - it('refuses a conversation the account does not hold, rather than opening a blank chat', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), `orca-${agent}-adopt-missing-`)) - await expect( - adopt(agent, { variable: ACCOUNT_VARIABLE[agent], path: root }) - ).rejects.toMatchObject({ - refusal: { code: 'agent_session_identity_required' } - }) - }) -}) - -describe('adopting a Pi CLI conversation', () => { - it('pins the Session History account when another Pi home has the same id', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-pi-adopt-homes-')) - const selected = join(root, 'selected') - const history = join(root, 'history') - await RECORDED.pi(selected, 'SELECTED') - const source = await RECORDED.pi(history, 'HISTORY') - vi.stubEnv('PI_CODING_AGENT_DIR', history) - - expect(await adopt('pi', { variable: 'PI_CODING_AGENT_DIR', path: selected })).toEqual({ - accountHome: { variable: 'PI_CODING_AGENT_DIR', path: history }, - transcriptPath: source - }) - }) -}) - -describe('adopting an OpenCode CLI conversation', () => { - const OPENCODE_SESSION = 'ses_orca_adopt' - const unmanaged: AgentSessionAccountHome = { kind: 'opencode', locator: { kind: 'unmanaged' } } - - function openCodeData(home: string): string { - vi.stubEnv('HOME', home) - vi.stubEnv('USERPROFILE', home) - vi.stubEnv('XDG_DATA_HOME', join(home, 'data')) - vi.stubEnv('OPENCODE_DB', '') - return join(home, 'data', 'opencode', 'opencode.db') - } - - it('imports from the configured database the resumed OpenCode child opens', async () => { - root = await createAdoptionTestDirectory(join(tmpdir(), 'orca-opencode-configured-adopt-')) - const defaultDb = openCodeData(root) - const configuredDb = join(root, 'data', 'opencode', 'work.db') - writeOpenCodeSqliteDatabase(defaultDb, [ - { id: OPENCODE_SESSION, turns: [{ role: 'user', parts: ['wrong database'] }] } - ]) - writeOpenCodeSqliteDatabase(configuredDb, [ - { id: OPENCODE_SESSION, turns: [{ role: 'user', parts: ['configured database'] }] } - ]) - const baseEnvironment = { HOME: root, XDG_DATA_HOME: join(root, 'data') } - const launchEnv = { OPENCODE_DB: 'work.db' } - const adoption = await adopt('opencode', unmanaged, OPENCODE_SESSION, { - ...baseEnvironment, - ...launchEnv - }) - const spec = acpLaunchSpecFor('opencode') - if (!spec) { - throw new Error('OpenCode launch spec missing') - } - const launch = await resolveAcpLaunchInvocation(spec, unmanaged, { - resolveEnvironment: async () => baseEnvironment, - resolveLaunchEnv: () => launchEnv, - resolveCommand: () => '/test/opencode', - dataDirectory: root - }) - - expect(adoption.transcriptPath).toBe(configuredDb) - expect(resolveOpenCodeDatabasePath(launch.env, launch.env.HOME)).toBe(configuredDb) - const imported = await prepareLegacyTranscriptImport({ - agent: 'opencode', - sessionId: OPENCODE_SESSION, - options: { filePath: adoption.transcriptPath } - }) - expect(imported.ok && JSON.stringify(imported.items)).toContain('configured database') - expect(imported.ok && JSON.stringify(imported.items)).not.toContain('wrong database') - }) -}) diff --git a/src/main/native-chat/structured-agent-command-resolution.test.ts b/src/main/native-chat/structured-agent-command-resolution.test.ts index b240fd38e95..49251da691a 100644 --- a/src/main/native-chat/structured-agent-command-resolution.test.ts +++ b/src/main/native-chat/structured-agent-command-resolution.test.ts @@ -1,13 +1,8 @@ -import { resolveCodexStructuredInvocation } from '../codex/structured/launch/codex-structured-launch-resolution' import { chmodSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - resolveStructuredAgentCommand, - resolveAgainAfterRefreshOnMissingProgram -} from './structured-agent-command-resolution' -import { resolveCliCommand } from '../../shared/node-cli-command-resolution' +import { afterEach, describe, expect, it } from 'vitest' +import { resolveStructuredAgentCommand } from './structured-agent-command-resolution' const NOT_RUNNABLE = expect.objectContaining({ name: 'AgentSessionPreSpawnError', @@ -31,21 +26,6 @@ function executable() { } describe('structured agent executable resolution', () => { - it('reads the Command setting of any agent, and its stock binary by the name it is given', () => { - const { command } = executable() - expect( - resolveStructuredAgentCommand('opencode', { agentCmdOverrides: { opencode: `"${command}"` } }) - ).toEqual({ command: command, prefixArgs: [] }) - expect( - resolveStructuredAgentCommand( - 'opencode', - { agentCmdOverrides: { claude: `"${command}"` } }, - { pathEnv: '/nowhere' }, - { command: 'opencode', resolve: (name) => `/stock/${name}` } - ) - ).toEqual({ command: '/stock/opencode', prefixArgs: [] }) - }) - it('resolves a basename through the configured PATH and a home-relative path through the host home', () => { const { directory, command } = executable() const basenameCommand = join(directory, 'agent-custom') @@ -68,44 +48,6 @@ describe('structured agent executable resolution', () => { ).toEqual({ command: command, prefixArgs: [] }) }) - it('resolves folder-relative PATH to each effective Codex executable before pooling', async () => { - const folders = [executable(), executable()] - for (const { directory, command } of folders) { - const invocation = await resolveCodexStructuredInvocation({ - resolveEnvironment: async () => ({ PATH: '.' }), - resolveWorkingDirectory: () => directory, - resolveCommand: (options) => ({ - command: resolveCliCommand('agent custom', options), - prefixArgs: [] - }) - }) - expect(invocation.command).toBe(command) - } - }) - - it('rereads a changed override instead of storing another copy of the command', () => { - const first = executable() - const second = executable() - const settings = { agentCmdOverrides: { claude: `"${first.command}"` } } - expect(resolveStructuredAgentCommand('claude', settings)).toEqual({ - command: first.command, - prefixArgs: [] - }) - settings.agentCmdOverrides.claude = `"${second.command}"` - expect(resolveStructuredAgentCommand('claude', settings)).toEqual({ - command: second.command, - prefixArgs: [] - }) - }) - - it.each(['', ' ', undefined])('uses the stock executable when the Command is %j', (command) => { - const settings = command === undefined ? {} : { agentCmdOverrides: { claude: command } } - expect(resolveStructuredAgentCommand('claude', settings)).toEqual({ - command: resolveCliCommand('claude'), - prefixArgs: [] - }) - }) - it('refuses missing files, directories, relative paths and command lines instead of the stock executable', () => { const { directory } = executable() const folder = join(directory, 'folder') @@ -132,14 +74,6 @@ describe('structured agent executable resolution', () => { ).toThrow(NOT_RUNNABLE) }) - it('keeps the saved value out of the refusal, since a command line can carry a secret', () => { - expect(() => - resolveStructuredAgentCommand('codex', { - agentCmdOverrides: { codex: 'TOKEN=sk-secret codex' } - }) - ).toThrow(expect.not.objectContaining({ message: expect.stringContaining('sk-secret') })) - }) - describe('on Windows', () => { function fileIn(directory: string, name: string): string { const file = join(directory, name) @@ -160,33 +94,6 @@ describe('structured agent executable resolution', () => { ).toThrow(NOT_RUNNABLE) }) - it('refuses a name whose only match on PATH is extensionless', () => { - const { directory } = executable() - fileIn(directory, 'my-claude') - expect(() => - resolveStructuredAgentCommand( - 'claude', - { agentCmdOverrides: { claude: 'my-claude' } }, - { platform: 'win32', pathEnv: directory, homePath: directory } - ) - ).toThrow(NOT_RUNNABLE) - }) - - it.each(['claude.exe', 'claude.com', 'claude.cmd', 'claude.bat'])( - 'runs an explicit %s path', - (name) => { - const { directory } = executable() - const command = fileIn(directory, name) - expect( - resolveStructuredAgentCommand( - 'claude', - { agentCmdOverrides: { claude: `"${command}"` } }, - { platform: 'win32' } - ) - ).toEqual({ command: command, prefixArgs: [] }) - } - ) - it('uses the execution host grammar for native paths after a PATH launcher', () => { const { directory } = executable() const command = fileIn(directory, 'op.exe') @@ -212,63 +119,5 @@ describe('structured agent executable resolution', () => { ] }) }) - - it('finds the .cmd shim for a bare name, as the stock lookup does', () => { - const { directory } = executable() - fileIn(directory, 'my-claude') - const shim = fileIn(directory, 'my-claude.cmd') - expect( - resolveStructuredAgentCommand( - 'claude', - { agentCmdOverrides: { claude: 'my-claude' } }, - { platform: 'win32', pathEnv: directory, homePath: directory } - ) - ).toEqual({ command: shim, prefixArgs: [] }) - }) - }) -}) - -it('does not refresh or look up again after an expired async missing-program check', async () => { - const cwd = Promise.withResolvers() - const entered = Promise.withResolvers() - let current = true - const resolve = vi.fn(async () => ({ - command: 'absent-fixture-program', - env: { PATH: 'relative-bin' } - })) - const refresh = vi.fn(async () => {}) - const result = resolveAgainAfterRefreshOnMissingProgram( - resolve, - refresh, - { - env: (row) => row.env, - cwd: () => { - entered.resolve() - return cwd.promise - } - }, - { current: () => current } - ).catch((error: unknown) => error) - await entered.promise - current = false - cwd.resolve('/fixture') - expect(await result).toBeInstanceOf(Error) - expect(refresh).not.toHaveBeenCalled() - expect(resolve).toHaveBeenCalledOnce() -}) - -it('expands home-relative prefix words without changing other tildes', () => { - const { command, directory } = executable() - expect( - resolveStructuredAgentCommand( - 'codex', - { - agentCmdOverrides: { codex: `"${command}" --config ~/work.json name~file` } - }, - { homePath: directory } - ) - ).toEqual({ - command, - prefixArgs: ['--config', join(directory, 'work.json'), 'name~file'] }) }) diff --git a/src/main/native-chat/structured-agent-session-history-adoption.test.ts b/src/main/native-chat/structured-agent-session-history-adoption.test.ts deleted file mode 100644 index 2dadbbc7bd7..00000000000 --- a/src/main/native-chat/structured-agent-session-history-adoption.test.ts +++ /dev/null @@ -1,268 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { - findCommittedStructuredAgentSessionAdoptionReplay, - findConflictingStructuredAdoption, - resolveStructuredAgentSessionAdoption, - structuredAdoptionConflictError, - type StructuredAgentSessionAdoptionOwnership -} from './structured-agent-session-history-adoption' -import { PI_SESSION_HISTORY } from '../pi/pi-session-history' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' - -const OPERATION = '1800000000000-00000000000000000000000000000001' - -function committedReplay(overrides: { callerKey?: string; operationId?: string } = {}) { - const lease = agentSessionLeaseFixture({ sessionId: 'codex_adopted' }) - return findCommittedStructuredAgentSessionAdoptionReplay({ - agent: 'codex', - providerSessionId: 'thread-1', - rowSessionId: (link) => link.handle.nativeId, - selfSessionId: 'codex_adopted', - callerKey: overrides.callerKey ?? 'client-1', - operationId: overrides.operationId ?? OPERATION, - record: { - ...agentSessionRecordFixture(lease), - provider: 'codex', - providerHandleChain: [ - { - linkId: 'codex-1-thread-1', - origin: 'adopted', - mintedAtFence: 1, - observedAt: 1_800_000_000_000, - handle: codexProviderHandle('thread-1') - } - ], - accountHome: { variable: 'CODEX_HOME', path: '/home/dev/.codex-original' } - }, - operations: [ - { - callerKey: 'client-1', - operationId: OPERATION, - fingerprint: 'fingerprint-1', - operationTimestamp: 1_800_000_000_000, - recordedAt: 1_800_000_000_000, - expiresAt: 1_900_000_000_000, - outcome: { status: 'succeeded', sessionId: 'codex_adopted' } - } - ] - }) -} - -function ownership( - overrides: Partial = {} -): StructuredAgentSessionAdoptionOwnership { - return { - sessionId: 'codex_owner', - workspaceId: 'workspace-owner', - provider: 'codex', - providerSessionId: 'thread-1', - ownerObservation: agentSessionConversationView(agentSessionRecordFixture()).ownerObservation, - role: 'head', - ...overrides - } -} - -describe('findConflictingStructuredAdoption', () => { - it('names the session continuing the conversation now, never one that held it earlier', () => { - const owner = ownership() - - expect( - findConflictingStructuredAdoption({ - agent: 'codex', - providerSessionId: 'thread-1', - selfSessionId: 'codex_new', - ownership: [ - ownership({ sessionId: 'other', providerSessionId: 'thread-2' }), - ownership({ sessionId: 'moved_on', role: 'earlier' }), - owner - ] - }) - ).toBe(owner) - }) - - it('exempts the requesting session, so a committed create replays instead of refusing', () => { - expect( - findConflictingStructuredAdoption({ - agent: 'codex', - providerSessionId: 'thread-1', - selfSessionId: 'codex_new', - ownership: [ownership({ sessionId: 'codex_new' })] - }) - ).toBeNull() - }) - - it('ignores an identical id held under the other provider', () => { - expect( - findConflictingStructuredAdoption({ - agent: 'claude', - providerSessionId: 'thread-1', - selfSessionId: 'claude_new', - ownership: [ownership({ provider: 'codex' })] - }) - ).toBeNull() - }) - - it.each([ - ['opencode', 'opencode2'], - ['opencode2', 'opencode'] - ] as const)('names an %s chat holding the conversation an %s chat would adopt', (held, agent) => { - const owner = ownership({ provider: held, providerSessionId: 'ses_same' }) - expect( - findConflictingStructuredAdoption({ - agent, - providerSessionId: 'ses_same', - selfSessionId: 'new', - ownership: [owner] - }) - ).toBe(owner) - }) - - it('finds nothing when no session holds the conversation', () => { - expect( - findConflictingStructuredAdoption({ - agent: 'codex', - providerSessionId: 'thread-unheld', - selfSessionId: 'codex_new', - ownership: [ownership()] - }) - ).toBeNull() - }) -}) - -describe('findCommittedStructuredAgentSessionAdoptionReplay', () => { - it('returns the record-pinned account and adopted handle for the exact committed operation', () => { - expect(committedReplay()).toMatchObject({ - record: { accountHome: { path: '/home/dev/.codex-original' } }, - providerHandle: codexProviderHandle('thread-1') - }) - }) - - it('does not cross caller or operation namespaces', () => { - expect(committedReplay({ callerKey: 'client-2' })).toBeNull() - expect(committedReplay({ operationId: `${OPERATION}-other` })).toBeNull() - }) - - it('preserves the adopted Claude leaf that participated in the attach fingerprint', () => { - const lease = agentSessionLeaseFixture({ sessionId: 'claude_adopted' }) - const record = agentSessionRecordFixture(lease) - record.providerHandleChain[0] = { - ...record.providerHandleChain[0]!, - origin: 'adopted', - handle: claudeProviderHandle('provider-session-alpha-1', 'leaf-1') - } - - expect( - findCommittedStructuredAgentSessionAdoptionReplay({ - agent: 'claude', - providerSessionId: 'provider-session-alpha-1', - rowSessionId: (link) => link.handle.nativeId, - selfSessionId: 'claude_adopted', - callerKey: 'client-1', - operationId: OPERATION, - record, - operations: [ - { - callerKey: 'client-1', - operationId: OPERATION, - fingerprint: 'fingerprint-1', - operationTimestamp: 1_800_000_000_000, - recordedAt: 1_800_000_000_000, - expiresAt: 1_900_000_000_000, - outcome: { status: 'succeeded', sessionId: 'claude_adopted' } - } - ] - }) - ).toMatchObject({ - providerHandle: claudeProviderHandle('provider-session-alpha-1', 'leaf-1') - }) - }) -}) - -describe('replaying a Pi adoption, whose handle names its session file', () => { - it("matches the row id the agent's Session History shows the file as", () => { - const file = - '/home/dev/.pi/agent/sessions/--repo--/2026-10-12T00-00-00-000Z_0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a.jsonl' - const lease = agentSessionLeaseFixture({ sessionId: 'pi_adopted' }) - const record = agentSessionRecordFixture(lease) - record.provider = 'pi' - record.providerHandleChain[0] = { - ...record.providerHandleChain[0]!, - origin: 'adopted', - handle: { transport: 'jsonl-rpc', agent: 'pi', nativeId: file } - } - const replay = (providerSessionId: string) => - findCommittedStructuredAgentSessionAdoptionReplay({ - agent: 'pi', - providerSessionId, - rowSessionId: PI_SESSION_HISTORY.rowSessionId, - selfSessionId: 'pi_adopted', - callerKey: 'client-1', - operationId: OPERATION, - record, - operations: [ - { - callerKey: 'client-1', - operationId: OPERATION, - fingerprint: 'fingerprint-1', - operationTimestamp: 1_800_000_000_000, - recordedAt: 1_800_000_000_000, - expiresAt: 1_900_000_000_000, - outcome: { status: 'succeeded', sessionId: 'pi_adopted' } - } - ] - }) - - expect(replay('0198c2a4-7d1e-7c3a-9a4b-1f2e3d4c5b6a')).toMatchObject({ - providerHandle: { nativeId: file } - }) - expect(replay('0198c2a4-7d1e-7c3a-9a4b-000000000000')).toBeNull() - }) -}) - -describe('structuredAdoptionConflictError', () => { - it('calls a conversation with an admitted writer a conflict', () => { - expect(structuredAdoptionConflictError(ownership()).message).toBe('agent_session_conflict') - }) - - it.each([ - ['a reservation with no process yet', { ownerProcess: null, claimStatus: 'reserved' as const }], - ['a lease mid-handoff', { handoffStage: 'new-owner-proving' as const }], - ['an unreconciled lease', { unreconciled: true }] - ])('calls %s an unknown owner rather than a conflict', (_label, leaseOverrides) => { - expect( - structuredAdoptionConflictError( - ownership({ - ownerObservation: agentSessionConversationView( - agentSessionRecordFixture(agentSessionLeaseFixture(leaseOverrides)) - ).ownerObservation - }) - ).message - ).toBe('agent_session_ownership_unknown') - }) -}) - -describe('resolveStructuredAgentSessionAdoption', () => { - it('refuses rather than falling back to a home that does not hold the conversation', async () => { - // Wrong-home resume silently opens a blank chat under the old name. - await expect( - resolveStructuredAgentSessionAdoption({ - providerSessionId: 'session-1', - candidateAccountHomes: [ - { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude-work' }, - { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude' } - ], - resolveTranscript: async () => null, - launchEnv: {}, - workspaceCwd: '/repo' - }) - ).rejects.toThrow('agent_session_identity_required') - }) -}) diff --git a/src/main/native-chat/structured-agent-session-source-admission.test.ts b/src/main/native-chat/structured-agent-session-source-admission.test.ts deleted file mode 100644 index f252431990a..00000000000 --- a/src/main/native-chat/structured-agent-session-source-admission.test.ts +++ /dev/null @@ -1,653 +0,0 @@ -import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -// Adoption forks the AI Vault service for the chat's title; naming is covered elsewhere. -vi.mock('../ai-vault/session-titles/session-title-resolver', () => ({ - resolveLocalAiVaultSessionTitles: async () => ({ titles: [] }) -})) -import { CLAUDE_CLI_CONVERSATIONS } from '../claude/claude-cli-conversations' -import { resolveStructuredAgentSessionAdoptionForCreate } from '../runtime/agent-session/structured-agent-session-create-adoption' -import { - captureStructuredAgentCliSource, - structuredAgentCliSourcePath, - structuredAgentCliSourceFromEvidence, - type StructuredAgentCliSourceEvidence -} from './structured-agent-cli-source' -import { prepareAdoptedTranscript } from './agent-session-wire/structured-agent-session-adopted-import' -import type { AgentSessionAttachParams } from './agent-session-wire/structured-agent-session-attach' -import type { StructuredAgentId } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { prepareLegacyTranscriptImport } from './agent-session-journal/journal-legacy-import' -import { prepareCodexAdoption } from './codex-adoption-preparation' -import { codexAiVaultSessionResumePreparation } from '../codex/history/resume/codex-ai-vault-session-resume' -import * as codexHomes from '../codex/configuration/homes/codex-home-paths' -import { adoptedDirectoryProbes } from './agent-session-journal/adopted-directory-probe' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' - -let root: string -beforeEach(async () => { - root = await realpath(await mkdtemp(join(tmpdir(), 'orca-source-admission-'))) - vi.stubEnv('ORCA_USER_DATA_PATH', join(root, 'user-data')) -}) -afterEach(async () => { - vi.unstubAllEnvs() - vi.restoreAllMocks() - await rm(root, { recursive: true, force: true }) -}) -const id = 'provider-session' -async function file(path: string, records: unknown[]) { - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`) - return path -} -function params(agent: StructuredAgentId, transcriptPath: string): AgentSessionAttachParams { - return { - envelope: { - sessionId: 'new-chat', - clientOperationId: 'create', - expectedRuntimeFence: null, - payloadFingerprint: '' - }, - location: { - executionHostId: 'local', - workspaceId: 'folder', - workspaceKind: 'folder', - wslDistro: null - }, - agent, - provider: agent, - runtimeKind: 'native', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, - adopt: { - providerHandle: { agent, transport: 'terminal-transcript', nativeId: id }, - transcriptPath, - source: { providerSessionId: id, workspaceCwd: root } - } - } -} - -it('preserves exact/Codex and the complete Pi two-link and fallback acceptance without the optional probe', async () => { - const probe = vi - .spyOn(adoptedDirectoryProbes, 'matches') - .mockRejectedValue(new Error('probe unavailable')) - const transcriptPath = join(root, `${id}.jsonl`) - const save = (agent: 'claude' | 'pi', cwd: string, sessionId = id) => - file( - transcriptPath, - agent === 'pi' - ? [ - { type: 'session', id: sessionId, cwd }, - { type: 'message', id: 'turn', message: { role: 'user', content: 'hello' } } - ] - : [ - { - type: 'user', - sessionId, - cwd, - uuid: 'turn', - message: { role: 'user', content: 'hello' } - } - ] - ) - await save('claude', root) - expect(await prepareAdoptedTranscript(params('claude', transcriptPath))).toMatchObject({ - ok: true - }) - const left = join(root, 'left') - const right = join(root, 'right') - for (const link of [left, right]) { - await symlink(root, link, process.platform === 'win32' ? 'junction' : 'dir') - } - const pi = params('pi', transcriptPath) - pi.adopt!.source!.workspaceCwd = left - await save('pi', right) - expect(await prepareAdoptedTranscript(pi)).toMatchObject({ ok: true }) - // Both unavailable paths retain samePiDirectory's established normalize fallback. - pi.adopt!.source!.workspaceCwd = join(root, 'missing', 'pkg') - await save('pi', `${join(root, 'missing')}/./pkg`) - expect(await prepareAdoptedTranscript(pi)).toMatchObject({ ok: true }) - await save('pi', right, 'wrong-header') - expect(await prepareAdoptedTranscript(pi)).toMatchObject({ ok: false }) - await file(transcriptPath, [ - { type: 'session_meta', payload: { id } }, - { type: 'response_item', payload: { type: 'message', role: 'user', content: 'hello' } } - ]) - expect(await prepareAdoptedTranscript(params('codex', transcriptPath))).toMatchObject({ - ok: true - }) - expect(probe).not.toHaveBeenCalled() -}) - -it('creates from the host hook path when Claude filename differs, then checks actual recorded cwd', async () => { - const transcriptPath = await file(join(root, 'projects', 'folder', 'different-uuid.jsonl'), [ - { - type: 'user', - uuid: 'first', - sessionId: id, - cwd: root, - message: { role: 'user', content: 'hello' } - }, - { - type: 'assistant', - uuid: 'reply', - sessionId: id, - cwd: '/later-drift', - message: { role: 'assistant', content: 'reply' } - } - ]) - const sourcePath = () => - structuredAgentCliSourcePath({ - agent: 'claude', - workspaceId: 'folder', - resumeFrom: { - providerSessionId: id, - cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } - }, - rows: [ - { - paneKey: 'tab:leaf', - worktreeId: 'folder', - agentType: 'claude', - state: 'waiting', - prompt: '', - connectionId: null, - receivedAt: 1, - stateStartedAt: 1, - providerSession: { key: 'session_id', id, transcriptPath } - } - ] - }) - const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! - const selectedAccountHome = { variable: 'CLAUDE_CONFIG_DIR', path: root } - vi.spyOn(importer, 'accountHomeCandidates').mockReturnValue([ - selectedAccountHome, - { ...selectedAccountHome, path: join(root, 'locked-account') } - ]) - const admit = importer.admitTranscriptPath.bind(importer) - const admission = vi.spyOn(importer, 'admitTranscriptPath').mockImplementation((args) => { - if (args.store !== join(root, 'projects')) { - throw Object.assign(new Error('Account inaccessible'), { code: 'EACCES' }) - } - return admit(args) - }) - const find = vi.spyOn(importer, 'findTranscript') - const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => ({ kind: 'matched', transcriptPath: sourcePath() }) - }) - expect(adoption.transcriptPath).toBe(transcriptPath) - expect(admission).toHaveBeenCalledOnce() - expect(find).not.toHaveBeenCalled() - await expect( - resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => - structuredAgentCliSourceFromEvidence({ - agent: 'claude', - workspaceId: 'folder', - resumeFrom: { - providerSessionId: id, - cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } - }, - evidence: captureStructuredAgentCliSource( - () => [], - { workspaceId: 'folder', paneKey: 'tab:leaf' }, - () => 'native-local' - ) - }) - }) - ).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) - expect(find).toHaveBeenCalled() - find.mockClear() - expect(await prepareAdoptedTranscript(params('claude', adoption.transcriptPath))).toMatchObject({ - ok: true - }) - const wrongDirectory = params('claude', adoption.transcriptPath) - if (wrongDirectory.adopt?.source) { - wrongDirectory.adopt.source.workspaceCwd = '/another-folder' - } - expect(await prepareAdoptedTranscript(wrongDirectory)).toMatchObject({ - ok: false, - refusal: { details: { reason: 'transcriptUnreadable' } } - }) - - const foreign = await file(join(root, 'foreign.jsonl'), []) - const escaped = process.platform === 'win32' ? foreign : join(root, 'projects', 'escaped.jsonl') - if (process.platform !== 'win32') { - await symlink(foreign, escaped) - } - await expect( - resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: root }, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => ({ kind: 'matched', transcriptPath: escaped }) - }) - ).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) - admission.mockRejectedValueOnce( - Object.assign(new Error('Selected account inaccessible'), { code: 'EACCES' }) - ) - await expect( - resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => ({ kind: 'matched', transcriptPath: sourcePath() }) - }) - ).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) - expect(find).not.toHaveBeenCalled() -}) - -it('imports early and late Claude history with an absent locator and captured native source', async () => { - const transcriptPath = await file(join(root, 'projects', 'folder', `${id}.jsonl`), [ - { - type: 'user', - uuid: 'early', - parentUuid: null, - isSidechain: false, - timestamp: '2026-10-29T18:00:00.000Z', - sessionId: id, - cwd: root, - message: { role: 'user', content: 'early Claude request' } - }, - { - type: 'assistant', - uuid: 'late', - parentUuid: 'early', - isSidechain: false, - timestamp: '2026-10-29T18:10:00.000Z', - sessionId: id, - cwd: root, - message: { role: 'assistant', content: [{ type: 'text', text: 'late Claude reply' }] } - } - ]) - const resumeFrom = { - providerSessionId: id, - cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } - } - const evidence = captureStructuredAgentCliSource( - () => [], - resumeFrom.cliSource, - () => 'native-local' - ) - const selectedAccountHome = { variable: 'CLAUDE_CONFIG_DIR', path: root } - const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! - vi.spyOn(importer, 'accountHomeCandidates').mockReturnValue([selectedAccountHome]) - const store = vi.spyOn(importer, 'conversationStore') - const find = vi.spyOn(importer, 'findTranscript') - const lookup = (captured: StructuredAgentCliSourceEvidence | undefined = evidence) => - resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => - structuredAgentCliSourceFromEvidence({ - agent: 'claude', - workspaceId: 'folder', - resumeFrom, - evidence: captured - }) - }) - for (const captured of [ - captureStructuredAgentCliSource(() => []), - captureStructuredAgentCliSource( - () => [], - resumeFrom.cliSource, - () => 'unknown' - ), - captureStructuredAgentCliSource( - () => [], - resumeFrom.cliSource, - () => { - throw new Error('route unreadable') - } - ), - captureStructuredAgentCliSource( - () => { - throw new Error('rows unreadable') - }, - resumeFrom.cliSource, - () => 'native-local' - ), - captureStructuredAgentCliSource( - () => [], - { ...resumeFrom.cliSource, workspaceId: 'other' }, - () => 'native-local' - ) - ]) { - await expect(lookup(captured)).rejects.toMatchObject({ - refusal: { details: { reason: 'transcriptUnreadable' } } - }) - } - await expect( - lookup( - captureStructuredAgentCliSource( - () => [], - resumeFrom.cliSource, - () => 'unsupported' - ) - ) - ).rejects.toMatchObject({ refusal: { details: { reason: 'hostUnsupported' } } }) - const row: AgentStatusIpcPayload = { - paneKey: 'tab:leaf', - worktreeId: 'folder', - agentType: 'claude', - state: 'waiting', - prompt: '', - connectionId: null, - receivedAt: 1, - stateStartedAt: 1, - providerSession: { key: 'session_id', id, transcriptPath } - } - for (const change of [ - { providerSession: undefined }, - { providerSession: { ...row.providerSession!, id: 'new-run' } }, - { worktreeId: 'other' }, - { agentType: 'codex' }, - { connectionId: 'ssh' }, - { structuredHost: 'owned' as const } - ]) { - await expect( - lookup( - captureStructuredAgentCliSource( - () => [{ ...row, ...change }], - resumeFrom.cliSource, - () => 'native-local' - ) - ) - ).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptUnreadable' } } }) - } - const resolve = (captured: StructuredAgentCliSourceEvidence, workspaceId = 'folder') => - structuredAgentCliSourceFromEvidence({ - agent: 'claude', - workspaceId, - resumeFrom, - evidence: captured - }) - expect(() => resolve(evidence, 'other')).toThrow('agent_session_identity_required') - const routeFault = () => { - throw new Error('unused route failure') - } - expect( - resolve( - captureStructuredAgentCliSource( - () => [row, { ...row, worktreeId: 'other' }], - resumeFrom.cliSource, - routeFault - ) - ) - ).toEqual({ kind: 'matched', transcriptPath }) - expect( - resolve( - captureStructuredAgentCliSource( - () => [{ ...row, providerSession: { key: 'session_id', id } }], - resumeFrom.cliSource, - routeFault - ) - ) - ).toEqual({ kind: 'matched' }) - expect(find).not.toHaveBeenCalled() - const adoption = await lookup() - expect(resumeFrom.cliSource).toEqual({ workspaceId: 'folder', paneKey: 'tab:leaf' }) - expect(adoption).toEqual({ accountHome: selectedAccountHome, transcriptPath }) - expect(store).toHaveBeenCalledOnce() - const prepared = await prepareAdoptedTranscript(params('claude', adoption.transcriptPath)) - expect(prepared).toMatchObject({ ok: true }) - if (!prepared.ok) { - throw new Error('Claude history was not imported') - } - expect(prepared.items).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - blocks: expect.arrayContaining([ - expect.objectContaining({ text: 'early Claude request' }) - ]) - }) - }), - expect.objectContaining({ - body: expect.objectContaining({ - blocks: expect.arrayContaining([expect.objectContaining({ text: 'late Claude reply' })]) - }) - }) - ]) - ) -}) - -it('judges the lookup and its re-admission against one store resolved once per account', async () => { - const transcriptPath = await file(join(root, 'projects', 'folder', `${id}.jsonl`), []) - const importer = CLAUDE_CLI_CONVERSATIONS.transcriptImport! - const selectedAccountHome = { variable: 'CLAUDE_CONFIG_DIR', path: root } - vi.spyOn(importer, 'accountHomeCandidates').mockReturnValue([selectedAccountHome]) - const store = vi.spyOn(importer, 'conversationStore') - const find = vi.spyOn(importer, 'findTranscript') - const admission = vi.spyOn(importer, 'admitTranscriptPath') - const adoption = await resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: importer, - providerSessionId: id, - selectedAccountHome, - launchEnv: {}, - workspaceCwd: root - }) - expect(adoption.transcriptPath).toBe(transcriptPath) - expect(store).toHaveBeenCalledOnce() - expect(find.mock.calls[0]?.[0].store).toBe(join(root, 'projects')) - expect(admission.mock.calls[0]?.[0].store).toBe(join(root, 'projects')) -}) - -it.skipIf(process.platform === 'win32')( - 'reports a not-yet-saved conversation under a linked account folder as unsaved', - async () => { - const linked = join(root, 'linked-account') - await mkdir(join(root, 'projects'), { recursive: true }) - await symlink(root, linked) - await expect( - resolveStructuredAgentSessionAdoptionForCreate({ - settings: {}, - agent: 'claude', - transcriptImport: CLAUDE_CLI_CONVERSATIONS.transcriptImport!, - providerSessionId: id, - selectedAccountHome: { variable: 'CLAUDE_CONFIG_DIR', path: linked }, - launchEnv: {}, - workspaceCwd: root, - resolveTranscriptSource: () => ({ - kind: 'matched', - transcriptPath: join(linked, 'projects', 'folder', `${id}.jsonl`) - }) - }) - ).rejects.toMatchObject({ refusal: { details: { reason: 'transcriptNotFound' } } }) - } -) - -it.each(['claude', 'codex', 'grok', 'omp', 'pi'] as const)( - 'retains empty versus unreadable source facts for %s', - async (agent) => { - const transcript = join(root, `${id}.jsonl`) - await writeFile(transcript, '') - expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ - ok: false, - refusal: { details: { reason: 'transcriptNotFound' } } - }) - for (const content of ['{broken json}\n', '{"type":"future_record"}\n']) { - await writeFile(transcript, content) - expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ - ok: false, - refusal: { details: { reason: 'transcriptUnreadable' } } - }) - } - } -) - -it('checks canonical provider metadata during the existing import, including Codex copied parent metadata', async () => { - const codex = await file(join(root, `${id}.jsonl`), [ - { type: 'session_meta', payload: { id } }, - { type: 'session_meta', payload: { id: 'copied-parent' } }, - { type: 'response_item', payload: { type: 'message', role: 'user', content: 'hello' } } - ]) - expect(await prepareAdoptedTranscript(params('codex', codex))).toMatchObject({ ok: true }) - for (const agent of ['omp', 'pi'] as const) { - const transcript = await file(join(root, `${id}.jsonl`), [ - { type: 'session', id, cwd: root }, - { - type: 'message', - id: 'turn', - message: { role: 'user', content: [{ type: 'text', text: 'hello' }] } - } - ]) - expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: true }) - await file(transcript, [{ type: 'session', id: 'foreign', cwd: root }]) - expect(await prepareAdoptedTranscript(params(agent, transcript))).toMatchObject({ ok: false }) - } - const grok = await file(join(root, id, 'chat_history.jsonl'), [ - { type: 'user', content: 'hello' } - ]) - await file(join(root, id, 'summary.json'), [{ info: { id, cwd: root } }]) - expect(await prepareAdoptedTranscript(params('grok', grok))).toMatchObject({ ok: true }) - await rm(join(root, id, 'summary.json')) - expect(await prepareAdoptedTranscript(params('grok', grok))).toMatchObject({ - ok: false, - refusal: { details: { reason: 'transcriptUnreadable' } } - }) - await file(codex, [{ type: 'session_meta', payload: { id } }]) - expect( - await prepareLegacyTranscriptImport({ - agent: 'codex', - sessionId: id, - options: { filePath: codex } - }) - ).toMatchObject({ ok: true, items: [], sourceEmpty: false }) - expect(await prepareAdoptedTranscript(params('codex', codex))).toMatchObject({ - ok: false, - refusal: { details: { reason: 'transcriptUnreadable' } } - }) -}) - -it('materializes legacy Codex into the system home and pins a verified selected account alias', async () => { - const legacy = codexHomes.getOrcaManagedCodexHomePath() - const system = join(root, 'system') - const historyOnly = join(root, 'history-only') - const selected = join(root, 'codex-accounts', 'selected', 'home') - const suffix = join('sessions', '2026', '10', '15', `rollout-stamp-${id}.jsonl`) - const transcriptPath = await file(join(legacy, suffix), [ - { type: 'session_meta', payload: { id } } - ]) - vi.spyOn(codexHomes, 'getSystemCodexHomePath').mockReturnValue(system) - const source = { accountHome: { variable: 'CODEX_HOME' as const, path: legacy }, transcriptPath } - const prepare = codexAiVaultSessionResumePreparation(() => ({ - runtimeHome: { - isHostSystemDefaultRealHomeSelected: () => true, - resolveSelectedHostAccountCodexHomePathForResume: () => null, - getHostCodexHomePathsForSessionDiscovery: () => [legacy] - }, - systemCodexHomePath: historyOnly, - preparePinnedLaunchHome: async () => {} - })) - const migrated = await prepareCodexAdoption(source, id, prepare, [source.accountHome]) - expect(migrated).toEqual({ - accountHome: { variable: 'CODEX_HOME', path: system }, - transcriptPath: join(system, suffix) - }) - await expect( - prepareLegacyTranscriptImport({ - agent: 'codex', - sessionId: id, - options: { filePath: join(historyOnly, suffix) } - }) - ).resolves.toMatchObject({ ok: false }) - await prepare({ - agent: 'codex', - sessionId: id, - filePath: transcriptPath, - codexHome: legacy, - executionHostId: 'local' - }) - expect( - await prepareLegacyTranscriptImport({ - agent: 'codex', - sessionId: id, - options: { filePath: join(historyOnly, suffix) } - }) - ).toMatchObject({ ok: true }) - await file(join(selected, suffix), [{ type: 'session_meta', payload: { id } }]) - expect( - await prepareCodexAdoption( - migrated, - id, - async () => ({ useRealCodexHome: false, substituteCodexHome: selected }), - [{ variable: 'CODEX_HOME', path: selected }] - ) - ).toEqual({ - accountHome: { variable: 'CODEX_HOME', path: selected }, - transcriptPath: join(selected, suffix) - }) - await expect( - prepareCodexAdoption( - source, - id, - async () => { - throw new Error('EACCES selected account') - }, - [source.accountHome] - ) - ).rejects.toThrow('EACCES selected account') -}) - -it.each([ - ['opencode', true], - ['opencode2', true], - ['claude', false] -] as const)('lets a %s chat take over an `opencode` pane: %s', (agent, allowed) => { - const sourcePath = () => - structuredAgentCliSourcePath({ - agent, - workspaceId: 'folder', - resumeFrom: { - providerSessionId: 'ses_1', - cliSource: { workspaceId: 'folder', paneKey: 'tab:leaf' } - }, - rows: [ - { - paneKey: 'tab:leaf', - worktreeId: 'folder', - agentType: 'opencode', - state: 'waiting', - prompt: '', - connectionId: null, - receivedAt: 1, - stateStartedAt: 1, - providerSession: { key: 'session_id', id: 'ses_1', transcriptPath: '/data/opencode.db' } - } - ] - }) - if (allowed) { - expect(sourcePath()).toBe('/data/opencode.db') - } else { - expect(sourcePath).toThrow('agent_session_identity_required') - } -}) diff --git a/src/main/native-chat/structured-chat-naming-execution.test.ts b/src/main/native-chat/structured-chat-naming-execution.test.ts deleted file mode 100644 index 958c5045fbf..00000000000 --- a/src/main/native-chat/structured-chat-naming-execution.test.ts +++ /dev/null @@ -1,261 +0,0 @@ -import { cancelLocalGeneration } from '../text-generation/source-control-generation-lanes' -import { AgentSessionJournal } from './agent-session-journal/journal-store' -import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import { structuredChatNamingDeps } from '../runtime/agent-session/naming/structured-chat-naming-runtime' -import { getDefaultSettings } from '../../shared/constants' -import { normalizeSourceControlAiSettings } from '../../shared/source-control/ai/settings/source-control-ai-settings' -import { setStructuredAgentSessionHost } from './agent-session-wire/structured-agent-session-registry' -import * as agentLaunch from '../text-generation/source-control-agent-launch' -import * as homeLock from '../codex-cli/codex-home-process-lock' -import { createMockDiscoveryChild } from '../text-generation/commit-message-text-generation-test-harness' -import { expect, it, onTestFinished, vi } from 'vitest' -import { createStructuredChatNamingHandler } from './structured-chat-naming' -import { - attach, - CALLER, - envelope, - hostTestState -} from './agent-session-wire/structured-agent-session-host-test-harness' -import { - hostTestAttachParams, - HOST_TEST_SESSION, - hostTestMessage -} from './agent-session-wire/structured-agent-session-host-test-data' - -async function send(text: string, sessionId = HOST_TEST_SESSION) { - const body = hostTestMessage(text) - const mutation = { method: 'agentSession.send', sessionId, fields: { body } } - expect( - await hostTestState().host.send(CALLER, { - body, - envelope: envelope(mutation.method, mutation.fields, { - sessionId, - payloadFingerprint: computeAgentSessionPayloadFingerprint(mutation) - }) - }) - ).toMatchObject({ ok: true }) -} -async function clearContext() { - expect( - await hostTestState().host.conversationCommand(CALLER, { - envelope: envelope('agentSession.conversationCommand', { command: 'clear' }), - command: 'clear' - }) - ).toMatchObject({ ok: true }) -} - -function titleChild(title: string) { - const child = createMockDiscoveryChild() - queueMicrotask(() => { - child.stdout.emit('data', Buffer.from(title)) - child.emit('close', 0) - }) - return child -} - -function productionNaming(home: string) { - const { host, store, log } = hostTestState() - setStructuredAgentSessionHost(host) - onTestFinished(() => { - setStructuredAgentSessionHost(null) - vi.restoreAllMocks() - }) - const settings = getDefaultSettings('/isolated') - settings.defaultTuiAgent = 'codex' - settings.sourceControlAi = normalizeSourceControlAiSettings({ - ...normalizeSourceControlAiSettings(settings.sourceControlAi), - actions: { conversationName: { agentId: 'codex' } } - }) - const deps = structuredChatNamingDeps( - () => ({ getSettings: () => settings }), - { - resolveWorkspace: async () => ({ path: '/same-folder', executionHostId: 'local' }), - resolveNamingEnvironment: async () => ({ CODEX_HOME: home }), - getAgentEnvResolvers: () => ({ - resolveBaseEnvironment: async () => ({ CODEX_HOME: home }) - }), - workerTaskTitle: () => null, - retitleOpenTab: () => {} - }, - log.logger - ) - const naming = createStructuredChatNamingHandler({ ...deps, now: () => 0 }) - host.deps.onSessionStatusChanged = naming - host.deps.conversationNaming = naming - return { host, store, naming, settings } -} - -it.each([ - [10, 'latest'], - [100, 'latest'], - [10, 'manual'], - [10, 'off'], - [10, 'cancel'] -] as const)('bounds actual title admission across %i seeded contexts (%s)', async (count, mode) => { - const home = `/isolated/naming-${count}` - const { host, store, naming, settings } = productionNaming(home) - const held = Promise.withResolvers() - let pending = 0 - const lock = homeLock.withCodexHomeProcessLock - const admissions = vi - .spyOn(homeLock, 'withCodexHomeProcessLock') - .mockImplementation((key: string, callback: () => Promise) => { - pending++ - return lock(key, callback).finally(() => { - pending-- - }) - }) - const predecessor = homeLock.withCodexHomeProcessLock(home, () => held.promise) - const order: string[] = [] - const spawn = vi.spyOn(agentLaunch, 'spawnSourceControlAgent').mockImplementation(() => { - order.push(spawn.mock.calls.length === 1 ? 'B' : 'A') - return titleChild('Latest title') - }) - await attach() - for (let index = 0; index < count; index++) { - if (index) { - await clearContext() - } - await send(`Context ${index}`) - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe(`Context ${index}`) - ) - await host.cancel(CALLER, { - envelope: envelope('agentSession.cancel', { turnId: 'turn-1' }), - turnId: 'turn-1' - }) - } - await vi.waitFor(() => expect(admissions).toHaveBeenCalledTimes(2)) - expect(spawn).not.toHaveBeenCalled() - if (mode === 'cancel') { - cancelLocalGeneration('conversation-name', '/same-folder') - await new Promise((done) => setImmediate(done)) - expect(pending).toBe(2) - expect(admissions).toHaveBeenCalledTimes(2) - } - const unrelated = homeLock.withCodexHomeProcessLock(home, async () => { - order.push('U') - }) - const other = hostTestAttachParams(null) - other.envelope.sessionId = 'session-beta' - expect( - await host.attach(CALLER, hostTestAttachParams(null, { envelope: other.envelope })) - ).toMatchObject({ ok: true }) - await send('Same folder, other chat', 'session-beta') - await vi.waitFor(() => expect(admissions).toHaveBeenCalledTimes(4)) - expect(pending).toBe(4) - if (mode === 'manual') { - await naming.setUserName(HOST_TEST_SESSION, 'Manual', 'rename') - } - if (mode === 'off') { - settings.nativeChatAutoName = false - } - held.resolve() - await Promise.all([predecessor, unrelated]) - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe( - mode === 'manual' ? 'Manual' : mode === 'off' ? `Context ${count - 1}` : 'Latest title' - ) - ) - await vi.waitFor(() => expect(pending).toBe(0)) - expect(order).toEqual(mode === 'off' ? ['U'] : mode === 'manual' ? ['U', 'B'] : ['U', 'B', 'A']) - expect(admissions).toHaveBeenCalledTimes(mode === 'manual' || mode === 'off' ? 4 : 5) - expect(spawn).toHaveBeenCalledTimes(mode === 'off' ? 0 : mode === 'manual' ? 1 : 2) - expect(naming.activeSessionIds()).toEqual([]) -}) - -it.each([10, 100])( - 'bounds reopened source and seed supersession across %i contexts', - async (count) => { - const { host, store } = hostTestState() - await attach() - const sendAndWait = async (text: string) => { - await send(text) - await vi.waitFor(() => - expect(host.readStatusSummary(HOST_TEST_SESSION)?.status).toBe('working') - ) - } - const clear = async () => { - await host.cancel(CALLER, { - envelope: envelope('agentSession.cancel', { turnId: 'turn-1' }), - turnId: 'turn-1' - }) - await clearContext() - } - await sendAndWait('Old journal input') - await host.close(HOST_TEST_SESSION, 'evict') - const { naming } = productionNaming('/isolated/source-proof') - const opening = Promise.withResolvers() - const open = AgentSessionJournal.prototype.open - let openOutstanding = 0, - openPeak = 0 - const opens = vi - .spyOn(AgentSessionJournal.prototype, 'open') - .mockImplementation(async function (this: AgentSessionJournal) { - openPeak = Math.max(openPeak, ++openOutstanding) - try { - await opening.promise - return await open.call(this) - } finally { - openOutstanding-- - } - }) - const reads = vi.spyOn(host, 'journalCurrentRead') - const seed = Promise.withResolvers() - const generated = Promise.withResolvers() - const publications = vi.spyOn(host, 'publishConversationName') - const phases: [string, number][] = [] - const cas = store.compareAndSetConversationName - vi.spyOn(store, 'compareAndSetConversationName').mockImplementation(async (...args) => { - const result = await cas(...args) - phases.push([args[1] === 'Current title' ? 'result' : 'seed', publications.mock.calls.length]) - await (args[1] !== 'Current title' ? seed.promise : generated.promise) - return result - }) - const spawn = vi - .spyOn(agentLaunch, 'spawnSourceControlAgent') - .mockImplementation(() => titleChild('Current title')) - onTestFinished(() => { - opening.resolve() - seed.resolve() - generated.resolve() - }) - naming.regenerate(HOST_TEST_SESSION) - for (let index = 0; index < count; index++) { - naming.regenerate(HOST_TEST_SESSION) - } - await vi.waitFor(() => expect(opens).toHaveBeenCalledOnce()) - expect(openOutstanding).toBe(1) - opening.resolve() - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Current title') - ) - // A new live input seeds independently of the held result, then newer clears supersede it. - for (let index = 0; index < count; index++) { - await clear() - await sendAndWait(`Input ${index}`) - } - expect(reads).toHaveBeenCalledTimes(2) - expect(spawn).toHaveBeenCalledOnce() - await clear() - const beforeLatest = publications.mock.calls.length - await sendAndWait('Final input') - seed.resolve() - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Final input') - ) - expect(openPeak).toBe(1) - expect(openOutstanding).toBe(0) - expect(reads).toHaveBeenCalledTimes(3) - expect(phases.at(-1)).toEqual(['seed', beforeLatest + 2]) - const resultPublications = publications.mock.calls.length - expect(naming.activeSessionIds()).toEqual([HOST_TEST_SESSION]) - generated.resolve() - await vi.waitFor(() => expect(naming.activeSessionIds()).toEqual([])) - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Current title') - expect(phases.at(-1)).toEqual(['result', resultPublications + 2]) - expect(publications).toHaveBeenCalledTimes(resultPublications + 4) - expect(phases.filter(([phase]) => phase === 'seed')).toHaveLength(2) - expect(spawn).toHaveBeenCalledTimes(2) - } -) diff --git a/src/main/native-chat/structured-chat-naming-publication.test.ts b/src/main/native-chat/structured-chat-naming-publication.test.ts deleted file mode 100644 index 1b9fee327f0..00000000000 --- a/src/main/native-chat/structured-chat-naming-publication.test.ts +++ /dev/null @@ -1,255 +0,0 @@ -import '../runtime/rpc/unused-default-rpc-methods.test-fixture' -import { expect, it, vi } from 'vitest' -import { getDefaultSettings, getDefaultWorkspaceSession } from '../../shared/constants' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../shared/agent-session/agent-session-runtime-capabilities' -import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { agentSessionRecordFixture } from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { codexProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { listResult } from '../ai-vault/structured-session-ownership.test-support' -import * as scanner from '../ai-vault/scan-service/session-scanner-background' -import { resetAiVaultSessionListCacheForTests } from '../ai-vault/cached-session-list' -import { OrcaRuntimeService } from '../runtime/orca-runtime' -import { RpcDispatcher } from '../runtime/rpc/dispatcher' -import { AI_VAULT_METHODS } from '../runtime/rpc/methods/ai-vault' -import { structuredChatNamingDeps } from '../runtime/agent-session/naming/structured-chat-naming-runtime' -import { createStructuredChatNamingHandler } from './structured-chat-naming' -import { setStructuredAgentSessionHost } from './agent-session-wire/structured-agent-session-registry' -import { - attach, - CALLER, - envelope, - hostTestState -} from './agent-session-wire/structured-agent-session-host-test-harness' -import { - HOST_TEST_SESSION, - HOST_TEST_THREAD -} from './agent-session-wire/structured-agent-session-host-test-data' - -it.each(['J', 'R', 'P', 'L', 'T', 'U', 'C'] as const)( - 'counts actual naming, ownership, tab and transport work as %s varies independently', - async (population) => { - for (const n of [10, 100]) { - const sizes = { J: 10, R: 10, P: 10, L: 10, T: 10, U: 10, C: 10 } - sizes[population] = n - if (population === 'J') { - sizes.R = 100 - } - const { host, store, log } = hostTestState() - await attach() - setStructuredAgentSessionHost(host) - const runtime = new OrcaRuntimeService() - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() - const source = Promise.withResolvers() - const naming = createStructuredChatNamingHandler({ - ...structuredChatNamingDeps( - () => ({ getSettings: () => getDefaultSettings('/isolated') }), - { - resolveWorkspace: async () => ({ path: '/fixture', executionHostId: 'local' }), - resolveNamingEnvironment: async () => ({}), - getAgentEnvResolvers: () => undefined, - workerTaskTitle: () => null, - retitleOpenTab: runtime.refreshStructuredConversationTabTitle.bind(runtime) - }, - log.logger - ), - readJournalFirstPrompt: () => source.promise - }) - host.deps.conversationNaming = naming - let recordVisits = 0, - linkVisits = 0, - rowVisits = 0, - labelVisits = 0 - const id = (index: number) => - index < 0 ? 'unrelated' : index ? `population-${index}` : HOST_TEST_SESSION - const get = store.getRecord - const getConversation = store.getConversation - const providerId = (sessionId: string) => - sessionId === HOST_TEST_SESSION ? HOST_TEST_THREAD : `renderer-provider-${sessionId}` - const records = Array.from({ length: sizes.R }, (_, index) => ({ - ...agentSessionRecordFixture(), - sessionId: id(index), - provider: 'codex' as const, - conversationName: 'Before', - get providerHandleChain() { - recordVisits++ - return Array.from({ length: index === 1 ? sizes.P : 1 }, (_, link) => ({ - ...agentSessionRecordFixture().providerHandleChain[0]!, - get handle() { - linkVisits++ - return codexProviderHandle(link ? `extra-provider-${link}` : providerId(id(index))) - } - })) - } - })) - const byId = new Map(records.map((record) => [record.sessionId, record])) - const conversations = records.map((record) => ({ - ...agentSessionConversationView(record), - get providerHandleChain() { - return record.providerHandleChain - } - })) - const conversationsById = new Map(conversations.map((view) => [view.sessionId, view])) - const lookup = vi - .spyOn(store, 'getRecord') - .mockImplementation((id) => get(id) ?? byId.get(id) ?? null) - const conversationLookup = vi - .spyOn(store, 'getConversation') - .mockImplementation((id) => getConversation(id) ?? conversationsById.get(id) ?? null) - const list = vi - .spyOn(store, 'listConversations') - .mockImplementation(() => [getConversation(HOST_TEST_SESSION)!, ...conversations.slice(1)]) - for (let index = 0; index < sizes.J; index++) { - naming.regenerate(id(index)) - } - const workspace = 'workspace-1' - for (let index = 0; index < sizes.T; index++) { - runtime.projectStructuredAgentSessionTab({ - activate: false, - sessionId: id(index), - workspaceId: workspace, - agent: 'codex' - }) - } - const session = getDefaultWorkspaceSession() - session.unifiedTabs = { - [workspace]: Array.from({ length: sizes.U }, (_, index) => ({ - id: `saved-${index}`, - contentType: 'agent-session' as const, - label: 'Codex Chat', - groupId: 'fixture-group', - worktreeId: workspace, - customLabel: null, - color: null, - sortOrder: index, - createdAt: 0, - get entityId() { - labelVisits++ - return id(index - Math.max(sizes.U - sizes.T, 0)) - } - })) - } - vi.spyOn(runtime, 'getWorkspaceSessionForWorktree').mockReturnValue(session) - const row = listResult().sessions[0]! - resetAiVaultSessionListCacheForTests() - const scan = vi.spyOn(scanner, 'scanAiVaultSessionsInBackground').mockResolvedValue({ - ...listResult(), - sessions: Array.from({ length: sizes.L }, () => ({ - ...row, - get sessionId() { - rowVisits++ - return HOST_TEST_THREAD - } - })) - }) - const client = { - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY] - } - const dispatcher = new RpcDispatcher({ runtime, methods: AI_VAULT_METHODS }) - const rpc = () => - dispatcher.dispatch( - { - id: 'list', - authToken: 'fixture', - method: 'aiVault.listSessions', - params: { executionHostId: 'runtime:paired-host' } - }, - client - ) - const deliveries: string[] = [] - const subscriptions = Array.from({ length: sizes.C }, (_, index) => - host.subscribeStatus({ - id: `consumer-${index}`, - emit: (event) => deliveries.push(JSON.stringify(event)) - }) - ) - const tabs: string[] = [] - subscriptions.push( - ...Array.from({ length: sizes.C }, () => - runtime.onMobileSessionTabsChanged((value) => tabs.push(JSON.stringify(value))) - ) - ) - try { - lookup.mockClear() - conversationLookup.mockClear() - list.mockClear() - recordVisits = linkVisits = rowVisits = labelVisits = 0 - deliveries.length = 0 - host.publishConversationName(HOST_TEST_SESSION) - const snapshots = deliveries.filter((event) => event.includes('namingActiveSessionIds')) - expect(snapshots).toHaveLength(sizes.C) - expect(JSON.parse(snapshots[0]!).namingActiveSessionIds).toHaveLength(sizes.J) - expect( - lookup.mock.calls.length + conversationLookup.mock.calls.length - ).toBeGreaterThanOrEqual(sizes.J + 1) - expect(lookup.mock.calls.length + conversationLookup.mock.calls.length).toBeLessThanOrEqual( - sizes.J + 10 - ) - expect(list).not.toHaveBeenCalled() - for (let index = 0; index < sizes.C; index++) { - const response = JSON.parse(JSON.stringify(await rpc())) - expect(response.ok).toBe(true) - expect(response.result.sessions).toHaveLength(sizes.L) - for (const session of response.result.sessions) { - expect(session).toMatchObject({ - executionHostId: 'runtime:paired-host', - structuredSession: { sessionId: HOST_TEST_SESSION, workspaceId: workspace } - }) - } - } - expect(list).toHaveBeenCalledTimes(sizes.C) - expect(recordVisits).toBe(2 * sizes.C * (sizes.R - 1)) - expect(linkVisits).toBe(sizes.C * (sizes.R - 1 + 2 * (sizes.P + sizes.R - 2))) - expect(rowVisits).toBe(2 * sizes.L * sizes.C) - expect(scan).toHaveBeenCalledOnce() - await store.setConversationName(HOST_TEST_SESSION, `Before ${n}`) - labelVisits = 0 - tabs.length = 0 - naming.publishName(workspace, HOST_TEST_SESSION) - expect(tabs).toHaveLength(sizes.C) - // Counts the inherited populated-label lookup; its owner must remove this amplification. - const comparisons = - Math.max(sizes.U - sizes.T, 0) + - 1 + - Array.from({ length: sizes.T }, (_, index) => - Math.min(sizes.U, Math.max(sizes.U - sizes.T, 0) + index + 1) - ).reduce((a, b) => a + b, 0) - expect(labelVisits).toBe(comparisons) - const command = { - envelope: envelope('agentSession.conversationCommand', { command: 'clear' }), - command: 'clear' as const - } - const publication = vi.spyOn(naming, 'publishName') - expect(await host.conversationCommand(CALLER, command)).toMatchObject({ ok: true }) - expect(publication).toHaveBeenCalledOnce() - const retired = await rpc() - expect(retired).toMatchObject({ ok: true }) - expect(JSON.stringify(retired)).not.toContain(`"sessionId":"${HOST_TEST_SESSION}"`) - expect(tabs.at(-1)).toContain('Codex Chat') - await store.setConversationName(HOST_TEST_SESSION, 'Newer name') - expect(await host.conversationCommand(CALLER, command)).toMatchObject({ ok: true }) - expect(publication).toHaveBeenCalledTimes(2) - expect(get(HOST_TEST_SESSION)?.conversationName).toBe('Newer name') - expect(tabs.at(-1)).toContain('Newer name') - expect( - await host.conversationCommand(CALLER, { - ...command, - envelope: { - ...command.envelope, - clientOperationId: crypto.randomUUID(), - expectedRuntimeFence: 0 - } - }) - ).toMatchObject({ ok: false }) - expect(publication).toHaveBeenCalledTimes(2) - } finally { - subscriptions.forEach((stop) => stop()) - source.resolve('') - await vi.waitFor(() => expect(naming.activeSessionIds()).toEqual([])) - vi.restoreAllMocks() - resetAiVaultSessionListCacheForTests() - setStructuredAgentSessionHost(null) - } - } - } -) diff --git a/src/main/native-chat/structured-chat-naming.test.ts b/src/main/native-chat/structured-chat-naming.test.ts deleted file mode 100644 index 084ca5d015e..00000000000 --- a/src/main/native-chat/structured-chat-naming.test.ts +++ /dev/null @@ -1,785 +0,0 @@ -import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/agent-session-conversation-view' -import { OrchestrationDb } from '../runtime/orchestration/db' -import { - structuredWorkerOpenTaskTitle, - structuredWorkerOwesWork -} from '../runtime/orchestration/terminal-authority/structured-sessions/structured-worker-custody' -import { - mintStructuredWorkerHandle, - mintStructuredWorkerPaneKey, - structuredWorkerProcessIncarnation -} from '../runtime/orchestration/terminal-authority/structured-sessions/structured-worker-identity' -import { describe, expect, it, onTestFinished, vi } from 'vitest' -import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' -import { agentSessionRecordFixture } from '../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { StructuredAgentSessionStatusFeed } from './agent-session-wire/structured-agent-session-status-feed' -import type { - AgentSessionStatusEvent, - AgentSessionStatusSummary -} from '../../shared/agent-session/agent-session-wire' -import { agentSessionCurrentContextRows } from '../../shared/agent-session/agent-session-context-clear' -import { - firstStructuredAgentSessionPrompt, - STRUCTURED_CHAT_NAME_PROMPT_LIMIT -} from '../../shared/agent-session/requests/structured-agent-session-first-prompt' -import { - type AgentSessionUserNameWrite, - compareAndSetAgentSessionRecordName, - setAgentSessionRecordUserName -} from '../runtime/agent-session/records/agent-session-record-conversation-name' -import { - createStructuredChatNamingHandler, - type StructuredChatNameGeneration, - type StructuredChatNamingDeps -} from './structured-chat-naming' -import { firstStructuredChatNamingPrompt } from '../../shared/structured-chat-naming-eligibility' -import { - attach, - CALLER, - envelope, - hostTestState -} from './agent-session-wire/structured-agent-session-host-test-harness' -import { - HOST_TEST_SESSION, - hostTestMessage -} from './agent-session-wire/structured-agent-session-host-test-data' - -function deferred() { - let resolve: (value: T) => void = () => { - throw new Error('Deferred not initialized') - } - const promise = new Promise((complete) => { - resolve = complete - }) - return { promise, resolve } -} - -async function settle() { - for (let index = 0; index < 12; index += 1) { - await Promise.resolve() - } -} - -function rig(provider: 'claude' | 'codex') { - let record: AgentSessionRecord | null = { ...agentSessionRecordFixture(), provider } - const getRecord = vi.fn(() => record) - // The store's own rules, over this rig's one record. - const mutate = async (apply: (current: AgentSessionRecord) => AgentSessionRecord) => { - if (!record) { - throw new Error('Missing record') - } - record = apply(record) - return record - } - const setConversationName = vi.fn( - (_id: string, name: string | null, expected: string | null, contextId?: string | null) => - compareAndSetAgentSessionRecordName(mutate, name, expected, contextId) - ) - const setUserConversationName = vi.fn( - async (_id: string, name: string, write: AgentSessionUserNameWrite) => { - let applied = false - const next = await mutate((current) => { - const result = setAgentSessionRecordUserName(current, name, write, Date.now()) - applied = result.applied - return result.record - }) - return { record: next, applied } - } - ) - const deps: StructuredChatNamingDeps = { - getStore: () => ({ - getRecord, - compareAndSetConversationName: setConversationName, - setUserConversationName - }), - getSettings: () => ({}), - now: () => 100, - workerTaskTitle: vi.fn(() => null), - readFirstPrompt: vi.fn(async () => 'Please repair the login flow'), - readJournalFirstPrompt: vi.fn(async () => 'Please repair the login flow'), - generate: vi.fn(async (): Promise => ({ name: 'auth/login' })), - onNamed: vi.fn(), - logger: { warn: vi.fn(), error: vi.fn() }, - wait: vi.fn(async () => {}) - } - const summary: AgentSessionStatusSummary = { - sessionId: record.sessionId, - workspaceId: record.location.workspaceId, - agent: provider, - status: 'working', - latestPrompt: 'login preview', - updatedAt: 100 - } - return { - deps, - summary, - getRecord, - setConversationName, - setUserConversationName, - handle: createStructuredChatNamingHandler(deps), - read: () => record, - replace: (next: AgentSessionRecord | null) => { - record = next - } - } -} - -describe.each(['claude', 'codex'] as const)('structured %s chat naming', (provider) => { - it('still names the first message after a manual rename fails to save', async () => { - const state = rig(provider) - state.setUserConversationName.mockRejectedValueOnce(new Error('Save failed')) - await expect( - state.handle.setUserName(state.summary.sessionId, 'Manual name', 'rename') - ).rejects.toThrow('Save failed') - expect(state.read()?.conversationName).toBeUndefined() - state.handle(state.summary, { replay: false, firstInputSubmissionKey: 'first-message' }) - await settle() - expect(state.setConversationName).toHaveBeenCalledWith( - state.summary.sessionId, - 'Please repair the login flow', - null, - null - ) - expect(state.deps.generate).toHaveBeenCalledTimes(1) - expect(state.read()?.conversationName).toBe('auth/login') - }) - - it('names the chat from its first prompt at once, then takes the generated name', async () => { - const state = rig(provider) - const generation = deferred() - state.deps.generate = vi.fn(() => generation.promise) - expect(state.handle(state.summary, { replay: false })).toBeUndefined() - await settle() - expect(state.read()?.conversationName).toBe('Please repair the login flow') - expect(state.deps.onNamed).toHaveBeenCalledTimes(2) - expect(state.deps.readFirstPrompt).toHaveBeenCalledWith(state.summary.sessionId, 100) - generation.resolve({ name: 'auth/login' }) - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - expect(state.deps.onNamed).toHaveBeenCalledTimes(4) - }) - - it.each(['success', 'error', 'null', 'throw'] as const)( - 'starts a fresh context while old generation finishes with %j', - async (outcome) => { - const state = rig(provider) - const old = Promise.withResolvers() - const fresh = deferred() - state.deps.generate = vi - .fn() - .mockReturnValueOnce(old.promise) - .mockReturnValueOnce(fresh.promise) - state.handle(state.summary, { replay: false }) - await settle() - const record = state.read()! - state.replace({ - ...record, - conversationName: undefined, - providerContextBoundary: { operationId: 'new-context', afterFence: 1, clearedAt: 101 } - }) - state.handle(state.summary, { replay: false, firstInputSubmissionKey: null }) - await settle() - expect(state.deps.generate).toHaveBeenCalledTimes(1) - state.handle(state.summary, { replay: false, firstInputSubmissionKey: 'new-input' }) - await settle() - expect(state.deps.generate).toHaveBeenCalledTimes(1) - if (outcome === 'throw') { - old.reject(new Error('Old failure')) - } else { - old.resolve( - outcome === 'null' - ? null - : outcome === 'error' - ? { error: 'Old failure' } - : { name: 'Stale name' } - ) - } - await settle() - expect(state.read()?.conversationName).toBe('Please repair the login flow') - expect(state.handle.activeSessionIds()).toEqual([state.summary.sessionId]) - expect(state.handle.failure(state.summary.sessionId)).toBeUndefined() - expect(state.handle.failureOutput(state.summary.sessionId)).toBeNull() - fresh.resolve({ name: 'Fresh name' }) - await settle() - expect(state.read()?.conversationName).toBe('Fresh name') - expect(state.handle.activeSessionIds()).toEqual([]) - } - ) - - it('clips a long first prompt into a short name', async () => { - const state = rig(provider) - const generation = deferred() - state.deps.generate = vi.fn(() => generation.promise) - state.deps.readFirstPrompt = async () => - 'use /agent-slack to search the thread and bring indexed search to cmd + j' - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('use /agent-slack to search the thread and bring…') - }) - - it.each([null, 'idle', 'attention'] as const)('does no work for status %s', async (status) => { - const state = rig(provider) - state.handle({ ...state.summary, status }, { replay: false }) - await settle() - expect(state.getRecord).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it('does no work on replay', async () => { - const state = rig(provider) - state.handle(state.summary, { replay: true }) - await settle() - expect(state.getRecord).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it.each(['missing', 'named'] as const)('skips a %s record', async (kind) => { - const state = rig(provider) - const record = state.read() - if (!record) { - throw new Error('Missing fixture') - } - state.replace(kind === 'missing' ? null : { ...record, conversationName: 'Existing name' }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.deps.readFirstPrompt).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it('names an orchestration worker after its task without generating', async () => { - const state = rig(provider) - state.deps.workerTaskTitle = () => ({ title: 'PR27814 final readiness review' }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('PR27814 final readiness review') - expect(state.deps.onNamed).toHaveBeenCalledTimes(3) - expect(state.deps.readFirstPrompt).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it('leaves a worker unnamed when naming is off', async () => { - const state = rig(provider) - state.deps.workerTaskTitle = () => ({ title: 'PR27814 final readiness review' }) - state.deps.getSettings = () => ({ nativeChatAutoName: false }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBeUndefined() - }) - - it('does not generate from a worker preamble when its task has no usable title', async () => { - const state = rig(provider) - state.deps.workerTaskTitle = () => ({ title: '' }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBeUndefined() - expect(state.deps.readFirstPrompt).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it('stays unnamed when disabled, including after enabling', async () => { - const state = rig(provider) - state.deps.getSettings = () => ({ nativeChatAutoName: false }) - state.handle(state.summary, { replay: false }) - await settle() - state.deps.getSettings = () => ({ nativeChatAutoName: true }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.setConversationName).not.toHaveBeenCalled() - expect(state.read()?.conversationName).toBeUndefined() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it.each(['rejected', 'failed', 'empty'] as const)( - 'retries %s generation twice, then keeps the first-prompt name and the failure', - async (outcome) => { - const state = rig(provider) - state.deps.generate = vi.fn(async () => { - if (outcome === 'rejected') { - throw new Error('Agent failed') - } - return outcome === 'empty' ? { name: '' } : { error: 'Invalid API key' } - }) - state.handle(state.summary, { replay: false }) - await settle() - state.handle({ ...state.summary, status: 'idle' }, { replay: false }) - state.handle({ ...state.summary, latestPrompt: 'Second request' }, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('Please repair the login flow') - expect(state.deps.generate).toHaveBeenCalledTimes(3) - expect(state.deps.wait).toHaveBeenNthCalledWith(1, 2000) - expect(state.deps.wait).toHaveBeenNthCalledWith(2, 4000) - expect(state.setConversationName).toHaveBeenCalledTimes(1) - expect(state.handle.failure(state.summary.sessionId)).toMatchObject({ - forName: 'Please repair the login flow', - ...(outcome === 'failed' ? { message: 'Invalid API key' } : {}) - }) - expect(state.deps.onNamed).toHaveBeenCalledTimes(4) - } - ) - - it('keeps the first-prompt name without retries or a failure where naming cannot run', async () => { - const state = rig(provider) - state.deps.generate = vi.fn(async () => null) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('Please repair the login flow') - expect(state.deps.generate).toHaveBeenCalledTimes(1) - expect(state.deps.wait).not.toHaveBeenCalled() - expect(state.handle.failure(state.summary.sessionId)).toBeUndefined() - }) - - it('regenerates a failed name with one try each, replacing the current name', async () => { - const state = rig(provider) - state.deps.generate = vi.fn(async () => ({ error: 'Invalid API key' })) - state.handle(state.summary, { replay: false }) - await settle() - const first = state.handle.failure(state.summary.sessionId) - state.deps.generate = vi.fn(async () => ({ error: 'Still invalid' })) - expect(state.handle.regenerate(state.summary.sessionId)).toBe(true) - await settle() - expect(state.deps.generate).toHaveBeenCalledTimes(1) - expect(state.deps.wait).toHaveBeenCalledTimes(2) - expect(state.handle.failure(state.summary.sessionId)).toMatchObject({ - message: 'Still invalid' - }) - expect(state.handle.failure(state.summary.sessionId)).not.toBe(first) - state.deps.generate = vi.fn(async () => ({ name: 'auth/login' })) - state.handle.regenerate(state.summary.sessionId) - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - expect(state.setConversationName).toHaveBeenLastCalledWith( - state.summary.sessionId, - 'auth/login', - 'Please repair the login flow', - null - ) - expect(state.handle.failure(state.summary.sessionId)).toBeUndefined() - }) - - it('codes the Orca-authored failure when the chat-name agent cannot run', async () => { - const state = rig(provider) - state.deps.generate = vi.fn(async () => { - throw new Error('spawn ENOENT') - }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.handle.failure(state.summary.sessionId)).toMatchObject({ - message: 'Orca could not run the chat-name agent.', - messageCode: 'agentNotRun' - }) - }) - - it.each(['read', 'save'] as const)( - 'publishes completion after a rejected %s without a summary', - async (stage) => { - const state = rig(provider) - const id = state.summary.sessionId - state.deps.generate = vi.fn(async () => ({ error: 'Agent failed' })) - state.handle(state.summary, { replay: false }) - await settle() - const failure = state.handle.failure(id) - const feed = new StructuredAgentSessionStatusFeed({ - sessions: new Map(), - getConversation: () => { - const record = state.getRecord() - return record ? agentSessionConversationView(record) : null - }, - now: () => 100, - logger: state.deps.logger, - namingActiveSessionIds: state.handle.activeSessionIds - }) - const events: AgentSessionStatusEvent[] = [] - feed.subscribe({ id: 'client', emit: (event) => events.push(event) }) - state.deps.onNamed = (_workspace, session) => feed.publishConversationName(session) - const prompt = deferred() - state.deps.readJournalFirstPrompt = vi.fn(() => - stage === 'read' - ? prompt.promise.then(() => { - throw new Error('read failed') - }) - : prompt.promise - ) - state.setConversationName.mockRejectedValueOnce(new Error('save failed')) - state.deps.generate = vi.fn(async () => ({ name: 'New name' })) - state.handle.regenerate(id) - state.handle.regenerate(id) - expect(events.at(-1)).toMatchObject({ - type: 'snapshot', - sessions: [], - namingActiveSessionIds: [id] - }) - prompt.resolve('Repair login') - await settle() - expect(state.deps.readJournalFirstPrompt).toHaveBeenCalledTimes(1) - expect(events.at(-1)).toMatchObject({ - type: 'snapshot', - sessions: [], - namingActiveSessionIds: [] - }) - expect(state.handle.failure(id)).toBe(failure) - state.deps.readJournalFirstPrompt = async () => '' - state.handle.regenerate(id) - expect(state.handle.activeSessionIds()).toEqual([id]) - await settle() - expect(state.handle.activeSessionIds()).toEqual([]) - } - ) - - it('takes the generated name from a retry after a failed first try', async () => { - const state = rig(provider) - state.deps.generate = vi - .fn() - .mockRejectedValueOnce(new Error('Agent failed')) - .mockResolvedValueOnce({ name: 'auth/login' }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - expect(state.deps.generate).toHaveBeenCalledTimes(2) - }) - - it('protects a name changed while generation runs', async () => { - const state = rig(provider) - const generation = deferred() - state.deps.generate = vi.fn(() => generation.promise) - state.handle(state.summary, { replay: false }) - await settle() - const current = state.read() - if (!current) { - throw new Error('Missing fixture') - } - state.replace({ ...current, conversationName: 'User name' }) - generation.resolve({ name: 'Late agent name' }) - await settle() - expect(state.read()?.conversationName).toBe('User name') - expect(state.deps.onNamed).toHaveBeenCalledTimes(3) - }) - - it('protects a name changed while the first prompt is read', async () => { - const state = rig(provider) - const prompt = deferred() - state.deps.readFirstPrompt = () => prompt.promise - state.handle(state.summary, { replay: false }) - const current = state.read() - if (!current) { - throw new Error('Missing fixture') - } - state.replace({ ...current, conversationName: 'User name' }) - prompt.resolve('Please repair the login flow') - await settle() - expect(state.read()?.conversationName).toBe('User name') - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it.each([{ name: 'Late agent name' }, { error: 'Generation failed' }])( - 'keeps a same-text user rename after generation settles with %j', - async (outcome) => { - const state = rig(provider) - const generation = deferred() - state.deps.generate = vi.fn(() => generation.promise) - state.handle(state.summary, { replay: false }) - await settle() - const id = state.summary.sessionId - const seed = 'Please repair the login flow' - await state.handle.setUserName(id, 'Login work', 'rename') - await state.handle.setUserName(id, seed, 'rename') - generation.resolve(outcome) - await settle() - expect(state.read()).toMatchObject({ conversationName: seed, conversationNameSource: 'user' }) - expect(state.handle.failure(id)).toBeUndefined() - } - ) - - it("takes a window's pre-upgrade tab name only over a name Orca chose", async () => { - const state = rig(provider) - const id = state.summary.sessionId - await state.handle(state.summary, { replay: false }) - await settle() - expect(await state.handle.setUserName(id, 'Old tab name', 'legacy-alias')).toEqual({ - name: 'Old tab name', - applied: true - }) - await state.handle.setUserName(id, 'Newer rename', 'rename') - // A second window's, or a replayed, upload of an older name never replaces the newer rename. - expect(await state.handle.setUserName(id, 'Old tab name', 'legacy-alias')).toEqual({ - name: 'Newer rename', - applied: false - }) - }) - - it('coalesces concurrent edges before the first journal read completes', async () => { - const state = rig(provider) - const prompt = deferred() - state.deps.readFirstPrompt = vi.fn(() => prompt.promise) - state.handle(state.summary, { replay: false }) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.deps.readFirstPrompt).toHaveBeenCalledTimes(1) - prompt.resolve('Repair the login flow') - await settle() - expect(state.deps.generate).toHaveBeenCalledTimes(1) - }) - - it.each(['', '?!'] as const)('keeps an unusable first prompt %j unnamed', async (prompt) => { - const state = rig(provider) - state.deps.readFirstPrompt = async () => prompt - state.handle(state.summary, { replay: false }) - await settle() - expect(state.setConversationName).not.toHaveBeenCalled() - expect(state.deps.generate).not.toHaveBeenCalled() - }) - - it('generates from a URL-only first message', async () => { - const state = rig(provider) - const prompt = 'https://example.test/issues/123' - const generation = deferred() - state.deps.readFirstPrompt = async () => prompt - state.deps.generate = vi.fn(() => generation.promise) - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe(prompt) - expect(state.deps.generate).toHaveBeenCalledWith( - expect.anything(), - prompt, - expect.any(Function) - ) - generation.resolve({ name: 'auth/login' }) - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - }) - - it('leaves an unreadable journal unnamed and does not retry', async () => { - const state = rig(provider) - state.deps.readFirstPrompt = vi.fn(async () => { - throw new Error('Unavailable') - }) - state.handle(state.summary, { replay: false }) - await settle() - state.handle(state.summary, { replay: false }) - await settle() - expect(state.deps.readFirstPrompt).toHaveBeenCalledTimes(1) - expect(state.deps.generate).not.toHaveBeenCalled() - expect(state.read()?.conversationName).toBeUndefined() - expect(state.deps.logger.warn).toHaveBeenCalled() - }) - - it('clips the first prompt without splitting a Unicode character', async () => { - const state = rig(provider) - const prefix = 'A'.repeat(STRUCTURED_CHAT_NAME_PROMPT_LIMIT - 1) - state.deps.readFirstPrompt = async () => `${prefix}𠮷` - state.handle(state.summary, { replay: false }) - await settle() - expect(state.deps.generate).toHaveBeenCalledWith( - expect.anything(), - prefix, - expect.any(Function) - ) - }) - - it('keeps the saved name when snapshot refresh fails', async () => { - const state = rig(provider) - state.deps.onNamed = () => { - throw new Error('Publish failed') - } - state.handle(state.summary, { replay: false }) - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - expect(state.deps.logger.warn).toHaveBeenCalled() - }) - - it('contains synchronous dependency and reporting failures off the send path', async () => { - const state = rig(provider) - state.deps.getStore = () => { - throw new Error('Store failed') - } - state.deps.logger.warn = () => { - throw new Error('Logger failed') - } - const print = vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(() => state.handle(state.summary, { replay: false })).not.toThrow() - await settle() - expect(state.deps.generate).not.toHaveBeenCalled() - print.mockRestore() - }) -}) - -it.each([false, true])('names the cleared context (user=%s)', async (user) => { - const { host, store, log } = hostTestState() - const db = new OrchestrationDb(':memory:') - onTestFinished(() => db.close()) - const onNamed = vi.fn((_workspace: string, id: string) => host.publishConversationName(id)) - const naming = createStructuredChatNamingHandler({ - getStore: () => store, - getSettings: () => ({}), - workerTaskTitle: (record) => structuredWorkerOpenTaskTitle(db, record), - readFirstPrompt: async (id, startedAt) => - firstStructuredChatNamingPrompt(await host.journalSnapshot(id), startedAt), - readJournalFirstPrompt: async (id) => - firstStructuredAgentSessionPrompt( - agentSessionCurrentContextRows((await host.journalSnapshot(id)).items).items - ), - generate: async (_record, prompt) => ({ - name: prompt === 'Please repair the login flow' ? 'auth/login' : 'New task' - }), - onNamed, - logger: log.logger - }) - host.deps.onSessionStatusChanged = naming - host.deps.conversationNaming = naming - const events: AgentSessionStatusEvent[] = [] - host.subscribeStatus({ id: 'history', emit: (event) => events.push(event) }) - await attach() - - const body = hostTestMessage('Please repair the login flow') - expect( - await host.send(CALLER, { envelope: envelope('agentSession.send', { body }), body }) - ).toMatchObject({ ok: true }) - - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('auth/login') - ) - if (user) { - await naming.setUserName(HOST_TEST_SESSION, 'My name', 'rename') - } - await host.cancel(CALLER, { - envelope: envelope('agentSession.cancel', { turnId: 'turn-1' }), - turnId: 'turn-1' - }) - const task = db.createTask({ runId: 'run_legacy_local', spec: 'Old task still open' }) - const { dispatch } = db.createStartingWorkerDispatch({ - taskId: task.id, - startOptions: {}, - creator: { kind: 'system' }, - maxDepth: 9 - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle: mintStructuredWorkerHandle(), - paneKey: mintStructuredWorkerPaneKey(HOST_TEST_SESSION), - processIncarnation: structuredWorkerProcessIncarnation(HOST_TEST_SESSION), - worktreeId: 'workspace', - effects: [], - setupState: 'not_configured', - hostScope: JSON.stringify({ kind: 'local', hostId: 'local' }), - terminalOwnership: 'created' - }) - expect(structuredWorkerOpenTaskTitle(db, store.getRecord(HOST_TEST_SESSION)!)).toEqual({ - title: 'Old task still open' - }) - await vi.waitFor(() => expect(naming.activeSessionIds()).toEqual([])) - onNamed.mockClear() - expect( - await host.conversationCommand(CALLER, { - envelope: envelope('agentSession.conversationCommand', { command: 'clear' }), - command: 'clear' - }) - ).toMatchObject({ ok: true }) - expect(onNamed).toHaveBeenCalledWith( - store.getRecord(HOST_TEST_SESSION)!.location.workspaceId, - HOST_TEST_SESSION - ) - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe(user ? 'My name' : undefined) - expect( - events.some( - (event) => - event.type === 'snapshot' && - event.conversationNames?.some( - (note) => - note.sessionId === HOST_TEST_SESSION && - note.conversationName === (user ? 'My name' : null) - ) - ) - ).toBe(true) - expect(naming.regenerate(HOST_TEST_SESSION)).toBe(true) - await vi.waitFor(() => expect(naming.activeSessionIds()).toEqual([])) - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe(user ? 'My name' : undefined) - const nextBody = hostTestMessage('Explain the database migrations') - expect( - await host.send(CALLER, { - envelope: envelope('agentSession.send', { body: nextBody }), - body: nextBody - }) - ).toMatchObject({ ok: true }) - await vi.waitFor(() => - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe(user ? 'My name' : 'New task') - ) - expect(structuredWorkerOwesWork(db, store.getRecord(HOST_TEST_SESSION)!)).toBe(true) - expect( - (await host.journalSnapshot(HOST_TEST_SESSION)).items.some( - (item) => - item.body.kind === 'message' && - item.body.blocks.some( - (block) => block.type === 'text' && block.text === 'Please repair the login flow' - ) - ) - ).toBe(true) - if (!user) { - naming.regenerate(HOST_TEST_SESSION) - await vi.waitFor(() => expect(naming.activeSessionIds()).toEqual([])) - expect(store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('New task') - } -}) - -it('replaces disabled pending automatic work with explicit Regenerate and coalesces eligible work', async () => { - const state = rig('codex') - const source = deferred() - state.deps.readFirstPrompt = vi.fn(() => source.promise) - state.handle(state.summary, { replay: false }) - state.deps.getSettings = () => ({ nativeChatAutoName: false }) - expect(state.handle.regenerate(state.summary.sessionId)).toBe(true) - state.handle.regenerate(state.summary.sessionId) - source.resolve('Obsolete automatic input') - await settle() - expect(state.deps.generate).toHaveBeenCalledExactlyOnceWith( - expect.anything(), - 'Please repair the login flow', - expect.any(Function) - ) - expect(state.read()?.conversationName).toBe('auth/login') -}) - -it('lets first input replace an empty Regenerate still reading its journal', async () => { - const state = rig('codex') - const empty = deferred() - state.deps.readJournalFirstPrompt = () => empty.promise - state.handle.regenerate(state.summary.sessionId) - state.handle(state.summary, { replay: false }) - empty.resolve('') - await settle() - expect(state.read()?.conversationName).toBe('auth/login') - expect(state.deps.generate).toHaveBeenCalledOnce() -}) - -it.each([false, true])('retains an entered backoff only (entered=%s)', async (entered) => { - const state = rig('codex') - const result = deferred() - const wait = deferred() - state.deps.generate = vi - .fn() - .mockReturnValueOnce(result.promise) - .mockResolvedValue({ name: 'Latest' }) - state.deps.wait = vi.fn(() => wait.promise) - state.handle(state.summary, { replay: false }) - await settle() - if (entered) { - result.resolve({ error: 'Retryable' }) - await settle() - } - state.replace({ - ...state.read()!, - conversationName: undefined, - providerContextBoundary: { operationId: 'latest', afterFence: 1, clearedAt: 101 } - }) - state.handle(state.summary, { replay: false }) - await settle() - if (entered) { - expect(state.deps.generate).toHaveBeenCalledTimes(1) - } else { - result.resolve({ error: 'Obsolete' }) - } - wait.resolve() - await settle() - expect(state.deps.wait).toHaveBeenCalledTimes(entered ? 1 : 0) - expect(state.deps.generate).toHaveBeenCalledTimes(2) - expect(state.read()?.conversationName).toBe('Latest') - expect(state.handle.failure(state.summary.sessionId)).toBeUndefined() -}) diff --git a/src/main/native-chat/transcript-line-decoders.omp.test.ts b/src/main/native-chat/transcript-line-decoders.omp.test.ts index 4fc0f03e1ab..20d71adbf9c 100644 --- a/src/main/native-chat/transcript-line-decoders.omp.test.ts +++ b/src/main/native-chat/transcript-line-decoders.omp.test.ts @@ -1,7 +1,4 @@ import { describe, expect, it } from 'vitest' -import { deriveNativeChatContextUsage } from '../../shared/native-chat/native-chat-context-usage' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { ompModelSelector, parseOmpModelList } from '../../shared/omp-model-list-probe' import { decodeOmpTranscriptLine } from './transcript-line-decoders' const line = (record: unknown): string => JSON.stringify(record) @@ -16,94 +13,6 @@ const message = (role: string, content: unknown, extra: Record }) describe('decodeOmpTranscriptLine', () => { - it('skips malformed lines and non-conversation records', () => { - expect(decodeOmpTranscriptLine('not json', 'f')).toBeNull() - expect(decodeOmpTranscriptLine(line({ type: 'session_init', id: 'a' }), 'f')).toBeNull() - expect(decodeOmpTranscriptLine(line({ type: 'mode_change', id: 'a' }), 'f')).toBeNull() - expect( - decodeOmpTranscriptLine(line({ type: 'custom', customType: 'tool_execution_start' }), 'f') - ).toBeNull() - expect(decodeOmpTranscriptLine(line({ type: 'a-type-from-the-future' }), 'f')).toBeNull() - }) - - it('decodes a user turn', () => { - const decoded = decodeOmpTranscriptLine( - message('user', [{ type: 'text', text: 'resume' }]), - 'f' - ) - expect(decoded).toEqual({ - id: 'rec-1', - role: 'user', - blocks: [{ type: 'text', text: 'resume' }], - timestamp: Date.parse('2026-07-16T00:27:02.222Z'), - source: 'transcript' - }) - }) - - it('keeps thinking and tool calls together on a mixed assistant turn', () => { - const decoded = decodeOmpTranscriptLine( - message('assistant', [ - { type: 'thinking', thinking: 'Checking the goal' }, - { type: 'text', text: 'Reading it now.' }, - { type: 'toolCall', id: 'call-1', name: 'goal', arguments: { op: 'get' } } - ]), - 'f' - ) - expect(decoded?.role).toBe('assistant') - expect(decoded?.blocks).toEqual([ - { type: 'text', text: 'Checking the goal' }, - { type: 'text', text: 'Reading it now.' }, - { type: 'tool-call', name: 'goal', input: { op: 'get' } } - ]) - }) - - it('keeps a thinking-only assistant turn on the assistant role', () => { - const decoded = decodeOmpTranscriptLine( - message('assistant', [{ type: 'thinking', thinking: 'Weighing two options' }]), - 'f' - ) - expect(decoded?.role).toBe('assistant') - expect(decoded?.blocks).toEqual([{ type: 'text', text: 'Weighing two options' }]) - }) - - it('passes tool arguments through unchanged', () => { - const decoded = decodeOmpTranscriptLine( - message('assistant', [ - { type: 'toolCall', name: 'goal', arguments: { op: 'get', objective: null } } - ]), - 'f' - ) - expect(decoded?.blocks[0]).toEqual({ - type: 'tool-call', - name: 'goal', - input: { op: 'get', objective: null } - }) - }) - - it('decodes a tool result', () => { - const decoded = decodeOmpTranscriptLine( - message('toolResult', [{ type: 'text', text: 'ok' }], { - toolCallId: 'call-1', - toolName: 'goal', - isError: false - }), - 'f' - ) - expect(decoded?.role).toBe('tool') - expect(decoded?.blocks).toEqual([{ type: 'tool-result', output: 'ok' }]) - }) - - it('flags an errored tool result', () => { - const decoded = decodeOmpTranscriptLine( - message('toolResult', [{ type: 'text', text: 'boom' }], { - toolCallId: 'call-2', - isError: true - }), - 'f' - ) - expect(decoded?.blocks[0]).toEqual({ type: 'tool-result', output: 'boom', isError: true }) - }) - it('surfaces a displayed custom_message, and hides a state-only one', () => { const custom = (display: boolean): string => line({ @@ -124,51 +33,6 @@ describe('decodeOmpTranscriptLine', () => { expect(decodeOmpTranscriptLine(custom(false), 'f')).toBeNull() }) - it('accepts string content on a custom_message', () => { - const decoded = decodeOmpTranscriptLine( - line({ type: 'custom_message', id: 'rec-s', display: true, content: 'peer said hi' }), - 'f' - ) - expect(decoded?.blocks).toEqual([{ type: 'text', text: 'peer said hi' }]) - }) - - it('renders a bash execution cell as a tool turn', () => { - const decoded = decodeOmpTranscriptLine( - line({ - type: 'message', - id: 'rec-b', - timestamp: '2026-07-16T00:27:02.222Z', - message: { role: 'bashExecution', command: 'ls -a', output: '.git\n', exitCode: 0 } - }), - 'f' - ) - expect(decoded?.role).toBe('tool') - expect(decoded?.blocks).toEqual([ - { type: 'tool-call', name: 'bash', input: 'ls -a' }, - { type: 'tool-result', output: '.git\n' } - ]) - }) - - it('flags a nonzero exit code and reads python cells from `code`', () => { - const decoded = decodeOmpTranscriptLine( - line({ - type: 'message', - id: 'rec-p', - message: { - role: 'pythonExecution', - code: 'raise SystemExit(2)', - output: 'boom', - exitCode: 2 - } - }), - 'f' - ) - expect(decoded?.blocks).toEqual([ - { type: 'tool-call', name: 'python', input: 'raise SystemExit(2)' }, - { type: 'tool-result', output: 'boom', isError: true } - ]) - }) - it('marks a cancelled run, which carries no exitCode at all', () => { const decoded = decodeOmpTranscriptLine( line({ @@ -202,29 +66,6 @@ describe('decodeOmpTranscriptLine', () => { expect(JSON.stringify(decoded)).not.toContain('SECRET FILE BODY') }) - it('honors the display gate on legacy custom / hookMessage message rows', () => { - const legacy = (role: string, display: boolean): string => - line({ - type: 'message', - id: 'rec-l', - message: { role, customType: 'irc:incoming', display, content: 'peer note' } - }) - expect(decodeOmpTranscriptLine(legacy('custom', false), 'f')).toBeNull() - expect(decodeOmpTranscriptLine(legacy('hookMessage', false), 'f')).toBeNull() - expect(decodeOmpTranscriptLine(legacy('custom', true), 'f')).toMatchObject({ - role: 'system', - blocks: [{ type: 'text', text: 'peer note' }] - }) - }) - - it('surfaces the developer channel as system', () => { - const decoded = decodeOmpTranscriptLine( - message('developer', [{ type: 'text', text: 'context note' }]), - 'f' - ) - expect(decoded?.role).toBe('system') - }) - it('drops blob-handle images, which the renderer cannot load', () => { expect( decodeOmpTranscriptLine( @@ -234,18 +75,6 @@ describe('decodeOmpTranscriptLine', () => { ).toBeNull() }) - it('surfaces an aborted turn as the interrupted row, not silence', () => { - const decoded = decodeOmpTranscriptLine( - message('assistant', [{ type: 'text', text: '' }], { - stopReason: 'aborted', - errorMessage: 'Stopped before model call' - }), - 'f' - ) - expect(decoded?.role).toBe('system') - expect(decoded?.blocks).toEqual([{ type: 'text', text: 'Conversation interrupted' }]) - }) - it('keeps partial content when a turn aborted mid-stream', () => { const decoded = decodeOmpTranscriptLine( message('assistant', [{ type: 'text', text: 'Partial answer' }], { stopReason: 'aborted' }), @@ -254,129 +83,4 @@ describe('decodeOmpTranscriptLine', () => { expect(decoded?.role).toBe('assistant') expect(decoded?.blocks).toEqual([{ type: 'text', text: 'Partial answer' }]) }) - - it('still drops an empty non-aborted assistant turn', () => { - expect( - decodeOmpTranscriptLine(message('assistant', [{ type: 'text', text: '' }]), 'f') - ).toBeNull() - }) - - it('falls back to the supplied id when the record carries none', () => { - const decoded = decodeOmpTranscriptLine( - line({ type: 'message', message: { role: 'user', content: [{ type: 'text', text: 'hi' }] } }), - 'fallback-9' - ) - expect(decoded?.id).toBe('fallback-9') - expect(decoded?.timestamp).toBeNull() - }) - - describe('what served a reply, and the prompt it read', () => { - // OMP 17.0.5 assistant payload with shortened IDs/content. - const reply = (extra: Record = {}): string => - message('assistant', [{ type: 'text', text: 'The `value` field is set to **42**.' }], { - api: 'openai-codex-responses', - provider: 'openai-codex', - model: 'gpt-5.5', - usage: { - input: 680, - output: 16, - cacheRead: 20992, - cacheWrite: 0, - totalTokens: 21688, - cost: { - input: 0.0034, - output: 0.00048, - cacheRead: 0.010496, - cacheWrite: 0, - total: 0.014376 - } - }, - stopReason: 'stop', - contextSnapshot: { promptTokens: 21672, nonMessageTokens: 20318 }, - ...extra - }) - - it('keeps the provider, model and usage of a completed reply', () => { - expect(decodeOmpTranscriptLine(reply(), 'f')).toMatchObject({ - role: 'assistant', - provider: 'openai-codex', - model: 'gpt-5.5', - usage: { - inputTokens: 680, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 20992, - outputTokens: 16 - } - }) - }) - - it('drops the accounting of an aborted or errored reply, keeping its model', () => { - for (const stopReason of ['aborted', 'error']) { - const decoded = decodeOmpTranscriptLine(reply({ stopReason }), 'f') - expect(decoded?.model).toBe('gpt-5.5') - expect(decoded).not.toHaveProperty('usage') - } - }) - - it("measures the prompt OMP recorded, against its listing's window for that model", () => { - // OMP 17.0.5 model-list format. - const listing = parseOmpModelList( - line({ - models: [ - { - provider: 'openai-codex', - id: 'gpt-5.5', - selector: 'openai-codex/gpt-5.5', - name: 'GPT-5.5', - contextWindow: 272000 - } - ] - }) - ) - const windowFor = (served: NativeChatMessage): number | null => - listing.find(({ id }) => id === ompModelSelector(served.provider, served.model)) - ?.contextWindowTokens ?? null - const decoded = decodeOmpTranscriptLine(reply(), 'f')! - expect(deriveNativeChatContextUsage([decoded], windowFor)).toEqual({ - usedTokens: 21672, - windowTokens: 272000, - percentage: 8 - }) - const compaction = decodeOmpTranscriptLine(line({ type: 'compaction', id: 'c' }), 'f')! - expect(deriveNativeChatContextUsage([decoded, compaction], windowFor)).toBeNull() - }) - - it('puts none of it on turns that are not replies', () => { - const decoded = decodeOmpTranscriptLine( - message('user', [{ type: 'text', text: 'hi' }], { model: 'gpt-5.5', usage: { input: 5 } }), - 'f' - ) - expect(decoded).not.toHaveProperty('usage') - expect(decoded).not.toHaveProperty('model') - }) - }) - - it('marks a compaction row as the boundary it draws', () => { - // OMP 17.0.5 appendCompaction shape with summary elided. - const decoded = decodeOmpTranscriptLine( - line({ - type: 'compaction', - id: 'cmp-1', - parentId: 'rec-9', - timestamp: '2026-07-16T01:00:00.000Z', - summary: '…', - shortSummary: '…', - firstKeptEntryId: 'rec-7', - tokensBefore: 180000 - }), - 'f' - ) - expect(decoded).toEqual({ - id: 'cmp-1', - role: 'system', - blocks: [{ type: 'text', text: 'Context compacted', presentation: 'compaction' }], - timestamp: Date.parse('2026-07-16T01:00:00.000Z'), - source: 'transcript' - }) - }) }) diff --git a/src/main/native-chat/transcript-opencode-database.test.ts b/src/main/native-chat/transcript-opencode-database.test.ts deleted file mode 100644 index 050eaeaf17c..00000000000 --- a/src/main/native-chat/transcript-opencode-database.test.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { join } from 'node:path' -import { homedir } from 'node:os' -import type { OpenCodeTranscriptSignal } from './transcript-opencode-sqlite-query' -import { WslTranscriptFsError } from './wsl-transcript-fs-error' - -const mocks = vi.hoisted(() => ({ - homes: vi.fn(async (): Promise => []), - native: vi.fn(async (): Promise => []), - directory: vi.fn( - async ( - _path: string, - _onRefusal?: (path: string, error: WslTranscriptFsError) => void - ): Promise => [] - ), - prepare: vi.fn(async () => []), - configure: vi.fn(), - access: vi.fn(async () => true), - wslPath: vi.fn((_path: string): { distro: string; linuxPath: string } | null => null), - readSignal: vi.fn( - async ( - _args: { dbPath: string; sessionId: string }, - _signal?: AbortSignal - ): Promise => null - ) -})) -vi.mock('../ai-vault/cached-session-list', () => ({ getAiVaultWslScanHomeDirs: mocks.homes })) -vi.mock('./wsl-transcript-fs-access', () => ({ wslGatedAccess: mocks.access })) -vi.mock('../opencode-usage/opencode-database-discovery', () => ({ - listOpenCodeDatabases: mocks.native, - listOpenCodeDatabasesInDirectory: mocks.directory, - compareOpenCodeClaimPriority: (a: string, b: string) => a.localeCompare(b) -})) -vi.mock('../ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation', () => ({ - prepareOpenCodeWslReaders: mocks.prepare -})) -vi.mock( - '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-wsl-client', - () => ({ - configureOpenCodeWslReaders: mocks.configure, - openCodeWslPath: mocks.wslPath - }) -) -vi.mock( - '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', - () => ({ - readOpenCodeTranscriptSignalViaWorker: mocks.readSignal, - readOpenCodeTranscriptPageViaWorker: vi.fn() - }) -) -import { - resolveOpenCodeTranscriptDbPath, - openCodeTranscriptDefaultDeps -} from './transcript-opencode' - -afterEach(() => { - vi.resetAllMocks() - vi.useRealTimers() -}) - -describe('OpenCode transcript owning-host database discovery', () => { - it('reports a missing ZCode install as unavailable without a SQLite refusal', async () => { - mocks.access.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' })) - await expect( - openCodeTranscriptDefaultDeps.resolveDbPath('z-session', undefined, 'zcode') - ).resolves.toBeNull() - expect(mocks.readSignal).not.toHaveBeenCalled() - }) - it('opens a native ZCode session before an unresolved WSL lookup', async () => { - vi.useFakeTimers() - mocks.homes.mockImplementation(() => new Promise(() => {})) - mocks.readSignal.mockResolvedValue({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - }) - const settled = vi.fn() - void openCodeTranscriptDefaultDeps - .resolveDbPath('z-session', undefined, 'zcode') - .then(settled, settled) - await vi.advanceTimersByTimeAsync(50) - expect(settled).toHaveBeenCalledWith(join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite')) - expect(mocks.homes).not.toHaveBeenCalled() - expect(mocks.native).not.toHaveBeenCalled() - }) - - it('finds a WSL ZCode session without probing OpenCode databases', async () => { - const home = 'wsl-home' - const dbPath = join(home, '.zcode', 'cli', 'db', 'db.sqlite') - mocks.homes.mockResolvedValue([home]) - mocks.readSignal.mockResolvedValueOnce(null).mockResolvedValueOnce({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - }) - await expect( - openCodeTranscriptDefaultDeps.resolveDbPath('z-session', undefined, 'zcode') - ).resolves.toBe(dbPath) - expect(mocks.prepare).toHaveBeenCalledWith([home]) - expect(mocks.readSignal).toHaveBeenLastCalledWith( - { dbPath, sessionId: 'z-session', agent: 'zcode' }, - expect.any(AbortSignal) - ) - expect(mocks.native).not.toHaveBeenCalled() - expect(mocks.directory).not.toHaveBeenCalled() - }) - - it.each(['homes', 'directory', 'prepare'] as const)( - 'opens a matching native database without waiting for WSL %s', - async (stage) => { - vi.useFakeTimers() - mocks.native.mockResolvedValue(['native.db']) - mocks.homes.mockResolvedValue(['wsl-home']) - mocks[stage].mockImplementation(() => new Promise(() => {})) - mocks.readSignal.mockResolvedValue({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - }) - const settled = vi.fn() - void resolveOpenCodeTranscriptDbPath('session').then(settled, settled) - await vi.advanceTimersByTimeAsync(50) - expect(settled).toHaveBeenCalledWith('native.db') - expect(mocks.readSignal).toHaveBeenCalledOnce() - expect(mocks.prepare).not.toHaveBeenCalled() - } - ) - - it('finds a WSL-only session using the same running homes and database discovery as Vault', async () => { - const home = 'wsl-home' - const dbPath = join(home, '.local', 'share', 'opencode', 'opencode.db') - mocks.homes.mockResolvedValue([home]) - mocks.directory.mockResolvedValue([dbPath]) - mocks.readSignal.mockResolvedValue(null) - mocks.readSignal.mockImplementation(async () => ({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - })) - await expect(resolveOpenCodeTranscriptDbPath('session')).resolves.toBe(dbPath) - expect(mocks.directory).toHaveBeenCalledWith( - join(home, '.local', 'share', 'opencode'), - expect.any(Function), - expect.any(AbortSignal) - ) - expect(mocks.prepare).toHaveBeenCalledWith([home]) - expect(mocks.configure).toHaveBeenCalledOnce() - expect(mocks.readSignal).toHaveBeenCalledWith( - { dbPath, sessionId: 'session' }, - expect.any(AbortSignal) - ) - }) - - it('caps candidate probes when a session is missing', async () => { - mocks.native.mockResolvedValue(Array.from({ length: 40 }, (_, index) => `db-${index}`)) - await expect(resolveOpenCodeTranscriptDbPath('missing')).resolves.toBe(null) - expect(mocks.readSignal).toHaveBeenCalledTimes(32) - }) - - it.each(['database is locked', 'file is not a database', 'Preparing the WSL SQLite reader…'])( - 'continues to the next candidate after %s', - async (message) => { - mocks.native.mockResolvedValue(['a.db', 'b.db']) - mocks.readSignal.mockRejectedValueOnce(new Error(message)).mockResolvedValueOnce({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - }) - await expect(resolveOpenCodeTranscriptDbPath('session')).resolves.toBe('b.db') - expect(mocks.readSignal).toHaveBeenCalledTimes(2) - } - ) - - it('retains the first probe failure when no candidate has the session', async () => { - const refusal = new Error('database is locked') - mocks.native.mockResolvedValue(['a.db', 'b.db']) - mocks.readSignal.mockRejectedValueOnce(refusal).mockResolvedValueOnce(null) - await expect(resolveOpenCodeTranscriptDbPath('session')).rejects.toBe(refusal) - expect(mocks.readSignal).toHaveBeenCalledTimes(2) - }) - - it('continues past an unprepared WSL reader to another owning-host candidate', async () => { - const home = 'wsl-home' - const failedPath = join(home, '.local', 'share', 'opencode', 'opencode-a.db') - const matchingPath = join(home, '.local', 'share', 'opencode', 'opencode-b.db') - mocks.homes.mockResolvedValue([home]) - mocks.directory.mockResolvedValue([failedPath, matchingPath]) - mocks.readSignal - .mockRejectedValueOnce(new Error('Preparing the WSL SQLite reader…')) - .mockResolvedValueOnce({ - messageCount: 1, - partCount: 1, - maxMessageRowId: 1, - maxPartTimeUpdated: 1 - }) - await expect(resolveOpenCodeTranscriptDbPath('session')).resolves.toBe(matchingPath) - expect(mocks.prepare).toHaveBeenCalledOnce() - expect(mocks.configure).toHaveBeenCalledOnce() - expect(mocks.readSignal).toHaveBeenCalledTimes(2) - }) - - it('caps failed probes as well as missing-session probes', async () => { - const error = new Error('file is not a database') - mocks.native.mockResolvedValue(Array.from({ length: 40 }, (_, index) => `db-${index}`)) - mocks.readSignal.mockRejectedValue(error) - await expect(resolveOpenCodeTranscriptDbPath('session')).rejects.toBe(error) - expect(mocks.readSignal).toHaveBeenCalledTimes(32) - }) - - it('rethrows cancellation during a probe without trying the next candidate', async () => { - const controller = new AbortController() - const reason = new Error('caller cancelled the probe') - mocks.native.mockResolvedValue(['a.db', 'b.db']) - mocks.readSignal.mockImplementationOnce(async () => { - controller.abort(reason) - throw new Error('database is locked') - }) - await expect( - openCodeTranscriptDefaultDeps.resolveDbPath('session', controller.signal) - ).rejects.toBe(reason) - expect(mocks.readSignal).toHaveBeenCalledOnce() - }) - - it('prepares an overridden WSL database before its owning-host probe', async () => { - const dbPath = '\\\\wsl.localhost\\Ubuntu\\custom\\opencode.db' - mocks.native.mockResolvedValue([dbPath]) - mocks.wslPath.mockReturnValue({ distro: 'Ubuntu', linuxPath: '/custom/opencode.db' }) - mocks.readSignal.mockImplementation(async () => { - expect(mocks.configure).toHaveBeenCalledOnce() - return { messageCount: 1, partCount: 1, maxMessageRowId: 1, maxPartTimeUpdated: 1 } - }) - await expect(resolveOpenCodeTranscriptDbPath('session')).resolves.toBe(dbPath) - expect(mocks.prepare).toHaveBeenCalledWith([dbPath]) - expect(mocks.readSignal).toHaveBeenCalledOnce() - }) - - it('reports a refused WSL read instead of treating that host as empty', async () => { - mocks.homes.mockResolvedValue(['wsl-home']) - const refusal = new WslTranscriptFsError('unavailable', 'WSL discovery unavailable') - mocks.directory.mockImplementation(async (path, onRefusal) => { - onRefusal?.(path, refusal) - return [] - }) - await expect(resolveOpenCodeTranscriptDbPath('session')).rejects.toBe(refusal) - }) - - it('aborts a slow candidate within the discovery deadline, including its in-flight read', async () => { - vi.useFakeTimers() - mocks.native.mockResolvedValue(['slow.db']) - mocks.readSignal.mockImplementation(() => new Promise(() => {})) - const pending = resolveOpenCodeTranscriptDbPath('session') - const assertion = expect(pending).rejects.toThrow('database discovery exceeded its time limit') - await vi.advanceTimersByTimeAsync(5000) - await assertion - const readSignal = mocks.readSignal.mock.calls[0]?.[1] - expect(readSignal?.aborted).toBe(true) - }) - - it('propagates caller cancellation rather than reporting a missing local transcript', async () => { - const controller = new AbortController() - controller.abort(new Error('cancelled')) - await expect( - openCodeTranscriptDefaultDeps.resolveDbPath('session', controller.signal) - ).rejects.toThrow('cancelled') - expect(mocks.readSignal).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts b/src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts deleted file mode 100644 index 483ecede19c..00000000000 --- a/src/main/native-chat/transcript-opencode-semantic-fidelity.test.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { AGENT_SESSION_HOST_STATUS_COPY } from '../../shared/agent-session/view/agent-session-host-status-rows' -import Database from '../sqlite/sync-database' -import { opencodeMessages } from './transcript-opencode-part-blocks' -import { - readOpenCodeTranscriptPage, - readOpenCodeTranscriptSignal -} from './transcript-opencode-sqlite-query' -import { readOpenCodeNativeChatTranscriptFull } from './transcript-opencode' -import { subscribeOpenCodeNativeChatTranscript } from './transcript-opencode-subscribe' - -vi.mock('../managed-data-accounts/service', () => ({ getManagedDataAccountService: vi.fn() })) - -const fixtures: { db: Database.Database; root: string }[] = [] -afterEach(() => { - for (const { db, root } of fixtures.splice(0)) { - db.close() - rmSync(root, { recursive: true, force: true }) - } -}) - -function fixture(version: 'v1' | 'v2') { - const root = mkdtempSync(join(tmpdir(), 'orca-opencode-semantics-')) - const path = join(root, 'opencode.db') - const db = new Database(path) - fixtures.push({ db, root }) - if (version === 'v1') { - db.exec(`CREATE TABLE session (id TEXT PRIMARY KEY); - CREATE TABLE message (id TEXT, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); - CREATE TABLE part (id TEXT, message_id TEXT, session_id TEXT, time_updated INTEGER, data TEXT); - INSERT INTO session VALUES ('session');`) - } else { - db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY); - CREATE TABLE session_message (id TEXT, session_id TEXT, type TEXT, seq INTEGER, - data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session');`) - } - let sequence = 0 - const insert = (id: string, parts: unknown[]) => { - sequence += 7 - if (version === 'v1') { - db.prepare('INSERT INTO message VALUES (?, ?, ?, ?, ?)').run( - id, - 'session', - sequence, - sequence, - JSON.stringify({ role: 'assistant' }) - ) - parts.forEach((part, index) => { - db.prepare('INSERT INTO part VALUES (?, ?, ?, ?, ?)').run( - `${id}:${index}`, - id, - 'session', - sequence, - JSON.stringify(part) - ) - }) - } else { - db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)').run( - id, - 'session', - 'assistant', - sequence, - JSON.stringify({ content: parts }), - sequence, - sequence - ) - } - } - const prefix = version === 'v1' ? '' : 'opencode:' - return { db, path, insert, prefix } -} - -const mixed = (answer = 'ANSWER_SENTINEL') => [ - { type: 'reasoning', text: 'REASONING_SENTINEL' }, - { type: 'text', text: answer } -] - -it('keeps reasoning apart from prose, image refs, tools, and applied patch records', () => { - // Contracts captured through isolated 2.0.16 and official 1.18.30 CLI ingestion. - const parts = [ - ...mixed(), - { type: 'text', text: 'injected context', synthetic: true }, - { type: 'step-finish' }, - { type: 'file', mime: 'image/png', url: 'data:image/png;base64,YQ==' }, - { type: 'patch', hash: 'snapshot-before-edit', files: ['sentinel.txt', 3] } - ].map((part) => ({ message_id: 'row', time_updated: 1, data: JSON.stringify(part) })) - const messages = opencodeMessages({ id: 'row', role: 'assistant', timestamp: 1 }, parts) - expect(messages).toEqual([ - { - id: 'row:reasoning', - role: 'reasoning', - timestamp: 1, - source: 'transcript', - blocks: [{ type: 'text', text: 'REASONING_SENTINEL' }] - }, - { - id: 'row', - role: 'assistant', - timestamp: 1, - source: 'transcript', - blocks: [ - { type: 'text', text: 'ANSWER_SENTINEL' }, - { type: 'image-ref', url: 'data:image/png;base64,YQ==' }, - { - type: 'tool-call', - name: 'patch', - state: 'completed', - input: { hash: 'snapshot-before-edit', files: ['sentinel.txt'] } - } - ] - } - ]) - expect( - opencodeMessages({ id: 'thinking', role: 'assistant', timestamp: null }, parts.slice(0, 1)) - ).toEqual([ - { - id: 'thinking', - role: 'reasoning', - timestamp: null, - source: 'transcript', - blocks: [{ type: 'text', text: 'REASONING_SENTINEL' }] - } - ]) -}) - -describe.each(['v1', 'v2'] as const)('%s semantic pagination', (version) => { - it.each([1, 2, 3])('reconstructs sparse mixed history once with a page limit of %i', (limit) => { - const { path, insert, prefix } = fixture(version) - const expected: string[] = [] - for (let index = 0; index < 12; index++) { - const id = String(index) - if (index % 3 === 1) { - insert(id, [{ type: 'step-start' }]) - } else if (index % 3 === 2) { - insert(id, mixed()) - expected.push(`${prefix}${id}:reasoning`, `${prefix}${id}`) - } else { - insert(id, [{ type: 'text', text: id }]) - expected.push(`${prefix}${id}`) - } - } - const pages: NativeChatMessage[][] = [] - let cursor: number | undefined - for (let pageIndex = 0; pageIndex < 30; pageIndex++) { - const page = readOpenCodeTranscriptPage({ - dbPath: path, - sessionId: 'session', - limit, - beforeMessageRowId: cursor - })! - expect(page.items.length).toBeLessThanOrEqual(limit + 1) - for (const item of page.items.filter((item) => item.message.role === 'reasoning')) { - expect( - page.items.some( - (other) => other.rowid === item.rowid && other.message.role === 'assistant' - ) - ).toBe(true) - } - pages.push(page.items.map((item) => item.message)) - if (!page.hasMore) { - break - } - expect(page.beforeMessageRowId).toBeLessThan(cursor ?? Number.MAX_SAFE_INTEGER) - cursor = page.beforeMessageRowId ?? undefined - } - expect( - pages - .toReversed() - .flat() - .map((message) => message.id) - ).toEqual(expected) - }) - - it('reconstructs a full read beyond its 500-message window without losing a split row', async () => { - const { db, path, insert, prefix } = fixture(version) - const expected: string[] = [] - db.exec('BEGIN') - for (let index = 0; index < 260; index++) { - insert(String(index), mixed()) - expected.push(`${prefix}${index}:reasoning`, `${prefix}${index}`) - } - db.exec('COMMIT') - const result = await readOpenCodeNativeChatTranscriptFull('session', { - resolveDbPath: async () => path, - readPage: async (args) => readOpenCodeTranscriptPage(args) - }) - expect('messages' in result && result.messages.map((message) => message.id)).toEqual(expected) - }) - - it('keeps both presentations on streaming mutation and new rows', async () => { - const { db, path, insert, prefix } = fixture(version) - insert('reply', mixed()) - const snapshots: NativeChatMessage[][] = [] - const replacements: NativeChatMessage[][] = [] - const appends: NativeChatMessage[][] = [] - let visible: NativeChatMessage[] = [] - const subscription = subscribeOpenCodeNativeChatTranscript( - { - agent: 'opencode', - sessionId: 'session', - initialLimit: 1, - resolvePollIntervalMs: 5, - onAppend: (messages) => { - appends.push(messages) - visible.push(...messages) - }, - onInitialSnapshot: (messages) => { - snapshots.push(messages) - visible = [...messages] - }, - onReplace: (messages) => { - replacements.push(messages) - visible = [...messages] - } - }, - undefined, - { - resolveDbPath: async () => path, - readSignal: async (dbPath, sessionId) => readOpenCodeTranscriptSignal(dbPath, sessionId), - readPage: async (args) => readOpenCodeTranscriptPage(args) - } - ) - try { - await expect.poll(() => snapshots.length).toBe(1) - expect(snapshots[0].map((message) => message.role)).toEqual(['reasoning', 'assistant']) - if (version === 'v1') { - db.prepare("UPDATE part SET data = ?, time_updated = 100 WHERE id = 'reply:1'").run( - JSON.stringify({ type: 'text', text: 'complete' }) - ) - } else { - db.prepare('UPDATE session_message SET data = ?, time_updated = 100').run( - JSON.stringify({ content: mixed('complete') }) - ) - } - await expect.poll(() => replacements.length).toBe(1) - expect(replacements[0].map((message) => message.role)).toEqual(['reasoning', 'assistant']) - expect(replacements[0][1].blocks).toEqual([{ type: 'text', text: 'complete' }]) - insert('next', mixed('next answer')) - await expect.poll(() => appends.length + replacements.length).toBe(2) - expect(visible.map((message) => message.id)).toEqual( - ['reply:reasoning', 'reply', 'next:reasoning', 'next'].map((id) => `${prefix}${id}`) - ) - expect(visible.map((message) => message.role)).toEqual([ - 'reasoning', - 'assistant', - 'reasoning', - 'assistant' - ]) - expect(visible[1].blocks).toEqual([{ type: 'text', text: 'complete' }]) - expect(visible[3].blocks).toEqual([{ type: 'text', text: 'next answer' }]) - } finally { - subscription.unsubscribe() - } - }) - - it('keeps complete pairs around an omitted oversized history row', () => { - const { path, insert, prefix } = fixture(version) - insert('before', mixed('BEFORE')) - insert('large', [ - ...mixed('MIDDLE'), - { type: 'file', mime: 'image/png', url: '😀'.repeat(2 * 1024 * 1024) } - ]) - insert('after', mixed('AFTER')) - const messages: NativeChatMessage[] = [] - const cursors = new Set() - let beforeMessageRowId: number | undefined - while (true) { - const page = readOpenCodeTranscriptPage({ - dbPath: path, - sessionId: 'session', - limit: 1, - beforeMessageRowId - }) - expect(page).not.toBeNull() - if (!page) { - throw new Error('History page unavailable') - } - messages.unshift(...page.items.map((item) => item.message)) - if (!page.hasMore) { - break - } - expect(page.beforeMessageRowId).not.toBeNull() - if (page.beforeMessageRowId === null) { - throw new Error('History cursor unavailable') - } - expect(cursors.has(page.beforeMessageRowId)).toBe(false) - cursors.add(page.beforeMessageRowId) - beforeMessageRowId = page.beforeMessageRowId - } - const middleIds = version === 'v1' ? ['large:reasoning', 'large', 'large:omission'] : ['large'] - expect(messages.map((message) => message.id)).toEqual( - ['before:reasoning', 'before', ...middleIds, 'after:reasoning', 'after'].map( - (id) => `${prefix}${id}` - ) - ) - const notices = messages.flatMap((message) => - message.blocks.filter( - (block) => - block.type === 'text' && - block.text === AGENT_SESSION_HOST_STATUS_COPY['history-item-too-large'] - ) - ) - expect(notices).toHaveLength(1) - expect(notices[0]).toMatchObject({ presentation: 'history-item-too-large' }) - const noticeRow = messages.find((message) => - message.blocks.some( - (block) => block.type === 'text' && block.presentation === 'history-item-too-large' - ) - ) - expect(noticeRow?.role).toBe('system') - expect(noticeRow?.transcriptOffset).toBeTypeOf('number') - expect(Buffer.byteLength(JSON.stringify(messages))).toBeLessThan(4096) - }) - - it('enforces one page byte budget across multiple mixed rows', () => { - const { path, insert } = fixture(version) - const large = 'x'.repeat(1_000_000) - for (let index = 0; index < 20; index++) { - insert(String(index), [ - { type: 'reasoning', text: large }, - { type: 'text', text: large } - ]) - } - expect(() => - readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 40 }) - ).toThrow('read limit') - }) -}) diff --git a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts b/src/main/native-chat/transcript-opencode-sqlite-query.test.ts index fd7c9292963..45ee0110456 100644 --- a/src/main/native-chat/transcript-opencode-sqlite-query.test.ts +++ b/src/main/native-chat/transcript-opencode-sqlite-query.test.ts @@ -1,9 +1,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { AGENT_SESSION_HOST_STATUS_COPY } from '../../shared/agent-session/view/agent-session-host-status-rows' +import { afterEach, describe, expect, it } from 'vitest' import Database from '../sqlite/sync-database' import { readOpenCodeTranscriptPage, @@ -85,58 +83,6 @@ function messageRowid(db: Database.Database, id: string): number { } describe('readOpenCodeTranscriptPage', () => { - it.each(['message', 'part'] as const)( - 'omits an oversized %s without losing identity or pagination', - (table) => { - const { db, path } = createTempDb() - applySchema(db) - for (let index = 1; index <= 3; index++) { - insertMessage(db, { id: `msg-${index}`, time: index }) - insertPart(db, { - id: `prt-${index}`, - messageId: `msg-${index}`, - time: index, - data: { type: 'text', text: `message ${index}` } - }) - } - db.prepare(`UPDATE ${table} SET data = ? WHERE id = ?`).run( - JSON.stringify({ - role: 'user', - type: 'file', - mime: 'image/png', - url: 'x'.repeat(2 * 1024 * 1024) - }), - table === 'message' ? 'msg-2' : 'prt-2' - ) - const args = { dbPath: path, sessionId: 'ses-1', limit: 2 } - const page = readOpenCodeTranscriptPage(args) - expect(page?.items.map((item) => item.message.id)).toEqual(['msg-2', 'msg-3']) - expect(page?.items[0]?.message.blocks).toEqual([ - { - type: 'text', - text: AGENT_SESSION_HOST_STATUS_COPY['history-item-too-large'], - presentation: 'history-item-too-large' - } - ]) - expect(page?.items[0]?.rowid).toBe(messageRowid(db, 'msg-2')) - expect(readOpenCodeTranscriptPage(args)?.items[0]?.fingerprint).toBe( - page?.items[0]?.fingerprint - ) - db.prepare(`UPDATE ${table} SET time_updated = 10 WHERE id = ?`).run( - table === 'message' ? 'msg-2' : 'prt-2' - ) - expect(readOpenCodeTranscriptPage(args)?.items[0]?.fingerprint).not.toBe( - page?.items[0]?.fingerprint - ) - expect( - readOpenCodeTranscriptPage({ - ...args, - beforeMessageRowId: page?.beforeMessageRowId ?? undefined - })?.items.map((item) => item.message.id) - ).toEqual(['msg-1']) - } - ) - it('preserves ordinary text beside an oversized UTF-8 attachment part', () => { const { db, path } = createTempDb() applySchema(db) @@ -166,61 +112,6 @@ describe('readOpenCodeTranscriptPage', () => { expect(page?.items[0]?.message.transcriptOffset).toBe(page?.items[1]?.message.transcriptOffset) }) - it('returns null when the session row does not exist', () => { - const { db, path } = createTempDb() - applySchema(db) - expect(readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'missing', limit: 10 })).toBeNull() - }) - - it('treats a session_v2-only (OpenCode 2) DB as not-found instead of throwing', () => { - const { db, path } = createTempDb() - // A v2-only store must fail softly in the v1 reader. - db.exec('CREATE TABLE session_v2 (id TEXT PRIMARY KEY)') - expect(readOpenCodeTranscriptSignal(path, 'ses-1')).toBeNull() - expect(readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 10 })).toBeNull() - }) - - it('returns the NEWEST limit messages when more history exists', () => { - const { db, path } = createTempDb() - applySchema(db) - for (let index = 1; index <= 10; index++) { - insertMessage(db, { id: `msg-${index}`, time: index }) - insertPart(db, { - id: `prt-${index}`, - messageId: `msg-${index}`, - time: index, - data: { type: 'text', text: `message ${index}` } - }) - } - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 3 }) - expect(page).not.toBeNull() - expect(page!.items.map((item) => item.message.id)).toEqual(['msg-8', 'msg-9', 'msg-10']) - expect(page!.hasMore).toBe(true) - expect(page!.beforeMessageRowId).toBe(page!.items[0]!.rowid) - }) - - it('pages strictly older messages from the raw-row cursor', () => { - const { db, path } = createTempDb() - applySchema(db) - for (let index = 1; index <= 10; index++) { - insertMessage(db, { id: `msg-${index}`, time: index }) - insertPart(db, { - id: `prt-${index}`, - messageId: `msg-${index}`, - time: index, - data: { type: 'text', text: `message ${index}` } - }) - } - const first = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 3 }) - const second = readOpenCodeTranscriptPage({ - dbPath: path, - sessionId: 'ses-1', - limit: 3, - beforeMessageRowId: first!.beforeMessageRowId! - }) - expect(second!.items.map((item) => item.message.id)).toEqual(['msg-5', 'msg-6', 'msg-7']) - }) - it('counts the limit in renderable messages, batching past non-renderable rows', () => { const { db, path } = createTempDb() applySchema(db) @@ -248,24 +139,6 @@ describe('readOpenCodeTranscriptPage', () => { expect(next!.hasMore).toBe(false) }) - it('walks a fully non-renderable history to its oldest raw row without dead-ending', () => { - const { db, path } = createTempDb() - applySchema(db) - for (let index = 1; index <= 4; index++) { - insertMessage(db, { id: `msg-${index}`, time: index }) - insertPart(db, { - id: `prt-${index}`, - messageId: `msg-${index}`, - time: index, - data: { type: 'step-start' } - }) - } - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 2 }) - expect(page!.items).toEqual([]) - expect(page!.hasMore).toBe(false) - expect(page!.beforeMessageRowId).toBe(messageRowid(db, 'msg-1')) - }) - it('re-reads messages trimmed by an overshoot batch instead of skipping them', () => { const { db, path } = createTempDb() applySchema(db) @@ -336,139 +209,6 @@ describe('readOpenCodeTranscriptPage', () => { expect(second!.items.map((item) => item.message.id)).toEqual(['msg-1']) expect(second!.hasMore).toBe(false) }) - - it('maps image file parts to image refs and skips non-image files', () => { - const { db, path } = createTempDb() - applySchema(db) - // Only native-platform file URLs decode to local paths; foreign paths stay opaque. - const localPath = process.platform === 'win32' ? 'C:\\Users\\u\\pic.jpg' : '/home/user/pic.jpg' - const fileUrl = pathToFileURL(localPath).href - insertMessage(db, { id: 'msg-1', time: 1, role: 'user' }) - insertPart(db, { - id: 'prt-data', - messageId: 'msg-1', - time: 1, - data: { - type: 'file', - mime: 'image/png', - url: 'data:image/png;base64,AAA', - filename: 'paste.png' - } - }) - insertPart(db, { - id: 'prt-file-url', - messageId: 'msg-1', - time: 1, - data: { type: 'file', mime: 'image/jpeg', url: fileUrl } - }) - insertPart(db, { - id: 'prt-plain-path', - messageId: 'msg-1', - time: 1, - data: { type: 'file', mime: 'image/webp', url: '/tmp/opencode/paste.webp' } - }) - insertPart(db, { - id: 'prt-pdf', - messageId: 'msg-1', - time: 1, - data: { type: 'file', mime: 'application/pdf', url: 'file:///tmp/doc.pdf' } - }) - insertPart(db, { - id: 'prt-text', - messageId: 'msg-1', - time: 1, - data: { type: 'text', text: 'prompt body' } - }) - - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 10 }) - expect(page!.items[0]!.message.blocks).toEqual([ - { type: 'image-ref', url: 'data:image/png;base64,AAA', alt: 'paste.png' }, - { type: 'image-ref', path: localPath }, - { type: 'image-ref', path: '/tmp/opencode/paste.webp' }, - { type: 'text', text: 'prompt body' } - ]) - }) - - it('filters synthetic text parts and maps tool parts to call/result blocks', () => { - const { db, path } = createTempDb() - applySchema(db) - insertMessage(db, { id: 'msg-1', time: 1, role: 'user' }) - insertPart(db, { - id: 'prt-syn', - messageId: 'msg-1', - time: 1, - data: { type: 'text', text: 'injected context', synthetic: true } - }) - insertPart(db, { - id: 'prt-text', - messageId: 'msg-1', - time: 1, - data: { type: 'text', text: 'real prompt' } - }) - insertMessage(db, { id: 'msg-2', time: 2, role: 'assistant' }) - insertPart(db, { - id: 'prt-tool-done', - messageId: 'msg-2', - time: 2, - data: { - type: 'tool', - tool: 'bash', - callID: 'call-1', - state: { status: 'completed', input: { command: 'ls' }, output: 'file list' } - } - }) - insertPart(db, { - id: 'prt-tool-pending', - messageId: 'msg-2', - time: 2, - data: { type: 'tool', tool: 'read', callID: 'call-2', state: { status: 'running' } } - }) - - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 10 }) - const user = page!.items.find((item) => item.message.id === 'msg-1')! - expect(user.message.blocks).toEqual([{ type: 'text', text: 'real prompt' }]) - const assistant = page!.items.find((item) => item.message.id === 'msg-2')! - expect(assistant.message.blocks).toEqual([ - { - type: 'tool-call', - callId: 'call-1', - name: 'bash', - state: 'completed', - input: { command: 'ls' } - }, - { type: 'tool-result', callId: 'call-1', output: 'file list' }, - { type: 'tool-call', callId: 'call-2', name: 'read', state: 'running', input: undefined } - ]) - }) - - it('surfaces a tool error string as the result output', () => { - const { db, path } = createTempDb() - applySchema(db) - insertMessage(db, { id: 'msg-1', time: 1, role: 'assistant' }) - insertPart(db, { - id: 'prt-tool-error', - messageId: 'msg-1', - time: 1, - data: { - type: 'tool', - tool: 'bash', - callID: 'call-1', - state: { status: 'error', input: { command: 'ls' }, error: 'exit 1: boom' } - } - }) - - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 10 }) - expect(page!.items[0]!.message.blocks).toEqual([ - { - type: 'tool-call', - callId: 'call-1', - name: 'bash', - state: 'failed', - input: { command: 'ls' } - }, - { type: 'tool-result', callId: 'call-1', output: 'exit 1: boom', isError: true } - ]) - }) }) describe('readOpenCodeTranscriptSignal', () => { @@ -493,41 +233,4 @@ describe('readOpenCodeTranscriptSignal', () => { maxPartTimeUpdated: 20 }) }) - - it('returns null when the session row does not exist', () => { - const { db, path } = createTempDb() - applySchema(db) - expect(readOpenCodeTranscriptSignal(path, 'missing')).toBeNull() - }) -}) - -it('stops before fetching a third part batch when earlier batches exhaust the page byte budget', () => { - const { db, path } = createTempDb() - applySchema(db) - const text = 'x'.repeat(100_000) - db.exec('BEGIN') - { - for (let i = 0; i < 300; i++) { - insertMessage(db, { id: `budget-${i}`, time: i }) - insertPart(db, { - id: `part-${i}`, - messageId: `budget-${i}`, - time: i, - data: { type: 'text', text } - }) - } - } - db.exec('COMMIT') - const prepared = vi.spyOn(Database.prototype, 'prepare') - try { - expect(() => - readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'ses-1', limit: 300 }) - ).toThrow('read limit') - const partQueries = prepared.mock.calls.filter( - ([sql]) => sql.includes('FROM part') && sql.includes('message_id IN') - ) - expect(partQueries).toHaveLength(2) - } finally { - prepared.mockRestore() - } }) diff --git a/src/main/native-chat/transcript-opencode-subscribe.test.ts b/src/main/native-chat/transcript-opencode-subscribe.test.ts deleted file mode 100644 index 75e457d2493..00000000000 --- a/src/main/native-chat/transcript-opencode-subscribe.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import Database from '../sqlite/sync-database' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { - readOpenCodeTranscriptPage, - readOpenCodeTranscriptSignal -} from './transcript-opencode-sqlite-query' -import { subscribeOpenCodeNativeChatTranscript } from './transcript-opencode-subscribe' - -const fixtures: { db: Database.Database; root: string; stop: () => void }[] = [] -it.each([undefined, 'zcode'] as const)( - 'discovers the subscribed session in its own store (%s)', - async (agent) => { - const resolveDbPath = vi.fn(async () => null) - const subscription = subscribeOpenCodeNativeChatTranscript( - { agent: agent ?? 'opencode', sessionId: 'second-database-session', onAppend: vi.fn() }, - undefined, - { resolveDbPath }, - agent - ) - subscription.unsubscribe() - expect(resolveDbPath).toHaveBeenCalledWith( - 'second-database-session', - expect.any(AbortSignal), - agent - ) - } -) -afterEach(() => { - for (const { db, root, stop } of fixtures.splice(0)) { - stop() - db.close() - rmSync(root, { recursive: true, force: true }) - } - vi.useRealTimers() -}) - -function watchFixture( - version: 'v1' | 'v2', - hiddenFirst = false, - messageCount = 300, - initialLimit = 300 -) { - vi.useFakeTimers() - const root = mkdtempSync(join(tmpdir(), 'orca-opencode-watch-')) - const path = join(root, 'opencode.db') - const db = new Database(path) - db.exec( - version === 'v1' - ? ` - CREATE TABLE session (id TEXT PRIMARY KEY); - CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, data TEXT, time_created INTEGER, time_updated INTEGER); - CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, data TEXT, time_updated INTEGER); - INSERT INTO session VALUES ('session'); - ` - : ` - CREATE TABLE session_v2 (id TEXT PRIMARY KEY); - CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session'); - ` - ) - const insert = (index: number, text = `message ${index}`) => { - if (version === 'v1') { - db.prepare('INSERT INTO message VALUES (?, ?, ?, 1, 1)').run( - String(index), - 'session', - '{"role":"user"}' - ) - db.prepare('INSERT INTO part VALUES (?, ?, ?, ?, 1)').run( - String(index), - String(index), - 'session', - JSON.stringify({ type: 'text', text }) - ) - } else { - db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, 1, 1)').run( - String(index), - 'session', - 'user', - index, - JSON.stringify({ text }) - ) - } - } - const update = (index: number, text: string, time = 2) => { - db.prepare( - version === 'v1' - ? 'UPDATE part SET data = ?, time_updated = ? WHERE message_id = ?' - : 'UPDATE session_message SET data = ?, time_updated = ? WHERE id = ?' - ).run(JSON.stringify(version === 'v1' ? { type: 'text', text } : { text }), time, String(index)) - } - const remove = (index: number) => { - if (version === 'v1') { - db.prepare('DELETE FROM part WHERE message_id = ?').run(String(index)) - db.prepare('DELETE FROM message WHERE id = ?').run(String(index)) - } else { - db.prepare('DELETE FROM session_message WHERE id = ?').run(String(index)) - } - } - const batch = (mutate: () => void) => { - db.exec('BEGIN') - try { - mutate() - db.exec('COMMIT') - } catch (error) { - db.exec('ROLLBACK') - throw error - } - } - batch(() => { - for (let index = 1; index <= messageCount; index++) { - insert(index, hiddenFirst && index === 1 ? '' : undefined) - } - }) - let displayed: NativeChatMessage[] = [] - const onReplace = vi.fn((messages: NativeChatMessage[]) => { - displayed = messages - }) - const onAppend = vi.fn((messages: NativeChatMessage[]) => { - displayed.push(...messages) - }) - const readPage = vi.fn(async (args: Parameters[0]) => - readOpenCodeTranscriptPage(args) - ) - const subscription = subscribeOpenCodeNativeChatTranscript( - { - agent: 'opencode', - sessionId: 'session', - initialLimit, - resolvePollIntervalMs: 5, - onInitialSnapshot: (messages) => { - displayed = messages - }, - onAppend, - onReplace - }, - undefined, - { - resolveDbPath: async () => path, - readSignal: async (dbPath, sessionId) => readOpenCodeTranscriptSignal(dbPath, sessionId), - readPage - } - ) - fixtures.push({ db, root, stop: subscription.unsubscribe }) - return { - db, - insert, - update, - remove, - batch, - displayed: () => displayed, - onReplace, - onAppend, - readPage - } -} - -describe.each(['v1', 'v2'] as const)('OpenCode %s watch reconciliation', (version) => { - it('removes the oldest displayed row when an append keeps the database count unchanged', async () => { - const f = watchFixture(version, false, 1000) - await vi.advanceTimersByTimeAsync(0) - expect(f.displayed()).toHaveLength(300) - f.batch(() => { - f.remove(701) - f.insert(1001) - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toHaveLength(300) - expect(f.displayed()[0]?.blocks).toEqual([{ type: 'text', text: 'message 702' }]) - expect(f.displayed().at(-1)?.blocks).toEqual([{ type: 'text', text: 'message 1001' }]) - expect(f.onReplace).toHaveBeenCalledOnce() - expect(f.readPage.mock.calls.every(([args]) => args.limit <= 2400)).toBe(true) - }) - - it('replaces an edit older than the newest 100 displayed messages', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - expect(f.displayed()).toHaveLength(300) - f.update(1, 'edited oldest') - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()[0]?.blocks).toEqual([{ type: 'text', text: 'edited oldest' }]) - expect(f.onReplace).toHaveBeenCalledOnce() - }) - - it('includes an older row that becomes renderable after the emitted frontier', async () => { - const f = watchFixture(version, true) - await vi.advanceTimersByTimeAsync(0) - expect(f.displayed()).toHaveLength(299) - f.update(1, 'newly renderable') - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()[0]?.blocks).toEqual([{ type: 'text', text: 'newly renderable' }]) - expect(f.displayed()).toHaveLength(300) - }) - - it.each([1, 300])('removes a deleted row at %s from the displayed window', async (index) => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.remove(index) - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toHaveLength(299) - expect( - f - .displayed() - .some((message) => message.id === (version === 'v1' ? String(index) : `opencode:${index}`)) - ).toBe(false) - expect(f.onReplace).toHaveBeenCalledOnce() - }) - - it('replaces an empty session and permits a reused provider cursor to append', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.batch(() => { - for (let index = 1; index <= 300; index++) { - f.remove(index) - } - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toEqual([]) - f.insert(1, 'after revert') - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed().map((message) => message.blocks)).toEqual([ - [{ type: 'text', text: 'after revert' }] - ]) - }) - - it('removes a row whose last renderable content is removed', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.update(1, '') - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toHaveLength(299) - expect(f.displayed()[0]?.blocks).toEqual([{ type: 'text', text: 'message 2' }]) - }) - - it('continues checking previously appended history and bounds every read', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.batch(() => { - for (let index = 301; index <= 450; index++) { - f.insert(index) - } - }) - await vi.advanceTimersByTimeAsync(10) - f.update(1, 'edited after append') - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()[0]?.blocks).toEqual([{ type: 'text', text: 'edited after append' }]) - expect(f.readPage.mock.calls.every(([args]) => args.limit <= 2400)).toBe(true) - const reads = f.readPage.mock.calls.length - await vi.advanceTimersByTimeAsync(20) - expect(f.readPage).toHaveBeenCalledTimes(reads) - }) - - it('holds the frontier and retries when a burst cannot bridge within the read cap', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.batch(() => { - for (let index = 301; index <= 2800; index++) { - f.insert(index) - } - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toHaveLength(300) - expect(f.onReplace).not.toHaveBeenCalled() - const reads = f.readPage.mock.calls.length - await vi.advanceTimersByTimeAsync(10) - expect(f.readPage.mock.calls.length).toBeGreaterThan(reads) - expect(f.readPage.mock.calls.every(([args]) => args.limit <= 2400)).toBe(true) - f.batch(() => { - for (let index = 301; index <= 2800; index++) { - f.remove(index) - } - f.insert(301, 'after discarded burst') - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.displayed()).toHaveLength(301) - expect(f.displayed().at(-1)?.blocks).toEqual([{ type: 'text', text: 'after discarded burst' }]) - }) - - it('keeps appending after the remembered window reaches 2400 rows', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - for (let start = 301; start <= 2400; start += 300) { - f.batch(() => { - for (let index = start; index < start + 300; index++) { - f.insert(index) - } - }) - await vi.advanceTimersByTimeAsync(10) - } - f.onReplace.mockClear() - f.onAppend.mockClear() - for (let index = 2401; index <= 2403; index++) { - f.insert(index) - await vi.advanceTimersByTimeAsync(10) - } - expect(f.onReplace).not.toHaveBeenCalled() - expect(f.onAppend.mock.calls.map(([messages]) => messages.length)).toEqual([1, 1, 1]) - expect(f.displayed()).toHaveLength(2403) - expect(f.readPage.mock.calls.every(([args]) => args.limit <= 2400)).toBe(true) - }) - - it('keeps appending after a bridged burst fills the cap', async () => { - const f = watchFixture(version) - await vi.advanceTimersByTimeAsync(0) - f.batch(() => { - for (let index = 301; index <= 2600; index++) { - f.insert(index) - } - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.onReplace).toHaveBeenCalledOnce() - expect(f.displayed()).toHaveLength(2400) - f.onReplace.mockClear() - f.insert(2601) - await vi.advanceTimersByTimeAsync(10) - expect(f.onReplace).not.toHaveBeenCalled() - expect(f.onAppend).toHaveBeenCalledOnce() - expect(f.displayed().at(-1)?.blocks).toEqual([{ type: 'text', text: 'message 2601' }]) - }) - - it.each(['delete', 'hide', 'edit'] as const)( - 'detects a first-tail-row %s outside the capped page during an append', - async (operation) => { - const f = watchFixture(version, false, 2500, 2400) - await vi.advanceTimersByTimeAsync(0) - f.batch(() => { - if (operation === 'delete') { - f.remove(101) - } else { - f.update(101, operation === 'hide' ? '' : 'edited first tail row') - } - f.insert(2501) - f.insert(2502) - }) - await vi.advanceTimersByTimeAsync(10) - expect(f.onReplace).toHaveBeenCalledOnce() - expect(f.onAppend).not.toHaveBeenCalled() - expect(f.readPage.mock.calls.every(([args]) => args.limit <= 2400)).toBe(true) - } - ) -}) diff --git a/src/main/native-chat/transcript-opencode.test.ts b/src/main/native-chat/transcript-opencode.test.ts deleted file mode 100644 index 30a8897d977..00000000000 --- a/src/main/native-chat/transcript-opencode.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { - readOpenCodeNativeChatTranscriptFull, - readOpenCodeNativeChatTranscriptTail, - resolveOpenCodeTranscriptDbPath, - type OpenCodeTranscriptDeps -} from './transcript-opencode' -import { DESKTOP_READ_WINDOW } from './transcript-watch-contract' - -let tempDirs: string[] = [] - -afterEach(() => { - for (const dir of tempDirs) { - rmSync(dir, { recursive: true, force: true }) - } - tempDirs = [] - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -describe('readOpenCodeNativeChatTranscriptFull', () => { - const message = (id: string): NativeChatMessage => ({ - id, - role: 'user', - blocks: [{ type: 'text', text: id }], - timestamp: null, - source: 'transcript' - }) - - it('returns the whole session oldest-first across page boundaries', async () => { - // Fetch newest windows first; concatenate windows in reverse while preserving each window’s order. - const ids = ['m1', 'm2', 'm3', 'm4', 'm5'] - const readPage: OpenCodeTranscriptDeps['readPage'] = async (args) => { - const upper = args.beforeMessageRowId ?? 6 - const lower = Math.max(1, upper - 2) - const slice = ids.slice(lower - 1, upper - 1) - return { - items: slice.map((id, index) => ({ - rowid: lower + index, - fingerprint: id, - message: message(id) - })), - hasMore: lower > 1, - beforeMessageRowId: lower > 1 ? lower : null - } - } - const result = await readOpenCodeNativeChatTranscriptFull('ses-1', { - resolveDbPath: async () => '/fake/opencode.db', - readPage - }) - expect(result).toEqual({ messages: ids.map(message), sourceEmpty: false }) - }) - - it('reports notFound when the first page misses', async () => { - const readPage: OpenCodeTranscriptDeps['readPage'] = async () => null - const result = await readOpenCodeNativeChatTranscriptFull('missing', { - resolveDbPath: async () => '/fake/opencode.db', - readPage - }) - expect(result).toEqual({ error: 'Transcript unavailable', notFound: true }) - }) - - it.each([ - [null, true], - [42, false] - ])( - 'distinguishes no raw rows from undecodable rows at cursor %s', - async (cursor, sourceEmpty) => { - const result = await readOpenCodeNativeChatTranscriptFull('ses-1', { - resolveDbPath: async () => '/fake/opencode.db', - readPage: async () => ({ items: [], hasMore: false, beforeMessageRowId: cursor }) - }) - expect(result).toEqual({ messages: [], sourceEmpty }) - } - ) - - it('reads the selected ZCode store on every full-read page', async () => { - const resolveDbPath = vi.fn(async () => '/fake/zcode.db') - const readPage = vi.fn(async () => ({ items: [], hasMore: false, beforeMessageRowId: null })) - await readOpenCodeNativeChatTranscriptFull( - 'z-session', - { resolveDbPath, readPage }, - undefined, - 'zcode' - ) - expect(resolveDbPath).toHaveBeenCalledWith('z-session', undefined, 'zcode') - expect(readPage).toHaveBeenCalledWith( - { dbPath: '/fake/zcode.db', sessionId: 'z-session', limit: 500, agent: 'zcode' }, - undefined - ) - }) - - it('returns a retryable error when DB discovery throws', async () => { - const result = await readOpenCodeNativeChatTranscriptFull('ses-1', { - resolveDbPath: async () => { - throw new Error('EACCES') - }, - readPage: async () => null - }) - expect(result).toEqual({ error: 'EACCES' }) - }) -}) - -describe('readOpenCodeNativeChatTranscriptTail', () => { - const message = (id: string): NativeChatMessage => ({ - id, - role: 'user', - blocks: [{ type: 'text', text: id }], - timestamp: null, - source: 'transcript' - }) - - it('passes beforeOffset through, floors the limit, and returns the page shape', async () => { - let seen: { limit: number; beforeMessageRowId?: number } | null = null - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 10.9, beforeOffset: 42 }, - { - resolveDbPath: async () => '/fake/opencode.db', - readPage: async (args) => { - seen = args - return { - items: [{ rowid: 40, fingerprint: 'm1', message: message('m1') }], - hasMore: true, - beforeMessageRowId: 39 - } - } - } - ) - expect(seen).toMatchObject({ - dbPath: '/fake/opencode.db', - sessionId: 'ses-1', - limit: 10, - beforeMessageRowId: 42 - }) - expect(result).toEqual({ messages: [message('m1')], hasMore: true, beforeOffset: 39 }) - }) - - it('defaults a non-positive limit to the desktop window and 0 beforeOffset', async () => { - let seenLimit = 0 - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 0 }, - { - resolveDbPath: async () => '/fake/opencode.db', - readPage: async (args) => { - seenLimit = args.limit - return { - items: [{ rowid: 7, fingerprint: 'm1', message: message('m1') }], - hasMore: false, - beforeMessageRowId: null - } - } - } - ) - expect(seenLimit).toBe(DESKTOP_READ_WINDOW) - expect(result).toEqual({ messages: [message('m1')], hasMore: false, beforeOffset: 0 }) - }) - - it('reports notFound when the page misses — the session row has not landed', async () => { - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 10 }, - { - resolveDbPath: async () => '/fake/opencode.db', - readPage: async () => null - } - ) - expect(result).toEqual({ error: 'Transcript unavailable', notFound: true }) - }) - - it('reports notFound when no DB resolves', async () => { - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 10 }, - { resolveDbPath: async () => null, readPage: async () => null } - ) - expect(result).toEqual({ error: 'Transcript unavailable', notFound: true }) - }) - - it('returns a retryable error without notFound when the page read throws', async () => { - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 10 }, - { - resolveDbPath: async () => '/fake/opencode.db', - readPage: async () => { - throw new Error('worker timeout') - } - } - ) - expect(result).toEqual({ error: 'worker timeout' }) - }) - - it('returns a retryable error when DB discovery throws', async () => { - const result = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'ses-1', limit: 10 }, - { - resolveDbPath: async () => { - throw new Error('EACCES') - }, - readPage: async () => null - } - ) - expect(result).toEqual({ error: 'EACCES' }) - }) -}) - -describe('resolveOpenCodeTranscriptDbPath', () => { - function createDataHome(): string { - const dataHome = mkdtempSync(join(tmpdir(), 'orca-opencode-discover-')) - tempDirs.push(dataHome) - return dataHome - } - - it('prefers the canonical opencode.db over stale opencode-*.db siblings', async () => { - const dataHome = createDataHome() - const dir = join(dataHome, 'opencode') - mkdirSync(dir, { recursive: true }) - writeFileSync(join(dir, 'opencode-backup.db'), '') - writeFileSync(join(dir, 'opencode.db'), '') - vi.stubEnv('XDG_DATA_HOME', dataHome) - await expect(resolveOpenCodeTranscriptDbPath()).resolves.toBe(join(dir, 'opencode.db')) - }) - - it('falls back to a sibling when no canonical DB exists', async () => { - const dataHome = createDataHome() - const dir = join(dataHome, 'opencode') - mkdirSync(dir, { recursive: true }) - writeFileSync(join(dir, 'opencode-backup.db'), '') - vi.stubEnv('XDG_DATA_HOME', dataHome) - await expect(resolveOpenCodeTranscriptDbPath()).resolves.toBe(join(dir, 'opencode-backup.db')) - }) - - it('keeps the canonical v1 DB when OpenCode 2 DBs coexist', async () => { - const dataHome = createDataHome() - const dir = join(dataHome, 'opencode') - mkdirSync(dir, { recursive: true }) - writeFileSync(join(dir, 'opencode-next.db'), '') - writeFileSync(join(dir, 'opencode-local.db'), '') - writeFileSync(join(dir, 'opencode.db'), '') - vi.stubEnv('XDG_DATA_HOME', dataHome) - await expect(resolveOpenCodeTranscriptDbPath()).resolves.toBe(join(dir, 'opencode.db')) - }) - - it('honors the OPENCODE_DB override and returns null with no DBs', async () => { - const dataHome = createDataHome() - const override = join(dataHome, 'custom.db') - writeFileSync(override, '') - vi.stubEnv('XDG_DATA_HOME', dataHome) - vi.stubEnv('OPENCODE_DB', override) - await expect(resolveOpenCodeTranscriptDbPath()).resolves.toBe(override) - - vi.stubEnv('OPENCODE_DB', '') - await expect(resolveOpenCodeTranscriptDbPath()).resolves.toBe(null) - }) -}) diff --git a/src/main/native-chat/transcript-opencode2-sqlite.test.ts b/src/main/native-chat/transcript-opencode2-sqlite.test.ts deleted file mode 100644 index 35f2126a679..00000000000 --- a/src/main/native-chat/transcript-opencode2-sqlite.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { AGENT_SESSION_HOST_STATUS_COPY } from '../../shared/agent-session/view/agent-session-host-status-rows' -import Database from '../sqlite/sync-database' -import { - readOpenCodeTranscriptPage, - readOpenCodeTranscriptSignal -} from './transcript-opencode-sqlite-query' -import { subscribeOpenCodeNativeChatTranscript } from './transcript-opencode-subscribe' - -const fixtures: { db: Database.Database; root: string }[] = [] -afterEach(() => { - for (const { db, root } of fixtures.splice(0)) { - db.close() - rmSync(root, { recursive: true, force: true }) - } -}) -function fixture() { - const root = mkdtempSync(join(tmpdir(), 'orca-native-opencode2-')) - const path = join(root, 'opencode.db') - const db = new Database(path) - fixtures.push({ db, root }) - db.exec(`CREATE TABLE session_v2 (id TEXT PRIMARY KEY); - CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, - seq INTEGER, data TEXT, time_created INTEGER, time_updated INTEGER); - INSERT INTO session_v2 VALUES ('session'); - ALTER TABLE session_v2 ADD COLUMN directory TEXT; - UPDATE session_v2 SET directory = '/folder';`) - const insertMessage = db.prepare('INSERT INTO session_message VALUES (?, ?, ?, ?, ?, ?, ?)') - let sequence = 0 - const insert = (id: string, type: string, data: unknown, time = 1) => - insertMessage.run(id, 'session', type, ++sequence, JSON.stringify(data), time, time) - return { db, path, insert } -} - -describe('OpenCode 2 native transcript', () => { - it('paginates real v2 user/assistant records past bookkeeping without losing messages', () => { - const { path, insert } = fixture() - insert('one', 'user', { text: 'first prompt' }) - insert('empty', 'idle', { outcome: 'succeeded' }) - insert('two', 'assistant', { content: [{ type: 'text', text: 'first reply' }] }) - insert('three', 'user', { text: 'second prompt' }) - insert('last-empty', 'idle', { outcome: 'succeeded' }) - expect(readOpenCodeTranscriptSignal(path, 'session')?.cwd).toBe('/folder') - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 2 }) - expect(page?.items.map((item) => item.message.id)).toEqual(['opencode:two', 'opencode:three']) - expect(page?.hasMore).toBe(true) - const older = readOpenCodeTranscriptPage({ - dbPath: path, - sessionId: 'session', - limit: 2, - beforeMessageRowId: page?.beforeMessageRowId ?? undefined - }) - expect(older?.items.map((item) => item.message.id)).toEqual(['opencode:one']) - expect(older?.hasMore).toBe(false) - }) - - it('preserves tool identity, inputs, outputs and errors across in-place updates', () => { - const { db, path, insert } = fixture() - const content = [ - { - type: 'tool', - id: 'call', - name: 'bash', - state: { status: 'running', input: { command: 'pwd' } } - } - ] - insert('tool', 'assistant', { content }) - const before = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 2 }) - expect(before?.items[0]?.message.blocks).toEqual([ - { - type: 'tool-call', - callId: 'call', - name: 'bash', - state: 'running', - input: { command: 'pwd' } - } - ]) - db.prepare('UPDATE session_message SET data = ?, time_updated = 2 WHERE id = ?').run( - JSON.stringify({ - content: [ - { - ...content[0], - state: { - status: 'error', - input: { command: 'pwd' }, - error: { message: 'denied' }, - content: [] - } - } - ] - }), - 'tool' - ) - const after = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 2 }) - expect(after?.items[0]?.fingerprint).not.toBe(before?.items[0]?.fingerprint) - expect(after?.items[0]?.message.blocks[0]).toMatchObject({ state: 'failed', callId: 'call' }) - expect(after?.items[0]?.message.blocks[1]).toMatchObject({ isError: true, callId: 'call' }) - expect(readOpenCodeTranscriptSignal(path, 'session')?.maxPartTimeUpdated).toBe(2) - }) - - it('surfaces provider errors and explicit interrupted boundaries', () => { - const { path, insert } = fixture() - insert('error', 'assistant', { error: { type: 'provider', message: 'Rate limit exceeded' } }) - insert('boundary', 'idle', { outcome: 'interrupted' }) - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 2 }) - expect(page?.items.map((item) => item.message.blocks)).toEqual([ - [{ type: 'text', text: 'Rate limit exceeded' }], - [{ type: 'text', text: 'Conversation interrupted' }] - ]) - }) - - it.each(['x', '😀'])( - 'omits oversized %s content with a stable cursor and time fingerprint', - (character) => { - const { db, path, insert } = fixture() - insert('before', 'user', { text: 'before' }) - insert('large', 'user', { - text: '', - files: [{ mime: 'image/png', data: character.repeat(2 * 1024 * 1024) }] - }) - insert('after', 'assistant', { text: 'after' }) - const args = { dbPath: path, sessionId: 'session', limit: 2 } - const page = readOpenCodeTranscriptPage(args) - expect(page?.items.map((item) => item.message.id)).toEqual([ - 'opencode:large', - 'opencode:after' - ]) - expect(page?.items[0]).toMatchObject({ - rowid: 2, - message: { - role: 'system', - timestamp: 1, - transcriptOffset: 2, - blocks: [ - { - type: 'text', - text: AGENT_SESSION_HOST_STATUS_COPY['history-item-too-large'], - presentation: 'history-item-too-large' - } - ] - } - }) - expect(readOpenCodeTranscriptPage(args)?.items[0]?.fingerprint).toBe( - page?.items[0]?.fingerprint - ) - db.prepare("UPDATE session_message SET time_updated = 2 WHERE id = 'large'").run() - expect(readOpenCodeTranscriptPage(args)?.items[0]?.fingerprint).not.toBe( - page?.items[0]?.fingerprint - ) - expect( - readOpenCodeTranscriptPage({ - ...args, - beforeMessageRowId: page?.beforeMessageRowId ?? undefined - })?.items.map((item) => item.message.id) - ).toEqual(['opencode:before']) - } - ) - - it('refuses excessive sparse scans instead of returning a partial transcript', () => { - const { db, path, insert } = fixture() - // The regression is the scan cap; avoid quadratic fixture scans between batches. - db.exec('CREATE INDEX session_message_sequence ON session_message (session_id, seq)') - db.exec('BEGIN') - for (let index = 0; index < 10001; index++) { - insert(String(index), 'idle', {}) - } - db.exec('COMMIT') - expect(() => - readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 1 }) - ).toThrow('read limit') - }) - - it('keeps the aggregate page byte budget when individual rows fit', () => { - const { db, path, insert } = fixture() - db.exec('BEGIN') - for (let index = 0; index < 18; index++) { - insert(String(index), 'user', { text: 'x'.repeat(1024 * 1024) }) - } - db.exec('COMMIT') - expect(() => - readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 18 }) - ).toThrow('read limit') - }) - - it('reconciles live streaming updates and stops after unsubscribe', async () => { - const { db, path, insert } = fixture() - insert('reply', 'assistant', { content: [{ type: 'text', text: 'partial' }] }) - const snapshots: unknown[] = [] - const replacements: unknown[] = [] - const subscription = subscribeOpenCodeNativeChatTranscript( - { - agent: 'opencode', - sessionId: 'session', - resolvePollIntervalMs: 5, - onAppend: () => {}, - onInitialSnapshot: (messages) => snapshots.push(messages), - onReplace: (messages) => replacements.push(messages) - }, - undefined, - { - resolveDbPath: async () => path, - readSignal: async (dbPath, sessionId) => readOpenCodeTranscriptSignal(dbPath, sessionId), - readPage: async (args) => readOpenCodeTranscriptPage(args) - } - ) - try { - await expect.poll(() => snapshots.length).toBe(1) - db.prepare('UPDATE session_message SET data = ?, time_updated = 2').run( - JSON.stringify({ content: [{ type: 'text', text: 'complete' }] }) - ) - await expect.poll(() => replacements.length).toBe(1) - expect(replacements[0]).toMatchObject([{ blocks: [{ text: 'complete' }] }]) - subscription.unsubscribe() - db.prepare('UPDATE session_message SET time_updated = 3').run() - await new Promise((resolve) => setTimeout(resolve, 25)) - expect(replacements).toHaveLength(1) - } finally { - subscription.unsubscribe() - } - }) -}) - -it('preserves real v2 user image files with or without accompanying text', () => { - const { path, insert } = fixture() - const file = { data: 'YQ==', mime: 'image/png', source: { type: 'inline' }, name: 'tiny.png' } - insert('text-image', 'user', { text: 'see this', files: [file] }) - insert('image-only', 'user', { text: '', files: [file] }) - const page = readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 10 }) - expect(page?.items.map((item) => item.message.blocks)).toEqual([ - [ - { type: 'text', text: 'see this' }, - { type: 'image-ref', url: `data:${file.mime};base64,${file.data}`, alt: 'tiny.png' } - ], - [{ type: 'image-ref', url: `data:${file.mime};base64,${file.data}`, alt: 'tiny.png' }] - ]) -}) - -it('prefers the migrated live v2 session over retained legacy tables for pages and signals', () => { - const { db, path, insert } = fixture() - db.exec(`CREATE TABLE session (id TEXT PRIMARY KEY); - CREATE TABLE message (id TEXT, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT); - CREATE TABLE part (id TEXT, message_id TEXT, session_id TEXT, time_updated INTEGER, data TEXT); - INSERT INTO session VALUES ('session'); - INSERT INTO message VALUES ('old', 'session', 1, 1, '{"role":"user"}'); - INSERT INTO part VALUES ('part', 'old', 'session', 1, '{"type":"text","text":"frozen legacy"}');`) - insert('imported', 'user', { text: 'migrated prompt' }) - insert('live', 'assistant', { content: [{ type: 'text', text: 'live reply' }] }) - expect(readOpenCodeTranscriptSignal(path, 'session')?.messageCount).toBe(2) - expect( - readOpenCodeTranscriptPage({ dbPath: path, sessionId: 'session', limit: 10 })?.items.map( - (item) => item.message.id - ) - ).toEqual(['opencode:imported', 'opencode:live']) -}) diff --git a/src/main/native-chat/transcript-reader-codex-history-mode.test.ts b/src/main/native-chat/transcript-reader-codex-history-mode.test.ts deleted file mode 100644 index 6013dd838d0..00000000000 --- a/src/main/native-chat/transcript-reader-codex-history-mode.test.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { codexLegacyMirrorRecords } from './agent-session-journal/codex-history-test-fixture' -import { prepareLegacyTranscriptImport } from './agent-session-journal/journal-legacy-import' -import { createNativeChatMerger, replaceList } from '../../shared/native-chat/native-chat-merge' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { extractPendingAsk } from '../../shared/native-chat/input/native-chat-ask' -import { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' -import { readNativeChatTranscript } from './transcript-reader' -import { readNativeChatTranscriptTail } from './transcript-tail-reader' - -let tempRoots: string[] = [] - -afterEach(async () => { - await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) - tempRoots = [] -}) - -async function writeCodexFixture(records: unknown[]): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-codex-history-')) - tempRoots.push(root) - const filePath = join(root, 'rollout.jsonl') - await writeFile(filePath, records.map((record) => JSON.stringify(record)).join('\n')) - return filePath -} - -function completedItem(item: unknown, timestamp: string): unknown { - return { - timestamp, - type: 'event_msg', - payload: { - type: 'item_completed', - thread_id: 'thread-1', - turn_id: 'turn-1', - item, - completed_at_ms: 1 - } - } -} - -describe('Codex transcript history modes', () => { - it('reads unwrapped response records from early rollouts', async () => { - const filePath = await writeCodexFixture([ - { - id: 'session-1', - timestamp: '2025-06-28T10:00:00.000Z', - instructions: null - }, - { - type: 'message', - id: null, - timestamp: '2025-06-28T10:00:01.000Z', - role: 'user', - content: [ - { type: 'input_text', text: 'Early prompt' }, - { type: 'input_image', image_url: 'data:image/png;base64,abc' } - ] - }, - { - type: 'message', - id: 'assistant-1', - timestamp: '2025-06-28T10:00:02.000Z', - role: 'assistant', - content: [{ type: 'output_text', text: 'Early response' }] - }, - { - type: 'message', - id: 'system-1', - role: 'system', - content: [{ type: 'input_text', text: 'Internal instructions' }] - } - ]) - - const result = await readNativeChatTranscript('codex', 'session-1', { filePath }) - const tail = await readNativeChatTranscriptTail({ - agent: 'codex', - sessionId: 'session-1', - filePath, - limit: 50 - }) - - expect(result).toMatchObject({ - messages: [ - { - role: 'user', - timestamp: Date.parse('2025-06-28T10:00:01.000Z'), - blocks: [ - { type: 'text', text: 'Early prompt' }, - { type: 'image-ref', url: 'data:image/png;base64,abc' } - ] - }, - { - id: 'assistant-1', - role: 'assistant', - timestamp: Date.parse('2025-06-28T10:00:02.000Z'), - blocks: [{ type: 'text', text: 'Early response' }] - } - ] - }) - expect(tail).toMatchObject({ messages: 'messages' in result ? result.messages : [] }) - }) - - it('reads canonical paginated messages without exposing model-only response copies', async () => { - const filePath = await writeCodexFixture([ - { - timestamp: '2026-08-09T10:00:00.000Z', - type: 'session_meta', - payload: { id: 'session-1', history_mode: 'paginated' } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'developer', - content: [{ type: 'text', text: 'internal instructions' }] - } - }, - { - type: 'response_item', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'input_text', text: 'model copy' }] - } - }, - completedItem( - { - type: 'UserMessage', - id: 'user-1', - content: [ - { type: 'text', text: 'Visible prompt', text_elements: [] }, - { type: 'image', image_url: 'data:image/png;base64,abc' }, - { type: 'local_image', path: '/tmp/reference.png' }, - { type: 'skill', name: 'example', path: '/tmp/SKILL.md' } - ] - }, - '2026-08-09T10:00:01.000Z' - ), - completedItem({ type: 'ContextCompaction', id: 'compaction-1' }, '2026-08-09T10:00:01.500Z'), - { - type: 'response_item', - payload: { - type: 'reasoning', - id: 'reason', - summary: [{ type: 'summary_text', text: 'why' }] - } - }, - completedItem( - { type: 'Reasoning', id: 'reason', summary_text: ['why'], raw_content: [] }, - '2026-08-09T10:00:01.750Z' - ), - { - type: 'response_item', - payload: { - type: 'message', - role: 'assistant', - content: [{ type: 'output_text', text: 'model copy' }] - } - }, - completedItem( - { - type: 'AgentMessage', - id: 'assistant-1', - content: [{ type: 'Text', text: 'Visible response' }], - phase: 'final_answer' - }, - '2026-08-09T10:00:02.000Z' - ) - ]) - - const result = await readNativeChatTranscript('codex', 'session-1', { filePath }) - const tail = await readNativeChatTranscriptTail({ - agent: 'codex', - sessionId: 'session-1', - filePath, - limit: 50 - }) - - expect(result).toMatchObject({ - messages: [ - { - id: 'user-1', - role: 'user', - blocks: [ - { type: 'text', text: 'Visible prompt' }, - { type: 'image-ref', url: 'data:image/png;base64,abc' }, - { type: 'image-ref', path: '/tmp/reference.png' } - ] - }, - { - id: 'compaction-1', - role: 'system', - timestamp: Date.parse('2026-08-09T10:00:01.500Z'), - blocks: [{ type: 'text', text: 'Context compacted', presentation: 'compaction' }] - }, - { id: 'reason', role: 'reasoning', blocks: [{ type: 'text', text: 'why' }] }, - { - id: 'assistant-1', - role: 'assistant', - blocks: [{ type: 'text', text: 'Visible response' }] - } - ] - }) - expect(tail).toMatchObject({ messages: 'messages' in result ? result.messages : [] }) - const snapshot = createNativeChatMerger() - replaceList(snapshot, 'messages' in result ? result.messages : []) - expect(snapshot.list.filter(({ role }) => role === 'reasoning')).toHaveLength(1) - const imported = await prepareLegacyTranscriptImport({ - agent: 'codex', - sessionId: 'session-1', - options: { filePath } - }) - expect( - imported.ok && - imported.items - .filter(({ body }) => body.kind === 'message' && body.role === 'reasoning') - .map(({ body }) => body) - ).toEqual([{ kind: 'message', role: 'reasoning', blocks: [{ type: 'text', text: 'why' }] }]) - }) - - it('keeps legacy event messages without duplicating response copies', async () => { - const filePath = await writeCodexFixture(codexLegacyMirrorRecords()) - - const result = await readNativeChatTranscript('codex', 'session-1', { filePath }) - - expect(result).toMatchObject({ - messages: [ - { role: 'user', blocks: [{ type: 'text', text: 'Prompt' }] }, - { - role: 'system', - blocks: [{ type: 'text', text: 'Context compacted', presentation: 'compaction' }] - }, - { role: 'assistant', blocks: [{ type: 'text', text: 'Response' }] } - ] - }) - }) - - it('decodes freeform tool calls and outputs', () => { - const call = decodeCodexTranscriptLine( - JSON.stringify({ - type: 'response_item', - payload: { - type: 'custom_tool_call', - id: 'call-1', - call_id: 'durable-call-1', - name: 'exec', - input: 'pwd' - } - }), - 'fallback-call' - ) - const output = decodeCodexTranscriptLine( - JSON.stringify({ - type: 'response_item', - payload: { type: 'custom_tool_call_output', call_id: 'durable-call-1', output: 'ok' } - }), - 'fallback-output' - ) - - expect(call).toMatchObject({ - id: 'call-1', - role: 'assistant', - blocks: [{ type: 'tool-call', name: 'exec', input: 'pwd', callId: 'durable-call-1' }] - }) - expect(output).toMatchObject({ - id: 'fallback-output', - role: 'tool', - blocks: [{ type: 'tool-result', output: 'ok' }] - }) - }) - - it('passes an argument payload through untouched, so no consumer changes shape', () => { - const call = decodeCodexTranscriptLine( - JSON.stringify({ - type: 'response_item', - payload: { - type: 'function_call', - id: 'call-2', - name: 'shell', - arguments: '{"command":["bash","-lc","echo hi"]}' - } - }), - 'fallback-args' - ) - - expect(call?.blocks[0]).toMatchObject({ - type: 'tool-call', - name: 'shell', - input: '{"command":["bash","-lc","echo hi"]}' - }) - }) - - it('does not raise a question card from an unrelated tool that carries a questions payload', () => { - const call = decodeCodexTranscriptLine( - JSON.stringify({ - type: 'response_item', - payload: { - type: 'function_call', - id: 'call-3', - name: 'some_mcp_tool', - arguments: '{"questions":[{"question":"Which branch?","options":["main","dev"]}]}' - } - }), - 'fallback-questions' - ) - - expect(call).not.toBeNull() - expect(extractPendingAsk(call ? [call] : [])).toBeNull() - }) - - it('keeps an async question pending past its display acknowledgement until the user replies', () => { - const lines = [ - { - type: 'response_item', - payload: { - type: 'function_call', - name: 'request_user_input_async', - call_id: 'call-async', - arguments: - '{"questions":[{"title":"Which color?","options":["Red (Recommended)","Blue"]},{"title":"Any constraints?"}]}' - } - }, - completedItem( - { - type: 'AgentMessage', - id: 'call-async', - content: [{ type: 'Text', text: 'Which color?\n- Red (Recommended)\n- Blue' }], - delivery: 'async' - }, - '2026-10-21T00:00:01.000Z' - ), - { - type: 'response_item', - payload: { - type: 'function_call_output', - call_id: 'call-async', - output: '{"accepted":true}' - } - } - ] - const messages = lines.flatMap((line, index) => { - const message = decodeCodexTranscriptLine(JSON.stringify(line), `line-${index}`) - return message ? [message] : [] - }) - - expect(extractPendingAsk(messages)).toEqual({ - replyAsMessage: true, - questions: [ - { - question: 'Which color?', - multiSelect: false, - options: [{ label: 'Red (Recommended)' }, { label: 'Blue' }] - }, - { question: 'Any constraints?', multiSelect: false, options: [] } - ] - }) - - const reply = decodeCodexTranscriptLine( - JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'Red' } }), - 'reply' - ) - expect(extractPendingAsk([...messages, ...(reply ? [reply] : [])])).toBeNull() - }) -}) diff --git a/src/main/native-chat/transcript-reader.test.ts b/src/main/native-chat/transcript-reader.test.ts index fa415244580..18aa6679870 100644 --- a/src/main/native-chat/transcript-reader.test.ts +++ b/src/main/native-chat/transcript-reader.test.ts @@ -2,10 +2,8 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { readNativeChatTranscript } from './transcript-reader' import { nativeChatLineDecoderForAgent, - readNativeChatTranscriptTail, readNativeChatTranscriptTailFile } from './transcript-tail-reader' @@ -28,285 +26,7 @@ async function writeFixture(prefix: string, records: unknown[]): Promise return filePath } -describe('readNativeChatTranscript (claude)', () => { - it('decodes OpenClaude with the Claude transcript format', async () => { - const filePath = await writeFixture('orca-native-chat-openclaude-', [ - { - type: 'assistant', - uuid: 'openclaude-assistant', - message: { role: 'assistant', content: [{ type: 'text', text: 'hello' }] } - } - ]) - - await expect( - readNativeChatTranscript('openclaude', 'session', { filePath }) - ).resolves.toMatchObject({ messages: [{ id: 'openclaude-assistant' }] }) - }) - - it('returns ordered user/assistant/tool messages with no 5-message cap', async () => { - const records: unknown[] = [] - for (let turn = 0; turn < 4; turn++) { - records.push({ - type: 'user', - uuid: `u-${turn}`, - timestamp: `2026-06-01T10:0${turn}:00.000Z`, - message: { role: 'user', content: `Prompt **${turn}**` } - }) - records.push({ - type: 'assistant', - uuid: `a-${turn}`, - timestamp: `2026-06-01T10:0${turn}:30.000Z`, - message: { role: 'assistant', content: [{ type: 'text', text: `Reply _${turn}_` }] } - }) - } - records.push({ - type: 'assistant', - uuid: 'a-tool', - timestamp: '2026-06-01T10:05:00.000Z', - message: { - role: 'assistant', - content: [{ type: 'tool_use', id: 'tool-call-1', name: 'Bash', input: { command: 'ls' } }] - } - }) - records.push({ - type: 'user', - uuid: 'u-toolresult', - timestamp: '2026-06-01T10:05:01.000Z', - message: { - role: 'user', - content: [{ type: 'tool_result', content: 'file-a\nfile-b', is_error: false }] - } - }) - - const filePath = await writeFixture('orca-native-chat-claude-', records) - const result = await readNativeChatTranscript('claude', 'sess', { filePath }) - expect('messages' in result).toBe(true) - if (!('messages' in result)) { - return - } - - expect(result.messages.length).toBe(10) - expect(result.messages.length).toBeGreaterThan(5) - expect(result.messages[0]).toMatchObject({ role: 'user', source: 'transcript' }) - expect(result.messages[0].blocks[0]).toEqual({ type: 'text', text: 'Prompt **0**' }) - expect(result.messages[1].blocks[0]).toEqual({ type: 'text', text: 'Reply _0_' }) - - const toolCall = result.messages.find((m) => m.blocks[0]?.type === 'tool-call') - expect(toolCall?.blocks[0]).toEqual({ - type: 'tool-call', - name: 'Bash', - input: { command: 'ls' }, - callId: 'tool-call-1' - }) - - const toolResult = result.messages.at(-1) - expect(toolResult?.role).toBe('tool') - expect(toolResult?.blocks[0]).toEqual({ type: 'tool-result', output: 'file-a\nfile-b' }) - }) - - it('drops structurally marked injected user turns but keeps their tool results', async () => { - const filePath = await writeFixture('orca-native-chat-claude-meta-', [ - { - type: 'user', - uuid: 'u-real', - timestamp: '2026-06-01T10:00:00.000Z', - message: { role: 'user', content: 'fix the login bug' } - }, - { - type: 'user', - uuid: 'u-meta', - isMeta: true, - timestamp: '2026-06-01T10:00:01.000Z', - message: { - role: 'user', - content: 'Another Claude session sent a message:\nhi' - } - }, - { - type: 'user', - uuid: 'u-compact', - isCompactSummary: true, - timestamp: '2026-06-01T10:00:02.000Z', - message: { - role: 'user', - content: 'This session is being continued from a previous conversation.' - } - }, - { - type: 'user', - uuid: 'u-meta-toolresult', - isMeta: true, - timestamp: '2026-06-01T10:00:03.000Z', - message: { - role: 'user', - content: [{ type: 'tool_result', content: 'ok', is_error: false }] - } - }, - { - type: 'user', - uuid: 'u-meta-mixed', - isMeta: true, - timestamp: '2026-06-01T10:00:04.000Z', - message: { - role: 'user', - content: [ - { type: 'text', text: 'hidden machinery' }, - { type: 'tool_result', content: 'mixed result', is_error: false } - ] - } - } - ]) - const result = await readNativeChatTranscript('claude', 'sess', { filePath }) - if (!('messages' in result)) { - throw new Error('expected messages') - } - expect(result.messages.map((m) => m.id)).toEqual([ - 'u-real', - 'u-meta-toolresult', - 'u-meta-mixed' - ]) - expect(result.messages[1].role).toBe('tool') - expect(result.messages[2]).toMatchObject({ - role: 'tool', - blocks: [{ type: 'tool-result', output: 'mixed result' }] - }) - }) - - it('marks thinking-only assistant content as a reasoning surface', async () => { - const filePath = await writeFixture('orca-native-chat-claude-think-', [ - { - type: 'assistant', - uuid: 'a-think', - timestamp: '2026-06-01T10:00:00.000Z', - message: { role: 'assistant', content: [{ type: 'thinking', thinking: 'pondering' }] } - } - ]) - const result = await readNativeChatTranscript('claude', 'sess', { filePath }) - if (!('messages' in result)) { - throw new Error('expected messages') - } - expect(result.messages[0]).toMatchObject({ - role: 'reasoning', - blocks: [{ type: 'text', text: 'pondering' }] - }) - }) -}) - -describe('readNativeChatTranscript (codex)', () => { - it('maps tool calls and results to tool-call/tool-result blocks', async () => { - const filePath = await writeFixture('orca-native-chat-codex-', [ - { - type: 'session_meta', - timestamp: '2026-06-01T10:00:00.000Z', - payload: { id: 'codex-sess', cwd: '/repo' } - }, - { - type: 'response_item', - timestamp: '2026-06-01T10:00:01.000Z', - payload: { - type: 'message', - role: 'user', - content: [{ type: 'text', text: 'Run the build' }] - } - }, - { - type: 'response_item', - timestamp: '2026-06-01T10:00:02.000Z', - payload: { type: 'reasoning', summary: [{ type: 'summary_text', text: 'I will run it' }] } - }, - { - type: 'response_item', - timestamp: '2026-06-01T10:00:03.000Z', - payload: { - type: 'function_call', - name: 'shell', - arguments: '{"command":["bash","-lc","make"]}' - } - }, - { - type: 'response_item', - timestamp: '2026-06-01T10:00:04.000Z', - payload: { - type: 'function_call_output', - output: { content: 'build ok', success: true } - } - }, - { - type: 'response_item', - timestamp: '2026-06-01T10:00:05.000Z', - payload: { type: 'message', role: 'assistant', content: [{ type: 'text', text: 'Done.' }] } - } - ]) - - const result = await readNativeChatTranscript('codex', 'codex-sess', { filePath }) - if (!('messages' in result)) { - throw new Error(`expected messages, got error`) - } - - const roles = result.messages.map((m) => m.role) - expect(roles).toEqual(['user', 'reasoning', 'assistant', 'tool', 'assistant']) - - const call = result.messages.find((m) => m.blocks[0]?.type === 'tool-call') - expect(call?.blocks[0]).toEqual({ - type: 'tool-call', - name: 'shell', - input: '{"command":["bash","-lc","make"]}' - }) - - const toolResult = result.messages.find((m) => m.blocks[0]?.type === 'tool-result') - expect(toolResult?.blocks[0]).toEqual({ type: 'tool-result', output: 'build ok' }) - - const reasoning = result.messages.find((m) => m.role === 'reasoning') - expect(reasoning?.blocks[0]).toEqual({ type: 'text', text: 'I will run it' }) - }) -}) - -describe('readNativeChatTranscript (errors)', () => { - it('marks an ENOENT on a directly-passed path as notFound (vanished after resolve)', async () => { - const result = await readNativeChatTranscript('claude', 'sess', { - filePath: join(tmpdir(), 'orca-native-chat-does-not-exist.jsonl') - }) - expect('error' in result).toBe(true) - if ('error' in result) { - expect(result.notFound).toBe(true) - } - }) - - it('returns a real read error (no notFound) when the path exists but is unreadable', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-unreadable-')) - tempRoots.push(root) - const result = await readNativeChatTranscript('claude', 'sess', { filePath: root }) - expect('error' in result).toBe(true) - if ('error' in result) { - expect(result.notFound).toBeUndefined() - } - }) - - it('marks an unresolved session as notFound so callers know to retry', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-noresolve-')) - tempRoots.push(root) - const result = await readNativeChatTranscript('claude', 'missing', { - claudeProjectsDir: join(root, 'empty') - }) - expect('error' in result).toBe(true) - if ('error' in result) { - expect(result.notFound).toBe(true) - } - }) -}) - describe('readNativeChatTranscriptTailFile', () => { - it('keeps a missing tail retry-worthy for the live-session seed', async () => { - const result = await readNativeChatTranscriptTail({ - agent: 'claude', - sessionId: 'sess', - filePath: join(tmpdir(), 'orca-native-chat-tail-does-not-exist.jsonl'), - limit: 40 - }) - - expect(result).toMatchObject({ notFound: true }) - }) - it('windows to nothing for a non-positive limit instead of the whole tail', async () => { const decode = nativeChatLineDecoderForAgent('claude')! const filePath = await writeFixture('orca-native-chat-tail-limit-', [ diff --git a/src/main/native-chat/transcript-stream-lines.test.ts b/src/main/native-chat/transcript-stream-lines.test.ts index cd2bbbb4c56..a19de6c2a3b 100644 --- a/src/main/native-chat/transcript-stream-lines.test.ts +++ b/src/main/native-chat/transcript-stream-lines.test.ts @@ -1,205 +1,6 @@ import { Readable } from 'node:stream' -import { describe, expect, it, vi } from 'vitest' -import { decodeTranscriptStream, splitTranscriptStreamLines } from './transcript-stream-lines' - -const decode = (line: string, id: string) => ({ - id, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: line }], - timestamp: null, - source: 'transcript' as const -}) - -describe('decodeTranscriptStream', () => { - it('accepts the exact source limit with split UTF-8 bytes and preserves order', async () => { - const bytes = Buffer.from('é\n😀\n') - const result = await decodeTranscriptStream( - Readable.from([bytes.subarray(0, 1), bytes.subarray(1, 5), bytes.subarray(5)]), - '/chat.jsonl', - 0, - decode, - true, - bytes.length - ) - expect(result.messages.map((message) => message.blocks[0])).toEqual([ - { type: 'text', text: 'é' }, - { type: 'text', text: '😀' } - ]) - }) - - it.each([Buffer.from('é'), 'é', Buffer.from([0xff, 0xff])])( - 'counts source bytes before decoding an oversized chunk %j', - async (chunk) => { - const stream = Readable.from([chunk]) - const trackedDecode = vi.fn(decode) - await expect( - decodeTranscriptStream(stream, '/chat.jsonl', 0, trackedDecode, true, 1) - ).rejects.toThrow('exceeds 1 byte limit') - expect(trackedDecode).not.toHaveBeenCalled() - expect(stream.destroyed).toBe(true) - } - ) - - it.each([true, false])('preserves chunked record offsets with trailing=%s', async (trailing) => { - const first = `${'long record '.repeat(10_000)}😀` - const prefix = `\r\n${first}\r\n\n` - const partial = 'unfinished é' - const bytes = Buffer.from(prefix + partial) - const chunks: Buffer[] = [] - for (let offset = 0; offset < bytes.length; offset += 1024) { - chunks.push(bytes.subarray(offset, offset + 1024)) - } - const result = await decodeTranscriptStream( - Readable.from(chunks), - '/chat.jsonl', - 100, - decode, - trailing - ) - expect(result.messages.map((message) => message.blocks[0])).toEqual([ - { type: 'text', text: first }, - ...(trailing ? [{ type: 'text', text: partial }] : []) - ]) - expect(result.messages[0]?.id).toBe('/chat.jsonl:0000000000000102') - expect(result.consumedBytes).toBe(trailing ? bytes.length : Buffer.byteLength(prefix)) - }) - - it('searches each chunk once when a line spans many chunks', async () => { - const input = `${'x'.repeat(256 * 1024)}\n` - const chunks: string[] = [] - for (let offset = 0; offset < input.length; offset += 4096) { - chunks.push(input.slice(offset, offset + 4096)) - } - let searchedCharacters = 0 - const originalIndexOf = String.prototype.indexOf - const spy = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function ( - this: string, - search: string, - position?: number - ) { - const found = originalIndexOf.call(this, search, position) - if (search === '\n') { - searchedCharacters += (found < 0 ? this.length : found + 1) - (position ?? 0) - } - return found - }) - let result - try { - result = await decodeTranscriptStream(Readable.from(chunks), '/chat.jsonl', 0, decode, true) - } finally { - spy.mockRestore() - } - expect(result.messages[0]?.blocks[0]).toEqual({ type: 'text', text: input.slice(0, -1) }) - expect(result.consumedBytes).toBe(input.length) - expect(searchedCharacters).toBeLessThanOrEqual(input.length * 2) - }) - - it('joins split UTF-16 surrogate pairs before deriving byte offsets', async () => { - const chunks = ['a\ud83d', '\ude00', '\r', '\n\n', 'tail\r'] - const actual = await decodeTranscriptStream( - Readable.from(chunks), - '/chat.jsonl', - 123, - decode, - true - ) - const expected = await decodeTranscriptStream( - Readable.from([chunks.join('')]), - '/chat.jsonl', - 123, - decode, - true - ) - expect(actual).toEqual(expected) - expect(actual.messages).toHaveLength(2) - expect(actual.consumedBytes).toBe(Buffer.byteLength(chunks.join(''))) - }) - - it.each([false, true])( - 'preserves decoder tail handling with includeTrailingLine=%s', - async (includeTrailingLine) => { - const chunks = [Buffer.from('line\r\n'), Buffer.from([0xf0, 0x9f])] - const actual = await decodeTranscriptStream( - Readable.from(chunks), - '/chat.jsonl', - 20, - decode, - includeTrailingLine - ) - expect(actual.messages.map((message) => message.blocks[0])).toEqual([ - { type: 'text', text: 'line' }, - ...(includeTrailingLine ? [{ type: 'text', text: '\ufffd' }] : []) - ]) - expect(actual.consumedBytes).toBe(6 + (includeTrailingLine ? 3 : 0)) - } - ) - - it('closes the source when a decoder throws', async () => { - const error = new Error('decode failed') - const stream = Readable.from(['partial', ' line\nsecond\n']) - const failingDecode = vi.fn(() => { - throw error - }) - await expect( - decodeTranscriptStream(stream, '/chat.jsonl', 0, failingDecode, true) - ).rejects.toBe(error) - expect(failingDecode).toHaveBeenCalledOnce() - expect(stream.destroyed).toBe(true) - }) - - it('uses identical absolute byte ids for full and incremental reads', async () => { - const prefix = '{"first":"é"}\r\n' - const appended = '{"second":true}\n' - const full = await decodeTranscriptStream( - Readable.from([prefix + appended]), - '/chat.jsonl', - 0, - decode, - true - ) - const incremental = await decodeTranscriptStream( - Readable.from([appended]), - '/chat.jsonl', - Buffer.byteLength(prefix, 'utf8'), - decode, - false - ) - - expect(incremental.messages[0]?.id).toBe(full.messages[1]?.id) - }) - - it('keeps a codepoint split across two Buffer chunks intact', async () => { - const line = `{"text":"😀é中"}\n` - const bytes = Buffer.from(line, 'utf8') - // Split inside the emoji's 4-byte sequence, as a 1 MiB gated chunk boundary does. - const split = Buffer.from('{"text":"', 'utf8').length + 2 - const result = await decodeTranscriptStream( - Readable.from([bytes.subarray(0, split), bytes.subarray(split)]), - '/chat.jsonl', - 0, - decode, - false - ) - - expect(result.messages[0]?.blocks[0]).toEqual({ type: 'text', text: line.slice(0, -1) }) - expect(result.consumedBytes).toBe(bytes.length) - }) - - it('does not consume a partial trailing JSONL record', async () => { - const complete = '{"first":true}\n' - const partial = '{"second"' - const result = await decodeTranscriptStream( - Readable.from([complete + partial]), - '/chat.jsonl', - 0, - decode, - false - ) - - expect(result.messages).toHaveLength(1) - expect(result.consumedBytes).toBe(Buffer.byteLength(complete, 'utf8')) - }) -}) +import { describe, expect, it } from 'vitest' +import { splitTranscriptStreamLines } from './transcript-stream-lines' describe('bounded transcript records', () => { async function collect(chunks: (Buffer | string)[], limit: number) { @@ -210,11 +11,6 @@ describe('bounded transcript records', () => { return records } - it.each(['', '\n', '\nnext\n'])('rejects an oversized record ending in %j', async (ending) => { - await expect(collect(['1234', `5${ending}`], 4)).rejects.toThrow('record exceeds 4 byte limit') - await expect(collect([`12345${ending}`], 4)).rejects.toThrow('record exceeds 4 byte limit') - }) - it('resets the byte budget per record and accepts the exact limit', async () => { expect(await collect(['1234\n123', '4\n1234'], 4)).toEqual(['1234', '1234', '1234']) }) diff --git a/src/main/native-chat/transcript-tool-result-identity.test.ts b/src/main/native-chat/transcript-tool-result-identity.test.ts deleted file mode 100644 index 4bda3f2143c..00000000000 --- a/src/main/native-chat/transcript-tool-result-identity.test.ts +++ /dev/null @@ -1,289 +0,0 @@ -import advisorCapture from '../../shared/__fixtures__/claude-server-tools-2.1.318.json' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { foldToolMessages } from '../../shared/native-chat/tools/native-chat-tool-fold' -import { pairToolBlocks } from '../../shared/native-chat/tools/native-chat-tool-pairs' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' -import { decodeClaudeTurnLifecycle } from './transcript-turn-lifecycle' -import { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude' -import { decodeCodexTranscriptLine } from './transcript-line-decoders-codex' -import { readNativeChatTranscriptTailFile } from './transcript-tail-reader' - -const roots: string[] = [] - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -async function load(records: unknown[], agent: 'claude' | 'codex'): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-transcript-result-identity-')) - roots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, `${records.map((record) => JSON.stringify(record)).join('\n')}\n`) - const page = await readNativeChatTranscriptTailFile( - filePath, - 100, - agent === 'claude' ? decodeClaudeTranscriptLine : decodeCodexTranscriptLine - ) - expect(page.hasMore).toBe(false) - return page.messages -} - -function claudeRecord(id: string, role: 'assistant' | 'user', content: unknown): unknown { - return { - type: role, - uuid: id, - timestamp: '2026-10-09T10:00:00.000Z', - message: { role, content } - } -} - -function codexRecord(id: string, payload: Record, wrapped = true): unknown { - return { - timestamp: '2026-10-09T10:00:00.000Z', - ...(wrapped ? { type: 'response_item', payload: { id, ...payload } } : { id, ...payload }) - } -} - -function claudeCalls(): unknown[] { - return [ - claudeRecord('calls', 'assistant', [ - { type: 'tool_use', id: 'spawn', name: 'spawn_agent', input: { task: 'Inspect' } }, - { type: 'tool_use', id: 'first', name: 'Bash', input: { command: 'echo first' } }, - { type: 'tool_use', id: 'second', name: 'Bash', input: { command: 'echo second' } } - ]) - ] -} - -function codexCalls(type: 'function_call' | 'custom_tool_call', wrapped: boolean): unknown[] { - return ['spawn', 'first', 'second'].map((callId) => - codexRecord( - `call-${callId}`, - { - type, - call_id: callId, - name: callId === 'spawn' ? 'spawn_agent' : 'exec_command', - arguments: JSON.stringify({ command: `echo ${callId}` }) - }, - wrapped - ) - ) -} - -function pairsFrom(messages: NativeChatMessage[]) { - return foldToolMessages(messages).flatMap((message) => pairToolBlocks(message.blocks)) -} - -describe('provider transcript result identity', () => { - it('replays captured server calls and results through the normal transcript cards', async () => { - const messages = await load(advisorCapture, 'claude') - expect(pairsFrom(messages)).toMatchObject([ - { - call: { callId: 'recorded-id-2', name: 'advisor', input: {} }, - result: { - callId: 'recorded-id-2', - output: - '{"type":"advisor_redacted_result","encrypted_content":"redacted-advisor-content"}' - } - } - ]) - const legacy = claudeRecord('legacy', 'assistant', [ - { type: 'text', text: 'done' }, - { type: 'server_tool_use', id: 'server', name: 'advisor', input: {} }, - { type: 'advisor_tool_result', tool_use_id: 'server', content: 'advice' } - ]) - expect(decodeClaudeTurnLifecycle(JSON.stringify(legacy), 'fallback')?.state).toBe('completed') - const failed = await load( - [ - claudeRecord('failed', 'assistant', [ - { - type: 'advisor_tool_result', - tool_use_id: 'server', - content: { type: 'advisor_tool_result_error', error_code: 'unavailable' } - } - ]) - ], - 'claude' - ) - expect(failed[0]?.blocks).toEqual([ - { - type: 'tool-result', - callId: 'server', - isError: true, - output: '{"type":"advisor_tool_result_error","error_code":"unavailable"}' - } - ]) - }) - - it('keeps Claude reverse completions attached to their calls past a silent spawn', async () => { - const messages = await load( - [ - ...claudeCalls(), - claudeRecord('results', 'user', [ - { type: 'tool_result', tool_use_id: 'second', content: 'SECOND', is_error: true }, - { type: 'tool_result', tool_use_id: 'first', content: ['FIRST', { text: 'detail' }] } - ]) - ], - 'claude' - ) - expect(messages.at(-1)?.blocks).toEqual([ - { type: 'tool-result', callId: 'second', output: 'SECOND', isError: true }, - { type: 'tool-result', callId: 'first', output: 'FIRST\ndetail' } - ]) - expect(pairsFrom(messages)).toMatchObject([ - { call: { callId: 'spawn' } }, - { call: { callId: 'first' }, result: { callId: 'first', output: 'FIRST\ndetail' } }, - { call: { callId: 'second' }, result: { callId: 'second', output: 'SECOND', isError: true } } - ]) - expect(pairsFrom(messages)[0]?.result).toBeUndefined() - }) - - it.each([ - ['function_call', 'function_call_output', true], - ['custom_tool_call', 'custom_tool_call_output', true], - ['function_call', 'function_call_output', false], - ['custom_tool_call', 'custom_tool_call_output', false] - ] as const)( - 'keeps Codex %s/%s results named (wrapped=%s)', - async (callType, outputType, wrapped) => { - const messages = await load( - [ - ...codexCalls(callType, wrapped), - codexRecord( - 'result-second', - { - type: outputType, - call_id: 'second', - output: { content: ['SECOND'], success: false } - }, - wrapped - ), - codexRecord( - 'result-first', - { type: outputType, call_id: 'first', output: { output: 'FIRST' } }, - wrapped - ) - ], - 'codex' - ) - expect(messages.slice(-2).map((message) => message.blocks[0])).toEqual([ - { type: 'tool-result', callId: 'second', output: 'SECOND', isError: true }, - { type: 'tool-result', callId: 'first', output: 'FIRST' } - ]) - expect(pairsFrom(messages)).toMatchObject([ - { call: { callId: 'spawn' } }, - { call: { callId: 'first' }, result: { callId: 'first', output: 'FIRST' } }, - { - call: { callId: 'second' }, - result: { callId: 'second', output: 'SECOND', isError: true } - } - ]) - expect(pairsFrom(messages)[0]?.result).toBeUndefined() - } - ) - - it('preserves the result identity together with Claude resolved edit ranges and record metadata', async () => { - const messages = await load( - [ - { - type: 'user', - uuid: 'edit-result', - parentUuid: 'edit-call', - timestamp: '2026-10-09T10:01:00.000Z', - message: { - role: 'user', - content: [ - { type: 'tool_result', tool_use_id: 'edit', content: 'edited', is_error: true } - ] - }, - toolUseResult: { - filePath: 'src/example.ts', - structuredPatch: [ - { oldStart: 10, oldLines: 1, newStart: 10, newLines: 1, lines: ['-old', '+new'] } - ] - } - } - ], - 'claude' - ) - expect(messages).toEqual([ - { - id: 'edit-result', - parentId: 'edit-call', - role: 'tool', - timestamp: Date.parse('2026-10-09T10:01:00.000Z'), - source: 'transcript', - blocks: [ - { - type: 'tool-result', - callId: 'edit', - output: 'edited', - isError: true, - editPatch: { - filePath: 'src/example.ts', - hunks: [ - { oldStart: 10, oldLines: 1, newStart: 10, newLines: 1, lines: ['-old', '+new'] } - ] - } - } - ] - } - ]) - }) - - it.each(['claude', 'codex'] as const)( - 'keeps historical %s results without IDs positional', - async (agent) => { - const records = - agent === 'claude' - ? [ - claudeRecord('calls', 'assistant', [ - { type: 'tool_use', id: 'first', name: 'Bash', input: {} }, - { type: 'tool_use', id: 'second', name: 'Bash', input: {} } - ]), - claudeRecord('results', 'user', [ - { type: 'tool_result', content: 'FIRST' }, - { type: 'tool_result', content: 'SECOND' } - ]) - ] - : [ - ...codexCalls('function_call', true).slice(1), - codexRecord('first-result', { type: 'function_call_output', output: 'FIRST' }), - codexRecord('second-result', { type: 'function_call_output', output: 'SECOND' }) - ] - const messages = await load(records, agent) - expect(pairsFrom(messages)).toMatchObject([ - { call: { callId: 'first' }, result: { output: 'FIRST' } }, - { call: { callId: 'second' }, result: { output: 'SECOND' } } - ]) - for (const message of messages) { - for (const block of message.blocks) { - if (block.type === 'tool-result') { - expect(Object.hasOwn(block, 'callId')).toBe(false) - } - } - } - } - ) - - it.each([null, '', ' ', 42, {}])('omits invalid provider result IDs (%s)', (callId) => { - const claude = decodeClaudeTranscriptLine( - JSON.stringify( - claudeRecord('result', 'user', [ - { type: 'tool_result', tool_use_id: callId, content: 'done' } - ]) - ), - 'fallback' - ) - const codex = decodeCodexTranscriptLine( - JSON.stringify( - codexRecord('result', { type: 'function_call_output', call_id: callId, output: 'done' }) - ), - 'fallback' - ) - expect(claude?.blocks).toEqual([{ type: 'tool-result', output: 'done' }]) - expect(codex?.blocks).toEqual([{ type: 'tool-result', output: 'done' }]) - }) -}) diff --git a/src/main/native-chat/transcript-turn-lifecycle.test.ts b/src/main/native-chat/transcript-turn-lifecycle.test.ts index dd70bc12009..49205824955 100644 --- a/src/main/native-chat/transcript-turn-lifecycle.test.ts +++ b/src/main/native-chat/transcript-turn-lifecycle.test.ts @@ -1,282 +1,7 @@ import { describe, expect, it } from 'vitest' -import { - decodeClaudeTurnLifecycle, - decodeCodexTurnLifecycle, - nativeChatTurnLifecycleDecoderForAgent -} from './transcript-turn-lifecycle' +import { decodeClaudeTurnLifecycle } from './transcript-turn-lifecycle' describe('native chat transcript turn lifecycle', () => { - it('exposes a lifecycle decoder only for transcript formats with explicit boundaries', () => { - expect(nativeChatTurnLifecycleDecoderForAgent('claude')).not.toBeNull() - expect(nativeChatTurnLifecycleDecoderForAgent('openclaude')).not.toBeNull() - expect(nativeChatTurnLifecycleDecoderForAgent('codex')).not.toBeNull() - expect(nativeChatTurnLifecycleDecoderForAgent('grok')).toBeNull() - }) - - it('decodes Codex task boundaries with the provider turn id', () => { - expect( - decodeCodexTurnLifecycle( - JSON.stringify({ - timestamp: '2026-07-16T23:40:14.001Z', - type: 'event_msg', - payload: { type: 'task_started', turn_id: 'turn-1' } - }), - 'fallback' - ) - ).toEqual({ - state: 'working', - turnId: 'turn-1', - timestamp: Date.parse('2026-07-16T23:40:14.001Z') - }) - - expect( - decodeCodexTurnLifecycle( - JSON.stringify({ - timestamp: '2026-07-16T23:45:37.608Z', - type: 'event_msg', - payload: { type: 'task_complete', turn_id: 'turn-1' } - }), - 'fallback' - ) - ).toEqual({ - state: 'completed', - turnId: 'turn-1', - timestamp: Date.parse('2026-07-16T23:45:37.608Z') - }) - - expect( - decodeCodexTurnLifecycle( - JSON.stringify({ - timestamp: '2026-07-16T23:46:01.000Z', - type: 'event_msg', - payload: { type: 'turn_aborted', reason: 'interrupted', turn_id: 'turn-2' } - }), - 'fallback' - ) - ).toEqual({ - state: 'interrupted', - turnId: 'turn-2', - timestamp: Date.parse('2026-07-16T23:46:01.000Z') - }) - }) - - it('does not mistake a Codex assistant message for completion', () => { - expect( - decodeCodexTurnLifecycle( - JSON.stringify({ - timestamp: '2026-07-16T23:45:37.472Z', - type: 'event_msg', - payload: { type: 'agent_message', message: 'final-looking prose' } - }), - 'fallback' - ) - ).toBeNull() - }) - - it('uses Claude terminal stop_reasons and excludes tool-result user rows', () => { - for (const stopReason of ['end_turn', 'max_tokens', 'stop_sequence', 'refusal'] as const) { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: `assistant-${stopReason}`, - timestamp: '2026-07-16T23:45:37.608Z', - message: { role: 'assistant', stop_reason: stopReason, content: [] } - }), - 'fallback' - ) - ).toEqual({ - state: 'completed', - turnId: `assistant-${stopReason}`, - timestamp: Date.parse('2026-07-16T23:45:37.608Z') - }) - } - - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'tool-result-1', - timestamp: '2026-07-16T23:45:38.000Z', - message: { - role: 'user', - content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'ok' }] - } - }), - 'fallback' - ) - ).toBeNull() - }) - - it('does not treat Claude mid-turn tool_use assistant rows as completed', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: 'assistant-tool', - timestamp: '2026-07-16T23:45:37.608Z', - message: { - role: 'assistant', - stop_reason: 'tool_use', - content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] - } - }), - 'fallback' - ) - ).toBeNull() - }) - - it('treats Claude assistant rows with omitted stop_reason and content as completed', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: 'assistant-null-stop', - timestamp: '2026-07-16T23:45:37.608Z', - message: { - role: 'assistant', - stop_reason: null, - content: [{ type: 'text', text: 'final answer' }] - } - }), - 'fallback' - ) - ).toEqual({ - state: 'completed', - turnId: 'assistant-null-stop', - timestamp: Date.parse('2026-07-16T23:45:37.608Z') - }) - - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: 'assistant-missing-stop', - timestamp: '2026-07-16T23:45:37.608Z', - message: { - role: 'assistant', - content: [{ type: 'text', text: 'final answer' }] - } - }), - 'fallback' - ) - ).toEqual({ - state: 'completed', - turnId: 'assistant-missing-stop', - timestamp: Date.parse('2026-07-16T23:45:37.608Z') - }) - }) - - it('does not complete a Claude assistant row that omits stop_reason but carries a tool_use block', () => { - for (const stopReason of [null, undefined] as const) { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: `assistant-pretool-${stopReason}`, - timestamp: '2026-07-16T23:45:37.608Z', - message: { - role: 'assistant', - ...(stopReason === null ? { stop_reason: null } : {}), - content: [ - { type: 'text', text: 'let me check' }, - { type: 'tool_use', id: 't1', name: 'Bash', input: {} } - ] - } - }), - 'fallback' - ) - ).toBeNull() - } - }) - - it('does not complete Claude assistant rows with omitted stop_reason and no content', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'assistant', - uuid: 'assistant-empty', - timestamp: '2026-07-16T23:45:37.608Z', - message: { role: 'assistant', stop_reason: null, content: [] } - }), - 'fallback' - ) - ).toBeNull() - }) - - it('does not treat harness noise user rows as a new working generation', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'task-note-1', - timestamp: '2026-07-16T23:46:10.000Z', - message: { - role: 'user', - content: [ - { - type: 'text', - text: 'background task finished' - } - ] - } - }), - 'fallback' - ) - ).toBeNull() - - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'reminder-1', - timestamp: '2026-07-16T23:46:11.000Z', - message: { - role: 'user', - content: [{ type: 'text', text: 'continue' }] - } - }), - 'fallback' - ) - ).toBeNull() - }) - - it.each([ - ' git status', - [{ type: 'text', text: 'ls' }] - ])('does not treat a `!` shell command as a new working generation', (content) => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'bash-1', - timestamp: '2026-07-16T23:46:12.000Z', - message: { role: 'user', content } - }), - 'fallback' - ) - ).toBeNull() - }) - - it('does not treat a prompt absorbed mid-turn as a new generation', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'attachment', - uuid: 'queued-1', - timestamp: '2026-07-16T23:46:13.000Z', - attachment: { - type: 'queued_command', - prompt: 'also check the config', - commandMode: 'prompt', - origin: { kind: 'human' } - } - }), - 'fallback' - ) - ).toBeNull() - }) - it('excludes Claude tool-result rows that also carry text sidecars', () => { expect( decodeClaudeTurnLifecycle( @@ -296,44 +21,4 @@ describe('native chat transcript turn lifecycle', () => { ) ).toBeNull() }) - - it('treats a real Claude user row as the next working generation', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'user-2', - timestamp: '2026-07-16T23:46:00.000Z', - message: { role: 'user', content: 'next task' } - }), - 'fallback' - ) - ).toEqual({ - state: 'working', - turnId: 'user-2', - timestamp: Date.parse('2026-07-16T23:46:00.000Z') - }) - }) - - it('treats Claude interruptedMessageId as terminal instead of a user generation', () => { - expect( - decodeClaudeTurnLifecycle( - JSON.stringify({ - type: 'user', - uuid: 'interrupt-row', - interruptedMessageId: 'assistant-request-1', - timestamp: '2026-07-16T23:46:01.000Z', - message: { - role: 'user', - content: [{ type: 'text', text: '[Request interrupted by user]' }] - } - }), - 'fallback' - ) - ).toEqual({ - state: 'interrupted', - turnId: 'assistant-request-1', - timestamp: Date.parse('2026-07-16T23:46:01.000Z') - }) - }) }) diff --git a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts deleted file mode 100644 index 575eb1450d3..00000000000 --- a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFsPromisesModule from 'node:fs/promises' -import type * as WslRunningPathFilterModule from '../wsl/filesystem/wsl-running-path-filter' -import { parseWslUncPath } from '../../shared/wsl-paths' - -const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' -const ROLLOUT_LINUX = - '/home/ada/.local/share/orca/codex-runtime-home/home/sessions/2026/07/24/rollout-wsl.jsonl' -const ROLLOUT_UNC = - '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\24\\rollout-wsl.jsonl' - -const mocks = vi.hoisted(() => ({ - filterPathsToRunningWslDistrosAsync: vi.fn(), - getWslHomeAsync: vi.fn(), - install: vi.fn(), - listRunningWslDistrosAsync: vi.fn(), - resolve: vi.fn() -})) - -vi.mock('./session-file-resolver', () => ({ - resolveSessionFilePath: mocks.resolve -})) -vi.mock('./transcript-watch-engine', () => ({ - getActiveNativeChatWatcherCount: vi.fn(() => 0), - installTranscriptWatcher: mocks.install -})) -// These cases cover root and path policy; the E9 gate has its own suite. -vi.mock('./wsl-transcript-running-admission', () => ({ admitWslTranscriptPath: async () => {} })) -vi.mock('../wsl/discovery/wsl-home-unless-stopped', async () => { - const wsl = await import('../wsl/discovery/distro-catalog') - return { - wslHomeUnlessStopped: (distro: string) => wsl.getWslHomeAsync(distro), - listRunningWslHomeDirsUnlessStopped: () => wsl.listRunningWslHomeDirsAsync() - } -}) -vi.mock('../wsl/discovery/distro-catalog', () => ({ - getWslHomeAsync: mocks.getWslHomeAsync, - listRunningWslDistrosAsync: mocks.listRunningWslDistrosAsync, - listRunningWslHomeDirsAsync: vi.fn(async () => [UBUNTU_HOME]) -})) -vi.mock('../wsl/filesystem/wsl-running-path-filter', async (importOriginal) => ({ - ...(await importOriginal()), - filterPathsToRunningWslDistrosAsync: mocks.filterPathsToRunningWslDistrosAsync -})) -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - access: async (path: string) => { - if (path !== ROLLOUT_UNC) { - await actual.access(path) - } - } - } -}) - -import { resetHostReadableTranscriptPathCacheForTests } from './host-readable-transcript-path' -import { subscribeNativeChatTranscript } from './transcript-watch' -import { WslTranscriptFsError } from './wsl-transcript-fs-gate' -import { - resetWslTranscriptRunningObserverForTests, - WSL_TRANSCRIPT_RUNNING_OBSERVATION_MS -} from './wsl-transcript-running-observer' - -const realPlatform = process.platform - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -describe('exact hook path install on a Windows host with WSL (#10326)', () => { - beforeEach(() => { - vi.useFakeTimers() - resetHostReadableTranscriptPathCacheForTests() - mocks.filterPathsToRunningWslDistrosAsync - .mockReset() - .mockImplementation(async (paths: readonly string[]) => { - const running = new Set( - (await mocks.listRunningWslDistrosAsync()).map((distro) => distro.toLowerCase()) - ) - return paths.filter((path) => { - const parsed = parseWslUncPath(path) - return !parsed || running.has(parsed.distro.toLowerCase()) - }) - }) - mocks.getWslHomeAsync.mockReset().mockResolvedValue(UBUNTU_HOME) - mocks.install.mockReset().mockReturnValue(null) - mocks.listRunningWslDistrosAsync.mockReset().mockResolvedValue(['Ubuntu']) - mocks.resolve.mockReset().mockResolvedValue(null) - }) - - afterEach(() => { - resetWslTranscriptRunningObserverForTests() - vi.useRealTimers() - setPlatform(realPlatform) - }) - - it('installs the watcher on the WSL UNC twin of the guest transcript path', async () => { - setPlatform('win32') - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_LINUX, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.install).toHaveBeenCalledWith( - ROLLOUT_UNC, - expect.anything(), - expect.anything(), - expect.any(AbortSignal) - ) - expect(mocks.install.mock.calls.every(([path]) => path !== ROLLOUT_LINUX)).toBe(true) - subscription.unsubscribe() - }) - - it('validates an exact UNC path without probing distro homes', async () => { - setPlatform('win32') - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.install).toHaveBeenCalledWith( - ROLLOUT_UNC, - expect.anything(), - expect.anything(), - expect.any(AbortSignal) - ) - expect(mocks.getWslHomeAsync).not.toHaveBeenCalled() - subscription.unsubscribe() - }) - - it('does not run broad id fallback for an unresolved exact WSL path', async () => { - setPlatform('win32') - mocks.listRunningWslDistrosAsync.mockResolvedValue([]) - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - expect(mocks.resolve).toHaveBeenCalledTimes(1) - mocks.resolve.mockClear() - await vi.advanceTimersByTimeAsync(2_100 + 2 * WSL_TRANSCRIPT_RUNNING_OBSERVATION_MS) - - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(3) - expect(mocks.resolve).not.toHaveBeenCalled() - expect(mocks.getWslHomeAsync).not.toHaveBeenCalled() - subscription.unsubscribe() - }) - - it('revalidates an absent UNC transcript before retrying after the distro stops', async () => { - setPlatform('win32') - mocks.listRunningWslDistrosAsync.mockResolvedValueOnce(['Ubuntu']).mockResolvedValue([]) - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.install).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_RUNNING_OBSERVATION_MS) - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(2) - expect(mocks.install).toHaveBeenCalledTimes(1) - subscription.unsubscribe() - }) - - it('revalidates an UNC transcript after a gated install failure', async () => { - setPlatform('win32') - mocks.listRunningWslDistrosAsync.mockResolvedValueOnce(['Ubuntu']).mockResolvedValue([]) - mocks.install.mockRejectedValueOnce(new WslTranscriptFsError('timeout', 'stalled')) - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.install).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_RUNNING_OBSERVATION_MS) - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(2) - expect(mocks.install).toHaveBeenCalledTimes(1) - subscription.unsubscribe() - }) - - it('shares one probe and skips history scans across staggered unresolved paths', async () => { - setPlatform('win32') - const subscriptions = await Promise.all( - [0, 1].map((index) => - subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: `wsl-sess-${index}`, - transcriptPath: ROLLOUT_UNC, - onAppend: () => {} - }) - ) - ) - await vi.advanceTimersByTimeAsync(1_000) - subscriptions.push( - ...(await Promise.all( - [2, 3].map((index) => - subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: `wsl-sess-${index}`, - transcriptPath: ROLLOUT_UNC, - onAppend: () => {} - }) - ) - )) - ) - mocks.resolve.mockClear() - - await vi.advanceTimersByTimeAsync(1_000) - - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(1) - expect(mocks.resolve).not.toHaveBeenCalled() - expect(mocks.install).toHaveBeenCalledTimes(4) - for (const subscription of subscriptions) { - subscription.unsubscribe() - } - }) -}) diff --git a/src/main/native-chat/transcript-watch.test.ts b/src/main/native-chat/transcript-watch.test.ts deleted file mode 100644 index 381d9a7638e..00000000000 --- a/src/main/native-chat/transcript-watch.test.ts +++ /dev/null @@ -1,770 +0,0 @@ -import { writeFileSync } from 'node:fs' -import { appendFile, mkdtemp, rename, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { - NativeChatMessage, - NativeChatTurnLifecycle -} from '../../shared/native-chat/native-chat-types' -import type { NativeChatTranscriptSubscription } from './transcript-watch-contract' -import { - getActiveNativeChatWatcherCount, - readNativeChatTranscriptTail, - subscribeNativeChatTranscript as subscribeTranscript -} from './transcript-watch' - -const subscriptions = new Set() -let tempRoots: string[] = [] - -async function subscribeNativeChatTranscript(...args: Parameters) { - const subscription = await subscribeTranscript(...args) - subscriptions.add(subscription) - return subscription -} - -beforeEach(() => { - tempRoots = [] -}) - -afterEach(async () => { - for (const subscription of subscriptions) { - subscription.unsubscribe() - } - subscriptions.clear() - await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) - tempRoots = [] -}) - -async function tempFile(initial: string): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-')) - tempRoots.push(root) - const filePath = join(root, 'rollout.jsonl') - await writeFile(filePath, initial) - return filePath -} - -async function pendingFilePath(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-pending-')) - tempRoots.push(root) - return join(root, 'rollout.jsonl') -} - -function claudeLine(uuid: string, role: 'user' | 'assistant', text: string): string { - return `${JSON.stringify({ - type: role, - uuid, - timestamp: '2026-06-01T10:00:00.000Z', - message: { role, content: role === 'user' ? text : [{ type: 'text', text }] } - })}\n` -} - -function claudeEndTurnLine(uuid: string, text: string): string { - return `${JSON.stringify({ - type: 'assistant', - uuid, - timestamp: '2026-06-01T10:00:01.000Z', - message: { - role: 'assistant', - stop_reason: 'end_turn', - content: [{ type: 'text', text }] - } - })}\n` -} - -function codexLifecycleLine( - state: 'task_started' | 'task_complete' | 'turn_aborted', - turnId = 'turn-1' -): string { - return `${JSON.stringify({ - type: 'event_msg', - timestamp: state === 'task_started' ? '2026-06-01T10:00:00.000Z' : '2026-06-01T10:00:01.000Z', - payload: { type: state, turn_id: turnId } - })}\n` -} - -async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise { - const start = Date.now() - while (!predicate()) { - if (Date.now() - start > timeoutMs) { - throw new Error('timed out waiting for condition') - } - await new Promise((resolve) => setTimeout(resolve, 10)) - } -} - -describe('subscribeNativeChatTranscript', () => { - it('delivers the offset-0 drain as one initial snapshot, then only live appends', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'first')) - const snapshots: NativeChatMessage[][] = [] - const appends: NativeChatMessage[][] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onInitialSnapshot: (messages) => snapshots.push(messages), - onAppend: (messages) => appends.push(messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - expect(sub.watching).toBe(true) - await waitFor(() => snapshots.length === 1) - expect(snapshots[0]?.map((message) => message.id)).toEqual(['u-1']) - expect(appends).toEqual([]) - - await appendFile(filePath, claudeLine('a-1', 'assistant', 'reply')) - await waitFor(() => appends.flat().some((message) => message.id === 'a-1')) - sub.unsubscribe() - - expect(snapshots).toHaveLength(1) - expect(appends.flat().map((message) => message.id)).toEqual(['a-1']) - }) - - it('delivers an empty initial snapshot so clients do not remain loading', async () => { - const filePath = await tempFile('') - const snapshots: NativeChatMessage[][] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onInitialSnapshot: (messages) => snapshots.push(messages), - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => snapshots.length === 1) - sub.unsubscribe() - expect(snapshots).toEqual([[]]) - }) - - it('replays and appends provider-authored turn lifecycle markers', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'first')) - const lifecycles: NativeChatTurnLifecycle[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onInitialSnapshot: (_messages, _hasMore, _beforeOffset, _error, lifecycle) => { - if (lifecycle) { - lifecycles.push(lifecycle) - } - }, - onAppend: (_messages, lifecycle) => { - if (lifecycle) { - lifecycles.push(lifecycle) - } - }, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => lifecycles.length === 1) - await appendFile(filePath, claudeEndTurnLine('a-1', 'done')) - await waitFor(() => lifecycles.length === 2) - sub.unsubscribe() - - expect(lifecycles.map((lifecycle) => lifecycle.state)).toEqual(['working', 'completed']) - expect(lifecycles.map((lifecycle) => lifecycle.turnId)).toEqual(['u-1', 'a-1']) - }) - - it('emits Codex task_complete even when the frame has no visible messages', async () => { - const filePath = await tempFile(codexLifecycleLine('task_started')) - const lifecycles: NativeChatTurnLifecycle[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'ignored', - filePath, - onInitialSnapshot: (_messages, _hasMore, _beforeOffset, _error, lifecycle) => { - if (lifecycle) { - lifecycles.push(lifecycle) - } - }, - onAppend: (messages, lifecycle) => { - expect(messages).toEqual([]) - if (lifecycle) { - lifecycles.push(lifecycle) - } - }, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => lifecycles.length === 1) - await appendFile(filePath, codexLifecycleLine('task_complete')) - await waitFor(() => lifecycles.length === 2) - sub.unsubscribe() - - expect(lifecycles).toMatchObject([ - { state: 'working', turnId: 'turn-1' }, - { state: 'completed', turnId: 'turn-1' } - ]) - }) - - it('replays Codex interruption as a terminal lifecycle and visible status row', async () => { - const filePath = await tempFile( - codexLifecycleLine('task_started') + codexLifecycleLine('turn_aborted') - ) - let snapshot: - | { messages: NativeChatMessage[]; lifecycle: NativeChatTurnLifecycle | undefined } - | undefined - const sub = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'ignored', - filePath, - initialLimit: 40, - onInitialSnapshot: (messages, _hasMore, _beforeOffset, _error, lifecycle) => { - snapshot = { messages, lifecycle } - }, - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => snapshot !== undefined) - sub.unsubscribe() - - expect(snapshot?.lifecycle).toMatchObject({ state: 'interrupted', turnId: 'turn-1' }) - expect(snapshot?.messages).toMatchObject([ - { role: 'system', blocks: [{ type: 'text', text: 'Conversation interrupted' }] } - ]) - }) - - it('does not replay an older interruption over a newer working turn', async () => { - const filePath = await tempFile( - codexLifecycleLine('task_started', 'turn-1') + - codexLifecycleLine('turn_aborted', 'turn-1') + - codexLifecycleLine('task_started', 'turn-2') - ) - const result = await readNativeChatTranscriptTail({ - agent: 'codex', - sessionId: 'ignored', - filePath, - limit: 40 - }) - - expect(result).toMatchObject({ lifecycle: { state: 'working', turnId: 'turn-2' } }) - }) - - it('recovers a completion marker even when trailing non-boundary rows follow it', async () => { - const toolResult = `${JSON.stringify({ - type: 'user', - uuid: 'tool-result-1', - timestamp: '2026-06-01T10:00:02.000Z', - message: { - role: 'user', - content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'ok' }] - } - })}\n` - const noise = `${JSON.stringify({ - type: 'user', - uuid: 'note-1', - timestamp: '2026-06-01T10:00:03.000Z', - message: { - role: 'user', - content: [{ type: 'text', text: 'continue' }] - } - })}\n` - const filePath = await tempFile(claudeEndTurnLine('a-1', 'done') + toolResult + noise) - const result = await readNativeChatTranscriptTail({ - agent: 'claude', - sessionId: 'ignored', - filePath, - limit: 40 - }) - - expect(result).toMatchObject({ lifecycle: { state: 'completed', turnId: 'a-1' } }) - }) - - it('emits a bulk append in bounded ordered batches', async () => { - const filePath = await tempFile('') - const batches: NativeChatMessage[][] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => batches.push(messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - await new Promise((resolve) => setTimeout(resolve, 20)) - await appendFile( - filePath, - Array.from({ length: 95 }, (_unused, index) => - claudeLine(`bulk-${index}`, 'user', `message-${index}`) - ).join('') - ) - - await waitFor(() => batches.flat().length === 95) - sub.unsubscribe() - expect(batches.map((batch) => batch.length)).toEqual([40, 40, 15]) - expect(batches.flat().map((message) => message.id)).toEqual( - Array.from({ length: 95 }, (_unused, index) => `bulk-${index}`) - ) - }) - - it('drops one oversized record without retaining or blocking the next append', async () => { - const filePath = await tempFile('') - const seen: NativeChatMessage[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - await new Promise((resolve) => setTimeout(resolve, 20)) - await appendFile( - filePath, - claudeLine('oversized', 'user', 'x'.repeat(2 * 1024 * 1024)) + - claudeLine('after-oversized', 'user', 'still delivered') - ) - - await waitFor(() => seen.some((message) => message.id === 'after-oversized')) - sub.unsubscribe() - expect(seen.some((message) => message.id === 'oversized')).toBe(false) - }) - - it('returns a bounded tail snapshot with exact pagination state', async () => { - const transcript = Array.from({ length: 800 }, (_unused, index) => - claudeLine(`u-${index}`, 'user', `message-${index}-${'x'.repeat(100)}`) - ).join('') - const filePath = await tempFile(transcript) - const snapshots: { ids: string[]; hasMore: boolean }[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - initialLimit: 2, - onInitialSnapshot: (messages, hasMore) => - snapshots.push({ ids: messages.map((message) => message.id), hasMore }), - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => snapshots.length === 1) - sub.unsubscribe() - expect(snapshots).toEqual([{ ids: ['u-798', 'u-799'], hasMore: true }]) - }) - - it('keeps an explicit zero-limit snapshot empty instead of reading unbounded', async () => { - const filePath = await tempFile(claudeLine('u-0', 'user', 'hello')) - const snapshots: { ids: string[]; hasMore: boolean }[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - initialLimit: 0, - onInitialSnapshot: (messages, hasMore) => - snapshots.push({ ids: messages.map((message) => message.id), hasMore }), - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => snapshots.length === 1) - sub.unsubscribe() - expect(snapshots).toEqual([{ ids: [], hasMore: false }]) - }) - - it('pages older history by byte cursor without resending the growing tail', async () => { - const filePath = await tempFile( - Array.from({ length: 10 }, (_unused, index) => - claudeLine(`page-${index}`, 'user', `message-${index}`) - ).join('') - ) - const newest = await readNativeChatTranscriptTail({ - agent: 'claude', - sessionId: 'ignored', - filePath, - limit: 3 - }) - if ('error' in newest) { - throw new Error(newest.error) - } - const older = await readNativeChatTranscriptTail({ - agent: 'claude', - sessionId: 'ignored', - filePath, - limit: 3, - beforeOffset: newest.beforeOffset - }) - - expect(newest.messages.map((message) => message.id)).toEqual(['page-7', 'page-8', 'page-9']) - expect('messages' in older && older.messages.map((message) => message.id)).toEqual([ - 'page-4', - 'page-5', - 'page-6' - ]) - }) - - it('decodes multi-chunk records once into the bounded tail order', async () => { - const large = 'x'.repeat(200_000) - const filePath = await tempFile( - claudeLine('u-large-1', 'user', large) + claudeLine('u-large-2', 'user', large) - ) - const snapshots: { ids: string[]; hasMore: boolean }[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - initialLimit: 1, - onInitialSnapshot: (messages, hasMore) => - snapshots.push({ ids: messages.map((message) => message.id), hasMore }), - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => snapshots.length === 1) - sub.unsubscribe() - expect(snapshots).toEqual([{ ids: ['u-large-2'], hasMore: true }]) - }) - - it('re-emits from the top on first drain so appended turns are never dropped', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'first')) - const batches: NativeChatMessage[][] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => batches.push(messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await appendFile(filePath, claudeLine('a-1', 'assistant', 'reply')) - await waitFor(() => batches.flat().some((m) => m.id === 'a-1')) - - sub.unsubscribe() - - // Offset-zero seed rereads existing rows; downstream ID dedup permits them beside new appends. - const ids = batches.flat().map((m) => m.id) - expect(ids).toContain('a-1') - }) - - it('recovers cleanly when a read throws (subscription not left deaf)', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'hi')) - const seen: NativeChatMessage[] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - // Fail a drain mid-flight; finally must clear reading so later appends recover. - await waitFor(() => seen.some((m) => m.id === 'u-1')) - const { chmod } = await import('node:fs/promises') - await chmod(filePath, 0o000) - await appendFile(filePath, claudeLine('a-1', 'assistant', 'reply')).catch(() => {}) - await new Promise((resolve) => setTimeout(resolve, 40)) - await chmod(filePath, 0o644) - await appendFile(filePath, claudeLine('a-2', 'assistant', 'recovered')) - - await waitFor(() => seen.some((m) => m.id === 'a-2')) - sub.unsubscribe() - expect(seen.some((m) => m.id === 'a-2')).toBe(true) - }) - - it('releases the watcher on unsubscribe (no leak)', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'hi')) - const before = getActiveNativeChatWatcherCount() - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - expect(getActiveNativeChatWatcherCount()).toBe(before + 1) - - sub.unsubscribe() - expect(getActiveNativeChatWatcherCount()).toBe(before) - - sub.unsubscribe() - expect(getActiveNativeChatWatcherCount()).toBe(before) - }) - - it('coalesces rapid successive appends without dropping messages', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'hi')) - const seen: NativeChatMessage[] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 10, - reconciliationIntervalMs: 20 - }) - - await appendFile(filePath, claudeLine('a-1', 'assistant', 'one')) - await appendFile(filePath, claudeLine('a-2', 'assistant', 'two')) - await appendFile(filePath, claudeLine('a-3', 'assistant', 'three')) - - await waitFor(() => ['a-1', 'a-2', 'a-3'].every((id) => seen.some((m) => m.id === id))) - sub.unsubscribe() - - const appendedIds = seen.map((m) => m.id).filter((id) => id !== 'u-1') - expect(appendedIds).toEqual(['a-1', 'a-2', 'a-3']) - }) - - it('waits for an incomplete trailing JSONL line before advancing the offset', async () => { - const filePath = await tempFile(claudeLine('u-1', 'user', 'hi')) - const seen: NativeChatMessage[] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await waitFor(() => seen.some((m) => m.id === 'u-1')) - - const line = claudeLine('a-partial', 'assistant', 'split reply') - const splitAt = Math.floor(line.length / 2) - await appendFile(filePath, line.slice(0, splitAt)) - await new Promise((resolve) => setTimeout(resolve, 40)) - expect(seen.some((m) => m.id === 'a-partial')).toBe(false) - - await appendFile(filePath, line.slice(splitAt)) - await waitFor(() => seen.some((m) => m.id === 'a-partial')) - - sub.unsubscribe() - expect(seen.filter((m) => m.id === 'a-partial')).toHaveLength(1) - }) - - it('survives file replacement / rotation (offset reset on shrink)', async () => { - const filePath = await tempFile( - claudeLine('u-1', 'user', 'old') + claudeLine('a-1', 'assistant', 'old-reply') - ) - const seen: NativeChatMessage[] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - - await writeFile(filePath, claudeLine('u-2', 'user', 'fresh')) - await waitFor(() => seen.some((m) => m.id === 'u-2')) - - await appendFile(filePath, claudeLine('a-2', 'assistant', 'fresh-reply')) - await waitFor(() => seen.some((m) => m.id === 'a-2')) - - sub.unsubscribe() - const ids = seen.map((m) => m.id) - expect(ids).toContain('u-2') - expect(ids).toContain('a-2') - }) - - it('detects same-size and larger in-place transcript replacement', async () => { - const filePath = await tempFile(claudeLine('u-old', 'user', 'old')) - const seen: NativeChatMessage[] = [] - const replacements = new Map([ - ['u-old', claudeLine('u-new', 'user', 'new')], - ['u-new', claudeLine('u-bigger', 'user', 'larger replacement text')] - ]) - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => { - seen.push(...messages) - // Rewrite during delivery so no mid-write stat sees Bun’s write-before-truncate intermediate version. - for (const message of messages) { - const next = replacements.get(message.id) - replacements.delete(message.id) - if (next) { - writeFileSync(filePath, next) - } - } - }, - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - await waitFor(() => seen.some((message) => message.id === 'u-bigger')) - sub.unsubscribe() - - expect(seen.map((message) => message.id)).toEqual(['u-old', 'u-new', 'u-bigger']) - }) - - it('keeps watching after atomic rename replacement', async () => { - const filePath = await tempFile(claudeLine('atomic-old', 'user', 'old')) - const replacementPath = `${filePath}.replacement` - const seen: NativeChatMessage[] = [] - const replacements: string[][] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - initialLimit: 40, - onInitialSnapshot: (messages) => seen.push(...messages), - onReplace: (messages) => { - replacements.push(messages.map((message) => message.id)) - seen.splice(0, seen.length, ...messages) - }, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20 - }) - await waitFor(() => seen.some((message) => message.id === 'atomic-old')) - - await writeFile(replacementPath, claudeLine('atomic-new', 'user', 'replacement')) - await rename(replacementPath, filePath) - await waitFor(() => seen.some((message) => message.id === 'atomic-new')) - await appendFile(filePath, claudeLine('atomic-followup', 'assistant', 'still watched')) - await waitFor(() => seen.some((message) => message.id === 'atomic-followup')) - sub.unsubscribe() - - expect(replacements).toEqual([['atomic-new']]) - expect(seen.some((message) => message.id === 'atomic-old')).toBe(false) - expect(seen.filter((message) => message.id === 'atomic-followup')).toHaveLength(1) - }) - - it('does not resurrect the watcher when unsubscribe races an atomic replacement', async () => { - const filePath = await tempFile(claudeLine('race-old', 'user', 'old')) - const replacementPath = `${filePath}.replacement` - const before = getActiveNativeChatWatcherCount() - const seen: NativeChatMessage[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 0, - reconciliationIntervalMs: 20 - }) - await waitFor(() => seen.some((message) => message.id === 'race-old')) - - await writeFile(replacementPath, claudeLine('race-new', 'user', 'replacement')) - await rename(replacementPath, filePath) - await new Promise((resolve) => setTimeout(resolve, 0)) - sub.unsubscribe() - await new Promise((resolve) => setTimeout(resolve, 30)) - - expect(getActiveNativeChatWatcherCount()).toBe(before) - await appendFile(filePath, claudeLine('race-after', 'assistant', 'must stay closed')) - await new Promise((resolve) => setTimeout(resolve, 30)) - expect(seen.some((message) => message.id === 'race-after')).toBe(false) - }) - - it('recovers after an unlink/recreate gap outlasts the fast retry window', async () => { - const filePath = await tempFile(claudeLine('unlink-old', 'user', 'old')) - const seen: NativeChatMessage[] = [] - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 0, - reconciliationIntervalMs: 20 - }) - await waitFor(() => seen.some((message) => message.id === 'unlink-old')) - - await rm(filePath) - await new Promise((resolve) => setTimeout(resolve, 1_200)) - await writeFile(filePath, claudeLine('unlink-new', 'user', 'replacement')) - await waitFor(() => seen.some((message) => message.id === 'unlink-new')) - await appendFile(filePath, claudeLine('unlink-after', 'assistant', 'still watched')) - await waitFor(() => seen.some((message) => message.id === 'unlink-after')) - sub.unsubscribe() - - expect(seen.filter((message) => message.id === 'unlink-after')).toHaveLength(1) - }) - - it('returns a no-op unsubscribe when the file cannot be resolved', async () => { - const before = getActiveNativeChatWatcherCount() - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: '', - onAppend: () => {} - }) - expect(sub.watching).toBe(false) - expect(getActiveNativeChatWatcherCount()).toBe(before) - sub.unsubscribe() - }) -}) - -describe('subscribeNativeChatTranscript (resolve-poll for a not-yet-created file, #8401)', () => { - it('keeps retrying resolve+install and tails the file once it is created', async () => { - const filePath = await pendingFilePath() - const seen: NativeChatMessage[] = [] - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: (messages) => seen.push(...messages), - debounceMs: 5, - reconciliationIntervalMs: 20, - resolvePollIntervalMs: 20 - }) - - expect(getActiveNativeChatWatcherCount()).toBe(0) - - await new Promise((resolve) => setTimeout(resolve, 50)) - await writeFile(filePath, claudeLine('u-1', 'user', 'hello')) - - await waitFor(() => seen.some((m) => m.id === 'u-1')) - expect(getActiveNativeChatWatcherCount()).toBe(1) - - sub.unsubscribe() - expect(getActiveNativeChatWatcherCount()).toBe(0) - }) - - it('returns a no-op (no resolve poll) for a blank session id with no explicit file', async () => { - const before = getActiveNativeChatWatcherCount() - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: ' ', - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20, - resolvePollIntervalMs: 10 - }) - - await new Promise((resolve) => setTimeout(resolve, 60)) - expect(getActiveNativeChatWatcherCount()).toBe(before) - sub.unsubscribe() - sub.unsubscribe() - expect(getActiveNativeChatWatcherCount()).toBe(before) - }) - - it('unsubscribing during the poll phase leaves no watcher or timer alive', async () => { - const filePath = await pendingFilePath() - const before = getActiveNativeChatWatcherCount() - - const sub = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'ignored', - filePath, - onAppend: () => {}, - debounceMs: 5, - reconciliationIntervalMs: 20, - resolvePollIntervalMs: 20 - }) - - sub.unsubscribe() - expect(getActiveNativeChatWatcherCount()).toBe(before) - - await new Promise((resolve) => setTimeout(resolve, 100)) - expect(getActiveNativeChatWatcherCount()).toBe(before) - }) -}) diff --git a/src/main/native-chat/transcript-zcode.test.ts b/src/main/native-chat/transcript-zcode.test.ts index 9721bfee35c..d8ac97ba68e 100644 --- a/src/main/native-chat/transcript-zcode.test.ts +++ b/src/main/native-chat/transcript-zcode.test.ts @@ -3,17 +3,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import Database from '../sqlite/sync-database' -import type { NativeChatMessage } from '../../shared/native-chat/native-chat-types' import { readOpenCodeTranscriptPage, readOpenCodeTranscriptSignal } from './transcript-opencode-sqlite-query' -import { - readOpenCodeNativeChatTranscriptFull, - readOpenCodeNativeChatTranscriptTail -} from './transcript-opencode' -import { subscribeOpenCodeNativeChatTranscript } from './transcript-opencode-subscribe' -import { handleOpenCodeSqliteRequest } from '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch' const cleanups: (() => void)[] = [] afterEach(() => { @@ -67,130 +60,6 @@ function fixture(sequenced = true) { return { db, dbPath, insert, deps } } -it.each([true, false])( - 'filters hidden messages through full, tail and worker reads (sequence=%s)', - async (sequenced) => { - const f = fixture(sequenced) - f.insert('legacy-visible', 0) - f.insert('hidden', 1, 'hidden') - f.insert('visible', 2, 'visible') - expect(readOpenCodeTranscriptSignal(f.dbPath, 'session', 'zcode')).toMatchObject({ - messageCount: 2, - partCount: 2 - }) - expect(readOpenCodeTranscriptSignal(f.dbPath, 'session')).toMatchObject({ - messageCount: 3, - partCount: 3 - }) - const full = await readOpenCodeNativeChatTranscriptFull('session', f.deps, undefined, 'zcode') - expect(full).toMatchObject({ messages: [{ id: 'legacy-visible' }, { id: 'visible' }] }) - const tail = await readOpenCodeNativeChatTranscriptTail( - { sessionId: 'session', limit: 1, agent: 'zcode' }, - f.deps - ) - expect(tail).toMatchObject({ messages: [{ id: 'visible' }], hasMore: true }) - const response = await handleOpenCodeSqliteRequest({ - id: 1, - kind: 'native-page', - dbPath: f.dbPath, - sessionId: 'session', - limit: 10, - agent: 'zcode' - }) - expect(response).toMatchObject({ - ok: true, - value: { items: [{ message: { id: 'legacy-visible' } }, { message: { id: 'visible' } }] } - }) - } -) - -it('paginates imported messages and parts by their recorded sequence', async () => { - const f = fixture() - f.insert('last', 2) - f.insert('first', 0) - f.insert('hidden', 1, 'hidden') - f.insert('second', 1) - f.insert('legacy-null', null) - f.db.prepare('UPDATE part SET sequence = 1 WHERE id = ?').run('second') - f.db - .prepare('INSERT INTO part VALUES (?, ?, ?, ?, 1, 1, 0)') - .run( - 'earlier-part', - 'second', - 'session', - JSON.stringify({ type: 'text', text: 'earlier part' }) - ) - const full = await readOpenCodeNativeChatTranscriptFull('session', f.deps, undefined, 'zcode') - expect(full).toMatchObject({ - messages: [ - { id: 'first' }, - { id: 'second', blocks: [{ text: 'earlier part' }, { text: 'second' }] }, - { id: 'last' }, - { id: 'legacy-null' } - ] - }) - const collected: string[] = [] - let cursor: number | undefined - for (let index = 0; index < 5; index++) { - const page = readOpenCodeTranscriptPage({ - dbPath: f.dbPath, - sessionId: 'session', - limit: 1, - agent: 'zcode', - beforeMessageRowId: cursor - }) - collected.unshift(...(page?.items.map((item) => item.message.id) ?? [])) - if (!page?.hasMore) { - break - } - cursor = page.beforeMessageRowId ?? undefined - } - expect(collected).toEqual(['first', 'second', 'last', 'legacy-null']) -}) - -it('reconciles visibility changes, ordered imports and deletions in a live chat', async () => { - vi.useFakeTimers() - const f = fixture() - f.insert('last', 2) - f.insert('first', 0) - f.insert('hidden', 1, 'hidden') - let displayed: NativeChatMessage[] = [] - const subscription = subscribeOpenCodeNativeChatTranscript( - { - agent: 'zcode', - sessionId: 'session', - resolvePollIntervalMs: 5, - onInitialSnapshot: (messages) => { - displayed = messages - }, - onReplace: (messages) => { - displayed = messages - }, - onAppend: (messages) => { - displayed.push(...messages) - } - }, - undefined, - f.deps, - 'zcode' - ) - cleanups.push(subscription.unsubscribe) - await vi.advanceTimersByTimeAsync(0) - expect(displayed.map((message) => message.id)).toEqual(['first', 'last']) - f.db - .prepare('UPDATE message SET data = ?, time_updated = 2 WHERE id = ?') - .run(JSON.stringify({ role: 'user' }), 'hidden') - await vi.advanceTimersByTimeAsync(5) - expect(displayed.map((message) => message.id)).toEqual(['first', 'hidden', 'last']) - f.insert('middle', 1) - await vi.advanceTimersByTimeAsync(5) - expect(displayed.map((message) => message.id)).toEqual(['first', 'hidden', 'middle', 'last']) - f.db.prepare('DELETE FROM message WHERE id = ?').run('first') - f.db.prepare('DELETE FROM part WHERE message_id = ?').run('first') - await vi.advanceTimersByTimeAsync(5) - expect(displayed.map((message) => message.id)).toEqual(['hidden', 'middle', 'last']) -}) - it('keeps a paging cursor stable when earlier messages are removed or imported', () => { const f = fixture() f.insert('last', 3) @@ -214,41 +83,3 @@ it('keeps a paging cursor stable when earlier messages are removed or imported', }) expect(older?.items.map((item) => item.message.id)).toEqual(['imported', 'middle']) }) - -it('observes a balanced visibility swap even when part counts and times stay unchanged', async () => { - vi.useFakeTimers() - const f = fixture() - f.insert('first', 0) - f.insert('hidden', 1, 'hidden') - f.insert('last', 2) - let displayed: NativeChatMessage[] = [] - const subscription = subscribeOpenCodeNativeChatTranscript( - { - agent: 'zcode', - sessionId: 'session', - resolvePollIntervalMs: 5, - onInitialSnapshot: (messages) => { - displayed = messages - }, - onReplace: (messages) => { - displayed = messages - }, - onAppend: (messages) => { - displayed.push(...messages) - } - }, - undefined, - f.deps, - 'zcode' - ) - cleanups.push(subscription.unsubscribe) - await vi.advanceTimersByTimeAsync(0) - f.db - .prepare('UPDATE message SET data = ?, time_updated = 2 WHERE id = ?') - .run(JSON.stringify({ role: 'user', semantics: { transcriptVisibility: 'hidden' } }), 'first') - f.db - .prepare('UPDATE message SET data = ?, time_updated = 2 WHERE id = ?') - .run(JSON.stringify({ role: 'user' }), 'hidden') - await vi.advanceTimersByTimeAsync(5) - expect(displayed.map((message) => message.id)).toEqual(['hidden', 'last']) -}) diff --git a/src/main/native-chat/wsl-transcript-fs-access.test.ts b/src/main/native-chat/wsl-transcript-fs-access.test.ts deleted file mode 100644 index 4c4646815b1..00000000000 --- a/src/main/native-chat/wsl-transcript-fs-access.test.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFsModule from 'node:fs' -import type * as NodeFsPromisesModule from 'node:fs/promises' -import type * as GateModule from './wsl-transcript-fs-gate' - -const UNC_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions\\a.jsonl' -const LEGACY_UNC_PATH = '\\\\wsl$\\Ubuntu\\home\\ada\\.codex\\sessions\\a.jsonl' -const WINDOWS_PATH = 'C:\\Users\\ada\\.codex\\sessions\\a.jsonl' -const POSIX_PATH = '/home/ada/.codex/sessions/a.jsonl' - -const mocks = vi.hoisted(() => ({ - stat: vi.fn(), - lstat: vi.fn(), - readdir: vi.fn(), - readFile: vi.fn(), - open: vi.fn(), - createReadStream: vi.fn(), - runTask: vi.fn() -})) - -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal()), - createReadStream: mocks.createReadStream -})) - -vi.mock('node:fs/promises', async (importOriginal) => ({ - ...(await importOriginal()), - stat: mocks.stat, - lstat: mocks.lstat, - readdir: mocks.readdir, - readFile: mocks.readFile, - open: mocks.open -})) - -vi.mock('./wsl-transcript-fs-gate', async (importOriginal) => { - const original = await importOriginal() - mocks.runTask.mockImplementation(original.runWslTranscriptFsTask) - return { ...original, runWslTranscriptFsTask: mocks.runTask } -}) - -import { - closeTranscriptHandle, - openTranscriptReadStream, - readTranscriptSlice, - wslGatedLstat, - openTranscriptFile, - readTranscriptFile, - wslGatedReaddir, - wslGatedReadFile, - wslGatedStat, - WSL_TRANSCRIPT_READ_CHUNK_BYTES -} from './wsl-transcript-fs-access' -import { - resetWslTranscriptFsGateForTests, - WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS, - WslTranscriptFsError -} from './wsl-transcript-fs-gate' - -function fakeHandle() { - return { read: vi.fn(), close: vi.fn(async () => {}) } -} - -beforeEach(() => { - // Reset real gate state; prior stalls must not quarantine later tests. - resetWslTranscriptFsGateForTests() - // Clear history without removing the mock’s real-gate delegation. - mocks.runTask.mockClear() - for (const [name, mock] of Object.entries(mocks)) { - if (name !== 'runTask') { - mock.mockReset() - } - } -}) - -describe('transcript filesystem accessor off WSL UNC', () => { - it.each([ - ['a posix path', POSIX_PATH], - ['a Windows drive path', WINDOWS_PATH] - ])('never enters the gate for %s', async (_label, path) => { - mocks.stat.mockResolvedValue({ size: 1 }) - mocks.lstat.mockResolvedValue({ size: 1 }) - mocks.readdir.mockResolvedValue([]) - mocks.readFile.mockResolvedValue('body') - const handle = fakeHandle() - handle.read.mockResolvedValue({ bytesRead: 0, buffer: Buffer.alloc(0) }) - mocks.open.mockResolvedValue(handle) - mocks.createReadStream.mockReturnValue('raw-stream') - - await wslGatedStat(path, 'exact') - await wslGatedLstat(path, 'scan') - await wslGatedReaddir(path, 'scan') - await wslGatedReadFile(path, 'utf-8', 'scan') - const opened = await openTranscriptFile(path, 'exact') - await readTranscriptFile(opened, path, Buffer.alloc(1), 0, 1, 0, 'exact') - const stream = openTranscriptReadStream(path, { encoding: 'utf-8' }, 'scan') - - expect(mocks.runTask).not.toHaveBeenCalled() - expect(mocks.stat).toHaveBeenCalledWith(path) - expect(mocks.readdir).toHaveBeenCalledWith(path, { withFileTypes: true }) - expect(mocks.readFile).toHaveBeenCalledWith(path, 'utf-8') - expect(mocks.open).toHaveBeenCalledWith(path, 'r') - expect(stream).toBe('raw-stream') - expect(mocks.createReadStream).toHaveBeenCalledWith(path, { - encoding: 'utf-8', - signal: undefined - }) - }) - - it('forwards the caller signal so the local stream honours cancellation', () => { - mocks.createReadStream.mockReturnValue('raw-stream') - const controller = new AbortController() - - openTranscriptReadStream(POSIX_PATH, { start: 4 }, 'exact', controller.signal) - - expect(mocks.createReadStream).toHaveBeenCalledWith(POSIX_PATH, { - start: 4, - signal: controller.signal - }) - }) -}) - -describe('transcript filesystem accessor on WSL UNC', () => { - it.each([ - ['wsl.localhost', UNC_PATH], - ['wsl$', LEGACY_UNC_PATH] - ])('routes %s paths through the gate', async (_label, path) => { - mocks.stat.mockResolvedValue({ size: 7 }) - mocks.lstat.mockResolvedValue({ size: 7 }) - mocks.readdir.mockResolvedValue([]) - mocks.readFile.mockResolvedValue('body') - - await wslGatedStat(path, 'exact') - await wslGatedLstat(path, 'scan') - await wslGatedReaddir(path, 'scan') - await wslGatedReadFile(path, 'utf-8', 'scan') - - expect(mocks.runTask.mock.calls.map(([options]) => options.operation)).toEqual([ - 'stat', - 'lstat', - 'readdir', - 'readfile' - ]) - }) - - it('opts positional reads and opens out of coalescing', async () => { - const handle = fakeHandle() - handle.read.mockResolvedValue({ bytesRead: 1, buffer: Buffer.alloc(1) }) - mocks.open.mockResolvedValue(handle) - - const opened = await openTranscriptFile(UNC_PATH, 'exact') - await readTranscriptFile(opened, UNC_PATH, Buffer.alloc(1), 0, 1, 0, 'exact') - - for (const call of mocks.runTask.mock.calls) { - expect(call[0]).toMatchObject({ dedupe: false }) - } - }) - - it('reads a slice and closes the handle even when the read rejects', async () => { - const handle = fakeHandle() - handle.read.mockRejectedValue(new Error('EIO')) - mocks.open.mockResolvedValue(handle) - - await expect(readTranscriptSlice(UNC_PATH, 4, 8, 'scan')).rejects.toThrow('EIO') - expect(handle.close).toHaveBeenCalled() - }) - - it('yields Buffer chunks and closes the handle when the consumer destroys the stream', async () => { - const handle = fakeHandle() - handle.read.mockImplementation( - async (buffer: Buffer, offset: number, length: number, position: number) => { - const body = Buffer.from('{"a":1}\n{"b":2}\n') - const slice = body.subarray(position, Math.min(position + length, body.length)) - slice.copy(buffer, offset) - return { bytesRead: slice.length, buffer } - } - ) - mocks.open.mockResolvedValue(handle) - - const stream = openTranscriptReadStream(UNC_PATH, {}, 'exact') - const chunks: unknown[] = [] - for await (const chunk of stream) { - chunks.push(chunk) - break - } - stream.destroy() - await new Promise((resolve) => setImmediate(resolve)) - - expect(chunks).toHaveLength(1) - expect(Buffer.isBuffer(chunks[0])).toBe(true) - expect((chunks[0] as Buffer).toString('utf-8')).toBe('{"a":1}\n{"b":2}\n') - expect(handle.close).toHaveBeenCalled() - }) - - it('swallows close failures so teardown never rejects', async () => { - const handle = fakeHandle() - handle.close.mockRejectedValue(new Error('stalled close')) - await expect(closeTranscriptHandle(handle as never, UNC_PATH)).resolves.toBeUndefined() - await new Promise((resolve) => setImmediate(resolve)) - }) - - it('does not await a UNC close, mirroring the process-handle contract', async () => { - let releaseStuck: (() => void) | undefined - const stuck = fakeHandle() - stuck.close.mockReturnValue( - new Promise((resolve) => { - releaseStuck = resolve - }) - ) - - try { - await expect(closeTranscriptHandle(stuck as never, UNC_PATH)).resolves.toBeUndefined() - expect(stuck.close).toHaveBeenCalledTimes(1) - } finally { - releaseStuck?.() - await new Promise((resolve) => setImmediate(resolve)) - } - }) - - it.each([ - ['stat', wslGatedStat, mocks.stat], - ['lstat', wslGatedLstat, mocks.lstat] - ])( - 'detaches a cancelled %s waiter without waiting out the deadline', - async (_op, gated, mock) => { - let release: (() => void) | undefined - mock.mockReturnValue( - new Promise((resolve) => { - release = () => resolve({ size: 0 }) - }) - ) - try { - const controller = new AbortController() - const reason = new Error('unsubscribed') - const pending = gated(UNC_PATH, 'exact', controller.signal) - const settled = pending.then( - () => 'resolved', - (error: unknown) => error - ) - // Start the unabortable syscall before cancellation so this exercises a running waiter. - await new Promise((resolve) => setImmediate(resolve)) - expect(mock).toHaveBeenCalledTimes(1) - - controller.abort(reason) - - await expect(settled).resolves.toBe(reason) - } finally { - release?.() - await new Promise((resolve) => setImmediate(resolve)) - } - } - ) - - it('disposes a late open result after the deadline already settled the task', async () => { - vi.useFakeTimers() - let release: ((handle: unknown) => void) | undefined - mocks.open.mockReturnValue( - new Promise((resolve) => { - release = resolve - }) - ) - try { - const handle = fakeHandle() - const refused = openTranscriptFile(UNC_PATH, 'exact').catch((error: unknown) => error) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - await expect(refused).resolves.toBeInstanceOf(WslTranscriptFsError) - - release?.(handle) - await vi.advanceTimersByTimeAsync(0) - - expect(handle.close).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) -}) - -describe('transcript handle close off WSL UNC', () => { - it('awaits teardown and surfaces the failure, as the raw close did', async () => { - const handle = fakeHandle() - let closed = false - handle.close.mockImplementation(async () => { - await new Promise((resolve) => setImmediate(resolve)) - closed = true - }) - - await closeTranscriptHandle(handle as never, POSIX_PATH) - expect(closed).toBe(true) - - handle.close.mockRejectedValue(new Error('EIO on close')) - await expect(closeTranscriptHandle(handle as never, WINDOWS_PATH)).rejects.toThrow( - 'EIO on close' - ) - }) -}) - -describe('per-chunk admission', () => { - it('carries a codepoint straddling the 1 MiB chunk boundary across chunks', async () => { - const emoji = Buffer.from('😀', 'utf8') - // Derive the split from the production chunk size so the emoji always straddles it. - const body = Buffer.concat([ - Buffer.alloc(WSL_TRANSCRIPT_READ_CHUNK_BYTES - 2, 0x61), - emoji, - Buffer.from('tail\n', 'utf8') - ]) - const handle = fakeHandle() - handle.read.mockImplementation( - async (buffer: Buffer, offset: number, length: number, position: number) => { - const slice = body.subarray(position, Math.min(position + length, body.length)) - slice.copy(buffer, offset) - return { bytesRead: slice.length, buffer } - } - ) - mocks.open.mockResolvedValue(handle) - - const stream = openTranscriptReadStream(UNC_PATH, { encoding: 'utf-8' }, 'exact') - let decoded = '' - for await (const chunk of stream) { - expect(typeof chunk).toBe('string') - decoded += chunk as string - } - - expect(decoded).not.toContain('�') - expect(decoded).toBe(body.toString('utf8')) - expect(handle.read.mock.calls.length).toBeGreaterThan(1) - }) - - it('surfaces a gate refusal mid-stream as an error event', async () => { - vi.useFakeTimers() - try { - let served = 0 - const handle = fakeHandle() - handle.read.mockImplementation((buffer: Buffer) => { - if (served++ === 0) { - buffer.write('x') - return Promise.resolve({ bytesRead: 1, buffer }) - } - return new Promise(() => {}) - }) - mocks.open.mockResolvedValue(handle) - - const stream = openTranscriptReadStream(UNC_PATH, {}, 'exact') - const drained = (async () => { - for await (const chunk of stream) { - void chunk - } - })() - const settled = drained.then( - () => null, - (error: unknown) => error - ) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - - await expect(settled).resolves.toBeInstanceOf(WslTranscriptFsError) - expect(handle.close).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/native-chat/wsl-transcript-fs-gate.test.ts b/src/main/native-chat/wsl-transcript-fs-gate.test.ts deleted file mode 100644 index 0d2230b41c1..00000000000 --- a/src/main/native-chat/wsl-transcript-fs-gate.test.ts +++ /dev/null @@ -1,851 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest' -import { - resetWslTranscriptFsGateForTests, - runWslTranscriptFsTask, - WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS, - WSL_TRANSCRIPT_FS_MAX_PENDING_TASKS, - WSL_TRANSCRIPT_FS_MAX_WAITERS_PER_TASK, - WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS, - WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS, - WslTranscriptFsError -} from './wsl-transcript-fs-gate' - -const SLOW_MESSAGE = - 'WSL transcript files are temporarily unavailable because filesystem access is taking too long. Try again shortly or restart Orca if the issue continues.' -const CAPACITY_MESSAGE = - 'WSL transcript discovery is temporarily unavailable because too many filesystem requests are already waiting. Try again shortly or restart Orca if the issue continues.' - -function deferred(): { - promise: Promise - resolve: (value: T) => void - reject: (error: unknown) => void -} { - let resolve!: (value: T) => void - let reject!: (error: unknown) => void - return { - promise: new Promise((res, rej) => ((resolve = res), (reject = rej))), - resolve, - reject - } -} - -function run( - path: string, - priority: 'exact' | 'scan', - task: () => Promise, - signal?: AbortSignal -): Promise { - return runWslTranscriptFsTask( - { operation: priority === 'exact' ? 'access' : 'readdir', path, priority, signal }, - task - ) -} - -describe('WSL transcript filesystem task scheduling', () => { - let warnSpy: MockInstance - - beforeEach(() => { - resetWslTranscriptFsGateForTests() - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - }) - - afterEach(() => { - warnSpy.mockRestore() - }) - - it('does not block an exact probe behind a running scan on the same route', async () => { - const stalled = deferred() - const scanTask = vi.fn(() => stalled.promise) - const scan = run('\\\\wsl.localhost\\Ubuntu\\tree', 'scan', scanTask) - await vi.waitFor(() => expect(scanTask).toHaveBeenCalledOnce()) - - await expect( - run('\\\\wsl.localhost\\Ubuntu\\transcript.jsonl', 'exact', async () => 'exact') - ).resolves.toBe('exact') - stalled.resolve('scan') - await expect(scan).resolves.toBe('scan') - }) - - it('allows healthy distros and provider routes to bypass a stalled lane', async () => { - const stalled = deferred() - const ubuntuLocalhost = run('\\\\wsl.localhost\\Ubuntu\\home\\a', 'scan', () => stalled.promise) - const debian = vi.fn(async () => 'debian') - const ubuntuLegacy = vi.fn(async () => 'legacy') - - await expect(run('\\\\wsl.localhost\\Debian\\home\\a', 'exact', debian)).resolves.toBe('debian') - await expect(run('\\\\wsl$\\Ubuntu\\home\\a', 'exact', ubuntuLegacy)).resolves.toBe('legacy') - expect(debian).toHaveBeenCalledOnce() - expect(ubuntuLegacy).toHaveBeenCalledOnce() - - stalled.resolve('localhost') - await expect(ubuntuLocalhost).resolves.toBe('localhost') - }) - - it('runs an exact probe before older queued scan work', async () => { - const ubuntu = deferred() - const debian = deferred() - const occupied: string[] = [] - const started: string[] = [] - const first = run('\\\\wsl.localhost\\Ubuntu\\a', 'exact', () => { - occupied.push('ubuntu') - return ubuntu.promise - }) - const second = run('\\\\wsl.localhost\\Debian\\a', 'exact', () => { - occupied.push('debian') - return debian.promise - }) - await vi.waitFor(() => expect(occupied).toEqual(['ubuntu', 'debian'])) - - const scan = run('\\\\wsl.localhost\\Fedora\\tree', 'scan', async () => { - started.push('scan') - return 'scan' - }) - const exact = run('\\\\wsl.localhost\\Fedora\\file', 'exact', async () => { - started.push('exact') - return 'exact' - }) - - debian.resolve('debian') - await expect(exact).resolves.toBe('exact') - expect(started).toEqual(['exact', 'scan']) - await expect(scan).resolves.toBe('scan') - ubuntu.resolve('ubuntu') - await expect(Promise.all([first, second])).resolves.toEqual(['ubuntu', 'debian']) - }) - - it('drops abandoned queued work before it reaches the filesystem', async () => { - const ubuntu = deferred() - const debian = deferred() - const first = run('\\\\wsl.localhost\\Ubuntu\\a', 'scan', () => ubuntu.promise) - const second = run('\\\\wsl.localhost\\Debian\\a', 'scan', () => debian.promise) - const controller = new AbortController() - const abandonedTask = vi.fn(async () => 'unused') - const abandoned = run('\\\\wsl.localhost\\Fedora\\a', 'scan', abandonedTask, controller.signal) - - const reason = new Error('closed subscription') - controller.abort(reason) - await expect(abandoned).rejects.toBe(reason) - ubuntu.resolve('ubuntu') - debian.resolve('debian') - await Promise.all([first, second]) - expect(abandonedTask).not.toHaveBeenCalled() - }) - - it('shares only byte-identical requests', async () => { - const firstTask = vi.fn(async () => 'first') - const duplicateTask = vi.fn(async () => 'duplicate') - const first = run('\\\\wsl.localhost\\Ubuntu\\home\\a', 'exact', firstTask) - const duplicate = run('\\\\wsl.localhost\\Ubuntu\\home\\a', 'exact', duplicateTask) - - await expect(Promise.all([first, duplicate])).resolves.toEqual(['first', 'first']) - expect(firstTask).toHaveBeenCalledOnce() - expect(duplicateTask).not.toHaveBeenCalled() - }) - - it('never joins an exact probe onto the same file queued as scan work', async () => { - const transcript = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\live.jsonl' - const statTask = (priority: 'exact' | 'scan', task: () => Promise): Promise => - runWslTranscriptFsTask({ operation: 'stat', path: transcript, priority }, task) - // Occupy the scan slot elsewhere so a same-file scan join would inherit its queued delay. - const blocked = deferred() - const holderTask = vi.fn(() => blocked.promise) - const holder = run('\\\\wsl.localhost\\Debian\\tree', 'scan', holderTask) - await vi.waitFor(() => expect(holderTask).toHaveBeenCalledOnce()) - - const scanTask = vi.fn(async () => 'scan') - const scanned = statTask('scan', scanTask) - const exactTask = vi.fn(async () => 'exact') - - await expect(statTask('exact', exactTask)).resolves.toBe('exact') - expect(exactTask).toHaveBeenCalledOnce() - expect(scanTask).not.toHaveBeenCalled() - - blocked.resolve('holder') - await expect(Promise.all([holder, scanned])).resolves.toEqual(['holder', 'scan']) - }) - - it('keeps shared work needed by a remaining waiter', async () => { - const pending = deferred() - const task = vi.fn(() => pending.promise) - const firstController = new AbortController() - const secondController = new AbortController() - const first = run('\\\\wsl.localhost\\Ubuntu\\shared', 'exact', task, firstController.signal) - const second = run('\\\\wsl.localhost\\Ubuntu\\shared', 'exact', task, secondController.signal) - await vi.waitFor(() => expect(task).toHaveBeenCalledOnce()) - - const reason = new Error('first closed') - firstController.abort(reason) - await expect(first).rejects.toBe(reason) - pending.resolve('second') - await expect(second).resolves.toBe('second') - expect(task).toHaveBeenCalledOnce() - }) - - it('does not attach new callers to abandoned running work', async () => { - const stalled = deferred() - const firstTask = vi.fn(() => stalled.promise) - const firstController = new AbortController() - const first = run( - '\\\\wsl.localhost\\Ubuntu\\abandoned', - 'exact', - firstTask, - firstController.signal - ) - await vi.waitFor(() => expect(firstTask).toHaveBeenCalledOnce()) - - firstController.abort(new Error('first closed')) - await expect(first).rejects.toThrow('first closed') - const replacementWork = deferred() - const replacementTask = vi.fn(() => replacementWork.promise) - const replacement = run('\\\\wsl.localhost\\Ubuntu\\abandoned', 'exact', replacementTask) - - stalled.resolve('abandoned') - await vi.waitFor(() => expect(replacementTask).toHaveBeenCalledOnce()) - const duplicateTask = vi.fn(async () => 'duplicate') - const duplicate = run('\\\\wsl.localhost\\Ubuntu\\abandoned', 'exact', duplicateTask) - replacementWork.resolve('replacement') - - await expect(Promise.all([replacement, duplicate])).resolves.toEqual([ - 'replacement', - 'replacement' - ]) - expect(replacementTask).toHaveBeenCalledOnce() - expect(duplicateTask).not.toHaveBeenCalled() - }) - - it('does not conflate provider aliases or Linux path case', async () => { - const paths = [ - '\\\\wsl.localhost\\Ubuntu\\home\\a', - '\\\\wsl$\\Ubuntu\\home\\a', - '\\\\wsl.localhost\\Ubuntu\\mnt\\C\\a', - '\\\\wsl.localhost\\Ubuntu\\mnt\\c\\a' - ] - const tasks = paths.map((path, index) => run(path, 'exact', async () => String(index))) - - await expect(Promise.all(tasks)).resolves.toEqual(['0', '1', '2', '3']) - }) - - it.each([ - ['exact', WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS], - ['scan', WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS] - ] as const)('rejects a stalled %s waiter at its deadline', async (priority, deadlineMs) => { - vi.useFakeTimers() - const stalled = deferred() - try { - const task = vi.fn(() => stalled.promise) - const pending = run(`\\\\wsl.localhost\\Deadline-${priority}\\a`, priority, task) - const rejected = expect(pending).rejects.toMatchObject({ - name: 'WslTranscriptFsError', - code: 'timeout', - message: SLOW_MESSAGE - }) - let settled = false - void pending.then( - () => (settled = true), - () => (settled = true) - ) - - await vi.advanceTimersByTimeAsync(0) - expect(task).toHaveBeenCalledOnce() - await vi.advanceTimersByTimeAsync(deadlineMs - 1) - expect(settled).toBe(false) - await vi.advanceTimersByTimeAsync(1) - await rejected - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it.each([ - ['exact', WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS], - ['scan', WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS] - ] as const)('completes healthy %s work below its deadline', async (priority, deadlineMs) => { - vi.useFakeTimers() - const work = deferred() - try { - const pending = run(`\\\\wsl.localhost\\Healthy-${priority}\\a`, priority, () => work.promise) - - await vi.advanceTimersByTimeAsync(deadlineMs - 1) - work.resolve('healthy') - await expect(pending).resolves.toBe('healthy') - expect(vi.getTimerCount()).toBe(0) - await vi.advanceTimersByTimeAsync(deadlineMs) - expect(vi.getTimerCount()).toBe(0) - } finally { - work.resolve('healthy') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('expires every waiter when shared work reaches its enforced deadline', async () => { - vi.useFakeTimers() - const work = deferred() - const task = vi.fn(() => work.promise) - try { - const path = '\\\\wsl.localhost\\Ubuntu\\staggered' - const first = run(path, 'exact', task) - const firstRejected = expect(first).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(10_000) - const second = run(path, 'exact', task) - const secondRejected = expect(second).rejects.toMatchObject({ code: 'timeout' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS - 10_000) - await Promise.all([firstRejected, secondRejected]) - work.resolve('shared') - expect(task).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - } finally { - work.resolve('shared') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('rejects newest work when the pending queue is full', async () => { - vi.useFakeTimers() - const ubuntu = deferred() - const debian = deferred() - const queuedController = new AbortController() - try { - const ubuntuTask = vi.fn(() => ubuntu.promise) - const debianTask = vi.fn(() => debian.promise) - const first = run('\\\\wsl.localhost\\Ubuntu\\occupied', 'exact', ubuntuTask) - const second = run('\\\\wsl.localhost\\Debian\\occupied', 'exact', debianTask) - await vi.advanceTimersByTimeAsync(0) - - const queued = Array.from({ length: WSL_TRANSCRIPT_FS_MAX_PENDING_TASKS }, (_, index) => - run( - `\\\\wsl.localhost\\Queued-${index}\\a`, - 'exact', - async () => String(index), - index === 0 ? queuedController.signal : undefined - ) - ) - const overflowTask = vi.fn(async () => 'overflow') - await expect( - run('\\\\wsl.localhost\\Overflow\\a', 'exact', overflowTask) - ).rejects.toMatchObject({ code: 'capacity', message: CAPACITY_MESSAGE }) - expect(overflowTask).not.toHaveBeenCalled() - - const reason = new Error('queued caller closed') - queuedController.abort(reason) - await expect(queued[0]).rejects.toBe(reason) - const replacement = run('\\\\wsl.localhost\\Replacement\\a', 'exact', async () => 'new') - - ubuntu.resolve('ubuntu') - debian.resolve('debian') - await expect( - Promise.all([first, second, ...queued.slice(1), replacement]) - ).resolves.toHaveLength(WSL_TRANSCRIPT_FS_MAX_PENDING_TASKS + 2) - expect(vi.getTimerCount()).toBe(0) - } finally { - ubuntu.resolve('ubuntu') - debian.resolve('debian') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('caps callers waiting on shared work', async () => { - vi.useFakeTimers() - const stalled = deferred() - const task = vi.fn(() => stalled.promise) - const firstController = new AbortController() - try { - const path = '\\\\wsl.localhost\\Ubuntu\\shared-cap' - const waiters = Array.from({ length: WSL_TRANSCRIPT_FS_MAX_WAITERS_PER_TASK }, (_, index) => - run(path, 'exact', task, index === 0 ? firstController.signal : undefined) - ) - await vi.advanceTimersByTimeAsync(0) - - await expect(run(path, 'exact', task)).rejects.toMatchObject({ - code: 'capacity', - message: CAPACITY_MESSAGE - }) - const reason = new Error('first waiter closed') - firstController.abort(reason) - await expect(waiters[0]).rejects.toBe(reason) - const replacement = run(path, 'exact', task) - stalled.resolve('shared') - await expect(Promise.all([...waiters.slice(1), replacement])).resolves.toEqual( - Array(WSL_TRANSCRIPT_FS_MAX_WAITERS_PER_TASK).fill('shared') - ) - expect(task).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - } finally { - stalled.resolve('shared') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('restores both permits after running work exceeds its deadline', async () => { - vi.useFakeTimers() - const ubuntu = deferred() - const debian = deferred() - try { - const first = run('\\\\wsl.localhost\\Ubuntu\\stalled', 'exact', () => ubuntu.promise) - const second = run('\\\\wsl.localhost\\Debian\\stalled', 'exact', () => debian.promise) - const firstRejected = expect(first).rejects.toBeInstanceOf(WslTranscriptFsError) - const secondRejected = expect(second).rejects.toBeInstanceOf(WslTranscriptFsError) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await Promise.all([firstRejected, secondRejected]) - const laterTask = vi.fn(async () => 'later') - await expect(run('\\\\wsl.localhost\\Fedora\\later', 'exact', laterTask)).resolves.toBe( - 'later' - ) - expect(laterTask).toHaveBeenCalledOnce() - expect(vi.getTimerCount()).toBe(0) - } finally { - ubuntu.resolve('ubuntu') - debian.resolve('debian') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - // Abort-responsive process tasks must not settle before deadline quarantine is recorded. - it('quarantines the route when a sole-waiter abort-responsive task hits the deadline', async () => { - vi.useFakeTimers() - try { - const path = '\\\\wsl.localhost\\Ubuntu\\solo-stall' - const stalled = runWslTranscriptFsTask( - { operation: 'open', path, priority: 'exact', dedupe: false }, - (signal) => - new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(signal.reason), { once: true }) - ) - ) - const stalledRejected = expect(stalled).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await stalledRejected - const retryTask = vi.fn(async () => 'retry') - await expect(run(path, 'exact', retryTask)).rejects.toMatchObject({ code: 'unavailable' }) - expect(retryTask).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) - } finally { - vi.useRealTimers() - } - }) - - it('lifts a first-strike quarantine quickly and escalates on repeat stalls', async () => { - // Quarantine uses performance.now; advance it with fake timers. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }) - const path = '\\\\wsl.localhost\\Ubuntu\\cold-start' - const stallOnce = (): Promise => - runWslTranscriptFsTask( - { operation: 'open', path, priority: 'exact', dedupe: false }, - (signal) => - new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(signal.reason), { once: true }) - ) - ) - try { - const first = stallOnce() - const firstRejected = expect(first).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await firstRejected - await expect(run(path, 'exact', async () => 'early')).rejects.toMatchObject({ - code: 'unavailable' - }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - const second = stallOnce() - const secondRejected = expect(second).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await secondRejected - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - await expect(run(path, 'exact', async () => 'still-blocked')).rejects.toMatchObject({ - code: 'unavailable' - }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - await expect(run(path, 'exact', async () => 'recovered')).resolves.toBe('recovered') - - const third = stallOnce() - const thirdRejected = expect(third).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await thirdRejected - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - await expect(run(path, 'exact', async () => 'reset')).resolves.toBe('reset') - } finally { - vi.useRealTimers() - } - }) - - it('keeps the quarantine when a same-route transport fault settles', async () => { - vi.useFakeTimers() - const stalledExact = deferred() - const scanWork = deferred() - try { - const stalled = run('\\\\wsl.localhost\\Ubuntu\\quarantine-me', 'exact', () => { - return stalledExact.promise - }) - const stalledRejected = expect(stalled).rejects.toMatchObject({ code: 'timeout' }) - const scan = run('\\\\wsl.localhost\\Ubuntu\\scan-tree', 'scan', () => scanWork.promise) - const scanRejected = expect(scan).rejects.toMatchObject({ code: 'unavailable' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await stalledRejected - - scanWork.reject(new WslTranscriptFsError('unavailable', 'helper process died')) - await vi.advanceTimersByTimeAsync(0) - await scanRejected - - const retryTask = vi.fn(async () => 'retry') - await expect( - run('\\\\wsl.localhost\\Ubuntu\\retry', 'exact', retryTask) - ).rejects.toMatchObject({ code: 'unavailable' }) - expect(retryTask).not.toHaveBeenCalled() - } finally { - stalledExact.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('lets abandoned running work finish instead of aborting its process', async () => { - const work = deferred() - const controller = new AbortController() - const sawAbort = vi.fn() - const task = vi.fn((signal: AbortSignal) => { - signal.addEventListener('abort', sawAbort, { once: true }) - return work.promise - }) - const pending = runWslTranscriptFsTask( - { - operation: 'read', - path: '\\\\wsl.localhost\\Ubuntu\\abandoned-read', - priority: 'exact', - dedupe: false, - signal: controller.signal - }, - task - ) - await vi.waitFor(() => expect(task).toHaveBeenCalledOnce()) - const reason = new Error('caller moved on') - controller.abort(reason) - await expect(pending).rejects.toBe(reason) - expect(sawAbort).not.toHaveBeenCalled() - work.resolve('late') - await Promise.resolve() - }) - - it('quarantines an expired route while keeping healthy routes usable', async () => { - vi.useFakeTimers() - const stalled = deferred() - try { - const stuck = run('\\\\wsl.localhost\\Ubuntu\\lane-stuck', 'exact', () => stalled.promise) - const stuckRejected = expect(stuck).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await stuckRejected - - const sameLaneTask = vi.fn(async () => 'same-lane') - await expect( - run('\\\\wsl.localhost\\Ubuntu\\lane-stuck-sibling', 'exact', sameLaneTask) - ).rejects.toMatchObject({ code: 'unavailable' }) - expect(sameLaneTask).not.toHaveBeenCalled() - await expect( - run('\\\\wsl.localhost\\Debian\\healthy-lane', 'exact', async () => 'debian') - ).resolves.toBe('debian') - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('restores the scan slot while quarantining the expired route', async () => { - vi.useFakeTimers() - const stalled = deferred() - try { - const stuckScan = run('\\\\wsl.localhost\\Ubuntu\\stuck-tree', 'scan', () => stalled.promise) - const stuckRejected = expect(stuckScan).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS) - await stuckRejected - - const otherScanTask = vi.fn(async () => 'other-scan') - await expect( - run('\\\\wsl.localhost\\Debian\\other-tree', 'scan', otherScanTask) - ).resolves.toBe('other-scan') - expect(otherScanTask).toHaveBeenCalledOnce() - await expect( - run('\\\\wsl.localhost\\Ubuntu\\live-probe', 'exact', async () => 'exact') - ).rejects.toMatchObject({ code: 'unavailable' }) - await expect( - run('\\\\wsl.localhost\\Debian\\live-probe', 'exact', async () => 'exact') - ).resolves.toBe('exact') - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('does not spend a replacement process on a quarantined route', async () => { - vi.useFakeTimers() - const stalled = deferred() - try { - const stuck = run('\\\\wsl.localhost\\Ubuntu\\hung-file', 'exact', () => stalled.promise) - const stuckRejected = expect(stuck).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await stuckRejected - - const doomedScanTask = vi.fn(async () => 'doomed') - await expect( - run('\\\\wsl.localhost\\Ubuntu\\tree', 'scan', doomedScanTask) - ).rejects.toMatchObject({ code: 'unavailable' }) - expect(doomedScanTask).not.toHaveBeenCalled() - await expect( - run('\\\\wsl.localhost\\Debian\\tree', 'scan', async () => 'debian-scan') - ).resolves.toBe('debian-scan') - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('ignores a late result after admitting replacement work', async () => { - // Quarantine uses performance.now; advance it with fake timers. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }) - const stalled = deferred() - try { - const stuck = run('\\\\wsl.localhost\\Ubuntu\\recovering', 'exact', () => stalled.promise) - const stuckRejected = expect(stuck).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await stuckRejected - await expect( - run('\\\\wsl.localhost\\Ubuntu\\recovering-next', 'exact', async () => 'blocked') - ).rejects.toMatchObject({ code: 'unavailable' }) - - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - await expect( - run('\\\\wsl.localhost\\Ubuntu\\recovering-next', 'exact', async () => 'still-blocked') - ).rejects.toMatchObject({ code: 'unavailable' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - await expect( - run('\\\\wsl.localhost\\Ubuntu\\recovering-next', 'exact', async () => 'recovered') - ).resolves.toBe('recovered') - expect(vi.getTimerCount()).toBe(0) - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('starts a new generation after shared work reaches its deadline', async () => { - // Quarantine uses performance.now; advance it with fake timers. - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] }) - const work = deferred() - const task = vi.fn(() => work.promise) - try { - const path = '\\\\wsl.localhost\\Ubuntu\\join-stuck' - const first = run(path, 'exact', task) - const firstRejected = expect(first).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(10_000) - const second = run(path, 'exact', task) - const secondRejected = expect(second).rejects.toMatchObject({ code: 'timeout' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS - 10_000) - await Promise.all([firstRejected, secondRejected]) - work.resolve('late') - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS) - const joinTask = vi.fn(async () => 'join') - await expect(run(path, 'exact', joinTask)).resolves.toBe('join') - expect(joinTask).toHaveBeenCalledOnce() - } finally { - work.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('fails queued same-route work fast when the deadline quarantines it', async () => { - vi.useFakeTimers() - const stalled = deferred() - const queuedTask = vi.fn(async () => 'queued') - try { - const stuck = run('\\\\wsl.localhost\\Ubuntu\\trap-hung', 'exact', () => stalled.promise) - const stuckRejected = expect(stuck).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(5_000) - // Queue before hang detection; sequential files must not each pay another full waiter deadline. - const queuedPath = '\\\\wsl.localhost\\Ubuntu\\trap-queued' - const queued = run(queuedPath, 'exact', queuedTask) - const queuedRejected = expect(queued).rejects.toMatchObject({ code: 'unavailable' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS - 5_000) - await stuckRejected - await queuedRejected - expect(queuedTask).not.toHaveBeenCalled() - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('keeps exact work moving while an isolated scan process is stalled', async () => { - vi.useFakeTimers() - const scanWork = deferred() - const debianWork = deferred() - const ubuntuTask = vi.fn(async () => 'ubuntu') - try { - const scanU = run( - '\\\\wsl.localhost\\Ubuntu\\queued-route-tree', - 'scan', - () => scanWork.promise - ) - const exactD = run( - '\\\\wsl.localhost\\Debian\\queued-route-d', - 'exact', - () => debianWork.promise - ) - const scanRejected = expect(scanU).rejects.toMatchObject({ code: 'timeout' }) - const exactDRejected = expect(exactD).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(35_000) - await exactDRejected - - const queuedU = run('\\\\wsl.localhost\\Ubuntu\\queued-route-file', 'exact', ubuntuTask) - await expect(queuedU).resolves.toBe('ubuntu') - await vi.advanceTimersByTimeAsync(25_000) - await scanRejected - - debianWork.resolve('debian') - await vi.advanceTimersByTimeAsync(0) - expect(ubuntuTask).toHaveBeenCalledOnce() - } finally { - scanWork.resolve('late') - debianWork.resolve('debian') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('warns once per task that outlives its deadline while running', async () => { - vi.useFakeTimers() - const stalled = deferred() - try { - const stuck = run('\\\\wsl.localhost\\Ubuntu\\logged', 'exact', () => stalled.promise) - const stuckRejected = expect(stuck).rejects.toMatchObject({ code: 'timeout' }) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS * 3) - await stuckRejected - expect(warnSpy).toHaveBeenCalledOnce() - expect(warnSpy.mock.calls[0][0]).toContain('exact') - expect(warnSpy.mock.calls[0][0]).toContain('logged') - } finally { - stalled.resolve('late') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) - - it('does not mark a scan permit stuck before the scan deadline', async () => { - vi.useFakeTimers() - const exactWork = deferred() - const scanWork = deferred() - try { - const exact = run( - '\\\\wsl.localhost\\Ubuntu\\stalled-exact', - 'exact', - () => exactWork.promise - ) - const scanTask = vi.fn(() => scanWork.promise) - const scanPath = '\\\\wsl.localhost\\Debian\\healthy-scan' - const scan = run(scanPath, 'scan', scanTask) - const exactRejected = expect(exact).rejects.toMatchObject({ code: 'timeout' }) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS) - await exactRejected - const duplicateTask = vi.fn(async () => 'duplicate') - const duplicate = run(scanPath, 'scan', duplicateTask) - - scanWork.resolve('scan') - await expect(Promise.all([scan, duplicate])).resolves.toEqual(['scan', 'scan']) - expect(scanTask).toHaveBeenCalledOnce() - expect(duplicateTask).not.toHaveBeenCalled() - } finally { - exactWork.resolve('late') - scanWork.resolve('scan') - await vi.advanceTimersByTimeAsync(0) - vi.useRealTimers() - } - }) -}) - -describe('WSL transcript filesystem task coalescing opt-out', () => { - const READ_PATH = '\\\\wsl.localhost\\Alpine\\home\\ada\\transcript.jsonl' - - function gatedRead(task: (signal: AbortSignal) => Promise): Promise { - return runWslTranscriptFsTask( - { operation: 'read', path: READ_PATH, priority: 'exact', dedupe: false }, - task - ) - } - - it('fills each caller its own buffer for identical positional reads', async () => { - const first = Buffer.alloc(4, 0xa1) - const second = Buffer.alloc(4, 0xb2) - const bodies = [Buffer.from('AAAA'), Buffer.from('BBBB')] - - const reads = Promise.all([ - gatedRead(async () => { - bodies.shift()!.copy(first) - return first - }), - gatedRead(async () => { - bodies.shift()!.copy(second) - return second - }) - ]) - - await expect(reads).resolves.toEqual([first, second]) - expect(first.toString()).toBe('AAAA') - expect(second.toString()).toBe('BBBB') - expect(first.equals(second)).toBe(false) - }) - - it('gives each open call a distinct handle', async () => { - const handles = [ - { id: 1, closed: false }, - { id: 2, closed: false } - ] - let served = 0 - const opened = await Promise.all( - handles.map(() => - runWslTranscriptFsTask( - { operation: 'open', path: READ_PATH, priority: 'exact', dedupe: false }, - async () => handles[served++] - ) - ) - ) - - expect(opened[0]).not.toBe(opened[1]) - opened[0].closed = true - expect(opened[1].closed).toBe(false) - }) - - it('still coalesces identical work when dedupe is omitted', async () => { - const stalled = deferred() - const task = vi.fn(() => stalled.promise) - const path = '\\\\wsl.localhost\\Alpine\\home\\ada' - const first = run(path, 'scan', task) - await vi.waitFor(() => expect(task).toHaveBeenCalledOnce()) - const joiner = run( - path, - 'scan', - vi.fn(async () => 'never') - ) - - stalled.resolve('shared') - await expect(Promise.all([first, joiner])).resolves.toEqual(['shared', 'shared']) - expect(task).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/native-chat/wsl-transcript-fs-process-client.test.ts b/src/main/native-chat/wsl-transcript-fs-process-client.test.ts deleted file mode 100644 index b898c5bdb76..00000000000 --- a/src/main/native-chat/wsl-transcript-fs-process-client.test.ts +++ /dev/null @@ -1,501 +0,0 @@ -import { EventEmitter } from 'node:events' -import type { ChildProcess } from 'node:child_process' -import type { Dirent, Stats } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { WslTranscriptFsProcessClient } from './wsl-transcript-fs-process-client' -import { - WSL_TRANSCRIPT_FS_PROCESS_CLOSE_TIMEOUT_MS, - WSL_TRANSCRIPT_FS_PROCESS_IDLE_REAP_MS -} from './wsl-transcript-fs-process-slot' -import { - resolveWslTranscriptFsProcessEntryPath, - wslTranscriptFsProcessForkEnv -} from './wsl-transcript-fs-process-spawn' -import type { - WslTranscriptFsProcessRequest, - WslTranscriptFsProcessResponse -} from './wsl-transcript-fs-process-protocol' - -class FakeProcess extends EventEmitter { - readonly sent: WslTranscriptFsProcessRequest[] = [] - readonly kill = vi.fn(() => true) - readonly unref = vi.fn() - readonly channel = { unref: vi.fn() } - - send(message: WslTranscriptFsProcessRequest, callback?: (error: Error | null) => void): boolean { - this.sent.push(message) - callback?.(null) - return true - } - - respond(response: WslTranscriptFsProcessResponse): void { - this.emit('message', response) - } -} - -function fakeChild(process: FakeProcess): ChildProcess { - return process as unknown as ChildProcess -} - -describe('WSL transcript filesystem process client', () => { - it('reuses a healthy process for sequential operations', async () => { - const child = new FakeProcess() - const factory = vi.fn(() => fakeChild(child)) - const client = new WslTranscriptFsProcessClient(factory) - - const first = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\one' }, - new AbortController().signal - ) - child.respond({ id: child.sent[0].id, ok: true, value: true }) - await expect(first).resolves.toBe(true) - - const second = client.run( - { - operation: 'readfile', - path: '\\\\wsl.localhost\\Ubuntu\\two', - encoding: 'utf8' - }, - new AbortController().signal - ) - child.respond({ id: child.sent[1].id, ok: true, value: 'body' }) - - await expect(second).resolves.toBe('body') - expect(factory).toHaveBeenCalledOnce() - expect(child.kill).not.toHaveBeenCalled() - client.dispose() - }) - - it('kills an aborted process and uses a replacement for later work', async () => { - const firstChild = new FakeProcess() - const replacement = new FakeProcess() - const factory = vi - .fn<() => ChildProcess>() - .mockReturnValueOnce(fakeChild(firstChild)) - .mockReturnValueOnce(fakeChild(replacement)) - const client = new WslTranscriptFsProcessClient(factory) - const controller = new AbortController() - const reason = new Error('deadline expired') - - const stalled = client.run( - { operation: 'stat', path: '\\\\wsl.localhost\\Ubuntu\\stalled' }, - controller.signal - ) - controller.abort(reason) - - await expect(stalled).rejects.toBe(reason) - expect(firstChild.kill).toHaveBeenCalledWith('SIGKILL') - - const later = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Fedora\\later' }, - new AbortController().signal - ) - replacement.respond({ id: replacement.sent[0].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - expect(factory).toHaveBeenCalledTimes(2) - client.dispose() - }) - - it('multiplexes sequential opened handles through one process until close', async () => { - const owner = new FakeProcess() - const factory = vi.fn(() => fakeChild(owner)) - const client = new WslTranscriptFsProcessClient(factory) - const signal = new AbortController().signal - - const opening = client.open('\\\\wsl.localhost\\Ubuntu\\transcript', signal) - owner.respond({ id: owner.sent[0].id, ok: true, value: 41 }) - const handle = await opening - - const secondOpening = client.open('\\\\wsl.localhost\\Ubuntu\\second', signal) - owner.respond({ id: owner.sent[1].id, ok: true, value: 42 }) - const secondHandle = await secondOpening - - const reading = client.read(handle, 8, 4, signal) - expect(owner.sent[2]).toMatchObject({ operation: 'read', handleId: 41, position: 8 }) - owner.respond({ id: owner.sent[2].id, ok: true, value: Buffer.from('old!') }) - await expect(reading).resolves.toEqual(Buffer.from('old!')) - - const secondReading = client.read(secondHandle, 0, 3, signal) - expect(owner.sent[3]).toMatchObject({ operation: 'read', handleId: 42, position: 0 }) - owner.respond({ id: owner.sent[3].id, ok: true, value: Buffer.from('new') }) - await expect(secondReading).resolves.toEqual(Buffer.from('new')) - - const closing = client.close(handle) - expect(owner.sent[4]).toMatchObject({ operation: 'close', handleId: 41 }) - owner.respond({ id: owner.sent[4].id, ok: true, value: true }) - await expect(closing).resolves.toBeUndefined() - - const secondClosing = client.close(secondHandle) - expect(owner.sent[5]).toMatchObject({ operation: 'close', handleId: 42 }) - owner.respond({ id: owner.sent[5].id, ok: true, value: true }) - await expect(secondClosing).resolves.toBeUndefined() - - const later = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\later' }, - signal - ) - owner.respond({ id: owner.sent[6].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - expect(factory).toHaveBeenCalledOnce() - client.dispose() - }) - - it('queues concurrent opens instead of creating another helper', async () => { - const child = new FakeProcess() - const factory = vi.fn(() => fakeChild(child)) - const client = new WslTranscriptFsProcessClient(factory) - const signal = new AbortController().signal - - const firstOpening = client.open('\\\\wsl.localhost\\Ubuntu\\first', signal) - const secondOpening = client.open('\\\\wsl.localhost\\Ubuntu\\second', signal) - expect(factory).toHaveBeenCalledOnce() - expect(child.sent).toHaveLength(1) - - child.respond({ id: child.sent[0].id, ok: true, value: 1 }) - const firstHandle = await firstOpening - await vi.waitFor(() => expect(child.sent).toHaveLength(2)) - child.respond({ id: child.sent[1].id, ok: true, value: 2 }) - const secondHandle = await secondOpening - - const firstClose = client.close(firstHandle) - child.respond({ id: child.sent[2].id, ok: true, value: true }) - await firstClose - const secondClose = client.close(secondHandle) - child.respond({ id: child.sent[3].id, ok: true, value: true }) - await secondClose - - expect(factory).toHaveBeenCalledOnce() - client.dispose() - }) - - it('returns a granted slot when its queued caller aborts before sending', async () => { - const child = new FakeProcess() - const client = new WslTranscriptFsProcessClient(() => fakeChild(child)) - const controller = new AbortController() - const signal = new AbortController().signal - - const first = client.run({ operation: 'access', path: 'first' }, signal) - const aborted = client.run({ operation: 'access', path: 'aborted' }, controller.signal) - child.respond({ id: child.sent[0].id, ok: true, value: true }) - controller.abort(new Error('cancelled after grant')) - - await expect(first).resolves.toBe(true) - await expect(aborted).rejects.toThrow('cancelled after grant') - const later = client.run({ operation: 'access', path: 'later' }, signal) - expect(child.sent).toHaveLength(2) - child.respond({ id: child.sent[1].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - client.dispose() - }) - - it('rejects a granted request if the helper exits before it sends', async () => { - const child = new FakeProcess() - const replacement = new FakeProcess() - const factory = vi - .fn<() => ChildProcess>() - .mockReturnValueOnce(fakeChild(child)) - .mockReturnValueOnce(fakeChild(replacement)) - const client = new WslTranscriptFsProcessClient(factory) - const signal = new AbortController().signal - - const first = client.run({ operation: 'access', path: 'first' }, signal) - const stranded = client.run({ operation: 'access', path: 'stranded' }, signal) - child.respond({ id: child.sent[0].id, ok: true, value: true }) - child.emit('disconnect') - - await expect(first).resolves.toBe(true) - await expect(stranded).rejects.toMatchObject({ code: 'unavailable' }) - expect(replacement.sent).toHaveLength(0) - client.dispose() - }) - - it('defers a close issued while a read is in flight instead of stranding the slot', async () => { - const owner = new FakeProcess() - const factory = vi.fn(() => fakeChild(owner)) - const client = new WslTranscriptFsProcessClient(factory) - const signal = new AbortController().signal - - const opening = client.open('\\\\wsl.localhost\\Ubuntu\\transcript', signal) - owner.respond({ id: owner.sent[0].id, ok: true, value: 5 }) - const handle = await opening - - const reading = client.read(handle, 0, 4, signal) - const closing = client.close(handle) - expect(owner.sent).toHaveLength(2) - - owner.respond({ id: owner.sent[1].id, ok: true, value: Buffer.from('data') }) - await expect(reading).resolves.toEqual(Buffer.from('data')) - await vi.waitFor(() => expect(owner.sent).toHaveLength(3)) - expect(owner.sent[2]).toMatchObject({ operation: 'close', handleId: 5 }) - owner.respond({ id: owner.sent[2].id, ok: true, value: true }) - await expect(closing).resolves.toBeUndefined() - - const later = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\after-close' }, - signal - ) - owner.respond({ id: owner.sent[3].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - expect(factory).toHaveBeenCalledOnce() - expect(owner.kill).not.toHaveBeenCalled() - client.dispose() - }) - - it('invalidates lane handles and serves queued work from a replacement', async () => { - const owner = new FakeProcess() - const healthy = new FakeProcess() - const factory = vi - .fn<() => ChildProcess>() - .mockReturnValueOnce(fakeChild(owner)) - .mockReturnValueOnce(fakeChild(healthy)) - const client = new WslTranscriptFsProcessClient(factory) - const opening = client.open( - '\\\\wsl.localhost\\Ubuntu\\transcript', - new AbortController().signal - ) - owner.respond({ id: owner.sent[0].id, ok: true, value: 9 }) - const handle = await opening - const controller = new AbortController() - const reason = new Error('read deadline') - - const stalled = client.read(handle, 0, 1, controller.signal) - const other = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Fedora\\healthy' }, - new AbortController().signal - ) - controller.abort(reason) - - await expect(stalled).rejects.toBe(reason) - await vi.waitFor(() => expect(healthy.sent).toHaveLength(1)) - healthy.respond({ id: healthy.sent[0].id, ok: true, value: true }) - await expect(other).resolves.toBe(true) - // Handles die with the helper; report retryable transport failure rather than caller EBADF. - await expect(client.read(handle, 0, 1, new AbortController().signal)).rejects.toMatchObject({ - name: 'WslTranscriptFsError', - code: 'unavailable' - }) - expect(owner.kill).toHaveBeenCalledWith('SIGKILL') - expect(healthy.kill).not.toHaveBeenCalled() - - const later = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Fedora\\later' }, - new AbortController().signal - ) - healthy.respond({ id: healthy.sent[1].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - client.dispose() - }) - - it('retires a process whose handle close does not settle', async () => { - vi.useFakeTimers() - const owner = new FakeProcess() - const healthy = new FakeProcess() - const factory = vi - .fn<() => ChildProcess>() - .mockReturnValueOnce(fakeChild(owner)) - .mockReturnValueOnce(fakeChild(healthy)) - const client = new WslTranscriptFsProcessClient(factory) - try { - const opening = client.open( - '\\\\wsl.localhost\\Ubuntu\\transcript', - new AbortController().signal - ) - owner.respond({ id: owner.sent[0].id, ok: true, value: 12 }) - const handle = await opening - const closing = client.close(handle) - const closeFailure = expect(closing).rejects.toThrow('close timed out') - - const unrelated = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Fedora\\healthy' }, - new AbortController().signal - ) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_PROCESS_CLOSE_TIMEOUT_MS) - await closeFailure - await vi.waitFor(() => expect(healthy.sent).toHaveLength(1)) - healthy.respond({ id: healthy.sent[0].id, ok: true, value: true }) - await expect(unrelated).resolves.toBe(true) - expect(owner.kill).toHaveBeenCalledWith('SIGKILL') - expect(healthy.kill).not.toHaveBeenCalled() - } finally { - client.dispose() - vi.useRealTimers() - } - }) - - it('reaps an idle process after the idle deadline and forks a fresh one later', async () => { - vi.useFakeTimers() - const child = new FakeProcess() - const replacement = new FakeProcess() - const factory = vi - .fn<() => ChildProcess>() - .mockReturnValueOnce(fakeChild(child)) - .mockReturnValueOnce(fakeChild(replacement)) - const client = new WslTranscriptFsProcessClient(factory) - try { - const first = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\one' }, - new AbortController().signal - ) - child.respond({ id: child.sent[0].id, ok: true, value: true }) - await expect(first).resolves.toBe(true) - - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_PROCESS_IDLE_REAP_MS) - expect(child.kill).toHaveBeenCalledWith('SIGKILL') - - const later = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\two' }, - new AbortController().signal - ) - replacement.respond({ id: replacement.sent[0].id, ok: true, value: true }) - await expect(later).resolves.toBe(true) - expect(factory).toHaveBeenCalledTimes(2) - } finally { - client.dispose() - vi.useRealTimers() - } - }) - - it('surfaces child transport faults as unavailable gate refusals', async () => { - const child = new FakeProcess() - const client = new WslTranscriptFsProcessClient(() => fakeChild(child)) - const pending = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\dead' }, - new AbortController().signal - ) - child.emit('exit', 9) - await expect(pending).rejects.toMatchObject({ - name: 'WslTranscriptFsError', - code: 'unavailable' - }) - client.dispose() - }) - - it('names the killing signal instead of a null exit code', async () => { - const child = new FakeProcess() - const client = new WslTranscriptFsProcessClient(() => fakeChild(child)) - const pending = client.run( - { operation: 'access', path: '\\\\wsl.localhost\\Ubuntu\\killed' }, - new AbortController().signal - ) - child.emit('exit', null, 'SIGKILL') - await expect(pending).rejects.toMatchObject({ - name: 'WslTranscriptFsError', - code: 'unavailable', - message: expect.stringContaining('exited (SIGKILL)') - }) - client.dispose() - }) - - it('reconstructs filesystem errors with their Node error code', async () => { - const child = new FakeProcess() - const client = new WslTranscriptFsProcessClient(() => fakeChild(child)) - const pending = client.run( - { operation: 'stat', path: '\\\\wsl.localhost\\Ubuntu\\missing' }, - new AbortController().signal - ) - - child.respond({ - id: child.sent[0].id, - ok: false, - error: { - name: 'Error', - message: 'not found', - code: 'ENOENT', - syscall: 'stat', - path: '\\\\wsl.localhost\\Ubuntu\\missing' - } - }) - - await expect(pending).rejects.toMatchObject({ - message: 'not found', - code: 'ENOENT', - syscall: 'stat' - }) - client.dispose() - }) - - it('restores Stats and Dirent methods after IPC serialization', async () => { - const child = new FakeProcess() - const client = new WslTranscriptFsProcessClient(() => fakeChild(child)) - const stats = client.run( - { operation: 'stat', path: '\\\\wsl.localhost\\Ubuntu\\file' }, - new AbortController().signal - ) - child.respond({ - id: child.sent[0].id, - ok: true, - value: { mode: 0o100644, size: 12, mtime: new Date(0) } - }) - - expect((await stats).isFile()).toBe(true) - - const entries = client.run( - { operation: 'readdir', path: '\\\\wsl.localhost\\Ubuntu\\dir' }, - new AbortController().signal - ) - child.respond({ - id: child.sent[1].id, - ok: true, - value: [ - { - name: 'child', - parentPath: '\\\\wsl.localhost\\Ubuntu\\dir', - isBlockDevice: false, - isCharacterDevice: false, - isDirectory: false, - isFIFO: false, - isFile: true, - isSocket: false, - isSymbolicLink: false - } - ] - }) - - expect((await entries)[0].isFile()).toBe(true) - client.dispose() - }) -}) - -describe('WSL transcript filesystem process entry resolution', () => { - it('prefers the unpacked sibling for a packaged main bundle', () => { - const exists = vi.fn((path: string) => path.includes('app.asar.unpacked')) - const moduleDir = join('root', 'resources', 'app.asar', 'out', 'main') - - expect( - resolveWslTranscriptFsProcessEntryPath(moduleDir, join('root', 'resources'), exists) - ).toBe( - join(moduleDir.replace('app.asar', 'app.asar.unpacked'), 'wsl-transcript-fs-process-entry.js') - ) - }) - - // Bundled shared chunks sit below out/main; scanner children lack resourcesPath fallback. - it('resolves the entry from a shared chunk one level below out/main', () => { - const moduleDir = join('root', 'out', 'main', 'chunks') - const target = join('root', 'out', 'main', 'wsl-transcript-fs-process-entry.js') - const exists = vi.fn((path: string) => path === target) - - expect(resolveWslTranscriptFsProcessEntryPath(moduleDir, undefined, exists)).toBe(target) - }) - - it('excludes ambient NODE_OPTIONS and secrets from the fork env', () => { - const env = wslTranscriptFsProcessForkEnv( - { - PATH: 'C:\\bin', - SYSTEMROOT: 'C:\\WINDOWS', - NODE_OPTIONS: '--inspect-brk', - SECRET_TOKEN: 'shh' - }, - 'win32' - ) - - expect(env).toMatchObject({ - ELECTRON_RUN_AS_NODE: '1', - PATH: 'C:\\bin', - SystemRoot: 'C:\\WINDOWS' - }) - expect(env).not.toHaveProperty('NODE_OPTIONS') - expect(env).not.toHaveProperty('SECRET_TOKEN') - }) -}) diff --git a/src/main/network/proxy-settings-session.test.ts b/src/main/network/proxy-settings-session.test.ts deleted file mode 100644 index 22214aa620d..00000000000 --- a/src/main/network/proxy-settings-session.test.ts +++ /dev/null @@ -1,555 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { defaultSessionMock } = vi.hoisted(() => ({ - defaultSessionMock: { - resolveProxy: vi.fn(async () => 'DIRECT'), - setProxy: vi.fn(async () => {}) - } -})) - -vi.mock('electron', () => ({ - session: { - defaultSession: defaultSessionMock - } -})) - -import { - applyProxySettingsToSession, - awaitProxySessionApplication, - releaseProxySessionApplication, - retireProxySessionApplication, - resetSessionProxyApplicationForTests -} from './proxy-settings' -import { handleElectronProxyLogin } from './electron-proxy-credentials' - -function createProxySession() { - return { - resolveProxy: vi.fn(async () => 'DIRECT'), - setProxy: vi.fn( - async (_config: { - mode?: 'system' | 'fixed_servers' - proxyRules?: string - proxyBypassRules?: string - }) => {} - ), - closeAllConnections: vi.fn(async () => {}) - } -} - -describe('applyProxySettingsToSession', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('pins the configured proxy onto a non-default session', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await expect( - applyProxySettingsToSession( - proxySession, - { - httpProxyUrl: ' socks5://127.0.0.1:1080/ ', - httpProxyBypassRules: 'localhost, *.internal' - }, - { env: {} } - ) - ).resolves.toEqual({ - source: 'settings', - proxyRules: 'socks5://127.0.0.1:1080', - proxyBypassRules: 'localhost;*.internal' - }) - - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'socks5://127.0.0.1:1080', - proxyBypassRules: 'localhost;*.internal' - }) - expect(proxySession.closeAllConnections).toHaveBeenCalledTimes(1) - }) - - it('does not touch defaultSession when applying to another session', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' }, - { env: {} } - ) - - expect(defaultSessionMock.setProxy).not.toHaveBeenCalled() - }) - - it('tracks applied config per session, so one session does not suppress another', async () => { - const first = createProxySession() - const second = createProxySession() - resetSessionProxyApplicationForTests(first) - resetSessionProxyApplicationForTests(second) - const settings = { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' } - - await applyProxySettingsToSession(first, settings, { env: {} }) - await applyProxySettingsToSession(second, settings, { env: {} }) - - expect(first.setProxy).toHaveBeenCalledTimes(1) - expect(second.setProxy).toHaveBeenCalledTimes(1) - }) - - it('skips a redundant write when the same config is re-applied', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - const settings = { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' } - - await applyProxySettingsToSession(proxySession, settings, { env: {} }) - await applyProxySettingsToSession(proxySession, settings, { env: {} }) - - expect(proxySession.setProxy).toHaveBeenCalledTimes(1) - }) - - it('refreshes in-memory authentication when only proxy credentials change', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://alice:old-secret@proxy.example:8080' }, - { env: {} } - ) - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://alice:new-secret@proxy.example:8080' }, - { env: {} } - ) - - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://proxy.example:8080' }], - [{ mode: 'fixed_servers', proxyRules: 'http://proxy.example:8080' }] - ]) - const callback = vi.fn() - handleElectronProxyLogin( - { preventDefault: vi.fn() } as never, - { session: proxySession } as never, - {} as never, - { - isProxy: true, - scheme: 'basic', - host: 'proxy.example', - port: 8080, - realm: 'proxy' - }, - callback - ) - expect(callback).toHaveBeenCalledWith('alice', 'new-secret') - }) - - it('coalesces concurrent writes of the same config', async () => { - let finishWrite: (() => void) | undefined - const proxySession = createProxySession() - proxySession.setProxy.mockImplementation( - () => new Promise((resolve) => (finishWrite = resolve)) - ) - resetSessionProxyApplicationForTests(proxySession) - const settings = { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' } - - const first = applyProxySettingsToSession(proxySession, settings, { env: {} }) - const second = applyProxySettingsToSession(proxySession, settings, { env: {} }) - - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(1)) - finishWrite?.() - await Promise.all([first, second]) - expect(proxySession.setProxy).toHaveBeenCalledTimes(1) - }) - - it('serializes config changes so an older write cannot finish last', async () => { - let finishFirstWrite: (() => void) | undefined - let effectiveProxy: string | undefined - const proxySession = createProxySession() - proxySession.setProxy - .mockImplementationOnce( - (config) => - new Promise((resolve) => { - finishFirstWrite = () => { - effectiveProxy = config.proxyRules - resolve() - } - }) - ) - .mockImplementationOnce(async (config) => { - effectiveProxy = config.proxyRules - }) - resetSessionProxyApplicationForTests(proxySession) - - const first = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://old.example:8080', httpProxyBypassRules: '' }, - { env: {} } - ) - const second = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://new.example:8080', httpProxyBypassRules: '' }, - { env: {} } - ) - - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(1)) - finishFirstWrite?.() - await Promise.all([first, second]) - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://old.example:8080' }], - [{ mode: 'fixed_servers', proxyRules: 'http://new.example:8080' }] - ]) - expect(effectiveProxy).toBe('http://new.example:8080') - }) - - it('holds request readiness until the newest queued policy settles', async () => { - let finishFirstWrite: (() => void) | undefined - let finishSecondWrite: (() => void) | undefined - const proxySession = createProxySession() - proxySession.setProxy - .mockImplementationOnce(() => new Promise((resolve) => (finishFirstWrite = resolve))) - .mockImplementationOnce(() => new Promise((resolve) => (finishSecondWrite = resolve))) - resetSessionProxyApplicationForTests(proxySession) - - const first = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://old.example:8080' }, - { env: {} } - ) - const second = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://new.example:8080' }, - { env: {} } - ) - let requestReleased = false - const readiness = awaitProxySessionApplication(proxySession).then((ready) => { - requestReleased = true - return ready - }) - - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(1)) - expect(requestReleased).toBe(false) - finishFirstWrite?.() - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(2)) - expect(requestReleased).toBe(false) - finishSecondWrite?.() - - await expect(readiness).resolves.toBe(true) - await Promise.all([first, second]) - }) - - it('keeps request readiness closed after proxy application fails', async () => { - const proxySession = createProxySession() - proxySession.setProxy.mockRejectedValue(new Error('proxy apply failed')) - resetSessionProxyApplicationForTests(proxySession) - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://proxy.example:8080' }, - { env: {} } - ) - ).rejects.toThrow('proxy apply failed') - - await expect(awaitProxySessionApplication(proxySession)).resolves.toBe(false) - }) - - it('keeps a deleted partition retired while its proxy release settles', async () => { - let finishClose: (() => void) | undefined - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://proxy.example:8080' }, - { env: {} } - ) - proxySession.closeAllConnections.mockImplementationOnce( - () => new Promise((resolve) => (finishClose = resolve)) - ) - - const retirement = retireProxySessionApplication(proxySession) - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledWith({ mode: 'system' })) - await expect(awaitProxySessionApplication(proxySession)).resolves.toBe(false) - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://later.example:8080' }, - { env: {} } - ) - ).rejects.toThrow('retired') - - finishClose?.() - await retirement - await expect(awaitProxySessionApplication(proxySession)).resolves.toBe(false) - }) - - it('forgets credentials when a retired partition cannot release its proxy', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://alice:secret@proxy.example:8080' }, - { env: {} } - ) - proxySession.setProxy.mockRejectedValue(new Error('proxy release failed')) - - await expect(retireProxySessionApplication(proxySession)).rejects.toThrow( - 'proxy release failed' - ) - const callback = vi.fn() - handleElectronProxyLogin( - { preventDefault: vi.fn() } as never, - { session: proxySession } as never, - {} as never, - { isProxy: true, host: 'proxy.example', port: 8080 }, - callback - ) - - expect(callback).not.toHaveBeenCalled() - }) - - it('orders a slow environment probe before a newer explicit setting', async () => { - let finishProbe: ((result: string) => void) | undefined - const proxySession = createProxySession() - proxySession.resolveProxy.mockImplementation( - () => new Promise((resolve) => (finishProbe = resolve)) - ) - resetSessionProxyApplicationForTests(proxySession) - - const environment = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: { HTTP_PROXY: 'http://env.example:8080' } } - ) - const explicit = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://configured.example:8080', httpProxyBypassRules: '' }, - { env: {} } - ) - - await vi.waitFor(() => expect(proxySession.resolveProxy).toHaveBeenCalledTimes(1)) - expect(proxySession.setProxy).not.toHaveBeenCalled() - finishProbe?.('DIRECT') - await Promise.all([environment, explicit]) - - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://env.example:8080' }], - [{ mode: 'fixed_servers', proxyRules: 'http://configured.example:8080' }] - ]) - }) - - it('falls back to the environment proxy when no proxy is configured', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: { HTTPS_PROXY: 'http://env.example:8080', NO_PROXY: 'localhost' } } - ) - ).resolves.toEqual({ - source: 'env', - proxyRules: 'http://env.example:8080', - proxyBypassRules: 'localhost' - }) - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'http://env.example:8080', - proxyBypassRules: 'localhost' - }) - }) - - it('releases a pin before probing for a system proxy', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - const env = { HTTPS_PROXY: 'http://env.example:8080' } - - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' }, - { env } - ) - proxySession.setProxy.mockClear() - proxySession.resolveProxy.mockResolvedValue('PROXY system.example:8080') - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env } - ) - ).resolves.toEqual({ source: 'system' }) - - expect(proxySession.setProxy).toHaveBeenCalledOnce() - expect(proxySession.setProxy).toHaveBeenCalledWith({ mode: 'system' }) - }) - - it('re-applies a pin after its release drops connections unsuccessfully', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - const settings = { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' } - - await applyProxySettingsToSession(proxySession, settings, { env: {} }) - proxySession.closeAllConnections - .mockRejectedValueOnce(new Error('close failed')) - .mockRejectedValueOnce(new Error('close failed')) - .mockRejectedValueOnce(new Error('close failed')) - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: {} } - ) - ).rejects.toThrow('close failed') - - proxySession.setProxy.mockClear() - await applyProxySettingsToSession(proxySession, settings, { env: {} }) - - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'socks5://127.0.0.1:1080' - }) - }) - - it('retries stale connection cleanup before a cleared proxy becomes ready', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' }, - { env: {} } - ) - proxySession.closeAllConnections.mockRejectedValueOnce(new Error('close failed')) - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: {} } - ) - ).resolves.toEqual({ source: 'none' }) - - expect(proxySession.setProxy.mock.calls.slice(-2)).toEqual([ - [{ mode: 'system' }], - [{ mode: 'system' }] - ]) - expect(proxySession.closeAllConnections).toHaveBeenCalledTimes(3) - await expect(awaitProxySessionApplication(proxySession)).resolves.toBe(true) - }) - - it('fails closed after all bounded proxy application attempts reject', async () => { - const proxySession = createProxySession() - proxySession.setProxy.mockRejectedValue(new Error('proxy apply failed')) - resetSessionProxyApplicationForTests(proxySession) - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://proxy.example:8080' }, - { env: {} } - ) - ).rejects.toThrow('proxy apply failed') - - expect(proxySession.setProxy).toHaveBeenCalledTimes(3) - await expect(awaitProxySessionApplication(proxySession)).resolves.toBe(false) - }) - - it('releases a previously pinned session back to the system proxy when settings are cleared', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'socks5://127.0.0.1:1080', httpProxyBypassRules: '' }, - { env: {} } - ) - proxySession.setProxy.mockClear() - - await expect( - applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: {} } - ) - ).resolves.toEqual({ source: 'none' }) - expect(proxySession.setProxy).toHaveBeenCalledWith({ mode: 'system' }) - }) - - it('forgets authentication when a session returns to the system proxy', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://alice:secret@proxy.example:8080' }, - { env: {} } - ) - await applyProxySettingsToSession(proxySession, { httpProxyUrl: '' }, { env: {} }) - - const callback = vi.fn() - handleElectronProxyLogin( - { preventDefault: vi.fn() } as never, - { session: proxySession } as never, - {} as never, - { - isProxy: true, - scheme: 'basic', - host: 'proxy.example', - port: 8080, - realm: 'proxy' - }, - callback - ) - expect(callback).not.toHaveBeenCalled() - }) - - it('releases a removed session through the ordered proxy queue', async () => { - let finishWrite: (() => void) | undefined - const proxySession = createProxySession() - proxySession.setProxy.mockImplementationOnce( - () => new Promise((resolve) => (finishWrite = resolve)) - ) - resetSessionProxyApplicationForTests(proxySession) - - const applying = applyProxySettingsToSession( - proxySession, - { httpProxyUrl: 'http://alice:secret@proxy.example:8080' }, - { env: {} } - ) - const releasing = releaseProxySessionApplication(proxySession) - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(1)) - finishWrite?.() - await Promise.all([applying, releasing]) - - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://proxy.example:8080' }], - [{ mode: 'system' }] - ]) - const callback = vi.fn() - handleElectronProxyLogin( - { preventDefault: vi.fn() } as never, - { session: proxySession } as never, - {} as never, - { - isProxy: true, - scheme: 'basic', - host: 'proxy.example', - port: 8080, - realm: 'proxy' - }, - callback - ) - expect(callback).not.toHaveBeenCalled() - }) - - it('leaves an untouched session alone when nothing is configured', async () => { - const proxySession = createProxySession() - resetSessionProxyApplicationForTests(proxySession) - - await applyProxySettingsToSession( - proxySession, - { httpProxyUrl: '', httpProxyBypassRules: '' }, - { env: {} } - ) - - expect(proxySession.setProxy).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/network/proxy-settings.test.ts b/src/main/network/proxy-settings.test.ts deleted file mode 100644 index 9912d64c5ad..00000000000 --- a/src/main/network/proxy-settings.test.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { defaultSessionMock } = vi.hoisted(() => ({ - defaultSessionMock: { - resolveProxy: vi.fn(async () => 'DIRECT'), - setProxy: vi.fn(async () => {}) - } -})) - -vi.mock('electron', () => ({ - session: { - defaultSession: defaultSessionMock - } -})) - -import { - applyElectronProxySettings, - ensureElectronProxyFromEnvironment, - resetProxyApplicationForTests, - setDefaultProxySessionResolver -} from './proxy-settings' -import { handleElectronProxyLogin } from './electron-proxy-credentials' - -function createProxySession(resolveProxy = 'DIRECT') { - return { - resolveProxy: vi.fn(async () => resolveProxy), - setProxy: vi.fn( - async (_config: { - mode?: 'system' | 'fixed_servers' - proxyRules?: string - proxyBypassRules?: string - }) => {} - ), - closeAllConnections: vi.fn(async () => {}) - } -} - -describe('Electron proxy settings', () => { - beforeEach(() => { - resetProxyApplicationForTests() - setDefaultProxySessionResolver(() => defaultSessionMock) - }) - - it('resolves proxy policy without a Chromium session on Node hosts', async () => { - setDefaultProxySessionResolver(null) - - await expect( - applyElectronProxySettings( - { - httpProxyUrl: 'http://user:pass@proxy.example:8080', - httpProxyBypassRules: 'localhost,*.internal' - }, - { env: { HTTP_PROXY: 'http://env.example:8080' } } - ) - ).resolves.toEqual({ - source: 'settings', - proxyRules: 'http://proxy.example:8080', - proxyBypassRules: 'localhost;*.internal' - }) - await expect( - applyElectronProxySettings({}, { env: { HTTP_PROXY: 'http://env.example:8080' } }) - ).resolves.toEqual({ source: 'env', proxyRules: 'http://env.example:8080' }) - expect(defaultSessionMock.setProxy).not.toHaveBeenCalled() - }) - - it('applies explicit settings before env fallback', async () => { - const proxySession = createProxySession('PROXY system.example:8080') - - await expect( - applyElectronProxySettings( - { - httpProxyUrl: ' http://user:pass@proxy.example:8080/path#token ', - httpProxyBypassRules: 'localhost, *.internal' - }, - { - proxySession, - env: { HTTPS_PROXY: 'http://env.example:8080' } - } - ) - ).resolves.toEqual({ - source: 'settings', - proxyRules: 'http://proxy.example:8080', - proxyBypassRules: 'localhost;*.internal' - }) - - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'http://proxy.example:8080', - proxyBypassRules: 'localhost;*.internal' - }) - expect(proxySession.resolveProxy).not.toHaveBeenCalled() - expect(proxySession.closeAllConnections).toHaveBeenCalledTimes(1) - }) - - it('serializes default-session transitions so the newest setting wins', async () => { - let finishFirstWrite: (() => void) | undefined - let effectiveProxy = '' - const proxySession = createProxySession() - proxySession.setProxy - .mockImplementationOnce( - (config) => - new Promise((resolve) => { - finishFirstWrite = () => { - effectiveProxy = config.proxyRules ?? '' - resolve() - } - }) - ) - .mockImplementationOnce(async (config) => { - effectiveProxy = config.proxyRules ?? '' - }) - - const first = applyElectronProxySettings( - { httpProxyUrl: 'http://old.example:8080' }, - { proxySession, env: {} } - ) - const second = applyElectronProxySettings( - { httpProxyUrl: 'http://new.example:8080' }, - { proxySession, env: {} } - ) - - await vi.waitFor(() => expect(proxySession.setProxy).toHaveBeenCalledTimes(1)) - finishFirstWrite?.() - await Promise.all([first, second]) - - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://old.example:8080' }], - [{ mode: 'fixed_servers', proxyRules: 'http://new.example:8080' }] - ]) - expect(effectiveProxy).toBe('http://new.example:8080') - }) - - it('keeps credentials out of proxy metadata and answers matching proxy auth challenges', async () => { - const proxySession = createProxySession() - const result = await applyElectronProxySettings( - { httpProxyUrl: 'http://alice:s%40fe@proxy.example:8080' }, - { proxySession, env: {} } - ) - - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'http://proxy.example:8080' - }) - expect(JSON.stringify(result)).not.toContain('alice') - expect(JSON.stringify(result)).not.toContain('s%40fe') - expect(JSON.stringify(result)).not.toContain('s@fe') - - const preventDefault = vi.fn() - const callback = vi.fn() - handleElectronProxyLogin( - { preventDefault } as never, - { session: proxySession } as never, - {} as never, - { - isProxy: true, - scheme: 'basic', - host: 'proxy.example', - port: 8080, - realm: 'proxy' - }, - callback - ) - - expect(preventDefault).toHaveBeenCalledOnce() - expect(callback).toHaveBeenCalledWith('alice', 's@fe') - }) - - it('answers proxy auth for app requests without an associated webContents', async () => { - await applyElectronProxySettings({ - httpProxyUrl: 'http://app-user:app-pass@proxy.example:8080' - }) - const preventDefault = vi.fn() - const callback = vi.fn() - - handleElectronProxyLogin( - { preventDefault } as never, - null, - {} as never, - { - isProxy: true, - scheme: 'basic', - host: 'proxy.example', - port: 8080, - realm: 'proxy' - }, - callback, - defaultSessionMock - ) - - expect(preventDefault).toHaveBeenCalledOnce() - expect(callback).toHaveBeenCalledWith('app-user', 'app-pass') - }) - - it('does not disclose proxy credentials to origin or mismatched proxy challenges', async () => { - const proxySession = createProxySession() - await applyElectronProxySettings( - { httpProxyUrl: 'http://alice:secret@proxy.example:8080' }, - { proxySession, env: {} } - ) - const preventDefault = vi.fn() - const callback = vi.fn() - - for (const authInfo of [ - { isProxy: false, host: 'proxy.example', port: 8080 }, - { isProxy: true, host: 'other.example', port: 8080 }, - { isProxy: true, host: 'proxy.example', port: 3128 } - ]) { - handleElectronProxyLogin( - { preventDefault } as never, - { session: proxySession } as never, - {} as never, - { scheme: 'basic', realm: 'proxy', ...authInfo }, - callback - ) - } - - expect(preventDefault).not.toHaveBeenCalled() - expect(callback).not.toHaveBeenCalled() - }) - - it('preserves system proxy settings when no explicit or env proxy is configured', async () => { - const proxySession = createProxySession('PROXY system.example:8080') - - await expect(applyElectronProxySettings({}, { proxySession, env: {} })).resolves.toEqual({ - source: 'system' - }) - - expect(proxySession.setProxy).not.toHaveBeenCalled() - }) - - it('preserves the system proxy ahead of environment fallback', async () => { - const proxySession = createProxySession('PROXY system.example:8080') - - await expect( - applyElectronProxySettings( - {}, - { proxySession, env: { HTTP_PROXY: 'http://env.example:8080' } } - ) - ).resolves.toEqual({ source: 'system' }) - - expect(proxySession.setProxy).not.toHaveBeenCalled() - }) - - it('bridges env proxy vars only when Chromium would otherwise go direct', async () => { - const proxySession = createProxySession('DIRECT') - - await expect( - applyElectronProxySettings( - {}, - { - proxySession, - env: { - HTTPS_PROXY: 'https://env.example:8443', - HTTP_PROXY: 'http://lower-priority.example:8080', - NO_PROXY: 'localhost,*.internal' - } - } - ) - ).resolves.toEqual({ - source: 'env', - proxyRules: 'https://env.example:8443', - proxyBypassRules: 'localhost;*.internal' - }) - - expect(proxySession.setProxy).toHaveBeenCalledWith({ - mode: 'fixed_servers', - proxyRules: 'https://env.example:8443', - proxyBypassRules: 'localhost;*.internal' - }) - }) - - it('clears a previous app proxy before returning to system/env behavior', async () => { - const proxySession = createProxySession('DIRECT') - - await applyElectronProxySettings( - { httpProxyUrl: 'http://proxy.example:8080' }, - { proxySession } - ) - await applyElectronProxySettings( - { httpProxyUrl: '' }, - { proxySession, env: { HTTP_PROXY: 'http://env.example:8080' } } - ) - - expect(proxySession.setProxy).toHaveBeenNthCalledWith(2, { mode: 'system' }) - expect(proxySession.setProxy).toHaveBeenNthCalledWith(3, { - mode: 'fixed_servers', - proxyRules: 'http://env.example:8080' - }) - }) - - it('does not let env fallback override an already-applied explicit setting', async () => { - const proxySession = createProxySession('DIRECT') - - await applyElectronProxySettings( - { httpProxyUrl: 'http://proxy.example:8080' }, - { proxySession } - ) - await ensureElectronProxyFromEnvironment({ - proxySession, - env: { HTTP_PROXY: 'http://env.example:8080' } - }) - - expect(proxySession.setProxy).toHaveBeenCalledTimes(1) - }) - - it('retries a transient connection-close failure before reporting an explicit proxy', async () => { - const proxySession = createProxySession() - proxySession.closeAllConnections.mockRejectedValueOnce(new Error('close failed')) - - await expect( - applyElectronProxySettings( - { httpProxyUrl: 'http://proxy.example:8080' }, - { proxySession, env: {} } - ) - ).resolves.toEqual({ source: 'settings', proxyRules: 'http://proxy.example:8080' }) - await expect( - ensureElectronProxyFromEnvironment({ - proxySession, - env: { HTTP_PROXY: 'http://env.example:8080' } - }) - ).resolves.toEqual({ - source: 'settings', - proxyRules: 'http://proxy.example:8080' - }) - - expect(proxySession.setProxy.mock.calls).toEqual([ - [{ mode: 'fixed_servers', proxyRules: 'http://proxy.example:8080' }], - [{ mode: 'fixed_servers', proxyRules: 'http://proxy.example:8080' }] - ]) - expect(proxySession.closeAllConnections).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/node-runtime/pinned-runtime-materializer-node.test.ts b/src/main/node-runtime/pinned-runtime-materializer-node.test.ts deleted file mode 100644 index ac04301e4a1..00000000000 --- a/src/main/node-runtime/pinned-runtime-materializer-node.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import { createHash } from 'node:crypto' -import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { runProcess } from '@orca/process-host' -import { - NODE_RUNTIME_ASSETS, - NODE_RUNTIME_PIN, - nodeRuntimeExecutablePath -} from '../../shared/node-runtime-pin' -import { materializeNodeRuntimeArchive } from './pinned-runtime-materializer' - -const TARGET = 'linux-x64-glibc' as const -const originalAsset = { ...NODE_RUNTIME_ASSETS[TARGET] } -let root = '' - -function sha256(bytes: Uint8Array): string { - return createHash('sha256').update(bytes).digest('hex') -} - -function fetcherFor(body: Uint8Array, signals: AbortSignal[] = []): typeof fetch { - return vi.fn(async (_url, options) => { - if (options?.signal) { - signals.push(options.signal) - } - return new Response(Buffer.from(body), { status: 200 }) - }) -} - -async function nodeDistArchiveFixture(executable: Uint8Array): Promise { - const staging = join(root, 'staging') - const member = nodeRuntimeExecutablePath(TARGET, NODE_RUNTIME_ASSETS[TARGET].archive) - await mkdir(join(staging, member, '..'), { recursive: true }) - await writeFile(join(staging, member), executable) - await writeFile(join(staging, member.split('/')[0]!, 'README.md'), 'not extracted') - const archivePath = join(root, 'archive.tar.gz') - const result = await runProcess({ - program: 'tar', - args: ['-czf', archivePath, '-C', staging, member.split('/')[0]!] - }) - expect(result.code, result.stderr).toBe(0) - return new Uint8Array(await readFile(archivePath)) -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-node-runtime-materializer-')) -}) - -afterEach(async () => { - Object.assign(NODE_RUNTIME_ASSETS[TARGET], originalAsset) - await rm(root, { recursive: true, force: true }) -}) - -describe.skipIf(process.platform === 'win32')('pinned Node runtime materializer', () => { - it('keeps the verified archive for upload and refetches only when it is corrupted', async () => { - const archive = await nodeDistArchiveFixture(new TextEncoder().encode('node')) - Object.assign(NODE_RUNTIME_ASSETS[TARGET], { archiveSha256: sha256(archive) }) - const cacheRoot = join(root, 'cache') - const signals: AbortSignal[] = [] - const fetcher = fetcherFor(archive, signals) - - const cached = await materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher }) - expect(cached.endsWith(originalAsset.archive)).toBe(true) - expect(fetcher).toHaveBeenCalledWith( - expect.stringContaining(`/v${NODE_RUNTIME_PIN.version}/${originalAsset.archive}`), - expect.objectContaining({ redirect: 'follow' }) - ) - expect(await materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher })).toBe(cached) - expect(fetcher).toHaveBeenCalledOnce() - - await writeFile(cached, 'torn') - const repaired = await materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher }) - expect(repaired).not.toBe(cached) - expect(sha256(new Uint8Array(await readFile(repaired)))).toBe(sha256(archive)) - expect(signals).toHaveLength(2) - expect(signals.every((signal) => !signal.aborted)).toBe(true) - }) - - it('refuses an archive that does not match the pin before caching it', async () => { - const archive = await nodeDistArchiveFixture(new TextEncoder().encode('node')) - await expect( - materializeNodeRuntimeArchive(TARGET, join(root, 'cache'), { fetcher: fetcherFor(archive) }) - ).rejects.toThrow('Node archive checksum mismatch') - }) -}) - -describe('pinned runtime archive request ownership', () => { - it.each(['http-error', 'oversized-declaration', 'staging-collision'] as const)( - 'retires the owned %s request without cancelling its caller', - async (failure) => { - const cacheRoot = join(root, 'cache') - const archiveRoot = join(cacheRoot, 'node', 'archives') - const parent = new AbortController() - const signals: AbortSignal[] = [] - const cancel = vi.fn() - const fetcher = vi.fn(async (_url, options) => { - if (options?.signal) { - signals.push(options.signal) - } - if (failure === 'staging-collision') { - const stage = (await readdir(archiveRoot)).find((name) => name.startsWith('.download-')) - if (!stage) { - throw new Error('Missing download staging directory') - } - await mkdir(join(archiveRoot, stage, originalAsset.archive)) - } - return new Response(new ReadableStream({ cancel }), { - status: failure === 'http-error' ? 404 : 200, - statusText: 'Unavailable', - headers: - failure === 'oversized-declaration' - ? { 'content-length': String(200 * 1024 * 1024 + 1) } - : {} - }) - }) - const pending = materializeNodeRuntimeArchive(TARGET, cacheRoot, { - fetcher, - signal: parent.signal - }) - await (failure === 'staging-collision' - ? expect(pending).rejects.toMatchObject({ code: 'EEXIST' }) - : expect(pending).rejects.toThrow( - failure === 'http-error' - ? 'Node download failed: 404 Unavailable' - : 'Node download exceeded the archive size limit' - )) - expect(cancel).toHaveBeenCalledOnce() - expect(signals).toHaveLength(1) - expect(signals[0]?.aborted).toBe(true) - expect(parent.signal.aborted).toBe(false) - expect(await readdir(archiveRoot)).toEqual([]) - } - ) - - it('keeps the caller cancellation reason and removes the incomplete stage', async () => { - const cacheRoot = join(root, 'cache') - const parent = new AbortController() - const reason = new Error('deployment cancelled') - const cancel = vi.fn() - const fetcher = vi.fn(async () => { - queueMicrotask(() => parent.abort(reason)) - return new Response(new ReadableStream({ cancel })) - }) - await expect( - materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher, signal: parent.signal }) - ).rejects.toBe(reason) - expect(parent.signal.reason).toBe(reason) - expect(cancel).toHaveBeenCalledOnce() - expect(await readdir(join(cacheRoot, 'node', 'archives'))).toEqual([]) - }) -}) - -describe('a pinned runtime archive this computer cannot download', () => { - it('says this computer could not reach the download, and where an offline copy goes', async () => { - const cacheRoot = join(root, 'cache') - const fetcher = vi.fn(async () => { - throw new Error('net::ERR_CONNECTION_REFUSED') - }) - const error = await materializeNodeRuntimeArchive(TARGET, cacheRoot, { - fetcher, - retryDelaysMs: [0, 0, 0] - }).catch((caught: unknown) => caught) - expect(fetcher).toHaveBeenCalledTimes(4) - const offlinePath = join(cacheRoot, 'node', 'archives', originalAsset.archive) - - expect(error).toBeInstanceOf(Error) - const message = error instanceof Error ? error.message : '' - expect(message).toContain("This computer couldn't download Node from https://") - expect(message).toContain(`/v${NODE_RUNTIME_PIN.version}/${originalAsset.archive}`) - expect(message).toContain('(net::ERR_CONNECTION_REFUSED)') - expect(message).toContain("the host doesn't need internet access") - expect(message).toContain(`copy it to ${offlinePath}`) - expect(error instanceof Error ? error.cause : null).toMatchObject({ - message: 'net::ERR_CONNECTION_REFUSED' - }) - }) - - it.skipIf(process.platform === 'win32')( - 'uses a copy placed at that path without downloading', - async () => { - const archive = await nodeDistArchiveFixture(new TextEncoder().encode('node')) - Object.assign(NODE_RUNTIME_ASSETS[TARGET], { archiveSha256: sha256(archive) }) - const cacheRoot = join(root, 'cache') - const offlinePath = join(cacheRoot, 'node', 'archives', originalAsset.archive) - await mkdir(join(offlinePath, '..'), { recursive: true }) - await writeFile(offlinePath, archive) - const fetcher = vi.fn(async () => { - throw new Error('net::ERR_CONNECTION_REFUSED') - }) - - expect(await materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher })).toBe(offlinePath) - expect(fetcher).not.toHaveBeenCalled() - } - ) - - it('keeps a local filesystem failure as it is', async () => { - const cacheRoot = join(root, 'cache') - const archiveRoot = join(cacheRoot, 'node', 'archives') - const fetcher = vi.fn(async () => { - const stage = (await readdir(archiveRoot)).find((name) => name.startsWith('.download-')) - await mkdir(join(archiveRoot, stage ?? 'missing', originalAsset.archive)) - return new Response(new ReadableStream(), { status: 200 }) - }) - await expect( - materializeNodeRuntimeArchive(TARGET, cacheRoot, { fetcher }) - ).rejects.toMatchObject({ code: 'EEXIST' }) - }) -}) diff --git a/src/main/node-runtime/pinned-runtime-materializer.test.ts b/src/main/node-runtime/pinned-runtime-materializer.test.ts deleted file mode 100644 index 6b04c691ecb..00000000000 --- a/src/main/node-runtime/pinned-runtime-materializer.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { createHash } from 'node:crypto' -import { access, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - NODE_RUNTIME_ASSETS, - NODE_RUNTIME_PIN, - nodeRuntimeExecutablePath, - SERVER_TARGETS, - type ServerTarget -} from '../../shared/node-runtime-pin' -import { setMainHttpClient } from '../network/http-client' -import { runProcess } from '@orca/process-host' -import { materializeCachedNodeRuntime } from './pinned-runtime-materializer' -import { RUNTIME_ARCHIVE_RETRY_DELAYS_MS } from './runtime-archive-download' - -const extraction = vi.hoisted(() => ({ executable: new Uint8Array(), member: '' })) - -vi.mock('@orca/process-host', () => ({ - runProcess: vi.fn(async (spec: { args: string[] }) => { - const flag = spec.args.includes('-C') ? '-C' : '-d' - const extracted = join(spec.args[spec.args.indexOf(flag) + 1]!, ...extraction.member.split('/')) - await mkdir(join(extracted, '..'), { recursive: true }) - await writeFile(extracted, extraction.executable) - return { code: 0, stdout: '', stderr: '' } - }) -})) - -const TARGET = 'linux-x64-glibc' as const -const originalAssets = structuredClone(NODE_RUNTIME_ASSETS) -let cacheRoot = '' - -function sha256(bytes: Uint8Array): string { - return createHash('sha256').update(bytes).digest('hex') -} - -function runtimeDirFor(target: ServerTarget = TARGET): string { - return join(cacheRoot, 'node', NODE_RUNTIME_ASSETS[target].executableSha256) -} - -function pin(target: ServerTarget, archive: Uint8Array, executable?: Uint8Array): void { - NODE_RUNTIME_ASSETS[target].archiveSha256 = sha256(archive) - if (executable) { - NODE_RUNTIME_ASSETS[target].executableSha256 = sha256(executable) - } - extraction.member = nodeRuntimeExecutablePath(target, NODE_RUNTIME_ASSETS[target].archive) -} - -function responseFetcher(body: Uint8Array, declaredLength = body.byteLength): typeof fetch { - return vi.fn( - async () => - new Response(Buffer.from(body), { - status: 200, - headers: { 'content-length': String(declaredLength) } - }) - ) -} - -beforeEach(async () => { - extraction.member = nodeRuntimeExecutablePath(TARGET, NODE_RUNTIME_ASSETS[TARGET].archive) - cacheRoot = await mkdtemp(join(tmpdir(), 'orca-node-runtime-executable-')) -}) - -afterEach(async () => { - vi.useRealTimers() - vi.unstubAllEnvs() - setMainHttpClient(null) - for (const target of SERVER_TARGETS) { - Object.assign(NODE_RUNTIME_ASSETS[target], originalAssets[target]) - } - await rm(cacheRoot, { recursive: true, force: true }) -}) - -describe('materializeCachedNodeRuntime', () => { - it('caches a Windows executable under its upstream name, keyed by its digest', async () => { - const target = 'win32-x64' as const - const archive = new TextEncoder().encode('windows archive') - const executable = new TextEncoder().encode('windows executable') - extraction.executable = executable - pin(target, archive, executable) - const runtimePath = await materializeCachedNodeRuntime(target, cacheRoot, { - fetcher: responseFetcher(archive) - }) - expect(runtimePath).toBe(join(runtimeDirFor(target), 'node.exe')) - expect(await readFile(runtimePath)).toEqual(Buffer.from(executable)) - }) - - it('reuses a checksum-valid cached runtime without fetching', async () => { - const runtime = new TextEncoder().encode('cached node') - NODE_RUNTIME_ASSETS[TARGET].executableSha256 = sha256(runtime) - const runtimeDir = runtimeDirFor() - const runtimePath = join(runtimeDir, 'node') - await mkdir(runtimeDir, { recursive: true }) - await writeFile(runtimePath, runtime) - const fetcher = vi.fn() - - await expect(materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher })).resolves.toBe( - runtimePath - ) - expect(fetcher).not.toHaveBeenCalled() - expect(await readFile(runtimePath)).toEqual(Buffer.from(runtime)) - }) - - it('downloads, verifies, extracts, and atomically caches the runtime', async () => { - const archive = new TextEncoder().encode('pinned archive') - const executable = new TextEncoder().encode('pinned node executable') - extraction.executable = executable - pin(TARGET, archive, executable) - const fetcher = responseFetcher(archive) - - const runtimePath = await materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher }) - - expect(await readFile(runtimePath)).toEqual(Buffer.from(executable)) - if (process.platform !== 'win32') { - expect((await stat(runtimePath)).mode & 0o111).toBe(0o111) - } - expect(fetcher).toHaveBeenCalledWith( - expect.stringContaining(`/v${NODE_RUNTIME_PIN.version}/${originalAssets[TARGET].archive}`), - expect.objectContaining({ redirect: 'follow' }) - ) - expect(await readdir(runtimeDirFor())).toEqual(['node']) - }) - - it('refuses an oversized declared archive before reading its body', async () => { - const fetcher = responseFetcher(new Uint8Array([1]), 200 * 1024 * 1024 + 1) - - await expect(materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher })).rejects.toThrow( - 'Node download exceeded the archive size limit' - ) - await expect(access(join(runtimeDirFor(), 'node'))).rejects.toThrow() - expect(await readdir(runtimeDirFor())).toEqual([]) - }) - - it('removes temporary data after an archive checksum mismatch', async () => { - const archive = new TextEncoder().encode('tampered archive') - const fetcher = responseFetcher(archive) - - await expect(materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher })).rejects.toThrow( - 'Node archive checksum mismatch' - ) - expect(await readdir(runtimeDirFor())).toEqual([]) - }) - - it('refuses an executable mismatch even when the archive matches its pin', async () => { - const archive = new TextEncoder().encode('pinned archive') - extraction.executable = new TextEncoder().encode('incorrect executable') - pin(TARGET, archive) - await expect( - materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher: responseFetcher(archive) }) - ).rejects.toThrow('Node executable checksum mismatch') - expect(await readdir(runtimeDirFor())).toEqual([]) - }) - - // Exercise real errno paths: absent programs reject with ENOENT; file parents throw ENOTDIR synchronously. - it.each([ - ['absent', (): string => join(cacheRoot, 'absent-extractor')], - ['unreachable through a file', (): string => join(cacheRoot, 'plain-file', 'unzip')] - ])('names the %s extractor and the override when it cannot be launched', async (_label, path) => { - const target = 'win32-x64' as const - const archive = new TextEncoder().encode('unextractable archive') - pin(target, archive) - await writeFile(join(cacheRoot, 'plain-file'), 'not a directory') - const { runProcess: spawnForReal } = await vi.importActual<{ - runProcess: typeof runProcess - }>('@orca/process-host') - vi.mocked(runProcess).mockImplementationOnce(spawnForReal) - vi.stubEnv('ORCA_UNZIP_BIN', path()) - - await expect( - materializeCachedNodeRuntime(target, cacheRoot, { fetcher: responseFetcher(archive) }) - ).rejects.toThrow(/install unzip, or set ORCA_UNZIP_BIN/) - expect(await readdir(runtimeDirFor(target))).toEqual([]) - }) - - it('cleans an aborted download before publishing any executable', async () => { - const controller = new AbortController() - controller.abort(new Error('deployment cancelled')) - await expect( - materializeCachedNodeRuntime(TARGET, cacheRoot, { - fetcher: responseFetcher(new Uint8Array([1])), - signal: controller.signal - }) - ).rejects.toThrow('deployment cancelled') - await expect(access(join(cacheRoot, 'node'))).rejects.toThrow() - }) -}) - -it('publishes concurrent runtime downloads without removing or replacing the winning executable', async () => { - const archive = new TextEncoder().encode('pinned archive') - extraction.executable = new TextEncoder().encode('pinned runtime') - pin(TARGET, archive, extraction.executable) - let finishSecond: (response: Response) => void = () => {} - const secondFetcher = vi.fn( - () => - new Promise((resolve) => { - finishSecond = resolve - }) - ) - const second = materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher: secondFetcher }) - await vi.waitFor(() => expect(secondFetcher).toHaveBeenCalledOnce()) - const firstPath = await materializeCachedNodeRuntime(TARGET, cacheRoot, { - fetcher: responseFetcher(archive) - }) - const firstIdentity = await stat(firstPath) - finishSecond(new Response(Buffer.from(archive))) - expect(await second).toBe(firstPath) - expect((await stat(firstPath)).ino).toBe(firstIdentity.ino) - expect(await readFile(firstPath)).toEqual(Buffer.from(extraction.executable)) -}) - -it('repairs a corrupt published runtime beside the old inode and reuses the repair', async () => { - const archive = new TextEncoder().encode('pinned archive') - extraction.executable = new TextEncoder().encode('pinned runtime') - pin(TARGET, archive, extraction.executable) - const runtimeDir = runtimeDirFor() - const runtimePath = join(runtimeDir, 'node') - await mkdir(runtimeDir, { recursive: true }) - await writeFile(runtimePath, 'corrupt') - const fetcher = responseFetcher(archive) - const repaired = await materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher }) - expect(repaired).not.toBe(runtimePath) - expect(await readFile(repaired)).toEqual(Buffer.from(extraction.executable)) - expect(await materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher })).toBe(repaired) - expect(fetcher).toHaveBeenCalledOnce() - expect(await readFile(runtimePath, 'utf8')).toBe('corrupt') -}) - -it('uses the configured HTTP client for deployment downloads', async () => { - const archive = new TextEncoder().encode('proxy archive') - extraction.executable = new TextEncoder().encode('proxy runtime') - pin(TARGET, archive, extraction.executable) - const fetcher = responseFetcher(archive) - setMainHttpClient({ fetch: fetcher, proxySession: () => null }) - await materializeCachedNodeRuntime(TARGET, cacheRoot, {}) - expect(fetcher).toHaveBeenCalledOnce() -}) - -it('allows a progressing download to exceed two minutes', async () => { - vi.useFakeTimers() - const first = new TextEncoder().encode('first') - const second = new TextEncoder().encode('second') - extraction.executable = new TextEncoder().encode('slow runtime') - pin(TARGET, Buffer.concat([first, second]), extraction.executable) - let stream: ReadableStreamDefaultController | undefined - let signal: AbortSignal | null | undefined - const fetcher = vi.fn(async (_url, options) => { - signal = options?.signal - return new Response( - new ReadableStream({ - start(controller) { - stream = controller - } - }) - ) - }) - const pending = materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher }) - await vi.waitFor(() => expect(fetcher).toHaveBeenCalledOnce()) - await vi.advanceTimersByTimeAsync(90_000) - stream!.enqueue(first) - await vi.waitFor(async () => { - const runtimeDir = runtimeDirFor() - const temporary = (await readdir(runtimeDir)).find((entry) => entry.startsWith('.download-'))! - expect( - (await stat(join(runtimeDir, temporary, NODE_RUNTIME_ASSETS[TARGET].archive))).size - ).toBe(first.length) - }) - await vi.advanceTimersByTimeAsync(90_000) - expect(signal?.aborted).toBe(false) - stream!.enqueue(second) - stream!.close() - expect(await readFile(await pending)).toEqual(Buffer.from(extraction.executable)) -}) - -it('retries a stalled body, then gives up and removes the unfinished download', async () => { - vi.useFakeTimers() - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const cancel = vi.fn() - const fetcher = vi.fn(async () => new Response(new ReadableStream({ cancel }))) - const pending = materializeCachedNodeRuntime(TARGET, cacheRoot, { fetcher }) - const rejected = expect(pending).rejects.toThrow('Node download stalled') - const attempts = RUNTIME_ARCHIVE_RETRY_DELAYS_MS.length + 1 - // Real file I/O sits between the timers, so step the clock until each attempt shows. - for (let attempt = 1; attempt <= attempts; attempt += 1) { - await vi.waitFor(async () => { - await vi.advanceTimersByTimeAsync(1_000) - expect(fetcher).toHaveBeenCalledTimes(attempt) - }) - await vi.waitFor(async () => { - await vi.advanceTimersByTimeAsync(10_000) - expect(cancel).toHaveBeenCalledTimes(attempt) - }) - } - await rejected - expect(fetcher).toHaveBeenCalledTimes(attempts) - expect(await readdir(runtimeDirFor())).toEqual([]) -}) diff --git a/src/main/notifications/notification-delivery-service.test.ts b/src/main/notifications/notification-delivery-service.test.ts deleted file mode 100644 index bf85bad3210..00000000000 --- a/src/main/notifications/notification-delivery-service.test.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { - createHarness as createPushHarness, - registration, - flush -} from '../runtime/push/push-dispatcher.test-fixture' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserWindow } from 'electron' -import { - createNotificationDeliveryService, - type NotificationDeliveryDependencies -} from './notification-delivery-service' -import { toWebTerminalSurfaceTabId } from '../../shared/workspace-layout/terminal-surface-id' - -import type { - NotificationDispatchRequest, - NotificationSettings -} from '../../shared/notification-settings-types' - -function makeSettings(overrides: Partial = {}): NotificationSettings { - return { - enabled: true, - agentTaskComplete: true, - agentNeedsInput: true, - terminalBell: true, - suppressWhenFocused: false, - customSoundId: 'system', - customSoundPath: null, - customSoundVolume: 1, - mutedNotificationSourceIds: [], - notifyHiddenWorkspaces: true, - ...overrides - } -} - -const LEAF = '11111111-1111-4111-8111-111111111111' - -function makeRequest( - overrides: Partial = {} -): NotificationDispatchRequest { - return { - source: 'agent-task-complete', - worktreeId: 'wt-1', - worktreeLabel: 'wt-1', - ...overrides - } -} - -type Harness = { - deps: NotificationDeliveryDependencies - order: string[] - setTrayAttention: ReturnType - dispatchMobileNotification: ReturnType - deliverNative: ReturnType -} - -let now = 1_000 - -function makeFocusedWindowStub(): BrowserWindow { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the service reads only isFocused(); a full BrowserWindow cannot be constructed outside Electron. - return { isFocused: () => true } as unknown as BrowserWindow -} - -function makeHarness(settings: NotificationSettings, windowVisible = false): Harness { - const order: string[] = [] - const setTrayAttention = vi.fn(() => order.push('tray')) - const dispatchMobileNotification = vi.fn(() => order.push('mobile')) - const deliverNative = vi.fn(() => { - order.push('native') - return { delivered: true } as const - }) - return { - order, - setTrayAttention, - dispatchMobileNotification, - deliverNative, - deps: { - readNotificationSettings: () => settings, - findActiveWindow: () => null, - isWindowVisible: () => windowVisible, - setTrayAttention, - isNotificationSupported: () => true, - dispatchMobileNotification, - readAuthorizationStatus: () => Promise.resolve('authorized'), - recordDeliveryOutcome: vi.fn(), - deliverNative, - platform: 'linux', - now: () => now - } - } -} - -beforeEach(() => { - now += 60_000 -}) - -describe('createNotificationDeliveryService', () => { - it('lights the tray dot before the enabled/cooldown gates can reject the event', () => { - const harness = makeHarness(makeSettings({ enabled: false })) - const result = createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) - - expect(harness.setTrayAttention).toHaveBeenCalledWith(true) - expect(result).toEqual({ delivered: false, reason: 'disabled' }) - expect(harness.deliverNative).not.toHaveBeenCalled() - expect(harness.order[0]).toBe('tray') - }) - - it('leaves the tray dot alone while the window is visible', () => { - const harness = makeHarness(makeSettings(), true) - createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) - expect(harness.setTrayAttention).not.toHaveBeenCalled() - }) - - it('fans out to mobile before the desktop-disabled early return', () => { - const harness = makeHarness(makeSettings({ agentTaskComplete: false })) - const result = createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) - - expect(result).toEqual({ delivered: false, reason: 'source-disabled' }) - expect(harness.dispatchMobileNotification).toHaveBeenCalledWith( - expect.objectContaining({ desktopAllowed: false, source: 'agent-task-complete' }) - ) - expect(harness.order).toEqual(['tray', 'mobile']) - }) - - it('gates agent questions on needs-input and finished turns on task-complete', () => { - const harness = makeHarness(makeSettings({ agentTaskComplete: false })) - const service = createNotificationDeliveryService(harness.deps) - expect(service.dispatch(makeRequest({ agentState: 'blocked' }))).toEqual({ delivered: true }) - expect( - service.dispatch( - makeRequest({ agentState: 'done', worktreeId: 'wt-2', worktreeLabel: 'wt-2' }) - ) - ).toEqual({ delivered: false, reason: 'source-disabled' }) - - const quiet = makeHarness(makeSettings({ agentNeedsInput: false })) - expect( - createNotificationDeliveryService(quiet.deps).dispatch(makeRequest({ agentState: 'waiting' })) - ).toEqual({ delivered: false, reason: 'source-disabled' }) - expect(quiet.dispatchMobileNotification).toHaveBeenCalledWith( - expect.objectContaining({ desktopAllowed: false, agentState: 'waiting' }) - ) - }) - - it('keeps the desktop source gates distinct per source', () => { - const harness = makeHarness(makeSettings({ terminalBell: false })) - const service = createNotificationDeliveryService(harness.deps) - expect(service.dispatch(makeRequest({ source: 'terminal-bell' }))).toEqual({ - delivered: false, - reason: 'source-disabled' - }) - expect(service.dispatch(makeRequest({ worktreeId: 'wt-2', worktreeLabel: 'wt-2' }))).toEqual({ - delivered: true - }) - }) - - it('skips the desktop banner for a muted machine but still reaches the phone', () => { - const harness = makeHarness(makeSettings({ mutedNotificationSourceIds: ['runtime:m4air'] })) - const service = createNotificationDeliveryService(harness.deps) - - expect(service.dispatch(makeRequest({ notificationSourceId: 'runtime:m4air' }))).toEqual({ - delivered: false, - reason: 'host-muted' - }) - expect(harness.dispatchMobileNotification).toHaveBeenCalledWith( - expect.not.objectContaining({ desktopAllowed: false }) - ) - expect(harness.deliverNative).not.toHaveBeenCalled() - - expect( - service.dispatch( - makeRequest({ notificationSourceId: 'local', worktreeId: 'wt-2', worktreeLabel: 'wt-2' }) - ) - ).toEqual({ delivered: true }) - expect(service.dispatch(makeRequest({ worktreeId: 'wt-3', worktreeLabel: 'wt-3' }))).toEqual({ - delivered: true - }) - }) - - it('reports the master switch over a muted machine', () => { - const harness = makeHarness( - makeSettings({ enabled: false, mutedNotificationSourceIds: ['runtime:m4air'] }) - ) - expect( - createNotificationDeliveryService(harness.deps).dispatch( - makeRequest({ notificationSourceId: 'runtime:m4air' }) - ) - ).toEqual({ delivered: false, reason: 'disabled' }) - }) - - it('suppresses a focused active workspace without touching mobile delivery', () => { - const harness = makeHarness(makeSettings({ suppressWhenFocused: true })) - const focusedWindow = makeFocusedWindowStub() - harness.deps.findActiveWindow = () => focusedWindow - const result = createNotificationDeliveryService(harness.deps).dispatch( - makeRequest({ isActiveWorktree: true }) - ) - - expect(result).toEqual({ delivered: false, reason: 'suppressed-focus' }) - expect(harness.dispatchMobileNotification).toHaveBeenCalledTimes(1) - }) - - it('dedupes desktop bursts per workspace but still reports the first delivery', () => { - const harness = makeHarness(makeSettings()) - const service = createNotificationDeliveryService(harness.deps) - expect(service.dispatch(makeRequest())).toEqual({ delivered: true }) - expect(service.dispatch(makeRequest({ source: 'terminal-bell' }))).toEqual({ - delivered: false, - reason: 'cooldown' - }) - }) - - it('lets keyed news through the workspace window, collapsing only its own repeat', () => { - const harness = makeHarness(makeSettings()) - const service = createNotificationDeliveryService(harness.deps) - expect(service.dispatch(makeRequest())).toEqual({ delivered: true }) - const prompt = (attentionKey: string) => makeRequest({ agentState: 'blocked', attentionKey }) - expect(service.dispatch(prompt('p1'))).toEqual({ delivered: true }) - expect(service.dispatch(prompt('p2'))).toEqual({ delivered: true }) - expect(service.dispatch(prompt('p2'))).toEqual({ delivered: false, reason: 'cooldown' }) - expect(harness.dispatchMobileNotification).toHaveBeenCalledWith( - expect.objectContaining({ attentionKey: 'p1', agentState: 'blocked' }) - ) - }) - - it('leaves the phone to the execution host when it already pushed', () => { - const harness = makeHarness(makeSettings()) - const service = createNotificationDeliveryService(harness.deps) - expect(service.dispatch(makeRequest({ mobileDeliveredByHost: true }))).toEqual({ - delivered: true - }) - expect(harness.dispatchMobileNotification).not.toHaveBeenCalled() - }) - - it('skips mobile fan-out entirely when no runtime is paired', () => { - const harness = makeHarness(makeSettings()) - harness.deps.dispatchMobileNotification = null - expect(createNotificationDeliveryService(harness.deps).dispatch(makeRequest())).toEqual({ - delivered: true - }) - expect(harness.dispatchMobileNotification).not.toHaveBeenCalled() - }) - - it('reports blocked-by-system on macOS when permission is undecided', async () => { - const harness = makeHarness(makeSettings()) - harness.deps.platform = 'darwin' - harness.deps.readAuthorizationStatus = () => Promise.resolve('not-determined') - await expect( - createNotificationDeliveryService(harness.deps).dispatch(makeRequest()) - ).resolves.toEqual({ delivered: false, reason: 'blocked-by-system' }) - expect(harness.deliverNative).not.toHaveBeenCalled() - }) -}) - -it.each>([{}, { enabled: false }, { agentTaskComplete: false }])( - 'preserves mobile event content and push eligibility when a machine is muted (%j)', - async (overrides) => { - const events: Parameters< - NonNullable - >[0][] = [] - for (const muted of [false, true]) { - const push = createPushHarness({ - devices: [{ deviceId: 'phone', pushRegistration: registration() }] - }) - const harness = makeHarness( - makeSettings({ ...overrides, mutedNotificationSourceIds: muted ? ['runtime:qa'] : [] }) - ) - harness.deps.dispatchMobileNotification = (event) => { - events.push(event) - push.dispatcher.enqueue({ ...event, notificationSeq: 1, notificationEpoch: 'epoch' }) - } - createNotificationDeliveryService(harness.deps).dispatch( - makeRequest({ notificationSourceId: 'runtime:qa', agentState: 'done' }) - ) - await flush() - expect(push.sends).toHaveLength( - overrides.enabled === false || overrides.agentTaskComplete === false ? 0 : 1 - ) - } - expect(events[1]).toEqual(events[0]) - } -) - -it('changing a machine mute preserves mobile cooldown and does not reserve desktop cooldown', () => { - const settings = makeSettings({ mutedNotificationSourceIds: ['runtime:qa'] }) - const harness = makeHarness(settings) - const service = createNotificationDeliveryService(harness.deps) - const request = makeRequest({ notificationSourceId: 'runtime:qa' }) - expect(service.dispatch(request)).toEqual({ delivered: false, reason: 'host-muted' }) - settings.mutedNotificationSourceIds = [] - expect(service.dispatch(request)).toEqual({ delivered: true }) - expect(harness.dispatchMobileNotification).toHaveBeenCalledTimes(1) -}) - -it('reports a muted host before a disabled source', () => { - const harness = makeHarness( - makeSettings({ agentTaskComplete: false, mutedNotificationSourceIds: ['runtime:qa'] }) - ) - expect( - createNotificationDeliveryService(harness.deps).dispatch( - makeRequest({ notificationSourceId: 'runtime:qa' }) - ) - ).toEqual({ delivered: false, reason: 'host-muted' }) -}) - -it("tells the phone which server and pane raised it, through the gateway's push", async () => { - const cases = [ - [undefined, `tab-1:${LEAF}`, `tab-1:${LEAF}`], - ['runtime:qa', `${toWebTerminalSurfaceTabId('host-tab')}:${LEAF}`, `host-tab:${LEAF}`], - // A per-surface mirror tab encodes the server's `tab::leaf` surface id. - ['runtime:qa', `${toWebTerminalSurfaceTabId(`host-tab::${LEAF}`)}:${LEAF}`, `host-tab:${LEAF}`] - ] as const - for (const [executionHost, paneKey, pushedPaneKey] of cases) { - const push = createPushHarness({ - devices: [{ deviceId: 'phone', pushRegistration: registration() }] - }) - const harness = makeHarness(makeSettings()) - harness.deps.dispatchMobileNotification = (event) => - push.dispatcher.enqueue({ ...event, notificationSeq: 1, notificationEpoch: 'epoch' }) - createNotificationDeliveryService(harness.deps).dispatch( - makeRequest({ agentState: 'done', paneKey, ...(executionHost ? { executionHost } : {}) }) - ) - await flush() - expect(push.sends[0]?.notification.worktreeId).toBe('wt-1') - expect(push.sends[0]?.notification.paneKey).toBe(pushedPaneKey) - expect(push.sends[0]?.notification.executionHost).toBe(executionHost) - } -}) diff --git a/src/main/observability/bundle.test.ts b/src/main/observability/bundle.test.ts index 38a40c38ed6..71573ed9d3b 100644 --- a/src/main/observability/bundle.test.ts +++ b/src/main/observability/bundle.test.ts @@ -1,11 +1,9 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type RequestListener, type Server } from 'node:http' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { _internalsForTests, collectBundle, generateBundleSubmissionId } from './bundle' -import { deleteBundle, uploadBundle, validateUploadUrl } from './diagnostic-bundle-upload' -import { MAX_RESPONSE_BYTES } from './diagnostic-upload-http' +import { _internalsForTests, collectBundle } from './bundle' +import { validateUploadUrl } from './diagnostic-bundle-upload' let dir: string let traceFile: string @@ -18,10 +16,6 @@ afterEach(() => { rmSync(dir, { recursive: true, force: true }) }) -function makeNDJSON(records: unknown[]): string { - return `${records.map((r) => JSON.stringify(r)).join('\n')}\n` -} - function makeSpan(overrides: Record = {}): Record { const now = BigInt(Date.now()) * 1_000_000n return { @@ -40,451 +34,7 @@ function makeSpan(overrides: Record = {}): Record { - it('is base64url, 22 chars (128 bits)', () => { - const id = generateBundleSubmissionId() - expect(id).toMatch(/^[A-Za-z0-9_-]{22}$/) - }) - it('is unique across many calls', () => { - const ids = new Set() - for (let i = 0; i < 100; i++) { - ids.add(generateBundleSubmissionId()) - } - expect(ids.size).toBe(100) - }) -}) - describe('bundle — collection', () => { - it.each([ - { kind: 'empty', names: [] }, - { kind: 'ASCII', names: ['plain'] }, - { kind: 'Unicode', names: ['漢字🙂', '\ud800'] }, - { - kind: 'capped', - names: Array.from({ length: 600 }, () => '漢字🙂'.repeat(1000)) - } - ])('reports the exact UTF-8 payload size for $kind records', ({ names }) => { - writeFileSync(traceFile, makeNDJSON(names.map((name) => makeSpan({ name })))) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 1, - appVersion: '1', - platform: 'win32', - arch: 'x64', - osRelease: 'test', - orcaChannel: 'dev' - }) - expect(bundle.bytes).toBe(Buffer.byteLength(bundle.payload)) - }) - - it('emits a header line with bundle_submission_id, app_version, platform', () => { - writeFileSync(traceFile, makeNDJSON([makeSpan()])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1.2.3', - platform: 'darwin', - arch: 'arm64', - osRelease: '24.0.0', - orcaChannel: 'dev' - }) - const header = JSON.parse(bundle.payload.split('\n').find(Boolean) ?? '') - expect(header.type).toBe('bundle-header') - expect(header.bundle_submission_id).toBe(bundle.bundleSubmissionId) - expect(header.app_version).toBe('1.2.3') - expect(header.platform).toBe('darwin') - expect(header.arch).toBe('arm64') - expect(header.orca_channel).toBe('dev') - expect(header.schema_version).toBe(1) - }) - - it('NEVER carries install_id in the header (Issue 8)', () => { - writeFileSync(traceFile, makeNDJSON([makeSpan()])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1.0', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - const header = JSON.parse(bundle.payload.split('\n')[0]) - expect(header).not.toHaveProperty('install_id') - expect(header).not.toHaveProperty('installId') - expect(header).not.toHaveProperty('distinct_id') - }) - - it('reads spans from the rotated family', () => { - writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'a' })])) - writeFileSync(`${traceFile}.1`, makeNDJSON([makeSpan({ name: 'b' })])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.spanCount).toBe(2) - }) - - it('drops spans older than the lookback window', () => { - const oldNanos = BigInt(Date.now() - 60 * 60 * 1000) * 1_000_000n - writeFileSync( - traceFile, - makeNDJSON([ - makeSpan({ name: 'recent' }), - makeSpan({ - name: 'old', - startTimeUnixNano: String(oldNanos - 1n), - endTimeUnixNano: String(oldNanos) - }) - ]) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - lookbackMinutes: 30, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.spanCount).toBe(1) - expect(bundle.payload).toContain('"name":"recent"') - expect(bundle.payload).not.toContain('"name":"old"') - }) - - it('merges the daemon lifecycle log, bounded by the same lookback', () => { - const daemonFile = join(dir, 'daemon.log') - writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) - writeFileSync( - daemonFile, - makeNDJSON([ - { - src: 'daemon', - ts: new Date().toISOString(), - pid: 1, - event: 'startup' - }, - { - src: 'daemon', - ts: new Date(Date.now() - 60 * 60 * 1000).toISOString(), - pid: 1, - event: 'session-exited' - } - ]) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - daemonLogFilePath: daemonFile, - daemonLogMaxFiles: 3, - lookbackMinutes: 30, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).toContain('"event":"startup"') - expect(bundle.payload).toContain('"name":"recent"') - expect(bundle.payload).not.toContain('"event":"session-exited"') - }) - - it('keeps daemon log lines when trace spans alone would fill the cap', () => { - const daemonFile = join(dir, 'daemon.log') - const filler = 'x'.repeat(4096) - writeFileSync( - traceFile, - makeNDJSON(Array.from({ length: 1500 }, () => makeSpan({ name: 'git.exec', filler }))) - ) - writeFileSync( - daemonFile, - makeNDJSON([ - { - src: 'daemon', - ts: new Date().toISOString(), - pid: 1, - event: 'session-created' - } - ]) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - daemonLogFilePath: daemonFile, - daemonLogMaxFiles: 3, - appVersion: '1', - platform: 'win32', - arch: 'x64', - osRelease: 'test', - orcaChannel: 'stable' - }) - expect(bundle.payload).toContain('"event":"session-created"') - expect(bundle.payload).toContain('"name":"git.exec"') - expect(bundle.bytes).toBe(Buffer.byteLength(bundle.payload)) - expect(bundle.bytes).toBeLessThanOrEqual(_internalsForTests.MAX_BUNDLE_BYTES) - expect(bundle.bytes).toBeGreaterThan(_internalsForTests.MAX_BUNDLE_BYTES - 8192) - }) - - it('gives the daemon log whatever quiet traces leave unused', () => { - const daemonFile = join(dir, 'daemon.log') - writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) - const detail = 'd'.repeat(1024) - writeFileSync( - daemonFile, - makeNDJSON( - Array.from({ length: 3000 }, (_, index) => ({ - src: 'daemon', - ts: new Date().toISOString(), - pid: 1, - event: `session-attached-${index}`, - detail - })) - ) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - daemonLogFilePath: daemonFile, - daemonLogMaxFiles: 3, - appVersion: '1', - platform: 'win32', - arch: 'x64', - osRelease: 'test', - orcaChannel: 'stable' - }) - expect(bundle.payload).toContain('"name":"recent"') - // The daemon share is a floor, not a cap. - expect(bundle.payload).toContain('"event":"session-attached-0"') - expect(bundle.payload).toContain('"event":"session-attached-2999"') - expect(bundle.bytes).toBe(Buffer.byteLength(bundle.payload)) - expect(bundle.bytes).toBeLessThanOrEqual(_internalsForTests.MAX_BUNDLE_BYTES) - }) - - it('keeps the newest daemon share when both sources overflow the cap', () => { - const daemonFile = join(dir, 'daemon.log') - const filler = 'x'.repeat(4096) - writeFileSync( - traceFile, - makeNDJSON(Array.from({ length: 1500 }, () => makeSpan({ name: 'git.exec', filler }))) - ) - const detail = 'd'.repeat(1024) - writeFileSync( - daemonFile, - makeNDJSON( - Array.from({ length: 6000 }, (_, index) => ({ - src: 'daemon', - ts: new Date().toISOString(), - pid: 1, - event: `session-attached-${index}`, - detail - })) - ) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - daemonLogFilePath: daemonFile, - daemonLogMaxFiles: 3, - appVersion: '1', - platform: 'win32', - arch: 'x64', - osRelease: 'test', - orcaChannel: 'stable' - }) - const daemonBytes = bundle.payload - .split('\n') - .filter((line) => line.includes('"src":"daemon"')) - .reduce((total, line) => total + Buffer.byteLength(line) + 1, 0) - expect(bundle.payload).toContain('"name":"git.exec"') - expect(bundle.payload).toContain('"event":"session-attached-5999"') - expect(daemonBytes).toBeGreaterThan(_internalsForTests.DAEMON_LOG_BUDGET_BYTES - 4096) - expect(daemonBytes).toBeLessThan(_internalsForTests.DAEMON_LOG_BUDGET_BYTES + 8192) - expect(bundle.bytes).toBeLessThanOrEqual(_internalsForTests.MAX_BUNDLE_BYTES) - }) - - it('collects no daemon log lines when no daemon log path is given', () => { - writeFileSync(traceFile, makeNDJSON([makeSpan({ name: 'recent' })])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).not.toContain('"src":"daemon"') - }) - - it('runs the redactor on the merged payload (belt-and-suspenders)', () => { - const span = makeSpan({ - attributes: { - leaked: `sk-ant-api03-${'a'.repeat(50)}` - } - }) - writeFileSync(traceFile, makeNDJSON([span])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).not.toContain('sk-ant-api03-aaaaa') - expect(bundle.payload).toContain('[redacted:anthropic-key]') - }) - - it('uses server-mode structured redaction for nested auth and identity keys', () => { - writeFileSync( - traceFile, - makeNDJSON([ - makeSpan({ - attributes: { - install_id: 'posthog-install-id', - request: { - headers: { - authorization: 'Bearer plain-secret', - cookie: 'sid=plain-secret', - keep: 'ok' - } - } - } - }) - ]) - ) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).not.toContain('posthog-install-id') - expect(bundle.payload).not.toContain('plain-secret') - expect(bundle.payload).not.toContain('authorization') - expect(bundle.payload).not.toContain('cookie') - expect(bundle.payload).toContain('"keep":"ok"') - }) - - it('does not append a span that would push the payload over the upload cap', () => { - const giantSpan = makeSpan({ - attributes: { - message: 'x'.repeat(_internalsForTests.MAX_BUNDLE_BYTES) - } - }) - writeFileSync(traceFile, makeNDJSON([giantSpan])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.bytes).toBeLessThanOrEqual(_internalsForTests.MAX_BUNDLE_BYTES) - expect(bundle.spanCount).toBe(0) - }) - - it('keeps the newest spans when the bundle size cap truncates a file', () => { - const oldSpan = makeSpan({ - name: 'oldest', - attributes: { message: 'x'.repeat(_internalsForTests.MAX_BUNDLE_BYTES) } - }) - const newSpan = makeSpan({ - name: 'newest', - attributes: { message: 'recent crash' } - }) - writeFileSync(traceFile, makeNDJSON([oldSpan, newSpan])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).toContain('"name":"newest"') - expect(bundle.payload).not.toContain('"name":"oldest"') - }) - - it('skips individually oversized recent spans and keeps smaller recent context', () => { - const tooLargeSpan = makeSpan({ - name: 'oversized', - attributes: { message: 'x'.repeat(_internalsForTests.MAX_BUNDLE_BYTES) } - }) - const usefulSpan = makeSpan({ - name: 'useful', - attributes: { message: 'still useful' } - }) - writeFileSync(traceFile, makeNDJSON([usefulSpan, tooLargeSpan])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).toContain('"name":"useful"') - expect(bundle.payload).not.toContain('"name":"oversized"') - }) - - it('skips oversized middle spans after accepting newer context', () => { - const olderUseful = makeSpan({ - name: 'older-useful', - attributes: { message: 'older context' } - }) - const oversizedMiddle = makeSpan({ - name: 'oversized-middle', - attributes: { message: 'x'.repeat(_internalsForTests.MAX_BUNDLE_BYTES) } - }) - const newestUseful = makeSpan({ - name: 'newest-useful', - attributes: { message: 'new context' } - }) - writeFileSync(traceFile, makeNDJSON([olderUseful, oversizedMiddle, newestUseful])) - const bundle = collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - expect(bundle.payload).toContain('"name":"newest-useful"') - expect(bundle.payload).toContain('"name":"older-useful"') - expect(bundle.payload).not.toContain('"name":"oversized-middle"') - }) - - it('skips malformed (non-JSON) lines without throwing', () => { - writeFileSync(traceFile, [JSON.stringify(makeSpan()), 'not json', ''].join('\n')) - expect(() => - collectBundle({ - traceFilePath: traceFile, - maxFiles: 10, - appVersion: '1', - platform: 'darwin', - arch: 'arm64', - osRelease: '24', - orcaChannel: 'dev' - }) - ).not.toThrow() - }) - it('skips valid JSON lines that are not span objects without throwing', () => { writeFileSync( traceFile, @@ -506,24 +56,12 @@ describe('bundle — collection', () => { }) describe('validateUploadUrl', () => { - it('allows https upload_url when tokenEndpoint is https', () => { - expect(() => - validateUploadUrl('https://api.example.com/upload', 'https://api.example.com/token') - ).not.toThrow() - }) - it('rejects http upload_url when tokenEndpoint is https (mixed scheme)', () => { expect(() => validateUploadUrl('http://api.example.com/upload', 'https://api.example.com/token') ).toThrow(/must use https/) }) - it('allows http upload_url when tokenEndpoint is http (localhost dev)', () => { - expect(() => - validateUploadUrl('http://localhost:8080/upload', 'http://localhost:8080/token') - ).not.toThrow() - }) - it('rejects an unparseable upload_url', () => { expect(() => validateUploadUrl('not a url', 'https://api.example.com/token')).toThrow( /invalid upload_url/ @@ -535,191 +73,4 @@ describe('validateUploadUrl', () => { validateUploadUrl('https://attacker.example.com/upload', 'https://api.example.com/token') ).toThrow(/must match tokenEndpoint host/) }) - - it('rejects a non-http(s) scheme like file://', () => { - expect(() => validateUploadUrl('file:///tmp/upload', 'https://api.example.com/token')).toThrow( - /must use https/ - ) - }) -}) - -describe('uploadBundle and deleteBundle', () => { - let server: Server | null = null - - afterEach( - () => - new Promise((resolve) => { - if (!server) { - resolve() - return - } - server.close(() => { - server = null - resolve() - }) - }) - ) - - function listen(handler: RequestListener): Promise { - server = createServer(handler) - return new Promise((resolve) => { - server?.listen(0, '127.0.0.1', () => { - const address = server?.address() - if (address && typeof address === 'object') { - resolve(`http://127.0.0.1:${address.port}`) - } - }) - }) - } - - it('does not include token endpoint response bodies in thrown errors', async () => { - const secretBody = 'internal token service detail: sk-ant-api03-secret' - const baseUrl = await listen((_req, res) => { - res.statusCode = 500 - res.end(secretBody) - }) - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^HTTP 500$/) - }) - - it('does not include upload endpoint response bodies in thrown errors', async () => { - const secretBody = 'internal upload detail: ghp_secret' - const baseUrl = await listen((req, res) => { - if (req.url === '/token') { - res.setHeader('content-type', 'application/json') - res.end( - JSON.stringify({ - token: 'test-token', - expires_at: new Date(Date.now() + 60_000).toISOString(), - upload_url: `${baseUrl}/upload`, - max_bytes: _internalsForTests.MAX_BUNDLE_BYTES - }) - ) - return - } - res.statusCode = 500 - res.end(secretBody) - }) - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^HTTP 500$/) - }) - - it('does not include malformed upload_url values in thrown errors', async () => { - const secretUrl = 'not a url with sk-ant-api03-secret' - const baseUrl = await listen((_req, res) => { - res.setHeader('content-type', 'application/json') - res.end( - JSON.stringify({ - token: 'test-token', - expires_at: new Date(Date.now() + 60_000).toISOString(), - upload_url: secretUrl, - max_bytes: _internalsForTests.MAX_BUNDLE_BYTES - }) - ) - }) - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^invalid upload_url from token endpoint$/) - }) - - it('does not include transport error details in thrown errors', async () => { - const baseUrl = await listen((req) => { - // Destroy a local socket to test transport redaction without DNS timing dependence. - req.socket.destroy(new Error('transport detail with sk-ant-api03-secret')) - }) - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/diagnostics/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^diagnostic network request failed$/) - }) - - it('does not include invalid tokenEndpoint values in thrown errors', async () => { - await expect( - uploadBundle({ - tokenEndpoint: 'not a url with sk-ant-api03-secret', - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^diagnostic endpoint configuration is invalid$/) - }) - - it('caps diagnostic endpoint response bodies', async () => { - const baseUrl = await listen((_req, res) => { - res.setHeader('content-type', 'application/json') - res.end('x'.repeat(MAX_RESPONSE_BYTES + 1)) - }) - - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).rejects.toThrow(/^diagnostic response exceeded size limit$/) - }) - - it('returns only the diagnostic ticket from successful uploads', async () => { - const baseUrl = await listen((req, res) => { - res.setHeader('content-type', 'application/json') - if (req.url === '/token') { - res.end( - JSON.stringify({ - token: 'test-token', - expires_at: new Date(Date.now() + 60_000).toISOString(), - upload_url: `${baseUrl}/upload`, - max_bytes: _internalsForTests.MAX_BUNDLE_BYTES - }) - ) - return - } - res.statusCode = 201 - res.end( - JSON.stringify({ - ticket_id: 'ticketabcdefghijklmnop' - }) - ) - }) - - await expect( - uploadBundle({ - tokenEndpoint: `${baseUrl}/token`, - payload: '{}\n', - bundleSubmissionId: generateBundleSubmissionId() - }) - ).resolves.toEqual({ - ticketId: 'ticketabcdefghijklmnop' - }) - }) - - it('posts deletion requests to the diagnostics delete endpoint for a ticket', async () => { - const ticketId = generateBundleSubmissionId() - const seen: string[] = [] - const baseUrl = await listen((req, res) => { - seen.push(req.url ?? '') - res.setHeader('content-type', 'application/json') - res.end('{}') - }) - await deleteBundle({ - tokenEndpoint: `${baseUrl}/diagnostics/token`, - ticketId - }) - expect(seen).toEqual([`/diagnostics/delete/${ticketId}`]) - }) }) diff --git a/src/main/observability/instrumentation.test.ts b/src/main/observability/instrumentation.test.ts deleted file mode 100644 index de9dc059ff1..00000000000 --- a/src/main/observability/instrumentation.test.ts +++ /dev/null @@ -1,287 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _resetTracerForTests, setActiveSink, type TracerSink } from './tracer' -import { - _gitSpanSamplingBucketCountForTests, - _resetGitSpanSamplingForTests, - addWorktreeCreatePhaseAttributes, - withGitSpan -} from './instrumentation' -import { - addAgentSessionCreatePhaseAttributes, - withAgentSessionSpan -} from './agent-session-instrumentation' - -type SpanRecord = { - readonly name: string - readonly durationMs: number - readonly attributes: Record - readonly exit: { readonly _tag: string; readonly cause?: string } -} - -type CapturedSink = TracerSink & { - readonly records: SpanRecord[] -} - -function isSpanRecord(record: unknown): record is SpanRecord { - return ( - record !== null && - typeof record === 'object' && - 'name' in record && - typeof record.name === 'string' && - 'durationMs' in record && - typeof record.durationMs === 'number' && - 'attributes' in record && - record.attributes !== null && - typeof record.attributes === 'object' && - 'exit' in record && - record.exit !== null && - typeof record.exit === 'object' && - '_tag' in record.exit && - typeof record.exit._tag === 'string' - ) -} - -function makeCapturingSink(): CapturedSink { - const records: SpanRecord[] = [] - return { - records, - push(record) { - if (!isSpanRecord(record)) { - throw new Error('expected span record') - } - records.push(record) - }, - flush() {}, - close() {} - } -} - -let sink: CapturedSink -let nowMs = 1_700_000_000_000 - -async function runGitSpan( - meta: { args: readonly string[]; cwd?: string }, - durationMs: number, - fail = false -) { - vi.setSystemTime(nowMs) - const promise = withGitSpan(meta, async () => { - vi.setSystemTime(nowMs + durationMs) - if (fail) { - throw new Error('git failed') - } - return 'ok' - }) - nowMs += durationMs + 1 - return await promise -} - -beforeEach(() => { - vi.useFakeTimers() - nowMs = 1_700_000_000_000 - _resetGitSpanSamplingForTests() - sink = makeCapturingSink() - setActiveSink(sink) -}) - -afterEach(() => { - vi.useRealTimers() - _resetGitSpanSamplingForTests() - _resetTracerForTests() -}) - -describe('withGitSpan sampling', () => { - it('bounds fast successful repeated git spans by subcommand and cwd while preserving important spans', async () => { - for (let i = 0; i < 10_000; i++) { - await runGitSpan({ args: ['status', '--short'], cwd: '/repo' }, 5) - } - - const repeatedFastSuccesses = sink.records.filter( - (record) => - record.name === 'git.exec' && - record.exit._tag === 'Success' && - record.attributes['git.subcommand'] === 'status' && - record.attributes.cwd === '/repo' && - record.durationMs < 250 - ) - expect(repeatedFastSuccesses.length).toBeGreaterThan(0) - expect(repeatedFastSuccesses.length).toBeLessThan(200) - - await expect(runGitSpan({ args: ['status'], cwd: '/repo' }, 5, true)).rejects.toThrow( - 'git failed' - ) - await runGitSpan({ args: ['status'], cwd: '/repo' }, 275) - await runGitSpan({ args: ['branch'], cwd: '/repo' }, 5) - await runGitSpan({ args: ['status'], cwd: '/other-repo' }, 5) - - expect( - sink.records.some( - (record) => - record.exit._tag === 'Failure' && - record.attributes['git.subcommand'] === 'status' && - record.attributes.cwd === '/repo' - ) - ).toBe(true) - expect( - sink.records.some( - (record) => - record.exit._tag === 'Success' && - record.durationMs >= 250 && - record.attributes['git.subcommand'] === 'status' && - record.attributes.cwd === '/repo' - ) - ).toBe(true) - expect( - sink.records.some( - (record) => - record.exit._tag === 'Success' && - record.attributes['git.subcommand'] === 'branch' && - record.attributes.cwd === '/repo' - ) - ).toBe(true) - expect( - sink.records.some( - (record) => - record.exit._tag === 'Success' && - record.attributes['git.subcommand'] === 'status' && - record.attributes.cwd === '/other-repo' - ) - ).toBe(true) - }) - it('parses git subcommands after global options without changing arg count', async () => { - await runGitSpan({ args: ['-c', 'core.quotePath=false', 'status', '--short'], cwd: '/repo' }, 5) - - expect(sink.records[0]?.attributes['git.subcommand']).toBe('status') - expect(sink.records[0]?.attributes['git.arg_count']).toBe(4) - }) - - it('prunes stale git sampling buckets and caps unique cwd buckets', async () => { - for (let i = 0; i < 700; i++) { - await runGitSpan({ args: ['status'], cwd: `/repo-${i}` }, 5) - } - - expect(_gitSpanSamplingBucketCountForTests()).toBeLessThanOrEqual(512) - - nowMs += 60_000 - await runGitSpan({ args: ['status'], cwd: '/fresh-repo' }, 5) - - expect(_gitSpanSamplingBucketCountForTests()).toBe(1) - }) -}) - -describe('addWorktreeCreatePhaseAttributes', () => { - function capture(): { - attributes: Record - span: Parameters[0] - } { - const attributes: Record = {} - const span = { - setAttribute: (key: string, value: unknown) => { - attributes[key] = value - } - } as unknown as Parameters[0] - return { attributes, span } - } - - it('counts concurrent phases once when measuring unattributed time', () => { - const { attributes, span } = capture() - // Concurrent phases must not double-count covered wall time. - addWorktreeCreatePhaseAttributes(span, { - totalDurationMs: 1000, - phases: [ - { phase: 'resolve_shared_directories', startedAtMs: 100, durationMs: 200 }, - { phase: 'resolve_worktreeinclude', startedAtMs: 150, durationMs: 150 } - ] - }) - - expect(attributes['worktree.create.phase.resolve_shared_directories_ms']).toBe(200) - expect(attributes['worktree.create.phase.resolve_worktreeinclude_ms']).toBe(150) - expect(attributes['worktree.create.unattributed_ms']).toBe(800) - }) - - it('sums disjoint phases and never reports negative unattributed time', () => { - const { attributes, span } = capture() - addWorktreeCreatePhaseAttributes(span, { - totalDurationMs: 500, - phases: [ - { phase: 'resolve_name', startedAtMs: 0, durationMs: 100 }, - { phase: 'git_worktree_add', startedAtMs: 300, durationMs: 200 } - ] - }) - - expect(attributes['worktree.create.total_ms']).toBe(500) - expect(attributes['worktree.create.unattributed_ms']).toBe(200) - }) - - it('records a prepared-checkout hit, the reset it needed and who armed it', () => { - const { attributes, span } = capture() - addWorktreeCreatePhaseAttributes(span, { - totalDurationMs: 900, - phases: [{ phase: 'git_worktree_add', startedAtMs: 0, durationMs: 400 }], - preparedCheckout: { - status: 'hit', - reset: 'retargeted', - origin: 'rearm', - buildMs: 1, - idleMs: 0 - } - }) - - expect(attributes['worktree.create.prepared_checkout']).toBe('hit') - expect(attributes['worktree.create.prepared_checkout_reset']).toBe('retargeted') - expect(attributes['worktree.create.prepared_checkout_origin']).toBe('rearm') - expect(attributes['worktree.create.prepared_checkout_miss']).toBeUndefined() - expect(attributes['worktree.create.unattributed_ms']).toBe(500) - }) - - it('records why a create missed the prepared checkout', () => { - const { attributes, span } = capture() - addWorktreeCreatePhaseAttributes(span, { - totalDurationMs: 8_000, - phases: [], - preparedCheckout: { status: 'miss', reason: 'base_mismatch' } - }) - - expect(attributes['worktree.create.prepared_checkout']).toBe('miss') - expect(attributes['worktree.create.prepared_checkout_miss']).toBe('base_mismatch') - expect(attributes['worktree.create.prepared_checkout_reset']).toBeUndefined() - }) - - it('stays silent on paths that never consult the prepared checkout', () => { - const { attributes, span } = capture() - addWorktreeCreatePhaseAttributes(span, { totalDurationMs: 10, phases: [] }) - - expect(attributes['worktree.create.prepared_checkout']).toBeUndefined() - }) -}) - -describe('agentSession.create tracing', () => { - it('emits one span with the closed phase vocabulary and no user content attributes', async () => { - await withAgentSessionSpan(async (span) => { - addAgentSessionCreatePhaseAttributes(span, { - totalDurationMs: 57, - phases: [ - { phase: 'reconcile_leases', startedAtMs: 0, durationMs: 1 }, - { phase: 'resolve_recovery', startedAtMs: 1, durationMs: 5 }, - { phase: 'probe_owner', startedAtMs: 6, durationMs: 4 }, - { phase: 'reserve_owner', startedAtMs: 10, durationMs: 5 }, - { phase: 'acquire_owner', startedAtMs: 15, durationMs: 6 }, - { phase: 'auth_settle', startedAtMs: 21, durationMs: 7 }, - { phase: 'spawn', startedAtMs: 28, durationMs: 8 }, - { phase: 'restore_options', startedAtMs: 36, durationMs: 10 }, - { phase: 'publish', startedAtMs: 46, durationMs: 11 } - ] - }) - }) - - const records = sink.records.filter((record) => record.name === 'agentSession.create') - expect(records).toHaveLength(1) - const attributes = records[0]!.attributes - expect(attributes['agent_session.create.phase.reconcile_leases_ms']).toBe(1) - expect(attributes['agent_session.create.phase.publish_ms']).toBe(11) - expect(attributes['agent_session.create.unattributed_ms']).toBe(0) - expect(Object.keys(attributes).some((key) => /path|branch|prompt|content/i.test(key))).toBe( - false - ) - }) -}) diff --git a/src/main/observability/redactor.test.ts b/src/main/observability/redactor.test.ts index b534fa31ea7..756cc22d7cf 100644 --- a/src/main/observability/redactor.test.ts +++ b/src/main/observability/redactor.test.ts @@ -1,11 +1,5 @@ import { describe, it, expect } from 'vitest' -import { - redactString, - redactAttributes, - redactValue, - redactSpan, - type RedactableSpan -} from './redactor' +import { redactString, redactValue } from './redactor' const SECRETS = { anthropic: 'sk-ant-api03-aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789ABCDEFGHIJKLMNOP', @@ -18,69 +12,6 @@ const SECRETS = { pem: '-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQ\n-----END PRIVATE KEY-----' } -const PROVIDER_KEY_CASES: { label: string; raw: string; tag: string }[] = [ - { label: 'anthropic', raw: SECRETS.anthropic, tag: 'anthropic-key' }, - { label: 'openai', raw: SECRETS.openai, tag: 'openai-key' }, - { label: 'github', raw: SECRETS.github, tag: 'github-token' }, - { label: 'aws-access-key', raw: SECRETS.awsAccessKey, tag: 'aws-access-key-id' }, - { label: 'aws-secret', raw: SECRETS.awsSecret, tag: 'aws-secret-access-key' }, - { label: 'jwt', raw: SECRETS.jwt, tag: 'jwt' }, - { label: 'slack', raw: SECRETS.slack, tag: 'slack-token' }, - { label: 'pem', raw: SECRETS.pem, tag: 'pem' } -] - -describe('redactor — provider-key fingerprints', () => { - for (const { label, raw, tag } of PROVIDER_KEY_CASES) { - describe(`${label}`, () => { - it('redacts when the secret appears as an attribute value', () => { - // Omit labels to isolate provider-shape redaction. - const out = redactAttributes({ msg: `failure ${raw}` }) - const serialized = JSON.stringify(out) - expect(serialized).not.toContain(raw) - expect(serialized).toContain(`[redacted:${tag}]`) - }) - - it('redacts when the secret appears in a span event attribute', () => { - const span = makeSpan({ - events: [ - { - name: 'log', - timeUnixNano: '0', - attributes: { 'log.message': `oops ${raw}` } - } - ] - }) - const out = JSON.stringify(redactSpan(span)) - expect(out).not.toContain(raw) - expect(out).toContain(`[redacted:${tag}]`) - }) - - it('redacts when the secret appears in the exit cause', () => { - const span = makeSpan({ - exit: { - _tag: 'Failure', - cause: `Error: provider rejected request ${raw}\n at handler (file.ts:1:1)` - } - }) - const out = JSON.stringify(redactSpan(span)) - expect(out).not.toContain(raw) - expect(out).toContain(`[redacted:${tag}]`) - }) - - it('redacts when nested under a labeled-kv keyword (defense in depth)', () => { - const span = makeSpan({ - exit: { - _tag: 'Failure', - cause: `Invalid token: ${raw}` - } - }) - const out = JSON.stringify(redactSpan(span)) - expect(out).not.toContain(raw) - }) - }) - } -}) - describe('redactor — labeled key-value', () => { it('redacts api_key:', () => { expect(redactString('api_key: hunter2')).toBe('[redacted:labeled-kv]') @@ -88,12 +19,7 @@ describe('redactor — labeled key-value', () => { it('redacts Authorization=Bearer …', () => { expect(redactString('Authorization=Bearer abcdef')).toBe('[redacted:labeled-kv]') }) - it('redacts password=…', () => { - expect(redactString("password='hunter2'")).toContain('[redacted:labeled-kv]') - }) - it('redacts secret=…', () => { - expect(redactString('secret=topsekret')).toBe('[redacted:labeled-kv]') - }) + it('preserves surrounding context outside the matched segment', () => { const out = redactString('before api_key=xyz after') expect(out).toContain('before') @@ -109,18 +35,9 @@ describe('redactor — URL userinfo strip', () => { expect(out).toContain('github.com/foo/bar') expect(out).toContain('[redacted]@') }) - it('preserves bare URLs without userinfo', () => { - expect(redactString('https://github.com/foo')).toBe('https://github.com/foo') - }) }) describe('redactor — .env-shape line', () => { - it('redacts the value but keeps the key', () => { - const out = redactString('FOO_SECRET=topsekret') - expect(out).toContain('FOO_SECRET=') - expect(out).toContain('[redacted:env-value]') - expect(out).not.toContain('topsekret') - }) it('handles multi-line .env dumps', () => { const out = redactString(['DB_HOST=db.local', 'DB_PASSWORD=hunter2', '# comment'].join('\n')) expect(out).toContain('DB_HOST=[redacted:env-value]') @@ -132,33 +49,6 @@ describe('redactor — .env-shape line', () => { }) describe('redactor — attribute-key blocklist', () => { - it('drops env attribute', () => { - const out = redactAttributes({ env: { ANTHROPIC_API_KEY: SECRETS.anthropic } }) - expect(out).not.toHaveProperty('env') - }) - it('drops authorization (case-insensitive)', () => { - const out = redactAttributes({ Authorization: 'Bearer x', cookie: 'a=b' }) - expect(out).not.toHaveProperty('Authorization') - expect(out).not.toHaveProperty('cookie') - }) - it('drops headers.authorization', () => { - const out = redactAttributes({ 'headers.authorization': 'Bearer x' }) - expect(out).not.toHaveProperty('headers.authorization') - }) - it('drops structured secret-bearing keys with plain values', () => { - const out = redactAttributes({ - token: 'plain-token', - api_key: 'plain-api-key', - password: 'plain-password', - secret: 'plain-secret', - keep: 'ok' - }) - expect(out).not.toHaveProperty('token') - expect(out).not.toHaveProperty('api_key') - expect(out).not.toHaveProperty('password') - expect(out).not.toHaveProperty('secret') - expect(out.keep).toBe('ok') - }) it('drops compound structured secret-bearing keys with plain values', () => { const out = redactValue({ ANTHROPIC_API_KEY: 'plain-anthropic', @@ -189,15 +79,7 @@ describe('redactor — attribute-key blocklist', () => { expect(out).not.toHaveProperty('serverSecretKey') expect(out.keep).toBe('ok') }) - it('keeps non-blocklisted keys', () => { - const out = redactAttributes({ path: '/Users/x/repo', method: 'GET' }) - expect(out).toHaveProperty('path') - expect(out).toHaveProperty('method') - }) - it('preserves filesystem paths verbatim — they are diagnostic data', () => { - const out = redactAttributes({ cwd: '/Users/brennanb/projects/orca' }) - expect(out.cwd).toBe('/Users/brennanb/projects/orca') - }) + it('drops nested blocked keys while recursively redacting values', () => { const out = redactValue({ request: { @@ -215,25 +97,6 @@ describe('redactor — attribute-key blocklist', () => { }) describe('redactor — server mode adds install_id keys', () => { - it('drops install_id, installId, distinct_id', () => { - const before = { - install_id: 'abc', - installId: 'def', - distinct_id: 'ghi', - keep: 'me' - } - const client = redactAttributes(before, 'client') - const server = redactAttributes(before, 'server') - - expect(client).toHaveProperty('install_id') - expect(client).toHaveProperty('installId') - expect(client).toHaveProperty('distinct_id') - - expect(server).not.toHaveProperty('install_id') - expect(server).not.toHaveProperty('installId') - expect(server).not.toHaveProperty('distinct_id') - expect(server).toHaveProperty('keep') - }) it('drops identity keys nested inside server-mode values', () => { const out = redactValue({ context: { install_id: 'abc', keep: 'me' } }, 'server') as { context: Record @@ -257,64 +120,4 @@ describe('redactor — recursive value redaction', () => { expect(out[0]).not.toContain(SECRETS.github) expect(out[1]).toBe('plain') }) - it('handles circular references without crashing', () => { - const a: Record = {} - a.self = a - expect(() => redactValue(a)).not.toThrow() - }) }) - -describe('redactor — idempotence', () => { - it('running twice equals running once', () => { - const cases = [ - `api_key: ${SECRETS.anthropic}`, - `https://${SECRETS.github}@github.com/foo`, - 'FOO=bar', - 'plain text' - ] - for (const c of cases) { - const once = redactString(c) - const twice = redactString(once) - expect(twice).toBe(once) - } - }) -}) - -describe('redactor — span shape', () => { - it('preserves traceId/spanId/name/duration', () => { - const span = makeSpan({}) - const out = redactSpan(span) - expect(out.traceId).toBe(span.traceId) - expect(out.spanId).toBe(span.spanId) - expect(out.name).toBe(span.name) - expect(out.durationMs).toBe(span.durationMs) - }) - it('preserves parentSpanId when present', () => { - const span = makeSpan({ parentSpanId: 'parent123' }) - expect(redactSpan(span).parentSpanId).toBe('parent123') - }) - it('does not mutate input span', () => { - const before = makeSpan({ - attributes: { token: SECRETS.anthropic } - }) - const beforeStr = JSON.stringify(before) - redactSpan(before) - expect(JSON.stringify(before)).toBe(beforeStr) - }) -}) - -function makeSpan(overrides: Partial): RedactableSpan { - return { - name: 'test.span', - traceId: '00000000000000000000000000000001', - spanId: '0000000000000001', - kind: 'internal', - startTimeUnixNano: '1000', - endTimeUnixNano: '2000', - durationMs: 1, - attributes: {}, - events: [], - exit: { _tag: 'Success' }, - ...overrides - } -} diff --git a/src/main/observability/stalled-log-disk.test.ts b/src/main/observability/stalled-log-disk.test.ts deleted file mode 100644 index 837b80a10bd..00000000000 --- a/src/main/observability/stalled-log-disk.test.ts +++ /dev/null @@ -1,267 +0,0 @@ -import type * as NodeFs from 'node:fs' -import type * as NodeFsPromises from 'node:fs/promises' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createDaemonFileLog } from '../daemon/observability/daemon-file-log' -import { createLocalFileSink, DROPPED_RECORD_TYPE } from './local-file-sink' - -// `holdAsync` parks async appends (at open) until released; `blockSync` makes sync writes hold the thread. -const disk = vi.hoisted(() => { - const heldWrites: (() => void)[] = [] - return { holdAsync: false, blockSync: false, heldWrites, blockingWrites: 0 } -}) - -const SYNC_STALL_MS = 150 - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - const stallSignal = new Int32Array(new SharedArrayBuffer(4)) - const blockLikeStalledDisk = (): void => { - if (disk.blockSync) { - disk.blockingWrites++ - Atomics.wait(stallSignal, 0, 0, SYNC_STALL_MS) - } - } - const mocked = { - ...actual, - appendFileSync: (...args: Parameters): void => { - blockLikeStalledDisk() - actual.appendFileSync(...args) - }, - // Overloads resolve to the last signature; the real call forwards whatever form was passed. - writeSync: (...args: Parameters): number => { - blockLikeStalledDisk() - return actual.writeSync(...args) - } - } - return { ...mocked, default: mocked } -}) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - const mocked = { - ...actual, - open: (...args: Parameters): ReturnType => { - if (!disk.holdAsync) { - return actual.open(...args) - } - return new Promise((resolve, reject) => { - disk.heldWrites.push(() => void actual.open(...args).then(resolve, reject)) - }) - } - } - return { ...mocked, default: mocked } -}) - -function stallDisk(): void { - disk.holdAsync = true - disk.blockSync = true -} - -function releaseDisk(): void { - disk.holdAsync = false - disk.blockSync = false - disk.blockingWrites = 0 - for (const run of disk.heldWrites.splice(0)) { - run() - } -} - -async function writeIsHeld(): Promise { - await vi.waitFor(() => expect(disk.heldWrites.length).toBeGreaterThan(0), { timeout: 10_000 }) -} - -/** Resolves when a timer queued now gets to run. */ -function nextTimer(): Promise<'ran'> { - return new Promise((resolve) => setTimeout(() => resolve('ran'), 0)) -} - -let dir: string -beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-stalled-log-')) -}) -afterEach(() => { - releaseDisk() - // Windows can briefly hold a file the writer is still closing. - rmSync(dir, { recursive: true, force: true, maxRetries: 5 }) -}) - -function readJsonLines(filePath: string): Record[] { - return readFileSync(filePath, 'utf8') - .split('\n') - .filter(Boolean) - .map((line): Record => JSON.parse(line)) -} - -describe('log writes on a stalled disk', () => { - it('daemon log writes leave a concurrent timer running while the write is stalled', async () => { - const filePath = join(dir, 'daemon.log') - const log = createDaemonFileLog(filePath) - stallDisk() - for (let i = 0; i < 4; i++) { - log.log('session-killed', { i }) - } - await writeIsHeld() - await expect(nextTimer()).resolves.toBe('ran') - expect(disk.heldWrites).toHaveLength(1) - expect(disk.blockingWrites).toBe(0) - releaseDisk() - await vi.waitFor(() => expect(readJsonLines(filePath)).toHaveLength(4), { timeout: 10_000 }) - log.close() - }) - - it('trace writes leave a concurrent timer running while the write is stalled', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 1 }) - stallDisk() - for (let i = 0; i < 40; i++) { - sink.push({ i }) - } - await writeIsHeld() - await expect(nextTimer()).resolves.toBe('ran') - expect(disk.heldWrites).toHaveLength(1) - expect(disk.blockingWrites).toBe(0) - releaseDisk() - await sink.flushAsync() - expect(readJsonLines(filePath)).toHaveLength(40) - sink.close() - }) - - it('daemon close writes the fatal line while an earlier write is still in flight', async () => { - const filePath = join(dir, 'daemon.log') - const log = createDaemonFileLog(filePath) - disk.holdAsync = true - log.log('before-hold') - await writeIsHeld() - log.log('uncaught-exception-fatal') - log.close() - const events = (): unknown[] => readJsonLines(filePath).map((line) => line.event) - expect(events()).toEqual(['uncaught-exception-fatal', 'daemon-log-closed']) - releaseDisk() - await vi.waitFor(() => expect(events()).toContain('before-hold'), { timeout: 10_000 }) - }) - - it('a crash-boundary trace flush lands while an earlier write is still in flight', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 1 }) - disk.holdAsync = true - sink.push({ name: 'before-hold' }) - await writeIsHeld() - sink.push({ name: 'app_relaunch_requested' }) - sink.flush() - expect(readJsonLines(filePath)).toEqual([{ name: 'app_relaunch_requested' }]) - releaseDisk() - await sink.flushAsync() - expect(readJsonLines(filePath)).toContainEqual({ name: 'before-hold' }) - sink.close() - }) - - it('flushAsync waits for its own records, not ones logged while it waits', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 1 }) - const heldCount = (count: number): Promise => - vi.waitFor(() => expect(disk.heldWrites).toHaveLength(count), { timeout: 10_000 }) - disk.holdAsync = true - sink.push({ batch: 'a' }) - let flushed = false - const flushing = sink.flushAsync().then(() => { - flushed = true - }) - await heldCount(1) - sink.push({ batch: 'b' }) - disk.heldWrites.shift()?.() - // Batch b is now held; flush must not wait for it. - await heldCount(1) - await vi.waitFor(() => expect(flushed).toBe(true), { timeout: 10_000 }) - expect(disk.heldWrites).toHaveLength(1) - releaseDisk() - await flushing - await sink.flushAsync() - sink.close() - }) - - it('two concurrent flushes both wait for lines queued behind an in-flight batch', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 100_000 }) - disk.holdAsync = true - sink.push({ name: 'A' }) - const firstBatch = sink.flushAsync() - await writeIsHeld() - sink.push({ name: 'L' }) - const first = sink.flushAsync() - const second = sink.flushAsync() - releaseDisk() - await second - expect(readJsonLines(filePath)).toContainEqual({ name: 'L' }) - await Promise.all([first, firstBatch]) - sink.close() - }) - - it('flush resolves right after a crash-boundary flush that follows a finished batch', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 100_000 }) - sink.push({ name: 'a' }) - await sink.flushAsync() - sink.push({ name: 'b' }) - sink.flush() - let flushed = false - void sink.flushAsync().then(() => { - flushed = true - }) - await vi.waitFor(() => expect(flushed).toBe(true), { timeout: 10_000 }) - expect(readJsonLines(filePath)).toEqual([{ name: 'a' }, { name: 'b' }]) - sink.close() - }) - - it('drops the oldest daemon entries when full, so the fatal line still lands', async () => { - const filePath = join(dir, 'daemon.log') - const log = createDaemonFileLog(filePath, { maxQueuedChars: 2_000 }) - disk.holdAsync = true - log.log('tick', { i: -1 }) - await writeIsHeld() - for (let i = 0; i < 200; i++) { - log.log('tick', { i }) - } - log.log('uncaught-exception-fatal') - log.close() - const events = (): unknown[] => readJsonLines(filePath).map((line) => line.event) - expect(events()).toContain('uncaught-exception-fatal') - releaseDisk() - const ticksWritten = (): unknown[] => - readJsonLines(filePath).flatMap((line) => (line.event === 'tick' ? [line.i] : [])) - // The held batch lands after the synchronous close. - await vi.waitFor(() => expect(ticksWritten()).toContain(-1), { timeout: 10_000 }) - - const lines = readJsonLines(filePath) - const ticks = lines.filter((line) => line.event === 'tick') - const markers = lines.filter((line) => line.event === 'log-entries-dropped') - expect(ticks.length).toBeLessThan(201) - expect(markers.map((line) => line.count)).toEqual([201 - ticks.length]) - expect(ticks.map((line) => line.i)).toContain(199) - }) - - it('drops trace records past the queue cap and reports the count once writes recover', async () => { - const filePath = join(dir, 'trace.ndjson') - const sink = createLocalFileSink({ filePath, batchWindowMs: 1, maxQueuedChars: 2_000 }) - disk.holdAsync = true - sink.push({ i: -1 }) - await writeIsHeld() - for (let i = 0; i < 200; i++) { - sink.push({ i, payload: 'x'.repeat(40) }) - } - releaseDisk() - await sink.flushAsync() - sink.push({ recovered: true }) - await sink.flushAsync() - - const lines = readJsonLines(filePath) - const records = lines.filter((line) => typeof line.i === 'number') - const marker = lines.find((line) => line.type === DROPPED_RECORD_TYPE) - expect(records.length).toBeLessThan(201) - expect(marker).toMatchObject({ reason: 'queue-full', droppedRecords: 201 - records.length }) - expect(lines.at(-1)).toEqual({ recovered: true }) - sink.close() - }) -}) diff --git a/src/main/opencode-usage/opencode2-session-usage.test.ts b/src/main/opencode-usage/opencode2-session-usage.test.ts deleted file mode 100644 index 503f26845e6..00000000000 --- a/src/main/opencode-usage/opencode2-session-usage.test.ts +++ /dev/null @@ -1,444 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import Database from '../sqlite/sync-database' -import { createUsageWorktreeResolver } from '../usage/usage-worktree-resolver' -import { parseOpenCodeUsageRow } from './opencode-usage-row-parsing' -import { selectUsageRows } from './opencode-usage-row-queries' -import { - OPENCODE_USAGE_FIXTURE_EPOCH_MS, - writeOpenCodeUsageDatabase, - type OpenCodeUsageFixtureSpec -} from './opencode-usage-sqlite-fixture' -import { parseOpenCodeUsageDatabase } from './scanner' - -const WORKTREE = '/workspace/repo' - -let tempDirs: string[] = [] - -afterEach(() => { - for (const dir of tempDirs) { - rmSync(dir, { recursive: true, force: true }) - } - tempDirs = [] -}) - -function createFixture(spec: OpenCodeUsageFixtureSpec): string { - const dir = mkdtempSync(join(tmpdir(), 'orca-opencode2-usage-')) - tempDirs.push(dir) - const path = join(dir, 'opencode.db') - writeOpenCodeUsageDatabase(path, spec) - return path -} - -function readEvents(dbPath: string) { - const db = new Database(dbPath, { readonly: true, fileMustExist: true }) - try { - return selectUsageRows(db).flatMap((row) => parseOpenCodeUsageRow(row) ?? []) - } finally { - db.close() - } -} - -async function worktreeResolver() { - return createUsageWorktreeResolver([ - { - repoId: 'repo-1', - worktreeId: 'repo-1::/workspace/repo', - path: WORKTREE, - displayName: 'Repo' - } - ]) -} - -describe('OpenCode 2 session_v2 usage', () => { - it('reads sessions that exist only in session_v2', () => { - const path = createFixture({ - generation: 'v2-only', - v2Sessions: [ - { - id: 'ses_v2_1', - directory: WORKTREE, - cost: 0.5, - tokensInput: 100, - tokensOutput: 20, - tokensReasoning: 5, - tokensCacheRead: 900, - tokensCacheWrite: 300 - } - ] - }) - - expect(readEvents(path)).toEqual([ - expect.objectContaining({ - sessionId: 'ses_v2_1', - cwd: WORKTREE, - model: 'anthropic/claude-sonnet-4-5', - estimatedCostUsd: 0.5, - inputTokens: 1300, - outputTokens: 20, - reasoningOutputTokens: 5, - cachedInputTokens: 1200, - totalTokens: 1325 - }) - ]) - }) - - it('includes cache read and cache write tokens in the session total', () => { - const path = createFixture({ - generation: 'v2-only', - v2Sessions: [ - { - id: 'ses_cache', - directory: WORKTREE, - tokensInput: 10, - tokensOutput: 1, - tokensCacheRead: 5_000, - tokensCacheWrite: 2_000 - } - ] - }) - - const [event] = readEvents(path) - expect(event?.cachedInputTokens).toBe(7_000) - expect(event?.inputTokens).toBe(7_010) - expect(event?.totalTokens).toBe(7_011) - }) - - it('counts a migrated session once, from session_v2', () => { - const shared = { - id: 'ses_shared', - directory: WORKTREE, - tokensInput: 100, - tokensCacheRead: 40 - } - const path = createFixture({ - generation: 'migrated', - legacySessions: [shared], - v2Sessions: [ - { ...shared, tokensInput: 180, tokensCacheRead: 60 }, - { id: 'ses_v2_only', directory: WORKTREE, tokensInput: 7 } - ] - }) - - const events = readEvents(path) - expect(events.map((event) => event.sessionId)).toEqual(['ses_shared', 'ses_v2_only']) - expect(events[0]?.inputTokens).toBe(240) - expect(events[0]?.cachedInputTokens).toBe(60) - }) - - it('keeps the legacy totals when session_v2 lacks the token columns', () => { - const path = createFixture({ - generation: 'migrated', - v2WithoutTokenColumns: true, - legacySessions: [{ id: 'ses_shared', directory: WORKTREE, tokensInput: 1000, cost: 5 }], - v2Sessions: [{ id: 'ses_shared', directory: WORKTREE }] - }) - - const events = readEvents(path) - expect(events.map((event) => event.sessionId)).toEqual(['ses_shared']) - expect(events[0]?.inputTokens).toBe(1000) - expect(events[0]?.estimatedCostUsd).toBe(5) - }) - - it('keeps the legacy totals when the migration recomputed session_v2 lower', () => { - const path = createFixture({ - generation: 'migrated', - // Migration drops undecodable messages, so v2 totals may be lower than frozen v1 totals. - legacySessions: [{ id: 'ses_shared', directory: WORKTREE, tokensInput: 900 }], - v2Sessions: [{ id: 'ses_shared', directory: WORKTREE, tokensInput: 120 }] - }) - - const events = readEvents(path) - expect(events.map((event) => event.sessionId)).toEqual(['ses_shared']) - expect(events[0]?.inputTokens).toBe(900) - }) - - it('resolves an identical migrated copy to session_v2', () => { - const shared = { id: 'ses_shared', directory: WORKTREE, tokensInput: 64 } - const path = createFixture({ - generation: 'migrated', - legacySessions: [{ ...shared, model: '{"providerID":"anthropic","modelID":"legacy"}' }], - v2Sessions: [{ ...shared, model: '{"providerID":"anthropic","modelID":"v2"}' }] - }) - - const events = readEvents(path) - expect(events.map((event) => event.sessionId)).toEqual(['ses_shared']) - expect(events[0]?.inputTokens).toBe(64) - expect(events[0]?.model).toContain('v2') - }) - - it('keeps legacy sessions that never migrated', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [{ id: 'ses_legacy_only', directory: WORKTREE, tokensInput: 42 }], - v2Sessions: [{ id: 'ses_v2_1', directory: WORKTREE, tokensInput: 9 }] - }) - - expect( - readEvents(path) - .map((event) => event.sessionId) - .sort() - ).toEqual(['ses_legacy_only', 'ses_v2_1']) - }) - - it('still reads an OpenCode 1 database unchanged', () => { - const path = createFixture({ - generation: 'v1', - legacySessions: [ - { - id: 'ses_v1', - directory: WORKTREE, - cost: 1.25, - tokensInput: 11, - tokensOutput: 3, - tokensCacheRead: 7, - tokensCacheWrite: 2 - } - ] - }) - - expect(readEvents(path)).toEqual([ - expect.objectContaining({ - sessionId: 'ses_v1', - estimatedCostUsd: 1.25, - inputTokens: 20, - outputTokens: 3, - cachedInputTokens: 9, - totalTokens: 23 - }) - ]) - }) - - it('reads assistant session_message rows when session_v2 carries no totals', () => { - const path = createFixture({ - generation: 'v2-only', - v2Sessions: [{ id: 'ses_msg', directory: WORKTREE }] - }) - const db = new Database(path) - db.prepare( - `INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) - VALUES ('msg-1', 'ses_msg', 'assistant', 1, ?, ?, ?)` - ).run( - OPENCODE_USAGE_FIXTURE_EPOCH_MS, - OPENCODE_USAGE_FIXTURE_EPOCH_MS, - JSON.stringify({ - tokens: { input: 60, output: 4, reasoning: 0, cache: { read: 12, write: 3 } }, - cost: 0.02, - time: { created: OPENCODE_USAGE_FIXTURE_EPOCH_MS } - }) - ) - db.close() - - expect(readEvents(path)).toEqual([ - expect.objectContaining({ sessionId: 'ses_msg', inputTokens: 75, cachedInputTokens: 15 }) - ]) - }) - - it('attributes session_v2 usage to the worktree that ran it', async () => { - const path = createFixture({ - generation: 'v2-only', - v2Sessions: [ - { id: 'ses_in_worktree', directory: WORKTREE, tokensInput: 30 }, - { id: 'ses_elsewhere', directory: '/elsewhere/project', tokensInput: 40 } - ] - }) - - const parsed = await parseOpenCodeUsageDatabase(path, await worktreeResolver()) - const byId = new Map(parsed.sessions.map((session) => [session.sessionId, session])) - expect(byId.get('ses_in_worktree')).toMatchObject({ - primaryWorktreeId: 'repo-1::/workspace/repo', - primaryRepoId: 'repo-1', - primaryProjectLabel: 'Repo', - totalInputTokens: 30 - }) - expect(byId.get('ses_elsewhere')).toMatchObject({ - primaryWorktreeId: null, - primaryRepoId: null, - totalInputTokens: 40 - }) - }) - - it('keeps a session that only session_v2 has when a legacy twin is absent', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [{ id: 'ses_shared', directory: WORKTREE, tokensInput: 5 }], - v2Sessions: [ - { id: 'ses_shared', directory: WORKTREE, tokensInput: 5 }, - { id: 'ses_v2_only', directory: WORKTREE, cost: 3.25, tokensInput: 70 } - ] - }) - - const events = readEvents(path) - const v2Only = events.find((event) => event.sessionId === 'ses_v2_only') - expect(v2Only).toMatchObject({ inputTokens: 70, estimatedCostUsd: 3.25, cwd: WORKTREE }) - }) - - it('falls back to the project worktree when the session has no directory', async () => { - const path = createFixture({ - generation: 'v2-only', - worktree: WORKTREE, - v2Sessions: [{ id: 'ses_no_dir', directory: '', tokensInput: 15 }] - }) - - const parsed = await parseOpenCodeUsageDatabase(path, await worktreeResolver()) - expect(parsed.sessions[0]).toMatchObject({ - sessionId: 'ses_no_dir', - primaryWorktreeId: 'repo-1::/workspace/repo' - }) - }) -}) - -describe('OpenCode 2 migrated session column merge', () => { - const SHARED = 'ses_shared' - - it('keeps a recorded cost the recomputed session_v2 row lost', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [{ id: SHARED, directory: WORKTREE, tokensInput: 100, cost: 12.5 }], - v2Sessions: [{ id: SHARED, directory: WORKTREE, tokensInput: 200, cost: 0 }] - }) - - const events = readEvents(path) - expect(events).toHaveLength(1) - expect(events[0]?.inputTokens).toBe(200) - expect(events[0]?.estimatedCostUsd).toBe(12.5) - }) - - it('attributes usage to the directory session_v2 records now', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [ - { id: SHARED, directory: '/old/pre-migration-path', title: 'Old title', tokensInput: 900 } - ], - v2Sessions: [ - { id: SHARED, directory: '/new/current-path', title: 'New title', tokensInput: 120 } - ] - }) - - const events = readEvents(path) - expect(events).toHaveLength(1) - expect(events[0]?.inputTokens).toBe(900) - expect(events[0]?.cwd).toBe('/new/current-path') - }) - - it('keeps the model session_v2 derived when the legacy row has none', () => { - const path = createFixture({ - generation: 'migrated', - // Migration derives a missing v1 model from the last user message. - legacySessions: [{ id: SHARED, directory: WORKTREE, model: null, tokensInput: 900 }], - v2Sessions: [ - { - id: SHARED, - directory: WORKTREE, - model: '{"providerID":"anthropic","modelID":"claude-opus-4-1"}', - tokensInput: 120 - } - ] - }) - - const events = readEvents(path) - expect(events).toHaveLength(1) - expect(events[0]?.inputTokens).toBe(900) - expect(events[0]?.model).toBe('anthropic/claude-opus-4-1') - }) - - it('takes each usage column from whichever generation recorded more', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [ - { id: SHARED, directory: WORKTREE, tokensInput: 1000, tokensCacheRead: 0, cost: 1 } - ], - v2Sessions: [ - { id: SHARED, directory: WORKTREE, tokensInput: 0, tokensCacheRead: 1200, cost: 2 } - ] - }) - - const events = readEvents(path) - expect(events).toHaveLength(1) - expect(events[0]).toMatchObject({ - inputTokens: 2200, - cachedInputTokens: 1200, - estimatedCostUsd: 2, - totalTokens: 2200 - }) - }) - - it('resolves a faithful migrated copy exactly as the v2 row alone', () => { - const session = { - id: SHARED, - directory: WORKTREE, - cost: 0.75, - tokensInput: 100, - tokensOutput: 20, - tokensReasoning: 5, - tokensCacheRead: 900, - tokensCacheWrite: 300 - } - const migrated = readEvents( - createFixture({ - generation: 'migrated', - legacySessions: [session], - v2Sessions: [session] - }) - ) - - expect(migrated).toEqual( - readEvents(createFixture({ generation: 'v2-only', v2Sessions: [session] })) - ) - }) - - it('leaves an OpenCode 1-only database untouched by the merge', () => { - const path = createFixture({ - generation: 'v1', - legacySessions: [ - { - id: 'ses_v1', - directory: WORKTREE, - cost: 1.25, - tokensInput: 11, - tokensOutput: 3, - tokensCacheRead: 7, - tokensCacheWrite: 2 - } - ] - }) - - expect(readEvents(path)).toEqual([ - expect.objectContaining({ - sessionId: 'ses_v1', - cwd: WORKTREE, - model: 'anthropic/claude-sonnet-4-5', - estimatedCostUsd: 1.25, - inputTokens: 20, - outputTokens: 3, - cachedInputTokens: 9, - totalTokens: 23 - }) - ]) - }) - - it('emits exactly one row per session id across both generations', () => { - const path = createFixture({ - generation: 'migrated', - legacySessions: [ - { id: SHARED, directory: WORKTREE, tokensInput: 900 }, - { id: 'ses_legacy_only', directory: WORKTREE, tokensInput: 42 } - ], - v2Sessions: [ - { id: SHARED, directory: WORKTREE, tokensInput: 120 }, - { id: 'ses_v2_only', directory: WORKTREE, tokensInput: 7 } - ] - }) - - const db = new Database(path, { readonly: true, fileMustExist: true }) - try { - const ids = selectUsageRows(db).map((row) => row.id) - expect(ids).toHaveLength(3) - expect(new Set(ids).size).toBe(3) - } finally { - db.close() - } - }) -}) diff --git a/src/main/opencode-usage/scanner.test.ts b/src/main/opencode-usage/scanner.test.ts index 6c760b6d0f5..16859e750ca 100644 --- a/src/main/opencode-usage/scanner.test.ts +++ b/src/main/opencode-usage/scanner.test.ts @@ -5,32 +5,10 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import Database from '../sqlite/sync-database' import { listOpenCodeDatabases } from './opencode-database-discovery' import { parseOpenCodeUsageRow } from './opencode-usage-row-parsing' -import { createUsageWorktreeResolver } from '../usage/usage-worktree-resolver' -import { attributeOpenCodeUsageEvent } from './opencode-usage-worktree-attribution' -import { parseOpenCodeUsageDatabase, scanOpenCodeUsageDatabases } from './scanner' +import { scanOpenCodeUsageDatabases } from './scanner' const WORKTREE = '/workspace/repo' -let tempDirs: string[] = [] - -function createTempDb(): { db: Database.Database; path: string } { - const dir = mkdtempSync(join(tmpdir(), 'orca-opencode-usage-')) - tempDirs.push(dir) - const path = join(dir, 'opencode.db') - return { db: new Database(path), path } -} - -async function resolveWorktree() { - return createUsageWorktreeResolver([ - { - repoId: 'repo-1', - worktreeId: 'repo-1::/workspace/repo', - path: WORKTREE, - displayName: 'Repo' - } - ]) -} - function createSessionTotalsSchema(db: Database.Database): void { db.exec(` CREATE TABLE session ( @@ -77,65 +55,7 @@ function insertSessionTotalsRow( ) } -function usageEvent(cwd: string) { - return { - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - cwd, - model: 'anthropic/claude-sonnet-4-5', - estimatedCostUsd: 0.012, - inputTokens: 100, - cachedInputTokens: 10, - outputTokens: 25, - reasoningOutputTokens: 10, - totalTokens: 125 - } -} - describe('parseOpenCodeUsageRow', () => { - it('reads assistant message tokens, cost, model, cwd, and timestamp', () => { - const parsed = parseOpenCodeUsageRow({ - id: 'message-1', - session_id: 'session-1', - time_created: 1_777_777_700_000, - time_updated: null, - directory: null, - title: null, - worktree: null, - session_model: null, - data: JSON.stringify({ - providerID: 'anthropic', - modelID: 'claude-sonnet-4-5', - path: { cwd: `${WORKTREE}/packages/app` }, - cost: 0.0123, - tokens: { - input: 1000, - output: 250, - reasoning: 100, - total: 1350, - cache: { read: 400, write: 25 } - }, - time: { - completed: 1_777_777_800_000 - } - }) - }) - - expect(parsed).toEqual({ - sessionId: 'session-1', - timestamp: new Date(1_777_777_800_000).toISOString(), - cwd: `${WORKTREE}/packages/app`, - model: 'anthropic/claude-sonnet-4-5', - estimatedCostUsd: 0.0123, - inputTokens: 1425, - cachedInputTokens: 425, - cacheWriteInputTokens: 25, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1775 - }) - }) - it.each([ [undefined, 10_125], [125, 10_125], @@ -175,227 +95,6 @@ describe('parseOpenCodeUsageRow', () => { }) }) -describe('attributeOpenCodeUsageEvent', () => { - it('does not attribute true parent-directory escapes to the worktree', async () => { - const attributed = await attributeOpenCodeUsageEvent( - usageEvent(`${WORKTREE}/../other/session`), - await resolveWorktree() - ) - - expect(attributed?.projectKey).toBe('cwd:/workspace/repo/../other/session') - expect(attributed?.worktreeId).toBeNull() - }) -}) - -describe('parseOpenCodeUsageDatabase', () => { - afterEach(() => { - for (const dir of tempDirs) { - rmSync(dir, { recursive: true, force: true }) - } - tempDirs = [] - }) - - it('uses materialized session token totals when the OpenCode DB has them', async () => { - const { db, path } = createTempDb() - db.exec(` - CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT); - CREATE TABLE session ( - id TEXT PRIMARY KEY, - project_id TEXT, - directory TEXT, - title TEXT, - model TEXT, - cost REAL, - tokens_input INTEGER, - tokens_output INTEGER, - tokens_reasoning INTEGER, - tokens_cache_read INTEGER, - tokens_cache_write INTEGER, - time_created INTEGER, - time_updated INTEGER - ); - `) - db.prepare('INSERT INTO project (id, worktree) VALUES (?, ?)').run('project-1', WORKTREE) - db.prepare( - `INSERT INTO session ( - id, project_id, directory, title, model, cost, - tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write, - time_created, time_updated - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` - ).run( - 'session-1', - 'project-1', - `${WORKTREE}/packages/app`, - 'Build feature', - JSON.stringify({ providerID: 'anthropic', id: 'claude-sonnet-4-5' }), - 0.06, - 1000, - 500, - 100, - 250, - 75, - 1_777_777_700_000, - 1_777_777_800_000 - ) - db.close() - - const parsed = await parseOpenCodeUsageDatabase(path, await resolveWorktree()) - - expect(parsed.sessions).toHaveLength(1) - expect(parsed.sessions[0]).toMatchObject({ - sessionId: 'session-1', - primaryModel: 'anthropic/claude-sonnet-4-5', - primaryProjectLabel: 'Repo', - eventCount: 1, - totalInputTokens: 1325, - totalCachedInputTokens: 325, - totalOutputTokens: 500, - totalReasoningOutputTokens: 100, - totalTokens: 1925, - estimatedCostUsd: 0.06 - }) - expect(parsed.dailyAggregates).toEqual([ - expect.objectContaining({ - projectLabel: 'Repo', - inputTokens: 1325, - cachedInputTokens: 325, - outputTokens: 500, - reasoningOutputTokens: 100, - totalTokens: 1925, - estimatedCostUsd: 0.06 - }) - ]) - }) - - it('supports session_message tables without a type column', async () => { - const { db, path } = createTempDb() - db.exec(` - CREATE TABLE session ( - id TEXT PRIMARY KEY, - directory TEXT, - title TEXT, - time_created INTEGER, - time_updated INTEGER - ); - CREATE TABLE session_message ( - id TEXT PRIMARY KEY, - session_id TEXT, - time_created INTEGER, - time_updated INTEGER, - data TEXT - ); - `) - db.prepare( - 'INSERT INTO session (id, directory, title, time_created, time_updated) VALUES (?, ?, ?, ?, ?)' - ).run('session-1', `${WORKTREE}/tools`, 'Legacy session', 1_777_777_700_000, 1_777_777_800_000) - db.prepare( - 'INSERT INTO session_message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)' - ).run( - 'message-1', - 'session-1', - 1_777_777_700_000, - 1_777_777_800_000, - JSON.stringify({ - providerID: 'openai', - modelID: 'gpt-5.5', - cost: 0.03, - tokens: { - input: 800, - output: 200, - reasoning: 50, - cache: { read: 100, write: 0 } - } - }) - ) - db.close() - - const parsed = await parseOpenCodeUsageDatabase(path, await resolveWorktree()) - - expect(parsed.sessions[0]).toMatchObject({ - primaryModel: 'openai/gpt-5.5', - primaryProjectLabel: 'Repo', - totalTokens: 1150, - estimatedCostUsd: 0.03 - }) - }) - - it('reports the session ids the database counted', async () => { - const { db, path } = createTempDb() - createSessionTotalsSchema(db) - insertSessionTotalsRow(db, 'session-1', 1000) - db.close() - - const parsed = await parseOpenCodeUsageDatabase(path, await resolveWorktree()) - - expect(parsed.ownedSessionIds).toEqual(['session-1']) - }) - - it('prefers session_message rows over legacy message rows to avoid double counting', async () => { - const { db, path } = createTempDb() - db.exec(` - CREATE TABLE session ( - id TEXT PRIMARY KEY, - directory TEXT, - title TEXT, - time_created INTEGER, - time_updated INTEGER - ); - CREATE TABLE session_message ( - id TEXT PRIMARY KEY, - session_id TEXT, - type TEXT, - time_created INTEGER, - time_updated INTEGER, - data TEXT - ); - CREATE TABLE message ( - id TEXT PRIMARY KEY, - session_id TEXT, - time_created INTEGER, - time_updated INTEGER, - data TEXT - ); - `) - db.prepare( - 'INSERT INTO session (id, directory, title, time_created, time_updated) VALUES (?, ?, ?, ?, ?)' - ).run('session-1', WORKTREE, 'Mixed schema session', 1_777_777_700_000, 1_777_777_800_000) - db.prepare( - 'INSERT INTO session_message (id, session_id, type, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)' - ).run( - 'session-message-1', - 'session-1', - 'assistant', - 1_777_777_700_000, - 1_777_777_800_000, - JSON.stringify({ - providerID: 'openai', - modelID: 'gpt-5.5', - tokens: { input: 100, output: 20, reasoning: 0, cache: { read: 10, write: 0 } } - }) - ) - db.prepare( - 'INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)' - ).run( - 'legacy-message-1', - 'session-1', - 1_777_777_700_000, - 1_777_777_800_000, - JSON.stringify({ - role: 'assistant', - providerID: 'openai', - modelID: 'gpt-5.5', - tokens: { input: 1000, output: 500, reasoning: 0, cache: { read: 100, write: 0 } } - }) - ) - db.close() - - const parsed = await parseOpenCodeUsageDatabase(path, await resolveWorktree()) - - expect(parsed.sessions[0]?.totalTokens).toBe(130) - expect(parsed.sessions[0]?.eventCount).toBe(1) - }) -}) - describe('scanOpenCodeUsageDatabases', () => { let dataRoot: string let openCodeDir: string @@ -506,52 +205,6 @@ describe('scanOpenCodeUsageDatabases', () => { expect(sessionOne?.eventCount).toBe(1) }) - it('reuses a fully-duplicate backup instead of reparsing it when the live db changes', async () => { - const canonicalPath = writeSessionTotalsDb('opencode.db', [['session-1', 1000]]) - writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) - - const first = await scanOpenCodeUsageDatabases([], []) - const firstBackup = first.processedDatabases.find((database) => - database.path.endsWith('opencode-backup.db') - ) - expect(firstBackup?.ownedSessionIds).toEqual([]) - - appendLiveSessionRow(canonicalPath, 'session-2', 200) - - const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) - const secondBackup = second.processedDatabases.find((database) => - database.path.endsWith('opencode-backup.db') - ) - // Cache reuse preserves object identity. - expect(secondBackup).toBe(firstBackup) - expect( - second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1200) - }) - - it('lets the live database reclaim sessions after a sticky backup-only claim', async () => { - writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) - - const first = await scanOpenCodeUsageDatabases([], []) - expect( - first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(400) - expect(first.processedDatabases[0]?.ownedSessionIds).toEqual(['session-1']) - - writeSessionTotalsDb('opencode.db', [ - ['session-1', 1000], - ['session-2', 200] - ]) - - const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) - expect( - second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1200) - const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') - expect(sessionOne?.totalInputTokens).toBe(1000) - expect(sessionOne?.eventCount).toBe(1) - }) - it('reclaims sessions when the owning live database is deleted', async () => { const canonicalPath = writeSessionTotalsDb('opencode.db', [ ['session-1', 1000], diff --git a/src/main/opencode-usage/store.test.ts b/src/main/opencode-usage/store.test.ts deleted file mode 100644 index 57fa7928db9..00000000000 --- a/src/main/opencode-usage/store.test.ts +++ /dev/null @@ -1,375 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - OpenCodeUsageDailyAggregate, - OpenCodeUsagePersistedState, - OpenCodeUsageSession -} from './types' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn(() => '/tmp/orca-test-userdata') -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanOpenCodeUsageDatabasesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -import { OpenCodeUsageStore, initOpenCodeUsagePath } from './store' -import { OPENCODE_USAGE_SCHEMA_VERSION } from './opencode-usage-provider' -import { normalizePersistedState } from './persisted-state-normalization' -import { scanOpenCodeUsageDatabasesViaWorker } from '../usage/usage-scan-worker-spawn' - -function createEmptyScanResult() { - return { - sessions: [], - dailyAggregates: [] - } -} - -function getDefaultState(): OpenCodeUsagePersistedState { - return { - schemaVersion: OPENCODE_USAGE_SCHEMA_VERSION, - worktreeFingerprint: null, - processedDatabases: [], - sessions: [], - dailyAggregates: [], - scanState: { - enabled: false, - lastScanStartedAt: null, - lastScanCompletedAt: null, - lastScanError: null - } - } -} - -function createStoreWithState(state: Partial): OpenCodeUsageStore { - const store = new OpenCodeUsageStore({ - getRepos: () => [], - getAllWorktreeMeta: () => ({}) - }) - - ;(store as unknown as { state: OpenCodeUsagePersistedState }).state = { - ...getDefaultState(), - ...state - } - - return store -} - -function makeSession(overrides: Partial = {}): OpenCodeUsageSession { - const worktreeId = overrides.primaryWorktreeId ?? 'repo-1::/workspace/repo' - const repoId = overrides.primaryRepoId ?? 'repo-1' - const projectLabel = overrides.primaryProjectLabel ?? 'Repo' - const model = overrides.primaryModel ?? 'anthropic/claude-sonnet-4-5' - return { - sessionId: 'session-1', - firstTimestamp: '2026-04-09T10:00:00.000Z', - lastTimestamp: '2026-04-09T10:10:00.000Z', - primaryModel: model, - hasMixedModels: false, - primaryProjectLabel: projectLabel, - hasMixedLocations: false, - primaryWorktreeId: worktreeId, - primaryRepoId: repoId, - eventCount: 1, - totalInputTokens: 1000, - totalCachedInputTokens: 400, - totalOutputTokens: 250, - totalReasoningOutputTokens: 100, - totalTokens: 1350, - estimatedCostUsd: 0.05, - locationBreakdown: [ - { - locationKey: worktreeId ? `worktree:${worktreeId}` : 'cwd:/outside/repo', - projectLabel, - repoId, - worktreeId, - eventCount: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1350, - estimatedCostUsd: 0.05 - } - ], - modelBreakdown: [ - { - modelKey: model ?? 'unknown', - modelLabel: model ?? 'Unknown model', - eventCount: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1350, - estimatedCostUsd: 0.05 - } - ], - locationModelBreakdown: [ - { - locationKey: worktreeId ? `worktree:${worktreeId}` : 'cwd:/outside/repo', - modelKey: model ?? 'unknown', - modelLabel: model ?? 'Unknown model', - repoId, - worktreeId, - eventCount: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1350, - estimatedCostUsd: 0.05 - } - ], - ...overrides - } -} - -function makeDaily( - overrides: Partial = {} -): OpenCodeUsageDailyAggregate { - const worktreeId = overrides.worktreeId ?? 'repo-1::/workspace/repo' - return { - day: '2026-04-09', - model: 'anthropic/claude-sonnet-4-5', - projectKey: worktreeId ? `worktree:${worktreeId}` : 'cwd:/outside/repo', - projectLabel: worktreeId ? 'Repo' : 'outside/repo', - repoId: worktreeId ? 'repo-1' : null, - worktreeId, - eventCount: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1350, - estimatedCostUsd: 0.05, - ...overrides - } -} - -describe('OpenCodeUsageStore', () => { - let tempUserData: string - - beforeEach(() => { - tempUserData = mkdtempSync(join(tmpdir(), 'orca-opencode-usage-store-')) - getPathMock.mockReturnValue(tempUserData) - initOpenCodeUsagePath() - vi.mocked(scanOpenCodeUsageDatabasesViaWorker).mockReset() - vi.mocked(scanOpenCodeUsageDatabasesViaWorker).mockResolvedValue(createEmptyScanResult()) - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-04-10T12:00:00.000-04:00')) - }) - - afterEach(() => { - vi.useRealTimers() - rmSync(tempUserData, { recursive: true, force: true }) - }) - - it('hands OpenCode scans the worker-owned source cache and persists a compact report', async () => { - const store = createStoreWithState({ - scanState: { - enabled: true, - lastScanStartedAt: null, - lastScanCompletedAt: null, - lastScanError: null - } - }) - - await store.refresh(true) - - const persistedJson = readFileSync(join(tempUserData, 'orca-opencode-usage.json'), 'utf-8') - expect(scanOpenCodeUsageDatabasesViaWorker).toHaveBeenCalledWith([], { - path: join(tempUserData, 'orca-opencode-usage-sources.json'), - schemaVersion: OPENCODE_USAGE_SCHEMA_VERSION, - worktreeFingerprint: '[]', - reuse: false - }) - expect(persistedJson).not.toContain('\n') - }) - - it('reports no data for Orca scope when only non-Orca OpenCode usage exists', async () => { - const store = createStoreWithState({ - sessions: [ - makeSession({ - primaryProjectLabel: 'outside/repo', - primaryWorktreeId: null, - primaryRepoId: null - }) - ], - dailyAggregates: [ - makeDaily({ - projectKey: 'cwd:/outside/repo', - projectLabel: 'outside/repo', - repoId: null, - worktreeId: null - }) - ] - }) - - const summary = await store.getSummary('orca', '30d') - - expect(summary.hasAnyOpenCodeData).toBe(false) - expect(summary.sessions).toBe(0) - expect(summary.events).toBe(0) - }) - - it('uses recorded OpenCode costs and token totals without model pricing inference', async () => { - const store = createStoreWithState({ - sessions: [ - makeSession({ sessionId: 'session-1' }), - makeSession({ - sessionId: 'session-2', - primaryModel: 'openai/gpt-5.5', - totalTokens: 2000, - estimatedCostUsd: null, - modelBreakdown: [ - { - modelKey: 'openai/gpt-5.5', - modelLabel: 'openai/gpt-5.5', - eventCount: 1, - inputTokens: 1500, - cachedInputTokens: 200, - outputTokens: 500, - reasoningOutputTokens: 0, - totalTokens: 2000, - estimatedCostUsd: null - } - ] - }) - ], - dailyAggregates: [ - makeDaily(), - makeDaily({ - model: 'openai/gpt-5.5', - eventCount: 2, - inputTokens: 1500, - cachedInputTokens: 200, - outputTokens: 500, - reasoningOutputTokens: 0, - totalTokens: 2000, - estimatedCostUsd: null - }) - ] - }) - - const summary = await store.getSummary('orca', '30d') - const daily = await store.getDaily('orca', '30d') - const breakdown = await store.getBreakdown('orca', '30d', 'model') - - expect(summary).toMatchObject({ - sessions: 2, - events: 3, - inputTokens: 2500, - cachedInputTokens: 600, - outputTokens: 750, - reasoningOutputTokens: 100, - totalTokens: 3350, - estimatedCostUsd: 0.05, - topModel: 'openai/gpt-5.5', - topProject: 'Repo', - hasAnyOpenCodeData: true - }) - expect(daily).toEqual([ - { - day: '2026-04-09', - inputTokens: 2500, - cachedInputTokens: 600, - outputTokens: 750, - reasoningOutputTokens: 100, - totalTokens: 3350 - } - ]) - expect(breakdown.find((row) => row.key === 'openai/gpt-5.5')).toMatchObject({ - sessions: 1, - estimatedCostUsd: null - }) - }) - - it('returns recent sessions with OpenCode event and token fields', async () => { - const store = createStoreWithState({ - sessions: [makeSession()], - dailyAggregates: [makeDaily()] - }) - - const sessions = await store.getRecentSessions('orca', '30d', 5) - - expect(sessions).toEqual([ - { - sessionId: 'session-1', - lastActiveAt: '2026-04-09T10:10:00.000Z', - durationMinutes: 10, - projectLabel: 'Repo', - model: 'anthropic/claude-sonnet-4-5', - events: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1350 - } - ]) - }) - - it.each([true, false])('rebuilds v2 caches without changing enabled=%s', (enabled) => { - const oldState = { - ...getDefaultState(), - schemaVersion: 2, - sessions: [makeSession()], - dailyAggregates: [makeDaily()], - scanState: { ...getDefaultState().scanState, enabled, lastScanCompletedAt: 123 } - } - expect(normalizePersistedState(oldState)).toEqual({ - ...getDefaultState(), - scanState: { ...getDefaultState().scanState, enabled } - }) - }) - - it('normalizes persisted OpenCode state by schema version', () => { - expect( - normalizePersistedState({ - ...getDefaultState(), - schemaVersion: 0, - processedDatabases: [ - { - path: '/tmp/opencode.db', - mtimeMs: 1, - size: 2, - sessions: [makeSession()], - dailyAggregates: [makeDaily()], - ownedSessionIds: ['session-1'], - hasDeferredClaims: false - } - ], - sessions: [makeSession()], - dailyAggregates: [makeDaily()] - }) - ).toEqual(getDefaultState()) - - expect( - normalizePersistedState({ - ...getDefaultState(), - processedDatabases: [ - { - path: '/tmp/opencode.db', - mtimeMs: 1, - size: 2, - sessions: [], - dailyAggregates: [], - ownedSessionIds: [], - hasDeferredClaims: false - } - ] - }).processedDatabases - ).toHaveLength(1) - }) -}) diff --git a/src/main/opencode/hook-plugin-child-attention.test.ts b/src/main/opencode/hook-plugin-child-attention.test.ts deleted file mode 100644 index 47135c77510..00000000000 --- a/src/main/opencode/hook-plugin-child-attention.test.ts +++ /dev/null @@ -1,603 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { getPath: getPathMock } -})) - -import { _internals } from './hook-service' - -type SessionFixture = { id: string; parentID?: string } -type PluginEvent = { type: string; properties?: Record } -type PluginEventHandler = (input: { event: PluginEvent }) => Promise -type PluginHooks = { event: PluginEventHandler; dispose?: () => Promise } -type PluginFactory = (ctx: unknown) => Promise -type SessionList = ( - parameters?: { signal?: AbortSignal }, - options?: { signal?: AbortSignal } -) => Promise<{ data: SessionFixture[] }> -type RecordedPost = { - hook_event_name: string - id?: string - sessionID?: string -} - -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN', - 'ORCA_AGENT_HOOK_ENDPOINT' -] as const - -describe('OpenCode plugin child attention', () => { - let tempDir: string - let posts: RecordedPost[] - let savedEnv: Record - let savedFetch: typeof globalThis.fetch - let pluginFactory: PluginFactory | undefined - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-child-attention-')) - posts = [] - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - process.env.ORCA_AGENT_HOOK_PORT = '45678' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - pluginFactory = undefined - savedFetch = globalThis.fetch - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const body = JSON.parse(String(init?.body)) as { payload: RecordedPost } - posts.push(body.payload) - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - }) - - afterEach(() => { - vi.useRealTimers() - globalThis.fetch = savedFetch - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - }) - - async function createHooks( - sessions: SessionFixture[], - list: SessionList = async () => ({ - data: sessions - }) - ): Promise { - if (!pluginFactory) { - const pluginPath = join(tempDir, 'orca-opencode-status.mjs') - writeFileSync(pluginPath, _internals.getOpenCodePluginSource()) - const module = (await import(pathToFileURL(pluginPath).href)) as { - OrcaOpenCodeStatusPlugin: PluginFactory - } - pluginFactory = module.OrcaOpenCodeStatusPlugin - } - return pluginFactory({ - client: { - session: { - list - } - } - }) - } - - function status(type: 'busy' | 'idle', sessionID: string): PluginEvent { - return { - type: 'session.status', - properties: { sessionID, status: { type } } - } - } - - function attention( - type: 'permission.asked' | 'question.asked', - id: string, - sessionID: string, - tool?: { messageID: string; callID: string } - ): PluginEvent { - return { - type, - properties: { id, sessionID, ...(tool ? { tool } : {}) } - } - } - - function resolution( - type: 'permission.replied' | 'question.replied' | 'question.rejected', - requestID: string, - sessionID: string - ): PluginEvent { - return { - type, - properties: { requestID, sessionID } - } - } - - function completedQuestion( - sessionID: string, - messageID: string, - callID: string, - status: 'completed' | 'error' = 'completed' - ): PluginEvent { - return { - type: 'message.part.updated', - properties: { - sessionID, - part: { - type: 'tool', - tool: 'question', - messageID, - callID, - state: { status } - } - } - } - } - - function names(): string[] { - return posts.map((post) => post.hook_event_name) - } - - it.each([ - ['permission.asked', 'PermissionRequest'], - ['question.asked', 'AskUserQuestion'] - ] as const)('attributes nested child %s to the root pane', async (type, expectedName) => { - const hooks = await createHooks([ - { id: 'root' }, - { id: 'child', parentID: 'root' }, - { id: 'grandchild', parentID: 'child' } - ]) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: attention(type, 'request-1', 'grandchild') }) - - expect(posts.at(-1)).toMatchObject({ - hook_event_name: expectedName, - id: 'request-1', - sessionID: 'root' - }) - }) - - it('clears only the matching child reply or rejection and preserves root Busy', async () => { - const hooks = await createHooks([ - { id: 'root' }, - { id: 'child-a', parentID: 'root' }, - { id: 'child-b', parentID: 'root' } - ]) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: attention('question.asked', 'question-a', 'child-a') }) - const waitingPosts = posts.length - await hooks.event({ event: status('busy', 'root') }) - expect(posts).toHaveLength(waitingPosts) - - await hooks.event({ event: attention('permission.asked', 'permission-b', 'child-b') }) - await hooks.event({ - event: resolution('permission.replied', 'permission-b', 'child-a') - }) - expect(posts.at(-1)?.hook_event_name).toBe('PermissionRequest') - - await hooks.event({ - event: resolution('permission.replied', 'permission-b', 'child-b') - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'question-a', - sessionID: 'root' - }) - - await hooks.event({ - event: resolution('question.rejected', 'question-a', 'child-a') - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'SessionBusy', - sessionID: 'root' - }) - - await hooks.event({ event: status('idle', 'root') }) - expect(posts.at(-1)?.hook_event_name).toBe('SessionIdle') - }) - - it.each(['completed', 'error'] as const)( - 'clears only the matching child question when its tool is %s', - async (completionStatus) => { - const hooks = await createHooks([ - { id: 'root' }, - { id: 'child-a', parentID: 'root' }, - { id: 'child-b', parentID: 'root' } - ]) - const toolA = { messageID: 'message-a', callID: 'call-a' } - const toolB = { messageID: 'message-b', callID: 'call-b' } - - await hooks.event({ - event: attention('question.asked', 'question-a', 'child-a', toolA) - }) - await hooks.event({ - event: attention('question.asked', 'question-b', 'child-b', toolB) - }) - const waitingPosts = posts.length - await hooks.event({ - event: completedQuestion('child-a', toolB.messageID, toolB.callID, completionStatus) - }) - await hooks.event({ - event: completedQuestion('child-b', toolB.messageID, 'wrong-call', completionStatus) - }) - expect(posts).toHaveLength(waitingPosts) - - await hooks.event({ - event: completedQuestion('child-b', toolB.messageID, toolB.callID, completionStatus) - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'question-a', - sessionID: 'root' - }) - - await hooks.event({ - event: completedQuestion('child-a', toolA.messageID, toolA.callID, completionStatus) - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'SessionIdle', - sessionID: 'root' - }) - } - ) - - it('uses child Idle only to clean that child blocker, then restores root Busy', async () => { - const hooks = await createHooks([{ id: 'root' }, { id: 'child', parentID: 'root' }]) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: attention('question.asked', 'question-child', 'child') }) - await hooks.event({ event: status('idle', 'child') }) - - expect(names()).toEqual(['SessionBusy', 'AskUserQuestion', 'SessionBusy']) - expect(posts.at(-1)?.sessionID).toBe('root') - }) - - it('lets only matching unknown Idle retire attention across cyclic ancestry', async () => { - const list = vi.fn(async () => ({ - data: [ - { id: 'child-a', parentID: 'child-b' }, - { id: 'child-b', parentID: 'child-a' } - ] - })) - const hooks = await createHooks([], list) - - await hooks.event({ - event: attention('question.asked', 'cyclic-question', 'child-a') - }) - await hooks.event({ event: status('idle', 'child-b') }) - expect(names()).toEqual(['AskUserQuestion']) - - await hooks.event({ event: status('idle', 'child-a') }) - - expect(names()).toEqual(['AskUserQuestion', 'SessionIdle']) - expect(posts[0]).toMatchObject({ - id: 'cyclic-question', - sessionID: 'child-a' - }) - expect(posts.at(-1)?.sessionID).toBe('child-a') - expect(list).toHaveBeenCalledTimes(6) - }) - - it('matches a child reply after its ancestry lookup fails', async () => { - let lookupFails = false - const list = vi.fn(async () => { - if (lookupFails) { - throw new Error('lookup unavailable') - } - return { data: [{ id: 'root' }] } - }) - const hooks = await createHooks([], list) - - await hooks.event({ event: status('busy', 'root') }) - lookupFails = true - await hooks.event({ - event: attention('permission.asked', 'permission-child', 'child') - }) - await hooks.event({ - event: resolution('permission.replied', 'permission-child', 'child') - }) - - expect(names()).toEqual(['SessionBusy', 'PermissionRequest', 'SessionBusy']) - expect(posts.at(-1)?.sessionID).toBe('root') - }) - - it('clears timed-out child attention without repeating its ancestry lookup', async () => { - vi.useFakeTimers() - let lookupHangs = false - const list = vi.fn( - async (options?: { signal?: AbortSignal }): Promise<{ data: SessionFixture[] }> => { - if (!lookupHangs) { - return { data: [{ id: 'root' }] } - } - return new Promise((_resolve, reject) => { - options?.signal?.addEventListener('abort', () => reject(new Error('aborted')), { - once: true - }) - }) - } - ) - const hooks = await createHooks([], list) - await hooks.event({ event: status('busy', 'root') }) - lookupHangs = true - - const asked = hooks.event({ - event: attention('question.asked', 'question-child', 'child') - }) - await vi.advanceTimersByTimeAsync(2_000) - await asked - const lookupCountAfterAsk = list.mock.calls.length - const replied = hooks.event({ - event: resolution('question.replied', 'question-child', 'child') - }) - await replied - - expect(names()).toEqual(['SessionBusy', 'AskUserQuestion', 'SessionBusy']) - expect(posts.at(-1)?.sessionID).toBe('root') - expect(list).toHaveBeenCalledTimes(lookupCountAfterAsk) - }) - - it('clears timed-out child attention on Idle without making unknown Idle authoritative', async () => { - vi.useFakeTimers() - let lookupHangs = false - const list = vi.fn( - async (options?: { signal?: AbortSignal }): Promise<{ data: SessionFixture[] }> => { - if (!lookupHangs) { - return { data: [{ id: 'root' }] } - } - return new Promise((_resolve, reject) => { - options?.signal?.addEventListener('abort', () => reject(new Error('aborted')), { - once: true - }) - }) - } - ) - const hooks = await createHooks([], list) - await hooks.event({ event: status('busy', 'root') }) - lookupHangs = true - - const asked = hooks.event({ - event: attention('question.asked', 'question-child', 'child') - }) - await vi.advanceTimersByTimeAsync(2_000) - await asked - const idle = hooks.event({ event: status('idle', 'child') }) - await vi.advanceTimersByTimeAsync(2_000) - await idle - - expect(names()).toEqual(['SessionBusy', 'AskUserQuestion', 'SessionBusy']) - expect(posts.at(-1)?.sessionID).toBe('root') - }) - - it('delivers same-id child blockers across factories when the older owner resolves first', async () => { - const first = await createHooks([{ id: 'root-a' }, { id: 'child-a', parentID: 'root-a' }]) - const second = await createHooks([{ id: 'root-b' }, { id: 'child-b', parentID: 'root-b' }]) - - await first.event({ event: status('busy', 'root-a') }) - await second.event({ event: status('busy', 'root-b') }) - await first.event({ event: attention('question.asked', 'same-id', 'child-a') }) - await second.event({ event: attention('question.asked', 'same-id', 'child-b') }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'same-id', - sessionID: 'root-b' - }) - const postsAfterSecondBlocker = posts.length - - await first.event({ - event: resolution('question.replied', 'same-id', 'child-a') - }) - expect(posts).toHaveLength(postsAfterSecondBlocker) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'same-id', - sessionID: 'root-b' - }) - - await second.event({ - event: resolution('question.replied', 'same-id', 'child-b') - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'SessionBusy', - sessionID: 'root-b' - }) - }) - - it('keeps same-id blockers from separate sessions in one factory independent', async () => { - const hooks = await createHooks([ - { id: 'root-a' }, - { id: 'child-a', parentID: 'root-a' }, - { id: 'root-b' }, - { id: 'child-b', parentID: 'root-b' } - ]) - - await hooks.event({ event: status('busy', 'root-a') }) - await hooks.event({ event: status('busy', 'root-b') }) - await hooks.event({ event: attention('question.asked', 'same-id', 'child-a') }) - await hooks.event({ event: attention('question.asked', 'same-id', 'child-b') }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - sessionID: 'root-b' - }) - - await hooks.event({ - event: resolution('question.replied', 'same-id', 'child-a') - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - sessionID: 'root-b' - }) - }) - - it('keeps the oldest blocker waiting when 128 newer blockers resolve', async () => { - const hooks = await createHooks([]) - - // Cross the old 128-entry cap: live blocker ownership must survive ancestry-cache eviction. - for (let index = 1; index <= 129; index += 1) { - await hooks.event({ - event: attention('question.asked', `question-${String(index)}`, `session-${String(index)}`) - }) - } - for (let index = 2; index <= 129; index += 1) { - await hooks.event({ - event: resolution( - 'question.replied', - `question-${String(index)}`, - `session-${String(index)}` - ) - }) - } - - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'question-1', - sessionID: 'session-1' - }) - }) - - it('cleans only the disposed factory blocker', async () => { - const first = await createHooks([{ id: 'root-a' }, { id: 'child-a', parentID: 'root-a' }]) - const second = await createHooks([{ id: 'root-b' }, { id: 'child-b', parentID: 'root-b' }]) - - await first.event({ event: status('busy', 'root-a') }) - await second.event({ event: status('busy', 'root-b') }) - await first.event({ event: attention('question.asked', 'first-id', 'child-a') }) - await second.event({ event: attention('question.asked', 'second-id', 'child-b') }) - await second.dispose?.() - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'AskUserQuestion', - id: 'first-id', - sessionID: 'root-a' - }) - - await first.event({ - event: resolution('question.replied', 'first-id', 'child-a') - }) - expect(posts.at(-1)).toMatchObject({ - hook_event_name: 'SessionBusy', - sessionID: 'root-a' - }) - }) - - it('keeps child lifecycle, deltas, and text previews from overriding root status', async () => { - const hooks = await createHooks([{ id: 'root' }, { id: 'child', parentID: 'root' }]) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: status('busy', 'child') }) - await hooks.event({ event: status('idle', 'child') }) - await hooks.event({ - event: { - type: 'message.part.delta', - properties: { sessionID: 'child', field: 'text', delta: 'child work' } - } - }) - await hooks.event({ - event: { - type: 'message.updated', - properties: { - sessionID: 'child', - info: { id: 'child-message', role: 'assistant' } - } - } - }) - await hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'child', - part: { - type: 'text', - text: 'private child preview', - messageID: 'child-message' - } - } - } - }) - - expect(names()).toEqual(['SessionBusy']) - await hooks.event({ event: status('idle', 'root') }) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('does not let a delayed child Idle invalidate an in-flight parent preview', async () => { - let releaseRootLookup: (() => void) | undefined - const rootLookup = new Promise((resolve) => { - releaseRootLookup = resolve - }) - let notifyRootLookup: (() => void) | undefined - const rootLookupStarted = new Promise((resolve) => { - notifyRootLookup = resolve - }) - let releaseChildLookup: (() => void) | undefined - const childLookup = new Promise((resolve) => { - releaseChildLookup = resolve - }) - let notifyChildLookup: (() => void) | undefined - const childLookupStarted = new Promise((resolve) => { - notifyChildLookup = resolve - }) - let calls = 0 - const sessions = [{ id: 'root' }, { id: 'child', parentID: 'root' }] - const list = vi.fn(async () => { - calls += 1 - if (calls === 1) { - notifyRootLookup?.() - await rootLookup - } else if (calls === 2) { - notifyChildLookup?.() - await childLookup - } - return { data: sessions } - }) - const hooks = await createHooks([], list) - - const seedRole = hooks.event({ - event: { - type: 'message.updated', - properties: { - sessionID: 'root', - info: { id: 'parent-message', role: 'assistant' } - } - } - }) - await rootLookupStarted - const preview = hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'parent preview', messageID: 'parent-message' } - } - } - }) - const childIdle = hooks.event({ event: status('idle', 'child') }) - - try { - releaseRootLookup?.() - await childLookupStarted - await vi.waitFor(() => expect(names()).toEqual(['MessagePart'])) - } finally { - releaseChildLookup?.() - } - await Promise.all([seedRole, preview, childIdle]) - - expect(names()).toEqual(['MessagePart']) - }) -}) diff --git a/src/main/opencode/hook-plugin-fail-open-ownership.test.ts b/src/main/opencode/hook-plugin-fail-open-ownership.test.ts deleted file mode 100644 index 72f41dee80b..00000000000 --- a/src/main/opencode/hook-plugin-fail-open-ownership.test.ts +++ /dev/null @@ -1,438 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { getPath: getPathMock } -})) - -import { _internals } from './hook-service' - -type SessionFixture = { id: string; parentID?: string } -type SessionClientFixture = { - list: (options?: { signal?: AbortSignal }) => Promise<{ data: SessionFixture[] }> -} -type PluginEvent = { type: string; properties?: Record } -type PluginEventHandler = (input: { event: PluginEvent }) => Promise -type PluginHooks = { event: PluginEventHandler; dispose?: () => Promise } -type RecordedPost = { - hook_event_name: string - sessionID?: string -} - -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN', - 'ORCA_AGENT_HOOK_ENDPOINT' -] as const - -describe('OpenCode plugin fail-open ownership', () => { - let tempDir: string - let posts: RecordedPost[] - let savedEnv: Record - let savedFetch: typeof globalThis.fetch - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-fail-open-plugin-')) - posts = [] - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - process.env.ORCA_AGENT_HOOK_PORT = '45678' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - savedFetch = globalThis.fetch - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - }) - - afterEach(() => { - vi.useRealTimers() - globalThis.fetch = savedFetch - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - }) - - function readPayload(init?: RequestInit): RecordedPost { - return JSON.parse(String(init?.body)).payload as RecordedPost - } - - async function loadHooks( - list: () => Promise<{ data: SessionFixture[] }> = async () => ({ - data: [{ id: 'root' }] - }) - ): Promise { - return loadHooksWithSession({ list }) - } - - async function loadHooksWithSession(session: SessionClientFixture): Promise { - return loadHooksWithContext({ client: { session } }) - } - - async function loadHooksWithContext(context: unknown): Promise { - const pluginPath = join(tempDir, 'orca-opencode-status.mjs') - writeFileSync(pluginPath, _internals.getOpenCodePluginSource()) - const module = (await import(pathToFileURL(pluginPath).href)) as { - OrcaOpenCodeStatusPlugin: (ctx: unknown) => Promise - } - return module.OrcaOpenCodeStatusPlugin(context) - } - - function status(type: 'busy' | 'idle' | 'retry', sessionID = 'root'): PluginEvent { - return { - type: 'session.status', - properties: { sessionID, status: { type } } - } - } - - function names(): string[] { - return posts.map((post) => post.hook_event_name) - } - - function rejectWhenAborted(signal: AbortSignal | undefined): Promise { - if (!signal) { - return Promise.reject(new Error('missing abort signal')) - } - return new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) - }) - } - - it('retires a provisional Busy when the factory has no SDK client', async () => { - const hooks = await loadHooksWithContext(undefined) - - await hooks.event({ event: status('busy') }) - await hooks.event({ event: status('idle') }) - - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('keeps concurrent provisional Busy owners active until each exact session retires', async () => { - const first = await loadHooksWithContext(undefined) - const second = await loadHooksWithContext(undefined) - - await first.event({ event: status('busy', 'unknown-a') }) - await second.event({ event: status('busy', 'unknown-b') }) - await first.event({ event: status('idle', 'unknown-a') }) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - - await second.event({ event: status('idle', 'unknown-b') }) - expect(names()).toEqual(['SessionBusy', 'SessionBusy', 'SessionIdle']) - }) - - it('keeps same-session provisional Busy ownership separate across factories', async () => { - const first = await loadHooksWithContext(undefined) - const second = await loadHooksWithContext(undefined) - - await first.event({ event: status('busy', 'same-session') }) - await second.event({ event: status('busy', 'same-session') }) - await first.event({ event: status('idle', 'same-session') }) - expect(names()).toEqual(['SessionBusy']) - - await second.event({ event: status('idle', 'same-session') }) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('does not evict an active provisional owner under high concurrency', async () => { - const hooks = await loadHooksWithContext(undefined) - - for (let index = 0; index < 129; index += 1) { - await hooks.event({ event: status('busy', `unknown-${index}`) }) - } - for (let index = 1; index < 129; index += 1) { - await hooks.event({ event: status('idle', `unknown-${index}`) }) - } - expect(names().at(-1)).toBe('SessionBusy') - expect(posts.at(-1)?.sessionID).toBe('unknown-0') - - await hooks.event({ event: status('idle', 'unknown-0') }) - expect(names().at(-1)).toBe('SessionIdle') - }) - - it('drains an older preview before unknown Idle retires its exact known root', async () => { - const sessions = Array.from({ length: 129 }, (_, index) => ({ id: `root-${index}` })) - let lookupFails = false - const list = vi.fn(async () => { - if (lookupFails) { - throw new Error('lookup unavailable') - } - return { data: sessions } - }) - let releasePart: (() => void) | undefined - const delayedPart = new Promise((resolve) => { - releasePart = resolve - }) - let notifyPartStarted: (() => void) | undefined - const partStarted = new Promise((resolve) => { - notifyPartStarted = resolve - }) - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const payload = readPayload(init) - if (payload.hook_event_name === 'MessagePart') { - notifyPartStarted?.() - await delayedPart - } - posts.push(payload) - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - const hooks = await loadHooks(list) - - await hooks.event({ event: status('busy', 'root-0') }) - await hooks.event({ - event: { - type: 'message.updated', - properties: { - sessionID: 'root-0', - info: { id: 'assistant-message', role: 'assistant' } - } - } - }) - const preview = hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root-0', - part: { - type: 'text', - text: 'older preview', - messageID: 'assistant-message' - } - } - } - }) - await partStarted - - // Evict root-0 ancestry while its preview remains in flight. - for (let index = 1; index < sessions.length; index += 1) { - await hooks.event({ - event: { - type: 'message.updated', - properties: { - sessionID: `root-${index}`, - info: { id: `message-${index}`, role: 'assistant' } - } - } - }) - } - lookupFails = true - const callsBeforeIdle = list.mock.calls.length - const idle = hooks.event({ event: status('idle', 'root-0') }) - await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(callsBeforeIdle + 1)) - await new Promise((resolve) => { - setImmediate(resolve) - }) - const namesBeforeRelease = names() - - releasePart?.() - await Promise.all([preview, idle]) - - expect(namesBeforeRelease).toEqual(['SessionBusy']) - expect(names()).toEqual(['SessionBusy', 'MessagePart', 'SessionIdle']) - }) - - it('drops a delayed text handler after its Waiting blocker resolves to Idle', async () => { - let lookupBlocks = false - let releaseLookup: (() => void) | undefined - const delayedLookup = new Promise((resolve) => { - releaseLookup = resolve - }) - let notifyLookupStarted: (() => void) | undefined - const lookupStarted = new Promise((resolve) => { - notifyLookupStarted = resolve - }) - const list = vi.fn(async () => { - if (!lookupBlocks) { - throw new Error('lookup unavailable') - } - notifyLookupStarted?.() - await delayedLookup - return { data: [{ id: 'root' }] } - }) - const hooks = await loadHooks(list) - await hooks.event({ - event: { - type: 'message.updated', - properties: { - sessionID: 'root', - info: { id: 'assistant-message', role: 'assistant' } - } - } - }) - await hooks.event({ - event: { - type: 'question.asked', - properties: { id: 'question-root', sessionID: 'root' } - } - }) - lookupBlocks = true - const preview = hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { - type: 'text', - text: 'stale preview', - messageID: 'assistant-message' - } - } - } - }) - await lookupStarted - - await hooks.event({ - event: { - type: 'question.replied', - properties: { requestID: 'question-root', sessionID: 'root' } - } - }) - expect(names()).toEqual(['AskUserQuestion', 'SessionIdle']) - - releaseLookup?.() - await preview - - expect(names()).toEqual(['AskUserQuestion', 'SessionIdle']) - }) - - it('disposes only its provisional Busy owner and reasserts the survivor', async () => { - const first = await loadHooksWithContext(undefined) - const second = await loadHooksWithContext(undefined) - - await first.event({ event: status('busy', 'unknown-a') }) - await second.event({ event: status('busy', 'unknown-b') }) - await second.dispose?.() - expect(names()).toEqual(['SessionBusy', 'SessionBusy', 'SessionBusy']) - expect(posts.at(-1)?.sessionID).toBe('unknown-a') - - await first.dispose?.() - expect(names()).toEqual(['SessionBusy', 'SessionBusy', 'SessionBusy', 'SessionIdle']) - }) - - it('lets exact unknown-session Idle clear a blocker without SDK lookup', async () => { - const hooks = await loadHooksWithContext(undefined) - - await hooks.event({ - event: { - type: 'question.asked', - properties: { id: 'question-unknown', sessionID: 'unknown' } - } - }) - await hooks.event({ event: status('idle', 'unknown') }) - - expect(names()).toEqual(['AskUserQuestion', 'SessionIdle']) - }) - - it('does not let another unknown session Busy overwrite an active blocker', async () => { - const hooks = await loadHooksWithContext(undefined) - - await hooks.event({ - event: { - type: 'permission.asked', - properties: { id: 'permission-root', sessionID: 'root' } - } - }) - await hooks.event({ event: status('busy', 'other-session') }) - - expect(names()).toEqual(['PermissionRequest']) - }) - - it('ignores malformed attention that has no required sessionID', async () => { - const hooks = await loadHooksWithContext(undefined) - - await hooks.event({ - event: { - type: 'question.asked', - properties: { id: 'question-without-session' } - } - }) - await hooks.event({ - event: { - type: 'permission.asked', - properties: { id: 'permission-without-session' } - } - }) - - expect(names()).toEqual([]) - }) - - it('retires provisional Busy after both ancestry lookups time out', async () => { - vi.useFakeTimers() - const list = vi.fn((options?: { signal?: AbortSignal }) => rejectWhenAborted(options?.signal)) - const hooks = await loadHooksWithSession({ list }) - - const busy = hooks.event({ event: status('busy') }) - await vi.advanceTimersByTimeAsync(2_000) - await busy - expect(names()).toEqual(['SessionBusy']) - - const idle = hooks.event({ event: status('idle') }) - await vi.advanceTimersByTimeAsync(2_000) - await idle - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('promotes provisional Busy when later lookup confirms the root', async () => { - let lookupFails = true - const list = vi.fn(async () => { - if (lookupFails) { - throw new Error('lookup unavailable') - } - return { data: [{ id: 'root' }] } - }) - const hooks = await loadHooksWithSession({ list }) - - await hooks.event({ event: status('busy') }) - lookupFails = false - await hooks.event({ - event: { - type: 'question.asked', - properties: { id: 'question-root', sessionID: 'root' } - } - }) - await hooks.event({ - event: { - type: 'question.replied', - properties: { requestID: 'question-root', sessionID: 'root' } - } - }) - await hooks.event({ event: status('idle') }) - - expect(names()).toEqual(['SessionBusy', 'AskUserQuestion', 'SessionBusy', 'SessionIdle']) - }) - - it('keeps a confirmed child provisionally Busy until its matching Idle', async () => { - let lookupFails = true - const list = vi.fn(async () => { - if (lookupFails) { - throw new Error('lookup unavailable') - } - return { data: [{ id: 'root' }, { id: 'child', parentID: 'root' }] } - }) - const hooks = await loadHooksWithSession({ list }) - - await hooks.event({ event: status('busy', 'child') }) - lookupFails = false - await hooks.event({ event: status('busy', 'child') }) - expect(names()).toEqual(['SessionBusy']) - - await hooks.event({ event: status('idle', 'child') }) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) -}) diff --git a/src/main/opencode/hook-plugin-legacy-tui-ownership.test.ts b/src/main/opencode/hook-plugin-legacy-tui-ownership.test.ts deleted file mode 100644 index e9404da3821..00000000000 --- a/src/main/opencode/hook-plugin-legacy-tui-ownership.test.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { getOpenCodePluginSource } from './status-plugin-module-source' -import { writeOpenCodeTuiPlugin } from '../../shared/opencode-tui-plugin-install' -import { fakeLegacyTui, type LegacyTuiEvent } from './opencode-legacy-tui-fixture' -import { getLegacyPlugins, readV1Plugin } from './opencode-legacy-plugin-loader-fixture' -import { getOpenCodeCliCapabilities } from '../../shared/opencode-cli-version' - -type Post = { - paneKey?: string - opencodeMajor?: number - opencodeTui?: number - opencodeSharedServer?: number - payload?: { hook_event_name?: string; sessionID?: string; role?: string; text?: string } -} -const PANE_A = 'tabA:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' -const PANE_B = 'tabB:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_OPENCODE_AGENT', - 'ORCA_AGENT_HOOK_ENDPOINT', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN', - 'ORCA_AGENT_HOOK_OPENCODE_TUI', - 'ORCA_OPENCODE_PLUGIN_API' -] as const -const created = (id: string, parentID?: string): LegacyTuiEvent => ({ - type: 'session.created', - properties: { info: { id, parentID, directory: '/same-folder' } } -}) -const status = (sessionID: string, type: string): LegacyTuiEvent => ({ - type: 'session.status', - properties: { sessionID, status: { type } } -}) - -describe('OpenCode 1 TUI API pane reporting', () => { - let dir: string - let posts: Post[] - let savedFetch: typeof fetch - let savedArgv: string[] - let savedEnv: Record - const cleanups: (() => Promise)[] = [] - - beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'orca-legacy-tui-')) - savedFetch = globalThis.fetch - savedArgv = process.argv - savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])) - process.argv = ['opencode', 'attach', 'http://127.0.0.1:4096'] - process.env.ORCA_OPENCODE_PLUGIN_API = 'v2' - process.env.ORCA_OPENCODE_AGENT = 'opencode' - process.env.ORCA_AGENT_HOOK_PORT = '59999' - process.env.ORCA_AGENT_HOOK_TOKEN = 'fixture' - process.env.ORCA_AGENT_HOOK_OPENCODE_TUI = '1' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - posts = [] - globalThis.fetch = vi.fn(async (_input, init) => { - posts.push(JSON.parse(String(init?.body))) - return new Response('{}', { status: 200 }) - }) - }) - - afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } - globalThis.fetch = savedFetch - process.argv = savedArgv - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(dir, { recursive: true, force: true }) - }) - - async function start(paneKey = PANE_A, tui = fakeLegacyTui()) { - process.env.ORCA_PANE_KEY = paneKey - const name = `orca-status-${Math.random().toString(36).slice(2)}.js` - writeOpenCodeTuiPlugin(dir, name, getOpenCodePluginSource()) - const plugin: unknown = await import( - pathToFileURL(join(dir, name.replace(/\.js$/, '-tui'), 'tui.js')).href - ) - if (typeof plugin !== 'object' || !plugin || !('default' in plugin)) { - throw new Error('No plugin') - } - const entry = readV1Plugin(plugin, name, 'tui') - expect(entry).not.toHaveProperty('server') - expect(entry).toHaveProperty('setup', expect.any(Function)) - if ( - typeof entry !== 'object' || - !entry || - !('tui' in entry) || - typeof entry.tui !== 'function' - ) { - throw new Error('No TUI entry') - } - await entry.tui(tui.api) - cleanups.push(() => tui.dispose()) - return tui - } - - const names = () => - posts.map((post) => `${post.payload?.hook_event_name}:${post.payload?.sessionID}`) - const settle = async (name: string) => vi.waitFor(() => expect(names().at(-1)).toBe(name)) - async function pump(tui: ReturnType, events: LegacyTuiEvent[]) { - for (const event of events) { - tui.emit(event) - await new Promise((resolve) => setTimeout(resolve, 20)) - } - } - - it('registers a separate object TUI entry while retaining the current server entry', async () => { - process.env.ORCA_PANE_KEY = PANE_A - const path = join(dir, 'server.mjs') - writeFileSync(path, getOpenCodePluginSource()) - const plugin: unknown = await import(pathToFileURL(path).href) - expect(plugin).toMatchObject({ - default: { server: expect.any(Function), setup: expect.any(Function) }, - OrcaOpenCodeStatusPlugin: expect.any(Function) - }) - if (typeof plugin !== 'object' || !plugin || !('default' in plugin)) { - throw new Error('No server plugin') - } - expect(readV1Plugin(plugin, path, 'server')).not.toHaveProperty('tui') - const tui = await start() - expect(tui.listenerCount()).toBeGreaterThan(0) - }) - - it('loads the selected v1 factory through the release fallback once and retains the separate TUI', async () => { - process.env.ORCA_OPENCODE_PLUGIN_API = getOpenCodeCliCapabilities('1.18.30').pluginApi - process.argv = ['opencode', 'serve'] - process.env.ORCA_PANE_KEY = PANE_A - const path = join(dir, 'selected-v1-server.mjs') - writeFileSync(path, getOpenCodePluginSource()) - const plugin: unknown = await import(pathToFileURL(path).href) - if (typeof plugin !== 'object' || !plugin || !('default' in plugin)) { - throw new Error('No server plugin') - } - expect(readV1Plugin(plugin, path, 'server', 'detect')).toBeUndefined() - const factories = getLegacyPlugins(plugin) - expect(factories).toHaveLength(1) - expect(factories[0]).toBe(plugin.default) - const hooks: unknown = await factories[0]({ - client: { session: { get: async () => ({ data: { id: 'ses_root' } }) } } - }) - if ( - !hooks || - typeof hooks !== 'object' || - !('event' in hooks) || - typeof hooks.event !== 'function' || - !('dispose' in hooks) || - typeof hooks.dispose !== 'function' - ) { - throw new Error('No legacy event hooks') - } - const dispose = hooks.dispose - cleanups.push(async () => { - await dispose() - }) - await hooks.event({ - event: { - type: 'session.status', - properties: { sessionID: 'ses_root', status: { type: 'busy' } } - } - }) - await settle('SessionBusy:ses_root') - expect(posts.at(-1)).toMatchObject({ opencodeSharedServer: 1 }) - process.argv = ['opencode', 'attach', 'http://127.0.0.1:4096'] - const tui = await start() - expect(tui.listenerCount()).toBeGreaterThan(0) - }) - - it('reproduces the release loader rejection of a combined server and TUI entry', () => { - expect(() => - readV1Plugin({ default: { server() {}, tui() {} } }, 'orca-opencode-status-tui/tui.js', 'tui') - ).toThrow('must default export either server() or tui(), not both') - }) - - it('keeps legacy reporting after the release catalog probes setup in the same module', async () => { - process.argv = ['opencode', 'serve'] - process.env.ORCA_PANE_KEY = PANE_A - const path = join(dir, 'catalog-probed-server.mjs') - writeFileSync(path, getOpenCodePluginSource()) - const plugin: unknown = await import(pathToFileURL(path).href) - if (typeof plugin !== 'object' || !plugin || !('default' in plugin)) { - throw new Error('No server plugin') - } - const entry = readV1Plugin(plugin, path, 'server') - if (!entry || typeof entry.setup !== 'function' || typeof entry.server !== 'function') { - throw new Error('No setup and server entry') - } - // OpenCode 1.18.30's catalog adapter probes setup before its legacy server loads. - const cleanup = await entry.setup({ options: {}, catalog: {} }) - expect(cleanup).toBeTypeOf('function') - const hooks = await entry.server({ - client: { session: { get: async () => ({ data: { id: 'ses_root' } }) } } - }) - if (!hooks || typeof hooks.event !== 'function' || typeof hooks.dispose !== 'function') { - throw new Error('No legacy event hooks') - } - cleanups.push(() => hooks.dispose()) - await hooks.event({ - event: { - type: 'session.status', - properties: { sessionID: 'ses_root', status: { type: 'busy' } } - } - }) - await settle('SessionBusy:ses_root') - expect(posts.at(-1)).toMatchObject({ opencodeSharedServer: 1 }) - expect(posts.at(-1)).not.toHaveProperty('opencodeMajor') - }) - - it('reports only the selected pane session on a same-folder shared event bus', async () => { - const bus = [ - created('ses_a'), - status('ses_a', 'busy'), - created('ses_b'), - status('ses_b', 'busy'), - status('ses_b', 'idle'), - status('ses_a', 'idle') - ] - for (const [pane, session] of [ - [PANE_A, 'ses_a'], - [PANE_B, 'ses_b'] - ] as const) { - const from = posts.length - const tui = await start(pane) - tui.navigate(session) - await pump(tui, bus) - await settle(`SessionIdle:${session}`) - const own = posts.slice(from) - expect(new Set(own.map((post) => post.payload?.sessionID))).toEqual(new Set([session])) - expect( - own.every( - (post) => - post.paneKey === pane && post.opencodeTui === 1 && post.opencodeMajor === undefined - ) - ).toBe(true) - await tui.dispose() - } - }) - - it('keeps the original running root after navigation and ignores sibling completion', async () => { - const tui = await start() - tui.navigate('ses_a') - await pump(tui, [created('ses_a'), status('ses_a', 'busy')]) - tui.navigate('ses_b') - await pump(tui, [created('ses_b'), status('ses_b', 'idle')]) - expect(names().at(-1)).toBe('SessionBusy:ses_a') - await pump(tui, [status('ses_a', 'idle')]) - await settle('SessionIdle:ses_a') - }) - - it('uses message session identity and leaves synthetic text out of the pane preview', async () => { - const tui = await start() - tui.navigate('ses_a') - await pump(tui, [created('ses_a'), status('ses_a', 'busy')]) - await settle('SessionBusy:ses_a') - const count = posts.length - const part = { type: 'text', messageID: 'msg_user', sessionID: 'ses_a', text: 'Synthetic task' } - await pump(tui, [ - { - type: 'message.updated', - properties: { info: { id: 'msg_user', sessionID: 'ses_a', role: 'user' } } - }, - { type: 'message.part.updated', properties: { part: { ...part, synthetic: true } } } - ]) - expect(posts).toHaveLength(count) - await pump(tui, [ - { type: 'message.part.updated', properties: { part: { ...part, text: 'Real prompt' } } } - ]) - await settle('MessagePart:ses_a') - expect(posts.at(-1)?.payload).toMatchObject({ - role: 'user', - text: 'Real prompt', - messageID: 'msg_user', - sessionID: 'ses_a' - }) - }) - - it.each(['permission', 'question'])( - 'reports a child %s under its owned root and clears the reply', - async (kind) => { - const tui = await start() - tui.navigate('ses_a') - await pump(tui, [ - created('ses_a'), - created('ses_child', 'ses_a'), - status('ses_a', 'busy'), - status('ses_child', 'busy') - ]) - await pump(tui, [ - { - type: `${kind}.asked`, - properties: { id: 'request_1', sessionID: 'ses_child', permission: 'bash', questions: [] } - } - ]) - await settle(`${kind === 'permission' ? 'PermissionRequest' : 'AskUserQuestion'}:ses_a`) - await pump(tui, [ - { type: `${kind}.replied`, properties: { requestID: 'request_1', sessionID: 'ses_child' } }, - status('ses_child', 'idle'), - status('ses_a', 'idle') - ]) - await settle('SessionIdle:ses_a') - expect(posts.every((post) => post.payload?.sessionID === 'ses_a')).toBe(true) - } - ) - - it('keeps newer hosts capability opt-in separate from the process environment', async () => { - const endpoint = join(dir, 'endpoint.env') - process.env.ORCA_AGENT_HOOK_ENDPOINT = endpoint - writeFileSync(endpoint, 'ORCA_AGENT_HOOK_PORT=59999\nORCA_AGENT_HOOK_TOKEN=fixture\n') - const tui = await start() - tui.navigate('ses_a') - await pump(tui, [created('ses_a'), status('ses_a', 'busy')]) - expect(posts).toEqual([]) - writeFileSync( - endpoint, - 'ORCA_AGENT_HOOK_PORT=59999\nORCA_AGENT_HOOK_TOKEN=fixture\nORCA_AGENT_HOOK_OPENCODE_TUI=1\n' - ) - await settle('SessionBusy:ses_a') - }) - - it('stops its listeners and publishes no invented Idle when its TUI is unloaded', async () => { - const tui = await start() - tui.navigate('ses_a') - await pump(tui, [created('ses_a'), status('ses_a', 'busy')]) - await settle('SessionBusy:ses_a') - await tui.dispose() - expect(tui.listenerCount()).toBe(0) - const count = posts.length - await pump(tui, [status('ses_a', 'idle')]) - expect(posts).toHaveLength(count) - }) - - it.each(['ordinary', 'other-agent', 'no-pane', 'wrong-version'])( - 'stays silent for %s', - async (kind) => { - const tui = fakeLegacyTui() - if (kind === 'ordinary') { - process.argv = ['opencode'] - } - if (kind === 'other-agent') { - process.env.ORCA_OPENCODE_AGENT = 'mimo-code' - } - if (kind === 'wrong-version') { - tui.api.app.version = '2.0.16' - } - await start(kind === 'no-pane' ? '' : PANE_A, tui) - expect(tui.on).not.toHaveBeenCalled() - expect(posts).toEqual([]) - } - ) -}) diff --git a/src/main/opencode/hook-plugin-lifecycle-delivery.test.ts b/src/main/opencode/hook-plugin-lifecycle-delivery.test.ts deleted file mode 100644 index 181cf8c742b..00000000000 --- a/src/main/opencode/hook-plugin-lifecycle-delivery.test.ts +++ /dev/null @@ -1,817 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { getPath: getPathMock } -})) - -import { _internals } from './hook-service' - -type SessionFixture = { id: string; parentID?: string } - -/** Fixtures cover both current two-argument and legacy single-options SDK calls. */ -type SessionClientCall = (...args: never[]) => Promise<{ data: SessionFixture[] }> - -type SessionClientFixture = { list: SessionClientCall; get?: SessionClientCall } -type PluginEvent = { type: string; properties?: Record } -type PluginEventHandler = (input: { event: PluginEvent }) => Promise -type PluginHooks = { event: PluginEventHandler; dispose?: () => Promise } -type RecordedPost = { - hook_event_name: string - sessionID?: string -} - -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN', - 'ORCA_AGENT_HOOK_ENDPOINT' -] as const - -describe('OpenCode plugin lifecycle delivery', () => { - let tempDir: string - let posts: RecordedPost[] - let savedEnv: Record - let savedFetch: typeof globalThis.fetch - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-lifecycle-plugin-')) - posts = [] - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - process.env.ORCA_AGENT_HOOK_PORT = '45678' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - savedFetch = globalThis.fetch - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - }) - - afterEach(() => { - vi.useRealTimers() - globalThis.fetch = savedFetch - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - }) - - function readPayload(init?: RequestInit): RecordedPost { - return JSON.parse(String(init?.body)).payload as RecordedPost - } - - async function loadHooks( - list: () => Promise<{ data: SessionFixture[] }> = async () => ({ - data: [{ id: 'root' }] - }) - ): Promise { - return loadHooksWithSession({ list }) - } - - async function loadHooksWithSession(session: SessionClientFixture): Promise { - const pluginPath = join(tempDir, 'orca-opencode-status.mjs') - writeFileSync(pluginPath, _internals.getOpenCodePluginSource()) - const module = (await import(pathToFileURL(pluginPath).href)) as { - OrcaOpenCodeStatusPlugin: (ctx: unknown) => Promise - } - return module.OrcaOpenCodeStatusPlugin({ client: { session } }) - } - - async function loadHandler( - list?: () => Promise<{ data: SessionFixture[] }> - ): Promise { - return (await loadHooks(list)).event - } - - function status(type: 'busy' | 'idle' | 'retry', sessionID = 'root'): PluginEvent { - return { - type: 'session.status', - properties: { sessionID, status: { type } } - } - } - - function delta(text: string, field = 'text', sessionID = 'root'): PluginEvent { - return { - type: 'message.part.delta', - properties: { - sessionID, - messageID: 'message-assistant', - partID: 'part-assistant', - field, - delta: text - } - } - } - - function names(): string[] { - return posts.map((post) => post.hook_event_name) - } - - function rejectWhenAborted(signal: AbortSignal | undefined): Promise { - if (!signal) { - return Promise.reject(new Error('missing abort signal')) - } - return new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) - }) - } - - it('maps only root session.created to SessionStart', async () => { - const handler = await loadHandler() - - await handler({ - event: { type: 'session.created', properties: { info: { id: 'root' } } } - }) - await handler({ - event: { - type: 'session.created', - properties: { info: { id: 'child', parentID: 'root' } } - } - }) - - expect(posts).toEqual([{ hook_event_name: 'SessionStart', sessionID: 'root' }]) - }) - - it('falls back per coordinate when the endpoint file is partial or malformed', async () => { - const endpointPath = join(tempDir, 'endpoint.env') - writeFileSync( - endpointPath, - 'not-an-assignment\nORCA_AGENT_HOOK_TOKEN=file-token\nBROKEN LINE\n' - ) - process.env.ORCA_AGENT_HOOK_ENDPOINT = endpointPath - - const fetchMock = vi.fn( - async (_url: RequestInfo | URL, _init?: RequestInit) => new Response(null, { status: 204 }) - ) - globalThis.fetch = fetchMock as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - - expect(fetchMock).toHaveBeenCalledOnce() - const [url, init] = fetchMock.mock.calls[0]! - expect(String(url)).toBe('http://127.0.0.1:45678/hook/opencode') - expect(new Headers(init?.headers).get('X-Orca-Agent-Hook-Token')).toBe('file-token') - }) - - it('warns once for an unreadable endpoint without exposing hook credentials', async () => { - process.env.ORCA_AGENT_HOOK_ENDPOINT = tempDir - process.env.ORCA_AGENT_HOOK_TOKEN = 'fallback-secret-token' - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - try { - const handler = await loadHandler() - await handler({ event: status('busy') }) - await handler({ event: delta('still working') }) - - expect(warn).toHaveBeenCalledOnce() - expect(warn.mock.calls.flat().join(' ')).not.toContain('fallback-secret-token') - } finally { - warn.mockRestore() - } - }) - - it('preserves FIFO lifecycle order while the first session lookup is delayed', async () => { - let releaseFirstLookup: (() => void) | undefined - const firstLookup = new Promise((resolve) => { - releaseFirstLookup = resolve - }) - let notifyFirstLookupStarted: (() => void) | undefined - const firstLookupStarted = new Promise((resolve) => { - notifyFirstLookupStarted = resolve - }) - let calls = 0 - const list = vi.fn(async () => { - calls += 1 - if (calls === 1) { - notifyFirstLookupStarted?.() - await firstLookup - } - return { data: [{ id: 'root' }] } - }) - const handler = await loadHandler(list) - - const busy = handler({ event: status('busy') }) - await firstLookupStarted - const idle = handler({ event: status('idle') }) - - try { - // OpenCode does not await hooks; later idle lookup must not overtake blocked busy lookup. - expect(list).toHaveBeenCalledTimes(1) - expect(posts).toHaveLength(0) - } finally { - releaseFirstLookup?.() - } - - await Promise.all([busy, idle]) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('retries an undelivered Busy transition after a non-2xx response', async () => { - vi.useFakeTimers() - let attempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - return new Response(null, { status: attempts === 1 ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - expect(names()).toEqual(['SessionBusy']) - - await vi.advanceTimersByTimeAsync(499) - expect(names()).toEqual(['SessionBusy']) - await vi.advanceTimersByTimeAsync(1) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - }) - - it('aborts a hung Busy post before delivering the queued Idle transition', async () => { - vi.useFakeTimers() - let attempts = 0 - let firstSignal: AbortSignal | undefined - let notifyFirstFetchStarted: (() => void) | undefined - const firstFetchStarted = new Promise((resolve) => { - notifyFirstFetchStarted = resolve - }) - globalThis.fetch = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - if (attempts > 1) { - return Promise.resolve(new Response(null, { status: 204 })) - } - firstSignal = init?.signal ?? undefined - notifyFirstFetchStarted?.() - return new Promise((_resolve, reject) => { - init?.signal?.addEventListener('abort', () => reject(new Error('aborted')), { - once: true - }) - }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - const busy = handler({ event: status('busy') }) - const idle = handler({ event: status('idle') }) - await firstFetchStarted - - expect(firstSignal).toBeDefined() - await vi.advanceTimersByTimeAsync(1_999) - expect(names()).toEqual(['SessionBusy']) - await vi.advanceTimersByTimeAsync(1) - await Promise.all([busy, idle]) - - expect(firstSignal?.aborted).toBe(true) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('lets Idle supersede a pending Busy retry', async () => { - vi.useFakeTimers() - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const payload = readPayload(init) - posts.push(payload) - return new Response(null, { - status: payload.hook_event_name === 'SessionBusy' ? 503 : 204 - }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ event: status('idle') }) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('uses a current nonempty text delta to retry a dirty Busy transition immediately', async () => { - vi.useFakeTimers() - let attempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - return new Response(null, { status: attempts === 1 ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - expect(names()).toEqual(['SessionBusy']) - - // Deltas after empty text-start parts must recover a lost Busy post. - await handler({ event: delta('hello') }) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - }) - - it('keeps backoff across OpenCode canonical and deprecated Idle duplicates', async () => { - vi.useFakeTimers() - let idleAttempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const payload = readPayload(init) - posts.push(payload) - if (payload.hook_event_name === 'SessionIdle') { - idleAttempts += 1 - return new Response(null, { status: idleAttempts === 1 ? 503 : 204 }) - } - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ event: status('idle') }) - await handler({ - event: { type: 'session.idle', properties: { sessionID: 'root' } } - }) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - - await vi.advanceTimersByTimeAsync(499) - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - await vi.advanceTimersByTimeAsync(1) - expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'SessionIdle']) - }) - - it('uses repeated Busy evidence to retry the same dirty state immediately', async () => { - vi.useFakeTimers() - let attempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - return new Response(null, { status: attempts === 1 ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ event: status('retry') }) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - }) - - it('does not turn empty or non-text deltas into immediate retry traffic', async () => { - vi.useFakeTimers() - let attempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - return new Response(null, { status: attempts === 1 ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ event: delta('reasoning', 'reasoning') }) - await handler({ event: delta('') }) - expect(names()).toEqual(['SessionBusy']) - - await vi.advanceTimersByTimeAsync(499) - expect(names()).toEqual(['SessionBusy']) - await vi.advanceTimersByTimeAsync(1) - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - }) - - it('backs off exponentially and caps outage retries at thirty seconds', async () => { - vi.useFakeTimers() - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - return new Response(null, { status: 503 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - expect(names()).toHaveLength(1) - - const retryDelays = [500, 1_000, 2_000, 4_000, 8_000, 16_000, 30_000, 30_000] - for (const [index, delay] of retryDelays.entries()) { - await vi.advanceTimersByTimeAsync(delay - 1) - expect(names()).toHaveLength(index + 1) - await vi.advanceTimersByTimeAsync(1) - expect(names()).toHaveLength(index + 2) - } - }) - - it('fails Busy open after a hung lookup and still lets queued Idle proceed', async () => { - vi.useFakeTimers() - let releaseLookup: (() => void) | undefined - const blockedLookup = new Promise((resolve) => { - releaseLookup = resolve - }) - let calls = 0 - const list = vi.fn(async () => { - calls += 1 - if (calls === 1) { - await blockedLookup - } - return { data: [{ id: 'root' }] } - }) - const handler = await loadHandler(list) - const busy = handler({ event: status('busy') }) - const idle = handler({ event: status('idle') }) - - await vi.advanceTimersByTimeAsync(1_999) - expect(list).toHaveBeenCalledTimes(1) - expect(posts).toHaveLength(0) - await vi.advanceTimersByTimeAsync(1) - try { - expect(list).toHaveBeenCalledTimes(2) - // Child activity safely marks its root busy; idle still requires confirmed root ownership. - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - } finally { - releaseLookup?.() - } - await Promise.all([busy, idle]) - }) - - it('aborts a hung current-SDK point lookup through its second options argument', async () => { - vi.useFakeTimers() - let capturedParameters: unknown - let capturedSignal: AbortSignal | undefined - function get(parameters: unknown, options: { signal?: AbortSignal }) { - capturedParameters = parameters - capturedSignal = options?.signal - return rejectWhenAborted(capturedSignal) - } - const hooks = await loadHooksWithSession({ - get, - list: async () => ({ data: [{ id: 'root' }] }) - }) - - const busy = hooks.event({ event: status('busy') }) - await vi.advanceTimersByTimeAsync(2_000) - await busy - - expect(capturedParameters).toEqual({ sessionID: 'root' }) - expect(capturedSignal?.aborted).toBe(true) - expect(names()).toEqual(['SessionBusy']) - }) - - it('aborts a hung legacy-SDK point lookup through its one-object argument', async () => { - vi.useFakeTimers() - let capturedOptions: { path?: { id?: string }; signal?: AbortSignal } | undefined - function get(options: { path?: { id?: string }; signal?: AbortSignal }) { - capturedOptions = options - return rejectWhenAborted(options.signal) - } - const hooks = await loadHooksWithSession({ - get, - list: async () => ({ data: [{ id: 'root' }] }) - }) - - const busy = hooks.event({ event: status('busy') }) - await vi.advanceTimersByTimeAsync(2_000) - await busy - - expect(capturedOptions?.path).toEqual({ id: 'root' }) - expect(capturedOptions?.signal?.aborted).toBe(true) - expect(names()).toEqual(['SessionBusy']) - }) - - it('aborts a hung current-SDK list fallback through its second options argument', async () => { - vi.useFakeTimers() - let capturedParameters: unknown - let capturedSignal: AbortSignal | undefined - function list(parameters: unknown, options: { signal?: AbortSignal }) { - capturedParameters = parameters - capturedSignal = options?.signal - return rejectWhenAborted(capturedSignal) - } - const hooks = await loadHooksWithSession({ list }) - - const busy = hooks.event({ event: status('busy') }) - await vi.advanceTimersByTimeAsync(2_000) - await busy - - expect(capturedParameters).toEqual({}) - expect(capturedSignal?.aborted).toBe(true) - expect(names()).toEqual(['SessionBusy']) - }) - - it('aborts a hung legacy-SDK list fallback through its one-object argument', async () => { - vi.useFakeTimers() - let capturedOptions: { signal?: AbortSignal } | undefined - function list(options: { signal?: AbortSignal }) { - capturedOptions = options - return rejectWhenAborted(options.signal) - } - const hooks = await loadHooksWithSession({ list }) - - const busy = hooks.event({ event: status('busy') }) - await vi.advanceTimersByTimeAsync(2_000) - await busy - - expect(capturedOptions?.signal?.aborted).toBe(true) - expect(names()).toEqual(['SessionBusy']) - }) - - it('does not let a failed Busy retry overwrite delivered permission attention', async () => { - vi.useFakeTimers() - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const payload = readPayload(init) - posts.push(payload) - const firstBusy = payload.hook_event_name === 'SessionBusy' && names().length === 1 - return new Response(null, { status: firstBusy ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ - event: { type: 'permission.asked', properties: { id: 'permission-1', sessionID: 'root' } } - }) - expect(names()).toEqual(['SessionBusy', 'PermissionRequest']) - - await vi.advanceTimersByTimeAsync(60_000) - expect(names()).toEqual(['SessionBusy', 'PermissionRequest']) - }) - - it('coalesces sustained text-delta recovery before returning to backoff', async () => { - vi.useFakeTimers() - let attempts = 0 - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - attempts += 1 - return new Response(null, { status: attempts < 3 ? 503 : 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ event: delta('stream-0') }) - for (let index = 1; index < 50; index += 1) { - await handler({ event: delta(`stream-${String(index)}`) }) - } - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - - await vi.advanceTimersByTimeAsync(999) - expect(names()).toHaveLength(2) - await vi.advanceTimersByTimeAsync(1) - expect(names()).toEqual(['SessionBusy', 'SessionBusy', 'SessionBusy']) - }) - - it('cancels lifecycle retries when OpenCode disposes the plugin', async () => { - vi.useFakeTimers() - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - return new Response(null, { status: 503 }) - }) as typeof globalThis.fetch - const hooks = await loadHooks() - - await hooks.event({ event: status('busy') }) - expect(hooks.dispose).toBeTypeOf('function') - await hooks.dispose?.() - await vi.advanceTimersByTimeAsync(60_000) - - expect(names()).toEqual(['SessionBusy']) - }) - - it('publishes final Idle when the last busy factory is disposed', async () => { - const hooks = await loadHooks() - - await hooks.event({ event: status('busy') }) - await hooks.dispose?.() - - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('publishes final Idle when MessagePart alone made the disposed factory Working', async () => { - const hooks = await loadHooks() - await hooks.event({ - event: { - type: 'message.updated', - properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } } - } - }) - await hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'prompt before busy', messageID: 'user-message' } - } - } - }) - - await hooks.dispose?.() - - expect(names()).toEqual(['MessagePart', 'SessionIdle']) - }) - - it('reasserts an already-delivered Idle after a later MessagePart', async () => { - const hooks = await loadHooks() - await hooks.event({ event: status('busy') }) - await hooks.event({ event: status('idle') }) - await hooks.event({ - event: { - type: 'message.updated', - properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } } - } - }) - await hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'late prompt', messageID: 'user-message' } - } - } - }) - - await hooks.dispose?.() - - expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'MessagePart', 'SessionIdle']) - }) - - it('lets OpenCode duplicate Idle supersede a later-delivered MessagePart', async () => { - const hooks = await loadHooks() - await hooks.event({ event: status('busy') }) - await hooks.event({ event: status('idle') }) - await hooks.event({ - event: { - type: 'message.updated', - properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } } - } - }) - await hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'late prompt', messageID: 'user-message' } - } - } - }) - - await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'root' } } }) - - expect(names()).toEqual(['SessionBusy', 'SessionIdle', 'MessagePart', 'SessionIdle']) - }) - - it('does not treat a failed MessagePart attempt as delivered Working authority', async () => { - globalThis.fetch = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { - const payload = readPayload(init) - posts.push(payload) - return new Response(null, { - status: payload.hook_event_name === 'MessagePart' ? 503 : 204 - }) - }) as typeof globalThis.fetch - const hooks = await loadHooks() - await hooks.event({ - event: { - type: 'message.updated', - properties: { sessionID: 'root', info: { id: 'user-message', role: 'user' } } - } - }) - await hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'undelivered prompt', messageID: 'user-message' } - } - } - }) - - await hooks.dispose?.() - - expect(names()).toEqual(['MessagePart']) - }) - - it('does not publish a MessagePart after its factory is disposed during lookup', async () => { - let releaseLookup: (() => void) | undefined - const blockedLookup = new Promise((resolve) => { - releaseLookup = resolve - }) - let calls = 0 - const list = vi.fn(async () => { - calls += 1 - if (calls === 2) { - await blockedLookup - } - return { data: [{ id: 'seed' }, { id: 'root' }] } - }) - const hooks = await loadHooks(list) - await hooks.event({ - event: { - type: 'message.updated', - properties: { sessionID: 'seed', info: { id: 'user-message', role: 'user' } } - } - }) - - const latePart = hooks.event({ - event: { - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text: 'late prompt', messageID: 'user-message' } - } - } - }) - await vi.waitFor(() => expect(list).toHaveBeenCalledTimes(2)) - await hooks.dispose?.() - releaseLookup?.() - await latePart - - expect(names()).toEqual([]) - }) - - it('drops a disposed factory pending preview while another factory stays active', async () => { - vi.useFakeTimers() - const first = await loadHooks() - const second = await loadHooks() - await first.event({ - event: { - type: 'message.updated', - properties: { - sessionID: 'root', - info: { id: 'assistant-message', role: 'assistant' } - } - } - }) - const part = (text: string): PluginEvent => ({ - type: 'message.part.updated', - properties: { - sessionID: 'root', - part: { type: 'text', text, messageID: 'assistant-message' } - } - }) - - await first.event({ event: part('first preview') }) - await first.event({ event: part('pending preview') }) - await first.dispose?.() - await vi.advanceTimersByTimeAsync(1_000) - await second.dispose?.() - - expect(names()).toEqual(['MessagePart', 'SessionIdle']) - }) - - it('keeps the pane Busy until every concurrent root session is idle', async () => { - const sessions = [{ id: 'root-a' }, { id: 'root-b' }] - const handler = await loadHandler(async () => ({ data: sessions })) - - await handler({ event: status('busy', 'root-a') }) - await handler({ event: status('busy', 'root-b') }) - await handler({ event: status('idle', 'root-a') }) - expect(names()).not.toContain('SessionIdle') - - await handler({ event: status('idle', 'root-b') }) - expect(names().filter((name) => name === 'SessionIdle')).toHaveLength(1) - expect(names().at(-1)).toBe('SessionIdle') - }) - - it('reasserts Busy through the refreshed endpoint after a live text delta', async () => { - const deliveries: { url: string; token: string | null }[] = [] - globalThis.fetch = vi.fn(async (url: RequestInfo | URL, init?: RequestInit) => { - posts.push(readPayload(init)) - deliveries.push({ - url: String(url), - token: new Headers(init?.headers).get('X-Orca-Agent-Hook-Token') - }) - return new Response(null, { status: 204 }) - }) as typeof globalThis.fetch - const handler = await loadHandler() - - await handler({ event: status('busy') }) - process.env.ORCA_AGENT_HOOK_PORT = '56789' - process.env.ORCA_AGENT_HOOK_TOKEN = 'refreshed-token' - await handler({ event: delta('still working') }) - - expect(names()).toEqual(['SessionBusy', 'SessionBusy']) - expect(deliveries).toEqual([ - { url: 'http://127.0.0.1:45678/hook/opencode', token: 'test-token' }, - { url: 'http://127.0.0.1:56789/hook/opencode', token: 'refreshed-token' } - ]) - }) - - it('clears unanswered question attention on authoritative root Idle', async () => { - const handler = await loadHandler() - - await handler({ event: status('busy') }) - await handler({ - event: { type: 'question.asked', properties: { id: 'question-1', sessionID: 'root' } } - }) - expect(names().at(-1)).toBe('AskUserQuestion') - - // OpenCode can finish the question tool without question.replied. - await handler({ event: status('idle') }) - expect(names().at(-1)).toBe('SessionIdle') - }) -}) diff --git a/src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts b/src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts deleted file mode 100644 index 75e5378469b..00000000000 --- a/src/main/opencode/hook-plugin-opencode2-session-lineage.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: getPathMock } })) - -import { _internals } from './hook-service' - -// OpenCode 2.0.12 returns bare session records, requires sessionID and has no session.list. -type LiveSession = { id: string; parentID?: string } - -const ROOT = 'ses_root' -const CHILD = 'ses_child' -const LIVE_SESSIONS: Record = { - [ROOT]: { id: ROOT }, - [CHILD]: { id: CHILD, parentID: ROOT } -} - -type Post = { hook_event_name: string; sessionID?: string } - -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_OPENCODE_AGENT', - 'ORCA_AGENT_HOOK_ENDPOINT', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN' -] as const - -describe.each(['opencode', 'opencode2'] as const)('%s plugin OpenCode 2 lineage', (agent) => { - let tempDir: string - let savedFetch: typeof globalThis.fetch - let savedEnv: Record - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode2-lineage-')) - savedFetch = globalThis.fetch - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - process.env.ORCA_OPENCODE_AGENT = agent - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - process.env.ORCA_AGENT_HOOK_PORT = '59999' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - }) - - afterEach(() => { - globalThis.fetch = savedFetch - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - }) - - async function loadPlugin(): Promise<{ - default?: { - server?: (ctx: unknown) => Promise<{ event: (input: { event: unknown }) => Promise }> - setup?: (ctx: unknown) => Promise<() => Promise> - } - }> { - const source = - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - const pluginPath = join(tempDir, `plugin-${Math.random().toString(36).slice(2)}.mjs`) - writeFileSync(pluginPath, source) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the local fixture module is written from the generated plugin source above. - return (await import(pathToFileURL(pluginPath).href)) as Awaited> - } - - async function runSetupBridge( - events: { type: string; data: Record }[] - ): Promise<{ - posts: Post[] - lookups: string[] - cleanup?: () => Promise - }> { - const posts: Post[] = [] - const lookups: string[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the plugin always posts a JSON body carrying `payload`. - const body = JSON.parse(String(init?.body)) as { payload: Post } - posts.push(body.payload) - return new Response('{}', { status: 200 }) - }) - const module = await loadPlugin() - const cleanup = await module.default?.setup?.({ - session: { - // Match the shipped SDK’s single-parameter arity. - get: async ({ sessionID }: { sessionID?: string }) => { - if (!sessionID) { - throw new Error('Missing key at ["sessionID"]') - } - lookups.push(sessionID) - const session = LIVE_SESSIONS[sessionID] - if (!session) { - throw new Error('unknown session') - } - return session - }, - hook: async () => ({ dispose: vi.fn() }) - }, - event: { - subscribe: async function* () { - for (const event of events) { - yield event - } - } - } - }) - return { posts, lookups, cleanup } - } - - function created(sessionID: string): { type: string; data: Record } { - const { parentID } = LIVE_SESSIONS[sessionID] - return { type: 'session.created', data: { sessionID, ...(parentID ? { parentID } : {}) } } - } - - function questionForm(id: string, sessionID: string): Record { - return { - id, - sessionID, - title: 'Questions', - metadata: { kind: 'question', tool: { messageID: 'msg-0', id: 'tool-0' } }, - fields: [{ key: 'q0', title: 'Proceed?', type: 'string', options: [] }] - } - } - - it('resolves child lineage from the flat OpenCode 2 session shape', async () => { - const { posts, lookups, cleanup } = await runSetupBridge([ - created(ROOT), - created(CHILD), - { type: 'session.execution.started', data: { sessionID: ROOT } }, - { type: 'session.execution.started', data: { sessionID: CHILD } } - ]) - await vi.waitFor(() => { - expect(posts.filter((post) => post.hook_event_name === 'SessionBusy').length).toBeGreaterThan( - 0 - ) - }) - expect(posts.map((post) => post.sessionID)).not.toContain(CHILD) - expect(lookups).toContain(CHILD) - await cleanup?.() - }) - - it('attributes a child question to the root instead of minting a child blocker', async () => { - const { posts, cleanup } = await runSetupBridge([ - created(ROOT), - created(CHILD), - { type: 'session.execution.started', data: { sessionID: ROOT } }, - { type: 'form.created', data: { form: questionForm('form-child', CHILD) } } - ]) - await vi.waitFor(() => { - expect(posts.map((post) => post.hook_event_name)).toContain('AskUserQuestion') - }) - expect(posts.filter((post) => post.hook_event_name === 'AskUserQuestion')).toEqual([ - expect.objectContaining({ sessionID: ROOT }) - ]) - await cleanup?.() - }) - - it('retires a child raised blocker when that child goes idle', async () => { - const { posts, cleanup } = await runSetupBridge([ - created(ROOT), - created(CHILD), - { type: 'session.execution.started', data: { sessionID: ROOT } }, - { type: 'form.created', data: { form: questionForm('form-child', CHILD) } }, - { type: 'session.execution.succeeded', data: { sessionID: CHILD } } - ]) - await vi.waitFor(() => { - expect(posts.map((post) => post.hook_event_name)).toContain('AskUserQuestion') - }) - await vi.waitFor(() => { - expect(posts.at(-1)?.hook_event_name).toBe('SessionBusy') - }) - expect(posts.at(-1)).toEqual(expect.objectContaining({ sessionID: ROOT })) - await cleanup?.() - }) - - // Unresolved child lineage leaves blockers keyed to the child, unreachable by root idle. - it('retires a child raised blocker when the root turn goes idle', async () => { - const { posts, cleanup } = await runSetupBridge([ - created(ROOT), - created(CHILD), - { type: 'session.execution.started', data: { sessionID: ROOT } }, - { type: 'form.created', data: { form: questionForm('form-child', CHILD) } }, - { type: 'session.execution.succeeded', data: { sessionID: ROOT } } - ]) - await vi.waitFor(() => { - expect(posts.map((post) => post.hook_event_name)).toContain('AskUserQuestion') - }) - await vi.waitFor(() => { - expect(posts.at(-1)?.hook_event_name).toBe('SessionIdle') - }) - expect(posts.at(-1)).toEqual(expect.objectContaining({ sessionID: ROOT })) - await cleanup?.() - }) - - it('still blocks the pane on the root session own question', async () => { - const { posts, cleanup } = await runSetupBridge([ - created(ROOT), - { type: 'session.execution.started', data: { sessionID: ROOT } }, - { type: 'form.created', data: { form: questionForm('form-root', ROOT) } } - ]) - await vi.waitFor(() => { - expect(posts.map((post) => post.hook_event_name)).toContain('AskUserQuestion') - }) - expect(posts.at(-1)).toEqual(expect.objectContaining({ sessionID: ROOT })) - await cleanup?.() - }) - - it('caches resolved ancestry instead of re-probing per event', async () => { - const { posts, lookups, cleanup } = await runSetupBridge([ - created(ROOT), - created(CHILD), - { type: 'session.execution.started', data: { sessionID: CHILD } }, - { type: 'session.execution.succeeded', data: { sessionID: CHILD } }, - { type: 'session.execution.started', data: { sessionID: CHILD } }, - { type: 'session.execution.succeeded', data: { sessionID: CHILD } } - ]) - await vi.waitFor(() => { - expect(posts.length).toBeGreaterThan(0) - }) - expect(lookups).toEqual([CHILD]) - await cleanup?.() - }) -}) diff --git a/src/main/opencode/hook-plugin-opencode2-setup.test.ts b/src/main/opencode/hook-plugin-opencode2-setup.test.ts deleted file mode 100644 index 1f611e212a1..00000000000 --- a/src/main/opencode/hook-plugin-opencode2-setup.test.ts +++ /dev/null @@ -1,560 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -import { _internals } from './hook-service' - -describe.each(['opencode', 'opencode2'] as const)('%s plugin on OpenCode 2', (agent) => { - type PostBody = { payload?: unknown } - - function record(value: unknown): Record | undefined { - return typeof value === 'object' && value !== null - ? Object.fromEntries(Object.entries(value)) - : undefined - } - - function payload(body: PostBody): Record { - return record(body.payload) ?? {} - } - - type PluginHooks = { - event: (input: { event: unknown }) => Promise - dispose?: () => Promise - } - type PluginModule = { - default?: { - id?: unknown - server?: (ctx: unknown) => Promise - setup?: (ctx: unknown) => Promise<() => Promise> - } - OrcaOpenCodeStatusPlugin?: (ctx: unknown) => Promise - } - - // Isolate endpoint-file and environment inputs so tests cannot post to a live Orca session. - const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_OPENCODE_AGENT', - 'ORCA_OPENCODE_PLUGIN_API', - 'ORCA_AGENT_HOOK_ENDPOINT', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN' - ] as const - - let tempDir: string - let savedFetch: typeof globalThis.fetch - let savedEnv: Record - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-plugin-contract-')) - savedFetch = globalThis.fetch - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_OPENCODE_AGENT = agent - process.env.ORCA_OPENCODE_PLUGIN_API = 'v2' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - process.env.ORCA_AGENT_HOOK_PORT = '59999' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - }) - - afterEach(() => { - globalThis.fetch = savedFetch - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - }) - - async function loadPluginModule( - source = _internals.getOpenCodePluginSource() - ): Promise { - // Bypass ESM caching between cases. - const pluginPath = join( - tempDir, - `orca-opencode-status-${Math.random().toString(36).slice(2)}.mjs` - ) - writeFileSync(pluginPath, source) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Runtime validation or the local test fixture establishes the asserted shape. - return (await import(pathToFileURL(pluginPath).href)) as PluginModule - } - - it('does not register hooks for the other pane variant', async () => { - process.env.ORCA_OPENCODE_AGENT = agent === 'opencode' ? 'opencode2' : 'opencode' - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const hook = vi.fn() - const subscribe = vi.fn() - const cleanup = await module.default?.setup?.({ session: { hook }, event: { subscribe } }) - expect(hook).not.toHaveBeenCalled() - expect(subscribe).not.toHaveBeenCalled() - await cleanup?.() - }) - - it('fails open when setup is probed without a usable context', async () => { - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - // OpenCode probes varying setup shapes; each must return cleanup without throwing in the TUI. - const contexts: unknown[] = [ - undefined, - {}, - { session: {} }, - { session: { hook: vi.fn() }, event: {} } - ] - for (const ctx of contexts) { - const cleanup = await module.default?.setup?.(ctx) - expect(cleanup).toBeTypeOf('function') - await cleanup?.() - } - }) - - it('disposes cleanly when the prompt hook returns nothing to dispose', async () => { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const cleanup = await module.default?.setup?.({ - session: { - get: async ({ sessionID }: { sessionID: string }) => ({ data: { id: sessionID } }), - hook: async () => undefined - }, - event: { - subscribe: async function* () {} - } - }) - expect(cleanup).toBeTypeOf('function') - await cleanup?.() - }) - - it('exposes a distinct plugin id per agent variant', async () => { - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - // Both plugins share one directory; duplicate IDs disable the second plugin. - expect(module.default?.id).toBe( - agent === 'opencode2' ? 'orca-opencode2-status' : 'orca-opencode-status' - ) - }) - - it('subscribes through the OpenCode 2 setup API and disposes its registrations', async () => { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const posts: unknown[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - posts.push(JSON.parse(String(init?.body))) - return new Response('{}', { status: 200 }) - }) - const dispose = vi.fn() - let subscriptionSignal: AbortSignal | undefined - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - expect(module.default?.setup).toBeTypeOf('function') - const cleanup = await module.default?.setup?.({ - session: { - get: async ({ sessionID }: { sessionID: string }) => ({ data: { id: sessionID } }), - hook: async () => ({ dispose }) - }, - event: { - subscribe: async function* ({ signal }: { signal: AbortSignal }) { - subscriptionSignal = signal - yield { type: 'session.created', data: { sessionID: 'ses_root' } } - yield { - type: 'session.execution.started', - data: { sessionID: 'ses_root' } - } - yield { - type: 'session.execution.succeeded', - data: { sessionID: 'ses_root' } - } - } - } - }) - await vi.waitFor(() => { - expect(posts).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - opencodeMajor: 2, - payload: expect.objectContaining({ hook_event_name: 'SessionBusy' }) - }), - expect.objectContaining({ - payload: expect.objectContaining({ hook_event_name: 'SessionIdle' }) - }) - ]) - ) - }) - expect(globalThis.fetch).toHaveBeenCalledWith( - `http://127.0.0.1:59999/hook/${agent}`, - expect.objectContaining({ method: 'POST' }) - ) - await cleanup?.() - expect(dispose).toHaveBeenCalledOnce() - expect(subscriptionSignal?.aborted).toBe(true) - }) - - it('declares no OpenCode major on posts from the OpenCode 1 server() entry', async () => { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const bodies: Record[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - bodies.push(record(JSON.parse(String(init?.body))) ?? {}) - return new Response('{}', { status: 200 }) - }) - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const hooks = await module.default?.server?.({ - client: { session: { get: async () => ({ data: { id: 'ses_root' } }) } } - }) - await hooks?.event({ - event: { - type: 'session.status', - properties: { sessionID: 'ses_root', status: { type: 'busy' } } - } - }) - await vi.waitFor(() => expect(bodies.length).toBeGreaterThan(0)) - expect(bodies.filter((body) => 'opencodeMajor' in body)).toEqual([]) - await hooks?.dispose?.() - }) - - it('maps permission, form, and text events through the live setup bridge', async () => { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const posts: { body: PostBody }[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - posts.push({ body: record(JSON.parse(String(init?.body))) ?? {} }) - return new Response('{}', { status: 200 }) - }) - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const cleanup = await module.default?.setup?.({ - session: { - get: async ({ sessionID }: { sessionID: string }) => ({ data: { id: sessionID } }), - hook: async () => ({ dispose: vi.fn() }) - }, - event: { - subscribe: async function* () { - yield { - type: 'permission.asked', - data: { id: 'perm-1', sessionID: 'ses_root', action: 'bash', resources: ['pwd'] } - } - yield { - type: 'permission.replied', - data: { id: 'perm-1', requestID: 'perm-1', sessionID: 'ses_root' } - } - yield { - type: 'form.created', - data: { - form: { - id: 'form-1', - sessionID: 'ses_root', - title: 'Pick', - metadata: { kind: 'question', tool: { messageID: 'msg-0', id: 'tool-0' } }, - fields: [ - { - title: 'Color', - description: 'Choose', - type: 'string', - options: [{ label: 'Red', value: 'red' }] - } - ] - } - } - } - yield { - type: 'session.text.started', - data: { sessionID: 'ses_root', assistantMessageID: 'msg-1' } - } - yield { - type: 'session.text.delta', - data: { sessionID: 'ses_root', assistantMessageID: 'msg-1', delta: 'hello' } - } - yield { - type: 'session.text.ended', - data: { sessionID: 'ses_root', assistantMessageID: 'msg-1', text: 'hello' } - } - yield { type: 'form.cancelled', data: { id: 'form-1', sessionID: 'ses_root' } } - } - } - }) - await vi.waitFor(() => { - const names = posts.map(({ body }) => payload(body).hook_event_name) - expect(names).toEqual(expect.arrayContaining(['PermissionRequest', 'MessagePart'])) - }) - await vi.waitFor(() => { - const names = posts.map(({ body }) => payload(body).hook_event_name) - expect(names).toContain('AskUserQuestion') - expect(posts).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - payload: expect.objectContaining({ - hook_event_name: 'AskUserQuestion', - sessionID: 'ses_root' - }) - }) - }) - ]) - ) - }) - await vi.waitFor(() => { - const names = posts.map(({ body }) => payload(body).hook_event_name) - expect(names.at(-1)).toBe('SessionIdle') - }) - await cleanup?.() - }) - - // OpenCode 2 form ownership decides blocker retirement; metadata alone cannot identify it. - async function runSetupBridge( - events: { type: string; data: Record }[] - ): Promise<{ names: string[]; cleanup?: () => Promise }> { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const names: string[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - names.push(String(payload(record(JSON.parse(String(init?.body))) ?? {}).hook_event_name)) - return new Response('{}', { status: 200 }) - }) - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const cleanup = await module.default?.setup?.({ - session: { - get: async ({ sessionID }: { sessionID: string }) => ({ data: { id: sessionID } }), - hook: async () => ({ dispose: vi.fn() }) - }, - event: { - subscribe: async function* () { - for (const event of events) { - yield event - } - } - } - }) - return { names, cleanup } - } - - function questionForm(id: string): Record { - return { - id, - sessionID: 'ses_root', - title: 'Questions', - metadata: { kind: 'question', tool: { messageID: 'msg-0', id: 'tool-0' } }, - fields: [{ key: 'q0', title: 'Proceed?', type: 'string', options: [] }] - } - } - - it('ignores a form owned by the non-session elicitation sentinel', async () => { - const { names, cleanup } = await runSetupBridge([ - { type: 'session.execution.started', data: { sessionID: 'ses_root' } }, - { - type: 'form.created', - data: { - form: { - id: 'form-mcp', - sessionID: 'global', - title: 'server is requesting input', - metadata: { kind: 'mcp-elicitation', server: 'server' }, - fields: [{ key: 'elicitation', title: 'Input', type: 'string', options: [] }] - } - } - }, - { type: 'form.cancelled', data: { id: 'form-mcp', sessionID: 'global' } }, - { type: 'session.execution.succeeded', data: { sessionID: 'ses_root' } } - ]) - await vi.waitFor(() => { - expect(names.at(-1)).toBe('SessionIdle') - }) - expect(names).not.toContain('AskUserQuestion') - await cleanup?.() - }) - - // Optional metadata kinds cannot decide whether session-owned forms block. - it.each([ - ['no metadata at all', undefined], - ['metadata without a kind', { server: 'server' }], - ['an unrecognised kind', { kind: 'some.future.kind' }], - ['the web search provider picker', { kind: 'websearch.provider' }] - ])('blocks the pane on a session-owned form with %s', async (_label, metadata) => { - const { names, cleanup } = await runSetupBridge([ - { type: 'session.execution.started', data: { sessionID: 'ses_root' } }, - { - type: 'form.created', - data: { - form: { - id: 'form-unknown', - sessionID: 'ses_root', - title: 'Choose a web search provider', - ...(metadata === undefined ? {} : { metadata }), - fields: [{ key: 'provider', title: 'Provider', type: 'string', options: [] }] - } - } - } - ]) - await vi.waitFor(() => { - expect(names).toContain('AskUserQuestion') - }) - expect(names.at(-1)).toBe('AskUserQuestion') - await cleanup?.() - }) - - it.each(['form.replied', 'form.cancelled'])( - 'retires an admitted unknown-kind blocker on %s', - async (resolution) => { - const { names, cleanup } = await runSetupBridge([ - { type: 'session.execution.started', data: { sessionID: 'ses_root' } }, - { - type: 'form.created', - data: { - form: { - id: 'form-unknown', - sessionID: 'ses_root', - title: 'Web Search', - fields: [{ key: 'choice', title: 'Allow?', type: 'string', options: [] }] - } - } - }, - { type: resolution, data: { id: 'form-unknown', sessionID: 'ses_root' } }, - { type: 'session.execution.succeeded', data: { sessionID: 'ses_root' } } - ]) - await vi.waitFor(() => { - expect(names).toContain('AskUserQuestion') - expect(names.at(-1)).toBe('SessionIdle') - }) - await cleanup?.() - } - ) - - it('still blocks on a real question form and retires it on reply', async () => { - const { names, cleanup } = await runSetupBridge([ - { type: 'session.execution.started', data: { sessionID: 'ses_root' } }, - { type: 'form.created', data: { form: questionForm('form-q') } }, - { - type: 'form.replied', - data: { id: 'form-q', sessionID: 'ses_root', answer: { q0: 'Yes' } } - }, - { type: 'session.execution.succeeded', data: { sessionID: 'ses_root' } } - ]) - await vi.waitFor(() => { - expect(names).toContain('AskUserQuestion') - expect(names.at(-1)).toBe('SessionIdle') - }) - await cleanup?.() - }) - - it('keeps a live question blocker while an ignored form is raised and resolved', async () => { - const { names, cleanup } = await runSetupBridge([ - { type: 'session.execution.started', data: { sessionID: 'ses_root' } }, - { type: 'form.created', data: { form: questionForm('form-q') } }, - { - type: 'form.created', - data: { - form: { - id: 'form-mcp', - sessionID: 'global', - title: 'server is requesting input', - metadata: { kind: 'mcp-elicitation', server: 'server' }, - fields: [{ key: 'elicitation', title: 'Input', type: 'string', options: [] }] - } - } - }, - { type: 'form.cancelled', data: { id: 'form-mcp', sessionID: 'global' } } - ]) - await vi.waitFor(() => { - expect(names).toContain('AskUserQuestion') - }) - expect(names.at(-1)).toBe('AskUserQuestion') - await cleanup?.() - }) - - it.each(['waiting', 'idle', 'disposed'])( - 'drops an admitted prompt overtaken by %s', - async (transition) => { - process.env.ORCA_PANE_KEY = 'tab-1:leaf-1' - const posts: unknown[] = [] - globalThis.fetch = vi.fn(async (_input, init) => { - posts.push(JSON.parse(String(init?.body))) - return new Response('{}', { status: 200 }) - }) - let releaseLookup: (value: { data: { id: string } }) => void = () => {} - const lookup = new Promise<{ data: { id: string } }>((resolve) => { - releaseLookup = resolve - }) - const module = await loadPluginModule( - agent === 'opencode2' - ? _internals.getOpenCode2PluginSource() - : _internals.getOpenCodePluginSource() - ) - const hooks = await module.default?.server?.({ client: { session: { get: () => lookup } } }) - expect(hooks).toBeDefined() - const prompt = hooks?.event({ - event: { - type: 'session.next.prompt.admitted', - properties: { - sessionID: 'ses_root', - messageID: 'msg_user', - prompt: { text: 'stale prompt' } - } - } - }) - if (transition === 'disposed') { - await hooks?.dispose?.() - } else { - await hooks?.event({ - event: { type: 'session.created', properties: { info: { id: 'ses_root' } } } - }) - await hooks?.event({ - event: - transition === 'waiting' - ? { - type: 'permission.asked', - properties: { - id: 'perm_1', - sessionID: 'ses_root', - permission: 'bash', - patterns: ['sleep 25'] - } - } - : { type: 'session.idle', properties: { sessionID: 'ses_root' } } - }) - } - releaseLookup({ data: { id: 'ses_root' } }) - await prompt - expect(posts).not.toContainEqual( - expect.objectContaining({ payload: expect.objectContaining({ role: 'user' }) }) - ) - await hooks?.dispose?.() - } - ) -}) diff --git a/src/main/opencode/hook-plugin-opencode2-tui-ownership.test.ts b/src/main/opencode/hook-plugin-opencode2-tui-ownership.test.ts deleted file mode 100644 index c9f589665c0..00000000000 --- a/src/main/opencode/hook-plugin-opencode2-tui-ownership.test.ts +++ /dev/null @@ -1,861 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { pathToFileURL } from 'node:url' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -import { _internals } from './hook-service' -import { fakeTui, type BusEvent } from './opencode-tui-session-fixture' - -type Post = { - paneKey?: string - opencodeMajor?: number - payload?: { - hook_event_name?: string - sessionID?: string - root_state?: string - root_turn_error_name?: string - } -} -type PluginModule = { - default?: { setup?: (ctx: unknown) => Promise<(() => Promise) | undefined> } -} - -const { setTimeout: realSetTimeout, clearTimeout: realClearTimeout } = globalThis - -const PANE_A = 'tabA:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' -const PANE_B = 'tabB:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -const SES_A = 'ses_f161fd85fffeieT0zYt80ZKorS' -const SES_B = 'ses_f161fcd7affeffV0OOrMCrTxtQ' -const ENV_KEYS = [ - 'ORCA_PANE_KEY', - 'ORCA_OPENCODE_AGENT', - 'ORCA_AGENT_HOOK_ENDPOINT', - 'ORCA_AGENT_HOOK_PORT', - 'ORCA_AGENT_HOOK_TOKEN' -] as const - -// OpenCode 2.0.14 event shapes, shared by server and TUI plugins. -function turn(sessionID: string, text: string): { start: BusEvent[]; finish: BusEvent[] } { - const assistantMessageID = `msg_${sessionID}_a` - return { - start: [ - { - type: 'session.created', - data: { sessionID, projectID: 'global', location: { directory: '/proj' }, subpath: '' } - }, - { - type: 'session.inbox.enqueued', - data: { - sessionID, - inboxID: `msg_${sessionID}_u`, - item: { type: 'user', payload: { text, files: [] }, delivery: 'steer' } - } - }, - { type: 'session.execution.started', data: { sessionID } }, - { type: 'session.step.started', data: { sessionID, assistantMessageID, agent: 'build' } }, - { type: 'session.text.started', data: { sessionID, assistantMessageID, ordinal: 0 } } - ], - finish: [ - { - type: 'session.text.ended', - data: { sessionID, assistantMessageID, ordinal: 0, text: 'tick0 tick1 ' } - }, - { type: 'session.step.ended', data: { sessionID, assistantMessageID, finish: 'stop' } }, - { type: 'session.execution.succeeded', data: { sessionID } } - ] - } -} - -describe('OpenCode 2 TUI reporter: each pane reports its own sessions', () => { - let tempDir: string - let savedFetch: typeof globalThis.fetch - let savedEnv: Record - let savedArgv: string[] - let posts: Post[] - /** Includes the sessionless start boundary from each fresh TUI. */ - let allPosts: Post[] - let failPosts: boolean - let postDelayMs: number - const cleanups = new Set<() => Promise>() - const delayedPosts = new Set<() => void>() - - beforeEach(() => { - tempDir = mkdtempSync(join(tmpdir(), 'orca-opencode-tui-adapter-')) - savedFetch = globalThis.fetch - savedArgv = process.argv - savedEnv = {} - for (const key of ENV_KEYS) { - savedEnv[key] = process.env[key] - } - process.env.ORCA_OPENCODE_AGENT = 'opencode' - delete process.env.ORCA_AGENT_HOOK_ENDPOINT - process.env.ORCA_AGENT_HOOK_PORT = '59999' - process.env.ORCA_AGENT_HOOK_TOKEN = 'test-token' - posts = [] - allPosts = [] - failPosts = false - postDelayMs = 0 - globalThis.fetch = vi.fn(async (_input, init) => { - const body = JSON.parse(String(init?.body)) - if (postDelayMs > 0) { - await new Promise((resolve) => { - const finish = (): void => { - clearTimeout(timer) - delayedPosts.delete(finish) - resolve() - } - const timer = setTimeout(finish, postDelayMs) - delayedPosts.add(finish) - }) - } - if (failPosts) { - return new Response('{}', { status: 500 }) - } - allPosts.push(body) - // Per-session assertions exclude the sessionless fresh-TUI boundary. - if ( - body.payload?.hook_event_name !== 'SessionStart' || - body.payload.sessionID !== undefined - ) { - posts.push(body) - } - return new Response('{}', { status: 200 }) - }) - }) - - afterEach(async () => { - let deadline: ReturnType | undefined - try { - postDelayMs = 0 - for (const finish of delayedPosts) { - finish() - } - const closing = Promise.allSettled([...cleanups].map((cleanup) => cleanup())) - expect( - await Promise.race([ - closing.then((results) => results.every((result) => result.status === 'fulfilled')), - new Promise((resolve) => { - deadline = realSetTimeout(() => resolve(false), 2000) - }) - ]) - ).toBe(true) - } finally { - realClearTimeout(deadline) - try { - if (vi.isFakeTimers()) { - expect(vi.getTimerCount()).toBe(0) - } - } finally { - if (vi.isFakeTimers()) { - vi.clearAllTimers() - } - vi.useRealTimers() - cleanups.clear() - delayedPosts.clear() - globalThis.fetch = savedFetch - process.argv = savedArgv - for (const key of ENV_KEYS) { - if (savedEnv[key] === undefined) { - delete process.env[key] - } else { - process.env[key] = savedEnv[key] - } - } - rmSync(tempDir, { recursive: true, force: true }) - } - } - }) - - async function loadPlugin(dir = tempDir): Promise { - // Bypass ESM caching to simulate a separate process. - const pluginPath = join(dir, `orca-opencode-status-${Math.random().toString(36).slice(2)}.mjs`) - writeFileSync(pluginPath, _internals.getOpenCodePluginSource()) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the generated module's default export is exercised below and fails the test if absent. - const plugin = (await import(pathToFileURL(pluginPath).href)) as PluginModule - if (!vi.isFakeTimers()) { - vi.useFakeTimers({ - toFake: ['Date', 'setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] - }) - } - const setup = plugin.default?.setup - return { - default: { - setup: async (ctx) => { - const cleanup = await setup?.(ctx) - if (!cleanup) { - return - } - const close = async (): Promise => { - try { - await cleanup() - if (vi.isFakeTimers()) { - expect(vi.getTimerCount()).toBe(0) - } - } finally { - cleanups.delete(close) - } - } - cleanups.add(close) - return close - } - } - } - } - - const summary = (list: Post[]): string[] => - list.map((post) => `${post.payload?.hook_event_name}:${post.payload?.sessionID}`) - - async function runPane( - paneKey: string, - ownSession: string, - script: (tui: ReturnType) => Promise - ): Promise { - process.env.ORCA_PANE_KEY = paneKey - const start = posts.length - const tui = fakeTui() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - await script(tui) - await waitFor(() => { - expect(summary(posts.slice(start)).at(-1)).toBe(`SessionIdle:${ownSession}`) - }) - await cleanup?.() - return posts.slice(start) - } - - const tick = async (ms = 20): Promise => { - await (vi.isFakeTimers() - ? vi.advanceTimersByTimeAsync(ms) - : new Promise((resolve) => setTimeout(resolve, ms))) - } - const waitFor = async ( - check: () => void, - { timeout = 1000 }: { timeout?: number } = {} - ): Promise => { - if (!vi.isFakeTimers()) { - await vi.waitFor(check, { timeout }) - return - } - const deadline = Date.now() + timeout - await tick(0) - for (;;) { - try { - check() - return - } catch (error) { - if (Date.now() >= deadline) { - throw error - } - await tick(Math.min(50, deadline - Date.now())) - } - } - } - const pump = async (tui: ReturnType, events: BusEvent[]): Promise => { - for (const event of events) { - tui.emit(event) - await tick() - } - } - - it.each([ - ['session.execution.failed', { error: { type: 'api' } }, 'api'], - ['session.execution.failed', {}, 'UnknownError'], - ['session.execution.interrupted', { reason: 'user' }, 'MessageAbortedError'], - ['session.execution.interrupted', { reason: 'pause' }, undefined], - ['session.execution.succeeded', {}, undefined] - ])('carries the root verdict for %s', async (type, fields, errorName) => { - const reported = await runPane(PANE_A, SES_A, async (tui) => { - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'root').start) - await pump(tui, [{ type, data: { sessionID: SES_A, ...fields } }]) - }) - expect(reported.at(-1)?.payload).toMatchObject({ root_state: 'done' }) - expect(reported.at(-1)?.payload?.root_turn_error_name).toBe(errorName) - }) - - it('clears a failed root verdict on its next turn', async () => { - const reported = await runPane(PANE_A, SES_A, async (tui) => { - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'first').start) - await pump(tui, [{ type: 'session.execution.failed', data: { sessionID: SES_A } }]) - await pump(tui, [{ type: 'session.execution.started', data: { sessionID: SES_A } }]) - await pump(tui, turn(SES_A, 'next').finish) - }) - expect(reported.at(-1)?.payload?.root_turn_error_name).toBeUndefined() - }) - - it('gives each overlapping pane only its own session and its own Idle', async () => { - const a = turn(SES_A, 'A long SLEEP=12') - const b = turn(SES_B, 'B short SLEEP=3') - const bus = [...a.start, ...b.start, ...b.finish, ...a.finish] - const paneA = await runPane(PANE_A, SES_A, async (tui) => { - tui.navigate(SES_A) - await pump(tui, bus) - }) - const paneB = await runPane(PANE_B, SES_B, async (tui) => { - await pump(tui, [...a.start]) - tui.navigate(SES_B) - await pump(tui, [...b.start, ...b.finish, ...a.finish]) - }) - - expect(paneA.every((post) => post.paneKey === PANE_A)).toBe(true) - expect(paneB.every((post) => post.paneKey === PANE_B)).toBe(true) - // Prevent the host’s OpenCode 1 session binder from consuming these posts. - expect([...paneA, ...paneB].every((post) => post.opencodeMajor === 2)).toBe(true) - expect(new Set(paneA.map((post) => post.payload?.sessionID))).toEqual(new Set([SES_A])) - expect(new Set(paneB.map((post) => post.payload?.sessionID))).toEqual(new Set([SES_B])) - for (const [list, session] of [ - [paneA, SES_A], - [paneB, SES_B] - ] as const) { - const names = summary(list) - expect(names[0]).toBe(`SessionStart:${session}`) - expect(names).toContain(`SessionBusy:${session}`) - expect(names.at(-1)).toBe(`SessionIdle:${session}`) - } - }) - - it('hydrates a session whose route switch lands after execution started', async () => { - const b = turn(SES_B, 'B tui SLEEP=4') - const paneB = await runPane(PANE_B, SES_B, async (tui) => { - await pump(tui, b.start) - expect(posts).toHaveLength(0) - tui.navigate(SES_B) - await waitFor(() => { - expect(summary(posts)).toContain(`SessionBusy:${SES_B}`) - }) - await pump(tui, b.finish) - }) - - const names = summary(paneB) - expect(names.slice(0, 3)).toEqual([ - `SessionStart:${SES_B}`, - `MessagePart:${SES_B}`, - `SessionBusy:${SES_B}` - ]) - expect(names.at(-1)).toBe(`SessionIdle:${SES_B}`) - }) - - it('keeps a started turn until it settles after the route moves on', async () => { - const a = turn(SES_A, 'A long') - const paneA = await runPane(PANE_A, SES_A, async (tui) => { - tui.navigate(SES_A) - await pump(tui, a.start) - tui.navigate('ses_other_idle_session') - await tick(250) - await pump(tui, a.finish) - }) - expect(summary(paneA)).toContain(`SessionBusy:${SES_A}`) - expect(summary(paneA).at(-1)).toBe(`SessionIdle:${SES_A}`) - }) - - it('reports nothing for sessions the pane never showed', async () => { - process.env.ORCA_PANE_KEY = PANE_A - const tui = fakeTui() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - const b = turn(SES_B, 'another pane') - await pump(tui, [...b.start, ...b.finish]) - await tick(250) - await cleanup?.() - expect(posts).toEqual([]) - }) - - it('settles an owned turn once the session data says it ended without an end event', async () => { - process.env.ORCA_PANE_KEY = PANE_A - const tui = fakeTui() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'A').start) - tui.loseEnd(SES_A) - await tick(99) - expect(summary(posts).at(-1)).toBe(`SessionBusy:${SES_A}`) - await tick(1) - expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`) - await cleanup?.() - }) - - it('does not settle a turn early while its events are still queued', async () => { - process.env.ORCA_PANE_KEY = PANE_A - const tui = fakeTui() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - tui.navigate(SES_A) - await tick() - const a = turn(SES_A, 'A fails fast') - for (const event of [...a.start, ...a.finish]) { - tui.emit(event) - } - await waitFor(() => { - expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`) - }) - await tick(250) - await cleanup?.() - const statuses = posts - .map((post) => post.payload?.hook_event_name) - .filter((name) => name === 'SessionBusy' || name === 'SessionIdle') - expect(statuses).toEqual(['SessionBusy', 'SessionIdle']) - }) - - it('re-derives Working for an owned session whose start it missed', async () => { - process.env.ORCA_PANE_KEY = PANE_A - const tui = fakeTui() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - tui.navigate(SES_A) - const first = turn(SES_A, 'A') - await pump(tui, [...first.start, ...first.finish]) - await waitFor(() => { - expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`) - }) - tui.loseStart(SES_A) - await waitFor(() => { - expect(summary(posts).at(-1)).toBe(`SessionBusy:${SES_A}`) - }) - tui.loseEnd(SES_A) - await waitFor(() => { - expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`) - }) - await cleanup?.() - }) - - describe('derived from the session data', () => { - const SES_CHILD = 'ses_f161fe00affeChildSubagent1' - const statuses = (list: Post[]): string[] => - summary(list).filter((name) => - /^(SessionBusy|SessionIdle|PermissionRequest|AskUserQuestion):/.test(name) - ) - const start = async ( - tui: ReturnType - ): Promise<(() => Promise) | undefined> => { - process.env.ORCA_PANE_KEY = PANE_A - return (await loadPlugin()).default?.setup?.(tui.ctx) - } - const childStart = (parentID: string): BusEvent[] => [ - { type: 'session.created', data: { sessionID: SES_CHILD, parentID } }, - { type: 'session.execution.started', data: { sessionID: SES_CHILD } } - ] - const permission = (sessionID: string): BusEvent => ({ - type: 'permission.asked', - data: { id: 'per_1', sessionID, action: 'bash', resources: ['rm -rf build'] } - }) - - it('publishes a root failure while its child keeps the aggregate Working', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - await pump(tui, [...turn(SES_A, 'root').start, ...childStart(SES_A)]) - await pump(tui, [{ type: 'session.execution.failed', data: { sessionID: SES_A } }]) - await waitFor(() => { - expect(posts.at(-1)?.payload).toMatchObject({ - hook_event_name: 'SessionBusy', - root_state: 'done', - root_turn_error_name: 'UnknownError' - }) - }) - await pump(tui, [{ type: 'session.execution.succeeded', data: { sessionID: SES_CHILD } }]) - expect(posts.at(-1)?.payload?.root_turn_error_name).toBe('UnknownError') - await cleanup?.() - }) - - it('does not turn a child failure into a root failure', async () => { - const reported = await runPane(PANE_A, SES_A, async (tui) => { - tui.navigate(SES_A) - await pump(tui, [...turn(SES_A, 'root').start, ...childStart(SES_A)]) - await pump(tui, [{ type: 'session.execution.failed', data: { sessionID: SES_CHILD } }]) - await pump(tui, turn(SES_A, 'root').finish) - }) - expect(reported.at(-1)?.payload?.root_turn_error_name).toBeUndefined() - }) - - it('keeps a failed terminal verdict through plugin hot reload', async () => { - const tui = fakeTui() - const first = await start(tui) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'root').start) - await pump(tui, [{ type: 'session.execution.failed', data: { sessionID: SES_A } }]) - await waitFor(() => expect(posts.at(-1)?.payload?.root_turn_error_name).toBe('UnknownError')) - await first?.() - const before = posts.length - const second = await start(tui) - await tick(150) - expect(posts).toHaveLength(before) - expect(posts.at(-1)?.payload?.root_turn_error_name).toBe('UnknownError') - await second?.() - }) - - it.each(['session.execution.succeeded', 'session.execution.interrupted'])( - 'repairs a failed verdict when %s follows a missed turn start during unload', - async (finishType) => { - const tui = fakeTui() - const first = await start(tui) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'first').start) - await pump(tui, [{ type: 'session.execution.failed', data: { sessionID: SES_A } }]) - await first?.() - await pump(tui, [ - { type: 'session.execution.started', data: { sessionID: SES_A } }, - { type: finishType, data: { sessionID: SES_A, reason: 'user' } } - ]) - const second = await start(tui) - await waitFor(() => expect(posts.at(-1)?.payload?.root_turn_error_name).toBeUndefined()) - expect(posts.at(-1)?.payload).toMatchObject({ - hook_event_name: 'SessionIdle', - root_state: 'done' - }) - await second?.() - } - ) - - it('shows Done for a turn that ended while the plugin was reloading', async () => { - const tui = fakeTui() - const firstGeneration = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - await pump(tui, a.start) - await waitFor(() => expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`])) - const beforeReload = posts.length - await firstGeneration?.() - expect(posts).toHaveLength(beforeReload) - await pump(tui, a.finish) - const secondGeneration = await start(tui) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await secondGeneration?.() - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`, `SessionIdle:${SES_A}`]) - }) - - it('keeps a navigated-away turn across a reload and settles it after', async () => { - const tui = fakeTui() - const firstGeneration = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - await pump(tui, a.start) - tui.navigate(SES_B) - await tick(150) - await firstGeneration?.() - const secondGeneration = await start(tui) - await tick(150) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`]) - await pump(tui, a.finish) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await secondGeneration?.() - }) - - it('re-posts a level the previous generation could not deliver', async () => { - const tui = fakeTui() - failPosts = true - const firstGeneration = await start(tui) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'A').start) - await tick(50) - await firstGeneration?.() - failPosts = false - const secondGeneration = await start(tui) - await waitFor(() => expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`])) - await secondGeneration?.() - }) - - it('posts each level once and in order while posts are slow', async () => { - postDelayMs = 120 - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - const b = turn(SES_B, 'another pane') - for (const event of [...a.start, ...b.start, ...b.finish, ...a.finish]) { - tui.emit(event) - } - await tick(119) - expect(allPosts).toEqual([]) - await tick(1) - expect(summary(allPosts)).toEqual(['SessionStart:undefined']) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`), { - timeout: 3000 - }) - await tick(300) - await cleanup?.() - expect(summary(posts)).toEqual([ - `SessionStart:${SES_A}`, - `MessagePart:${SES_A}`, - `SessionBusy:${SES_A}`, - `MessagePart:${SES_A}`, - `SessionIdle:${SES_A}` - ]) - expect(posts.at(-2)?.payload).toMatchObject({ role: 'assistant', text: 'tick0 tick1 ' }) - expect(summary(allPosts)[0]).toBe('SessionStart:undefined') - }) - - // Fresh panes may retain status left by another process before an upgrade. - it('lands one start boundary in a freshly started TUI, and none on a reload after Done', async () => { - const tui = fakeTui() - const firstGeneration = await start(tui) - await waitFor(() => expect(summary(allPosts)).toEqual(['SessionStart:undefined'])) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - await pump(tui, [...a.start, ...a.finish]) - await waitFor(() => expect(summary(allPosts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await firstGeneration?.() - const secondGeneration = await start(tui) - await tick(250) - await secondGeneration?.() - expect(summary(allPosts).at(-1)).toBe(`SessionIdle:${SES_A}`) - expect(summary(allPosts).filter((name) => name.startsWith('SessionStart:'))).toEqual([ - 'SessionStart:undefined', - `SessionStart:${SES_A}` - ]) - }) - - it('lands the start boundary only once across reloads of an idle pane', async () => { - const tui = fakeTui() - const firstGeneration = await start(tui) - await waitFor(() => expect(summary(allPosts)).toEqual(['SessionStart:undefined'])) - await firstGeneration?.() - const secondGeneration = await start(tui) - await tick(150) - await secondGeneration?.() - expect(summary(allPosts)).toEqual(['SessionStart:undefined']) - }) - - it('names the idle session a freshly started TUI shows', async () => { - const tui = fakeTui() - tui.navigate(SES_B) - const cleanup = await start(tui) - await waitFor(() => expect(summary(allPosts)).toEqual([`SessionStart:${SES_B}`])) - await cleanup?.() - }) - - it('posts Working instead of the start boundary when the route shows a running turn', async () => { - const tui = fakeTui() - tui.navigate(SES_A) - tui.loseStart(SES_A) - const cleanup = await start(tui) - await waitFor(() => expect(summary(allPosts)).toEqual([`SessionBusy:${SES_A}`])) - await tick(150) - await cleanup?.() - expect(summary(allPosts)).toEqual([`SessionBusy:${SES_A}`]) - }) - - it('lands no start boundary where OpenCode keeps no plugin memory', async () => { - const tui = fakeTui() - Reflect.deleteProperty(tui.ctx, 'storage') - const cleanup = await start(tui) - await tick(150) - await cleanup?.() - expect(allPosts).toEqual([]) - }) - - it('stays Working while a child session holds the turn, even if its end is missed', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A spawns a background task') - await pump(tui, [...a.start, ...childStart(SES_A), ...a.finish]) - await tick(250) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`, `SessionBusy:${SES_A}`]) - expect(posts.at(-1)?.payload).toMatchObject({ root_state: 'done' }) - tui.loseEnd(SES_CHILD) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await cleanup?.() - expect(posts.every((post) => post.payload?.sessionID === SES_A)).toBe(true) - }) - - it('keeps automatically answered permissions Working without an attention post', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'auto').start) - for (let index = 0; index < 3; index += 1) { - tui.emit({ - type: 'permission.asked', - data: { ...permission(SES_A).data, id: `auto_${index}` } - }) - await tick(20) - tui.emit({ - type: 'permission.replied', - data: { sessionID: SES_A, requestID: `auto_${index}` } - }) - } - await tick(650) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`]) - await pump(tui, turn(SES_A, 'auto').finish) - await cleanup?.() - }) - - it("shows a child's permission as Needs input on the root, then Working after the reply", async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - await pump(tui, [...a.start, ...childStart(SES_A)]) - await tick(60) - await pump(tui, [permission(SES_CHILD)]) - await tick(479) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`]) - await tick(1) - expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`) - await pump(tui, [ - { type: 'permission.replied', data: { sessionID: SES_CHILD, requestID: 'per_1' } }, - { type: 'session.execution.succeeded', data: { sessionID: SES_CHILD } }, - ...a.finish - ]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await cleanup?.() - expect(statuses(posts)).toEqual([ - `SessionBusy:${SES_A}`, - `PermissionRequest:${SES_A}`, - `SessionBusy:${SES_A}`, - `SessionIdle:${SES_A}` - ]) - }) - - // MessagePart implies Working, so it must not bury an open request. - it('keeps Needs input while the root streams text beside a waiting background child', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A spawns a background task') - await pump(tui, [...a.start, ...childStart(SES_A), permission(SES_CHILD)]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`)) - await pump(tui, a.finish) - await tick(300) - expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`) - await cleanup?.() - }) - - it('clears Needs input answered while disconnected once the TUI reconnects', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - await pump(tui, [...turn(SES_A, 'A').start, permission(SES_A)]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`)) - tui.navigate(SES_B) - await pump(tui, [{ type: 'server.connected', data: {} }]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionBusy:${SES_A}`)) - await cleanup?.() - }) - - it('ignores a reply that a reconnect fetch restores', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - await pump(tui, [...turn(SES_A, 'A').start, permission(SES_A)]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`)) - const release = tui.holdPermissionFetch() - tui.serverPermissions.set(SES_A, [...(tui.permissions.get(SES_A) ?? [])]) - await pump(tui, [ - { type: 'server.connected', data: {} }, - { type: 'permission.replied', data: { sessionID: SES_A, requestID: 'per_1' } } - ]) - release() - await tick(250) - expect(tui.permissions.get(SES_A)).toHaveLength(1) - expect(summary(posts).at(-1)).toBe(`SessionBusy:${SES_A}`) - await cleanup?.() - }) - - it('re-posts the current level once the hook endpoint moves', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - await pump(tui, turn(SES_A, 'A').start) - await tick(200) - await waitFor(() => expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`])) - process.env.ORCA_AGENT_HOOK_PORT = '59998' - await tick(4699) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`]) - await tick(1) - expect(statuses(posts)).toEqual([`SessionBusy:${SES_A}`, `SessionBusy:${SES_A}`]) - await tick(300) - await tick(5000) - await tick(50) - expect(statuses(posts)).toHaveLength(2) - await cleanup?.() - }) - - it('does not pin Needs input on a request the data kept after its turn ended', async () => { - const tui = fakeTui() - const cleanup = await start(tui) - tui.navigate(SES_A) - const a = turn(SES_A, 'A') - await pump(tui, [...a.start, permission(SES_A)]) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`PermissionRequest:${SES_A}`)) - await pump(tui, a.finish) - await waitFor(() => expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`)) - await tick(250) - expect(summary(posts).at(-1)).toBe(`SessionIdle:${SES_A}`) - await cleanup?.() - }) - }) - - it.each([ - ['an OpenCode 1 TUI', () => fakeTui('1.18.33')], - ['the other pane variant', () => fakeTui()], - ['a TUI outside an Orca pane', () => fakeTui()] - ])('stays silent in %s', async (label, make) => { - if (label === 'the other pane variant') { - process.env.ORCA_OPENCODE_AGENT = 'opencode2' - } - process.env.ORCA_PANE_KEY = PANE_A - if (label === 'a TUI outside an Orca pane') { - delete process.env.ORCA_PANE_KEY - } - const tui = make() - const cleanup = await (await loadPlugin()).default?.setup?.(tui.ctx) - expect(tui.listen).not.toHaveBeenCalled() - await cleanup?.() - }) - - describe('server plugin stand-down', () => { - function serverContext() { - const subscribe = vi.fn(async function* () {}) - const hook = vi.fn(async () => ({ dispose: vi.fn() })) - return { - subscribe, - hook, - ctx: { - session: { hook, get: async () => undefined }, - event: { subscribe } - } - } - } - const installTuiCopy = (): void => { - mkdirSync(join(tempDir, 'orca-opencode-status-tui')) - writeFileSync(join(tempDir, 'orca-opencode-status-tui', 'tui.js'), '') - } - - it('reports nothing from a serve process when the TUI copy is installed beside it', async () => { - installTuiCopy() - process.argv = [...savedArgv, 'serve', '--service'] - const server = serverContext() - const cleanup = await (await loadPlugin()).default?.setup?.(server.ctx) - expect(server.subscribe).not.toHaveBeenCalled() - expect(server.hook).not.toHaveBeenCalled() - await cleanup?.() - }) - - it('stands down in a --standalone private server too', async () => { - installTuiCopy() - process.argv = [...savedArgv, 'serve', '--stdio', '--port', '0'] - const server = serverContext() - const cleanup = await (await loadPlugin()).default?.setup?.(server.ctx) - expect(server.subscribe).not.toHaveBeenCalled() - await cleanup?.() - }) - - // Older SSH relays install the server file without a TUI copy. - it('keeps reporting from a serve process whose installer wrote no TUI copy', async () => { - process.argv = [...savedArgv, 'serve', '--service'] - const server = serverContext() - const cleanup = await (await loadPlugin()).default?.setup?.(server.ctx) - expect(server.subscribe).toHaveBeenCalled() - await cleanup?.() - }) - }) -}) diff --git a/src/main/opencode/hook-service-legacy-acl.test.ts b/src/main/opencode/hook-service-legacy-acl.test.ts deleted file mode 100644 index fe838ade9fd..00000000000 --- a/src/main/opencode/hook-service-legacy-acl.test.ts +++ /dev/null @@ -1,323 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - existsSync, - lstatSync, - mkdirSync, - mkdtempSync, - readFileSync, - readdirSync, - realpathSync, - rmSync, - symlinkSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' -import type * as NodeFs from 'node:fs' -import type * as Win32Utils from '../windows/windows-directory-acl' -import { setAppEnvironment } from '../../shared/app-environment' -import { - openCodeTuiPluginDirName, - writeOpenCodeTuiPlugin -} from '../../shared/opencode-tui-plugin-install' -import { - OpenCodeHookService, - openCode2HookService, - getOpenCodePluginSource, - getOpenCode2PluginSource -} from './hook-service' - -const fsMock = vi.hoisted(() => ({ - writeFileSync: vi.fn(), - mkdirSync: vi.fn(), - grantDirAcl: vi.fn<(directory: string) => void>() -})) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - fsMock.writeFileSync.mockImplementation(actual.writeFileSync) - fsMock.mkdirSync.mockImplementation(actual.mkdirSync) - return { ...actual, writeFileSync: fsMock.writeFileSync, mkdirSync: fsMock.mkdirSync } -}) - -vi.mock('../windows/windows-directory-acl', async (importOriginal) => ({ - ...(await importOriginal()), - grantDirAcl: fsMock.grantDirAcl -})) - -const hostPlatform = process.platform -const variants = [ - { - hooks: 'opencode-hooks', - file: 'orca-opencode-status.js', - service: new OpenCodeHookService(), - source: getOpenCodePluginSource - }, - { - hooks: 'opencode2-hooks', - file: 'orca-opencode2-status.js', - service: openCode2HookService, - source: getOpenCode2PluginSource - } -] - -let root: string - -beforeEach(async () => { - const actual = await vi.importActual('node:fs') - fsMock.writeFileSync.mockReset().mockImplementation(actual.writeFileSync) - fsMock.mkdirSync.mockReset().mockImplementation(actual.mkdirSync) - fsMock.grantDirAcl.mockReset() - root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-legacy-plugin-acl-'))) - setAppEnvironment({ - getPath: () => root, - getAppPath: () => process.cwd(), - getVersion: () => '0.0.0-test', - isPackaged: () => false, - onWillQuit: () => {}, - exit: () => {}, - getAppMetrics: () => [] - }) - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - vi.spyOn(console, 'warn').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() - rmSync(root, { recursive: true, force: true }) -}) - -function installedPlugin(variant: (typeof variants)[number]): { - server: string - tui: string - source: string - tuiSource: string -} { - const plugins = join(root, variant.hooks, 'shared', 'plugins') - const server = join(plugins, variant.file) - const tui = join(plugins, openCodeTuiPluginDirName(variant.file), 'tui.js') - const source = variant.source() - mkdirSync(dirname(tui), { recursive: true }) - writeFileSync(server, '// stale server') - writeOpenCodeTuiPlugin(plugins, variant.file, source) - const tuiSource = readFileSync(tui, 'utf8') - fsMock.writeFileSync.mockClear() - fsMock.mkdirSync.mockClear() - return { server, tui, source, tuiSource } -} - -function tempWritesFor(target: string): string[] { - return fsMock.writeFileSync.mock.calls - .map(([file]) => String(file)) - .filter((file) => dirname(file) === dirname(target) && basename(file).startsWith('.')) -} - -describe.each(variants)('$hooks legacy plugin ACL recovery', (variant) => { - it.each(['EPERM', 'EACCES'])('retries one denied server generation after %s', async (code) => { - const { server, tui, source, tuiSource } = installedPlugin(variant) - const actual = await vi.importActual('node:fs') - const denial = Object.assign(new Error('protected directory DACL'), { code }) - let attempts = 0 - fsMock.writeFileSync.mockImplementation((...args) => { - expect(readFileSync(server, 'utf8')).toBe('// stale server') - expect(readFileSync(tui, 'utf8')).toBe(tuiSource) - actual.writeFileSync(...args) - if (++attempts === 1) { - throw denial - } - }) - - variant.service.refreshLegacySharedPlugin() - - expect(readFileSync(server, 'utf8')).toBe(source) - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(server)) - const generations = tempWritesFor(server) - expect(generations).toHaveLength(2) - expect(new Set(generations).size).toBe(2) - expect(generations.every((path) => !existsSync(path))).toBe(true) - expect(fsMock.grantDirAcl.mock.invocationCallOrder[0]).toBeGreaterThan( - fsMock.writeFileSync.mock.invocationCallOrder[0] - ) - expect(fsMock.grantDirAcl.mock.invocationCallOrder[0]).toBeLessThan( - fsMock.writeFileSync.mock.invocationCallOrder[1] - ) - expect(console.warn).not.toHaveBeenCalled() - }) - - it('recovers a denied mkdir in the shared atomic server writer', async () => { - const { server, source } = installedPlugin(variant) - const actual = await vi.importActual('node:fs') - fsMock.mkdirSync - .mockImplementationOnce(() => { - throw Object.assign(new Error('mkdir denied'), { code: 'EPERM' }) - }) - .mockImplementation(actual.mkdirSync) - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(server)) - expect(fsMock.mkdirSync).toHaveBeenCalledTimes(2) - expect(readFileSync(server, 'utf8')).toBe(source) - }) - - it('grants the existing parent when creation of the TUI directory is denied', async () => { - const { server, tui, source, tuiSource } = installedPlugin(variant) - rmSync(dirname(tui), { recursive: true }) - const actual = await vi.importActual('node:fs') - fsMock.mkdirSync - .mockImplementationOnce(() => { - throw Object.assign(new Error('TUI mkdir denied'), { code: 'EACCES' }) - }) - .mockImplementation(actual.mkdirSync) - fsMock.writeFileSync.mockImplementation((...args) => { - if (dirname(String(args[0])) === dirname(server)) { - expect(readFileSync(tui, 'utf8')).toBe(tuiSource) - } - return actual.writeFileSync(...args) - }) - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(server)) - expect(readFileSync(tui, 'utf8')).toBe(tuiSource) - expect(readFileSync(server, 'utf8')).toBe(source) - }) - - it('recovers a denied TUI write before replacing the server plugin', async () => { - const { server, tui, source, tuiSource } = installedPlugin(variant) - writeFileSync(tui, '// stale TUI') - fsMock.writeFileSync.mockClear() - const actual = await vi.importActual('node:fs') - let denied = false - fsMock.writeFileSync.mockImplementation((...args) => { - if (dirname(String(args[0])) === dirname(tui) && !denied) { - denied = true - throw Object.assign(new Error('TUI write denied'), { code: 'EPERM' }) - } - if (dirname(String(args[0])) === dirname(server)) { - expect(readFileSync(tui, 'utf8')).toBe(tuiSource) - } - return actual.writeFileSync(...args) - }) - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(tui)) - expect(tempWritesFor(tui)).toHaveLength(2) - expect(readFileSync(server, 'utf8')).toBe(source) - }) - - it('keeps the old server when TUI recovery still fails', () => { - const { server, tui } = installedPlugin(variant) - writeFileSync(tui, '// stale TUI') - fsMock.writeFileSync.mockClear() - const denial = Object.assign(new Error('TUI generation denied'), { code: 'EPERM' }) - fsMock.writeFileSync.mockImplementation(() => { - throw denial - }) - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(tui)) - expect(tempWritesFor(tui)).toHaveLength(2) - expect(tempWritesFor(server)).toHaveLength(0) - expect(readFileSync(tui, 'utf8')).toBe('// stale TUI') - expect(readFileSync(server, 'utf8')).toBe('// stale server') - expect(console.warn).toHaveBeenCalledWith(expect.any(String), server, denial) - }) - - it.each(['darwin', 'linux'] as const)('does not grant or retry on %s', (platform) => { - const { server } = installedPlugin(variant) - vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) - const denial = Object.assign(new Error('write denied'), { code: 'EPERM' }) - fsMock.writeFileSync.mockImplementation(() => { - throw denial - }) - - variant.service.refreshLegacySharedPlugin() - - expect(tempWritesFor(server)).toHaveLength(1) - expect(fsMock.grantDirAcl).not.toHaveBeenCalled() - expect(readFileSync(server, 'utf8')).toBe('// stale server') - expect(console.warn).toHaveBeenCalledWith(expect.any(String), server, denial) - }) - - it.each(['EIO', 'ENOSPC', 'EBUSY', 'ENOENT'])('does not retry an unrelated %s error', (code) => { - const { server } = installedPlugin(variant) - fsMock.writeFileSync.mockImplementation(() => { - throw Object.assign(new Error('unrelated failure'), { code }) - }) - - variant.service.refreshLegacySharedPlugin() - - expect(tempWritesFor(server)).toHaveLength(1) - expect(fsMock.grantDirAcl).not.toHaveBeenCalled() - expect(readFileSync(server, 'utf8')).toBe('// stale server') - }) - - it.each(['grant', 'retry'])('keeps the original denial when the %s fails', (failure) => { - const { server } = installedPlugin(variant) - const original = Object.assign(new Error('original denial'), { code: 'EPERM' }) - const later = Object.assign(new Error('later failure'), { code: 'EACCES' }) - fsMock.writeFileSync - .mockImplementationOnce(() => { - throw original - }) - .mockImplementation(() => { - throw later - }) - if (failure === 'grant') { - fsMock.grantDirAcl.mockImplementation(() => { - throw later - }) - } - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(server)) - expect(tempWritesFor(server)).toHaveLength(failure === 'grant' ? 1 : 2) - expect(console.warn).toHaveBeenCalledWith(expect.any(String), server, original) - expect(readFileSync(server, 'utf8')).toBe('// stale server') - expect(readdirSync(dirname(server)).some((name) => name.endsWith('.tmp'))).toBe(false) - }) - - it.skipIf(hostPlatform === 'win32')( - 'repairs the canonical target directory and preserves its link', - async () => { - const { server, source } = installedPlugin(variant) - const target = join(root, 'dotfiles', 'status.js') - mkdirSync(dirname(target), { recursive: true }) - writeFileSync(target, '// stale target') - rmSync(server) - symlinkSync(target, server) - fsMock.writeFileSync.mockClear() - const actual = await vi.importActual('node:fs') - fsMock.writeFileSync - .mockImplementationOnce(() => { - throw Object.assign(new Error('target denied'), { code: 'EPERM' }) - }) - .mockImplementation(actual.writeFileSync) - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).toHaveBeenCalledExactlyOnceWith(dirname(target)) - expect(lstatSync(server).isSymbolicLink()).toBe(true) - expect(readFileSync(target, 'utf8')).toBe(source) - } - ) - - it('leaves current and absent installs alone', () => { - variant.service.refreshLegacySharedPlugin() - expect(existsSync(join(root, variant.hooks))).toBe(false) - const { server, source } = installedPlugin(variant) - writeFileSync(server, source) - fsMock.writeFileSync.mockClear() - fsMock.mkdirSync.mockClear() - - variant.service.refreshLegacySharedPlugin() - - expect(fsMock.grantDirAcl).not.toHaveBeenCalled() - expect(fsMock.writeFileSync).not.toHaveBeenCalled() - expect(fsMock.mkdirSync).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/opencode/opencode-acp-connection.test.ts b/src/main/opencode/opencode-acp-connection.test.ts deleted file mode 100644 index 7f62cca6de7..00000000000 --- a/src/main/opencode/opencode-acp-connection.test.ts +++ /dev/null @@ -1,351 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { PassThrough } from 'node:stream' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child' -import { AcpScriptedAgent, deferred } from '../acp/acp-scripted-agent.test-support' -import { AcpAgentError, AcpAuthRequiredError } from '../acp/acp-errors' -import { AcpTimelineTranslator } from '../acp/acp-timeline-translator' -import { acpLaunchSpecFor } from '../acp/acp-launch-specs' -import { openAcpAdapterRig, sendHello } from '../acp/acp-structured-adapter.test-support' -import { - closeProviderTimelineRigs, - SESSION -} from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import { OPENCODE_ACP_DIALECT } from '../acp/acp-dialects/opencode-dialect' -import { readOpenCodePromptFailure } from '../foreign-sqlite-readers/readers/opencode-prompt-failure' -import type { OpenCodePromptFailureQuery } from '../foreign-sqlite-readers/opencode-prompt-failure-result' -import SyncDatabase from '../sqlite/sync-database' -import { createOpenCodeAcpConnection } from './opencode-acp-connection' - -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } - vi.unstubAllEnvs() - await closeProviderTimelineRigs() -}) - -async function fixture( - native: unknown, - options: { - stale?: boolean - unavailable?: boolean - readGate?: Promise - readStarted?: () => void - acpCode?: number - } = {} -) { - const directory = mkdtempSync(join(tmpdir(), 'orca-opencode-acp-failure-')) - const dataHome = join(directory, 'account-data') - mkdirSync(join(dataHome, 'opencode'), { recursive: true }) - const dbPath = join(dataHome, 'opencode', 'opencode.db') - const db = new SyncDatabase(dbPath) - db.exec(`CREATE TABLE session_message ( - id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, time_created INTEGER, data TEXT - )`) - const agent = new AcpScriptedAgent() - const child = Object.assign(createFakePipedChild(), { - pid: 9_999_999, - stdout: agent.stdout, - stdin: agent.stdin, - stderr: new PassThrough() - }) - agent.on('initialize', (frame) => agent.reply(frame, { protocolVersion: 1 })) - agent.on('session/new', (frame) => agent.reply(frame, { sessionId: 'ses-own' })) - let turn = 0 - agent.on('session/prompt', (frame) => { - turn++ - db.prepare('INSERT OR REPLACE INTO session_message VALUES (?, ?, ?, ?, ?, ?)').run( - `input-${turn}`, - 'ses-own', - 'user', - turn * 10, - Date.now(), - '{}' - ) - db.prepare('INSERT OR REPLACE INTO session_message VALUES (?, ?, ?, ?, ?, ?)').run( - `outcome-${turn}`, - 'ses-own', - 'idle', - turn * 10 + 1, - options.stale ? 1 : Date.now(), - JSON.stringify({ error: native }) - ) - agent.fail( - frame, - options.acpCode ?? -32000, - 'Authentication required: provider authentication required', - { - details: 'provider authentication required' - } - ) - }) - const readFailure = vi.fn(async (query: OpenCodePromptFailureQuery) => { - if (options.unavailable) { - throw new Error('database unavailable') - } - const result = readOpenCodePromptFailure(query) - options.readStarted?.() - await options.readGate - return result - }) - const connection = createOpenCodeAcpConnection( - { - command: 'opencode2', - args: ['acp'], - cwd: directory, - env: { XDG_DATA_HOME: dataHome }, - envToDelete: ['OPENCODE_DB'] - }, - {}, - () => child, - readFailure - ) - cleanups.push(async () => { - child.emit('exit', 0, null) - await connection.close() - db.close() - rmSync(directory, { recursive: true, force: true }) - }) - await connection.start({ cwd: directory, mcpServers: [] }) - return { connection, readFailure, dbPath, agent, child, cwd: directory } -} - -const quota = { type: 'provider.quota', message: 'Free usage limit reached.', status: 429 } - -describe('OpenCode ACP native failure recovery', () => { - it('leaves successful turns off the native failure reader', async () => { - const { connection, readFailure, agent } = await fixture(quota) - agent.on('session/prompt', (frame) => agent.reply(frame, { stopReason: 'end_turn' })) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).resolves.toEqual({ - stopReason: 'end_turn' - }) - expect(readFailure).not.toHaveBeenCalled() - }) - - it('reads the selected account after stripping an inherited database override', async () => { - vi.stubEnv('OPENCODE_DB', join(tmpdir(), 'other-account', 'opencode.db')) - const { connection, readFailure, dbPath } = await fixture(quota) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - message: quota.message - }) - expect(readFailure).toHaveBeenCalledWith(expect.objectContaining({ dbPath })) - }) - - it.each([-32000, -32603])( - 'reports native quota correctly when ACP returns %i', - async (acpCode) => { - const { connection, readFailure, dbPath } = await fixture(quota, { acpCode }) - const error: unknown = await connection - .prompt([{ type: 'text', text: 'hello' }]) - .catch((e) => e) - expect(error).toBeInstanceOf(AcpAgentError) - expect(error).not.toBeInstanceOf(AcpAuthRequiredError) - if (!(error instanceof AcpAgentError)) { - throw error - } - expect(error.message).toBe(quota.message) - expect(error.data).toMatchObject({ errorName: 'provider.quota', status: 429 }) - expect(readFailure).toHaveBeenCalledWith( - expect.objectContaining({ dbPath, sessionId: 'ses-own' }) - ) - const translator = new AcpTimelineTranslator({ - sessionId: 'ses-own', - agentName: 'OpenCode 2', - dialect: OPENCODE_ACP_DIALECT - }) - translator.openPrompt('send', 100) - const rows = translator.promptFailed('send', error, 200) - expect(rows).toContainEqual( - expect.objectContaining({ - type: 'item.update', - body: expect.objectContaining({ - failure: expect.objectContaining({ - kind: 'usageLimitReached', - detail: { text: quota.message, audience: 'person' } - }) - }) - }) - ) - } - ) - - it('journals the recovered failure through the full chat adapter and accepts the next send', async () => { - const spec = acpLaunchSpecFor('opencode2') - if (!spec) { - throw new Error('OpenCode 2 launch specification missing') - } - const { connection, agent, cwd } = await fixture({ ...quota, retryAfterMs: 60_000 }) - const rig = await openAcpAdapterRig({ - spec, - launch: { cwd }, - deps: { connect: () => connection, now: Date.now } - }) - cleanups.push(async () => { - await rig.adapter.closeSession(SESSION) - }) - await rig.acquire() - await sendHello(rig, 'first') - await rig.settle() - expect((await rig.rig.rows()).map((row) => row.body)).toContainEqual( - expect.objectContaining({ - kind: 'status', - tone: 'warning', - failure: expect.objectContaining({ - kind: 'usageLimitReached', - detail: { text: quota.message, audience: 'person' }, - usageLimit: { resetsAt: expect.any(Number) } - }) - }) - ) - expect((await rig.rig.turns())[0]?.outcome).toBe('failure') - agent.on('session/prompt', (frame) => agent.reply(frame, { stopReason: 'end_turn' })) - await sendHello(rig, 'second') - await rig.settle() - expect((await rig.rig.turns()).map((turn) => turn.outcome)).toEqual(['failure', 'success']) - }) - - it.each([ - { type: 'provider.quota', message: 'Insufficient account funds', status: 402 }, - { - type: 'provider.auth', - message: 'Provider authentication required', - status: 403, - response: { - body: JSON.stringify({ error: { type: 'FreeTierError', message: 'Free tier restricted' } }) - } - } - ])('does not turn billing or access refusal into a sign-in failure: $status', async (native) => { - const { connection } = await fixture(native) - const error: unknown = await connection - .prompt([{ type: 'text', text: 'hello' }]) - .catch((e) => e) - expect(error).not.toBeInstanceOf(AcpAuthRequiredError) - if (!(error instanceof AcpAgentError)) { - throw error - } - expect(OPENCODE_ACP_DIALECT.promptFailure?.(error, 100)).toBeUndefined() - }) - - it('keeps the same session usable after a quota failure', async () => { - const { connection, agent } = await fixture(quota) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - message: quota.message - }) - agent.on('session/prompt', (frame) => agent.reply(frame, { stopReason: 'end_turn' })) - await expect(connection.prompt([{ type: 'text', text: 'try another model' }])).resolves.toEqual( - { - stopReason: 'end_turn' - } - ) - expect(connection.closed).toBe(false) - }) - - it('keeps another prompt out until native failure recovery settles', async () => { - const started = deferred() - const gate = deferred() - const { connection, agent } = await fixture(quota, { - readGate: gate.promise, - readStarted: () => started.resolve() - }) - const pending = connection.prompt([{ type: 'text', text: 'first' }]).catch((error) => error) - await started.promise - const overlapping = connection - .prompt([{ type: 'text', text: 'second' }]) - .catch((error) => error) - gate.resolve() - await expect(overlapping).resolves.toMatchObject({ message: 'ACP prompt already in progress' }) - await expect(pending).resolves.toMatchObject({ message: quota.message }) - expect(agent.frames.filter((frame) => frame.method === 'session/prompt')).toHaveLength(1) - }) - - it('preserves newer native failure classifications instead of interpreting their raw body again', async () => { - const { connection } = await fixture({ - type: 'provider.free-limit', - message: 'Connect a provider or switch models.', - status: 429, - response: { - body: JSON.stringify({ error: { type: 'FreeUsageLimitError', message: 'Legacy message' } }) - } - }) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - message: 'Connect a provider or switch models.', - data: { errorName: 'provider.free-limit', status: 429 } - }) - }) - - it('does not consume the same native failure twice when successive prompts share a clock tick', async () => { - const clock = vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) - try { - const { connection, agent } = await fixture(quota) - await expect(connection.prompt([{ type: 'text', text: 'first' }])).rejects.toMatchObject({ - message: quota.message - }) - agent.on('session/prompt', (frame) => agent.fail(frame, -32000, 'Authentication required')) - await expect(connection.prompt([{ type: 'text', text: 'second' }])).rejects.toMatchObject({ - name: 'AcpAuthRequiredError', - message: 'Authentication required' - }) - } finally { - clock.mockRestore() - } - }) - - it('keeps HTTP 401 classified as authentication even with an access error in the body', async () => { - const { connection } = await fixture({ - type: 'provider.auth', - message: 'Invalid API key', - status: 401, - response: { - body: JSON.stringify({ error: { type: 'RegionError', message: 'Region blocked' } }) - } - }) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - name: 'AcpAuthRequiredError', - message: 'Invalid API key' - }) - }) - - it('does not revise a closed connection with a late native read', async () => { - const started = deferred() - const gate = deferred() - const { connection, child } = await fixture(quota, { - readGate: gate.promise, - readStarted: () => started.resolve() - }) - const pending = connection.prompt([{ type: 'text', text: 'hello' }]) - await started.promise - child.emit('exit', 0, null) - gate.resolve() - await expect(pending).rejects.toMatchObject({ - name: 'AcpAuthRequiredError', - message: 'Authentication required: provider authentication required' - }) - }) - - it('keeps genuine authentication failures classified as signed out', async () => { - const { connection } = await fixture({ - type: 'provider.auth', - message: 'Invalid API key', - status: 401 - }) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - name: 'AcpAuthRequiredError', - message: 'Invalid API key' - }) - }) - - it.each([{ stale: true }, { unavailable: true }])( - 'retains the ACP error without fresh native evidence: %j', - async (options) => { - const { connection } = await fixture(quota, options) - await expect(connection.prompt([{ type: 'text', text: 'hello' }])).rejects.toMatchObject({ - name: 'AcpAuthRequiredError', - message: 'Authentication required: provider authentication required' - }) - } - ) -}) diff --git a/src/main/opencode/opencode-model-startup-plan.test.ts b/src/main/opencode/opencode-model-startup-plan.test.ts deleted file mode 100644 index 35c45ada790..00000000000 --- a/src/main/opencode/opencode-model-startup-plan.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { resolveAgentStartupPlanInputs } from '../../shared/agent-launch/startup/agent-startup-plan-inputs' -import { applyManagedDataAccountEnvironment } from '../managed-data-accounts/launch-environment' -import { probeOpenCodeLaunchCapabilities } from './opencode-launch-capabilities' -import { resolveOpenCodeDirectModelExecutable } from './opencode-model-executable' -import { probeOpenCodeLaunchModelContext } from './opencode-launch-model-context' -import { buildExecutionHostAgentStartupPlan } from './opencode-model-startup-plan' -import { - OPENCODE_MODEL_CONFIG_REFUSAL, - OPENCODE_MODEL_TRANSPORT_REFUSAL, - OPENCODE_MODEL_VERSION_REFUSAL -} from '../../shared/agent-launch/choices/agent-launch-model-preferences' - -vi.mock('../managed-data-accounts/launch-environment', () => ({ - applyManagedDataAccountEnvironment: vi.fn() -})) -vi.mock('./opencode-launch-capabilities', () => ({ probeOpenCodeLaunchCapabilities: vi.fn() })) -vi.mock('./opencode-model-executable', () => ({ - resolveOpenCodeDirectModelExecutable: vi.fn() -})) -vi.mock('./opencode-launch-model-context', () => ({ probeOpenCodeLaunchModelContext: vi.fn() })) - -const preferred = 'opencode/fledge-alpha-free' -const original = JSON.stringify({ - default_agent: 'reviewer', - providers: { custom: { apiKey: 'placeholder' } }, - agents: { reviewer: { system: 'Review only', model: 'opencode/big-pickle' } } -}) -function scope() { - return { - inputs: resolveAgentStartupPlanInputs({ - agent: 'opencode', - settings: { - agentCmdOverrides: {}, - agentDefaultEnv: { opencode: { OPENCODE_CONFIG_CONTENT: original } } - }, - platform: process.platform, - isRemote: false, - shell: undefined, - sessionOptions: { model: preferred } - }), - cwd: '/private/project', - prompt: 'Read only', - hostIdentity: 'host' - } -} - -describe('execution-host OpenCode model startup', () => { - beforeEach(() => { - vi.resetAllMocks() - vi.mocked(resolveOpenCodeDirectModelExecutable).mockResolvedValue('/private/opencode') - vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ - version: '2.0.16', - pluginApi: 'v2', - promptMode: 'prefill' - }) - vi.mocked(probeOpenCodeLaunchModelContext).mockResolvedValue({ primaryAgent: 'reviewer' }) - }) - - it('refuses unsupported effort preferences before probing or dropping them', async () => { - const options = scope() - options.inputs.sessionOptions = { model: preferred, effort: 'high' } - await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ - code: 'capability_unsupported' - }) - expect(probeOpenCodeLaunchModelContext).not.toHaveBeenCalled() - expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() - }) - - it.each(['2.0.16', '2.0.19', '2.1.4'])( - 'launches v2 %s in isolation and keeps one-time model preferences out of resume state', - async (version) => { - vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ - version, - pluginApi: 'v2', - promptMode: 'prefill' - }) - const options = scope() - const plan = await buildExecutionHostAgentStartupPlan(options) - expect(plan?.launchCommand).toContain('--standalone') - expect(plan?.launchCommand).not.toContain('--model') - expect(plan?.sessionOptions).toEqual({ model: preferred }) - expect(JSON.parse(plan?.env?.OPENCODE_CONFIG_CONTENT ?? 'null')).toEqual({ - default_agent: 'reviewer', - model: preferred, - providers: { custom: { apiKey: 'placeholder' } }, - agents: { reviewer: { system: 'Review only', model: preferred } } - }) - expect(plan?.launchConfig).toEqual({ - agentCommand: 'opencode', - agentArgs: '', - agentEnv: { OPENCODE_CONFIG_CONTENT: original } - }) - expect(options.inputs.agentEnv.OPENCODE_CONFIG_CONTENT).toBe(original) - } - ) - - it('uses the selected account environment in its single primary-agent probe', async () => { - vi.mocked(applyManagedDataAccountEnvironment).mockImplementation((env) => { - env.XDG_DATA_HOME = '/selected/data' - env.OPENCODE_DB = 'opencode.db' - }) - await buildExecutionHostAgentStartupPlan(scope()) - expect(probeOpenCodeLaunchModelContext).toHaveBeenCalledOnce() - for (const call of vi.mocked(probeOpenCodeLaunchModelContext).mock.calls) { - expect(call[0].env).toMatchObject({ - XDG_DATA_HOME: '/selected/data', - OPENCODE_DB: 'opencode.db' - }) - } - }) - - it.each(['1.18.30', '1.18.35', '1.19.4'])( - 'launches legacy %s with the requested model flag and no catalog probe', - async (version) => { - vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ - version, - pluginApi: 'v1', - promptMode: 'submit' - }) - expect((await buildExecutionHostAgentStartupPlan(scope()))?.launchCommand).toContain( - '--model' - ) - expect(probeOpenCodeLaunchModelContext).not.toHaveBeenCalled() - } - ) - - it('preserves ordinary launches without any private server probe', async () => { - const options = scope() - options.inputs.sessionOptions = undefined - expect((await buildExecutionHostAgentStartupPlan(options))?.launchCommand).not.toContain( - '--standalone' - ) - expect(probeOpenCodeLaunchCapabilities).not.toHaveBeenCalled() - }) - - it.each(['--agent build', '--continue', '--server http://localhost'])( - 'refuses current-v2 manual launch arguments %s', - async (agentArgs) => { - const options = scope() - options.inputs.agentArgs = agentArgs - await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ - code: 'capability_unsupported', - message: OPENCODE_MODEL_TRANSPORT_REFUSAL - }) - expect(probeOpenCodeLaunchModelContext).not.toHaveBeenCalled() - } - ) - - it('keeps the v2 overlay when primary metadata is unavailable', async () => { - vi.mocked(probeOpenCodeLaunchModelContext).mockResolvedValue(null) - const plan = await buildExecutionHostAgentStartupPlan(scope()) - expect(plan?.launchCommand).not.toContain('--model') - expect(JSON.parse(plan?.env?.OPENCODE_CONFIG_CONTENT ?? 'null')).toEqual({ - ...JSON.parse(original), - model: preferred - }) - }) - - it('refuses remote and WSL execution before touching the local binary', async () => { - const options = scope() - options.inputs.isRemote = true - await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ - code: 'capability_unsupported' - }) - options.inputs.isRemote = false - await expect( - buildExecutionHostAgentStartupPlan({ ...options, isWsl: true }) - ).rejects.toMatchObject({ code: 'capability_unsupported' }) - expect(resolveOpenCodeDirectModelExecutable).not.toHaveBeenCalled() - }) - - it.each([ - '1.18.29', - '1.20.0-beta.1', - '2.0.12', - '2.0.13', - '2.0.14', - '2.0.15', - '2.0.17', - '2.0.18', - '2.1.5-beta.1', - '3.0.0', - null - ])('refuses unverified version %s before model probing', async (version) => { - vi.mocked(probeOpenCodeLaunchCapabilities).mockResolvedValue({ - version, - pluginApi: 'v2', - promptMode: 'prefill' - }) - await expect(buildExecutionHostAgentStartupPlan(scope())).rejects.toMatchObject({ - code: 'capability_unsupported', - message: OPENCODE_MODEL_VERSION_REFUSAL - }) - expect(probeOpenCodeLaunchModelContext).not.toHaveBeenCalled() - expect(resolveOpenCodeDirectModelExecutable).not.toHaveBeenCalled() - }) - - it('keeps invalid inline configuration guidance separate from a version refusal', async () => { - const options = scope() - options.inputs.agentEnv.OPENCODE_CONFIG_CONTENT = '{' - await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ - code: 'capability_unsupported', - message: OPENCODE_MODEL_CONFIG_REFUSAL - }) - }) - - it('resolves the default bare launch command through the execution host', async () => { - await buildExecutionHostAgentStartupPlan(scope()) - expect(resolveOpenCodeDirectModelExecutable).toHaveBeenCalledWith( - expect.objectContaining({ command: 'opencode' }) - ) - }) - - it.each(['blank-model', 'effort-only'])( - 'refuses invalid preferences before probing', - async (scenario) => { - const options = scope() - options.inputs.sessionOptions = - scenario === 'blank-model' ? { model: '' } : { effort: 'high' } - await expect(buildExecutionHostAgentStartupPlan(options)).rejects.toMatchObject({ - code: 'capability_unsupported' - }) - expect(resolveOpenCodeDirectModelExecutable).not.toHaveBeenCalled() - } - ) -}) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.subagent-reveal.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.subagent-reveal.test.tsx deleted file mode 100644 index 24bb776f21f..00000000000 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.subagent-reveal.test.tsx +++ /dev/null @@ -1,515 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { act, cleanup, fireEvent, screen, waitFor } from '@testing-library/react' -import { createRef, useCallback, useState } from 'react' -import { render } from './native-chat-tooltip-test-harness' - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('./NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) - -import type { - AgentJournalItemBody, - AgentJournalProducerLinkage, - AgentJournalRenderItem -} from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type { StructuredAgentSubagentRoster } from '../../../../shared/agent-session/view/structured-agent-session-subagent-roster' -import type { NativeChatSubagentEntry } from '../../../../shared/native-chat/native-chat-types' -import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection' -import { NativeChatMessageList } from './NativeChatMessageList' -import type { NativeChatOlderPageResult } from './native-chat-pagination' -import { - deliverResizes, - layout, - session, - stubLayout, - stubResizeObserver -} from './native-chat-windowing-test-harness' -import { transcriptRowOffset } from './native-chat-window-test-layout' -import type { NativeChatMessageListHandle } from './use-native-chat-reveal-latest' - -function journalItem( - itemId: string, - body: AgentJournalItemBody, - sequence: number, - linkage: AgentJournalProducerLinkage = {} -): AgentJournalRenderItem { - return { itemId, body, sequence, observedAt: sequence * 1000, revision: 1, ...linkage } -} - -const say = ( - itemId: string, - role: 'user' | 'assistant', - text: string, - sequence: number, - agentId?: string -): AgentJournalRenderItem => - journalItem( - itemId, - { kind: 'message', role, blocks: [{ type: 'text', text }] }, - sequence, - agentId === undefined ? {} : { agentId, producerKind: 'agent' } - ) - -const spawn = ( - itemId: string, - agents: NativeChatSubagentEntry[], - sequence: number, - agentId?: string -): AgentJournalRenderItem => - journalItem( - itemId, - { - kind: 'message', - role: 'system', - blocks: [{ type: 'subagent-group', groupId: `group-${itemId}`, agents }] - }, - sequence, - agentId === undefined ? {} : { agentId, producerKind: 'agent' } - ) - -const agent = (id: string, label: string): NativeChatSubagentEntry => ({ - id, - label, - state: 'working' -}) - -function rosterOf(item: AgentJournalRenderItem): StructuredAgentSubagentRoster { - const block = item.body.kind === 'message' ? item.body.blocks[0] : undefined - // A legacy group names every agent; a current host writes one roster item per agent. - const agents = - block?.type === 'subagent-group' ? block.agents : block?.type === 'subagent' ? [block] : [] - return new Map( - agents.map((entry) => [ - entry.id, - { - entry, - rosterItemId: item.itemId, - rosterPosition: { sequence: item.sequence, index: 0 }, - rosterRevision: 1 - } - ]) - ) -} - -/** Pages older items in on demand; the host's roster names every spawn, loaded or not. */ -function Transcript({ - items, - initiallyLoaded = items.length, - roster, - loadEarlier: onLoadEarlier, - handle -}: { - items: AgentJournalRenderItem[] - initiallyLoaded?: number - roster?: StructuredAgentSubagentRoster - /** Called per page; a returned promise holds the page in flight until it settles. */ - loadEarlier?: () => void | Promise - handle: React.Ref -}): React.JSX.Element { - const [loaded, setLoaded] = useState(initiallyLoaded) - const loadEarlier = useCallback(async (): Promise => { - await onLoadEarlier?.() - setLoaded((current) => Math.min(items.length, current + 2)) - return 'applied' - }, [items.length, onLoadEarlier]) - const shown = items.slice(Math.max(0, items.length - loaded)) - return ( - - ) -} - -async function reveal( - handle: React.RefObject, - agentId: string -): Promise { - await act(async () => { - handle.current?.revealSubagent(agentId) - await Promise.resolve() - }) -} - -describe('revealing a subagent named by the agents strip', () => { - let restoreLayout = (): void => {} - beforeEach(() => { - restoreLayout = stubLayout() - }) - afterEach(() => { - cleanup() - restoreLayout() - vi.restoreAllMocks() - }) - - it("opens a closed roster and the child's section, past a last row that draws nothing", async () => { - const items = [ - say('ask', 'user', 'Review it', 1), - spawn('spawn', [agent('task-a', 'lane a'), agent('task-b', 'lane b')], 2), - say('a-said', 'assistant', 'Read lane a.', 3, 'task-a'), - say('b-said', 'assistant', 'Read lane b.', 4, 'task-b'), - journalItem('b-stub', { kind: 'message', role: 'assistant', blocks: [] }, 5, { - agentId: 'task-b', - producerKind: 'agent' - }), - say('answer', 'assistant', 'Delegated.', 6) - ] - const handle = createRef() - render() - expect(screen.queryByText('Read lane b.')).toBeNull() - - await reveal(handle, 'task-b') - - await waitFor(() => expect(screen.getByText('Read lane b.')).toBeInTheDocument()) - expect(screen.queryByText('Read lane a.')).toBeNull() - expect(screen.getByRole('button', { name: /lane b/, expanded: true })).toBeVisible() - }) - - it('opens the ancestors of a nested child', async () => { - const items = [ - say('ask', 'user', 'Review it', 1), - spawn('spawn', [agent('task-a', 'lane a')], 2), - say('a-said', 'assistant', 'Starting a helper.', 3, 'task-a'), - spawn('a-spawn', [agent('task-n', 'helper')], 4, 'task-a'), - journalItem( - 'n-said', - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'Helper found it.' }] - }, - 5, - { agentId: 'task-n', parentAgentId: 'task-a', producerKind: 'agent' } - ), - say('answer', 'assistant', 'Delegated.', 6) - ] - const handle = createRef() - render() - - await reveal(handle, 'task-n') - - await waitFor(() => expect(screen.getByText('Helper found it.')).toBeInTheDocument()) - expect(screen.getByText('Starting a helper.')).toBeInTheDocument() - }) - - it('opens a roster whose child has no activity yet and shows its entry', async () => { - const roster = spawn('spawn', [agent('grok-1', 'search the docs')], 2) - const items = [ - say('ask', 'user', 'Look it up', 1), - roster, - say('answer', 'assistant', 'Started.', 3) - ] - const handle = createRef() - render() - expect( - screen.getByRole('button', { name: /Kicked off 1 subagent/, expanded: false }) - ).toBeVisible() - expect(screen.queryByText('search the docs')).toBeNull() - - await reveal(handle, 'grok-1') - - await waitFor(() => expect(screen.getByText('search the docs')).toBeInTheDocument()) - expect( - screen.getByRole('button', { name: /Kicked off 1 subagent/, expanded: true }) - ).toBeVisible() - }) - - it('pages older history until the spawn loads, and a reader scroll abandons the paging', async () => { - const roster = spawn('spawn', [agent('grok-1', 'search the docs')], 2) - const items = [ - say('ask', 'user', 'Look it up', 1), - roster, - ...Array.from({ length: 6 }, (_, index) => - say(`later-${index}`, 'assistant', `Later ${index}.`, 3 + index) - ) - ] - const loads = vi.fn() - const handle = createRef() - const { unmount } = render( - - ) - - await reveal(handle, 'grok-1') - - await waitFor(() => expect(screen.getByText('search the docs')).toBeInTheDocument()) - expect(loads).toHaveBeenCalledTimes(3) - unmount() - - let releasePage = (): void => {} - const abandoned = vi.fn( - () => - new Promise((resolve) => { - releasePage = resolve - }) - ) - render( - - ) - await reveal(handle, 'grok-1') - await waitFor(() => expect(abandoned).toHaveBeenCalledTimes(1)) - fireEvent.wheel(screen.getByLabelText('Conversation'), { deltaY: -40 }) - await act(async () => { - releasePage() - await Promise.resolve() - }) - - expect(abandoned).toHaveBeenCalledTimes(1) - expect(screen.queryByText('search the docs')).toBeNull() - }) - - it("finds a later sibling's entry in the row its roster folds into, without paging", async () => { - const sibling = (itemId: string, id: string, label: string, sequence: number) => - journalItem( - itemId, - { - kind: 'message', - role: 'system', - blocks: [{ type: 'subagent', id, label, state: 'working', groupId: 'turn-1' }] - }, - sequence - ) - const first = sibling('spawn-1', 'grok-1', 'search the docs', 3) - const second = sibling('spawn-2', 'grok-2', 'read the tests', 4) - const items = [ - say('older', 'assistant', 'Earlier work.', 1), - say('ask', 'user', 'Look it up', 2), - first, - second, - say('answer', 'assistant', 'Started both.', 5) - ] - const loads = vi.fn() - const handle = createRef() - render( - - ) - expect(screen.queryByText('read the tests')).toBeNull() - - await reveal(handle, 'grok-2') - - await waitFor(() => expect(screen.getByText('read the tests')).toBeInTheDocument()) - expect(loads).not.toHaveBeenCalled() - }) - - it('does not page for a child spawned before the latest /clear', async () => { - const roster = spawn('spawn', [agent('task-1', 'old work')], 2) - const items = [ - say('ask', 'user', 'Start it', 1), - roster, - journalItem( - 'clear', - { - kind: 'status', - text: 'Context cleared', - presentation: 'context-cleared', - contextClear: { operationId: 'clear-4', afterFence: 1, clearedAt: 4 } - }, - 4 - ), - say('after-1', 'user', 'New topic', 5), - say('after-2', 'assistant', 'Sure.', 6) - ] - const loads = vi.fn() - const handle = createRef() - render( - - ) - - await reveal(handle, 'task-1') - - expect(loads).not.toHaveBeenCalled() - }) -}) - -describe('where a strip reveal lands', () => { - let restore: (() => void)[] = [] - beforeEach(() => { - vi.useFakeTimers() - restore = [stubLayout({ scrollGeometry: true, offsetChain: true }), stubResizeObserver()] - layout.aboveTranscriptPx = 0 - }) - afterEach(() => { - cleanup() - for (const undo of restore.toReversed()) { - undo() - } - vi.useRealTimers() - vi.restoreAllMocks() - }) - - function scroller(): HTMLElement { - const element = document.querySelector('[data-native-chat-scroll]') - if (!element) { - throw new Error('no transcript scroll root') - } - return element - } - - /** Deliver resizes and scroll events until the virtualizer stops moving, as painted frames would. */ - function paint(): void { - const element = scroller() - let last = -1 - for (let pass = 0; pass < 12; pass += 1) { - act(() => { - deliverResizes() - vi.advanceTimersByTime(16) - }) - if (element.scrollTop === last && pass >= 2) { - return - } - last = element.scrollTop - fireEvent.scroll(element) - } - } - - it("brings the end of a child's newest drawn row to the bottom of the view, past an open sibling", async () => { - const items = [ - // Earlier history, so the child sits far enough down that its end can reach the view's bottom. - ...Array.from({ length: 40 }, (_, index) => - say(`earlier-${index}`, 'assistant', `Earlier ${index}.`, index - 40) - ), - say('ask', 'user', 'Review it', 1), - spawn('spawn', [agent('task-a', 'lane a'), agent('task-b', 'lane b')], 2), - ...Array.from({ length: 6 }, (_, index) => - say(`a-${index}`, 'assistant', `Lane a step ${index}.`, 3 + index, 'task-a') - ), - say('b-first', 'assistant', 'Opening lane b.', 8.5, 'task-b'), - say('b-said', 'assistant', 'Read lane b.', 9, 'task-b'), - journalItem('b-stub', { kind: 'message', role: 'assistant', blocks: [] }, 10, { - agentId: 'task-b', - producerKind: 'agent' - }), - ...Array.from({ length: 80 }, (_, index) => - say(`later-${index}`, 'assistant', `Later ${index}.`, 11 + index) - ) - ] - const handle = createRef() - render() - paint() - await reveal(handle, 'task-a') - paint() - - await reveal(handle, 'task-b') - paint() - - const row = screen.getByText('Read lane b.').closest('[data-index]') - expect(row).not.toBeNull() - const viewBottom = scroller().scrollTop + scroller().clientHeight - const rowBottom = transcriptRowOffset(row!) + row!.offsetHeight - expect(Math.abs(rowBottom - viewBottom)).toBeLessThanOrEqual(1) - expect(screen.getByText('Lane a step 5.')).toBeInTheDocument() - - // A row above it measures taller only after the jump settled (late markdown, fonts): the end stays put. - const above = screen.getByText('Opening lane b.').closest('[data-index]')! - const heights: number[] = [] - heights[Number(above.dataset.index)] = above.offsetHeight + 120 - layout.measuredRowHeights = heights - paint() - const settledBottom = scroller().scrollTop + scroller().clientHeight - const settledRowBottom = transcriptRowOffset(row!) + row!.offsetHeight - expect(Math.abs(settledRowBottom - settledBottom)).toBeLessThanOrEqual(1) - - // Once the reader acts on the content (Enter on a disclosure above), the view is theirs: nothing moves it. - fireEvent.keyDown(screen.getByRole('button', { name: /lane a/, expanded: true }), { - key: 'Enter' - }) - const readerTop = scroller().scrollTop - heights[Number(above.dataset.index)] = above.offsetHeight + 200 - layout.measuredRowHeights = [...heights] - paint() - expect(scroller().scrollTop).toBe(readerTop) - layout.measuredRowHeights = [] - }) - - it('lets go of a revealed row once it is gone, so rows that grow later do not move the view', async () => { - const parent = [ - ...Array.from({ length: 40 }, (_, index) => - say(`earlier-${index}`, 'assistant', `Earlier ${index}.`, index - 40) - ), - say('ask', 'user', 'Review it', 1), - spawn('spawn', [agent('task-b', 'lane b')], 2) - ] - const child = [ - say('b-first', 'assistant', 'Opening lane b.', 3, 'task-b'), - say('b-said', 'assistant', 'Read lane b.', 4, 'task-b') - ] - const later = Array.from({ length: 80 }, (_, index) => - say(`later-${index}`, 'assistant', `Later ${index}.`, 5 + index) - ) - const handle = createRef() - const { rerender } = render( - - ) - paint() - await reveal(handle, 'task-b') - paint() - expect(screen.getByText('Read lane b.')).toBeInTheDocument() - - // The child's rows leave the transcript (a rewind of its output, say); the hold must not pass to whatever row now has its index. - rerender() - paint() - const restingTop = scroller().scrollTop - // The last mounted parent row, whose end sits at or below the viewport's bottom. - const grown = Array.from(scroller().querySelectorAll('[data-index]')).findLast( - (row) => row.textContent?.includes('Later') - )! - const heights: number[] = [] - heights[Number(grown.dataset.index)] = grown.offsetHeight + 200 - layout.measuredRowHeights = heights - paint() - expect(scroller().scrollTop).toBe(restingTop) - layout.measuredRowHeights = [] - }) -}) diff --git a/src/renderer/src/components/native-chat/use-native-chat-history-jump.test.ts b/src/renderer/src/components/native-chat/use-native-chat-history-jump.test.ts deleted file mode 100644 index 11274d4b2dd..00000000000 --- a/src/renderer/src/components/native-chat/use-native-chat-history-jump.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook, waitFor } from '@testing-library/react' -import { useMemo, useSyncExternalStore } from 'react' -import { describe, expect, it, vi } from 'vitest' -import type { NativeChatRailItem } from './native-chat-message-rail-items' -import type { NativeChatOlderPageResult } from './native-chat-pagination' -import { - nativeChatRailJumpStep, - useNativeChatHistoryJump, - type NativeChatHistoryJumpTarget -} from './use-native-chat-history-jump' - -type LaneSnapshot = { loaded: number; messages: readonly string[]; streamed: number } - -/** Model structured paging: commit before resolving and share pending-page results with concurrent callers. */ -function createLane({ - total, - pageSize, - initiallyLoaded, - ghost, - pageResult = 'applied' -}: { - total: number - pageSize: number - initiallyLoaded: number - /** Unrenderable outline entry disappears once the window covers its index. */ - ghost?: { id: string; at: number } - pageResult?: NativeChatOlderPageResult -}) { - const ids = Array.from({ length: total }, (_, index) => `m${index}`) - let snapshot: LaneSnapshot = { - loaded: initiallyLoaded, - messages: ids.slice(total - initiallyLoaded), - streamed: 0 - } - const listeners = new Set<() => void>() - const emit = (): void => listeners.forEach((listener) => listener()) - const pageGate: { release: (() => void) | null } = { release: null } - let holdPages = false - let inFlight: Promise | null = null - const reads = { count: 0 } - const readPage = async (): Promise => { - reads.count += 1 - if (holdPages) { - await new Promise((resolve) => { - pageGate.release = resolve - }) - } - await Promise.resolve() - if (pageResult !== 'applied') { - return pageResult - } - const loaded = Math.min(total, snapshot.loaded + pageSize) - snapshot = { ...snapshot, loaded, messages: ids.slice(total - loaded) } - emit() - return 'applied' - } - const loadEarlier = vi.fn((): Promise => { - if (inFlight) { - return inFlight - } - if (snapshot.loaded >= total) { - return Promise.resolve('exhausted') - } - const page = readPage().finally(() => { - inFlight = null - }) - inFlight = page - return page - }) - const lane = { - loadEarlier, - reads, - holdPages: () => { - holdPages = true - }, - releasePage: () => pageGate.release?.(), - stream: () => { - snapshot = { ...snapshot, streamed: snapshot.streamed + 1 } - emit() - }, - subscribe: (listener: () => void) => { - listeners.add(listener) - return () => listeners.delete(listener) - }, - getSnapshot: () => snapshot - } - const useLaneRailJump = ( - jumpToLoaded: (item: NativeChatRailItem) => void, - sessionKey = 'session-1', - isVisible = true - ) => { - const current = useSyncExternalStore(lane.subscribe, lane.getSnapshot) - const items = useMemo(() => { - const firstLoaded = total - current.loaded - const unloaded = ids.slice(0, firstLoaded) - const outline = ghost && ghost.at < firstLoaded ? [ghost.id, ...unloaded] : unloaded - return [ - ...outline.map((id) => ({ id, slotIndex: null, text: id, hasImages: false })), - ...current.messages.map((id, slotIndex) => ({ id, slotIndex, text: id, hasImages: false })) - ] - }, [current]) - return useNativeChatHistoryJump({ - step: (target) => - target.kind === 'rail' ? nativeChatRailJumpStep(items, target.id, jumpToLoaded) : 'stop', - sessionKey, - isVisible, - loadEarlier: lane.loadEarlier - }) - } - return { lane, useLaneRailJump } -} - -function outlineItem(id: string): NativeChatHistoryJumpTarget { - return { kind: 'rail', id } -} - -async function releasePage(lane: { releasePage: () => void }): Promise { - await act(async () => { - lane.releasePage() - await Promise.resolve() - }) -} - -describe('rail jump through unloaded history', () => { - it("lets a pick made during another pick's page win, sharing that page", async () => { - const { lane, useLaneRailJump } = createLane({ total: 40, pageSize: 10, initiallyLoaded: 10 }) - lane.holdPages() - const jumpToLoaded = vi.fn() - const { result } = renderHook(() => useLaneRailJump(jumpToLoaded)) - - act(() => result.current.start(outlineItem('m25'))) - await waitFor(() => expect(lane.reads.count).toBe(1)) - act(() => result.current.start(outlineItem('m2'))) - expect(result.current.pending).toEqual(outlineItem('m2')) - for (let page = 0; page < 3; page += 1) { - await releasePage(lane) - } - - await waitFor(() => expect(jumpToLoaded).toHaveBeenCalledTimes(1)) - expect(jumpToLoaded).toHaveBeenCalledWith(expect.objectContaining({ id: 'm2' })) - expect(lane.reads.count).toBe(3) - }) - - it("aims at a pick made before the previous one's commit settled", async () => { - const { lane, useLaneRailJump } = createLane({ total: 40, pageSize: 10, initiallyLoaded: 10 }) - const jumpToLoaded = vi.fn() - const { result } = renderHook(() => useLaneRailJump(jumpToLoaded)) - - act(() => { - result.current.start(outlineItem('m25')) - result.current.start(outlineItem('m2')) - }) - - await waitFor(() => expect(result.current.pending).toBeNull()) - expect(jumpToLoaded).toHaveBeenCalledTimes(1) - expect(jumpToLoaded).toHaveBeenCalledWith(expect.objectContaining({ id: 'm2' })) - expect(lane.reads.count).toBe(3) - }) - - it('abandons the jump when the session changes mid-page', async () => { - const { lane, useLaneRailJump } = createLane({ total: 40, pageSize: 10, initiallyLoaded: 10 }) - lane.holdPages() - const jumpToLoaded = vi.fn() - const { result, rerender } = renderHook( - ({ sessionKey }: { sessionKey: string }) => useLaneRailJump(jumpToLoaded, sessionKey), - { initialProps: { sessionKey: 'session-1' } } - ) - - act(() => result.current.start(outlineItem('m25'))) - await waitFor(() => expect(lane.reads.count).toBe(1)) - rerender({ sessionKey: 'session-2' }) - expect(result.current.pending).toBeNull() - await releasePage(lane) - - expect(lane.reads.count).toBe(1) - expect(jumpToLoaded).not.toHaveBeenCalled() - }) -})