From 2e3af9aa03c21d9005344eae27d9d2657c32fcac Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:22:46 -0700 Subject: [PATCH 1/5] fix(wsl): startup CLI reconciliation never inspects distros Orca has no record of (#36683) At every startup, managed WSL CLI registration reconciliation ran a guest command in every running distro it hadn't inspected recently, including the user's own unrelated distros. That's EDR-noisy and touches environments Orca never set up. It now repairs distros carrying Orca's own registration record, and inspects only distros Orca deployed a WSL host into. --- ...sl-cli-registration-reconciliation.test.ts | 34 ++++++++++++++- .../wsl-cli-registration-reconciliation.ts | 22 +++++++++- .../cli/wsl-cli-registration-registry.test.ts | 42 +++++++++++++++---- src/main/cli/wsl-cli-registration-registry.ts | 9 ++++ 4 files changed, 97 insertions(+), 10 deletions(-) diff --git a/src/main/cli/wsl-cli-registration-reconciliation.test.ts b/src/main/cli/wsl-cli-registration-reconciliation.test.ts index 5067595316c..b3381514aea 100644 --- a/src/main/cli/wsl-cli-registration-reconciliation.test.ts +++ b/src/main/cli/wsl-cli-registration-reconciliation.test.ts @@ -24,6 +24,7 @@ describe('reconcileManagedWslCliRegistrations', () => { isPackaged: true, userDataPath: '/user-data', listDistros: async () => ['Ubuntu', 'Debian', 'Fedora'], + listOrcaHostDistros: () => ['Debian'], listRunningDistros: async () => ['Ubuntu', 'Debian', 'Fedora'], isDistroRunning: async (distro: string) => ['Ubuntu', 'Debian', 'Fedora'].includes(distro), registry, @@ -37,7 +38,8 @@ describe('reconcileManagedWslCliRegistrations', () => { expect(registry.getCandidates).toHaveBeenCalledWith(['Ubuntu', 'Debian', 'Fedora'], { currentTarget: null, - appVersion: '' + appVersion: '', + inspectableDistros: ['Debian'] }) expect(registry.recordObservations).toHaveBeenCalledTimes(2) expect(registry.recordObservations).toHaveBeenCalledWith([ @@ -195,6 +197,7 @@ describe('reconcileManagedWslCliRegistrations', () => { isPackaged: true, userDataPath: '/user-data', listDistros: async () => ['Ubuntu', 'Debian'], + listOrcaHostDistros: () => [], listRunningDistros: async () => running, isDistroRunning: async (distro: string) => running.includes(distro), deferUntilRunning: (distro: string, _key: string, task: () => unknown) => { @@ -221,7 +224,8 @@ describe('reconcileManagedWslCliRegistrations', () => { expect(repaired).toEqual(['Ubuntu', 'Debian']) expect(registry.getCandidates).toHaveBeenLastCalledWith(['Debian'], { currentTarget: null, - appVersion: '' + appVersion: '', + inspectableDistros: [] }) }) @@ -255,4 +259,30 @@ describe('reconcileManagedWslCliRegistrations', () => { expect(deferred).toEqual(['Debian']) expect(results).toContainEqual({ distro: 'Debian', outcome: 'deferred' }) }) + + it("asks the registry to inspect only distros Orca deployed a host into, read from the user's store", async () => { + const registry = { + getCandidates: vi.fn(async () => []), + recordObservations: vi.fn(async () => undefined) + } + const createInstaller = vi.fn() + + await reconcileManagedWslCliRegistrations({ + platform: 'win32', + isPackaged: true, + userDataPath: '/user-data-without-hosts', + listDistros: async () => ['Ubuntu', 'MyDevBox'], + getHostLauncherTarget: async () => null, + registry, + createInstaller + }) + + // No deployment store exists for this profile: no host, so no distro is inspectable. + expect(registry.getCandidates).toHaveBeenCalledWith(['Ubuntu', 'MyDevBox'], { + currentTarget: null, + appVersion: '', + inspectableDistros: [] + }) + expect(createInstaller).not.toHaveBeenCalled() + }) }) diff --git a/src/main/cli/wsl-cli-registration-reconciliation.ts b/src/main/cli/wsl-cli-registration-reconciliation.ts index 1fa6692c7e4..b7edc00e891 100644 --- a/src/main/cli/wsl-cli-registration-reconciliation.ts +++ b/src/main/cli/wsl-cli-registration-reconciliation.ts @@ -13,6 +13,7 @@ import { } from './wsl-cli-registration-registry' import { WslCliInstaller } from './wsl-cli-installer' import { runSerializedWslCliRegistrationOperation } from './wsl-cli-registration-operation' +import { readWslHostDeployments } from '../../shared/wsl-host-deployment-store' // Why: each repair spawns a guest shell; a small cap bounds the startup fan-out. const MAX_CONCURRENT_DISTRO_REPAIRS = 2 @@ -29,6 +30,7 @@ type ManagedWslCliInstaller = { type WslCliRegistrationCandidateContext = { currentTarget?: string | null appVersion?: string | null + inspectableDistros?: readonly string[] } type WslCliRegistrationRegistry = { @@ -48,6 +50,8 @@ type WslCliRegistrationReconciliationOptions = { createInstaller?: (distro: string) => ManagedWslCliInstaller getHostLauncherTarget?: () => Promise registry?: WslCliRegistrationRegistry + /** Distros Orca deployed a WSL host into; only those may be inspected for an unrecorded registration. */ + listOrcaHostDistros?: () => string[] listRunningDistros?: () => Promise /** Settled read taken right before each repair spawns. */ isDistroRunning?: (distro: string) => Promise @@ -112,7 +116,14 @@ export async function reconcileManagedWslCliRegistrations( ? await getHostLauncherTarget().catch(() => null) : null const appVersion = options.appVersion ?? '' - const candidates = await registry.getCandidates(availableDistros, { currentTarget, appVersion }) + const inspectableDistros = ( + options.listOrcaHostDistros ?? (() => orcaHostDistros(options.userDataPath)) + )() + const candidates = await registry.getCandidates(availableDistros, { + currentTarget, + appVersion, + inspectableDistros + }) if (candidates.length === 0) { return [] } @@ -206,6 +217,15 @@ export async function reconcileManagedWslCliRegistrations( return [...results, ...deferred] } +function orcaHostDistros(userDataPath: string): string[] { + try { + return readWslHostDeployments(userDataPath).deployments.map((record) => record.distro) + } catch { + // An unreadable store names no host; registered distros are still reconciled. + return [] + } +} + export function logWslCliReconciliationResults( results: readonly WslCliRegistrationReconciliationResult[] ): void { diff --git a/src/main/cli/wsl-cli-registration-registry.test.ts b/src/main/cli/wsl-cli-registration-registry.test.ts index 4eec3a27a08..7b72d9ce2ff 100644 --- a/src/main/cli/wsl-cli-registration-registry.test.ts +++ b/src/main/cli/wsl-cli-registration-registry.test.ts @@ -76,13 +76,15 @@ describe('WSL CLI registration registry', () => { await expect( getWslCliRegistrationCandidates(userDataPath, ['Fedora'], { now: 2_000, - negativeInspectionTtlMs: 10_000 + negativeInspectionTtlMs: 10_000, + inspectableDistros: ['Fedora'] }) ).resolves.toEqual([]) await expect( getWslCliRegistrationCandidates(userDataPath, ['Fedora'], { now: 12_000, - negativeInspectionTtlMs: 10_000 + negativeInspectionTtlMs: 10_000, + inspectableDistros: ['Fedora'] }) ).resolves.toEqual(['Fedora']) }) @@ -99,7 +101,9 @@ describe('WSL CLI registration registry', () => { // Reads join the write queue, so startup cannot observe a half-updated registry. await expect( - getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian']) + getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], { + inspectableDistros: ['Ubuntu', 'Debian'] + }) ).resolves.toEqual(['Ubuntu', 'Debian']) await updates const state = JSON.parse( @@ -113,7 +117,9 @@ describe('WSL CLI registration registry', () => { await writeFile(join(userDataPath, 'wsl-cli-registrations.json'), '{broken', 'utf8') await expect( - getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian']) + getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], { + inspectableDistros: ['Ubuntu', 'Debian'] + }) ).resolves.toEqual(['Ubuntu', 'Debian']) }) @@ -159,13 +165,15 @@ describe('WSL CLI registration registry', () => { await expect( getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'], { now: 1_001, - negativeInspectionTtlMs: 10_000 + negativeInspectionTtlMs: 10_000, + inspectableDistros: ['Ubuntu'] }) ).resolves.toEqual([]) await expect( getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'], { now: 11_001, - negativeInspectionTtlMs: 10_000 + negativeInspectionTtlMs: 10_000, + inspectableDistros: ['Ubuntu'] }) ).resolves.toEqual(['Ubuntu']) }) @@ -184,7 +192,8 @@ describe('WSL CLI registration registry', () => { await expect( getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'], { now: 1, - negativeInspectionTtlMs: 1_000_000 + negativeInspectionTtlMs: 1_000_000, + inspectableDistros: ['Ubuntu', 'Debian'] }) ).resolves.toEqual(['Ubuntu', 'Debian']) }) @@ -211,4 +220,23 @@ describe('WSL CLI registration registry', () => { expect(Object.keys(state.inspectionTimes).length).toBeLessThanOrEqual(65) expect(state.inspectionTimes['managed oldest']).toBe(0) }) + + it("never inspects a distro Orca has no record of: the user's own distros get no guest command", async () => { + await expect( + getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'MyDevBox'], { + inspectableDistros: ['Ubuntu'] + }) + ).resolves.toEqual(['Ubuntu']) + await expect(getWslCliRegistrationCandidates(userDataPath, ['MyDevBox'])).resolves.toEqual([]) + }) + + it("still reconciles a distro carrying Orca's own registration record", async () => { + await recordWslCliRegistrationObservations(userDataPath, [ + { distro: 'Ubuntu', inspected: true, managed: true, reconciled: null } + ]) + + await expect(getWslCliRegistrationCandidates(userDataPath, ['Ubuntu'])).resolves.toEqual([ + 'Ubuntu' + ]) + }) }) diff --git a/src/main/cli/wsl-cli-registration-registry.ts b/src/main/cli/wsl-cli-registration-registry.ts index e4b2f7da833..74182caa6cb 100644 --- a/src/main/cli/wsl-cli-registration-registry.ts +++ b/src/main/cli/wsl-cli-registration-registry.ts @@ -28,6 +28,11 @@ type WslCliRegistrationRegistryTiming = { // Unchanged launcher/build pairs need no repair; app updates must trigger a new probe. currentTarget?: string | null appVersion?: string | null + /** + * Unregistered distros that may still be inspected: ones Orca deployed a host into. Any other + * distro is the user's own and never gets a guest command (EDR noise, untouched environments). + */ + inspectableDistros?: readonly string[] } export type WslCliRegistrationObservation = { @@ -193,6 +198,7 @@ export async function getWslCliRegistrationCandidates( const now = timing.now ?? Date.now() const negativeInspectionTtlMs = timing.negativeInspectionTtlMs ?? DEFAULT_NEGATIVE_INSPECTION_TTL_MS + const inspectable = new Set((timing.inspectableDistros ?? []).map(normalizeWslDistroKey)) return uniqueDistros(availableDistros).filter((distro) => { const key = normalizeWslDistroKey(distro) if (registered.has(key)) { @@ -204,6 +210,9 @@ export async function getWslCliRegistrationCandidates( reconciliation.appVersion === (timing.appVersion ?? '') ) } + if (!inspectable.has(key)) { + return false + } const inspectedAt = state.inspectionTimes[key] return ( inspectedAt === undefined || inspectedAt > now || now - inspectedAt >= negativeInspectionTtlMs From 63fc1f11c54364b572c0d33b63d86b32a5e6b62a Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 31 Oct 2026 06:29:29 -0700 Subject: [PATCH 2/5] test: remove 19 low-value suites and 200 individual cases (#36681) * test: remove low-value suites and cases * test: shrink stale timeout baseline after removing cases --- config/flaky-test-pattern-baseline.txt | 3 +- config/scripts/ci-shard-timings.json | 17 -- .../vitest-transform-tsconfig.test.mjs | 22 -- .../browser/browser-route-identity.test.ts | 31 --- ...browser-cookie-public-suffix-scope.test.ts | 9 - ...ude-structured-option-confirmation.test.ts | 53 ---- .../claude/claude-subagent-id-aliases.test.ts | 24 -- .../codex-rollout-resume-state.test.ts | 42 +--- ...sh-breadcrumb-renderer-attribution.test.ts | 31 --- src/main/daemon/daemon-errors.test.ts | 21 +- .../daemon/process-boundary-ground.test.ts | 8 - ...ro-7329-remote-snapshot-corruption.test.ts | 32 --- .../daemon/session-pending-output.test.ts | 19 -- .../terminal-history-seed-segments.test.ts | 66 +---- .../terminal-snapshot-mouse-encoding.test.ts | 36 --- .../emulator/emulator-availability.test.ts | 159 ------------ src/main/git/pack-refs-lock-ownership.test.ts | 57 +---- .../host/secret-protection-report.test.ts | 15 +- .../local-build-candidate.test.ts | 21 -- .../activation/orcad-activation-gate.test.ts | 168 ------------- .../orcad-state-snapshot-space.test.ts | 6 - .../provider-timeline-assembler-turns.test.ts | 32 --- ...t-session-history-large-identities.test.ts | 10 - .../native-chat-visual-file-read.test.ts | 76 +----- .../plugins/plugin-bundled-bootstrap.test.ts | 43 +--- .../plugin-uninstall-lifecycle.test.ts | 12 - .../pty/node-pty-master-fd-retirement.test.ts | 13 - .../rate-limits/cursor-session-token.test.ts | 27 +-- src/main/ripgrep/bundled-ripgrep-path.test.ts | 58 +---- ...device-registry-external-edit-auth.test.ts | 7 - .../runtime/orchestration/db-messages.test.ts | 82 +------ .../mutation-receipt-capacity.test.ts | 29 --- .../structured-worker-journal-archive.test.ts | 23 -- .../methods/mobile-web-bundle-range.test.ts | 41 +--- .../methods/orchestration/gates/gates.test.ts | 62 ----- .../worker-stop-liveness-verdict.test.ts | 35 --- ...ructured-agent-session-attachments.test.ts | 44 +--- .../wsl-enumeration-protocol.test.ts | 36 +-- src/main/skills/skill-discovery-wsl.test.ts | 94 +------- .../ssh/config/ssh-config-alias-claim.test.ts | 30 --- .../ssh-hostile-host-cells.test.ts | 119 --------- .../orcad-fence-lost-classification.test.ts | 26 +- .../ssh/orcad-migration-path-rewrite.test.ts | 47 +--- .../ssh/targets/ssh-target-identity.test.ts | 8 - .../ssh-target-orcad-preflight.test.ts | 94 +------- ...dows-install-dir-package-acl-grant.test.ts | 115 +-------- ...ssage-text-generation-linked-issue.test.ts | 180 -------------- ...e-text-generation-remote-execution.test.ts | 68 +----- ...rktree-create-execution-host-route.test.ts | 76 ------ ...ktree-removal-execution-host-route.test.ts | 61 ----- .../remote-browser-page-input-model.test.ts | 117 --------- .../crash-report-submit-notice.test.ts | 91 +------ .../preview-terminal-options.test.ts | 134 ---------- .../editor/editor-model-owner.test.ts | 182 -------------- .../editor/markdown-rich-size-limit.test.ts | 31 +-- .../editor/markdown-table-of-contents.test.ts | 22 +- .../editor/rich-markdown-commands.test.ts | 48 ---- .../landing-preflight-issues.test.ts | 106 -------- .../NativeChatBackgroundTaskRun.test.tsx | 56 +---- .../project-combobox-matching.test.ts | 55 +---- .../presentation/plugin-install-trust.test.ts | 151 ------------ .../pr-comments-resolution-prompt.test.ts | 144 +---------- .../file-search-include-pattern.test.ts | 54 +---- .../useFileExplorerRowDrag.test.ts | 54 +---- .../settings/cli-install-failure.test.ts | 108 --------- ...ostSetupsSection.workspace-window.test.tsx | 195 --------------- ...repo-existing-workspaces-telemetry.test.ts | 94 +------- ...rkspace-kanban-virtual-lane-layout.test.ts | 57 ----- .../sidebar/worktree-review-helpers.test.tsx | 121 ---------- .../task-page-jira-project-selection.test.ts | 72 ------ .../task-page-linear-issue-request.test.ts | 133 ---------- ...me-xterm-korean-enter-commit-order.test.ts | 33 --- ...e-xterm-trailing-preedit-occlusion.test.ts | 22 -- .../terminal-pane-host-state.test.ts | 228 ------------------ .../worktree-jump-palette-primitives.test.tsx | 156 ------------ .../store/project-host-setup-selector.test.ts | 23 -- .../persisted-ui-write-baseline.test.ts | 75 ------ .../src/store/slices/terminal-helpers.test.ts | 74 ------ 78 files changed, 47 insertions(+), 4977 deletions(-) delete mode 100644 config/scripts/vitest-transform-tsconfig.test.mjs delete mode 100644 src/main/emulator/emulator-availability.test.ts delete mode 100644 src/main/managed-server/activation/orcad-activation-gate.test.ts delete mode 100644 src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts delete mode 100644 src/main/text-generation/commit-message-text-generation-linked-issue.test.ts delete mode 100644 src/main/worktree-create-execution-host-route.test.ts delete mode 100644 src/main/worktree-removal-execution-host-route.test.ts delete mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts delete mode 100644 src/renderer/src/components/editor/editor-model-owner.test.ts delete mode 100644 src/renderer/src/components/landing-preflight-issues.test.ts delete mode 100644 src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts delete mode 100644 src/renderer/src/components/settings/cli-install-failure.test.ts delete mode 100644 src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx delete mode 100644 src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx delete mode 100644 src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts delete mode 100644 src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts delete mode 100644 src/renderer/src/components/worktree-jump-palette-primitives.test.tsx delete mode 100644 src/renderer/src/store/slices/terminal-helpers.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 1a97c148b57..64c3649f085 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -1161,7 +1161,6 @@ 1 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-agent-status-retention.test.ts 2 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-exact-runtime-stop.test.ts 7 test-no-wall-clock:src/renderer/src/store/slices/tabs-unread-and-focus.test.ts -1 test-no-wall-clock:src/renderer/src/store/slices/terminal-helpers.test.ts 1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-view-layout.test.ts 1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts 2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-agent-stop-preflight.test.ts @@ -1316,7 +1315,7 @@ 2 test-timeout-needs-reason:src/main/providers/local-pty-child-process-verdict.test.ts 3 test-timeout-needs-reason:src/main/providers/pty-repaint-wide-char-buffer.node-pty.test.ts 2 test-timeout-needs-reason:src/main/providers/startup-line-typed-length.live-shell.test.ts -7 test-timeout-needs-reason:src/main/pty/node-pty-master-fd-retirement.test.ts +5 test-timeout-needs-reason:src/main/pty/node-pty-master-fd-retirement.test.ts 2 test-timeout-needs-reason:src/main/runtime/cline-screen-readiness-transcripts.test.ts 4 test-timeout-needs-reason:src/main/runtime/codex-header-readiness-transcripts.test.ts 1 test-timeout-needs-reason:src/main/runtime/codex-quiet-ready-screen.test.ts diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 6dc880d03f8..4ca542ff09c 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -2308,7 +2308,6 @@ "src/main/emulator/android/uiautomator-tree.test.ts": 77, "src/main/emulator/backends/android-emulator-backend.test.ts": 230, "src/main/emulator/backends/ios-emulator-backend.test.ts": 167, - "src/main/emulator/emulator-availability.test.ts": 68, "src/main/emulator/emulator-bridge.test.ts": 397, "src/main/emulator/emulator-gesture-sender.test.ts": 174, "src/main/emulator/emulator-session-registry.test.ts": 50, @@ -3346,7 +3345,6 @@ "src/main/managed-server/activation/orcad-activation-crash-recovery.test.ts": 430, "src/main/managed-server/activation/orcad-activation-fence-generation.test.ts": 608, "src/main/managed-server/activation/orcad-activation-fence-hold.test.ts": 345, - "src/main/managed-server/activation/orcad-activation-gate.test.ts": 65, "src/main/managed-server/activation/orcad-activation-record.test.ts": 131, "src/main/managed-server/activation/orcad-activation-transaction.test.ts": 258, "src/main/managed-server/host-state/orcad-machine-home.test.ts": 1699, @@ -6119,7 +6117,6 @@ "src/main/ssh/connection/ssh-connection-system-transport.test.ts": 276, "src/main/ssh/connection/ssh-connection-wake-retry.test.ts": 316, "src/main/ssh/connection/ssh-connection.test.ts": 1650, - "src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts": 74, "src/main/ssh/hostile-host-test-support/ssh-hostile-hosts.docker.test.ts": 575, "src/main/ssh/legacy-relay/legacy-relay-bridge-relay-restart.test.ts": 70, "src/main/ssh/legacy-relay/legacy-relay-bridge-restart-stop.test.ts": 3036, @@ -6393,7 +6390,6 @@ "src/main/text-generation/commit-message-text-generation-cancellation.test.ts": 914, "src/main/text-generation/commit-message-text-generation-failure-sanitization.test.ts": 584, "src/main/text-generation/commit-message-text-generation-generated-output.test.ts": 445, - "src/main/text-generation/commit-message-text-generation-linked-issue.test.ts": 475, "src/main/text-generation/commit-message-text-generation-local-subprocess.test.ts": 302, "src/main/text-generation/commit-message-text-generation-model-discovery.test.ts": 417, "src/main/text-generation/commit-message-text-generation-regression.test.ts": 391, @@ -6574,7 +6570,6 @@ "src/main/worktree-create-base.test.ts": 41, "src/main/worktree-create-candidates.test.ts": 54, "src/main/worktree-create-concurrency.test.ts": 44, - "src/main/worktree-create-execution-host-route.test.ts": 495, "src/main/worktree-create-in-flight.test.ts": 175, "src/main/worktree-create-preparation-activity.test.ts": 42, "src/main/worktree-create-preparation-cancellation.test.ts": 613, @@ -6597,7 +6592,6 @@ "src/main/worktree-prunable-git-file.test.ts": 42, "src/main/worktree-removal-authority.test.ts": 142, "src/main/worktree-removal-close-records.test.ts": 1302, - "src/main/worktree-removal-execution-host-route.test.ts": 413, "src/main/worktree-removal-home-guard.test.ts": 85, "src/main/worktree-removal-repo-owner.test.ts": 42, "src/main/worktree-removal-safety.test.ts": 153, @@ -7091,7 +7085,6 @@ "src/renderer/src/components/dashboard-popout/preview-grid-claim.test.ts": 322, "src/renderer/src/components/dashboard-popout/preview-terminal-box-fit-lifecycle.test.ts": 294, "src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts": 333, - "src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts": 170, "src/renderer/src/components/dashboard-popout/preview-terminal-right-click-paste.test.ts": 1760, "src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts": 178, "src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts": 38, @@ -7272,7 +7265,6 @@ "src/renderer/src/components/editor/editor-header.test.ts": 57, "src/renderer/src/components/editor/editor-labels.test.ts": 46, "src/renderer/src/components/editor/editor-model-host-isolation.test.ts": 5854, - "src/renderer/src/components/editor/editor-model-owner.test.ts": 316, "src/renderer/src/components/editor/editor-model-uri-labels.test.ts": 1029, "src/renderer/src/components/editor/editor-model-uri-language-service.test.ts": 2417, "src/renderer/src/components/editor/editor-model-uri-parity.test.ts": 154, @@ -7587,7 +7579,6 @@ "src/renderer/src/components/jira-prompt-templates.test.ts": 106, "src/renderer/src/components/jira-self-user.test.ts": 44, "src/renderer/src/components/landing-preflight-dismissal.test.ts": 104, - "src/renderer/src/components/landing-preflight-issues.test.ts": 134, "src/renderer/src/components/landing-preflight-runtime-boundary.test.ts": 1576, "src/renderer/src/components/landing-preflight-unverifiable-host.test.tsx": 1436, "src/renderer/src/components/linear-api-key-dialog-state.test.ts": 53, @@ -8433,7 +8424,6 @@ "src/renderer/src/components/settings/browser-session-host-selection.test.ts": 43, "src/renderer/src/components/settings/bundled-skill-setup-result-copy.test.ts": 304, "src/renderer/src/components/settings/chat-naming-persistence.test.tsx": 3654, - "src/renderer/src/components/settings/cli-install-failure.test.ts": 34, "src/renderer/src/components/settings/codex-config-sync-warning.test.ts": 34, "src/renderer/src/components/settings/developer-permissions-search.test.ts": 178, "src/renderer/src/components/settings/general-editor-search.test.ts": 136, @@ -8454,7 +8444,6 @@ "src/renderer/src/components/settings/repository/execution/RepositoryHooksSection.test.ts": 715, "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.settings-entry.test.tsx": 1786, "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.test.tsx": 1674, - "src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx": 1584, "src/renderer/src/components/settings/repository/execution/RepositoryWorktreeDefaultsSection.test.tsx": 577, "src/renderer/src/components/settings/repository/execution/repository-hook-settings-draft.test.ts": 368, "src/renderer/src/components/settings/repository/execution/repository-host-setup-options.test.ts": 151, @@ -8817,7 +8806,6 @@ "src/renderer/src/components/sidebar/worktree-manual-order.test.ts": 237, "src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts": 142, "src/renderer/src/components/sidebar/worktree-parent-eligibility.test.ts": 36, - "src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx": 92, "src/renderer/src/components/sidebar/worktree-scroll-to-current-button.test.ts": 51, "src/renderer/src/components/sidebar/worktree-sidebar-drag-autoscroll.test.ts": 63, "src/renderer/src/components/sidebar/worktree-sidebar-drag-geometry.test.ts": 79, @@ -9055,7 +9043,6 @@ "src/renderer/src/components/task-page-jira-grouping.test.ts": 1486, "src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 54, "src/renderer/src/components/task-page/jira/task-page-jira-load-state.test.ts": 48, - "src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts": 28, "src/renderer/src/components/task-page/jira/task-page-jira-quick-copy.test.tsx": 2171, "src/renderer/src/components/task-page/jira/task-page-jira-saved-filter-application.test.tsx": 1838, "src/renderer/src/components/task-page-jira-saved-filter-load-failure.test.tsx": 2974, @@ -9088,7 +9075,6 @@ "src/renderer/src/components/task-page/jira/IssueUserField.test.tsx": 2183, "src/renderer/src/components/task-page/linear/task-page-linear-in-orca-issues.test.ts": 98, "src/renderer/src/components/task-page/linear/task-page-linear-issue-grouping.test.ts": 1441, - "src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts": 57, "src/renderer/src/components/task-page/linear/task-page-linear-team-selection.test.ts": 46, "src/renderer/src/components/task-page/task-page-default-repo-selection.test.ts": 42, "src/renderer/src/components/task-page/task-page-initial-selection-scaling.test.tsx": 1703, @@ -9534,7 +9520,6 @@ "src/renderer/src/components/terminal-pane/terminal-pane-element-file-drop.test.tsx": 1853, "src/renderer/src/components/terminal-pane/terminal-pane-frame-reconciliation.test.ts": 387, "src/renderer/src/components/terminal-pane/terminal-pane-host-state-memo.test.ts": 2151, - "src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts": 1272, "src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-commands.test.ts": 222, "src/renderer/src/components/terminal-pane/terminal-pane-layout-owner-gestures.test.ts": 43, "src/renderer/src/components/terminal-pane/terminal-pane-local-windows-conpty.test.ts": 1431, @@ -9742,7 +9727,6 @@ "src/renderer/src/components/workspace-surface-projection.test.ts": 48, "src/renderer/src/components/worktree-jump-palette-browser-navigation.test.tsx": 2772, "src/renderer/src/components/worktree-jump-palette-interleaved-sections.test.tsx": 2023, - "src/renderer/src/components/worktree-jump-palette-primitives.test.tsx": 384, "src/renderer/src/components/worktree-jump-palette-quick-action-availability.test.tsx": 1441, "src/renderer/src/components/worktree-jump-palette-recent-inclusion.test.ts": 93, "src/renderer/src/components/worktree-jump-palette-sleeping-filter.test.ts": 36, @@ -11267,7 +11251,6 @@ "src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts": 1309, "src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1204, "src/renderer/src/store/slices/tabs/tabs-root-group.test.ts": 1263, - "src/renderer/src/store/slices/terminal-helpers.test.ts": 68, "src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts": 1443, "src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts": 1313, "src/renderer/src/store/slices/terminal-orphan-helpers.test.ts": 170, diff --git a/config/scripts/vitest-transform-tsconfig.test.mjs b/config/scripts/vitest-transform-tsconfig.test.mjs deleted file mode 100644 index de36bf2b9aa..00000000000 --- a/config/scripts/vitest-transform-tsconfig.test.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { globSync, readFileSync } from 'node:fs' -import { dirname, posix, resolve } from 'node:path' -import { expect, it } from 'vitest' - -const root = resolve(import.meta.dirname, '../..') -const references = (file) => - JSON.parse(readFileSync(resolve(root, file), 'utf8')).references.map(({ path }) => - posix.join(posix.dirname(file), path) - ) - -// Unit tests transform with this pinned solution, so a project missing from it loses its compiler options. -it('lists every project tsconfig auto-discovery would find for unit-test sources', () => { - const nested = globSync('**/tsconfig.json', { - cwd: root, - exclude: ['**/node_modules/**', 'mobile/**', 'docs/**'] - }) - .map((file) => file.replaceAll('\\', '/')) - .filter((file) => dirname(file) !== '.') - expect(references('config/tsconfig.vitest-transform.json').sort()).toEqual( - [...nested, ...references('tsconfig.json')].sort() - ) -}) diff --git a/src/main/browser/browser-route-identity.test.ts b/src/main/browser/browser-route-identity.test.ts index d036ed84c34..d4ef9158338 100644 --- a/src/main/browser/browser-route-identity.test.ts +++ b/src/main/browser/browser-route-identity.test.ts @@ -20,20 +20,6 @@ const pinnedIdentity = { } describe('browser route partition identity', () => { - it('derives a stable opaque cross-platform partition and binding fingerprint', () => { - const first = deriveBrowserRoutePartition(identity) - const second = deriveBrowserRoutePartition({ ...identity }) - - expect(second).toEqual(first) - expect(first.partition).toMatch(/^persist:orca-browser-v1-[a-f0-9]{64}$/) - expect(first.bindingFingerprint).toMatch(/^[a-f0-9]{64}$/) - expect(first.partition.slice('persist:'.length)).toMatch(/^[a-z0-9-]+$/) - for (const rawIdentity of Object.values(identity)) { - expect(first.partition).not.toContain(rawIdentity) - } - expect(first.partition).not.toContain('private.example') - }) - it('keeps delimiter-containing components structurally distinct', () => { const left = deriveBrowserRoutePartition({ ...identity, @@ -49,17 +35,6 @@ describe('browser route partition identity', () => { expect(left).not.toEqual(right) }) - it('does not expose equality of individual identity components', () => { - const baseline = deriveBrowserRoutePartition(identity).partition - const sameProfile = deriveBrowserRoutePartition({ - ...identity, - executionHostIdentity: 'ssh/target:other.example' - }).partition - - expect(baseline.split('-').at(-1)).not.toBe(sameProfile.split('-').at(-1)) - expect(baseline).not.toMatch(/:[a-f0-9]{16}:/) - }) - it('makes every identity component load-bearing', () => { const derived = [ identity, @@ -82,12 +57,6 @@ describe('browser route partition identity', () => { }) }) - it('keeps the partition name and the binding fingerprint in separate digest domains', () => { - const derived = deriveBrowserRoutePartition(identity) - - expect(derived.partition).not.toContain(derived.bindingFingerprint) - }) - it('scopes partition ownership to one orca profile and one environment', () => { const scope = deriveBrowserRoutePartitionStorageScope({ orcaProfileId: 'orca/profile:alpha', diff --git a/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts b/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts index b81918cac5a..e617a78affc 100644 --- a/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts +++ b/src/main/browser/cookies/browser-cookie-public-suffix-scope.test.ts @@ -36,10 +36,6 @@ describe('registrable family across public-suffix sections', () => { expect(registrableFamily('[::1]')).toBe('[::1]') }) - it('treats an unlisted suffix as its own boundary', () => { - expect(registrableFamily('example.notaruleatall')).toBe('example.notaruleatall') - }) - it('rejects a bare suffix as an import domain but keeps real hosts', () => { expect(normalizeCookieImportDomain('co.uk')).toBeNull() expect(normalizeCookieImportDomain('api.br')).toBeNull() @@ -50,11 +46,6 @@ describe('registrable family across public-suffix sections', () => { // Unlisted .local uses a two-label family boundary. describe('unlisted .local suffix', () => { - it('stops at the two-label boundary', () => { - expect(registrableFamily('app.orca.local')).toBe('orca.local') - expect(registrableFamily('orca.local')).toBe('orca.local') - }) - it('pulls the shared parent into the removal scope', () => { const scope = importedDomainScope(['app.orca.local']) diff --git a/src/main/claude/claude-structured-option-confirmation.test.ts b/src/main/claude/claude-structured-option-confirmation.test.ts index 6948f352822..bb5a44132dc 100644 --- a/src/main/claude/claude-structured-option-confirmation.test.ts +++ b/src/main/claude/claude-structured-option-confirmation.test.ts @@ -53,19 +53,6 @@ function modelValue(result: AgentSessionOptionsResult): string | undefined { } describe('structured option confirmation reaches the pill', () => { - it('shows a just-set model before any turn reports it', async () => { - const claude = fakeClaude({ - initModel: 'claude-sonnet-5', - routes: { list_models: () => CATALOG } - }) - const adapter = await acquired(claude) - await adapter.setOption({ sessionId: 'session-1', key: 'model', value: 'haiku', fence: 7 }) - - const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 }) - expect(result.current.confirmed ?? []).not.toContain('model') - expect(modelSource(result)).toBe('dispatched') - }) - it('marks the model reported once the provider names it back', async () => { const claude = fakeClaude({ initModel: 'claude-sonnet-5', @@ -79,46 +66,6 @@ describe('structured option confirmation reaches the pill', () => { expect(result.current.confirmed).toContain('model') expect(modelSource(result)).toBe('reported') }) - - it('records an effort the readback could not take without confirming it', async () => { - const claude = fakeClaude({ - initModel: 'claude-sonnet-5', - settings: { applied: {}, effective: {}, sources: {} }, - routes: { list_models: () => CATALOG } - }) - const adapter = await acquired(claude) - // Max is session-only and cannot be confirmed through persisted settings. - await adapter.setOption({ sessionId: 'session-1', key: 'effort', value: 'max', fence: 7 }) - - const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 }) - expect(result.current.effort).toBe('max') - expect(result.current.confirmed ?? []).not.toContain('effort') - }) - - it('confirms an effort the readback agreed with', async () => { - const claude = fakeClaude({ - initModel: 'claude-sonnet-5', - settings: { applied: { effort: 'low' }, effective: { effortLevel: 'low' }, sources: {} }, - routes: { list_models: () => CATALOG } - }) - const adapter = await acquired(claude) - await adapter.setOption({ sessionId: 'session-1', key: 'effort', value: 'low', fence: 7 }) - - await vi.waitFor(async () => { - const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 }) - expect(result.current.confirmed).toContain('effort') - }) - }) - - it('treats a host that reports no confirmation as unconfirmed', () => { - // Older hosts omit confirmed; preserve their value with unconfirmed provenance. - const result = { - models: [{ id: 'haiku', label: 'Haiku', isDefault: false, efforts: [] }], - current: { model: 'haiku' } - } - expect(modelSource(result)).toBe('dispatched') - expect(modelValue(result)).toBe('haiku') - }) }) describe('the provider report corrects the pill', () => { diff --git a/src/main/claude/claude-subagent-id-aliases.test.ts b/src/main/claude/claude-subagent-id-aliases.test.ts index 0a0b0fddb1d..89005f524a0 100644 --- a/src/main/claude/claude-subagent-id-aliases.test.ts +++ b/src/main/claude/claude-subagent-id-aliases.test.ts @@ -2,21 +2,6 @@ import { describe, expect, it } from 'vitest' import { ClaudeSubagentIds } from './claude-subagent-id-aliases' describe('ClaudeSubagentIds', () => { - it('resolves an aliased tool id to its task, and an unaliased id to itself', () => { - const ids = new ClaudeSubagentIds() - ids.alias('toolu_1', 'task-1') - expect(ids.canonical('toolu_1')).toBe('task-1') - expect(ids.canonical('toolu_unknown')).toBe('toolu_unknown') - }) - - it('remembers an exclusion under either of the ids that named it', () => { - const ids = new ClaudeSubagentIds() - ids.exclude('task-bash') - expect(ids.isExcluded('toolu_bash', 'task-bash')).toBe(true) - expect(ids.isExcluded(null, null)).toBe(false) - expect(ids.isExcluded('task-agent')).toBe(false) - }) - it('drops the oldest alias past the bound and keeps the newest', () => { const ids = new ClaudeSubagentIds() for (let index = 0; index <= 512; index += 1) { @@ -47,15 +32,6 @@ describe('ClaudeSubagentIds', () => { expect(ids.canonical('tool-1')).toBe('tool-1') expect(ids.isExcluded(oversized)).toBe(false) }) - - it('forgets everything on clear', () => { - const ids = new ClaudeSubagentIds() - ids.alias('toolu_1', 'task-1') - ids.exclude('task-1') - ids.clear() - expect(ids.canonical('toolu_1')).toBe('toolu_1') - expect(ids.isExcluded('task-1')).toBe(false) - }) }) describe('ClaudeSubagentIds with an earlier run journaled', () => { diff --git a/src/main/codex-usage/codex-rollout-resume-state.test.ts b/src/main/codex-usage/codex-rollout-resume-state.test.ts index b0c1baaf5fd..a68463c47fc 100644 --- a/src/main/codex-usage/codex-rollout-resume-state.test.ts +++ b/src/main/codex-usage/codex-rollout-resume-state.test.ts @@ -4,9 +4,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { buildCodexRolloutResumeState, - MIN_RESUMABLE_PREFIX_BYTES, resolveCodexRolloutResume } from './codex-rollout-resume-state' + import type { CodexUsageParseContext } from './codex-usage-record-parser' import type { CodexUsagePersistedFile } from './types' @@ -71,28 +71,6 @@ describe('buildCodexRolloutResumeState', () => { buildCodexRolloutResumeState(filePath, 5 * WINDOW_BYTES, context) ).resolves.toBeNull() }) - - // Digest verification costs more than rereading a short prefix. - it('refuses a prefix at or under the resumable floor', async () => { - const filePath = writeRollout('at-floor.jsonl', 4 * WINDOW_BYTES) - - expect(MIN_RESUMABLE_PREFIX_BYTES).toBe(3 * WINDOW_BYTES) - await expect( - buildCodexRolloutResumeState(filePath, MIN_RESUMABLE_PREFIX_BYTES, context) - ).resolves.toBeNull() - await expect( - buildCodexRolloutResumeState(filePath, MIN_RESUMABLE_PREFIX_BYTES + 1, context) - ).resolves.not.toBeNull() - }) - - it('records an offset the file still reaches', async () => { - const filePath = writeRollout('full-prefix.jsonl', 4 * WINDOW_BYTES) - - const state = await buildCodexRolloutResumeState(filePath, 4 * WINDOW_BYTES, context) - - expect(state?.parsedBytes).toBe(4 * WINDOW_BYTES) - expect(state?.headDigest).toMatch(new RegExp(`^${WINDOW_BYTES}:`)) - }) }) describe('resolveCodexRolloutResume', () => { @@ -107,24 +85,6 @@ describe('resolveCodexRolloutResume', () => { await expect(resolveCodexRolloutResume(filePath, previous)).resolves.toBeNull() }) - // Validate untrusted cache offsets before calculating the boundary window. - it('rejects a persisted offset under the floor', async () => { - const filePath = writeRollout('under-floor.jsonl', 4 * WINDOW_BYTES) - const previous = persistedFile(filePath, { - parsedBytes: 100, - boundaryDigest: `${WINDOW_BYTES}:unused`, - headDigest: `${WINDOW_BYTES}:unused`, - physicalFileId: null, - sessionId: 'session-under-floor', - sessionCwd: null, - currentCwd: null, - currentModel: null, - previousTotals: null - }) - - await expect(resolveCodexRolloutResume(filePath, previous)).resolves.toBeNull() - }) - it('accepts a recorded offset when the file only grew', async () => { const filePath = writeRollout('grown.jsonl', 4 * WINDOW_BYTES) const state = await buildCodexRolloutResumeState(filePath, 4 * WINDOW_BYTES, context) diff --git a/src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts b/src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts index 3431a35089b..f98da67bee1 100644 --- a/src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts +++ b/src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts @@ -32,37 +32,6 @@ describe('renderer crash breadcrumb attribution', () => { ]) }) - it('does not merge identical coalesced storms from sibling renderers', () => { - recordCoalescedCrashBreadcrumb({ - name: 'renderer_error', - data: { message: 'boom' }, - coalesceKey: 'renderer:11\u0000renderer_error:boom', - minIntervalMs: 30_000, - origin: 'renderer:11' - }) - recordCoalescedCrashBreadcrumb({ - name: 'renderer_error', - data: { message: 'boom' }, - coalesceKey: 'renderer:22\u0000renderer_error:boom', - minIntervalMs: 30_000, - origin: 'renderer:22' - }) - - expect(getCrashBreadcrumbSnapshot('renderer:11')).toHaveLength(1) - expect(getCrashBreadcrumbSnapshot('renderer:22')).toHaveLength(1) - expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11') - expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22') - }) - - it('retains identical high-water profiles independently per renderer', () => { - const profile = { rendererSurface: 'main', thresholdPct: 80, usedHeapMB: 512 } - recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:11') - recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:22') - - expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11') - expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22') - }) - it('preserves the reporter trail when sibling renderer traffic fills the ring', () => { for (let index = 0; index < 4; index += 1) { recordCrashBreadcrumb('renderer_memory_highwater', { diff --git a/src/main/daemon/daemon-errors.test.ts b/src/main/daemon/daemon-errors.test.ts index 71374415772..eb2cf9a1a7d 100644 --- a/src/main/daemon/daemon-errors.test.ts +++ b/src/main/daemon/daemon-errors.test.ts @@ -3,10 +3,8 @@ import { DaemonProtocolError, decodeDaemonResponseError, isDaemonEndpointGoneError, - SessionNotFoundError, - TerminalHostGoneError + SessionNotFoundError } from './daemon-errors' -import { mapRuntimeError } from '../runtime/rpc/errors' function socketError(code: string, syscall: string): Error & { code: string; syscall: string } { return Object.assign(new Error(`${syscall} ${code}`), { code, syscall }) @@ -48,21 +46,4 @@ describe('isDaemonEndpointGoneError', () => { expect(isDaemonEndpointGoneError(socketError(code, 'connect'))).toBe(false) } }) - - it('ignores non-socket errors and non-objects', () => { - expect(isDaemonEndpointGoneError(new Error('Connection lost'))).toBe(false) - expect(isDaemonEndpointGoneError('connect ENOENT')).toBe(false) - expect(isDaemonEndpointGoneError(null)).toBe(false) - expect(isDaemonEndpointGoneError(undefined)).toBe(false) - }) - - it('keeps the host-gone marker across runtime RPC error mapping', () => { - const response = mapRuntimeError( - 'req-1', - { runtimeId: 'runtime-1' }, - new TerminalHostGoneError() - ) - - expect(response.error).toEqual({ code: 'runtime_error', message: 'terminal_host_gone' }) - }) }) diff --git a/src/main/daemon/process-boundary-ground.test.ts b/src/main/daemon/process-boundary-ground.test.ts index 219d60e8392..b81e6182cd4 100644 --- a/src/main/daemon/process-boundary-ground.test.ts +++ b/src/main/daemon/process-boundary-ground.test.ts @@ -126,14 +126,6 @@ describe('process boundary ground at a cold restore', () => { } }) - it('grounds without moving the cursor', () => { - const live = emulator(DAEMON_SESSION_SCROLLBACK_ROWS) - write(live, 'OLD_OUTPUT_1\r\n$ ') - write(live, PROCESS_BOUNDARY_GROUND) - write(live, 'X') - expect(live.getBufferTailLines(24)[1]).toBe('$ X') - }) - // awin verify-11: a reattach after Wake showed the new prompt beside the dead shell's (`$ $`). it("starts the new shell's prompt on its own line, keeping the recovered history", () => { const live = seededLive(checkpointOfDeadProcess('')) diff --git a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts index 332833b47f6..cfedc08654c 100644 --- a/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts +++ b/src/main/daemon/repro-7329-remote-snapshot-corruption.test.ts @@ -103,36 +103,4 @@ describe('#7329 remote-server snapshot corruption', () => { term.dispose() } }) - - it('does not eat the continuation byte when the tail and continuation are contiguous', async () => { - // Test a contiguous continuation directly; production snapshot-sequence accounting is not exercised here. - const emu = new HeadlessEmulator({ cols: 80, rows: 24 }) - const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - try { - await emulatorWrite(emu, '\x1b[38;5;') - const snapshot = emu.getSnapshot({ scrollbackRows: 0 }) - expect(snapshot.pendingEscapeTailAnsi).toBe('\x1b[38;5;') - await replayRemoteSnapshot(term, snapshot) - await writeXterm(term, '82mHELLO') - const visible = renderVisible(term) - expect(visible).toBe('HELLO') - } finally { - emu.dispose() - term.dispose() - } - }) - - it('documents the residual edge: an idle-death tail eats the next output byte', async () => { - // A tail with no continuation can consume unrelated later output; pin the known parser limitation. - const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - try { - await writeXterm(term, 'prompt$ ') - await writeXterm(term, '\x1b[3') - await writeXterm(term, 'yes\r\n') - // CSI consumes 'y' as a final byte; only the remaining 'es' renders. - expect(renderVisible(term)).toBe('prompt$ es') - } finally { - term.dispose() - } - }) }) diff --git a/src/main/daemon/session-pending-output.test.ts b/src/main/daemon/session-pending-output.test.ts index f7012327206..0b302d22677 100644 --- a/src/main/daemon/session-pending-output.test.ts +++ b/src/main/daemon/session-pending-output.test.ts @@ -63,19 +63,6 @@ describe('Session pending output', () => { ]) }) - it('coalesces adjacent output chunks', () => { - const subprocess = createMockSubprocess() - const live = createSession(subprocess) - - for (let i = 0; i < 100; i += 1) { - subprocess.simulateData(`chunk-${i};`) - } - - const take = live.takePendingOutput(false) - expect(take!.records).toHaveLength(1) - expect(take!.records[0]).toMatchObject({ kind: 'output' }) - }) - it('drains on take and increments the batch sequence', () => { const subprocess = createMockSubprocess() const live = createSession(subprocess) @@ -125,10 +112,4 @@ describe('Session pending output', () => { const next = live.takePendingOutput(false) expect(next!.records).toEqual([]) }) - - it('returns null after dispose', () => { - const live = createSession() - live.dispose() - expect(live.takePendingOutput(false)).toBeNull() - }) }) diff --git a/src/main/daemon/terminal-history-seed-segments.test.ts b/src/main/daemon/terminal-history-seed-segments.test.ts index ea63a0cac8b..a364eb93fa3 100644 --- a/src/main/daemon/terminal-history-seed-segments.test.ts +++ b/src/main/daemon/terminal-history-seed-segments.test.ts @@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest' import { HeadlessEmulator } from './headless-emulator' import { buildRehydrateSequences } from './terminal-mode-rehydrate-sequences' import { getRecoveredHistorySeedSegments } from './terminal-history-seed-segments' -import { - PROCESS_BOUNDARY_GROUND, - RESET_GRAPHIC_RENDITION -} from '../../shared/terminal-mode-reset-profiles' -import { buildFreshShellViewportBlankingSequence } from '../../shared/terminal-fresh-shell-viewport' + import type { ColdRestoreInfo } from './terminal-history-cold-restore-info' import type { TerminalModes } from './types' @@ -19,10 +15,6 @@ const ARMED_MODES: TerminalModes = { alternateScreen: false } -// Assert seed placement here; terminal-mode-reset-profiles.test.ts pins the reset bytes. -const GROUND = PROCESS_BOUNDARY_GROUND -const FRESH_VIEWPORT = buildFreshShellViewportBlankingSequence(24) - function restoreInfo(overrides: Partial = {}): ColdRestoreInfo { return { snapshotAnsi: 'user@host ~ $ \x1b[?1003h', @@ -37,51 +29,6 @@ function restoreInfo(overrides: Partial = {}): ColdRestoreInfo } describe('getRecoveredHistorySeedSegments', () => { - it('grounds after the snapshot and drops the dead process torn escape tail', () => { - const segments = getRecoveredHistorySeedSegments( - restoreInfo({ pendingEscapeTailAnsi: '\x1b[3' }) - ) - expect(segments).toEqual([ - `${RESET_GRAPHIC_RENDITION}\x1b[?1003h\x1b[?1006h`, - 'user@host ~ $ \x1b[?1003h', - GROUND, - FRESH_VIEWPORT - ]) - }) - - it('grounds the alt-screen normal-buffer branch too', () => { - expect( - getRecoveredHistorySeedSegments( - restoreInfo({ modes: { ...ARMED_MODES, alternateScreen: true } }) - ) - ).toEqual([`${RESET_GRAPHIC_RENDITION}user@host ~ $ `, GROUND, FRESH_VIEWPORT]) - }) - - it('stays empty when there is no recovered normal buffer', () => { - expect( - getRecoveredHistorySeedSegments( - restoreInfo({ - modes: { ...ARMED_MODES, alternateScreen: true }, - scrollbackAnsi: '', - snapshotAnsi: '' - }) - ) - ).toEqual([]) - }) - - it('keeps the empty "nothing to recover" sentinel on the normal-screen branch', () => { - expect( - getRecoveredHistorySeedSegments( - restoreInfo({ - modes: { ...ARMED_MODES, mouseTracking: false, mouseTrackingMode: 'none' }, - scrollbackAnsi: '', - snapshotAnsi: '', - rehydrateSequences: '' - }) - ) - ).toEqual([]) - }) - it('recovers nothing when a torn escape is the only recovered data', () => { expect( getRecoveredHistorySeedSegments( @@ -112,15 +59,4 @@ describe('getRecoveredHistorySeedSegments', () => { emulator.dispose() } }) - - it('does not touch the live-session reattach payload (mobile scroll gestures)', () => { - // Live reattach must preserve the active TUI’s modes; only recovery knows that process is dead. - expect(buildRehydrateSequences(ARMED_MODES)).toBe('\x1b[?1003h\x1b[?1006h') - }) - - it('grounds the pen before re-entering the alternate screen', () => { - expect(buildRehydrateSequences({ ...ARMED_MODES, alternateScreen: true })).toBe( - `${RESET_GRAPHIC_RENDITION}\x1b[?1049h\x1b[?1003h\x1b[?1006h` - ) - }) }) diff --git a/src/main/daemon/terminal-snapshot-mouse-encoding.test.ts b/src/main/daemon/terminal-snapshot-mouse-encoding.test.ts index 749101f5e5b..0658cec0568 100644 --- a/src/main/daemon/terminal-snapshot-mouse-encoding.test.ts +++ b/src/main/daemon/terminal-snapshot-mouse-encoding.test.ts @@ -8,7 +8,6 @@ import { serializeWithAbsoluteCursor } from '../../shared/terminal-serialize-abs import { readTerminalMouseEncoding } from '../../shared/terminal-mouse-encoding' const CODEX_FULLSCREEN_MODES = '\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h' -const X10_WHEEL_UP_AT_10_5 = `\x1b[M${String.fromCharCode(96, 42, 37)}` const SGR_WHEEL_UP_AT_10_5 = '\x1b[<64;10;5M' function createTerminal(): { terminal: Terminal; addon: SerializeAddon } { @@ -69,16 +68,6 @@ function wheelUpReport(terminal: Terminal): string | null { } describe('snapshot mouse encoding', () => { - it('the bare addon drops SGR encoding, so its restore reports X10 (the #23818 shape)', async () => { - const { terminal, addon } = createTerminal() - await write(terminal, `shell$ ${CODEX_FULLSCREEN_MODES}codex`) - - const restored = await replay(addon.serialize()) - - expect(restored.modes.mouseTrackingMode).toBe('any') - expect(wheelUpReport(restored)).toBe(X10_WHEEL_UP_AT_10_5) - }) - it('round-trips SGR encoding with the tracking mode, so the restore reports SGR', async () => { const { terminal, addon } = createTerminal() await write(terminal, `shell$ ${CODEX_FULLSCREEN_MODES}codex`) @@ -111,19 +100,6 @@ describe('snapshot mouse encoding', () => { expect(wheelUpReport(restored)).toBeNull() }) - it('adds nothing for the default encoding or when modes are excluded', async () => { - const { terminal, addon } = createTerminal() - await write(terminal, 'x\x1b[?1000h') - const legacy = serializeWithAbsoluteCursor(addon, terminal) - expect(legacy).toContain('\x1b[?1000h') - expect(legacy).not.toContain('\x1b[?1006h') - expect(legacy).not.toContain('\x1b[?1016h') - - await write(terminal, '\x1b[?1006h') - const excluded = serializeWithAbsoluteCursor(addon, terminal, { excludeModes: true }) - expect(excluded).not.toContain('\x1b[?1006h') - }) - it('carries the encoding from a renderer snapshot through a headless seed to its snapshot', async () => { // Mobile replay discards bytes before the last alternate-screen entry; encoding must survive that slice. const { terminal, addon } = createTerminal() @@ -142,16 +118,4 @@ describe('snapshot mouse encoding', () => { expect(wheelUpReport(await replay(data))).toBe(SGR_WHEEL_UP_AT_10_5) emulator.dispose() }) - - it('a snapshot from an older host without the encoding restores as before', async () => { - const emulator = new HeadlessEmulator({ cols: 40, rows: 10 }) - await emulator.write('\x1b[?1049h\x1b[?1003hcodex') - - const snapshot = emulator.getSnapshot() - - expect(snapshot.modes.mouseTrackingMode).toBe('any') - expect(snapshot.modes.sgrMouseMode).toBe(false) - expect(snapshot.rehydrateSequences).not.toContain('\x1b[?1006h') - emulator.dispose() - }) }) diff --git a/src/main/emulator/emulator-availability.test.ts b/src/main/emulator/emulator-availability.test.ts deleted file mode 100644 index 987f16f9cfe..00000000000 --- a/src/main/emulator/emulator-availability.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { inspectEmulatorAvailability } from './emulator-availability' -import type { EmulatorBridge } from './emulator-bridge' -import type { SimulatorDevice } from './simctl-simulator-devices' -import type { BackendAvailability } from './backends/emulator-backend' -import { EmulatorError } from './emulator-errors' -import { emulatorFailureText } from '../../shared/emulator-failure-copy' - -type FakeBridgeOverrides = { - supported?: boolean - listSimulators?: () => Promise - checkServeSimAvailable?: () => Promise - android?: BackendAvailability -} - -const NO_ANDROID: BackendAvailability = { - available: false, - devices: [], - message: 'Android SDK not found. Install Android Studio and set ANDROID_HOME.' -} - -function fakeBridge(overrides: FakeBridgeOverrides = {}): EmulatorBridge { - const android = overrides.android ?? NO_ANDROID - return { - listBackends: () => [ - { kind: 'ios', isSupportedOnHost: () => overrides.supported ?? true }, - { - kind: 'android', - isSupportedOnHost: () => android.available, - checkAvailability: async () => android - } - ], - listSimulators: overrides.listSimulators ?? (async () => []), - checkServeSimAvailable: overrides.checkServeSimAvailable ?? (async () => {}) - } as unknown as EmulatorBridge -} - -const DEVICE: SimulatorDevice = { - name: 'iPhone 17 Pro', - udid: 'udid-1', - state: 'Booted', - runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-18-0' -} - -describe('inspectEmulatorAvailability', () => { - it('falls back to the Android setup message when no backend is available', async () => { - const result = await inspectEmulatorAvailability(fakeBridge({ supported: false })) - expect(result.available).toBe(false) - expect(result.message).toMatch(/Android SDK/) - expect(result.devices).toEqual([]) - }) - - it('reports ready when iOS simulators exist and serve-sim is available', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ supported: true, listSimulators: async () => [DEVICE] }) - ) - expect(result.available).toBe(true) - expect(result.message).toBe('Ready') - expect(result.devices).toEqual([DEVICE]) - }) - - it('reports ready with Android devices when the iOS backend is unsupported', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ - supported: false, - android: { - available: true, - message: 'Ready', - devices: [ - { - backend: 'android', - id: 'emulator-5554', - name: 'Pixel_7', - state: 'booted', - isAvailable: true - } - ] - } - }) - ) - expect(result.available).toBe(true) - expect(result.message).toBe('Ready') - expect(result.devices).toEqual([ - { - name: 'Pixel_7', - udid: 'emulator-5554', - state: 'Booted', - runtime: 'Android', - isAvailable: true - } - ]) - }) - - it('flags simctl when no simulators are installed', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ supported: true, listSimulators: async () => [] }) - ) - expect(result.available).toBe(false) - expect(result.simctl.ok).toBe(false) - expect(result.simctl.message).toMatch(/No iOS simulators/) - }) - - it('flags serve-sim when its check throws', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ - supported: true, - listSimulators: async () => [DEVICE], - checkServeSimAvailable: async () => { - throw new Error('serve-sim missing') - } - }) - ) - expect(result.available).toBe(false) - expect(result.serveSim.ok).toBe(false) - expect(result.serveSim.message).toBe('serve-sim missing') - }) - - it('flags simctl when listing simulators throws', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ - supported: true, - listSimulators: async () => { - throw new Error('xcrun exploded') - } - }) - ) - expect(result.available).toBe(false) - expect(result.simctl.ok).toBe(false) - expect(result.simctl.message).toBe('xcrun exploded') - }) - - it('codes known setup sentences without changing their English text', async () => { - const result = await inspectEmulatorAvailability( - fakeBridge({ - supported: true, - listSimulators: async () => { - throw new EmulatorError( - 'emulator_device_not_found', - emulatorFailureText('simulatorNotFound', { udid: 'udid-9' }) - ) - }, - android: { - available: false, - devices: [], - message: 'adb exploded', - messageCode: 'adbUnavailable' - } - }) - ) - expect(result.simctl).toEqual({ - ok: false, - message: - 'Simulator udid-9 not found. Create one via Xcode > Window > Devices and Simulators.', - messageCode: 'simulatorNotFound', - messageParams: { udid: 'udid-9' } - }) - expect(result.android).toMatchObject({ message: 'adb exploded', messageCode: 'adbUnavailable' }) - }) -}) diff --git a/src/main/git/pack-refs-lock-ownership.test.ts b/src/main/git/pack-refs-lock-ownership.test.ts index 31e7a9e9259..581b22e03c9 100644 --- a/src/main/git/pack-refs-lock-ownership.test.ts +++ b/src/main/git/pack-refs-lock-ownership.test.ts @@ -1,4 +1,5 @@ -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -43,25 +44,6 @@ afterEach(async () => { }) describe('packed-refs lock ownership', () => { - it('claims a repository with no lock and records the owner', async () => { - const commonDir = await gitCommonDir() - const { marker } = paths(commonDir) - - await expect(new PackRefsLockOwnership(commonDir).claim()).resolves.toEqual({ ok: true }) - - await expect(readFile(marker, 'utf-8')).resolves.toContain(String(process.pid)) - }) - - it('drops the owner marker on release', async () => { - const commonDir = await gitCommonDir() - const ownership = new PackRefsLockOwnership(commonDir) - await ownership.claim() - - await ownership.release() - - await expect(exists(paths(commonDir).marker)).resolves.toBe(false) - }) - it('refuses a lock it cannot prove is its own', async () => { const commonDir = await gitCommonDir() await writeFile(paths(commonDir).lock, 'someone else') @@ -70,18 +52,6 @@ describe('packed-refs lock ownership', () => { await expect(exists(paths(commonDir).lock)).resolves.toBe(true) }) - it('refuses a lock whose recorded owner is still running', async () => { - const commonDir = await gitCommonDir() - const { lock, marker } = paths(commonDir) - await writeFile(lock, 'in progress') - await writeFile(marker, JSON.stringify({ pid: process.pid })) - - await expect( - new PackRefsLockOwnership(commonDir).claim(laterBy(ABANDONED_LOCK_AGE_MS + 1)) - ).resolves.toMatchObject({ ok: false }) - await expect(exists(lock)).resolves.toBe(true) - }) - it('reclaims the lock its own dead process left behind', async () => { const commonDir = await gitCommonDir() const { lock, marker } = paths(commonDir) @@ -136,27 +106,4 @@ describe('packed-refs lock ownership', () => { ).resolves.toMatchObject({ ok: false }) await expect(exists(lock)).resolves.toBe(true) }) - - it('claims cleanly when a marker outlived its lock', async () => { - const commonDir = await gitCommonDir() - await writeFile(paths(commonDir).marker, JSON.stringify({ pid: DEAD_PID })) - - await expect(new PackRefsLockOwnership(commonDir).claim()).resolves.toEqual({ ok: true }) - }) -}) - -describe('unattributed per-ref locks', () => { - it('preserves empty ref locks when only an old dead-owner marker exists', async () => { - const commonDir = await gitCommonDir() - const namespace = join(commonDir, 'refs', 'remotes', 'origin') - await mkdir(namespace, { recursive: true }) - await writeFile(join(namespace, 'main.lock'), '') - await writeFile(join(namespace, 'main'), 'a'.repeat(40)) - await writeFile(paths(commonDir).marker, JSON.stringify({ pid: DEAD_PID })) - - await new PackRefsLockOwnership(commonDir).claim(laterBy(ABANDONED_LOCK_AGE_MS + 1)) - - await expect(exists(join(namespace, 'main.lock'))).resolves.toBe(true) - await expect(exists(join(namespace, 'main'))).resolves.toBe(true) - }) }) diff --git a/src/main/host/secret-protection-report.test.ts b/src/main/host/secret-protection-report.test.ts index 524017af653..6bd0bc939d9 100644 --- a/src/main/host/secret-protection-report.test.ts +++ b/src/main/host/secret-protection-report.test.ts @@ -2,7 +2,8 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { _resetSecretStoreForTests, setSecretStore } from '../../shared/secret-store' +import { setSecretStore } from '../../shared/secret-store' + import { reportSecretProtectionGap } from './secret-protection-report' const WEAK = 'Secrets are obfuscated with a built-in key.' @@ -66,12 +67,6 @@ describe('reportSecretProtectionGap', () => { expect(logged).toHaveLength(2) }) - it('stays silent from a clean start when secrets are properly sealed', () => { - installStore(null) - expect(report()).toBeNull() - expect(logged).toEqual([]) - }) - it('re-reports on demand for support, without disturbing stored state', () => { installStore(WEAK) report() @@ -87,10 +82,4 @@ describe('reportSecretProtectionGap', () => { expect(report()).toBe(WEAK) expect(logged).toHaveLength(1) }) - - it('does not throw startup when no store is installed', () => { - _resetSecretStoreForTests() - expect(() => report()).not.toThrow() - expect(logged[0]).toContain('could not determine at-rest protection') - }) }) diff --git a/src/main/local-builds/local-build-candidate.test.ts b/src/main/local-builds/local-build-candidate.test.ts index 2807164ed9c..507d978ba46 100644 --- a/src/main/local-builds/local-build-candidate.test.ts +++ b/src/main/local-builds/local-build-candidate.test.ts @@ -65,18 +65,6 @@ afterEach(async () => { }) describe('loadLocalBuildCandidate', () => { - it('returns a sanitized, architecture-specific feed after hash validation', async () => { - const { manifestPath } = await fixture() - const candidate = await loadLocalBuildCandidate(manifestPath, 'arm64', { - readCompatibility: async () => compatibility() - }) - - expect(candidate.version).toBe('1.2.3-local.1') - expect([...candidate.artifacts.keys()]).toEqual(['orca-macos-arm64.zip']) - expect(candidate.manifestContent).toContain('orca-macos-arm64.zip') - await candidate.close() - }) - it('rejects mismatched hashes and traversal paths', async () => { const badHash = await fixture({ sha512: Buffer.alloc(64).toString('base64') }) await expect( @@ -160,13 +148,4 @@ describe('loadLocalBuildCandidate', () => { await candidate.close() } ) - - it('requires exactly one ZIP for the running architecture', async () => { - const { manifestPath } = await fixture() - await expect( - loadLocalBuildCandidate(manifestPath, 'x64', { - readCompatibility: async () => compatibility() - }) - ).rejects.toThrow('exactly one x64 Orca ZIP') - }) }) diff --git a/src/main/managed-server/activation/orcad-activation-gate.test.ts b/src/main/managed-server/activation/orcad-activation-gate.test.ts deleted file mode 100644 index 67871b01bef..00000000000 --- a/src/main/managed-server/activation/orcad-activation-gate.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { evaluateOrcadActivation } from './orcad-activation-gate' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' -import type { ServeReadiness } from '../../server/serve-readiness' -import type { OrcadHealth, TerminalDaemonHealth } from '../../orcad/orcad-health' - -const EXPECTED = { buildHash: 'abc123def4567890', fullVersion: '0.2.0+bb01' } - -function daemon(overrides: Partial = {}): TerminalDaemonHealth { - return { - state: 'live', - ownsFreshSessions: true, - pid: 4242, - buildVersion: '0.2.0+bb01', - entryPath: '/home/u/.orca-remote/orcad-0.2.0+bb01/daemon-entry.js', - protocolVersion: 3, - cgroupUnit: null, - selfTest: { ok: true, coverage: 'pty-spawn', verdict: 'healthy', durationMs: 12 }, - ...overrides - } -} - -function health(overrides: Partial = {}): OrcadHealth { - return { - buildHash: EXPECTED.buildHash, - buildVersion: EXPECTED.fullVersion, - nodeVersion: '20.11.0', - nodeAbi: '115', - platform: 'linux', - arch: 'x64', - pid: 4200, - terminalDaemon: daemon(), - ...overrides - } -} - -function readiness(overrides: Partial = {}): ServeReadiness { - return { - runtimeId: 'runtime-1', - boundEndpoint: 'ws://127.0.0.1:7777', - advertisedEndpoint: null, - managedWslCliReconciliation: 'settled', - pairing: { available: false, reason: 'disabled_by_operator', guidance: 'n/a' }, - health: health(), - ...overrides - } -} - -describe('evaluateOrcadActivation', () => { - it('activates a candidate that proved a real PTY round trip', () => { - const verdict = evaluateOrcadActivation(readiness(), EXPECTED) - expect(verdict).toEqual({ decision: 'activate', coverage: 'pty-spawn', warnings: [] }) - }) - - it('refuses when the candidate never published readiness', () => { - const verdict = evaluateOrcadActivation(null, EXPECTED) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_no_readiness' }) - }) - - it('refuses a readiness payload with no health, rather than reading silence as healthy', () => { - const { health: _dropped, ...withoutHealth } = readiness() - const verdict = evaluateOrcadActivation(withoutHealth as ServeReadiness, EXPECTED) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_no_health' }) - }) - - it('refuses when a different build answered — a stale process holding the port', () => { - const verdict = evaluateOrcadActivation( - readiness({ health: health({ buildHash: '0000000000000000' }) }), - EXPECTED - ) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_build_mismatch' }) - }) - - it('refuses a listening orcad whose terminal daemon is absent', () => { - const verdict = evaluateOrcadActivation( - readiness({ - health: health({ - terminalDaemon: daemon({ - state: 'absent', - ownsFreshSessions: false, - selfTest: { ok: false, coverage: 'pty-spawn', verdict: 'no-daemon', durationMs: 1 } - }) - }) - }), - EXPECTED - ) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_daemon_absent' }) - // Cold daemon startup is transient; later connects must remain eligible to deploy. - expect(classifyOrcadHostUnavailable({ code: 'orcad_activation_daemon_absent' })).toBeNull() - }) - - it('refuses a degraded daemon, whose fresh terminals would not survive a restart', () => { - const verdict = evaluateOrcadActivation( - readiness({ - health: health({ terminalDaemon: daemon({ state: 'degraded', ownsFreshSessions: false }) }) - }), - EXPECTED - ) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_daemon_degraded' }) - }) - - it('refuses a live daemon that failed its PTY spawn probe', () => { - const verdict = evaluateOrcadActivation( - readiness({ - health: health({ - terminalDaemon: daemon({ - selfTest: { - ok: false, - coverage: 'pty-spawn', - verdict: 'pty-spawn-unhealthy', - durationMs: 30 - } - }) - }) - }), - EXPECTED - ) - expect(verdict).toMatchObject({ - decision: 'reject', - code: 'orcad_activation_pty_self_test_failed' - }) - }) - - it('refuses a green daemon that does not own fresh sessions', () => { - const verdict = evaluateOrcadActivation( - readiness({ health: health({ terminalDaemon: daemon({ ownsFreshSessions: false }) }) }), - EXPECTED - ) - expect(verdict).toMatchObject({ - decision: 'reject', - code: 'orcad_activation_no_persistent_terminals' - }) - }) - - it('refuses a candidate that is not listening', () => { - const verdict = evaluateOrcadActivation(readiness({ boundEndpoint: null }), EXPECTED) - expect(verdict).toMatchObject({ decision: 'reject', code: 'orcad_activation_not_listening' }) - }) - - it('activates handshake-only coverage but never records it as a proven PTY', () => { - const verdict = evaluateOrcadActivation( - readiness({ - health: health({ - platform: 'win32', - terminalDaemon: daemon({ - selfTest: { ok: true, coverage: 'handshake', verdict: 'healthy', durationMs: 5 } - }) - }) - }), - EXPECTED - ) - expect(verdict).toMatchObject({ decision: 'activate', coverage: 'handshake' }) - expect(verdict.decision === 'activate' && verdict.warnings[0]).toContain( - 'covered the daemon handshake only' - ) - }) - - it('checks identity before health, so a wrong-build green payload cannot pass', () => { - const verdict = evaluateOrcadActivation( - readiness({ - health: health({ buildHash: 'ffffffffffffffff', terminalDaemon: daemon() }) - }), - EXPECTED - ) - expect(verdict).toMatchObject({ code: 'orcad_activation_build_mismatch' }) - }) -}) diff --git a/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts b/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts index 501e361b0d5..d127c079ca7 100644 --- a/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts +++ b/src/main/managed-server/host-state/orcad-state-snapshot-space.test.ts @@ -142,10 +142,4 @@ describe.skipIf(process.platform === 'win32')('snapshot room on a real shell (#3 expect(output.trim()).toBe('SNAPSHOT_SPACE UNMEASURED') expect(parseOrcadSnapshotSpace(output)).toBeNull() }) - - it('reads no room answer from a host that printed none', () => { - expect(parseOrcadSnapshotSpace('')).toBeNull() - expect(orcadSnapshotShortfallKb(null)).toBeNull() - expect(orcadSnapshotShortfallKb({ neededKb: 0, availableKb: 0, reclaimKb: 0 })).toBeNull() - }) }) diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts index a22305f5ebd..3d4cd86838d 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-turns.test.ts @@ -50,38 +50,6 @@ describe('provider timeline turns', () => { expect(row?.revision).toBeGreaterThan(runningRow?.revision ?? Infinity) }) - it('records a cancelled turn as interrupted with the cancellation verdict', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 }) - rig.assembler.apply({ - type: 'turn.end', - at: 2_000, - state: 'interrupted', - outcome: 'cancellation' - }) - expect(await rig.turn('turn-1')).toMatchObject({ - state: 'interrupted', - outcome: 'cancellation', - completedAt: 2_000 - }) - }) - - it('keeps a provider-reported failure a completed turn whose verdict says it failed', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 }) - rig.assembler.apply({ type: 'turn.end', at: 2_000, state: 'completed', outcome: 'failure' }) - expect(await rig.turn('turn-1')).toMatchObject({ state: 'completed', outcome: 'failure' }) - }) - - it('leaves the verdict absent when the provider gave none', async () => { - const rig = await openProviderTimelineRig() - rig.assembler.apply({ type: 'turn.open', turn: 'turn-1', at: 1_000 }) - rig.assembler.apply({ type: 'turn.end', at: 2_000, state: 'completed' }) - const turn = await rig.turn('turn-1') - expect(turn?.state).toBe('completed') - expect(turn).not.toHaveProperty('outcome') - }) - it('mints a turn id when the provider names none, and keys a turn no send opened by its own row', async () => { const rig = await openProviderTimelineRig() rig.assembler.apply({ type: 'turn.open', at: 1_000 }) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts index 80a239e8cdd..1b1c817d193 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts @@ -186,14 +186,4 @@ describe('identity bounding at admission', () => { ) expect(removal.page.removedItemIds).toEqual([appended.itemId]) }) - - it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { - const oversized = 'x'.repeat(2 * 1024 * 1024) - const bounded = boundJournalKeyComponent(oversized) - expect(bounded).toBe(boundJournalKeyComponent(oversized)) - expect(boundJournalKeyComponent(bounded)).toBe(bounded) - expect(bounded.length).toBeLessThan(2048) - expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) - expect(boundJournalKeyComponent('short')).toBe('short') - }) }) diff --git a/src/main/native-chat/native-chat-visual-file-read.test.ts b/src/main/native-chat/native-chat-visual-file-read.test.ts index 2071f10b60a..746ca77193c 100644 --- a/src/main/native-chat/native-chat-visual-file-read.test.ts +++ b/src/main/native-chat/native-chat-visual-file-read.test.ts @@ -1,11 +1,12 @@ import { execFileSync } from 'node:child_process' -import { chmod, mkdir, mkdtemp, rm, symlink, writeFile, link } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, symlink, writeFile, link } from 'node:fs/promises' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { NATIVE_CHAT_VISUAL_MAX_BYTES } from '../../shared/native-chat/native-chat-visual-directive' import { nativeChatScratchFolderFor } from './native-chat-scratch-folder' -import { nativeChatVisualRevision, readNativeChatVisualFile } from './native-chat-visual-file-read' +import { readNativeChatVisualFile } from './native-chat-visual-file-read' const posixIt = process.platform === 'win32' ? it.skip : it @@ -22,30 +23,7 @@ afterEach(async () => { await rm(stateDirectory, { recursive: true, force: true }) }) -describe('nativeChatScratchFolderFor', () => { - it('places each chat in its own hashed folder under the state directory', () => { - const alpha = nativeChatScratchFolderFor('/state', 'session-alpha') - const beta = nativeChatScratchFolderFor('/state', 'session-beta') - expect(alpha).toMatch(/chat-scratch[\\/][0-9a-f]{32}$/) - expect(alpha.startsWith(join('/state', 'chat-scratch'))).toBe(true) - expect(alpha).not.toBe(beta) - }) -}) - describe('readNativeChatVisualFile', () => { - it('reads a UTF-8 visual with its revision and size', async () => { - const html = '

Grüße

' - await writeFile(join(folder, 'chart.html'), html) - const result = await readNativeChatVisualFile(folder, 'chart.html') - expect(result).toEqual({ - ok: true, - html, - revision: nativeChatVisualRevision(Buffer.from(html)), - sizeBytes: Buffer.byteLength(html), - path: join(folder, 'chart.html') - }) - }) - it('answers unchanged without the bytes when the client already holds the revision', async () => { await writeFile(join(folder, 'chart.html'), '

a

') const first = await readNativeChatVisualFile(folder, 'chart.html') @@ -65,18 +43,6 @@ describe('readNativeChatVisualFile', () => { expect(changed).toMatchObject({ ok: true, html: '

b

' }) }) - it('reports a missing file or a missing folder as not_found', async () => { - expect(await readNativeChatVisualFile(folder, 'nope.html')).toEqual({ - ok: false, - error: 'not_found' - }) - const absent = nativeChatScratchFolderFor(stateDirectory, 'session-never') - expect(await readNativeChatVisualFile(absent, 'chart.html')).toEqual({ - ok: false, - error: 'not_found' - }) - }) - it('refuses names that are not a bare visual file name', async () => { await mkdir(join(stateDirectory, 'other'), { recursive: true }) await writeFile(join(stateDirectory, 'other', 'secret.html'), 'secret') @@ -134,14 +100,6 @@ describe('readNativeChatVisualFile', () => { }) }) - it('refuses a directory named like a visual', async () => { - await mkdir(join(folder, 'dir.html')) - expect(await readNativeChatVisualFile(folder, 'dir.html')).toEqual({ - ok: false, - error: 'not_a_file' - }) - }) - posixIt('refuses a FIFO without waiting for a writer', async () => { execFileSync('mkfifo', [join(folder, 'pipe.html')]) expect(await readNativeChatVisualFile(folder, 'pipe.html')).toEqual({ @@ -179,32 +137,4 @@ describe('readNativeChatVisualFile', () => { await link(join(folder, 'a.html'), join(folder, 'b.html')) expect(await readNativeChatVisualFile(folder, 'b.html')).toMatchObject({ ok: true }) }) - - it('reads the replacement after a file is swapped for new content', async () => { - await writeFile(join(folder, 'chart.html'), '

old

') - await rm(join(folder, 'chart.html')) - await writeFile(join(folder, 'chart.html'), '

new

') - expect(await readNativeChatVisualFile(folder, 'chart.html')).toMatchObject({ - ok: true, - html: '

new

' - }) - }) - - posixIt('reports an unexpected filesystem fault without the host path', async () => { - await writeFile(join(folder, 'chart.html'), '

a

') - await chmod(join(folder, 'chart.html'), 0o000) - try { - const failure = await readNativeChatVisualFile(folder, 'chart.html').then( - () => null, - (error: unknown) => error - ) - // Root bypasses mode bits, so assert refusal only when the read fails. - if (failure !== null) { - expect(String(failure)).toContain('visual_read_failed:EACCES') - expect(String(failure)).not.toContain(stateDirectory) - } - } finally { - await chmod(join(folder, 'chart.html'), 0o644) - } - }) }) diff --git a/src/main/plugins/plugin-bundled-bootstrap.test.ts b/src/main/plugins/plugin-bundled-bootstrap.test.ts index 5e195c1c7f3..c4905310577 100644 --- a/src/main/plugins/plugin-bundled-bootstrap.test.ts +++ b/src/main/plugins/plugin-bundled-bootstrap.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { hashPluginTree } from './plugin-content-hash' import { installPluginFromLocalPath, readPluginLockfile } from './installation/plugin-install' -import { bootstrapBundledPlugins, resolveBundledPluginRoot } from './plugin-bundled-bootstrap' +import { bootstrapBundledPlugins } from './plugin-bundled-bootstrap' const roots: string[] = [] @@ -53,30 +53,6 @@ afterEach(async () => { }) describe('bundled plugin bootstrap', () => { - it('installs release-indexed content once and keeps unchanged startup work bounded', async () => { - const root = await tempRoot('orca-bundled-resources-') - const userDataPath = await tempRoot('orca-bundled-user-data-') - const bundle = await writeBundle(root) - await writeIndex(root, bundle.path, bundle.hash) - - await expect( - bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' }) - ).resolves.toEqual({ - installed: ['stablyai.orca-skills'], - unchanged: [], - retired: [], - errors: [] - }) - await expect( - bootstrapBundledPlugins({ root, userDataPath, hostVersion: '1.4.0' }) - ).resolves.toEqual({ - installed: [], - unchanged: ['stablyai.orca-skills'], - retired: [], - errors: [] - }) - }) - it('publishes an updated immutable bundle only when the indexed hash matches', async () => { const root = await tempRoot('orca-bundled-resources-') const userDataPath = await tempRoot('orca-bundled-user-data-') @@ -198,21 +174,4 @@ describe('bundled plugin bootstrap', () => { expect(result.errors[0]?.error).toContain('does not match its release index') expect((await readPluginLockfile(join(userDataPath, 'plugins'))).plugins).toEqual({}) }) - - it('resolves packaged and development resource roots without platform separators', () => { - expect( - resolveBundledPluginRoot({ - isPackaged: true, - resourcesPath: join('app', 'resources'), - appPath: join('repo', 'app') - }) - ).toBe(join('app', 'resources', 'plugins', 'launch')) - expect( - resolveBundledPluginRoot({ - isPackaged: false, - resourcesPath: join('app', 'resources'), - appPath: join('repo', 'app') - }) - ).toBe(join('repo', 'app', 'resources', 'plugins', 'launch')) - }) }) diff --git a/src/main/plugins/plugin-uninstall-lifecycle.test.ts b/src/main/plugins/plugin-uninstall-lifecycle.test.ts index 65acea26e52..56d1d2253ad 100644 --- a/src/main/plugins/plugin-uninstall-lifecycle.test.ts +++ b/src/main/plugins/plugin-uninstall-lifecycle.test.ts @@ -169,15 +169,3 @@ it('waits for removal during service disposal and preserves history until succes } expect(service.getLogs(key)).toHaveLength(0) }) - -it('preserves installed crash history while cancelling the existing restart backoff', async () => { - const { service, install } = await createUninstallFixture() - const key = await install('crash') - const child = latestUninstallWorker() - child.connected = false - child.emit('exit', 1) - expect(latestPluginLog(service, key).line).toContain('exited unexpectedly') - await service.deactivatePlugin(key) - expect(service.findValidPlugin(key)).not.toBeNull() - expect(service.getLogs(key)).toHaveLength(200) -}) diff --git a/src/main/pty/node-pty-master-fd-retirement.test.ts b/src/main/pty/node-pty-master-fd-retirement.test.ts index 96d5d142066..ebf4b5abf0a 100644 --- a/src/main/pty/node-pty-master-fd-retirement.test.ts +++ b/src/main/pty/node-pty-master-fd-retirement.test.ts @@ -47,13 +47,6 @@ async function retiredPty( const describeOnPosix = process.platform === 'win32' ? describe.skip : describe describeOnPosix('node-pty master fd retirement', () => { - it('invalidates the descriptor once it gives up the handle', async () => { - const { term, spawnFd } = await retiredPty() - - expect(spawnFd).toBeGreaterThanOrEqual(0) - expect(masterFd(term)).toBe(-1) - }, 15000) - it('answers a resize past retirement without issuing the ioctl', async () => { const { term } = await retiredPty() @@ -71,12 +64,6 @@ describeOnPosix('node-pty master fd retirement', () => { writeStream(term).write('x') expect(writeStream(term)._writeQueue).toHaveLength(0) }, 15000) - - it('names the spawn file rather than tcgetpgrp on a retired descriptor', async () => { - const { term } = await retiredPty() - - expect(term.process).toBe(POSIX_SHELL) - }, 15000) }) // Linux reuses the lowest free fd; await every fixture exit so leaked descriptors cannot invalidate the next case. diff --git a/src/main/rate-limits/cursor-session-token.test.ts b/src/main/rate-limits/cursor-session-token.test.ts index 61bb7d8221a..2b01ab3090c 100644 --- a/src/main/rate-limits/cursor-session-token.test.ts +++ b/src/main/rate-limits/cursor-session-token.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - cursorSessionCookie, - isCursorSessionTokenExpired, - parseCursorSessionToken -} from './cursor-session-token' +import { cursorSessionCookie, parseCursorSessionToken } from './cursor-session-token' type JwtSegment = Record @@ -31,27 +27,6 @@ describe('parseCursorSessionToken', () => { expect(parseCursorSessionToken('not-a-jwt')).toBeNull() expect(parseCursorSessionToken('a.!!!.c')).toBeNull() }) - - it('leaves expiry null when the token omits exp', () => { - expect(parseCursorSessionToken(jwt({ sub: 'auth0|user_1' }))?.expiresAtMs).toBeNull() - }) -}) - -describe('isCursorSessionTokenExpired', () => { - const token = parseCursorSessionToken(jwt({ sub: 'auth0|user_1', exp: 2_000 })) - - it('reports a lapsed session', () => { - expect(isCursorSessionTokenExpired(token!, 2_000_001)).toBe(true) - }) - - it('reports a live session', () => { - expect(isCursorSessionTokenExpired(token!, 1_999_999)).toBe(false) - }) - - it('never expires a token with no exp claim', () => { - const noExpiry = parseCursorSessionToken(jwt({ sub: 'auth0|user_1' })) - expect(isCursorSessionTokenExpired(noExpiry!, Number.MAX_SAFE_INTEGER)).toBe(false) - }) }) describe('cursorSessionCookie', () => { diff --git a/src/main/ripgrep/bundled-ripgrep-path.test.ts b/src/main/ripgrep/bundled-ripgrep-path.test.ts index 6e0b95be8c5..47b1865c278 100644 --- a/src/main/ripgrep/bundled-ripgrep-path.test.ts +++ b/src/main/ripgrep/bundled-ripgrep-path.test.ts @@ -1,20 +1,11 @@ -import { - chmodSync, - existsSync, - mkdirSync, - mkdtempSync, - realpathSync, - rmSync, - writeFileSync -} from 'node:fs' +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { toBundledRipgrepPlatform } from '../../shared/bundled-ripgrep' + import { - bundledRipgrepCommand, - bundledRipgrepContentKey, bundledRipgrepWslSpawnOptions, resetBundledRipgrepPathCacheForTests, resolveBundledRipgrepPath @@ -32,21 +23,6 @@ describe('bundled ripgrep path', () => { resetBundledRipgrepPathCacheForTests() }) - it('resolves the checkout binary for this host in development', () => { - setResourcesPath(undefined) - const command = bundledRipgrepCommand() - - expect(command).toContain(join('@vscode', 'ripgrep-universal', 'bin')) - expect(existsSync(command)).toBe(true) - }) - - it('resolves the Linux build for WSL-routed spawns', () => { - setResourcesPath(undefined) - const linuxPlatform = toBundledRipgrepPlatform('linux', process.arch) - - expect(bundledRipgrepCommand({ wsl: true })).toContain(join('bin', `${linuxPlatform}`, 'rg')) - }) - it('prefers the packaged resources copy', () => { const resourcesDir = mkdtempSync(join(tmpdir(), 'orca-rg-resources-')) try { @@ -62,34 +38,6 @@ describe('bundled ripgrep path', () => { } }) - it('names no bundled build for platforms outside the relay set', () => { - expect(toBundledRipgrepPlatform('freebsd', 'x64')).toBeNull() - expect(toBundledRipgrepPlatform('win32', 'ia32')).toBeNull() - }) - - it('keys the remote cache on the shipped bytes', () => { - setResourcesPath(undefined) - const platform = toBundledRipgrepPlatform(process.platform, process.arch)! - const key = bundledRipgrepContentKey(platform) - - expect(key).toMatch(/^[0-9a-f]{16}$/) - const otherPlatform = platform === 'win32-x64' ? 'linux-x64' : 'win32-x64' - expect(bundledRipgrepContentKey(otherPlatform)).not.toBe(key) - }) - - it('picks the distro-arch Linux build and fails closed when its drive is unavailable', () => { - const { wslShellCommand } = bundledRipgrepWslSpawnOptions( - 'C:\\Program Files\\Orca\\resources\\ripgrep\\linux-x64\\rg' - ) - - expect(wslShellCommand).toContain(`wslpath -u 'C:\\Program Files\\Orca\\resources\\ripgrep'`) - expect(wslShellCommand).toContain('aarch64|arm64) a=linux-arm64') - expect(wslShellCommand).toContain('printf %s "$d/$a/rg"') - expect(wslShellCommand).toContain('else printf /dev/null/orca-ripgrep-unavailable') - expect(wslShellCommand).not.toContain('else printf rg') - expect(bundledRipgrepWslSpawnOptions('rg')).toEqual({}) - }) - it.skipIf(process.platform === 'win32')( 'never executes a PATH ripgrep when WSL cannot translate the install drive', async () => { diff --git a/src/main/runtime/device-registry-external-edit-auth.test.ts b/src/main/runtime/device-registry-external-edit-auth.test.ts index 33dcb252642..9ede3791236 100644 --- a/src/main/runtime/device-registry-external-edit-auth.test.ts +++ b/src/main/runtime/device-registry-external-edit-auth.test.ts @@ -101,13 +101,6 @@ describe('device registry auth checks see edits made on disk', () => { expect(registry.validateToken(added.token)?.deviceId).toBe(added.deviceId) }) - it('stays usable when there is no file at all', () => { - const registry = new DeviceRegistry(dir) - - expect(registry.validateToken('not-a-token')).toBeNull() - expect(registry.lookupDeviceKey('missing-device')).toEqual({ kind: 'unknown' }) - }) - it('keeps what it has when the file turns corrupt, since that proves no removal', () => { const registry = new DeviceRegistry(dir) const desktop = registry.addDevice('desktop', 'runtime') diff --git a/src/main/runtime/orchestration/db-messages.test.ts b/src/main/runtime/orchestration/db-messages.test.ts index 92066292023..d27f8bfdb1c 100644 --- a/src/main/runtime/orchestration/db-messages.test.ts +++ b/src/main/runtime/orchestration/db-messages.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' -import type Database from '../../sqlite/sync-database' -import { OrchestrationDb, type MessageType } from './db' + +import { OrchestrationDb } from './db' const runId = 'run_legacy_local' @@ -17,26 +17,6 @@ describe('OrchestrationDb', () => { } describe('messages', () => { - it('inserts and retrieves a message', () => { - const d = createDb() - const msg = d.insertMessage({ - runId, - from: 'term_a', - to: 'term_b', - subject: 'hello', - body: 'world' - }) - expect(msg.id).toMatch(/^msg_/) - expect(msg.from_handle).toBe('term_a') - expect(msg.to_handle).toBe('term_b') - expect(msg.subject).toBe('hello') - expect(msg.body).toBe('world') - expect(msg.type).toBe('status') - expect(msg.priority).toBe('normal') - expect(msg.read).toBe(0) - expect(msg.sequence).toBeGreaterThan(0) - }) - it('returns unread messages in sequence order', () => { const d = createDb() d.insertMessage({ runId, from: 'a', to: 'b', subject: 'first' }) @@ -49,28 +29,6 @@ describe('OrchestrationDb', () => { expect(unread[1].subject).toBe('second') }) - it('filters unread by type', () => { - const d = createDb() - d.insertMessage({ - runId, - from: 'a', - to: 'b', - subject: 'status msg', - type: 'status' - }) - d.insertMessage({ - runId, - from: 'a', - to: 'b', - subject: 'done msg', - type: 'worker_done' - }) - - const filtered = d.getUnreadMessages('b', ['worker_done']) - expect(filtered).toHaveLength(1) - expect(filtered[0].type).toBe('worker_done') - }) - it('excludes already-delivered rows from getUndeliveredUnreadMessages', () => { const d = createDb() const m1 = d.insertMessage({ runId, from: 'a', to: 'b', subject: 'one' }) @@ -86,19 +44,6 @@ describe('OrchestrationDb', () => { expect(unread).toHaveLength(2) }) - it('creates the undelivered inbox index used by push delivery', () => { - const d = createDb() - const sqlite = (d as unknown as { db: Database.Database }).db - - const indexes = sqlite - .prepare( - `SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'messages' AND name = 'idx_messages_undelivered_inbox'` - ) - .all() - - expect(indexes).toHaveLength(1) - }) - it('filters getUndeliveredUnreadMessages by type', () => { const d = createDb() d.insertMessage({ @@ -132,28 +77,5 @@ describe('OrchestrationDb', () => { expect(unread).toHaveLength(1) expect(unread[0].id).toBe(m2.id) }) - - it('rejects invalid message type', () => { - const d = createDb() - expect(() => - d.insertMessage({ - runId, - from: 'a', - to: 'b', - subject: 'bad', - type: 'invalid' as MessageType - }) - ).toThrow() - }) - - it('getInbox returns all messages across recipients', () => { - const d = createDb() - d.insertMessage({ runId, from: 'a', to: 'b', subject: 'one' }) - d.insertMessage({ runId, from: 'a', to: 'c', subject: 'two' }) - d.insertMessage({ runId, from: 'b', to: 'a', subject: 'three' }) - - const inbox = d.getInbox(10) - expect(inbox).toHaveLength(3) - }) }) }) diff --git a/src/main/runtime/orchestration/mutation-receipt-capacity.test.ts b/src/main/runtime/orchestration/mutation-receipt-capacity.test.ts index d45cc9f434e..8fa2402c415 100644 --- a/src/main/runtime/orchestration/mutation-receipt-capacity.test.ts +++ b/src/main/runtime/orchestration/mutation-receipt-capacity.test.ts @@ -55,35 +55,6 @@ describe('mutation receipt capacity schema', () => { } }) - it('uses the completed receipt index for age and capacity pruning', () => { - db = new OrchestrationDb(':memory:') - const sqlite = sqliteFor(db) - insertReceipts(sqlite, 10, 'completed') - - const agePlan = sqlite - .prepare( - `EXPLAIN QUERY PLAN - DELETE FROM mutation_receipts - WHERE state = 'completed' - AND updated_at < datetime('now', ?)` - ) - .all('-30 days') as { detail: string }[] - const capacityPlan = sqlite - .prepare( - `EXPLAIN QUERY PLAN - SELECT rowid FROM mutation_receipts - WHERE state = 'completed' - ORDER BY updated_at ASC, rowid ASC - LIMIT ?` - ) - .all(64) as { detail: string }[] - const details = [...agePlan, ...capacityPlan].map((row) => row.detail).join('\n') - - expect(details).toContain('idx_mutation_receipts_completed_updated') - expect(details).not.toContain('USE TEMP B-TREE') - expect(details).not.toMatch(/SCAN mutation_receipts(?:\n|$)/) - }) - it('migrates a populated v25 database and tracks writes from older connections', () => { tempDir = mkdtempSync(join(tmpdir(), 'orca-mutation-receipt-migration-')) const dbPath = join(tempDir, 'orchestration.db') diff --git a/src/main/runtime/orchestration/structured-worker-journal-archive.test.ts b/src/main/runtime/orchestration/structured-worker-journal-archive.test.ts index add55413c49..0b1a4356b0a 100644 --- a/src/main/runtime/orchestration/structured-worker-journal-archive.test.ts +++ b/src/main/runtime/orchestration/structured-worker-journal-archive.test.ts @@ -47,14 +47,6 @@ describe('buildStructuredJournalArchive', () => { expect(built.messages[0]?.id).not.toBe('item-0') }) - it('reports the end it actually dropped', () => { - const built = archive(longJournal(200)) - expect(built.warnings).toContain( - 'The oldest archived journal messages were dropped to fit the size bound.' - ) - expect(built.warnings).not.toContain('Transcript response was clipped to the wire-size limit.') - }) - it('stays inside the durable bound', () => { const built = archive(longJournal(200)) expect(Buffer.byteLength(JSON.stringify(built.messages), 'utf8')).toBeLessThanOrEqual( @@ -62,15 +54,6 @@ describe('buildStructuredJournalArchive', () => { ) }) - it('keeps a short journal whole and unflagged', () => { - const built = archive(longJournal(3)) - expect(built.limited).toBe(false) - expect(built.messages.map((message) => message.id)).toEqual(['item-0', 'item-1', 'item-2']) - expect(built.warnings).not.toContain( - 'The oldest archived journal messages were dropped to fit the size bound.' - ) - }) - it('archives raw result-before-call order without publishing client presentation markers', () => { const items: AgentJournalRenderItem[] = [ { @@ -124,10 +107,4 @@ describe('buildStructuredJournalArchive', () => { expect(projected[1]).toMatchObject({ id: 'old-x', role: 'tool', blocks: [{ output: 'OLD X' }] }) expect(foldToolMessages(projected)).toEqual(projected) }) - - it('still reports omitted older items when the page itself was bounded', () => { - const built = archive(longJournal(2), true) - expect(built.limited).toBe(true) - expect(built.warnings).toContain('Older journal items were omitted from the bounded archive.') - }) }) diff --git a/src/main/runtime/rpc/methods/mobile-web-bundle-range.test.ts b/src/main/runtime/rpc/methods/mobile-web-bundle-range.test.ts index b3fca6b92e6..901f441b646 100644 --- a/src/main/runtime/rpc/methods/mobile-web-bundle-range.test.ts +++ b/src/main/runtime/rpc/methods/mobile-web-bundle-range.test.ts @@ -7,15 +7,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MOBILE_WEB_BUNDLE_CHUNK_BYTES as RANGE_BYTES, MOBILE_WEB_BUNDLE_RANGE_METHOD, - MobileWebBundleManifestResultSchema, MobileWebBundleRangeResultSchema, type MobileWebBundleRangeResult } from '../../../../shared/mobile-web-bundle/bundle-rpc-contract' + import { resetBundledMobileWebBundleCacheForTests } from '../../bundled-mobile-web-bundle' -import { MOBILE_RPC_METHOD_ALLOWLIST } from '../../runtime-rpc/runtime-rpc-mobile-method-allowlist' + import type { RpcResponse } from '../core' import type { RpcDispatcher } from '../dispatcher' -import { ALL_RPC_METHODS } from './index' + import { resetMobileWebBundleAssetVerdictsForTests } from './mobile-web-bundle-asset-reader' import { resetMobileWebBundleReadAdmissionForTests } from './mobile-web-bundle-read-admission' import { @@ -86,22 +86,6 @@ describe('mobileWeb.bundle.range on an install that carries a bundle', () => { ]) }) - it('names the range grid on the manifest reply', async () => { - const response = await call('mobileWeb.bundle.manifest') - const result = MobileWebBundleManifestResultSchema.parse(response.ok && response.result) - expect(result.rangeBytes).toBe(RANGE_BYTES) - }) - - // Manifest discovery must name a method the mobile allowlist actually permits. - it('names the grid only for a method a paired phone can actually call', async () => { - const response = await call('mobileWeb.bundle.manifest') - expect( - MobileWebBundleManifestResultSchema.parse(response.ok && response.result).rangeBytes - ).toBeDefined() - expect(ALL_RPC_METHODS.map((method) => method.name)).toContain(MOBILE_WEB_BUNDLE_RANGE_METHOD) - expect(MOBILE_RPC_METHOD_ALLOWLIST.has(MOBILE_WEB_BUNDLE_RANGE_METHOD)).toBe(true) - }) - it('pages every asset back byte for byte on the range grid, each reply a strict result', async () => { for (const asset of bundle.assets) { const pieces: Buffer[] = [] @@ -155,23 +139,4 @@ describe('mobileWeb.bundle.range on an install that carries a bundle', () => { Buffer.from(result.dataBase64, 'base64').equals(INCOMPRESSIBLE.bytes.subarray(0, RANGE_BYTES)) ).toBe(true) }) - - it('serves a zero-byte asset as one empty identity range at eof', async () => { - const mark = bundle.assets.find((asset) => asset.byteLength === 0)! - - const result = body(await range({ buildId: bundle.buildId, path: mark.path, offset: 0 })) - - expect(result).toMatchObject({ encoding: 'identity', dataBase64: '', eof: true }) - }) - - it('refuses a caller-chosen length at the params schema', async () => { - const response = await range({ - buildId: bundle.buildId, - path: COMPRESSIBLE.path, - offset: 0, - length: 1000 - }) - - expect(response.ok ? undefined : response.error.code).toBe('invalid_argument') - }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/gates/gates.test.ts b/src/main/runtime/rpc/methods/orchestration/gates/gates.test.ts index d3d5776ebcc..7273bfb9ea2 100644 --- a/src/main/runtime/rpc/methods/orchestration/gates/gates.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/gates/gates.test.ts @@ -5,7 +5,6 @@ import type { OrchestrationDb } from '../../../../orchestration/db' describe('orchestration RPC methods', () => { const h = createOrchestrationRpcHarness() - const { findMethod } = h let db: OrchestrationDb let ctx: RpcContext @@ -67,30 +66,6 @@ describe('orchestration RPC methods', () => { expect(db.getTask(foreignTask.id)?.status).toBe('ready') expect(db.listGates({ taskId: foreignTask.id })).toHaveLength(0) }) - - it('rejects invalid options JSON', async () => { - setup() - const task = db.createTask({ spec: 'work' }) - await expect( - call('orchestration.gateCreate', { - task: task.id, - question: 'ok?', - options: 'not-json' - }) - ).rejects.toThrow('Invalid --options') - }) - - it('rejects options that are not string arrays', async () => { - setup() - const task = db.createTask({ spec: 'work' }) - await expect( - call('orchestration.gateCreate', { - task: task.id, - question: 'ok?', - options: JSON.stringify(['yes', 1]) - }) - ).rejects.toThrow('Invalid --options') - }) }) describe('orchestration.gateResolve', () => { @@ -110,42 +85,5 @@ describe('orchestration RPC methods', () => { const updated = db.getTask(task.id) expect(updated?.status).toBe('ready') }) - - it('throws on nonexistent gate', async () => { - setup() - await expect( - call('orchestration.gateResolve', { id: 'gate_fake', resolution: 'yes' }) - ).rejects.toThrow('Gate not found') - }) - }) - - describe('orchestration.gateList', () => { - it('lists all gates', async () => { - setup() - const t1 = db.createTask({ spec: 'a' }) - const t2 = db.createTask({ spec: 'b' }) - db.createGate({ taskId: t1.id, question: 'q1' }) - db.createGate({ taskId: t2.id, question: 'q2' }) - - const result = (await call('orchestration.gateList', {})) as { count: number } - expect(result.count).toBe(2) - }) - - it('filters by status', async () => { - setup() - const task = db.createTask({ spec: 'work' }) - const gate = db.createGate({ taskId: task.id, question: 'q' }) - db.resolveGate(gate.id, 'yes') - - const result = (await call('orchestration.gateList', { - status: 'resolved' - })) as { count: number } - expect(result.count).toBe(1) - }) - - it('rejects invalid status filters', () => { - const method = findMethod('orchestration.gateList') - expect(() => method.params!.parse({ status: 'closed' })).toThrow() - }) }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts index e546553bff5..908fe7360b0 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts @@ -124,26 +124,6 @@ describe('worker-stop against a terminal we lost contact with', () => { expect(stopped.lastError).toContain('could not be confirmed stopped') }) - it('uses the canonical live verdict for an observed process', async () => { - vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ - handle: 'term_worker', - worktreeId: 'repo::worktree', - connected: true, - status: 'running' - } as never) - vi.spyOn(runtime, 'getTerminalLivenessVerdict').mockReturnValue({ - status: 'live', - ptyIds: ['runtime:pty:1'] - }) - const dispatch = createWorker() - - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - observation: { status: 'live', exactWorker: true } - }) - }) - it('does not close a legacy worker terminal without an ownership record', async () => { vi.spyOn(runtime, 'showTerminal').mockResolvedValue({ handle: 'term_worker', @@ -184,19 +164,4 @@ describe('worker-stop against a terminal we lost contact with', () => { ) expect(db.getWorkerDispatch(dispatch.id)?.state).toBe('stopping') }) - - it('still reports a locally observed exit as exited', async () => { - const dispatch = createWorker() - - await expect( - call('orchestration.workerShow', { dispatch: dispatch.id }) - ).resolves.toMatchObject({ - observation: { status: 'exited', exactWorker: true } - }) - - const stopped = (await call('orchestration.workerStop', { dispatch: dispatch.id })) as { - lastError: string - } - expect(stopped.lastError).toBe('The recorded worker process is exited; no terminal was closed.') - }) }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-attachments.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-attachments.test.ts index 440d681c5d6..e823d383369 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-attachments.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-attachments.test.ts @@ -6,11 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import type { OrcaRuntimeService } from '../../orca-runtime' import type { RpcResponse } from '../core' import { RpcDispatcher } from '../dispatcher' -import { - AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY, - AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY, - RUNTIME_CAPABILITIES -} from '../../../../shared/protocol-version' + import { AgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store' import { setAgentSessionAttachmentStore } from '../../../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { STRUCTURED_AGENT_SESSION_ATTACHMENT_METHODS } from './structured-agent-session-attachments' @@ -103,11 +99,6 @@ async function uploadBytes(name: string, bytes: Buffer): Promise { } describe('agentSessionAttachment.*', () => { - it('is advertised, so a client can tell a host with the store from an older one', () => { - expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_ATTACHMENTS_RUNTIME_CAPABILITY) - expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY) - }) - it('stores an upload for the chat and hands back the server path', async () => { const { uploadId } = result<{ uploadId: string }>( await call( @@ -134,27 +125,6 @@ describe('agentSessionAttachment.*', () => { expect(preview).toMatchObject({ ok: true, result: { isBinary: true, mimeType: 'image/png' } }) }) - it('refuses a client that cannot read structured sessions', async () => { - const response = await call( - 'agentSessionAttachment.uploadStart', - { sessionId: 'session-alpha', name: 'shot.png', byteLength: 3 }, - { clientKind: 'runtime', clientCapabilities: [] } - ) - expect(response).toMatchObject({ - ok: false, - error: { message: expect.stringContaining('structured_agent_session_unsupported') } - }) - }) - - it('refuses a declared size over the attachment limit before storing anything', async () => { - const response = await call( - 'agentSessionAttachment.uploadStart', - { sessionId: 'session-alpha', name: 'big.bin', byteLength: 51 * 1024 * 1024 }, - CLIENT_A - ) - expect(response.ok).toBe(false) - }) - it("keeps one client's upload out of another's reach", async () => { const { uploadId } = result<{ uploadId: string }>( await call( @@ -175,18 +145,6 @@ describe('agentSessionAttachment.*', () => { expect(store.isUploadInFlight(uploadId)).toBe(true) }) - it('refuses an upload for a chat this host does not hold', async () => { - const response = await call( - 'agentSessionAttachment.uploadStart', - { sessionId: 'session-elsewhere', name: 'a.txt', byteLength: 1 }, - CLIENT_A - ) - expect(response).toMatchObject({ - ok: false, - error: { message: expect.stringContaining('not on this host') } - }) - }) - it('answers a remote preview of an image over 3 MiB with a small refusal, not an oversized reply', async () => { const path = await uploadBytes('big.png', Buffer.alloc(3.5 * 1024 * 1024, 7)) const replies: string[] = [] diff --git a/src/main/skills/skill-delete/wsl-enumeration-protocol.test.ts b/src/main/skills/skill-delete/wsl-enumeration-protocol.test.ts index db2c761c685..5be06189679 100644 --- a/src/main/skills/skill-delete/wsl-enumeration-protocol.test.ts +++ b/src/main/skills/skill-delete/wsl-enumeration-protocol.test.ts @@ -2,9 +2,7 @@ import { describe, expect, it } from 'vitest' import { parseWslInspectPathsOutput, parseWslListEntriesOutput, - WslEnumerationProtocolError, - WSL_INSPECT_PATHS_SCRIPT, - WSL_LIST_ENTRIES_SCRIPT + WslEnumerationProtocolError } from './wsl-enumeration-protocol' const NUL = '\0' @@ -28,12 +26,6 @@ describe('parseWslListEntriesOutput', () => { expect(listings.get(directories[1])).toEqual([]) }) - it('reports an absent directory as an empty listing rather than a missing key', () => { - const listings = parseWslListEntriesOutput('', ['/a', '/b']) - expect([...listings.keys()]).toEqual(['/a', '/b']) - expect(listings.get('/a')).toEqual([]) - }) - it('refuses an unknown record kind instead of guessing', () => { expect(() => parseWslListEntriesOutput(records('X', '0'), ['/a'])).toThrow( WslEnumerationProtocolError @@ -76,29 +68,3 @@ describe('parseWslInspectPathsOutput', () => { ).toThrow(WslEnumerationProtocolError) }) }) - -describe('guest scripts', () => { - it('classify a symlink before following it, so a broken link is not "missing"', () => { - expect(WSL_INSPECT_PATHS_SCRIPT.indexOf('-L "$path"')).toBeLessThan( - WSL_INSPECT_PATHS_SCRIPT.indexOf('-d "$path"') - ) - expect(WSL_LIST_ENTRIES_SCRIPT.indexOf('-L "$entry"')).toBeLessThan( - WSL_LIST_ENTRIES_SCRIPT.indexOf('-d "$entry"') - ) - }) - - it('reads mtime without dereferencing, matching WSL discovery', () => { - expect(WSL_INSPECT_PATHS_SCRIPT).toContain(`stat -c '%Y' -- "$path"`) - expect(WSL_INSPECT_PATHS_SCRIPT).not.toContain('stat -L') - }) - - it('takes every path positionally rather than interpolating it into the script', () => { - expect(WSL_LIST_ENTRIES_SCRIPT).toContain('for dir in "$@"; do') - expect(WSL_INSPECT_PATHS_SCRIPT).toContain('for path in "$@"; do') - }) - - it('marks an unreadable directory instead of listing it as empty', () => { - expect(WSL_LIST_ENTRIES_SCRIPT).toContain('if ! [ -r "$dir" ]; then') - expect(WSL_LIST_ENTRIES_SCRIPT).toContain(`printf 'X\\0'`) - }) -}) diff --git a/src/main/skills/skill-discovery-wsl.test.ts b/src/main/skills/skill-discovery-wsl.test.ts index 0a6de76744f..17c8411de72 100644 --- a/src/main/skills/skill-discovery-wsl.test.ts +++ b/src/main/skills/skill-discovery-wsl.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' + import type { SkillScanRoot } from './skill-discovery-sources' -import { buildWslSkillDiscoveryCommand, parseWslSkillDiscoveryOutput } from './skill-discovery-wsl' +import { parseWslSkillDiscoveryOutput } from './skill-discovery-wsl' const homeRoot: SkillScanRoot = { id: 'home-codex', @@ -71,63 +72,6 @@ describe('WSL skill discovery', () => { ) }) - it('builds a distro-side scan for enumeration, reads, and canonical identity', () => { - const script = buildWslSkillDiscoveryCommand([ - { ...repoRoot, path: "/work/alice's project/.agents/skills" } - ]) - - expect(script).toContain('find -L "$root_path"') - expect(script).toContain('realpath -- "$skill_file"') - expect(script).toContain('head -c 262144 -- "$skill_file"') - expect(script).toContain(`'/work/alice'\\''s project/.agents/skills'`) - }) - - it('filters requested names before reading skill payloads', () => { - const script = buildWslSkillDiscoveryCommand([homeRoot], ['Orchestration', 'computer-use']) - - expect(script).toContain("'orchestration'|'computer-use') return 0") - expect(script).toContain('local normalized_name=${1,,}') - expect(script).toContain('metadata_name_known=0') - expect(script).toContain('IFS= read -r -n "$remaining" line || read_status=$?') - expect(script).toContain('[ "$line_length" -ge "$remaining" ] && return') - expect(script).toContain('[[ "$candidate_name" =~ $non_ascii_pattern ]] && continue') - expect(script).toContain("line=${line#$'\\xEF\\xBB\\xBF'}") - expect(script).toContain('if [ "$metadata_name_known" -eq 1 ]; then') - expect(script).toContain('done < "$1"') - expect(script).not.toContain("awk '") - expect(script).not.toContain("tr '[:upper:]'") - expect(script.indexOf('matches_requested_name "$metadata_name" || continue')).toBeLessThan( - script.indexOf('encoded_markdown=$(head') - ) - }) - - it('filters classified source kinds while parsing', () => { - const markdown = Buffer.from('---\nname: Bundled\n---\n').toString('base64') - const output = [ - record('R', '0', '1'), - record( - 'S', - '0', - '/home/alice/.codex/skills/.system/bundled/SKILL.md', - '/home/alice/.codex/skills/.system/bundled/SKILL.md', - '1700000000', - markdown - ) - ].join('') - - expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, ['home']).skills).toEqual([]) - expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, []).skills).toHaveLength(1) - expect(parseWslSkillDiscoveryOutput(output, [homeRoot], 42, [], [' ']).skills).toHaveLength(1) - }) - - it('keeps ASCII prefiltering for mixed-locale requested names', () => { - const script = buildWslSkillDiscoveryCommand([homeRoot], ['orchestration', 'hébergement']) - - expect(script).toContain("'orchestration') return 0") - expect(script).not.toContain('hébergement) return 0') - expect(script).toContain('is_ascii_name "$directory_name"') - }) - it('uses the TypeScript summary parser for uncertain WSL name candidates', () => { const blockName = Buffer.from('\uFEFF---\nname: >-\n Agent\n Orchestration\n---\n').toString( 'base64' @@ -163,36 +107,4 @@ describe('WSL skill discovery', () => { ).skills.map((skill) => skill.name) ).toEqual(['Agent Orchestration', 'Computer Use']) }) - - it('rejects malformed host responses instead of reporting an empty scan', () => { - expect(() => parseWslSkillDiscoveryOutput(record('S', '9'), [homeRoot])).toThrow( - 'unknown source' - ) - }) -}) - -it('reuses one source collator while preserving locale, lexical numbers, and stable ties', () => { - const labels = Array.from( - { length: 200 }, - (_, index) => - ['éclair', 'Eclair', 'item2', 'item10', 'Ångström', 'zebra', 'İstanbul'][index % 7] - ) - const roots = labels.map((label, index) => ({ ...homeRoot, id: String(index), label })) - const expected = [...roots].sort((a, b) => - // ast-grep-ignore: no-repeated-collator -- Preserve the old comparator as the parity oracle. - a.label.localeCompare(b.label, undefined, { sensitivity: 'base' }) - ) - const NativeCollator = Intl.Collator - const construct = vi.spyOn(Intl, 'Collator').mockImplementation(function (locales, options) { - return new NativeCollator(locales, options) - }) - const localeCompare = vi.spyOn(String.prototype, 'localeCompare') - try { - const result = parseWslSkillDiscoveryOutput('', roots, 42) - expect(result.sources.map((source) => source.id)).toEqual(expected.map((root) => root.id)) - expect(construct).toHaveBeenCalledExactlyOnceWith(undefined, { sensitivity: 'base' }) - expect(localeCompare).not.toHaveBeenCalled() - } finally { - vi.restoreAllMocks() - } }) diff --git a/src/main/ssh/config/ssh-config-alias-claim.test.ts b/src/main/ssh/config/ssh-config-alias-claim.test.ts index 4af00f8ce95..2ee7a5f89ea 100644 --- a/src/main/ssh/config/ssh-config-alias-claim.test.ts +++ b/src/main/ssh/config/ssh-config-alias-claim.test.ts @@ -16,16 +16,6 @@ Host * expect(mayClaim(config, 'prod')).toBe(false) }) - it('keeps a Host block that names the alias authoritative', () => { - const config = ` -Host * - ProxyCommand nc %h %p -Host prod - HostName prod.internal -` - expect(mayClaim(config, 'prod')).toBe(true) - }) - it('keeps a glob that reaches the alias authoritative', () => { // parseSshConfig drops these, which is why the claim check cannot reuse it. const config = ` @@ -56,24 +46,4 @@ Match host prod expect(mayClaim('Host * !prod\n ForwardAgent yes\n', 'stage')).toBe(true) expect(mayClaim('Host * !prod\n ForwardAgent yes\n', 'prod')).toBe(true) }) - - it('still proves absence when no group negates', () => { - expect(mayClaim('Host *\n ForwardAgent yes\nHost prod\n User ops\n', 'stage')).toBe(false) - }) - - it('reads an unreadable config as uncertainty, not absence', () => { - expect(sshConfigMayClaimAlias('prod', null)).toBe(true) - }) - - it('reads an empty alias as uncertainty', () => { - expect(sshConfigMayClaimAlias('', parseSshConfigAliasClaims('Host *\n'))).toBe(true) - }) -}) - -describe('parseSshConfigAliasClaims', () => { - it('retains the raw pattern groups and flags Match blocks', () => { - expect( - parseSshConfigAliasClaims('Host a b* # comment\n User x\nMatch final\n User y\n') - ).toEqual({ hostPatternGroups: [['a', 'b*']], hasMatchBlock: true }) - }) }) diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts deleted file mode 100644 index c93864f7c81..00000000000 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - canRunHostileHostCell, - forbiddenToolActions, - forbiddenToolsFor, - forbiddenToolShimScript, - HOSTILE_HOST_CELLS, - isLocalSshdCell, - selectHostileHostCells, - type DockerHostileHostCell, - type HostileHostCell -} from './ssh-hostile-host-cells' -import { hostileHostDockerfile } from './ssh-hostile-host-test-fixture' - -const LINUX = { platform: 'linux', arch: 'x64' } as const -const MAC_ARM = { platform: 'darwin', arch: 'arm64' } as const -const DOCKER_CELLS = HOSTILE_HOST_CELLS.filter( - (candidate): candidate is DockerHostileHostCell => !isLocalSshdCell(candidate) -) - -function dockerCell(id: string): DockerHostileHostCell { - const found = DOCKER_CELLS.find((candidate) => candidate.id === id) - if (!found) { - throw new Error(`no docker cell ${id}`) - } - return found -} - -function cell(id: string): HostileHostCell { - const found = HOSTILE_HOST_CELLS.find((candidate) => candidate.id === id) - if (!found) { - throw new Error(`no cell ${id}`) - } - return found -} - -describe('hostile-host cells', () => { - it('states a managed orcad expectation for every host the matrix runs', () => { - expect(HOSTILE_HOST_CELLS.map((c) => [c.id, c.managed.runtime, c.managed.outcome])).toEqual([ - ['debian10-glibc228', 'linux-x64-glibc', 'activated'], - ['almalinux8-glibc228', 'linux-x64-glibc', 'activated'], - ['alpine-musl', 'linux-x64-musl', 'activated'], - ['alpine-musl-no-libstdcxx', 'linux-x64-musl', 'unavailable'], - ['ubuntu2204-noexec-home', 'linux-x64-glibc', 'unavailable'], - ['centos7-glibc217', 'linux-x64-glibc217', 'activated'], - ['debian10-no-egress', 'linux-x64-glibc', 'activated'], - ['almalinux8-desktop-no-egress', 'linux-x64-glibc', 'activated'], - ['macos-arm64-local-sshd', 'darwin-arm64', 'activated'], - ['macos-x64-local-sshd', 'darwin-x64', 'activated'] - ]) - }) - - it('pins every base image by digest and installs no compiler or host Node', () => { - for (const { dockerfile } of DOCKER_CELLS) { - for (const from of dockerfile.filter((line) => line.startsWith('FROM '))) { - expect(from).toMatch(/@sha256:[0-9a-f]{64}\b/) - } - expect(dockerfile.join('\n')).not.toMatch(/\b(?:gcc|g\+\+|build-essential|nodejs|npm)\b/) - } - }) - - it('shims the toolchain and starts sshd in every image', () => { - const dockerfile = hostileHostDockerfile(dockerCell('alpine-musl')) - expect(dockerfile.startsWith('FROM alpine:3.20@sha256:')).toBe(true) - expect(dockerfile).toContain('ln -sf orca-forbidden-tool /usr/local/bin/npm') - expect(dockerfile).toContain('ln -sf orca-forbidden-tool /usr/local/bin/gcc') - expect(dockerfile.trimEnd().endsWith('CMD ["/orca-entrypoint.sh"]')).toBe(true) - }) - - it('selects named cells this machine can host and rejects unknown ones', () => { - expect(selectHostileHostCells(undefined, HOSTILE_HOST_CELLS, LINUX)).toEqual(DOCKER_CELLS) - expect(selectHostileHostCells(' ', HOSTILE_HOST_CELLS, LINUX)).toEqual(DOCKER_CELLS) - expect( - selectHostileHostCells('alpine-musl, centos7-glibc217', HOSTILE_HOST_CELLS, LINUX).map( - (c) => c.id - ) - ).toEqual(['alpine-musl', 'centos7-glibc217']) - expect(() => selectHostileHostCells('alpine-musl,solaris', HOSTILE_HOST_CELLS, LINUX)).toThrow( - 'Unknown hostile-host cells: solaris' - ) - }) - - it('runs a macOS cell only on its own OS and arch, and no Docker cell there', () => { - expect(selectHostileHostCells('', HOSTILE_HOST_CELLS, MAC_ARM).map((c) => c.id)).toEqual([ - 'macos-arm64-local-sshd' - ]) - expect( - selectHostileHostCells('macos-arm64-local-sshd', HOSTILE_HOST_CELLS, MAC_ARM).map((c) => c.id) - ).toEqual(['macos-arm64-local-sshd']) - expect(() => - selectHostileHostCells('alpine-musl,macos-arm64-local-sshd', HOSTILE_HOST_CELLS, LINUX) - ).toThrow('cannot run on linux-x64: macos-arm64-local-sshd') - expect(() => - selectHostileHostCells('macos-x64-local-sshd', HOSTILE_HOST_CELLS, MAC_ARM) - ).toThrow('cannot run on darwin-arm64: macos-x64-local-sshd') - expect(canRunHostileHostCell(cell('macos-x64-local-sshd'), MAC_ARM)).toBe(false) - expect( - canRunHostileHostCell(cell('macos-x64-local-sshd'), { platform: 'darwin', arch: 'x64' }) - ).toBe(true) - }) - - it('forbids xattr only on the macOS runners', () => { - expect(forbiddenToolsFor(cell('macos-arm64-local-sshd'))).toContain('xattr') - expect(forbiddenToolsFor(cell('debian10-glibc228'))).not.toContain('xattr') - }) - - it('writes a shim that logs its own name and arguments, then fails like a missing tool', () => { - expect(forbiddenToolShimScript('/tmp/x/calls.log')).toBe( - `#!/bin/sh\nprintf '%s %s\\n' "\${0##*/}" "$*" >> '/tmp/x/calls.log'\nexit 127\n` - ) - }) - - it('reports logged installs and compiles but not version probes', () => { - expect(forbiddenToolActions('npm install\n\ngcc -v\nnpm --version\nmake all\n')).toEqual([ - 'npm install', - 'make all' - ]) - }) -}) diff --git a/src/main/ssh/orcad-fence-lost-classification.test.ts b/src/main/ssh/orcad-fence-lost-classification.test.ts index 7b0144d51c9..36f3316b61e 100644 --- a/src/main/ssh/orcad-fence-lost-classification.test.ts +++ b/src/main/ssh/orcad-fence-lost-classification.test.ts @@ -9,14 +9,12 @@ import { import { ORCAD_FENCE_LOST_MARKER, OrcadFenceLostError, - isOrcadFenceLost, posixOrcadFenceGuard, runWithOrcadFence } from '../managed-server/activation/orcad-activation-fence-scope' -import { - isUnconfirmedSshCommandTermination, - sshCommandExitError -} from './remote-exec/remote-exec-command' + +import { isUnconfirmedSshCommandTermination } from './remote-exec/remote-exec-command' + import { getRemoteHostPlatform } from './ssh-remote-platform' import type { OrcadHostTransport } from './orcad-host-transport' @@ -86,14 +84,6 @@ describe('a fenced step through the real exec', () => { expect(error).toMatchObject({ exitCode: 1, stdout: 'boom\n' }) }) - it('lets a failed step fall back', async () => { - const answer = await settledAfter( - fenced(() => execOrcadRemoteOr(target, 'false', 'FALLBACK')), - () => channel.exit(1, '') - ) - expect(answer).toBe('FALLBACK') - }) - it('keeps a timed-out step unconfirmed, so the fence is not released under it', async () => { const settled = fenced(() => execOrcadRemoteOr(target, 'sleep 99', 'FALLBACK')).catch( (error: unknown) => error @@ -139,13 +129,3 @@ describe('a fenced state mutation through the real exec', () => { expect(error).toBeInstanceOf(OrcadFenceLostError) }) }) - -describe('a Windows host op whose exit PowerShell flattened to 1', () => { - it('is a lost fence only when the host script printed the marker', () => { - const op = `powershell.exe -Command "& 'node.exe' 'host.js' --fence d t ${ORCAD_FENCE_LOST_MARKER}"` - expect(isOrcadFenceLost(sshCommandExitError(op, 1, `${ORCAD_FENCE_LOST_MARKER}\r\n`))).toBe( - true - ) - expect(isOrcadFenceLost(sshCommandExitError(op, 1, 'ENOENT\r\n'))).toBe(false) - }) -}) diff --git a/src/main/ssh/orcad-migration-path-rewrite.test.ts b/src/main/ssh/orcad-migration-path-rewrite.test.ts index 69ccabfbf6e..c675738b19e 100644 --- a/src/main/ssh/orcad-migration-path-rewrite.test.ts +++ b/src/main/ssh/orcad-migration-path-rewrite.test.ts @@ -1,17 +1,14 @@ import { describe, expect, it } from 'vitest' -import { - serializeOrcadMigrationValue, - type OrcadMigrationCatalogPayload -} from '../../shared/orcad-migration/orcad-migration-manifest' +import type { OrcadMigrationCatalogPayload } from '../../shared/orcad-migration/orcad-migration-manifest' + import { isRecord } from '../../shared/orcad-migration/orcad-migration-manifest-fields' import { ownedEditorFileId } from '../../shared/workspace-session-pane-ownership' import { ORCAD_MIGRATION_PATH_FIELDS, - ORCAD_MIGRATION_UNREWRITTEN_PATH_FIELDS, type OrcadMigrationPathFieldKind } from './orcad-migration-path-fields' + import { - IDENTITY_ORCAD_MIGRATION_PATH_REWRITER, parseFieldLocation, rewriteOrcadMigrationPayloadPaths, type OrcadMigrationPathRewriter @@ -125,24 +122,7 @@ function valuesAt(node: unknown, steps: ReturnType): return valuesAt(node[step.name], rest) } -function deepFreeze(value: T): T { - if (typeof value === 'object' && value !== null) { - Object.values(value).forEach(deepFreeze) - Object.freeze(value) - } - return value -} - describe('orcad migration path-rewrite stage', () => { - it('is exact under the identity: same value, same bytes, same key order, input untouched', () => { - const input = deepFreeze(payloadWithEveryField()) - const output = rewriteOrcadMigrationPayloadPaths(input, IDENTITY_ORCAD_MIGRATION_PATH_REWRITER) - expect(output).not.toBe(input) - expect(output).toEqual(input) - expect(JSON.stringify(output)).toBe(JSON.stringify(input)) - expect(serializeOrcadMigrationValue(output)).toBe(serializeOrcadMigrationValue(input)) - }) - // Guard against per-entry Object.keys calls that made 20k-key renames quadratic. it('walks a large keyed record in linear time', () => { const started = performance.now() @@ -150,27 +130,6 @@ describe('orcad migration path-rewrite stage', () => { expect(performance.now() - started).toBeLessThan(2_000) }) - it('reaches every field the table names', () => { - const input = deepFreeze(payloadWithEveryField()) - const output = rewriteOrcadMigrationPayloadPaths(input, MARKING) - for (const field of ORCAD_MIGRATION_PATH_FIELDS) { - const values = valuesAt(output, parseFieldLocation(field.at)) - expect(values, field.at).not.toEqual([]) - for (const value of values) { - expect(value, field.at).not.toBe(SAMPLE[field.kind]) - expect(String(value), field.at).not.toMatch(/\/src\/|%2Fsrc%2F|^rel\//) - } - } - }) - - it('names every location once, and never both rewrites and skips one', () => { - const rewritten = ORCAD_MIGRATION_PATH_FIELDS.map((field) => field.at) - expect(new Set(rewritten).size).toBe(rewritten.length) - for (const skipped of ORCAD_MIGRATION_UNREWRITTEN_PATH_FIELDS) { - expect(rewritten).not.toContain(skipped.at) - } - }) - it('rewrites only the path half of composite ids', () => { const map = (kind: OrcadMigrationPathFieldKind, value: string): unknown => { const field = ORCAD_MIGRATION_PATH_FIELDS.find((entry) => entry.kind === kind)! diff --git a/src/main/ssh/targets/ssh-target-identity.test.ts b/src/main/ssh/targets/ssh-target-identity.test.ts index 99564e60b55..814123e8b36 100644 --- a/src/main/ssh/targets/ssh-target-identity.test.ts +++ b/src/main/ssh/targets/ssh-target-identity.test.ts @@ -10,14 +10,6 @@ const route = (overrides: Partial = {}): SshRoute => ({ }) describe('sshRouteKey', () => { - it('keeps aliases apart when a shared ProxyCommand names the alias with %n', () => { - const proxy = { kind: 'proxy-command' as const, command: 'docker exec -i %n nc localhost 22' } - - expect(sshRouteKey(route({ alias: 'dev1', proxy }))).not.toBe( - sshRouteKey(route({ alias: 'dev2', proxy })) - ) - }) - it('matches a route whose tokens expand to the same command', () => { expect( sshRouteKey(route({ proxy: { kind: 'proxy-command', command: 'ssh bastion -W %h:%p' } })) diff --git a/src/main/ssh/targets/ssh-target-orcad-preflight.test.ts b/src/main/ssh/targets/ssh-target-orcad-preflight.test.ts index 8601d9fe998..5423e608a52 100644 --- a/src/main/ssh/targets/ssh-target-orcad-preflight.test.ts +++ b/src/main/ssh/targets/ssh-target-orcad-preflight.test.ts @@ -2,7 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import type { SshRemotePtyLease, SshTarget } from '../../../shared/ssh-types' +import type { SshTarget } from '../../../shared/ssh-types' + import { closeTestStores, createSqliteTestStore } from '../../persistence/persistence-test-harness' import { Store } from '../../persistence/loading-store/store' import { @@ -71,68 +72,6 @@ describe('migration export preflight', () => { ]) }) - it('previews a connected but unused host as movable with no blockers', () => { - const store = preflightStore((store) => { - store.addSshTarget(TARGET) - // Connect writes this reconnect hint before migration preflight. - store.patchWorkspaceSession({ activeConnectionIdsAtShutdown: [TARGET.id] }) - }) - expect(preflightOrcadMigrationExport(store, TARGET.id)).toMatchObject({ - claimable: true, - blockers: [] - }) - }) - - it('blocks on a live relay terminal, which cannot move', () => { - const lease: SshRemotePtyLease = { - targetId: TARGET.id, - ptyId: 'pty-1', - state: 'attached', - createdAt: 1, - updatedAt: 1 - } - const result = preflightOrcadMigrationExport( - preflightStore(withRepo, { getSshRemotePtyLeases: () => [lease] }), - TARGET.id - ) - expect(result.claimable).toBe(false) - expect(result.blockers.map((blocker) => blocker.code)).toContain( - 'orcad_migration_direct_ssh_terminal_leases' - ) - }) - - it('blocks on dependent state the manifest cannot carry', () => { - const result = preflightOrcadMigrationExport( - preflightStore(withRepo, { - inspectOrcadMigrationUntransferredDependencies: () => ({ - totalCount: 2, - counts: { - automation: 2, - 'automation-run': 0, - 'mobile-tab-selection': 0, - 'retired-worktree-name': 0, - 'saved-port-forward': 0, - 'sparse-preset': 0, - 'terminal-lease': 0, - 'terminal-recovery': 0, - 'ui-routing': 0, - 'workspace-lineage': 0, - 'workspace-session': 0, - 'worktree-lineage': 0, - 'worktree-metadata': 0 - } - }) - }), - TARGET.id - ) - expect(result.claimable).toBe(false) - expect(result.blockers).toContainEqual({ - code: 'orcad_migration_dependent_state', - category: 'client-owned-state', - dependencies: [{ kind: 'automation', count: 2 }] - }) - }) - it('treats a census the store could not take as unverifiable, never empty', () => { const result = preflightOrcadMigrationExport( preflightStore(withRepo, { @@ -147,33 +86,4 @@ describe('migration export preflight', () => { 'orcad_migration_dependency_unverifiable' ) }) - - it('refuses a target another runtime owns, and passes the owner only with its journal', () => { - const owned = preflightStore((store) => - store.addSshTarget({ ...TARGET, orcadFence: { environmentId: 'env-1' } }) - ) - expect(preflightOrcadMigrationExport(owned, TARGET.id).claimable).toBe(false) - expect( - preflightOrcadMigrationExport(owned, TARGET.id, { environmentId: 'env-1', recorded: true }) - .claimable - ).toBe(true) - expect( - preflightOrcadMigrationExport(owned, TARGET.id, { environmentId: 'env-1', recorded: false }) - ).toMatchObject({ - claimable: false, - blockers: [{ code: 'orcad_migration_owner_unrecorded' }] - }) - }) - - it('reports an unknown target', () => { - expect( - preflightOrcadMigrationExport( - preflightStore(() => {}), - 'missing' - ) - ).toMatchObject({ - claimable: false, - blockers: [{ code: 'orcad_migration_target_not_found' }] - }) - }) }) diff --git a/src/main/startup/windows-install-dir-package-acl-grant.test.ts b/src/main/startup/windows-install-dir-package-acl-grant.test.ts index 580418fdda7..aaca43a9c24 100644 --- a/src/main/startup/windows-install-dir-package-acl-grant.test.ts +++ b/src/main/startup/windows-install-dir-package-acl-grant.test.ts @@ -5,15 +5,11 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { resetWindowsSecurityLoadForTests, setWindowsSecurityForTests, - WINDOWS_FILE_READ_EXECUTE, type GrantAccessOptions, type WindowsSecurityAddon } from '../../shared/windows-security-addon' -import { - grantInstallDirPackageRoot, - grantInstallDirPackageTree, - RESTRICTED_APP_PACKAGES_SID -} from './windows-install-dir-package-acl-grant' + +import { grantInstallDirPackageTree } from './windows-install-dir-package-acl-grant' type GrantCall = { path: string @@ -75,61 +71,6 @@ describe('install-dir package grant passes', () => { rmSync(installDir, { recursive: true, force: true }) }) - it('grants the root once, inheritable, so files a later update writes inherit it', async () => { - const calls = installFakeAddon() - const outcome = await grantInstallDirPackageRoot(installDir) - expect(outcome).toEqual({ ok: true, failedFileCount: 0 }) - expect(calls).toEqual([ - { - path: installDir, - sid: RESTRICTED_APP_PACKAGES_SID, - accessMask: WINDOWS_FILE_READ_EXECUTE, - options: { inheritable: true, replace: false } - } - ]) - }) - - it('grants every file below the root flagless, and leaves the root to the root pass', async () => { - const calls = installFakeAddon() - const outcome = await grantInstallDirPackageTree(installDir) - expect(outcome).toEqual({ ok: true, failedFileCount: 0 }) - expect(calls.map((call) => call.path).sort()).toEqual( - [ - join(installDir, 'ffmpeg.dll'), - join(installDir, 'resources', 'app.asar.unpacked', 'addon.node') - ].sort() - ) - for (const call of calls) { - expect(call.sid).toBe(RESTRICTED_APP_PACKAGES_SID) - expect(call.accessMask).toBe(WINDOWS_FILE_READ_EXECUTE) - expect(call.options).toEqual({ inheritable: false, replace: false }) - } - }) - - // Re-granting inherited directories redundantly propagates entire subtrees. - it('grants a directory only when its own DACL is protected, inheritably', async () => { - const shielded = join(installDir, 'resources', 'app.asar.unpacked') - const calls = installFakeAddon(() => false, [shielded]) - await grantInstallDirPackageTree(installDir) - const directoryGrants = calls.filter((call) => !/\.(dll|node)$/.test(call.path)) - expect(directoryGrants).toEqual([ - { - path: shielded, - sid: RESTRICTED_APP_PACKAGES_SID, - accessMask: WINDOWS_FILE_READ_EXECUTE, - options: { inheritable: true, replace: false } - } - ]) - }) - - it('never replaces existing rules on either pass', async () => { - const calls = installFakeAddon() - await grantInstallDirPackageRoot(installDir) - await grantInstallDirPackageTree(installDir) - expect(calls.length).toBeGreaterThan(1) - expect(calls.every((call) => call.options.replace === false)).toBe(true) - }) - it('does not follow a link out of the install tree', async (context) => { const outside = mkdtempSync(join(tmpdir(), 'orca-acl-grant-outside-')) writeFileSync(join(outside, 'elsewhere.dll'), 'binary') @@ -160,56 +101,4 @@ describe('install-dir package grant passes', () => { expect(outcome.failedFileCount).toBe(2) expect(outcome.reason).toMatch(/^failed-files: .*Win32 error 5/) }) - - it('counts a failed root grant as one failed entry', async () => { - installFakeAddon(() => true) - const outcome = await grantInstallDirPackageRoot(installDir) - expect(outcome).toMatchObject({ ok: false, failedFileCount: 1 }) - expect(outcome.reason).toContain('Win32 error 5') - }) - - it('reports an unavailable addon instead of granting anything', async () => { - setWindowsSecurityForTests(null) - expect(await grantInstallDirPackageRoot(installDir)).toEqual({ - ok: false, - failedFileCount: 0, - reason: 'addon-unavailable' - }) - expect(await grantInstallDirPackageTree(installDir)).toEqual({ - ok: false, - failedFileCount: 0, - reason: 'addon-unavailable' - }) - }) - - // Windows security APIs need extended-length paths beyond MAX_PATH; the host wrapper namespaces once. - it.runIf(process.platform === 'win32')( - 'reaches a path past MAX_PATH through the extended-length prefix', - async () => { - const calls = installFakeAddon() - const longDir = `C:\\Program Files\\${'orca'.repeat(70)}` - const seen: string[] = [] - setWindowsSecurityForTests({ - currentUserSid: () => 'S-1-5-21-1-2-3-1001', - getDaclAces: unexpected, - setDaclSddl: unexpected, - setDaclSddlAsync: unexpected, - createFileWithDacl: unexpected, - readFileWithDacl: unexpected, - readGenericCredential: unexpected, - writeGenericCredential: unexpected, - grantAccess: unexpected, - clearStdHandleInheritance: unexpected, - spawnDetachedIsolated: unexpected, - isolatedSpawnBreaksAwayFromJob: unexpected, - hasNativeExport: unexpected, - grantAccessAsync: async (path) => { - seen.push(path) - } - }) - await grantInstallDirPackageRoot(longDir) - expect(calls).toEqual([]) - expect(seen).toEqual([`\\\\?\\${longDir}`]) - } - ) }) diff --git a/src/main/text-generation/commit-message-text-generation-linked-issue.test.ts b/src/main/text-generation/commit-message-text-generation-linked-issue.test.ts deleted file mode 100644 index b85bc197315..00000000000 --- a/src/main/text-generation/commit-message-text-generation-linked-issue.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - generateBranchNameFromContext, - generateCommitMessageFromContext, - generatePullRequestFieldsFromContext -} from './commit-message-text-generation' - -describe('linkedIssue template substitution', () => { - const COMMIT_CONTEXT = { - branch: 'feature/login', - stagedSummary: 'M src/login.ts', - stagedPatch: 'diff --git a/src/login.ts b/src/login.ts' - } - const PULL_REQUEST_CONTEXT = { - branch: 'feature/login', - base: 'main', - branchChangedByPreparation: false, - currentTitle: 'Fix login', - currentBody: '', - currentDraft: false, - commitSummary: 'a1b2c3d Fix login', - changeSummary: 'src/login.ts | 4 ++--', - patch: 'diff --git a/src/login.ts b/src/login.ts' - } - - function capturingTarget(capture: (prompt: string) => void): { - kind: 'remote' - cwd: string - missingBinaryLocation: string - execute: (plan: { stdinPayload: string | null }) => Promise<{ - stdout: string - stderr: string - exitCode: number - timedOut: boolean - }> - } { - return { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async (plan) => { - capture(plan.stdinPayload ?? '') - return { - stdout: '{"base":"main","title":"Fix login","body":"body","draft":false}', - stderr: '', - exitCode: 0, - timedOut: false - } - } - } - } - - const templateParams = { - agentId: 'custom' as const, - model: '', - customAgentCommand: 'agent', - commandInputTemplate: '{basePrompt}\n\nFixes #{linkedIssue}' - } - - it('substitutes the linked issue into the commit-message prompt', async () => { - let prompt = '' - await generateCommitMessageFromContext( - { ...COMMIT_CONTEXT, linkedIssue: 42 }, - templateParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain('Fixes #42') - expect(prompt).not.toContain('{linkedIssue}') - }) - - it('renders an empty commit-message issue for null and omitted fields', async () => { - for (const context of [{ ...COMMIT_CONTEXT, linkedIssue: null }, COMMIT_CONTEXT]) { - let prompt = '' - await generateCommitMessageFromContext( - context, - templateParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain('Fixes #') - expect(prompt).not.toContain('{linkedIssue}') - } - }) - - // Use a unique issue sentinel; small numbers can also occur in prompt-truncation character counts. - const BUILT_IN_PROMPT_SENTINEL_ISSUE = 987654 - const builtInPromptParams = { - agentId: 'custom' as const, - model: '', - customAgentCommand: 'agent' - } - - it('leaves the built-in commit prompt free of issue guidance', async () => { - let prompt = '' - await generateCommitMessageFromContext( - { ...COMMIT_CONTEXT, linkedIssue: BUILT_IN_PROMPT_SENTINEL_ISSUE }, - builtInPromptParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).not.toContain(String(BUILT_IN_PROMPT_SENTINEL_ISSUE)) - expect(prompt).not.toContain('linkedIssue') - }) - - it('includes the linked issue in the built-in pull-request prompt', async () => { - let prompt = '' - await generatePullRequestFieldsFromContext( - { - ...PULL_REQUEST_CONTEXT, - linkedIssue: BUILT_IN_PROMPT_SENTINEL_ISSUE, - provider: 'gitlab', - linkedIssueDetails: { - provider: 'gitlab', - number: BUILT_IN_PROMPT_SENTINEL_ISSUE, - title: 'Stop phantom polling', - description: 'Avoid paths that cannot exist on this host.' - } - }, - builtInPromptParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain(`Linked GitLab issue: #${BUILT_IN_PROMPT_SENTINEL_ISSUE}`) - expect(prompt).toContain(`Closes #${BUILT_IN_PROMPT_SENTINEL_ISSUE}`) - expect(prompt).toContain(`Related to #${BUILT_IN_PROMPT_SENTINEL_ISSUE}`) - expect(prompt).toContain('Stop phantom polling') - expect(prompt).toContain('Avoid paths that cannot exist on this host.') - expect(prompt).not.toContain('GitHub issue') - }) - - it('substitutes the linked issue into the pull-request prompt', async () => { - let prompt = '' - await generatePullRequestFieldsFromContext( - { ...PULL_REQUEST_CONTEXT, linkedIssue: 7 }, - templateParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain('Fixes #7') - expect(prompt).not.toContain('{linkedIssue}') - }) - - it('renders an empty pull-request issue when none resolves', async () => { - let prompt = '' - await generatePullRequestFieldsFromContext( - PULL_REQUEST_CONTEXT, - templateParams, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain('Fixes #') - expect(prompt).not.toContain('{linkedIssue}') - }) - - it('leaves a hand-typed linkedIssue literal in branch-name templates', async () => { - let prompt = '' - await generateBranchNameFromContext( - { firstPrompt: 'Fix login flow' }, - { ...templateParams, commandInputTemplate: '{basePrompt}\n\nIssue {linkedIssue}' }, - capturingTarget((value) => { - prompt = value - }) - ) - - expect(prompt).toContain('Issue {linkedIssue}') - }) -}) diff --git a/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts b/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts index 0308275ac81..6cb496d90e5 100644 --- a/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts +++ b/src/main/text-generation/commit-message-text-generation-remote-execution.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - createSshDisposalError, - SSH_MUX_REQUEST_TIMEOUT_CODE -} from '../ssh/ssh-channel-multiplexer' + import { generateCommitMessageFromContext } from './commit-message-text-generation' describe('generateCommitMessageFromContext', () => { @@ -46,69 +43,6 @@ describe('generateCommitMessageFromContext', () => { }) }) - it('reports a remote transport timeout without claiming the agent is unreachable', async () => { - const transportTimeout = Object.assign( - new Error('Request "agent.execNonInteractive" timed out after 65000ms'), - { code: SSH_MUX_REQUEST_TIMEOUT_CODE } - ) - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => { - throw transportTimeout - } - } - ) - - expect(result).toEqual({ - success: false, - error: 'agent took longer than 60s to respond and may still be running on the remote host.', - canceled: undefined - }) - }) - - it('keeps the unverifiable wording when the link is declared lost instead of timing out', async () => { - // Both lost mux and response timeout mean dispatched work may still run; neither proves the host was never reached (ssh-execution-boundary.md). - const result = await generateCommitMessageFromContext( - { - branch: 'main', - stagedSummary: 'M\tREADME.md', - stagedPatch: '+hello' - }, - { - agentId: 'custom', - model: '', - customAgentCommand: 'agent' - }, - { - kind: 'remote', - cwd: '/repo', - missingBinaryLocation: 'remote PATH', - execute: async () => { - throw createSshDisposalError('connection_lost') - } - } - ) - - expect(result).toEqual({ - success: false, - error: 'agent took longer than 60s to respond and may still be running on the remote host.', - canceled: undefined - }) - }) - it('sanitizes remote execution transport failures', async () => { const result = await generateCommitMessageFromContext( { diff --git a/src/main/worktree-create-execution-host-route.test.ts b/src/main/worktree-create-execution-host-route.test.ts deleted file mode 100644 index 4d92206076b..00000000000 --- a/src/main/worktree-create-execution-host-route.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { ExecutionHostNotDispatchableError } from './providers/execution-host-provider-dispatch' -import type { Repo } from '../shared/repo-types' -import { - requireWorktreeCreateRoute, - resolveWorktreeCreateRoute -} from './worktree-create-execution-host-route' - -const HOST_A = 'target-a' - -function repoRow(fields: Partial): Repo { - return { - id: 'repo-1', - path: '/remote/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - ...fields - } as Repo -} - -describe('resolveWorktreeCreateRoute', () => { - it('routes a row that names its host only as executionHostId to that SSH target', () => { - expect(resolveWorktreeCreateRoute(repoRow({ executionHostId: 'ssh:target-a' }))).toEqual({ - kind: 'ssh', - hostId: 'ssh:target-a', - connectionId: HOST_A - }) - }) - - it('routes a legacy connectionId-only repo to the same SSH target', () => { - expect(resolveWorktreeCreateRoute(repoRow({ connectionId: HOST_A }))).toEqual({ - kind: 'ssh', - hostId: 'ssh:target-a', - connectionId: HOST_A - }) - }) - - it('lets an explicit local host win over a surviving connectionId', () => { - expect( - resolveWorktreeCreateRoute(repoRow({ executionHostId: 'local', connectionId: HOST_A })) - ).toEqual({ kind: 'local', hostId: 'local' }) - }) - - it('answers runtime for a runtime row with no nested SSH target', () => { - expect(resolveWorktreeCreateRoute(repoRow({ executionHostId: 'runtime:env-1' }))).toEqual({ - kind: 'runtime', - hostId: 'runtime:env-1', - environmentId: 'env-1' - }) - }) - - it('answers runtime for a runtime row that also names a nested target', () => { - expect( - resolveWorktreeCreateRoute( - repoRow({ executionHostId: 'runtime:env-1', connectionId: HOST_A }) - ) - ).toMatchObject({ kind: 'runtime', environmentId: 'env-1' }) - }) -}) - -describe('requireWorktreeCreateRoute', () => { - it('refuses a runtime host rather than creating through this client', () => { - expect(() => requireWorktreeCreateRoute(repoRow({ executionHostId: 'runtime:env-1' }))).toThrow( - ExecutionHostNotDispatchableError - ) - }) - - it('passes local and SSH hosts through unchanged', () => { - expect(requireWorktreeCreateRoute(repoRow({}))).toEqual({ kind: 'local', hostId: 'local' }) - expect(requireWorktreeCreateRoute(repoRow({ executionHostId: 'ssh:target-a' }))).toMatchObject({ - kind: 'ssh', - connectionId: HOST_A - }) - }) -}) diff --git a/src/main/worktree-removal-execution-host-route.test.ts b/src/main/worktree-removal-execution-host-route.test.ts deleted file mode 100644 index 1187fb4d36b..00000000000 --- a/src/main/worktree-removal-execution-host-route.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { ExecutionHostNotDispatchableError } from './providers/execution-host-provider-dispatch' -import { SshHostNotServedError } from './providers/ssh-host-not-served-error' -import type { ExecutionHostId } from '../shared/execution-host' -import { - resolveWorktreeRemovalHome, - resolveWorktreeRemovalHomeForHost, - resolveWorktreeRemovalRoute -} from './worktree-removal-execution-host-route' - -describe('resolveWorktreeRemovalRoute', () => { - it('routes a local host to this machine', () => { - expect(resolveWorktreeRemovalRoute('local')).toEqual({ kind: 'local', hostId: 'local' }) - }) - - it('refuses an SSH host with the typed not-served error instead of answering local', () => { - expect(() => resolveWorktreeRemovalRoute('ssh:target-a')).toThrow(SshHostNotServedError) - }) - - it('refuses a runtime host with no nested SSH target', () => { - expect(() => resolveWorktreeRemovalRoute('runtime:env-1')).toThrow( - ExecutionHostNotDispatchableError - ) - }) -}) - -describe('resolveWorktreeRemovalHome', () => { - it('keeps a local removal on this client s home', () => { - expect(resolveWorktreeRemovalHome(resolveWorktreeRemovalRoute('local'))).toEqual({ - kind: 'client' - }) - }) -}) - -describe('resolveWorktreeRemovalHomeForHost', () => { - it('never answers an ssh host id with this client s home', () => { - expect(resolveWorktreeRemovalHomeForHost('ssh:target-a')).toEqual({ - kind: 'executionHost', - homePath: null - }) - }) - - it('keeps the client home for the local host', () => { - expect(resolveWorktreeRemovalHomeForHost('local')).toEqual({ kind: 'client' }) - }) - - it('refuses to answer a runtime host with this client s home', () => { - expect(resolveWorktreeRemovalHomeForHost('runtime:env-1')).toEqual({ - kind: 'executionHost', - homePath: null - }) - }) - - it('refuses to answer an id that names no host', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: host ids also arrive from persistence and IPC, where the compiler cannot vouch for them; this pins what an unparseable one answers. - expect(resolveWorktreeRemovalHomeForHost('nonsense' as ExecutionHostId)).toEqual({ - kind: 'executionHost', - homePath: null - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.test.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.test.ts index 9d9271da1b1..73f95c44063 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-input-model.test.ts @@ -1,116 +1,10 @@ import { describe, expect, it } from 'vitest' import { - buildRemoteContextMenuExpression, - getPositiveFiniteNumber, - getRemoteBrowserMouseButton, mapRemoteBrowserClientPoint, - readRemoteContextMenuResult, - readRemoteCssViewportSize, resolveRemoteBrowserCssViewport } from './remote-browser-page-input-model' describe('remote browser page input model', () => { - it('maps mouse buttons and rejects unknown codes', () => { - expect(getRemoteBrowserMouseButton(0)).toBe('left') - expect(getRemoteBrowserMouseButton(1)).toBe('middle') - expect(getRemoteBrowserMouseButton(2)).toBe('right') - expect(getRemoteBrowserMouseButton(3)).toBeNull() - }) - - it('accepts only positive finite numbers', () => { - expect(getPositiveFiniteNumber(12)).toBe(12) - expect(getPositiveFiniteNumber(0)).toBeNull() - expect(getPositiveFiniteNumber(-1)).toBeNull() - expect(getPositiveFiniteNumber(Number.NaN)).toBeNull() - expect(getPositiveFiniteNumber('12')).toBeNull() - }) - - it('embeds coordinates in the guest context-menu expression', () => { - const expression = buildRemoteContextMenuExpression(10, 20) - expect(expression).toContain('10') - expect(expression).toContain('20') - expect(expression).toContain('elementFromPoint') - }) - - it('parses context-menu eval results and rejects junk', () => { - expect(readRemoteContextMenuResult(null)).toBeNull() - expect(readRemoteContextMenuResult({ result: 1 })).toBeNull() - expect( - readRemoteContextMenuResult({ - result: JSON.stringify({ - linkUrl: 'https://example.com', - pageUrl: 'https://example.com/page', - selectionText: 'hi' - }) - }) - ).toEqual({ - linkUrl: 'https://example.com', - pageUrl: 'https://example.com/page', - selectionText: 'hi' - }) - expect(readRemoteContextMenuResult({ result: JSON.stringify({ linkUrl: '' }) })).toEqual({ - linkUrl: null, - pageUrl: 'about:blank', - selectionText: '' - }) - }) - - it('parses CSS viewport sizes from eval results', () => { - expect( - readRemoteCssViewportSize({ result: JSON.stringify({ width: 800, height: 600 }) }) - ).toEqual({ width: 800, height: 600 }) - expect( - readRemoteCssViewportSize({ result: JSON.stringify({ width: 0, height: 600 }) }) - ).toBeNull() - expect(readRemoteCssViewportSize({ result: 'not-json' })).toBeNull() - }) - - describe('resolveRemoteBrowserCssViewport', () => { - const naturalSize = { width: 2800, height: 1800 } - - it('keeps the cached CSS viewport while frames report the size this pane requested', () => { - expect( - resolveRemoteBrowserCssViewport({ - // Scrollbars can make innerWidth differ from the requested size, so prefer the cached CSS viewport. - cssViewportSize: { width: 1385, height: 900 }, - requestedViewportSize: { width: 1400, height: 900 }, - frameMetadata: { deviceWidth: 1400, deviceHeight: 900 }, - naturalSize - }) - ).toEqual({ width: 1385, height: 900 }) - }) - - it('falls back to the frame device size once another subscriber owns the viewport', () => { - expect( - resolveRemoteBrowserCssViewport({ - cssViewportSize: { width: 1385, height: 900 }, - requestedViewportSize: { width: 1400, height: 900 }, - frameMetadata: { deviceWidth: 390, deviceHeight: 844 }, - naturalSize - }) - ).toEqual({ width: 390, height: 844 }) - }) - - it('keeps the cache when frames carry no device size and falls back to natural size', () => { - expect( - resolveRemoteBrowserCssViewport({ - cssViewportSize: { width: 1385, height: 900 }, - requestedViewportSize: { width: 1400, height: 900 }, - frameMetadata: null, - naturalSize - }) - ).toEqual({ width: 1385, height: 900 }) - expect( - resolveRemoteBrowserCssViewport({ - cssViewportSize: null, - requestedViewportSize: null, - frameMetadata: null, - naturalSize - }) - ).toEqual(naturalSize) - }) - }) - // Map input through the same contained frame box when the host cannot paint the requested pane size. describe('pointer mapping for a frame smaller than the pane', () => { const pane = { left: 0, top: 0, width: 1833, height: 1179 } @@ -153,16 +47,5 @@ describe('remote browser page input model', () => { mapRemoteBrowserClientPoint({ clientX: 10, clientY: 2, frameRect, cssViewport }) ).toEqual({ x: 8, y: 0 }) }) - - it('refuses a frame that has no box yet', () => { - expect( - mapRemoteBrowserClientPoint({ - clientX: 1, - clientY: 1, - frameRect: { left: 0, top: 0, width: 0, height: 0 }, - cssViewport - }) - ).toBeNull() - }) }) }) diff --git a/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts b/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts index b7b0c0dd34e..b51d2a70ddb 100644 --- a/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts +++ b/src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts @@ -1,8 +1,7 @@ import { describe, expect, it } from 'vitest' import { getCrashReportCopySubmissionFailure, - getCrashReportSubmitFailureNotice, - getCrashReportSubmitWarningNotice + getCrashReportSubmitFailureNotice } from './crash-report-submit-notice' describe('crash report submit notices', () => { @@ -24,77 +23,6 @@ describe('crash report submit notices', () => { }) }) - it('keeps the returned error and points attached-log failures to the no-log retry', () => { - const notice = getCrashReportSubmitFailureNotice({ error: 'status 413' }, true) - - expect(notice).toEqual({ - title: "Crash report wasn't sent", - description: - 'status 413. Uncheck "Attach recent diagnostic logs" and try again, or copy the details.', - actionLabel: 'Copy Details' - }) - }) - - it('uses connection guidance when diagnostic logs were already excluded', () => { - const notice = getCrashReportSubmitFailureNotice({ error: 'network unreachable' }, false) - - expect(notice.description).toBe( - 'network unreachable. Check your connection and try again, or copy the details.' - ) - expect(notice.description).not.toContain('Uncheck') - }) - - it('preserves an uploaded diagnostic ticket alongside the core failure', () => { - const notice = getCrashReportSubmitFailureNotice( - { - error: 'status 502', - diagnosticBundle: { - status: 'uploaded', - ticketId: 'ticket-123', - bundleSubmissionId: 'bundle-123', - bytes: 42, - spanCount: 2 - } - }, - true - ) - - expect(notice.description).toContain('status 502.') - expect(notice.description).toContain( - 'Diagnostic ticket ticket-123 was uploaded but not linked.' - ) - }) - - it('shows both failures when the attachment was already omitted', () => { - const notice = getCrashReportSubmitFailureNotice( - { - error: 'fallback host unreachable', - diagnosticBundle: { - status: 'not_uploaded', - reason: 'diagnostic log attachment failed: request timed out after 60 seconds' - } - }, - true - ) - - expect(notice.description).toContain('fallback host unreachable.') - expect(notice.description).toContain( - 'Diagnostic logs were not attached: diagnostic log attachment failed: request timed out after 60 seconds.' - ) - expect(notice.description).toContain('Check your connection') - expect(notice.description).not.toContain('Uncheck') - }) - - it('safely surfaces Error messages and ignores unhelpful rejected values', () => { - expect( - getCrashReportSubmitFailureNotice({ error: new Error('IPC channel closed') }, false) - .description - ).toContain('IPC channel closed.') - expect( - getCrashReportSubmitFailureNotice({ error: { unexpected: true } }, false).description - ).toContain('The crash report request failed before it returned a reason.') - }) - it('redacts paths and tokens before displaying transport errors', () => { const token = `ghp_${'a'.repeat(30)}` const notice = getCrashReportSubmitFailureNotice( @@ -108,21 +36,4 @@ describe('crash report submit notices', () => { expect(notice.description).not.toContain(token) expect(notice.description).toContain('[redacted') }) - - it('warns only when an opted-in diagnostic bundle was not attached', () => { - const result = { - ok: true as const, - report: null, - diagnosticBundle: { - status: 'not_uploaded' as const, - reason: 'bundle collection failed' - } - } - - expect(getCrashReportSubmitWarningNotice(result, true)).toEqual({ - title: 'Crash report sent without diagnostic logs', - description: 'Diagnostic logs were not attached: bundle collection failed' - }) - expect(getCrashReportSubmitWarningNotice(result, false)).toBeNull() - }) }) diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts deleted file mode 100644 index 3e7edee8594..00000000000 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -// @vitest-environment happy-dom - -import { describe, expect, it } from 'vitest' -import type { GlobalSettings } from '../../../../shared/global-settings-types' -import { - buildPreviewAppearanceOptions, - buildPreviewTerminalOptions -} from './preview-terminal-options' - -const SETTINGS = { - terminalFontSize: 17, - terminalFontFamily: 'Fira Code', - terminalFontWeight: 500, - terminalFontWeightBold: 800, - terminalCursorStyle: 'bar', - terminalCursorBlink: false, - terminalLineHeight: 1.4, - terminalWordSeparator: ' ()[]', - terminalScrollSensitivity: 3 -} as unknown as GlobalSettings - -describe('buildPreviewAppearanceOptions', () => { - it('carries the user terminal appearance a pane would apply', () => { - const options = buildPreviewAppearanceOptions(SETTINGS, false) - expect(options.fontSize).toBe(17) - expect(options.fontFamily).toContain('Fira Code') - expect(options.fontWeight).toBe(500) - expect(options.fontWeightBold).toBe(800) - expect(options.cursorStyle).toBe('bar') - expect(options.cursorBlink).toBe(false) - expect(options.lineHeight).toBe(1.4) - expect(options.wordSeparator).toBe(' ()[]') - expect(options.scrollSensitivity).toBe(3) - // Why: a bar cursor's inactive style must not become xterm's block outline. - expect(options.cursorInactiveStyle).toBe('bar') - }) - - it('enables macOptionIsMeta only for the resolved full Option-as-Alt', () => { - expect(buildPreviewAppearanceOptions(SETTINGS, true).macOptionIsMeta).toBe(true) - expect(buildPreviewAppearanceOptions(SETTINGS, false).macOptionIsMeta).toBe(false) - }) - - it('falls back to pane defaults with no settings hydrated', () => { - const options = buildPreviewAppearanceOptions(null, false) - expect(options.fontSize).toBe(14) - expect(options.cursorBlink).toBe(true) - }) -}) - -describe('buildPreviewTerminalOptions', () => { - const base = { - settings: SETTINGS, - macOptionIsMeta: false, - theme: null, - themeMode: 'dark' as const, - cols: 100, - rows: 30, - scrollback: 1000 - } - - // Match the pane’s automatic contrast floor so the same live Powerline buffer renders consistently. - it('mirrors the automatic contrast floor when no override is set', () => { - expect( - buildPreviewTerminalOptions({ - ...base, - terminalInput: null, - theme: { background: '#1e242a' } - }).minimumContrastRatio - ).toBe(3) - expect( - buildPreviewTerminalOptions({ - ...base, - terminalInput: null, - theme: { background: '#ffffff' }, - themeMode: 'light' - }).minimumContrastRatio - ).toBe(4.5) - }) - - it('honors the user contrast override, clamped to xterm range', () => { - expect( - buildPreviewTerminalOptions({ - ...base, - terminalInput: null, - settings: { ...SETTINGS, terminalMinimumContrastRatio: 1 } - }).minimumContrastRatio - ).toBe(1) - expect( - buildPreviewTerminalOptions({ - ...base, - terminalInput: null, - settings: { ...SETTINGS, terminalMinimumContrastRatio: 0 } - }).minimumContrastRatio - ).toBe(1) - }) - - it('keeps the kitty advertisement and skips ConPTY options off Windows', () => { - const options = buildPreviewTerminalOptions({ - ...base, - terminalInput: { - hostPlatform: 'darwin', - localWindowsConpty: false, - windowsShiftEnterEncoding: 'alt-enter', - ctrlEnterCsiU: false, - kittyKeyboardAdvertised: true - } - }) - expect(options.vtExtensions?.kittyKeyboard).toBe(true) - expect(options.windowsPty).toBeUndefined() - expect(options.cols).toBe(100) - }) - - it('mirrors the ConPTY backend and kitty withhold a local Windows pane resolves', () => { - const options = buildPreviewTerminalOptions({ - ...base, - terminalInput: { - hostPlatform: 'win32', - localWindowsConpty: true, - osRelease: '10.0.22631', - windowsShiftEnterEncoding: 'alt-enter', - ctrlEnterCsiU: false, - kittyKeyboardAdvertised: false - } - }) - expect(options.windowsPty).toEqual({ backend: 'conpty', buildNumber: 22631 }) - expect(options.vtExtensions?.kittyKeyboard).toBe(false) - }) - - it('keeps the advertised default when the card carries no host profile', () => { - const options = buildPreviewTerminalOptions({ ...base, terminalInput: null }) - expect(options.vtExtensions?.kittyKeyboard).toBe(true) - expect(options.windowsPty).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/editor/editor-model-owner.test.ts b/src/renderer/src/components/editor/editor-model-owner.test.ts deleted file mode 100644 index 9af5c7e3e2e..00000000000 --- a/src/renderer/src/components/editor/editor-model-owner.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { OpenFile } from '@/store/slices/editor' -import type { - WorktreeOperationRoute, - WorktreeOperationRouteState -} from '@/lib/worktree-operation-route' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' -import { detachedEditorBufferId } from '@/store/slices/editor/buffers/editor-buffer-views' -import { getEditorModelOwnerKey } from './editor-model-owner' -import { toEditorModelUri } from './editor-model-uri' - -function file(overrides: Partial = {}): OpenFile { - return { - id: 'file', - filePath: '/srv/repo/file.ts', - relativePath: 'file.ts', - worktreeId: 'repo::/srv/repo', - language: 'typescript', - mode: 'edit', - isDirty: false, - ...overrides - } -} - -function captured(route: WorktreeOperationRoute): OpenFile['operationProvenance'] { - return { - ownershipProjection: 'explicit', - generation: { - route, - runtimeConnectionGeneration: null, - runtimePairingRevision: undefined, - runtimeSshGeneration: null, - nestedSshGeneration: null, - directSshGeneration: null - } - } -} - -const localState: WorktreeOperationRouteState = { - worktreesByRepo: { repo: [{ id: 'repo::/srv/repo', repoId: 'repo', hostId: 'local' }] } -} - -describe('editor model ownership', () => { - it('shares local physical files across workspace and tab identities', () => { - expect(getEditorModelOwnerKey(file(), localState)).toBe('') - expect( - getEditorModelOwnerKey( - file({ - id: 'other', - worktreeId: 'other', - operationProvenance: captured({ executionHostId: 'local', runtimeEnvironmentId: null }) - }), - {} - ) - ).toBe('') - }) - - it('keeps captured ownership when the focused host changes', () => { - const opened = file({ - operationProvenance: captured({ - executionHostId: 'ssh:target', - runtimeEnvironmentId: 'hub-a' - }) - }) - const key = getEditorModelOwnerKey(opened, {}) - expect( - getEditorModelOwnerKey(opened, { - ...localState, - activeWorktreeId: opened.worktreeId, - activeWorkspaceExecutionHostId: 'runtime:hub-b' - }) - ).toBe(key) - expect(key).toBe('["hub-a","ssh:target"]') - }) - - it('keeps distinct paired transports to the same target separate', () => { - const keys = ['hub-a', 'hub-b'].map((runtimeEnvironmentId) => - getEditorModelOwnerKey( - file({ - operationProvenance: captured({ executionHostId: 'ssh:target', runtimeEnvironmentId }) - }), - {} - ) - ) - expect(keys[0]).not.toBe(keys[1]) - expect(keys).not.toContain( - getEditorModelOwnerKey( - file({ externalSshTargetId: 'target', runtimeEnvironmentId: null }), - {} - ) - ) - }) - - it('uses the tab runtime hint when no owner catalog is present', () => { - expect(getEditorModelOwnerKey(file({ runtimeEnvironmentId: 'hub-a' }), {})).toBe( - '["hub-a","runtime:hub-a"]' - ) - expect(getEditorModelOwnerKey(file({ runtimeEnvironmentId: 'hub-b' }), {})).toBe( - '["hub-b","runtime:hub-b"]' - ) - }) - - it('honors an explicit local transport hint instead of the focused runtime', () => { - const opened = file({ runtimeEnvironmentId: null, externalSshTargetId: 'target' }) - const state: WorktreeOperationRouteState = { - worktreesByRepo: { - repo: [ - { - id: opened.worktreeId, - repoId: 'repo', - hostId: 'ssh:target', - runtimeOwnerEnvironmentId: 'hub-a' - } - ] - } - } - expect(getEditorModelOwnerKey(opened, state)).toBe('[null,"ssh:target"]') - }) - - it('does not adopt a new active host for a legacy local tab', () => { - const opened = file() - expect( - getEditorModelOwnerKey(opened, { - ...localState, - activeWorktreeId: opened.worktreeId, - activeWorkspaceExecutionHostId: 'ssh:new-target' - }) - ).toBe('') - }) - - it('keeps unresolved owners separate from local files', () => { - expect(getEditorModelOwnerKey(file(), {})).not.toBe('') - expect(getEditorModelOwnerKey(file(), {})).not.toBe( - getEditorModelOwnerKey(file({ worktreeId: 'another-owner' }), {}) - ) - }) - - it('supports local and remote folder workspaces', () => { - const opened = file({ worktreeId: folderWorkspaceKey('folder') }) - expect( - getEditorModelOwnerKey(opened, { - folderWorkspaces: [{ id: 'folder', projectGroupId: 'group', executionHostId: 'local' }] - }) - ).toBe('') - expect( - getEditorModelOwnerKey(opened, { - folderWorkspaces: [ - { id: 'folder', projectGroupId: 'group', executionHostId: 'runtime:hub-a' } - ] - }) - ).toBe('["hub-a","runtime:hub-a"]') - }) - - it('gives a detached record its own model, apart from the file and from other detached records', () => { - const shared = { ...localState, editorBufferIdOf: { file: 'file', other: 'file' } } - const detached = { - ...localState, - editorBufferIdOf: { file: detachedEditorBufferId('file'), other: 'file' } - } - const detachedUri = toEditorModelUri(file().filePath, getEditorModelOwnerKey(file(), detached)) - - expect(getEditorModelOwnerKey(file(), shared)).toBe('') - expect(getEditorModelOwnerKey(file({ id: 'other' }), detached)).toBe('') - expect(detachedUri).not.toBe(toEditorModelUri(file().filePath)) - expect(getEditorModelOwnerKey(file(), detached)).not.toBe( - getEditorModelOwnerKey(file({ id: 'other' }), { - ...localState, - editorBufferIdOf: { other: detachedEditorBufferId('other') } - }) - ) - // The host owner stays in the key: one detached record id on two hosts gets two models. - const remote = file({ runtimeEnvironmentId: 'env' }) - expect(getEditorModelOwnerKey(remote, detached)).not.toBe( - getEditorModelOwnerKey(file(), detached) - ) - expect(JSON.parse(getEditorModelOwnerKey(remote, detached))).toEqual([ - 'detached', - detachedEditorBufferId('file'), - getEditorModelOwnerKey(remote, localState) - ]) - }) -}) diff --git a/src/renderer/src/components/editor/markdown-rich-size-limit.test.ts b/src/renderer/src/components/editor/markdown-rich-size-limit.test.ts index 47a9447ce56..dbd3950b119 100644 --- a/src/renderer/src/components/editor/markdown-rich-size-limit.test.ts +++ b/src/renderer/src/components/editor/markdown-rich-size-limit.test.ts @@ -3,39 +3,10 @@ import { RICH_MARKDOWN_MAX_SIZE_BYTES } from '../../../../shared/constants' import { MARKDOWN_RENDER_OVERRIDE_MAX_SIZE_BYTES, canRenderMarkdownAtSize, - exceedsMarkdownRenderOverrideSizeLimit, - exceedsMarkdownRichModeSizeLimit + exceedsMarkdownRenderOverrideSizeLimit } from './markdown-rich-size-limit' -describe('exceedsMarkdownRichModeSizeLimit', () => { - it('uses a 600 KB default rich-mode ceiling', () => { - expect(RICH_MARKDOWN_MAX_SIZE_BYTES).toBe(600 * 1024) - }) - - it('allows markdown at the rich-mode byte limit', () => { - expect(exceedsMarkdownRichModeSizeLimit('a'.repeat(RICH_MARKDOWN_MAX_SIZE_BYTES))).toBe(false) - }) - - it('detects markdown over the byte limit', () => { - expect(exceedsMarkdownRichModeSizeLimit('a'.repeat(RICH_MARKDOWN_MAX_SIZE_BYTES + 1))).toBe( - true - ) - }) - - it('detects unread multibyte content at the byte boundary', () => { - expect( - exceedsMarkdownRichModeSizeLimit(`${'a'.repeat(RICH_MARKDOWN_MAX_SIZE_BYTES)}\u00e9`) - ).toBe(true) - }) -}) - describe('exceedsMarkdownRenderOverrideSizeLimit', () => { - it('allows exactly the override limit and rejects one byte over', () => { - const limit = MARKDOWN_RENDER_OVERRIDE_MAX_SIZE_BYTES - expect(exceedsMarkdownRenderOverrideSizeLimit('a'.repeat(limit))).toBe(false) - expect(exceedsMarkdownRenderOverrideSizeLimit('a'.repeat(limit + 1))).toBe(true) - }) - it('counts UTF-8 bytes, not UTF-16 length', () => { const limit = MARKDOWN_RENDER_OVERRIDE_MAX_SIZE_BYTES // 3-byte CJK chars: floor(limit / 3) fit, one more does not. diff --git a/src/renderer/src/components/editor/markdown-table-of-contents.test.ts b/src/renderer/src/components/editor/markdown-table-of-contents.test.ts index 74b245085d4..ed92bb4981d 100644 --- a/src/renderer/src/components/editor/markdown-table-of-contents.test.ts +++ b/src/renderer/src/components/editor/markdown-table-of-contents.test.ts @@ -1,8 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { - buildMarkdownTableOfContents, - stripInlineMarkdownForToc -} from './markdown-table-of-contents' +import { buildMarkdownTableOfContents } from './markdown-table-of-contents' afterEach(() => { vi.restoreAllMocks() @@ -121,21 +118,4 @@ describe('markdown table of contents', () => { title: 'A & B' }) }) - - it('strips inline markdown from labels', () => { - expect(stripInlineMarkdownForToc('Use **bold** [links](./x) and [[docs|Docs]]')).toBe( - 'Use bold links and Docs' - ) - }) - - it('folds large pasted heading whitespace without global whitespace replacement', () => { - const replaceSpy = vi.spyOn(String.prototype, 'replace') - const toc = buildMarkdownTableOfContents(`# ${'Large heading\ttext '.repeat(120)}`) - - expect(toc[0].title).toContain('Large heading text Large heading text') - const usedWhitespaceReplace = replaceSpy.mock.calls.some( - ([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+' - ) - expect(usedWhitespaceReplace).toBe(false) - }) }) diff --git a/src/renderer/src/components/editor/rich-markdown-commands.test.ts b/src/renderer/src/components/editor/rich-markdown-commands.test.ts index 7a043e5e860..d2393340d1a 100644 --- a/src/renderer/src/components/editor/rich-markdown-commands.test.ts +++ b/src/renderer/src/components/editor/rich-markdown-commands.test.ts @@ -29,44 +29,6 @@ function runCommand(id: SlashCommandId, content = '/'): Editor { } describe('rich markdown slash commands', () => { - it('registers high-value markdown building blocks with searchable aliases', () => { - expect(getCommand('table').aliases).toContain('grid') - expect(getCommand('mermaid').aliases).toContain('diagram') - expect(getCommand('inline-math').aliases).toContain('latex') - expect(getCommand('math-block').aliases).toContain('equation block') - expect(getCommand('emoji').aliases).toContain('reaction') - expect(getCommand('toggle-h5').aliases).toContain('toggle-h5') - }) - - it('orders commands under section headers', () => { - expect(slashCommands.map((command) => `${command.group}:${command.id}`)).toEqual([ - 'Headings:heading-1', - 'Headings:heading-2', - 'Headings:heading-3', - 'Headings:heading-4', - 'Headings:heading-5', - 'Toggle headings:toggle-h1', - 'Toggle headings:toggle-h2', - 'Toggle headings:toggle-h3', - 'Toggle headings:toggle-h4', - 'Toggle headings:toggle-h5', - 'Basic blocks:blockquote', - 'Basic blocks:ordered-list', - 'Basic blocks:bullet-list', - 'Basic blocks:task-list', - 'Basic blocks:text', - 'Basic blocks:toggle-text', - 'Basic blocks:code-block', - 'Basic blocks:divider', - 'Advanced:table', - 'Advanced:mermaid', - 'Advanced:inline-math', - 'Advanced:math-block', - 'Media:image', - 'Others:emoji' - ]) - }) - it('supports deep heading slash commands', () => { const h4Editor = createEditor('Deep heading') const h5Editor = createEditor('Nested heading') @@ -165,14 +127,4 @@ describe('rich markdown slash commands', () => { editor.destroy() } }) - - it('inserts a plain unicode emoji', () => { - const editor = runCommand('emoji') - - try { - expect(editor.getMarkdown()).toBe('🙂') - } finally { - editor.destroy() - } - }) }) diff --git a/src/renderer/src/components/landing-preflight-issues.test.ts b/src/renderer/src/components/landing-preflight-issues.test.ts deleted file mode 100644 index 75ba7a5e006..00000000000 --- a/src/renderer/src/components/landing-preflight-issues.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getLandingPreflightIssues, - hasGitHubBackedProject, - type LandingPreflightStatus -} from './landing-preflight-issues' -import type { Repo } from '../../../shared/repo-types' - -function repo(overrides: Partial & Pick): Repo { - return { - badgeColor: '#737373', - addedAt: 100, - kind: 'git', - ...overrides - } -} - -const missingGhStatus: LandingPreflightStatus = { - git: { installed: true }, - gh: { installed: false, authenticated: false } -} - -describe('landing preflight issues', () => { - it('keeps Git issues even when no GitHub-backed project is registered', () => { - const issues = getLandingPreflightIssues( - { - git: { installed: false }, - gh: { installed: false, authenticated: false } - }, - { hasGitHubBackedProject: false } - ) - - expect(issues.map((issue) => issue.id)).toEqual(['git']) - }) - - it('does not report GitHub CLI issues when no GitHub-backed project is registered', () => { - const issues = getLandingPreflightIssues(missingGhStatus, { - hasGitHubBackedProject: false - }) - - expect(issues.some((issue) => issue.id.startsWith('gh'))).toBe(false) - }) - - it('keeps GitHub CLI issues when a GitHub-backed project is registered', () => { - const issues = getLandingPreflightIssues(missingGhStatus, { - hasGitHubBackedProject: true - }) - - expect(issues.map((issue) => issue.id)).toContain('gh') - }) - - it('reports GitHub auth issue when gh is installed but unauthenticated', () => { - const issues = getLandingPreflightIssues( - { - git: { installed: true }, - gh: { installed: true, authenticated: false } - }, - { hasGitHubBackedProject: true } - ) - - expect(issues.map((issue) => issue.id)).toContain('gh-auth') - }) - - it('treats GitLab-only registered projects as not GitHub-backed', () => { - expect( - hasGitHubBackedProject([ - repo({ - id: 'gitlab-repo', - path: '/Users/alice/gitlab', - displayName: 'gitlab' - }) - ]) - ).toBe(false) - }) - - it('detects GitHub-backed projects from generated avatar metadata', () => { - expect( - hasGitHubBackedProject([ - repo({ - id: 'github-repo', - path: '/Users/alice/orca', - displayName: 'orca', - repoIcon: { - type: 'image', - src: 'https://github.com/stablyai.png?size=64', - source: 'github', - label: 'stablyai/orca' - } - }) - ]) - ).toBe(true) - }) - - it('detects GitHub-backed projects from existing provider metadata', () => { - expect( - hasGitHubBackedProject([ - repo({ - id: 'github-repo', - path: '/Users/alice/orca', - displayName: 'orca', - upstream: { owner: 'stablyai', repo: 'orca' } - }) - ]) - ).toBe(true) - }) -}) diff --git a/src/renderer/src/components/native-chat/NativeChatBackgroundTaskRun.test.tsx b/src/renderer/src/components/native-chat/NativeChatBackgroundTaskRun.test.tsx index 8dde4894607..c9a742b9992 100644 --- a/src/renderer/src/components/native-chat/NativeChatBackgroundTaskRun.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatBackgroundTaskRun.test.tsx @@ -2,11 +2,11 @@ import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { cleanup } from '@testing-library/react' + import { afterEach, describe, expect, it } from 'vitest' import type { NativeChatBackgroundTaskBlock } from '../../../../shared/native-chat-types' import { deriveNativeChatRowContent } from '../../../../shared/native-chat-row-content' -import { NativeChatBackgroundTaskRun } from './NativeChatBackgroundTaskRun' afterEach(cleanup) @@ -24,49 +24,6 @@ function task( } } -describe('NativeChatBackgroundTaskRun', () => { - it('draws the failure as a state, with the provider sentence beside it', () => { - render( - - ) - expect(screen.queryByText('Background command')).toBeNull() - expect(screen.getByText('Wait for the verification verdict')).toBeInTheDocument() - expect(screen.getByText(/^blocked · failed · 18\.2k · 1m 0s$/)).toBeInTheDocument() - expect( - screen.getByText('Background command "Wait" failed with exit code 1') - ).toBeInTheDocument() - }) - - it('never draws a wire opcode, whatever the task reported', () => { - const { container } = render() - expect(container.textContent).not.toContain('message:system') - expect(container.textContent).not.toContain('task_notification') - }) - - it('falls through to the kind when the provider named nothing usable', () => { - render() - expect(screen.getByText('Background workflow')).toBeInTheDocument() - }) - - it('shows an unnamed task once instead of repeating its kind', () => { - render() - expect(screen.getAllByText('Background task')).toHaveLength(1) - }) - - it('reads a state this build has no word for as status unavailable, never as live', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: models a row a newer build wrote, which the wire admits as an open string. - render() - expect(screen.getByText(/status unavailable/)).toBeInTheDocument() - }) -}) - describe('background task rows in a transcript message', () => { it('drops the frozen twin the block replaces, and keeps real prose', () => { const block = task({ state: 'blocked', summary: 'it failed' }) @@ -78,13 +35,4 @@ describe('background task rows in a transcript message', () => { expect(content.markdown).toBe('here is what happened') expect(content.backgroundTasks).toEqual([block]) }) - - it('counts a task row as content, so the transcript reserves its slot', () => { - const content = deriveNativeChatRowContent([ - { type: 'text', text: 'it failed' }, - task({ state: 'blocked', summary: 'it failed' }) - ]) - expect(content.markdown).toBe('') - expect(content.backgroundTasks).toHaveLength(1) - }) }) diff --git a/src/renderer/src/components/new-workspace/project-combobox-matching.test.ts b/src/renderer/src/components/new-workspace/project-combobox-matching.test.ts index ea79afd1b55..61f00be45ed 100644 --- a/src/renderer/src/components/new-workspace/project-combobox-matching.test.ts +++ b/src/renderer/src/components/new-workspace/project-combobox-matching.test.ts @@ -1,25 +1,13 @@ import { describe, expect, it } from 'vitest' import type { NewWorkspaceProjectOption } from '@/lib/new-workspace-project-options' -import { - getAmbiguousProjectOptionIds, - rankProjectOptions, - sectionProjectOptions -} from './project-combobox-matching' +import { rankProjectOptions } from './project-combobox-matching' function project(id: string, displayName: string, detail: string): NewWorkspaceProjectOption { return { kind: 'project', id, projectId: id, displayName, badgeColor: '#111', detail } } - -const orca = project('orca', 'orca', 'stablyai/orca') -const relay = project('relay', 'orca-relay', 'stablyai/orca-relay') const gateway = project('gateway', 'api-gateway', 'acme/api-gateway') describe('rankProjectOptions', () => { - it('ranks a name-prefix match above a mid-name match', () => { - const ranked = rankProjectOptions([relay, orca], 'orca', []) - expect(ranked[0]?.option.id).toBe('orca') - }) - it('matches the detail line when the name does not match', () => { const ranked = rankProjectOptions([gateway], 'acme', []) expect(ranked).toHaveLength(1) @@ -32,45 +20,4 @@ describe('rankProjectOptions', () => { expect(rankProjectOptions([hosts], 'sc', [])).toHaveLength(0) expect(rankProjectOptions([hosts], 'ifa', [])).toHaveLength(1) }) - - it('orders an unfiltered list by recency', () => { - const ranked = rankProjectOptions([orca, relay, gateway], '', ['gateway', 'relay']) - expect(ranked.map((r) => r.option.id)).toEqual(['gateway', 'relay', 'orca']) - }) - - it('returns nothing for an oversized query rather than scanning it', () => { - expect(rankProjectOptions([orca], 'x'.repeat(4096), [])).toEqual([]) - }) -}) - -describe('sectionProjectOptions', () => { - const many = Array.from({ length: 7 }, (_, i) => project(`p${i}`, `proj-${i}`, `acme/proj-${i}`)) - - it('collapses to a single unlabelled list while a query is live', () => { - const matches = rankProjectOptions(many, 'proj', []) - const sections = sectionProjectOptions(matches, 'proj', ['p3']) - expect(sections).toHaveLength(1) - expect(sections[0]?.heading).toBeNull() - }) - - it('splits into Recent/Projects once the list is long enough to warrant it', () => { - const matches = rankProjectOptions(many, '', ['p3', 'p5']) - const sections = sectionProjectOptions(matches, '', ['p3', 'p5']) - expect(sections.map((s) => s.heading)).toEqual(['Recent', 'Projects']) - expect(sections[0]?.items.map((i) => i.option.id)).toEqual(['p3', 'p5']) - }) - - it('keeps a short list unsectioned', () => { - const matches = rankProjectOptions([orca, relay], '', ['relay']) - expect(sectionProjectOptions(matches, '', ['relay'])).toHaveLength(1) - }) -}) - -describe('getAmbiguousProjectOptionIds', () => { - it('flags only ids whose display name repeats', () => { - const a = project('a', 'scratch', '~/code/scratch') - const b = project('b', 'scratch', '~/src/scratch') - const ids = getAmbiguousProjectOptionIds([a, b, orca]) - expect(ids).toEqual(new Set(['a', 'b'])) - }) }) diff --git a/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts b/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts deleted file mode 100644 index 44b2d7413ea..00000000000 --- a/src/renderer/src/components/plugins/presentation/plugin-install-trust.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - PluginMarketplaceHostInstallPreview, - PluginMarketplaceHostListing -} from '../../../../../preload/api-types' -import { isProtectedPluginTranslationPath } from '../../../../../shared/plugins/artifacts/plugin-language-pack-artifact' -import { pluginManifestSchema } from '../../../../../shared/plugins/manifest/plugin-manifest' -import en from '../../../i18n/locales/en.json' -import { - catalogInstallTrustPrompt, - localFolderTrustPrompt, - pluginRepositoryOrigin, - sourceInstallTrustPrompt -} from './plugin-install-trust' - -const listing: PluginMarketplaceHostListing = { - marketplaceSourceId: 'source', - marketplaceName: 'Orca community', - marketplaceOwner: 'stablyai', - marketplaceCommit: 'b'.repeat(40), - pluginKey: 'acme.dusk', - source: { kind: 'git', url: 'https://github.com/Acme/dusk.git', ref: 'main' }, - categories: [], - official: false, - bundled: false -} - -function preview(contributes: Record, main?: string) { - return { - ...listing, - resolvedCommit: 'c'.repeat(40), - contentHash: 'd'.repeat(64), - consentFingerprint: 'sha256-shown', - manifest: pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'dusk', - publisher: 'acme', - name: 'Dusk', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - ...(main ? { main } : {}), - contributes - }) - } satisfies PluginMarketplaceHostInstallPreview -} - -const theme = preview({ themes: [{ id: 'dusk', title: 'Dusk', path: 'themes/dusk.json' }] }) - -describe('catalogInstallTrustPrompt', () => { - it('asks nothing only when both listing and preview are official', () => { - expect( - catalogInstallTrustPrompt({ ...listing, official: true }, { ...theme, official: true }) - ).toBeNull() - expect(catalogInstallTrustPrompt({ ...listing, official: true }, theme)).not.toBeNull() - expect(catalogInstallTrustPrompt(listing, { ...theme, official: true })).not.toBeNull() - }) - - it('asks for a community theme with the softer copy and the owner Orca parsed', () => { - expect(catalogInstallTrustPrompt(listing, theme)).toEqual({ - kind: 'theme', - trustee: 'Acme', - publisher: 'acme', - repository: 'github.com/acme/dusk', - location: 'Orca community', - access: [] - }) - }) - - it('shows the publisher Orca installs as, not the one the manifest declares', () => { - const claimed = { ...theme, manifest: { ...theme.manifest, publisher: 'stablyai' } } - expect(catalogInstallTrustPrompt(listing, claimed)?.publisher).toBe('acme') - }) - - it('names other content and translations apart from themes', () => { - const grammar = preview({ - syntaxes: [{ id: 'g', title: 'G', scopeName: 'source.g', path: 'g.json', extensions: ['.g'] }] - }) - expect(catalogInstallTrustPrompt(listing, grammar)?.kind).toBe('content') - const pack = preview({ - languagePacks: [{ locale: 'eo', path: 'eo.json' }] - }) - expect(catalogInstallTrustPrompt(listing, pack)?.kind).toBe('translations') - }) - - it('warns a code plugin runs code and lists what it may do', () => { - const worker = preview({}, 'dist/worker.js') - const prompt = catalogInstallTrustPrompt(listing, worker) - expect(prompt?.kind).toBe('code') - expect(prompt?.access[0]).toMatch(/^Full access/) - }) - - it('treats a release the catalog calls code as code even if the manifest looks like content', () => { - const codeRelease = { - ...listing, - release: { - version: '1.0.0', - commit: 'c'.repeat(40), - contentHash: 'd'.repeat(64), - execution: 'declarative' as const, - minimumOrca: '1.0.0', - types: [] - } - } - expect(catalogInstallTrustPrompt(codeRelease, theme)?.kind).toBe('code') - }) -}) - -describe('sourceInstallTrustPrompt', () => { - it('names the Git owner and repository for a Git URL install', () => { - expect( - sourceInstallTrustPrompt({ - kind: 'git', - url: 'git@gitlab.com:team/tools/notes.git', - ref: 'v1' - }) - ).toMatchObject({ - kind: 'git', - trustee: 'team', - publisher: 'team', - repository: 'gitlab.com/team/tools/notes' - }) - }) - - it('calls a folder install and a development folder unverified local folders', () => { - expect(sourceInstallTrustPrompt({ kind: 'local-path', path: '/tmp/p' })).toMatchObject({ - kind: 'local-folder', - location: '/tmp/p' - }) - expect(localFolderTrustPrompt('dev-folder', '/tmp/p').kind).toBe('dev-folder') - }) - - it('names a subdirectory plugin location', () => { - expect(pluginRepositoryOrigin('https://github.com/acme/mono.git', 'plugins/dusk')).toEqual({ - owner: 'acme', - repository: 'github.com/acme/mono (plugins/dusk)' - }) - }) -}) - -describe('install trust copy', () => { - it('is copy no language pack may rewrite', () => { - const keys = Object.keys(en.auto.components.settings.PluginInstallTrustDialog) - expect(keys.length).toBeGreaterThan(10) - for (const key of keys) { - expect( - isProtectedPluginTranslationPath(`auto.components.settings.PluginInstallTrustDialog.${key}`) - ).toBe(true) - } - }) -}) diff --git a/src/renderer/src/components/pr-comments-resolution-prompt.test.ts b/src/renderer/src/components/pr-comments-resolution-prompt.test.ts index 9ff4fad596c..9f1cff975cf 100644 --- a/src/renderer/src/components/pr-comments-resolution-prompt.test.ts +++ b/src/renderer/src/components/pr-comments-resolution-prompt.test.ts @@ -1,124 +1,8 @@ import { describe, expect, it } from 'vitest' -import type { PRComment } from '../../../shared/github/comment-types' -import { groupPRComments } from '../../../shared/pr-comment-groups' -import { - buildPRCommentsResolutionPrompt, - isResolvablePRCommentGroup -} from './pr-comments-resolution-prompt' -function comment(overrides: Partial): PRComment { - return { - id: 1, - author: 'alice', - authorAvatarUrl: '', - body: 'Please simplify this branch.', - createdAt: '2026-05-14T00:00:00Z', - url: 'https://github.com/acme/widgets/pull/42#discussion_r1', - ...overrides - } -} +import { buildPRCommentsResolutionPrompt } from './pr-comments-resolution-prompt' describe('buildPRCommentsResolutionPrompt', () => { - it('includes review metadata, root and replies, file location, outdated state, and safety rules', () => { - const groups = groupPRComments([ - comment({ - id: 101, - author: 'reviewer', - body: 'Use the safer parser.', - threadId: 'thread-1', - path: 'src/parser.ts', - line: 42, - startLine: 40, - isResolved: false, - isOutdated: true - }), - comment({ - id: 102, - author: 'author', - body: 'Good catch, checking.', - threadId: 'thread-1', - path: 'src/parser.ts', - line: 42, - isResolved: false - }) - ]) - - const prompt = buildPRCommentsResolutionPrompt({ - reviewKind: 'MR', - reviewNumber: 7, - reviewTitle: 'Fix parser', - reviewUrl: 'https://gitlab.com/acme/widgets/-/merge_requests/7', - groups, - worktreePath: '/tmp/widgets' - }) - - expect(prompt).toContain('MR !7') - expect(prompt).toContain('Treat the review title, URL, comment authors') - expect(prompt).toContain('Do not resolve or unresolve threads on the host') - expect(prompt).toContain('"selectedCommentGroups"') - expect(prompt).toContain('"hostResolvableThreads"') - expect(prompt).toContain('"threadId": "thread-1"') - expect(prompt).toContain('"title": "Fix parser"') - expect(prompt).toContain('"worktreePath": "/tmp/widgets"') - expect(prompt).toContain('"path": "src/parser.ts"') - expect(prompt).toContain('"line": 42') - expect(prompt).toContain('"startLine": 40') - expect(prompt).toContain('"isOutdated": true') - expect(prompt).toContain('"replies"') - expect(prompt).toContain('Good catch, checking.') - expect(prompt).toContain('- For outdated comments, inspect the current file') - expect(prompt).toContain('- Run git diff --check before finishing.') - }) - - it('includes standalone PR comments in the selected AI payload', () => { - const groups = groupPRComments([ - comment({ - id: 201, - author: 'coderabbitai', - body: 'Review Change Stack\\nNo actionable comments were generated.' - }) - ]) - - const prompt = buildPRCommentsResolutionPrompt({ - reviewKind: 'PR', - reviewNumber: 42, - reviewTitle: 'Improve comments', - reviewUrl: 'https://github.com/acme/widgets/pull/42', - groups - }) - - expect(prompt).toContain('Inspect and fix the selected review feedback for PR #42.') - expect(prompt).toContain('"kind": "standalone"') - expect(prompt).toContain('"author": "coderabbitai"') - expect(prompt).toContain('Review Change Stack') - expect(prompt).toContain('"hostResolvableThreads": []') - expect(prompt).toContain('standalone summaries') - }) - - it('includes resolvable GitLab discussions even when they are not tied to a file path', () => { - const groups = groupPRComments([ - comment({ - id: 301, - author: 'reviewer', - body: 'Please update the summary before merging.', - threadId: 'discussion-1', - isResolved: false - }) - ]) - - const prompt = buildPRCommentsResolutionPrompt({ - reviewKind: 'MR', - reviewNumber: 8, - reviewTitle: 'Clarify docs', - reviewUrl: 'https://gitlab.com/acme/widgets/-/merge_requests/8', - groups - }) - - expect(prompt).toContain('"hostResolvableThreads"') - expect(prompt).toContain('"threadId": "discussion-1"') - expect(prompt).toContain('"path": null') - }) - it('quotes untrusted review metadata in the instruction header', () => { const prompt = buildPRCommentsResolutionPrompt({ reviewKind: 'PR', @@ -138,29 +22,3 @@ describe('buildPRCommentsResolutionPrompt', () => { ) }) }) - -describe('isResolvablePRCommentGroup', () => { - it('selects unresolved host thread groups', () => { - const groups = groupPRComments([ - comment({ - id: 1, - threadId: 'open-inline', - path: 'src/a.ts', - isResolved: false - }), - comment({ - id: 2, - threadId: 'resolved-inline', - path: 'src/b.ts', - isResolved: true - }), - comment({ id: 3, threadId: 'top-level-gitlab-discussion', isResolved: false }), - comment({ - id: 4, - url: 'https://github.com/acme/widgets/pull/42#pullrequestreview-4' - }) - ]) - - expect(groups.map(isResolvablePRCommentGroup)).toEqual([true, false, true, false]) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/file-search-include-pattern.test.ts b/src/renderer/src/components/right-sidebar/file-search-include-pattern.test.ts index 48f789ee0b1..87a40c54b39 100644 --- a/src/renderer/src/components/right-sidebar/file-search-include-pattern.test.ts +++ b/src/renderer/src/components/right-sidebar/file-search-include-pattern.test.ts @@ -1,67 +1,15 @@ import { describe, expect, it } from 'vitest' -import { - folderRelativePathToIncludeGlob, - selectedExplorerFolderRelativePath -} from './file-search-include-pattern' +import { folderRelativePathToIncludeGlob } from './file-search-include-pattern' describe('folderRelativePathToIncludeGlob', () => { - it('converts a relative folder path into a recursive include glob', () => { - expect(folderRelativePathToIncludeGlob('src')).toBe('src/**') - expect(folderRelativePathToIncludeGlob('src/components')).toBe('src/components/**') - }) - it('normalizes separators and trailing slashes before appending the recursive glob', () => { expect(folderRelativePathToIncludeGlob('src\\components\\')).toBe('src/components/**') expect(folderRelativePathToIncludeGlob('/src//components///')).toBe('src/components/**') }) - it('returns an empty pattern for the repository root', () => { - expect(folderRelativePathToIncludeGlob('')).toBe('') - expect(folderRelativePathToIncludeGlob('/')).toBe('') - }) - it('escapes literal folder path characters that are meaningful to search globs', () => { expect(folderRelativePathToIncludeGlob('!secret')).toBe('\\!secret/**') expect(folderRelativePathToIncludeGlob('foo,bar')).toBe('foo\\,bar/**') expect(folderRelativePathToIncludeGlob('a[b]/{draft}?')).toBe('a\\[b\\]/\\{draft\\}\\?/**') }) }) - -describe('selectedExplorerFolderRelativePath', () => { - it('reads the selected folder path from the explorer shell', () => { - const shell = { - getAttribute: (name: string) => (name === 'data-selected-folder-relative-path' ? 'src' : null) - } as Element - const child = { - closest: (selector: string) => (selector === '[data-orca-explorer-shell]' ? shell : null) - } as Element - - expect(selectedExplorerFolderRelativePath(child)).toBe('src') - }) - - it('treats the repository root empty path as a selected folder', () => { - const shell = { - getAttribute: (name: string) => (name === 'data-selected-folder-relative-path' ? '' : null) - } as Element - const child = { - closest: (selector: string) => (selector === '[data-orca-explorer-shell]' ? shell : null) - } as Element - - expect(selectedExplorerFolderRelativePath(child)).toBe('') - }) - - it('returns null when focus is outside the explorer or no folder is selected', () => { - const outside = { - closest: () => null - } as unknown as Element - const shellWithoutFolder = { - getAttribute: () => null - } as unknown as Element - const child = { - closest: () => shellWithoutFolder - } as unknown as Element - - expect(selectedExplorerFolderRelativePath(outside)).toBeNull() - expect(selectedExplorerFolderRelativePath(child)).toBeNull() - }) -}) diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerRowDrag.test.ts b/src/renderer/src/components/right-sidebar/useFileExplorerRowDrag.test.ts index 4bdc0f8ae5e..fbc65b0b97f 100644 --- a/src/renderer/src/components/right-sidebar/useFileExplorerRowDrag.test.ts +++ b/src/renderer/src/components/right-sidebar/useFileExplorerRowDrag.test.ts @@ -1,33 +1,12 @@ import { describe, expect, it } from 'vitest' import { decodeWorkspaceFilePaths, - encodeWorkspaceFilePaths, - getWorkspaceFileDragRejectionMessage, getWorkspaceFileDragPaths, readWorkspaceFileDragPaths, - WORKSPACE_FILE_PATH_MIME, - WORKSPACE_FILE_PATHS_MIME + WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag' -describe('encodeWorkspaceFilePaths / decodeWorkspaceFilePaths', () => { - it('encodes and decodes a single path as a plain string', () => { - const encoded = encodeWorkspaceFilePaths(['/repo/a.ts']) - expect(encoded).toBe('/repo/a.ts') - expect(decodeWorkspaceFilePaths(encoded)).toEqual(['/repo/a.ts']) - }) - - it('encodes and decodes multiple paths as a JSON array', () => { - const paths = ['/repo/a.ts', '/repo/b.ts', '/repo/c.ts'] - const encoded = encodeWorkspaceFilePaths(paths) - expect(decodeWorkspaceFilePaths(encoded)).toEqual(paths) - }) -}) - describe('decodeWorkspaceFilePaths', () => { - it('returns empty array for an empty string', () => { - expect(decodeWorkspaceFilePaths('')).toEqual([]) - }) - it('filters out non-string entries from a JSON array', () => { expect(decodeWorkspaceFilePaths(JSON.stringify(['/repo/a.ts', 42, null]))).toEqual([ '/repo/a.ts' @@ -36,28 +15,6 @@ describe('decodeWorkspaceFilePaths', () => { }) describe('getWorkspaceFileDragPaths', () => { - it('falls back to the legacy single-path MIME', () => { - expect( - getWorkspaceFileDragPaths({ - getData: (type) => (type === WORKSPACE_FILE_PATH_MIME ? '/repo/a.ts' : '') - }) - ).toEqual(['/repo/a.ts']) - }) - - it('prefers the multi-path MIME when present', () => { - const paths = ['/repo/a.ts', '/repo/b.ts'] - expect( - getWorkspaceFileDragPaths({ - getData: (type) => - type === WORKSPACE_FILE_PATHS_MIME - ? encodeWorkspaceFilePaths(paths) - : type === WORKSPACE_FILE_PATH_MIME - ? '/repo/a.ts' - : '' - }) - ).toEqual(paths) - }) - it('fails closed when the drag payload exceeds the bounded decoder limits', () => { const oversizedPath = `C:\\Users\\alice\\${'s'.repeat(260 * 1024)}` @@ -87,13 +44,4 @@ describe('readWorkspaceFileDragPaths', () => { expect(JSON.stringify(result)).not.toContain('secret') } }) - - it('returns redacted user-facing messages for bounded internal drag rejection', () => { - expect(getWorkspaceFileDragRejectionMessage('too-many-paths')).toBe( - 'Drop contains too many paths.' - ) - expect(getWorkspaceFileDragRejectionMessage('paths-too-large')).toBe( - 'Drop path list is too large.' - ) - }) }) diff --git a/src/renderer/src/components/settings/cli-install-failure.test.ts b/src/renderer/src/components/settings/cli-install-failure.test.ts deleted file mode 100644 index dfd39f15649..00000000000 --- a/src/renderer/src/components/settings/cli-install-failure.test.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { CliInstallStatus } from '../../../../shared/cli-install-types' -import { readCliInstallFailure, readCliInstallRejection } from './cli-install-failure' - -const FALLBACK = 'Orca could not finish CLI registration and reported no reason.' - -function cliStatus(overrides: Partial = {}): CliInstallStatus { - return { - platform: 'darwin', - commandName: 'orca', - commandPath: '/usr/local/bin/orca', - pathDirectory: '/usr/local/bin', - pathConfigured: true, - launcherPath: '/Applications/Orca.app/Contents/Resources/bin/orca', - installMethod: 'symlink', - supported: true, - state: 'installed', - currentTarget: null, - unsupportedReason: null, - detail: null, - ...overrides - } -} - -describe('readCliInstallFailure', () => { - it('reports no failure for a landed registration', () => { - expect(readCliInstallFailure(cliStatus(), FALLBACK)).toBeNull() - }) - - it('surfaces the main-process reason verbatim without re-classifying it', () => { - expect( - readCliInstallFailure( - cliStatus({ - state: 'unsupported', - supported: false, - unsupportedReason: 'launcher_missing', - detail: 'The bundled CLI launcher is missing from this Orca build.' - }), - FALLBACK - ) - ).toEqual({ - reason: 'The bundled CLI launcher is missing from this Orca build.', - conflictCommandPath: null - }) - }) - - it('names the conflicting path so the panel can offer the remedy', () => { - expect( - readCliInstallFailure( - cliStatus({ - state: 'conflict', - detail: '/usr/local/bin/orca exists but is not an Orca symlink.' - }), - FALLBACK - ) - ).toEqual({ - reason: '/usr/local/bin/orca exists but is not an Orca symlink.', - conflictCommandPath: '/usr/local/bin/orca' - }) - }) - - it('falls back when the main process reported no detail', () => { - expect(readCliInstallFailure(cliStatus({ state: 'not_installed' }), FALLBACK)).toEqual({ - reason: FALLBACK, - conflictCommandPath: null - }) - }) -}) - -describe('readCliInstallRejection', () => { - it('strips the Electron transport prefix off the installer message', () => { - expect( - readCliInstallRejection( - new Error( - "Error invoking remote method 'cli:install': Error: Refusing to replace non-Orca " + - 'command at /usr/local/bin/orca. Remove it and register again if it is no longer needed.' - ), - FALLBACK - ) - ).toEqual({ - reason: - 'Refusing to replace non-Orca command at /usr/local/bin/orca. ' + - 'Remove it and register again if it is no longer needed.', - conflictCommandPath: null - }) - }) - - it('keeps the registration-lock remedy that names the lock file', () => { - const failure = readCliInstallRejection( - new Error( - "Error invoking remote method 'cli:install': Error: Timed out waiting for another Orca " + - 'process to finish CLI registration (waited 330s). If no other Orca is running, remove ' + - '/home/u/.cache/orca/appimage/.cli-registration.lock and retry.' - ), - FALLBACK - ) - - expect(failure.reason).toContain('.cli-registration.lock and retry.') - expect(failure.reason.startsWith('Timed out waiting')).toBe(true) - }) - - it('falls back for a non-Error rejection with no message', () => { - expect(readCliInstallRejection(new Error(' '), FALLBACK)).toEqual({ - reason: FALLBACK, - conflictCommandPath: null - }) - }) -}) diff --git a/src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx b/src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx deleted file mode 100644 index 3ccb5de66b8..00000000000 --- a/src/renderer/src/components/settings/repository/execution/RepositoryHostSetupsSection.workspace-window.test.tsx +++ /dev/null @@ -1,195 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY -} from '../../../../../../shared/worktree-runtime-capabilities' -import { RUNTIME_PROTOCOL_VERSION } from '../../../../../../shared/protocol-version' -import type { RuntimeStatus } from '../../../../../../shared/runtime-session-contracts' -import type { Project, ProjectHostSetup } from '../../../../../../shared/project-types' -import type { Repo } from '../../../../../../shared/repo-types' -import { useAppStore } from '../../../../store/index' -import { RepositoryHostSetupsSection } from './RepositoryHostSetupsSection' - -let container: HTMLDivElement -let root: Root - -const repo: Repo = { - id: 'remote-repo', - displayName: 'Orca', - path: '/srv/orca', - badgeColor: '#737373', - addedAt: 100, - kind: 'git', - executionHostId: 'runtime:hub' -} -const project: Project = { - id: 'github:stablyai/orca', - displayName: 'Orca', - badgeColor: '#737373', - sourceRepoIds: [repo.id], - createdAt: 100, - updatedAt: 100 -} -const setup: ProjectHostSetup = { - id: 'hub-setup', - projectId: project.id, - repoId: repo.id, - hostId: 'runtime:hub', - runtimeOwnerEnvironmentId: 'hub', - path: repo.path, - displayName: repo.displayName, - kind: 'git', - setupState: 'ready', - setupMethod: 'legacy-repo', - createdAt: 100, - updatedAt: 100 -} - -function makeStatus(overrides: Partial): RuntimeStatus { - return { - runtimeId: 'runtime-hub', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - desktopWindowStatus: 'available', - liveTabCount: 0, - liveLeafCount: 0, - runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, - minCompatibleRuntimeClientVersion: 1, - capabilities: [PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY], - ...overrides - } -} - -function renderWithOwnerStatus(status: RuntimeStatus | null): void { - useAppStore.setState({ - repos: [repo], - projects: [project], - projectHostSetups: [setup], - runtimeStatusByEnvironmentId: new Map([['hub', { checkedAt: 1, appVersion: '1.8.0', status }]]) - }) - act(() => { - root.render( - React.createElement(RepositoryHostSetupsSection, { - repo, - forceVisible: true, - searchQuery: '', - searchEntries: [] - }) - ) - }) -} - -beforeEach(() => { - useAppStore.setState(useAppStore.getInitialState(), true) - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - useAppStore.setState(useAppStore.getInitialState(), true) -}) - -// Reachable servers with missing renderer graphs previously showed every owned setup Ready (#12350). -describe('RepositoryHostSetupsSection workspace window availability', () => { - it('flags a reachable runtime owner whose workspace window is closed instead of Ready', () => { - renderWithOwnerStatus( - makeStatus({ - graphStatus: 'unavailable', - authoritativeWindowId: null, - desktopWindowStatus: 'openable' - }) - ) - - const currentSetup = container.querySelector('[data-current="true"]') - expect(currentSetup?.textContent).toContain('Workspace window closed') - expect(currentSetup?.textContent).not.toContain('Ready') - // The host is reachable — this must not be reported as a lost connection. - expect(container.textContent).not.toContain('Disconnected') - expect(container.textContent).toContain('Open Orca on') - }) - - it('keeps a graph-ready runtime owner Ready when it reports no desktop window', () => { - // Headless serve can own a ready graph/openable desktop; readiness must not require a live renderer (#6844). - renderWithOwnerStatus(makeStatus({ graphStatus: 'ready', desktopWindowStatus: 'openable' })) - - expect(container.textContent).toContain('Ready') - expect(container.textContent).not.toContain('Workspace window closed') - expect(container.textContent).not.toContain('Disconnected') - }) - - it('keeps an unreachable runtime owner disconnected', () => { - renderWithOwnerStatus(null) - - expect(container.textContent).toContain('Disconnected') - expect(container.textContent).not.toContain('Workspace window closed') - }) - - it('does not mark a transport-connected but unavailable runtime setup Ready', () => { - useAppStore.setState({ - repos: [repo], - projects: [project], - projectHostSetups: [setup], - runtimeStatusByEnvironmentId: new Map([ - [ - 'hub', - { - checkedAt: 1, - status: null, - remoteControl: { - state: 'ready', - pendingRequestCount: 0, - subscriptionCount: 0, - reconnectAttempt: 0, - lastConnectedAt: 1, - lastClose: null, - lastError: null - } - } - ] - ]) - }) - act(() => { - root.render( - React.createElement(RepositoryHostSetupsSection, { - repo, - forceVisible: true, - searchQuery: '', - searchEntries: [] - }) - ) - }) - - const currentSetup = container.querySelector('[data-current="true"]') - expect(currentSetup?.textContent).toContain('Unknown') - expect(currentSetup?.textContent).not.toContain('Ready') - }) - - it('does not call a setup Ready when the owner control channel closed with an error', () => { - renderWithOwnerStatus( - makeStatus({ - remoteControl: { - state: 'closed', - pendingRequestCount: 0, - subscriptionCount: 0, - reconnectAttempt: 0, - lastConnectedAt: null, - lastClose: null, - lastError: 'Connection closed' - } - }) - ) - - expect(container.textContent).toContain('Disconnected') - expect(container.textContent).not.toContain('Workspace window closed') - }) -}) diff --git a/src/renderer/src/components/sidebar/add-repo-existing-workspaces-telemetry.test.ts b/src/renderer/src/components/sidebar/add-repo-existing-workspaces-telemetry.test.ts index 851367f56ef..78b1299003c 100644 --- a/src/renderer/src/components/sidebar/add-repo-existing-workspaces-telemetry.test.ts +++ b/src/renderer/src/components/sidebar/add-repo-existing-workspaces-telemetry.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' import type { Worktree } from '../../../../shared/worktree/types' -import { - buildAddRepoExistingWorkspacesDetectedEvent, - buildAddRepoExistingWorkspacesTelemetry, - shouldTrackAddRepoExistingWorkspacesDetected -} from './add-repo-existing-workspaces-telemetry' +import { buildAddRepoExistingWorkspacesDetectedEvent } from './add-repo-existing-workspaces-telemetry' function worktree(overrides: Partial): Worktree { return { @@ -30,94 +26,6 @@ function worktree(overrides: Partial): Worktree { } describe('add repo existing workspace telemetry', () => { - it('builds count-only payloads without raw workspace names', () => { - const payload = buildAddRepoExistingWorkspacesTelemetry('local_folder_picker', [ - worktree({ path: '/repo', displayName: 'main', branch: 'refs/heads/main' }), - worktree({ - id: 'repo::/repo-feature', - path: '/repo-feature', - displayName: 'Feature With User Text', - branch: 'refs/heads/feature/private-task', - isMainWorktree: false, - isSparse: true - }), - worktree({ - id: 'repo::/detached', - path: 'C:\\workspaces\\detached', - displayName: 'detached', - branch: '', - isMainWorktree: false - }) - ]) - - expect(payload).toEqual({ - source: 'local_folder_picker', - existing_workspace_count: 3, - existing_linked_workspace_count: 2, - main_workspace_count: 1, - branch_named_workspace_count: 2, - detached_workspace_count: 1, - custom_named_workspace_count: 1, - sparse_workspace_count: 1 - }) - expect(JSON.stringify(payload)).not.toContain('private-task') - expect(JSON.stringify(payload)).not.toContain('Feature With User Text') - }) - - it('tracks detection only for imported linked workspaces', () => { - expect(buildAddRepoExistingWorkspacesTelemetry(null, [worktree({})])).toBeNull() - expect(buildAddRepoExistingWorkspacesTelemetry('local_folder_picker', [])).toBeNull() - - const mainOnlyPayload = buildAddRepoExistingWorkspacesTelemetry('local_folder_picker', [ - worktree({}) - ]) - expect(mainOnlyPayload?.existing_linked_workspace_count).toBe(0) - expect(shouldTrackAddRepoExistingWorkspacesDetected(mainOnlyPayload)).toBe(false) - - const importedLocalPayload = buildAddRepoExistingWorkspacesTelemetry('local_folder_picker', [ - worktree({}), - worktree({ id: 'repo::/repo-existing', path: '/repo-existing', isMainWorktree: false }) - ]) - const importedRemotePayload = buildAddRepoExistingWorkspacesTelemetry('ssh_remote_path', [ - worktree({}), - worktree({ id: 'repo::/remote-existing', path: '/remote-existing', isMainWorktree: false }) - ]) - const clonePayload = buildAddRepoExistingWorkspacesTelemetry('clone_url', [ - worktree({}), - worktree({ id: 'repo::/clone-existing', path: '/clone-existing', isMainWorktree: false }) - ]) - const createPayload = buildAddRepoExistingWorkspacesTelemetry('create_project', [ - worktree({}), - worktree({ id: 'repo::/create-existing', path: '/create-existing', isMainWorktree: false }) - ]) - - expect(shouldTrackAddRepoExistingWorkspacesDetected(importedLocalPayload)).toBe(true) - expect(shouldTrackAddRepoExistingWorkspacesDetected(importedRemotePayload)).toBe(true) - expect(shouldTrackAddRepoExistingWorkspacesDetected(clonePayload)).toBe(false) - expect(shouldTrackAddRepoExistingWorkspacesDetected(createPayload)).toBe(false) - }) - - it('derives linked and detached counts before clamping reported values', () => { - const mainOnlyPayload = buildAddRepoExistingWorkspacesTelemetry( - 'local_folder_picker', - Array.from({ length: 60 }, (_, index) => - worktree({ - id: `repo::/repo-main-${index}`, - path: `/repo-main-${index}`, - isMainWorktree: true - }) - ) - ) - - expect(mainOnlyPayload).toMatchObject({ - existing_workspace_count: 50, - existing_linked_workspace_count: 0, - main_workspace_count: 50, - detached_workspace_count: 0 - }) - expect(shouldTrackAddRepoExistingWorkspacesDetected(mainOnlyPayload)).toBe(false) - }) - it('sorts without crashing when a detected worktree has no displayName (crash 99657ab1)', () => { // Equal activity forces the name tie-break that crashed on undefined runtime names. expect(() => diff --git a/src/renderer/src/components/sidebar/workspace-kanban-virtual-lane-layout.test.ts b/src/renderer/src/components/sidebar/workspace-kanban-virtual-lane-layout.test.ts index 003cdf73784..734ee57e124 100644 --- a/src/renderer/src/components/sidebar/workspace-kanban-virtual-lane-layout.test.ts +++ b/src/renderer/src/components/sidebar/workspace-kanban-virtual-lane-layout.test.ts @@ -66,22 +66,6 @@ describe('workspace kanban virtual lane layout', () => { unregister() }) - it('exposes every logical item even when no card is mounted', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregister = registerLayout(scrollElement, spacerElement) - scrollElement.scrollTop = 3_980 - - const rects = getWorkspaceKanbanVirtualLaneItemRects(scrollElement) - expect(rects).toHaveLength(ITEM_COUNT) - expect(rects?.[50]).toMatchObject({ - id: 'w50', - index: 50, - contentTop: 2_208, - contentBottom: 2_244 - }) - unregister() - }) - it('selects intermediate never-mounted cards across a jumped lane range', () => { const { scrollElement, spacerElement } = createLayoutElements() const unregister = registerLayout(scrollElement, spacerElement) @@ -129,45 +113,4 @@ describe('workspace kanban virtual lane layout', () => { unregisterSecond() expect(getWorkspaceKanbanVirtualLaneItemRects(scrollElement)).toBeNull() }) - - it('places empty-lane and boundary drop indicators from the spacer', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregisterEmpty = registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => [], - getMeasurements: () => [] - }) - expect(resolveWorkspaceKanbanVirtualLaneDropIndex(scrollElement, 200)).toBe(0) - expect(resolveWorkspaceKanbanVirtualLaneDropIndicatorY(scrollElement, 0)).toBe(114) - unregisterEmpty() - - const unregister = registerLayout(scrollElement, spacerElement) - expect(resolveWorkspaceKanbanVirtualLaneDropIndex(scrollElement, 90)).toBe(0) - expect(resolveWorkspaceKanbanVirtualLaneDropIndicatorY(scrollElement, 0)).toBe(103) - expect(resolveWorkspaceKanbanVirtualLaneDropIndicatorY(scrollElement, 1)).toBe(148) - unregister() - }) - - it('returns null when measurements are incomplete or mismatched', () => { - const { scrollElement, spacerElement } = createLayoutElements() - const unregisterShort = registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => ['a', 'b'], - getMeasurements: () => [{ index: 0, start: 0, end: ITEM_HEIGHT }] - }) - expect(getWorkspaceKanbanVirtualLaneItemRects(scrollElement)).toBeNull() - expect(resolveWorkspaceKanbanVirtualLaneDropIndex(scrollElement, 120)).toBeNull() - unregisterShort() - - const unregisterBadIndex = registerWorkspaceKanbanVirtualLaneLayout({ - scrollElement, - spacerElement, - getItemIds: () => ['a'], - getMeasurements: () => [{ index: 3, start: 0, end: ITEM_HEIGHT }] - }) - expect(getWorkspaceKanbanVirtualLaneItemRects(scrollElement)).toBeNull() - unregisterBadIndex() - }) }) diff --git a/src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx b/src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx deleted file mode 100644 index 20b8752987f..00000000000 --- a/src/renderer/src/components/sidebar/worktree-review-helpers.test.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import { describe, expect, it } from 'vitest' -import { ReviewIcon } from './worktree-review-helpers' -import { derivePipelineStatus } from '../../../../main/gitlab/mappers' -import type { WorktreeCardPrDisplay } from './worktree-card-pr-display' - -const gitlabReview: WorktreeCardPrDisplay = { - provider: 'gitlab', - number: 456, - title: 'Review me', - state: 'open', - status: 'pending' -} - -describe('ReviewIcon', () => { - it('uses the provider-specific GitLab MR icon by default', () => { - const markup = renderToStaticMarkup() - - expect(markup).toContain('lucide-git-merge') - }) - - it('can use the generic review icon for compact lanes', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('viewBox="0 0 16 16"') - expect(markup).not.toContain('lucide-git-merge') - }) - - // Manual-blocked GitLab pipelines need a check tone or the open-MR fallback would look passing. - it('does not paint a manual-blocked GitLab pipeline like a passing one', () => { - const status = derivePipelineStatus({ status: 'manual' }) - const blocked = renderToStaticMarkup( - - ) - const passing = renderToStaticMarkup( - - ) - - expect(blocked).toContain('text-amber-500/85') - expect(blocked).not.toContain('text-emerald-500/80') - expect(blocked).not.toBe(passing) - }) - - it('gives a draft its own glyph and never paints it with a check tone', () => { - const draft = renderToStaticMarkup( - - ) - const closed = renderToStaticMarkup( - - ) - - expect(draft).toContain('lucide-git-pull-request-draft') - expect(draft).not.toContain('text-rose-500/85') - expect(closed).toContain('lucide-git-pull-request-closed') - expect(draft).not.toBe(closed) - }) - - it('keeps check tones on open reviews so failing checks still stand out', () => { - const failing = renderToStaticMarkup( - - ) - - expect(failing).toContain('text-rose-500/85') - }) - - it('renders merged reviews with the merge glyph', () => { - const merged = renderToStaticMarkup( - - ) - - expect(merged).toContain('lucide-git-merge') - }) - - it('overrides the GitLab provider glyph for closed merge requests', () => { - const closed = renderToStaticMarkup( - - ) - - expect(closed).toContain('lucide-git-pull-request-closed') - expect(closed).not.toContain('lucide-git-merge') - }) - - // Loading/failed folder review rows lack a state glyph; show problems without implying confirmed success. - it('flags problems on a stateless row without ever claiming success', () => { - const stateless = (status: 'failure' | 'pending' | 'success') => - renderToStaticMarkup( - - ) - - expect(stateless('failure')).toContain('text-rose-500/85') - expect(stateless('pending')).toContain('text-amber-500/85') - expect(stateless('success')).not.toContain('text-emerald-500/80') - }) -}) diff --git a/src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts b/src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts deleted file mode 100644 index f660a6d791e..00000000000 --- a/src/renderer/src/components/task-page/jira/task-page-jira-project-selection.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { - getJiraProjectSelectionKey, - jiraProjectDisplayLabelComparator -} from './task-page-jira-project-selection' -import type { JiraProject } from '../../../../../shared/jira/jira-types' - -function project(overrides: Partial = {}): JiraProject { - return { id: '1', key: 'AA', name: 'Alpha', ...overrides } -} - -describe('getJiraProjectSelectionKey', () => { - it('qualifies the project id with its site id', () => { - expect(getJiraProjectSelectionKey(project({ id: '10', siteId: 'site-1' }))).toBe('site-1:10') - }) - - it('falls back to the "selected" site sentinel when siteId is absent', () => { - expect(getJiraProjectSelectionKey(project({ id: '10' }))).toBe('selected:10') - }) - - it('treats an empty siteId as a real site id', () => { - expect(getJiraProjectSelectionKey(project({ id: '10', siteId: '' }))).toBe(':10') - }) -}) - -describe('jiraProjectDisplayLabelComparator', () => { - const sortOf = (projects: JiraProject[], includeSiteName: boolean): string[] => - [...projects] - .sort(jiraProjectDisplayLabelComparator(includeSiteName)) - .map((entry) => `${entry.siteName ?? ''}/${entry.name}/${entry.key}`) - - it('orders by site name first when site names are included', () => { - const projects = [ - project({ name: 'Alpha', key: 'AA', siteName: 'Zeta' }), - project({ name: 'Beta', key: 'BB', siteName: 'Acme' }) - ] - expect(sortOf(projects, true)).toEqual(['Acme/Beta/BB', 'Zeta/Alpha/AA']) - }) - - it('ignores site name when it is not included', () => { - const projects = [ - project({ name: 'Alpha', key: 'AA', siteName: 'Zeta' }), - project({ name: 'Beta', key: 'BB', siteName: 'Acme' }) - ] - expect(sortOf(projects, false)).toEqual(['Zeta/Alpha/AA', 'Acme/Beta/BB']) - }) - - it('falls back to project name, then project key', () => { - const projects = [ - project({ name: 'Alpha', key: 'AB' }), - project({ name: 'Alpha', key: 'AA' }), - project({ name: 'Beta', key: 'BA' }) - ] - expect(sortOf(projects, false)).toEqual(['/Alpha/AA', '/Alpha/AB', '/Beta/BA']) - }) - - it('sorts numeric segments naturally and case-insensitively', () => { - const projects = [project({ name: 'Team 10', key: 'A' }), project({ name: 'team 2', key: 'B' })] - expect(sortOf(projects, false)).toEqual(['/team 2/B', '/Team 10/A']) - }) - - it('returns 0 for projects with identical display labels', () => { - expect(jiraProjectDisplayLabelComparator(true)(project(), project({ id: '2' }))).toBe(0) - }) - - it('treats a missing site name as an empty string when comparing sites', () => { - const withSite = project({ name: 'Zeta', key: 'ZZ', siteName: 'Acme' }) - const withoutSite = project({ name: 'Alpha', key: 'AA' }) - expect(sortOf([withSite, withoutSite], true)).toEqual(['/Alpha/AA', 'Acme/Zeta/ZZ']) - }) -}) diff --git a/src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts b/src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts deleted file mode 100644 index e9851635314..00000000000 --- a/src/renderer/src/components/task-page/linear/task-page-linear-issue-request.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - buildLinearIssueListReadArgs, - buildLinearIssueListRequestSignature, - isLinearIssueSearchActive, - shouldClearTeamDerivedFacets, - shouldForceLinearIssueListRead, - teamDerivedFacetsForPrimaryTeamChange -} from './task-page-linear-issue-request' -import type { LinearIssueAttributeFilter } from '../../../../../shared/linear/issue-attribute-filter' - -const filter: LinearIssueAttributeFilter = { - stateIds: ['s1'], - priorities: [1], - assignee: { kind: 'unassigned' }, - labelIds: ['l1'] -} - -describe('task-page-linear-issue-request', () => { - it('treats immediate or applied search as active', () => { - expect(isLinearIssueSearchActive('q', '')).toBe(true) - expect(isLinearIssueSearchActive('', 'q')).toBe(true) - expect(isLinearIssueSearchActive(' ', ' ')).toBe(false) - }) - - it('omits attribute filters from list read args while search is active', () => { - expect( - buildLinearIssueListReadArgs({ - limit: 36, - attributeFilter: filter, - searchActive: true - }).attributeFilter - ).toBeUndefined() - expect( - buildLinearIssueListReadArgs({ - limit: 36, - attributeFilter: filter, - searchActive: false - }).attributeFilter - ).toEqual(filter) - }) - - it('includes source scope and canonical signature in the request identity', () => { - const signature = buildLinearIssueListRequestSignature({ - workspaceId: 'ws-1', - limit: 36, - attributeFilter: filter - }) - expect(signature).toContain('local::ws-1::list::all::36::') - expect(signature).toContain('"stateIds":["s1"]') - }) - - it('forces a read when the filter signature changes within one workspace', () => { - expect( - shouldForceLinearIssueListRead({ - previousFilterRead: { workspaceId: 'ws-1', signature: 'a' }, - nextFilterRead: { workspaceId: 'ws-1', signature: 'b' }, - refreshForced: false - }) - ).toBe(true) - expect( - shouldForceLinearIssueListRead({ - previousFilterRead: { workspaceId: 'ws-1', signature: 'a' }, - nextFilterRead: { workspaceId: 'ws-1', signature: 'a' }, - refreshForced: false - }) - ).toBe(false) - }) - - it('does not force the first read of a session, so a restored filter serves warm cache', () => { - expect( - shouldForceLinearIssueListRead({ - previousFilterRead: null, - nextFilterRead: { workspaceId: 'ws-1', signature: 'restored' }, - refreshForced: false - }) - ).toBe(false) - expect( - shouldForceLinearIssueListRead({ - previousFilterRead: null, - nextFilterRead: { workspaceId: 'ws-1', signature: 'restored' }, - refreshForced: true - }) - ).toBe(true) - }) - - // Workspace-keyed warm caches must not trigger a blocking forced round trip on every switch. - it('does not force on a workspace switch, even when each workspace has its own filter', () => { - expect( - shouldForceLinearIssueListRead({ - previousFilterRead: { workspaceId: 'ws-1', signature: 'filter-a' }, - nextFilterRead: { workspaceId: 'ws-2', signature: 'filter-b' }, - refreshForced: false - }) - ).toBe(false) - }) - - it('clears team-derived facets only when the primary team changes within one workspace', () => { - expect( - shouldClearTeamDerivedFacets({ - previous: { workspaceId: 'ws-1', teamId: 'team-a' }, - next: { workspaceId: 'ws-1', teamId: 'team-b' } - }) - ).toBe(true) - expect( - shouldClearTeamDerivedFacets({ - previous: { workspaceId: 'ws-1', teamId: 'team-a' }, - next: { workspaceId: 'ws-2', teamId: 'team-b' } - }) - ).toBe(false) - expect( - shouldClearTeamDerivedFacets({ - previous: null, - next: { workspaceId: 'ws-1', teamId: 'team-a' } - }) - ).toBe(false) - expect( - shouldClearTeamDerivedFacets({ - previous: { workspaceId: 'ws-1', teamId: 'team-a' }, - next: { workspaceId: 'ws-1', teamId: 'team-a' } - }) - ).toBe(false) - }) - - it('clears team-derived facets while preserving priority', () => { - expect(teamDerivedFacetsForPrimaryTeamChange(filter)).toEqual({ - stateIds: [], - priorities: [1], - assignee: null, - labelIds: [] - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-xterm-korean-enter-commit-order.test.ts b/src/renderer/src/components/terminal-pane/terminal-ime-xterm-korean-enter-commit-order.test.ts index 540f00d68a9..0f1288dc0a0 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-xterm-korean-enter-commit-order.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-xterm-korean-enter-commit-order.test.ts @@ -130,37 +130,4 @@ describe('STA-3132 — Korean commit reaches the PTY before the physical Enter', expect(stream.indexOf('가')).toBeLessThan(stream.indexOf('\r')) expect(stream).toBe('가\r') }) - - it('leaves ordinary non-IME typing followed by Enter unchanged', async () => { - const { emitted, textarea } = openTerminal() - for (const key of ['a', 'b', 'c']) { - dispatchKeydown(textarea, { - key, - code: `Key${key.toUpperCase()}`, - keyCode: key.toUpperCase().charCodeAt(0), - isComposing: false - }) - await nextEventLoop() - } - dispatchKeydown(textarea, { key: 'Enter', code: 'Enter', keyCode: 13, isComposing: false }) - await nextEventLoop() - - // The paired latin arm of the same capture session read `61 62 63 0d` at the PTY. - expect(emitted.join('')).toBe('abc\r') - }) - - // Back-to-back compositions exercise the pending-session force-end path (#12278); recorded 25/60/120 ms arms read 가 then CR then 나. - it('keeps the first syllable when the next composition starts immediately', async () => { - const { emitted, textarea } = openTerminal() - await composeGa(textarea) - await finalizeThenEnter(textarea) - await composeSyllable(textarea, 'KeyS', 'ㄴ', '나') - dispatchCompositionEvent(textarea, 'compositionend', '나') - await nextEventLoop() - - const stream = emitted.join('') - expect(stream).toBe('가\r나') - // A dropped flush loses the leading syllable; a double flush repeats it. - expect(stream.match(/가/g)).toHaveLength(1) - }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-ime-xterm-trailing-preedit-occlusion.test.ts b/src/renderer/src/components/terminal-pane/terminal-ime-xterm-trailing-preedit-occlusion.test.ts index 14305b53570..8506f21cba4 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ime-xterm-trailing-preedit-occlusion.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ime-xterm-trailing-preedit-occlusion.test.ts @@ -128,28 +128,6 @@ describe('#12729 — the block over a trailing Korean syllable is the preedit ov expect(rig.compositionView.querySelector('.xterm-composition-remainder')).toBeNull() }) - it('anchors the overlay to the cursor cell so the preedit continues the run', async () => { - const rig = openTerminal() - - await typeHangulRun(rig, ['가', '나', '다', '라']) - - expect(rig.compositionView.style.left).toBe(`${6 * CELL_WIDTH_PX}px`) - expect(rig.compositionView.style.height).toBe(`${CELL_HEIGHT_PX}px`) - // Synced to the grid's font so the preedit keeps the advance the committed syllables have. - expect(rig.compositionView.style.fontFamily).toBe(rig.terminal.options.fontFamily) - expect(rig.compositionView.style.fontSize).toBe(`${rig.terminal.options.fontSize}px`) - }) - - it('themes the trailing overlay instead of the stock opaque #000/#FFF block', async () => { - const rig = openTerminal() - - await typeHangulRun(rig, ['가', '나', '다', '라']) - - const { background, color } = rig.compositionView.style - expect([THEME.background, 'rgb(17, 34, 51)']).toContain(background) - expect([THEME.foreground, 'rgb(170, 187, 204)']).toContain(color) - }) - it('clears the overlay once the trailing syllable commits', async () => { const rig = openTerminal() await typeHangulRun(rig, ['가', '나', '다', '라']) diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts deleted file mode 100644 index fd549bb2947..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pane-host-state.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import { selectWorktreeHostConnectionPhase } from '@/lib/worktree-host-connection-phase' -import { selectTerminalPaneHostState } from './terminal-pane-host-state' - -function makeState(overrides: Record): AppState { - return { - activeWorktreeId: null, - detectedWorktreesByRepo: {}, - folderWorkspaces: [], - projectGroups: [], - removedSshTargetLabels: new Map(), - repos: [], - runtimeStatusByEnvironmentId: new Map(), - sshConnectionStates: new Map(), - sshStateByEnvironment: new Map(), - sshTargetLabels: new Map(), - sshTargetsHydrated: true, - worktreesByRepo: {}, - ...overrides - } as unknown as AppState -} - -describe('selectTerminalPaneHostState', () => { - it('resolves local and direct SSH workspaces without changing reconnect semantics', () => { - const localState = makeState({ - repos: [{ id: 'repo-local' }], - worktreesByRepo: { - 'repo-local': [{ id: 'wt-local', repoId: 'repo-local' }] - } - }) - - expect(selectTerminalPaneHostState(localState, 'wt-local')).toEqual({ - nativeChatTranscriptIsLocalReadable: true, - sshReconnectEnvironmentId: null, - sshReconnectError: null, - sshReconnectStatus: null, - sshReconnectTargetId: null, - sshReconnectTargetLabel: '', - sshReconnectTargetRemoved: false - }) - - const sshState = makeState({ - repos: [{ id: 'repo-ssh', connectionId: 'ssh-a' }], - sshConnectionStates: new Map([ - ['ssh-a', { targetId: 'ssh-a', status: 'connected', error: null, reconnectAttempt: 0 }] - ]), - sshTargetLabels: new Map([['ssh-a', 'devbox']]), - worktreesByRepo: { - 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] - } - }) - - expect(selectTerminalPaneHostState(sshState, 'wt-ssh')).toEqual({ - nativeChatTranscriptIsLocalReadable: false, - sshReconnectEnvironmentId: null, - sshReconnectError: null, - sshReconnectStatus: 'connected', - sshReconnectTargetId: 'ssh-a', - sshReconnectTargetLabel: 'devbox', - sshReconnectTargetRemoved: false - }) - }) - - it('reads nested SSH state from the worktree owner runtime', () => { - const state = makeState({ - repos: [ - { - id: 'repo-runtime', - connectionId: 'ssh-nested', - executionHostId: 'runtime:env-a' - } - ], - runtimeStatusByEnvironmentId: new Map([ - ['env-a', { status: { runtimeId: 'runtime-a' }, checkedAt: 1 }] - ]), - sshStateByEnvironment: new Map([ - [ - 'env-a', - { - connectionStates: new Map([ - [ - 'ssh-nested', - { - targetId: 'ssh-nested', - status: 'disconnected', - error: null, - reconnectAttempt: 0 - } - ] - ]), - targetLabels: new Map([['ssh-nested', 'build box']]), - removedTargetLabels: new Map(), - targetsHydrated: true - } - ] - ]), - worktreesByRepo: { - 'repo-runtime': [ - { - id: 'wt-runtime', - repoId: 'repo-runtime', - hostId: 'runtime:env-a', - runtimeOwnerEnvironmentId: 'env-a' - } - ] - } - }) - - expect(selectTerminalPaneHostState(state, 'wt-runtime')).toEqual({ - nativeChatTranscriptIsLocalReadable: false, - sshReconnectEnvironmentId: 'env-a', - sshReconnectError: null, - sshReconnectStatus: 'disconnected', - sshReconnectTargetId: 'ssh-nested', - sshReconnectTargetLabel: 'build box', - sshReconnectTargetRemoved: false - }) - }) - - // Expose the host’s detail so terminal overlays include actionable rejection remedies. - it('carries the failure detail alongside the status', () => { - const state = makeState({ - repos: [{ id: 'repo-ssh', connectionId: 'ssh-a' }], - sshConnectionStates: new Map([ - [ - 'ssh-a', - { - targetId: 'ssh-a', - status: 'error', - error: 'Host key verification failed for devbox. Run: ssh-keygen -R devbox', - reconnectAttempt: 0 - } - ] - ]), - sshTargetLabels: new Map([['ssh-a', 'devbox']]), - worktreesByRepo: { 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] } - }) - - const host = selectTerminalPaneHostState(state, 'wt-ssh') - - expect(host.sshReconnectStatus).toBe('error') - expect(host.sshReconnectError).toContain('ssh-keygen -R devbox') - }) - - it('keeps runtime-owned SSH plumbing out of reconnect UI', () => { - const state = makeState({ - repos: [{ id: 'repo-ephemeral', connectionId: 'runtime-ssh-vm-a' }], - worktreesByRepo: { - 'repo-ephemeral': [{ id: 'wt-ephemeral', repoId: 'repo-ephemeral' }] - } - }) - - expect(selectTerminalPaneHostState(state, 'wt-ephemeral')).toEqual({ - nativeChatTranscriptIsLocalReadable: true, - sshReconnectEnvironmentId: null, - sshReconnectError: null, - sshReconnectStatus: null, - sshReconnectTargetId: null, - sshReconnectTargetLabel: '', - sshReconnectTargetRemoved: false - }) - }) - - // Keep published disconnected status during startup; shared connecting hints must not change terminal overlay/error ownership. - it('reports the published status through the shared signal, across startup and connect', () => { - const repos = [{ id: 'repo-ssh', connectionId: 'ssh-a' }] - const worktreesByRepo = { 'repo-ssh': [{ id: 'wt-ssh', repoId: 'repo-ssh' }] } - const withStatus = (status: string | null): AppState => - makeState({ - repos, - worktreesByRepo, - terminalStartupRestorationReady: false, - sshConnectionStates: new Map( - status ? [['ssh-a', { targetId: 'ssh-a', status, error: null, reconnectAttempt: 0 }]] : [] - ) - }) - - expect(selectWorktreeHostConnectionPhase(withStatus(null), 'wt-ssh').phase).toBe('connecting') - expect(selectTerminalPaneHostState(withStatus(null), 'wt-ssh').sshReconnectStatus).toBe( - 'disconnected' - ) - expect(selectTerminalPaneHostState(withStatus('connecting'), 'wt-ssh').sshReconnectStatus).toBe( - 'connecting' - ) - expect(selectTerminalPaneHostState(withStatus('connected'), 'wt-ssh').sshReconnectStatus).toBe( - 'connected' - ) - }) - - // Missing owner-runtime SSH state is unknown; show no disconnected overlay without evidence. - it('reports no status for a nested target whose runtime has not published its SSH state', () => { - const state = makeState({ - repos: [{ id: 'repo-runtime', connectionId: 'ssh-nested', executionHostId: 'runtime:env-a' }], - runtimeStatusByEnvironmentId: new Map([ - ['env-a', { status: { runtimeId: 'runtime-a' }, checkedAt: 1 }] - ]), - sshStateByEnvironment: new Map([ - [ - 'env-a', - { - connectionStates: new Map(), - targetLabels: new Map(), - removedTargetLabels: new Map(), - targetsHydrated: false - } - ] - ]), - worktreesByRepo: { - 'repo-runtime': [ - { - id: 'wt-runtime', - repoId: 'repo-runtime', - hostId: 'runtime:env-a', - runtimeOwnerEnvironmentId: 'env-a' - } - ] - } - }) - - expect(selectWorktreeHostConnectionPhase(state, 'wt-runtime').phase).toBe('unverifiable') - expect(selectTerminalPaneHostState(state, 'wt-runtime')).toMatchObject({ - sshReconnectEnvironmentId: 'env-a', - sshReconnectStatus: null, - sshReconnectTargetId: 'ssh-nested' - }) - }) -}) diff --git a/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx b/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx deleted file mode 100644 index 8834c240086..00000000000 --- a/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx +++ /dev/null @@ -1,156 +0,0 @@ -// @vitest-environment happy-dom - -import { cleanup, render, type RenderResult, screen } from '@testing-library/react' -import { afterEach, expect, it } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { PaletteLocationChip, PaletteOpenTabPrimaryLine } from './worktree-jump-palette-primitives' - -afterEach(() => cleanup()) - -function renderPrimaryLine( - secondaryMatches: readonly { text: string; ranges: readonly never[] }[] -): RenderResult { - return render( - - - - ) -} - -it('exposes the extra secondary matches through the row text, not the tab order', () => { - const { container } = renderPrimaryLine([ - { text: 'src/app.ts', ranges: [] }, - { text: 'src/deep/nested.ts', ranges: [] }, - { text: 'docs/readme.md', ranges: [] } - ]) - - const extraMatches = container.querySelector('[data-slot="palette-open-tab-extra-matches"]') - expect(extraMatches?.textContent).toBe('src/deep/nested.ts, docs/readme.md') - - const badge = screen.getByText('+2') - expect(badge.getAttribute('aria-hidden')).toBe('true') - expect(badge.tabIndex).toBe(-1) -}) - -it('renders no badge when every secondary match is already shown', () => { - renderPrimaryLine([{ text: 'src/app.ts', ranges: [] }]) - - expect(screen.queryByText(/^\+\d+$/)).toBeNull() -}) - -it('elides a deep path from the head so the matched tail stays visible', () => { - const path = '/Users/me/projects/orca/new-create-button-design/proposals/create-button.html' - const start = path.indexOf('create-butt') - const { container } = render( - - - - ) - - const secondary = container.querySelector('[data-slot="palette-open-tab-secondary"]') - expect(secondary?.textContent).toBe(path) - const [head, tail] = Array.from(secondary?.children ?? []) - expect(head?.textContent).toBe('/Users/me/projects/orca') - expect(tail?.textContent).toBe('/new-create-button-design/proposals/create-button.html') - expect(tail?.querySelector('.font-semibold')?.textContent).toBe('create-butt') -}) - -it('keeps slash-separated agent snippets intact', () => { - const snippet = - 'Ran pnpm test src/renderer/src/components/worktree-jump-palette-primitives.test.tsx' - const start = snippet.indexOf('worktree-jump') - const { container } = render( - - - - ) - - const secondary = container.querySelector('[data-slot="palette-open-tab-secondary"]') - expect(secondary?.textContent).toBe(snippet) - expect(secondary?.children).toHaveLength(1) - expect(secondary?.querySelector('.font-semibold')?.textContent).toBe('worktree-jump') -}) - -it('folds the worktree into the repo chip and drops it when it repeats the repo name', () => { - const { container, rerender } = render( - - - - ) - expect(container.querySelector('[data-slot="palette-location-chip"]')?.textContent).toBe( - 'orca·new-create-button-design' - ) - const chip = container.querySelector('[data-slot="palette-location-chip"]') - const repo = container.querySelector('[data-slot="palette-location-repo"]') - const worktree = container.querySelector('[data-slot="palette-open-tab-worktree"]') - expect(chip?.className).toContain('overflow-hidden') - expect(chip?.className).toContain('min-w-0') - expect(repo?.className).toContain('max-w-[55%]') - expect(repo?.className).toContain('min-w-[3ch]') - expect(worktree?.className).toContain('min-w-[3ch]') - expect(worktree?.getAttribute('data-state')).toBeNull() - expect(worktree?.getAttribute('tabindex')).toBeNull() - - rerender( - - - - ) - expect(container.querySelector('[data-slot="palette-location-chip"]')?.textContent).toBe('orca') - expect( - container.querySelector('[data-slot="palette-location-repo"] .font-semibold')?.textContent - ).toBe('orca') -}) - -it('keeps a short title at its natural width so the session age stays beside it', () => { - const { container } = render( - - - - ) - - const title = container.querySelector('[data-slot="palette-open-tab-title"]') - expect(title?.className).toContain('min-w-0') - expect(title?.className).not.toContain('shrink-0') -}) - -it('caps the title only when it shares the line with secondary text', () => { - const { container } = renderPrimaryLine([]) - - const title = container.querySelector('[data-slot="palette-open-tab-title"]') - expect(title?.className).toContain('max-w-[62%]') - expect(title?.className).toContain('shrink-0') -}) diff --git a/src/renderer/src/store/project-host-setup-selector.test.ts b/src/renderer/src/store/project-host-setup-selector.test.ts index c6de8f65820..260a18197ac 100644 --- a/src/renderer/src/store/project-host-setup-selector.test.ts +++ b/src/renderer/src/store/project-host-setup-selector.test.ts @@ -114,29 +114,6 @@ describe('project host setup selector', () => { expect(countedSetups.counters).toEqual({ map: 0, flatMap: 0, iterator: 0, length: 0 }) }) - it('invalidates the projection when hydrated setup identity changes', () => { - const repo = makeRepo('repo-1') - const repos = [repo] - const projects = [makeProject('repo:repo-1', repo.id)] - const setups = [makeSetup(repo.id, 'repo:repo-1')] - const first = getProjectHostSetupProjectionFromState({ - repos, - projects, - projectHostSetups: setups - }) - const replacementSetups = [...setups] - - const next = getProjectHostSetupProjectionFromState({ - repos, - projects, - projectHostSetups: replacementSetups - }) - - expect(next).not.toBe(first) - expect(next.projects).toBe(projects) - expect(next.setups).toBe(replacementSetups) - }) - it('invalidates the projection when the repo identity changes', () => { const repo = makeRepo('repo-1') const repos = [repo] diff --git a/src/renderer/src/store/slices/persisted-ui-write-baseline.test.ts b/src/renderer/src/store/slices/persisted-ui-write-baseline.test.ts index cc132e17cb8..da52e278d61 100644 --- a/src/renderer/src/store/slices/persisted-ui-write-baseline.test.ts +++ b/src/renderer/src/store/slices/persisted-ui-write-baseline.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from 'vitest' import { - PERSISTED_UI_WRITE_BASELINE_FIELDS, - capturePersistedUIWriteBaseline, diffPersistedUIWriteFields, - persistedUIWriteFieldsToWireUpdate, type PersistedUIWriteBaseline } from './persisted-ui-write-baseline' @@ -39,23 +36,6 @@ function makeBaseline(overrides: Partial = {}): Persis } } -describe('capturePersistedUIWriteBaseline', () => { - it('picks exactly the writer-owned fields off a superset', () => { - const superset = { ...makeBaseline(), persistedUIReady: true, repos: [] } - const captured = capturePersistedUIWriteBaseline(superset) - expect(Object.keys(captured).sort()).toEqual([...PERSISTED_UI_WRITE_BASELINE_FIELDS].sort()) - }) -}) - -describe('PERSISTED_UI_WRITE_BASELINE_FIELDS', () => { - it('covers every writer-owned field (runtime census, independent of the impl list)', () => { - // Maintain independent full literal so omitted writer fields fail even when typechecking is skipped. - expect([...PERSISTED_UI_WRITE_BASELINE_FIELDS].sort()).toEqual( - Object.keys(makeBaseline()).sort() - ) - }) -}) - describe('diffPersistedUIWriteFields', () => { it('is empty when values are equal even across fresh array/record identities', () => { const a = makeBaseline({ @@ -110,58 +90,3 @@ describe('diffPersistedUIWriteFields', () => { expect(diffPersistedUIWriteFields(current, baseline)).toEqual({ filterRepoIds: ['r2', 'r1'] }) }) }) - -describe('manuallyUnreadTurnsByPaneKey write round-trip', () => { - it('is writer-owned and diffs by record content like the other pane-key records', () => { - expect(PERSISTED_UI_WRITE_BASELINE_FIELDS).toContain('manuallyUnreadTurnsByPaneKey') - const baseline = makeBaseline({ manuallyUnreadTurnsByPaneKey: { p1: 5 } }) - expect( - diffPersistedUIWriteFields( - makeBaseline({ manuallyUnreadTurnsByPaneKey: { p1: 5 } }), - baseline - ) - ).toEqual({}) - expect( - diffPersistedUIWriteFields( - makeBaseline({ manuallyUnreadTurnsByPaneKey: { p1: 7 } }), - baseline - ) - ).toEqual({ manuallyUnreadTurnsByPaneKey: { p1: 7 } }) - expect(persistedUIWriteFieldsToWireUpdate({ manuallyUnreadTurnsByPaneKey: { p1: 7 } })).toEqual( - { manuallyUnreadTurnsByPaneKey: { p1: 7 } } - ) - }) -}) - -describe('persistedUIWriteFieldsToWireUpdate', () => { - it('inverts showSleepingWorkspaces to the durable hide form', () => { - expect(persistedUIWriteFieldsToWireUpdate({ showSleepingWorkspaces: true })).toEqual({ - hideSleepingWorkspaces: false - }) - expect(persistedUIWriteFieldsToWireUpdate({ showSleepingWorkspaces: false })).toEqual({ - hideSleepingWorkspaces: true - }) - }) - - it('copies filterRepoIds so main never receives the readonly store array', () => { - const filterRepoIds = ['r1'] - const update = persistedUIWriteFieldsToWireUpdate({ filterRepoIds }) - expect(update.filterRepoIds).toEqual(['r1']) - expect(update.filterRepoIds).not.toBe(filterRepoIds) - }) - - it('passes same-name fields through and never invents keys', () => { - const update = persistedUIWriteFieldsToWireUpdate({ - hideDefaultBranchWorkspace: true, - groupBy: 'none' - }) - expect(update).toEqual({ hideDefaultBranchWorkspace: true, groupBy: 'none' }) - }) -}) - -describe('sidebarOpen write round-trip', () => { - it('sends a left sidebar close to main under its persisted key', () => { - const changed = diffPersistedUIWriteFields(makeBaseline({ sidebarOpen: false }), makeBaseline()) - expect(persistedUIWriteFieldsToWireUpdate(changed)).toEqual({ sidebarOpen: false }) - }) -}) diff --git a/src/renderer/src/store/slices/terminal-helpers.test.ts b/src/renderer/src/store/slices/terminal-helpers.test.ts deleted file mode 100644 index bed0a44e819..00000000000 --- a/src/renderer/src/store/slices/terminal-helpers.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import { clearTransientTerminalState } from './terminal-helpers' - -function makeTab(overrides: Partial = {}): TerminalTab { - return { - id: 'tab-1', - ptyId: 'pty-123', - worktreeId: 'wt-1', - title: 'bash', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now(), - ...overrides - } -} - -describe('clearTransientTerminalState', () => { - it('clears ptyId to null', () => { - const tab = makeTab({ ptyId: 'pty-abc' }) - const result = clearTransientTerminalState(tab, 0) - expect(result.ptyId).toBeNull() - }) - - it('uses customTitle as fallback when tab has agent status in title', () => { - const tab = makeTab({ title: '. claude', customTitle: 'My Agent' }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('My Agent') - }) - - it('uses "Terminal {index+1}" fallback when agent status in title and no customTitle', () => { - const tab = makeTab({ title: '. claude', customTitle: null }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('Terminal 1') - }) - - it('prefers defaultTitle over index fallback when present', () => { - const tab = makeTab({ title: '. claude', customTitle: null, defaultTitle: 'Terminal 4' }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('Terminal 4') - }) - - it('keeps original title when no agent status detected', () => { - const tab = makeTab({ title: 'bash' }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('bash') - }) - - // Prior-session agents are no longer running after restart; do not restore misleading done/spinner titles. - it('resets idle agent titles to fallback across hydration', () => { - const tab = makeTab({ title: '* Claude done', customTitle: null }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('Terminal 1') - }) - - it('also resets working agent titles to fallback across hydration', () => { - const tab = makeTab({ title: '⠋ Claude working', customTitle: null }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('Terminal 1') - }) - - it('uses "Terminal {index+1}" when customTitle is whitespace only', () => { - const tab = makeTab({ title: '⠋ codex running', customTitle: ' ' }) - const result = clearTransientTerminalState(tab, 0) - expect(result.title).toBe('Terminal 1') - }) - - it('index-based fallback numbering: index 2 → "Terminal 3"', () => { - const tab = makeTab({ title: '. claude', customTitle: null }) - const result = clearTransientTerminalState(tab, 2) - expect(result.title).toBe('Terminal 3') - }) -}) From 68a4bfb58f25d0bbf04e4e5d56debeade35e4e31 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:34:29 -0700 Subject: [PATCH 3/5] fix(runtime-host): Explorer and Source Control load again once a runtime host answers (#36684) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(runtime-host): Explorer and Source Control load again once a runtime host answers After a relaunch with a WSL-host workspace active, both panels read before the host connected: Explorer kept "the Orca server … isn't answering" until Retry, and Source Control kept a clean status until a reload. The runtime status stays verified across the relaunch, so the existing contact-regained signal never fired when the WSL host's connection came up. - subscribeRuntimeHostContactRegained also fires when the environment's WSL host turns ready. - Explorer reloads a failed root on that signal (gated: never boots a stopped distro), as it already does for SSH providers. - Git status polling reads again on that signal. Co-Authored-By: Claude * fix(runtime-host): keep the Explorer's contact retry current from an effect, not render React Doctor flags a ref mutated during render. Co-Authored-By: Claude --------- Co-authored-by: Claude --- .../file-explorer-host-contact-retry.test.tsx | 72 +++++++++++++++++++ .../use-file-explorer-tree-load-effects.ts | 24 +++++++ .../use-refresh-on-host-contact.test.ts | 42 +++++++++++ .../use-refresh-on-host-contact.ts | 24 +++++++ .../right-sidebar/useGitStatusPolling.ts | 3 + ...me-host-contact-regained-wsl-ready.test.ts | 53 ++++++++++++++ .../runtime/runtime-host-contact-regained.ts | 16 ++++- 7 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/file-explorer-host-contact-retry.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.test.ts create mode 100644 src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.ts create mode 100644 src/renderer/src/runtime/runtime-host-contact-regained-wsl-ready.test.ts diff --git a/src/renderer/src/components/right-sidebar/file-explorer-host-contact-retry.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer-host-contact-retry.test.tsx new file mode 100644 index 00000000000..3f9aadf3695 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/file-explorer-host-contact-retry.test.tsx @@ -0,0 +1,72 @@ +// @vitest-environment happy-dom +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' + +const contact = vi.hoisted(() => ({ listeners: new Map void>() })) +vi.mock('@/runtime/runtime-host-contact-regained', () => ({ + subscribeRuntimeHostContactRegained: (environmentId: string, listener: () => void) => { + contact.listeners.set(environmentId, listener) + return () => contact.listeners.delete(environmentId) + } +})) +vi.mock('@/lib/worktree-runtime-owner', () => ({ + runtimeEnvironmentIdOrLocalUnlessTwin: (_state: unknown, workspaceId: string | null) => + workspaceId === 'wt-host' ? 'wsl:ubuntu' : null +})) +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: unknown) => T) => + selector({ settings: {}, sshConnectedGeneration: 0 }) +})) +vi.mock('@/lib/workspace-switch-user-act', () => ({ takeRecentWorkspaceSwitchWake: () => false })) + +import { useFileExplorerTreeLoadEffects } from './use-file-explorer-tree-load-effects' + +afterEach(() => { + cleanup() + contact.listeners.clear() +}) + +function render(workspaceKey: string, rootError: string | null) { + const resetAndLoad = vi.fn() + const hook = renderHook( + ({ error }: { error: string | null }) => + useFileExplorerTreeLoadEffects({ + workspaceKey, + visibleFilesWorktreePath: '/home/u/app', + expanded: new Set(), + dirCache: {}, + loadingDirPaths: new Set(), + rootError: error, + isDirStale: () => false, + loadDir: vi.fn(async () => true), + refreshTree: vi.fn(async () => undefined), + resetAndLoad, + resetSelection: vi.fn(), + setNameFilterQuery: vi.fn() + }), + { initialProps: { error: rootError } } + ) + resetAndLoad.mockClear() + return { hook, resetAndLoad } +} + +// QA F1: after a relaunch the tree loaded before the WSL host answered and showed its error until Retry. +it('reloads a tree that failed once its runtime host answers again', () => { + const { resetAndLoad } = render('wt-host', 'The Orca server in the WSL distro isn’t answering') + contact.listeners.get('wsl:ubuntu')?.() + expect(resetAndLoad).toHaveBeenCalledOnce() + // Without the user acting, so a stopped distro is never booted for it (E9). + expect(resetAndLoad).toHaveBeenCalledWith() +}) + +it('leaves a tree that loaded fine alone, and a local workspace never subscribes', () => { + const { hook, resetAndLoad } = render('wt-host', 'failed') + hook.rerender({ error: null }) + contact.listeners.get('wsl:ubuntu')?.() + expect(resetAndLoad).not.toHaveBeenCalled() + + cleanup() + contact.listeners.clear() + render('wt-local', 'failed') + expect(contact.listeners.size).toBe(0) +}) diff --git a/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects.ts b/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects.ts index 9feddf986cf..e92fda4c620 100644 --- a/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects.ts +++ b/src/renderer/src/components/right-sidebar/use-file-explorer-tree-load-effects.ts @@ -7,6 +7,8 @@ import { clearFileExplorerUndoHistory } from './fileExplorerUndoRedo' import type { DirCache } from './file-explorer-types' import { splitPathSegments } from '../../../../shared/cross-platform-path' import { takeRecentWorkspaceSwitchWake } from '@/lib/workspace-switch-user-act' +import { runtimeEnvironmentIdOrLocalUnlessTwin } from '@/lib/worktree-runtime-owner' +import { subscribeRuntimeHostContactRegained } from '@/runtime/runtime-host-contact-regained' type UseFileExplorerTreeLoadEffectsParams = { /** The store worktree id, keying the user's own switches to this workspace. */ @@ -107,6 +109,28 @@ export function useFileExplorerTreeLoadEffects({ } }, [sshConnectedGeneration, visibleFilesWorktreePath]) // eslint-disable-line react-hooks/exhaustive-deps + // The same for a runtime host (WSL or SSH server): a relaunch can load before it answers. + const runtimeEnvironmentId = useAppStore((s) => + runtimeEnvironmentIdOrLocalUnlessTwin(s, workspaceKey) + ) + const retryAfterContactRef = useRef(() => {}) + // Kept current from an effect, not render; the subscription below outlives renders. + useEffect(() => { + retryAfterContactRef.current = () => { + if (visibleFilesWorktreePath && rootError) { + resetAndLoad() + } + } + }, [visibleFilesWorktreePath, rootError, resetAndLoad]) + useEffect(() => { + if (!runtimeEnvironmentId) { + return + } + return subscribeRuntimeHostContactRegained(runtimeEnvironmentId, () => + retryAfterContactRef.current() + ) + }, [runtimeEnvironmentId]) + useEffect(() => { if ( !visibleFilesWorktreePath || diff --git a/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.test.ts b/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.test.ts new file mode 100644 index 00000000000..8ed5c3e88af --- /dev/null +++ b/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.test.ts @@ -0,0 +1,42 @@ +// @vitest-environment happy-dom +import { cleanup, renderHook } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' + +const contact = vi.hoisted(() => ({ listeners: new Map void>() })) +vi.mock('@/runtime/runtime-host-contact-regained', () => ({ + subscribeRuntimeHostContactRegained: (environmentId: string, listener: () => void) => { + contact.listeners.set(environmentId, listener) + return () => contact.listeners.delete(environmentId) + } +})) +vi.mock('@/lib/window-visibility-interval', () => ({ isWindowVisible: () => true })) + +import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' +import { useRefreshOnHostContact } from './use-refresh-on-host-contact' + +afterEach(() => { + cleanup() + contact.listeners.clear() +}) + +// QA F1: Source Control showed "clean" after a relaunch while the guest had a modified file. +it('reads Git status again when the runtime host answers, while it may fetch', () => { + const scheduler = { current: { refreshNow: vi.fn() } } + const canFetch = { current: true } + renderHook(() => + useRefreshOnHostContact(toRuntimeExecutionHostId('wsl:ubuntu'), scheduler, canFetch) + ) + contact.listeners.get('wsl:ubuntu')?.() + expect(scheduler.current.refreshNow).toHaveBeenCalledOnce() + + canFetch.current = false + contact.listeners.get('wsl:ubuntu')?.() + expect(scheduler.current.refreshNow).toHaveBeenCalledOnce() +}) + +it('does nothing for a workspace on this computer', () => { + renderHook(() => + useRefreshOnHostContact('local', { current: { refreshNow: vi.fn() } }, { current: true }) + ) + expect(contact.listeners.size).toBe(0) +}) diff --git a/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.ts b/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.ts new file mode 100644 index 00000000000..8b5d6e0f92d --- /dev/null +++ b/src/renderer/src/components/right-sidebar/use-refresh-on-host-contact.ts @@ -0,0 +1,24 @@ +import { useEffect } from 'react' +import { isWindowVisible } from '@/lib/window-visibility-interval' +import { subscribeRuntimeHostContactRegained } from '@/runtime/runtime-host-contact-regained' +import { parseExecutionHostId } from '../../../../shared/execution-host' + +/** A status read before the runtime host answered (a relaunch) came back empty; read again once it does. */ +export function useRefreshOnHostContact( + executionHostId: string | null | undefined, + scheduler: { readonly current: { refreshNow: () => void } | null }, + canFetch: { readonly current: boolean } +): void { + const host = parseExecutionHostId(executionHostId) + const environmentId = host?.kind === 'runtime' ? host.environmentId : null + useEffect(() => { + if (!environmentId) { + return + } + return subscribeRuntimeHostContactRegained(environmentId, () => { + if (canFetch.current && isWindowVisible()) { + scheduler.current?.refreshNow() + } + }) + }, [environmentId, scheduler, canFetch]) +} diff --git a/src/renderer/src/components/right-sidebar/useGitStatusPolling.ts b/src/renderer/src/components/right-sidebar/useGitStatusPolling.ts index 1256299a899..bf9ed2f00bd 100644 --- a/src/renderer/src/components/right-sidebar/useGitStatusPolling.ts +++ b/src/renderer/src/components/right-sidebar/useGitStatusPolling.ts @@ -6,6 +6,7 @@ import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' import { refreshGitStatusForWorktree } from './git-status-refresh' import { isWindowVisible } from '@/lib/window-visibility-interval' import { takeRecentWorkspaceSwitchWake } from '@/lib/workspace-switch-user-act' +import { useRefreshOnHostContact } from './use-refresh-on-host-contact' import { hasInteractiveActiveGitStatusConsumer, shouldPollActiveGitStatus @@ -249,6 +250,8 @@ export function useGitStatusPolling(options: { enabled?: boolean } = {}): void { } }, [activeStatusPollScope, canFetchActiveWorktreeGitStatus]) + useRefreshOnHostContact(activeExecutionHostId, statusSchedulerRef, canApplyScheduledStatusRef) + const previousConsumerVisibilityRef = useRef({ worktreeId: activeWorktreeId, visible: interactiveConsumerVisible, diff --git a/src/renderer/src/runtime/runtime-host-contact-regained-wsl-ready.test.ts b/src/renderer/src/runtime/runtime-host-contact-regained-wsl-ready.test.ts new file mode 100644 index 00000000000..e918f9220b1 --- /dev/null +++ b/src/renderer/src/runtime/runtime-host-contact-regained-wsl-ready.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/store', async () => { + const { create } = await import('zustand') + return { + useAppStore: create(() => { + const wslHostStatuses: Record = {} + return { runtimeStatusByEnvironmentId: new Map(), runtimeEnvironments: [], wslHostStatuses } + }) + } +}) + +import { useAppStore } from '@/store' +import { subscribeRuntimeHostContactRegained } from './runtime-host-contact-regained' +import type { WslHostConnectionState } from '../../../shared/wsl-host-types' + +function wslHost(state: WslHostConnectionState): void { + useAppStore.setState({ + wslHostStatuses: { + 'wsl:ubuntu': { environmentId: 'wsl:ubuntu', distro: 'Ubuntu', state, detail: null } + } + }) +} + +// QA F1: after a relaunch the runtime status stayed verified while the WSL host connected, so +// panels that loaded before it never heard the host was back. +describe('regaining a WSL host', () => { + it('counts the host becoming ready, once per return', () => { + wslHost('connecting') + const listener = vi.fn() + const stop = subscribeRuntimeHostContactRegained('wsl:ubuntu', listener) + + wslHost('ready') + expect(listener).toHaveBeenCalledOnce() + wslHost('ready') + expect(listener).toHaveBeenCalledOnce() + + wslHost('distro-stopped') + expect(listener).toHaveBeenCalledOnce() + wslHost('ready') + expect(listener).toHaveBeenCalledTimes(2) + stop() + }) + + it('ignores another environment', () => { + const listener = vi.fn() + const stop = subscribeRuntimeHostContactRegained('wsl:debian', listener) + wslHost('connecting') + wslHost('ready') + expect(listener).not.toHaveBeenCalled() + stop() + }) +}) diff --git a/src/renderer/src/runtime/runtime-host-contact-regained.ts b/src/renderer/src/runtime/runtime-host-contact-regained.ts index 4ba155a4bad..b10153e6c37 100644 --- a/src/renderer/src/runtime/runtime-host-contact-regained.ts +++ b/src/renderer/src/runtime/runtime-host-contact-regained.ts @@ -13,25 +13,37 @@ function contactMarks(state: AppState, environmentId: string): string { : runtimeEnvironmentContinuityStamp(environmentId) } +function wslHostReady(state: AppState, environmentId: string): boolean { + // Optional: test stores built from one slice carry no WSL host statuses. + return state.wslHostStatuses?.[environmentId]?.state === 'ready' +} + /** * Calls `listener` each time this client regains contact with an environment's runtime: the * same-runtime return (`hostContactEpoch`) or a new runtime session (`connectionGeneration`), - * or resolved pairing continuity published by runtime-status.ts. + * resolved pairing continuity published by runtime-status.ts, or its WSL host's connection + * becoming ready, which a status kept verified across a relaunch does not show. */ export function subscribeRuntimeHostContactRegained( environmentId: string, listener: () => void ): () => void { let lastMarks = contactMarks(useAppStore.getState(), environmentId) + let lastWslReady = wslHostReady(useAppStore.getState(), environmentId) return useAppStore.subscribe((state, previousState) => { + const wslChanged = state.wslHostStatuses !== previousState.wslHostStatuses if ( + !wslChanged && state.runtimeStatusByEnvironmentId === previousState.runtimeStatusByEnvironmentId && state.runtimeEnvironments === previousState.runtimeEnvironments ) { return } + const wslReady = wslHostReady(state, environmentId) + const becameReady = wslReady && !lastWslReady + lastWslReady = wslReady const marks = contactMarks(state, environmentId) - if (marks === lastMarks) { + if (marks === lastMarks && !becameReady) { return } lastMarks = marks From 1804e44610c84b5d36dc2bf8bb008041bafcfbd6 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:43:57 -0700 Subject: [PATCH 4/5] refactor(mobile): colocate chat pinch gesture hook and tests (#36690) --- mobile/src/session/MobileNativeChatView.tsx | 2 +- .../transcript}/use-mobile-native-chat-pinch-gesture.test.ts | 5 +---- .../transcript}/use-mobile-native-chat-pinch-gesture.ts | 2 +- 3 files changed, 3 insertions(+), 6 deletions(-) rename mobile/src/session/{ => native-chat/transcript}/use-mobile-native-chat-pinch-gesture.test.ts (95%) rename mobile/src/session/{ => native-chat/transcript}/use-mobile-native-chat-pinch-gesture.ts (91%) diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index 1ae147fc458..2781eb57e75 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -35,7 +35,7 @@ import { type MobileNativeChatPendingItem } from './mobile-native-chat-render-data' import { useMobileNativeChatRowKeys } from './native-chat/transcript/mobile-native-chat-row-keys' -import { useMobileNativeChatPinchGesture } from './use-mobile-native-chat-pinch-gesture' +import { useMobileNativeChatPinchGesture } from './native-chat/transcript/use-mobile-native-chat-pinch-gesture' import { useMobileNativeChatTailFollow } from './use-mobile-native-chat-tail-follow' import { useMobileNativeChatTurnDisclosure } from './native-chat/transcript/use-mobile-native-chat-turn-disclosure' import { diff --git a/mobile/src/session/use-mobile-native-chat-pinch-gesture.test.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts similarity index 95% rename from mobile/src/session/use-mobile-native-chat-pinch-gesture.test.ts rename to mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts index c67797c6220..770ac1d8cc7 100644 --- a/mobile/src/session/use-mobile-native-chat-pinch-gesture.test.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.test.ts @@ -1,10 +1,7 @@ import { createElement } from 'react' import { act, create } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - FONT_SCALE_STEP, - quantizeFontScale -} from './native-chat/transcript/mobile-native-chat-message-text' +import { FONT_SCALE_STEP, quantizeFontScale } from './mobile-native-chat-message-text' const handlers: { start?: () => void; update?: (e: { scale: number }) => void } = {} diff --git a/mobile/src/session/use-mobile-native-chat-pinch-gesture.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.ts similarity index 91% rename from mobile/src/session/use-mobile-native-chat-pinch-gesture.ts rename to mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.ts index 3550602b940..03972a5d15d 100644 --- a/mobile/src/session/use-mobile-native-chat-pinch-gesture.ts +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-pinch-gesture.ts @@ -1,7 +1,7 @@ import { useMemo, useRef, useState } from 'react' import { Gesture } from 'react-native-gesture-handler' import type { ComposedGesture } from 'react-native-gesture-handler' -import { quantizeFontScale } from './native-chat/transcript/mobile-native-chat-message-text' +import { quantizeFontScale } from './mobile-native-chat-message-text' // Anchor each pinch on the committed scale so successive gestures compound. export function useMobileNativeChatPinchGesture(): { From 1da1099dadb780b7206b6d562be730a4341bd29c Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 31 Oct 2026 07:07:33 -0700 Subject: [PATCH 5/5] test: remove 14 low-value suites and 241 individual cases (#36693) --- config/flaky-test-pattern-baseline.txt | 3 +- config/reliability-gates.jsonc | 46 ++--- config/scripts/ci-shard-timings.json | 13 -- ...rowser-extension-runtime-lifecycle.test.ts | 96 ---------- ...browser-extension-webstore-updater.test.ts | 33 +--- .../claude-context-usage-restart.test.ts | 40 ----- .../daemon-appimage-generation-launch.test.ts | 57 +----- ...aemon-pty-router-newer-daemon-hold.test.ts | 23 --- .../daemon-server-kill-attribution.test.ts | 130 -------------- .../daemon/daemon-severed-restart.test.ts | 57 +----- src/main/daemon/daemon-wsl-sleep-cwd.test.ts | 21 --- src/main/daemon/post-ready-flush-gate.test.ts | 45 ----- src/main/git/remote-ref-probe-cache.test.ts | 38 ---- .../remove-worktree-clean-preflight.test.ts | 47 ----- .../status-branch-line-total-real-git.test.ts | 35 ---- src/main/git/worktree-base-ref-probe.test.ts | 73 +------- src/main/github/pr-head-tracking-ref.test.ts | 52 ------ .../project-view/project-view-table.test.ts | 24 --- .../hang-watchdog-detection-loop.test.ts | 67 ------- .../electron-manual-redirect-fetch.test.ts | 7 - src/main/ipc/ephemeral-vm-managed-ssh.test.ts | 10 -- .../managed-host-status-publication.test.ts | 50 ------ ...spawn-host-env-wsl-passive-restore.test.ts | 23 --- ...-shutdown-checkpoint-sleep-records.test.ts | 13 -- src/main/ipc/wsl-guest-native-program.test.ts | 62 +------ .../linux-package-install-diagnostic.test.ts | 55 ------ ...t-session-claude-stop-ends-session.test.ts | 38 ---- ...t-session-interrupted-continuation.test.ts | 29 --- .../orcad/orcad-daemon-supervision.test.ts | 97 ---------- .../wsl-move-host-readiness.test.ts | 32 ---- .../wsl-move-ui-routing-rewrite.test.ts | 72 +------- src/main/plugins/plugin-discovery.test.ts | 79 -------- ...shell-ready-zsh-launch-environment.test.ts | 121 ------------- .../providers/pty-process-inspection.test.ts | 36 ---- .../windows-foreground-process-rows.test.ts | 14 -- src/main/repo-backfill-wsl-move.test.ts | 11 -- src/main/repo-git-remote-identity.test.ts | 54 ------ src/main/repo-maintenance-idle-gate.test.ts | 130 -------------- ...bile-session-tabs-notify-coalescer.test.ts | 113 ------------ .../pty-shell-ownership-mirror.test.ts | 24 --- .../agent-launch-terminal-preferences.test.ts | 110 ------------ .../worker-start-turn-observation.test.ts | 120 ------------- .../terminal-snapshot-scrollback-rows.test.ts | 42 +---- .../rpc/terminal-agent-send-guard.test.ts | 29 --- ...-folder-workspace-wsl-launch-scope.test.ts | 40 ----- src/main/runtime/runtime-metadata.test.ts | 57 ------ .../runtime/runtime-visible-catalog.test.ts | 43 +---- .../structured-chat-worker-start.test.ts | 17 -- .../layout/pane-grid-recording.test.ts | 53 +----- .../repo-remote-head-branch.test.ts | 7 - src/main/speech/openai-api-key-store.test.ts | 34 +--- .../ssh-target-orcad-dependents.test.ts | 133 +------------- ...-process-ready-persistence-cleanup.test.ts | 31 +--- .../startup/renderer-heap-headroom.test.ts | 121 ------------- src/main/updater-release-build-cache.test.ts | 38 ---- .../serve-supervisor-install-park.test.ts | 47 +---- src/main/wsl-fish-history-cleanup.test.ts | 41 ----- ...owser-page-viewport-size-feedback.test.tsx | 35 +--- .../navigate/browser-reload-action.test.ts | 113 ------------ .../remote-browser-page-session.test.ts | 30 ---- ...e-remote-browser-stream-activation.test.ts | 32 ---- .../MarkdownPreview.image-access.test.tsx | 127 ------------- .../editor-clean-tab-draft-invariant.test.ts | 27 +-- .../editor/editor-dropped-file-open.test.ts | 33 +--- .../markdown-preview-row-measurements.test.ts | 12 -- .../editor/monaco-find-widget.test.ts | 128 ------------- .../editor/pdf-scale-preference.test.ts | 56 +----- .../rich-markdown-link-shortcut.test.ts | 34 +--- .../quick-open-file-history.test.ts | 38 ---- .../settings/RuntimeEnvironmentsPane.test.ts | 169 +----------------- ...time-environment-mutation-actions.test.tsx | 35 ---- .../terminal-drop-upload-report.test.ts | 64 ------- ...rminal-layout-duplicate-pty-replay.test.ts | 127 ------------- ...inal-link-legacy-relay-bridge-pane.test.ts | 28 --- .../terminal-pty-ack-gate.test.ts | 124 ------------- ...se-workspace-cleanup-browse-state.test.tsx | 14 -- ...c-tab-switch-group-order-hydration.test.ts | 30 +--- ...obile-terminal-reveal-tab-adoption.test.ts | 72 -------- .../src/i18n/language-readiness.test.ts | 57 ------ ...d-agent-session-launch-persistence.test.ts | 93 +--------- .../lib/linear-issue-context-snapshot.test.ts | 139 -------------- .../monaco-languages/register-dotenv.test.ts | 85 +-------- ...sume-sleeping-agent-session-replay.test.ts | 39 +--- ...ping-agent-session-retired-binding.test.ts | 12 -- .../slices/active-tab-owner-worktree.test.ts | 64 ------- .../slices/browser-webview-cleanup.test.ts | 129 ------------- .../slices/ui-host-workspace-statuses.test.ts | 53 ------ 87 files changed, 49 insertions(+), 4883 deletions(-) delete mode 100644 src/main/browser/extensions/browser-extension-runtime-lifecycle.test.ts delete mode 100644 src/main/daemon/daemon-server-kill-attribution.test.ts delete mode 100644 src/main/orcad/orcad-daemon-supervision.test.ts delete mode 100644 src/main/repo-maintenance-idle-gate.test.ts delete mode 100644 src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts delete mode 100644 src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts delete mode 100644 src/main/startup/renderer-heap-headroom.test.ts delete mode 100644 src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts delete mode 100644 src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx delete mode 100644 src/renderer/src/components/editor/monaco-find-widget.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts delete mode 100644 src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts delete mode 100644 src/renderer/src/store/slices/browser-webview-cleanup.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 64c3649f085..047be93dc5e 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -979,7 +979,6 @@ 6 test-no-wall-clock:src/main/runtime/orchestration/worker-output-archive.test.ts 1 test-no-wall-clock:src/main/runtime/owned-session-teardown-policy.test.ts 2 test-no-wall-clock:src/main/runtime/project-removal-structured-sessions.test.ts -2 test-no-wall-clock:src/main/runtime/pty-shell-ownership-mirror.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-device-registration-persistence.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-unpair-persistence.test.ts @@ -1062,7 +1061,7 @@ 2 test-no-wall-clock:src/main/terminal-history-fish-session.node-pty.test.ts 2 test-no-wall-clock:src/main/terminal-history-gc-fs-call-count.test.ts 2 test-no-wall-clock:src/main/updater-sqlite-profile-downgrade.test.ts -6 test-no-wall-clock:src/main/updater/serve-supervisor-install-park.test.ts +4 test-no-wall-clock:src/main/updater/serve-supervisor-install-park.test.ts 4 test-no-wall-clock:src/main/windows-live-tree-kill.win32.test.ts 2 test-no-wall-clock:src/main/windows/windows-host-job.win32.test.ts 3 test-no-wall-clock:src/main/windows/windows-msys-job.win32.test.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index f8b3b05f463..839d0cea47f 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -8667,7 +8667,7 @@ "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Provider-independent unit tests cover persisted replay, state-boundary authority transfer, remote-runtime mirroring, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps.", + "coverageNotes": "Provider-independent unit tests cover persisted replay, state-boundary authority transfer, remote-runtime mirroring, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11757", "https://github.com/stablyai/orca/pull/11726" @@ -8675,12 +8675,11 @@ "invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.", "oracle": "Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Unit contracts require the same one-owner result through persisted replay, store hydration, remote mirroring, rootless and repeated-leaf layouts, and deeply nested input.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ - "src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts", "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts", "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts", "src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts", @@ -8688,13 +8687,6 @@ "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts" ], "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts", - "assertions": [ - "replays one surface when restored leaves point to the same PTY", - "reattaches one PTY when the split repeats its bound leaf id" - ] - }, { "file": "src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts", "assertions": ["prunes deeply nested duplicate ownership without recursive stack growth"] @@ -8723,15 +8715,6 @@ } ], "evidenceRuns": [ - { - "date": "2026-08-01", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/terminal-layout-pty-ownership.test.ts src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts --reporter=dot", - "result": "passed", - "durationSeconds": 1.33, - "summary": "Five focused files passed 92 ownership, replay, hydration, depth, and remote-mirroring tests." - }, { "date": "2026-08-01", "runner": "local", @@ -8767,7 +8750,8 @@ "Live Electron evidence currently covers macOS with a local daemon PTY only.", "The live journey uses a git-backed test workspace; folder-workspace restoration currently relies on the same provider-independent normalization contracts rather than a separate Electron run.", "The gate deterministically seeds the historical persisted-state shape; it does not depend on reproducing the unknown UI sequence that originally wrote duplicate ownership.", - "The visual old-release evidence and the structural current-version oracle are separate runs because the current test harness did not exist in Orca 1.4.161." + "The visual old-release evidence and the structural current-version oracle are separate runs because the current test harness did not exist in Orca 1.4.161.", + "The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage." ], "demotionRule": "Keep experimental or demote if ownership cardinality flakes, duplicate replay reaches a second renderer, active metadata or authority moves to the wrong leaf, deep normalization regresses, or a supported provider bypasses normalization." }, @@ -9448,7 +9432,7 @@ "providers": ["daemon", "runtime", "ssh", "wsl"], "coveredPlatforms": ["linux", "macos", "windows"], "coveredProviders": ["daemon", "runtime"], - "coverageNotes": "Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps.", + "coverageNotes": "Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/9749", "https://github.com/stablyai/orca/issues/9949", @@ -9459,12 +9443,11 @@ "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", "oracle": "Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-server-kill-attribution.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/runtime-close-attribution-topology.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/runtime-close-attribution-topology.test.ts src/main/runtime/rpc/methods/session-tabs.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/runtime/web-runtime-session.test.ts src/renderer/src/runtime/web-session-close-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts", "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ - "src/main/daemon/daemon-server-kill-attribution.test.ts", "src/main/runtime/orca-runtime.test.ts", "src/main/runtime/remote-runtime-request-connection.integration.test.ts", "src/main/runtime/rpc/runtime-close-attribution-topology.test.ts", @@ -9488,12 +9471,6 @@ "tests/e2e/daemon-generation-legacy-close-safety.spec.ts" ], "assertionRefs": [ - { - "file": "src/main/daemon/daemon-server-kill-attribution.test.ts", - "assertions": [ - "successful and failed daemon kill requests retain the authenticated control-client identity without claiming a failed kill succeeded" - ] - }, { "file": "src/main/runtime/rpc/runtime-close-attribution-topology.test.ts", "assertions": [ @@ -9656,7 +9633,8 @@ "Headless orca serve parity, live Linux, Linux SSH relay, and Windows WSL reconnect are not exercised; Docker SSH would cover only the SSH provider and cannot substitute for paired Orca-server evidence.", "A topology containing any pre-contract paired desktop viewer remains vulnerable to that viewer's stale reasonless close storm; preserving its intentional-close behavior makes this unavoidable until the viewer upgrades.", "Cross-profile daemon inventory and generation handoff/retirement remain the separate #9138/#9229 design.", - "A dead split leaf stays with its authoritative owner rather than being remotely pruned." + "A dead split leaf stays with its authoritative owner rather than being remotely pruned.", + "The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage." ], "demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect." }, @@ -17372,7 +17350,7 @@ "providers": ["remote-runtime", "ssh", "local", "daemon"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required.", + "coverageNotes": "Local macOS evidence covers runtime-RPC stream budgets, paired-renderer parse/discard credit, and negotiated host-side suppression for hidden paired desktop panes. Deferred credit is shared by local and remote transports, batches ACKs at 192 KiB or 4 ms, grows per-stream windows from 512 KiB to 2 MiB and aggregate windows from 2 MiB to 8 MiB, bounds queued output to 256 KiB per stream, and caps each multiplex connection at 32 active or pending streams for an 8 MiB aggregate pending-output ceiling. Deterministic tests cover replay ordering, stale generations, malformed frames, hidden panes, queue eviction, disposal, send/recovery failure, repeated pending-slot replacement, reconnect, mixed-version pause negotiation, and round-robin fairness. The opt-in benchmark models 1/20/100 ms RTT and 1/4/8 viewers, throughput, window use, completion spread and protocol-frame counts. It measures model scheduler elapsed time separately from actual @xterm/headless parser CPU/retained heap; modeled credit and ACK results do not qualify production credit enforcement. Live Android restore evidence, browser/WebGL parser measurements, and legacy JSON subscribe parity remain required. The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6951", "https://github.com/stablyai/orca/pull/6955", @@ -17383,7 +17361,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/main/runtime/rpc/terminal-output-batching.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-multiplex-output-pause-and-viewport.test.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts src/renderer/src/runtime/runtime-terminal-stream.test.ts --maxWorkers=1", "ORCA_TERMINAL_PERF_BENCH=1 pnpm exec vitest run --config config/vitest.config.ts --disableConsoleIntercept src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts", "pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/mobile-native-chat-terminal-stream.test.ts", "pnpm --dir mobile exec vitest run --root .. mobile/src/session/native-chat/use-mobile-native-chat-terminal-stream.test.ts" @@ -17399,7 +17377,6 @@ "src/main/runtime/rpc/terminal-multiplex-flow-control.bench.test.ts", "src/renderer/src/components/terminal-pane/pty-connection-hidden-replay.test.ts", "src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts", - "src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts", "src/renderer/src/lib/pane-manager/terminal-delivery-credit.test.ts", "src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts", "src/renderer/src/runtime/runtime-terminal-stream.test.ts", @@ -17570,7 +17547,8 @@ "knownGaps": [ "The pure mobile decision gate does not yet prove live Android WebView scrollback restore after a chat toggle.", "Legacy JSON subscribe parity is undecided.", - "The parser measurement uses @xterm/headless; browser renderer/WebGL CPU, GPU, and allocation behavior still need packaged-app performance evidence." + "The parser measurement uses @xterm/headless; browser renderer/WebGL CPU, GPU, and allocation behavior still need packaged-app performance evidence.", + "The audit removed the PTY ACK wrapper suite, which replayed credit arithmetic with mocked IPC. Its isolated wrapper alarms are no longer registered here; generic credit and runtime stream tests do not establish equivalent PTY integration coverage." ], "demotionRule": "Cannot promote while a supported stream path has uncapped snapshot or live-output buffering." }, diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 4ca542ff09c..720c0bcd277 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -2130,7 +2130,6 @@ "src/main/daemon/daemon-server-attach-only.test.ts": 477, "src/main/daemon/daemon-server-attachment-lifecycle.test.ts": 676, "src/main/daemon/daemon-server-error-handling.test.ts": 822, - "src/main/daemon/daemon-server-kill-attribution.test.ts": 902, "src/main/daemon/daemon-server.test.ts": 1218, "src/main/daemon/daemon-session-owner-resolution.test.ts": 106, "src/main/daemon/daemon-session-scrollback-window.test.ts": 513, @@ -3953,7 +3952,6 @@ "src/main/orcad/orcad-compile-cache.test.ts": 60, "src/main/orcad/orcad-cross-runtime-daemon-adoption.integration.test.ts": 484, "src/main/orcad/orcad-daemon-retirement.test.ts": 202, - "src/main/orcad/orcad-daemon-supervision.test.ts": 107, "src/main/orcad/orcad-daemon-teardown-linux.test.ts": 787, "src/main/orcad/orcad-daemon-teardown-pid-reuse.test.ts": 595, "src/main/orcad/orcad-data-root-locality.test.ts": 51, @@ -4596,7 +4594,6 @@ "src/main/repo-icon-autodetect.test.ts": 693, "src/main/repo-icon-file-detection.test.ts": 485, "src/main/repo-icon-source-href.test.ts": 75, - "src/main/repo-maintenance-idle-gate.test.ts": 125, "src/main/repo-worktrees.test.ts": 410, "src/main/ripgrep/bundled-ripgrep-path.test.ts": 78, "src/main/ripgrep/bundled-ripgrep-real.test.ts": 172, @@ -4856,7 +4853,6 @@ "src/main/runtime/mobile-session-tab-close-refusal-message.test.ts": 43, "src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts": 59, "src/main/runtime/mobile-session-tabs-churn-coalescing.test.ts": 2207, - "src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts": 53, "src/main/runtime/mobile-session-terminal-persistence-retirement.test.ts": 218, "src/main/runtime/mobile-session-terminal-retirement-proof.test.ts": 43, "src/main/runtime/mobile-session-terminal-retirement.test.ts": 155, @@ -5179,7 +5175,6 @@ "src/main/runtime/rpc/methods/agent-launch-settings-work.test.ts": 5277, "src/main/runtime/rpc/methods/agent-launch-structured-prompt.test.ts": 122, "src/main/runtime/rpc/methods/agent-launch-terminal-identity.test.ts": 1277, - "src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts": 969, "src/main/runtime/rpc/methods/agent-launch-terminal-prompt-writer.test.ts": 10669, "src/main/runtime/rpc/methods/agent-launch-terminal-prompt.test.ts": 522, "src/main/runtime/rpc/methods/agent-launch.test.ts": 1343, @@ -5323,7 +5318,6 @@ "src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-budget.test.ts": 111, "src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts": 3293, "src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.test.ts": 541, - "src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts": 43, "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-exit-race.test.ts": 3668, "src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts": 3343, "src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts": 3239, @@ -6324,7 +6318,6 @@ "src/main/startup/profile-state-recovery-preflight.test.ts": 603, "src/main/startup/profile-state-save-delay.test.ts": 39, "src/main/startup/profile-state-write-failure.test.ts": 425, - "src/main/startup/renderer-heap-headroom.test.ts": 74, "src/main/startup/run-electron-vite-dev-web.test.ts": 697, "src/main/startup/run-electron-vite-dev.test.ts": 899, "src/main/startup/select-linux-keyring-backend.test.ts": 63, @@ -7009,7 +7002,6 @@ "src/renderer/src/components/browser-pane/navigate/browser-load-failure-overlay.test.tsx": 549, "src/renderer/src/components/browser-pane/navigate/browser-notices.test.ts": 173, "src/renderer/src/components/browser-pane/navigate/browser-page-download-activity.test.ts": 41, - "src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts": 52, "src/renderer/src/components/browser-pane/navigate/browser-webview-load-failure.test.ts": 105, "src/renderer/src/components/browser-pane/navigate/chromium-error-page-poll-visibility.test.ts": 2172, "src/renderer/src/components/browser-pane/navigate/chromium-error-page-polling.test.ts": 25, @@ -7164,7 +7156,6 @@ "src/renderer/src/components/editor/IpynbKernelToolbar.test.tsx": 581, "src/renderer/src/components/editor/IpynbRendering.test.tsx": 1560, "src/renderer/src/components/editor/LargeDiffLoadPrompt.test.tsx": 286, - "src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx": 753, "src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx": 828, "src/renderer/src/components/editor/MarkdownPreview.test.ts": 1141, "src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx": 933, @@ -7355,7 +7346,6 @@ "src/renderer/src/components/editor/monaco-content-sync.undo-history.test.ts": 996, "src/renderer/src/components/editor/monaco-context-menu-paste.test.ts": 230, "src/renderer/src/components/editor/monaco-cursor-line-lifetime.test.ts": 1210, - "src/renderer/src/components/editor/monaco-find-widget.test.ts": 147, "src/renderer/src/components/editor/monaco-large-text-paste.test.ts": 209, "src/renderer/src/components/editor/monaco-markdown-doc-completions-retention.test.ts": 66, "src/renderer/src/components/editor/monaco-markdown-doc-link-decorations.offset-scan.test.ts": 167, @@ -9473,7 +9463,6 @@ "src/renderer/src/components/terminal-pane/terminal-keyboard-protocol-pane-agent.test.ts": 37, "src/renderer/src/components/terminal-pane/terminal-keyboard-search-dispatch.test.ts": 893, "src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts": 59, - "src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts": 39, "src/renderer/src/components/terminal-pane/terminal-layout-leaf-detach.test.ts": 37, "src/renderer/src/components/terminal-pane/terminal-layout-leaf-ids.test.ts": 44, "src/renderer/src/components/terminal-pane/terminal-layout-overlay-focus.test.tsx": 206, @@ -9562,7 +9551,6 @@ "src/renderer/src/components/terminal-pane/terminal-path-exists-cache.test.ts": 30, "src/renderer/src/components/terminal-pane/terminal-process-exit-restart.test.ts": 42, "src/renderer/src/components/terminal-pane/terminal-programmatic-text-paste.test.ts": 272, - "src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts": 159, "src/renderer/src/components/terminal-pane/terminal-quick-command-dispatch.test.ts": 59, "src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts": 22, "src/renderer/src/components/terminal-pane/terminal-render-desync-evidence-persistence.test.ts": 52, @@ -11001,7 +10989,6 @@ "src/renderer/src/store/slices/browser-session-host-selection.test.ts": 670, "src/renderer/src/store/slices/browser-session-profiles.test.ts": 894, "src/renderer/src/store/slices/browser-tab-creation-placement.test.ts": 1372, - "src/renderer/src/store/slices/browser-webview-cleanup.test.ts": 57, "src/renderer/src/store/slices/browser-workspace-doc-location.test.ts": 1464, "src/renderer/src/store/slices/browser-workspace-host-ownership.test.ts": 1531, "src/renderer/src/store/slices/browser.test.ts": 1679, diff --git a/src/main/browser/extensions/browser-extension-runtime-lifecycle.test.ts b/src/main/browser/extensions/browser-extension-runtime-lifecycle.test.ts deleted file mode 100644 index 05df05eedf4..00000000000 --- a/src/main/browser/extensions/browser-extension-runtime-lifecycle.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { mkdtempSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => ({ userData: '', emit: vi.fn() })) - -vi.mock('electron', () => ({ app: { getPath: () => mocks.userData, on: vi.fn() } })) -vi.mock('./browser-extension-api-host', () => ({ - emitBrowserExtensionWorkerStartEvent: mocks.emit -})) - -mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-lifecycle-')) - -const { decideRuntimeLifecycleEvents, fireRuntimeLifecycleEvents } = - await import('./browser-extension-runtime-lifecycle') -const { getBrowserExtensionProfileStateStore } = - await import('./browser-extension-profile-state-store') - -const loaded = (extensionVersion: string, chromiumVersion = '140.0.0.0') => ({ - extensionVersion, - chromiumVersion -}) -const install = { event: 'onInstalled', args: [{ reason: 'install' }] } -const startup = { event: 'onStartup', args: [] } - -describe('decideRuntimeLifecycleEvents', () => { - it('installs on the first load in a profile, with no onStartup even at launch', () => { - expect(decideRuntimeLifecycleEvents(undefined, loaded('1.0'), 'startup')).toEqual([install]) - expect(decideRuntimeLifecycleEvents(undefined, loaded('1.0'), 'other')).toEqual([install]) - }) - - it('fires only onStartup when an installed extension loads at launch unchanged', () => { - expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'startup')).toEqual([startup]) - expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'other')).toEqual([]) - }) - - it('reports a new version, or any reload, as an update with the previous version', () => { - const update = { event: 'onInstalled', args: [{ reason: 'update', previousVersion: '1.0' }] } - expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('2.0'), 'reload')).toEqual([update]) - expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('1.0'), 'reload')).toEqual([update]) - expect(decideRuntimeLifecycleEvents(loaded('1.0'), loaded('2.0'), 'startup')).toEqual([ - startup, - update - ]) - }) - - it('reports a new Chromium under the same extension version as chrome_update', () => { - expect( - decideRuntimeLifecycleEvents(loaded('1.0', '139.0'), loaded('1.0', '140.0'), 'startup') - ).toEqual([startup, { event: 'onInstalled', args: [{ reason: 'chrome_update' }] }]) - }) -}) - -describe('fireRuntimeLifecycleEvents', () => { - const session: Electron.Session = Object.create(null) - const extension = (version: string, background: unknown = { service_worker: 'w.js' }) => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the firing reads only id, version and manifest.background. - ({ id: 'a'.repeat(32), version, manifest: { background } }) as unknown as Electron.Extension - - beforeEach(() => { - mocks.emit.mockClear() - getBrowserExtensionProfileStateStore().forgetExtension('a'.repeat(32)) - }) - - it('records what it fired so the same launch never fires it twice', () => { - fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other') - fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other') - expect(mocks.emit.mock.calls).toEqual([ - [session, 'a'.repeat(32), 'runtime', 'onInstalled', [{ reason: 'install' }]] - ]) - expect( - getBrowserExtensionProfileStateStore().read('default', 'a'.repeat(32)).lastLoaded - ).toEqual({ extensionVersion: '1.0', chromiumVersion: process.versions.chrome }) - }) - - it('keeps each profile apart and is cleared with the extension', () => { - fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'other') - fireRuntimeLifecycleEvents(session, 'work', extension('1.0'), 'startup') - getBrowserExtensionProfileStateStore().forgetExtension('a'.repeat(32)) - fireRuntimeLifecycleEvents(session, 'default', extension('1.0'), 'startup') - expect(mocks.emit.mock.calls.map((call) => [call[3], call[4]])).toEqual([ - ['onInstalled', [{ reason: 'install' }]], - ['onInstalled', [{ reason: 'install' }]], - ['onInstalled', [{ reason: 'install' }]] - ]) - }) - - it('records but raises nothing for an extension without a service worker', () => { - fireRuntimeLifecycleEvents(session, 'default', extension('1.0', null), 'other') - expect(mocks.emit).not.toHaveBeenCalled() - expect( - getBrowserExtensionProfileStateStore().read('default', 'a'.repeat(32)).lastLoaded - ).toBeDefined() - }) -}) diff --git a/src/main/browser/extensions/browser-extension-webstore-updater.test.ts b/src/main/browser/extensions/browser-extension-webstore-updater.test.ts index 7af201d92ab..97cef48abb0 100644 --- a/src/main/browser/extensions/browser-extension-webstore-updater.test.ts +++ b/src/main/browser/extensions/browser-extension-webstore-updater.test.ts @@ -27,7 +27,7 @@ vi.mock('./browser-extension-webstore-install', () => ({ isBrowserExtensionBusy: () => false })) -const { checkForBrowserExtensionUpdates, compareExtensionVersions, parseOmahaUpdateResponse } = +const { checkForBrowserExtensionUpdates, parseOmahaUpdateResponse } = await import('./browser-extension-webstore-updater') const UBOL = 'ddkjiahejlhfcafbddmgiahcphecmpfh' @@ -64,38 +64,7 @@ ${JSON.stringify({ } })}` -describe('compareExtensionVersions', () => { - it('compares dotted integers numerically', () => { - expect(compareExtensionVersions('2026.1018.2229', '2026.1018.2228')).toBe(1) - expect(compareExtensionVersions('1.10', '1.9')).toBe(1) - expect(compareExtensionVersions('1.0', '1')).toBe(0) - expect(compareExtensionVersions('1.0.0.1', '1.0.1')).toBe(-1) - }) -}) - describe('parseOmahaUpdateResponse', () => { - it('offers newer versions with the package URL, size and checksum', () => { - const installed = new Map([ - [UBOL, '2026.1001.1'], - [BITWARDEN, '2026.1.0'] - ]) - expect(parseOmahaUpdateResponse(RESPONSE, installed)).toEqual([ - { - extensionId: UBOL, - version: '2026.1018.2229', - url: 'https://clients2.googleusercontent.com/crx/blobs/AZPV/DDKJIAHEJLHFCAFBDDMGIAHCPHECMPFH_2026_1018_2229_0.crx', - sha256: '559d10ef7dcb96bc4e812de6b3ff0c2e6c7abca578324d8d7afd7d8cf78a6dd7', - size: 9145194 - } - ]) - }) - - it('skips versions that are not newer, unknown apps and malformed replies', () => { - expect(parseOmahaUpdateResponse(RESPONSE, new Map([[UBOL, '2026.1018.2229']]))).toEqual([]) - expect(parseOmahaUpdateResponse(RESPONSE, new Map())).toEqual([]) - expect(parseOmahaUpdateResponse('not json', new Map([[UBOL, '1']]))).toEqual([]) - }) - it('drops download URLs outside Google hosts', () => { const hostile = RESPONSE.replace( 'https://clients2.googleusercontent.com/crx/blobs/AZPV/', diff --git a/src/main/claude/claude-context-usage-restart.test.ts b/src/main/claude/claude-context-usage-restart.test.ts index c7e08ede440..a1e23119f67 100644 --- a/src/main/claude/claude-context-usage-restart.test.ts +++ b/src/main/claude/claude-context-usage-restart.test.ts @@ -197,31 +197,6 @@ describe('context usage across a restart', () => { after.release() }) - it('keeps the last known size of a turn the child crashed in', async () => { - const journal = await openJournal() - const crashed = acquire(journal) - crashed.translator.handle(initFrame(900)) - crashed.translator.handle(userFrame('turn-a', 1_000)) - crashed.translator.handle(assistantFrame('reply-a', 2_000, 20_000)) - crashed.translator.handle(resultFrame(3_000)) - crashed.translator.handle(initFrame(3900)) - crashed.translator.handle(userFrame('turn-b', 4_000)) - crashed.translator.handle(assistantFrame('reply-b', 5_000, 120_000)) - await crashed.settle() - crashed.release() - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'orca-session', - fence: 2, - acquisitionGeneration: 'next', - deathEvidence: null - }) - const turns = journal.snapshot().items.map((item) => readAgentJournalTurn(item.body)?.state) - expect(turns).toContain('unverifiable') - expect(ring(journal)).toMatchObject({ usedTokens: 120_000, windowTokens: 1_000_000 }) - }) - it('never brings a settled turn back to running with a context write that ran late', async () => { const journal = await openJournal() const live = acquire(journal) @@ -251,21 +226,6 @@ describe('context usage across a restart', () => { live.release() }) - it("reads a new session's implied window the same from its loaded rows and from the host", async () => { - const journal = await openJournal() - const live = acquire(journal) - live.translator.modelWritten('opus[1m]') - live.translator.handle(initFrame(900)) - live.translator.handle(userFrame('turn-a', 1_000)) - live.translator.handle(assistantFrame('reply-a', 2_000, 150_000)) - await live.settle() - const expected = { usedTokens: 150_000, windowTokens: 1_000_000, percentage: 15 } - expect(ring(journal)).toMatchObject(expected) - expect(journal.contextUsage()).toMatchObject({ window: { tokens: 1_000_000 } }) - expect(selectStructuredAgentContextUsage([], journal.contextUsage())).toMatchObject(expected) - live.release() - }) - it('keeps the window a restarted journal holds over the one the model name implies', async () => { const journal = await openJournal() const before = acquire(journal) diff --git a/src/main/daemon/daemon-appimage-generation-launch.test.ts b/src/main/daemon/daemon-appimage-generation-launch.test.ts index 435feb7c0fe..cd4ebe76ba2 100644 --- a/src/main/daemon/daemon-appimage-generation-launch.test.ts +++ b/src/main/daemon/daemon-appimage-generation-launch.test.ts @@ -3,10 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { resolveAppImageExtractedRoot } from '../cli/appimage-extracted-root' -import { - buildAppImageGenerationDaemonCommand, - resolveAppImageGenerationDaemonLaunch -} from './daemon-appimage-generation-launch' +import { resolveAppImageGenerationDaemonLaunch } from './daemon-appimage-generation-launch' const { resolveIdentity } = vi.hoisted(() => ({ resolveIdentity: vi.fn() })) vi.mock('../appimage-runtime-identity', () => ({ resolveAppImageRuntimeIdentity: resolveIdentity })) @@ -61,32 +58,6 @@ function extractGeneration(options: { node?: boolean; version?: string } = {}): } describe('resolveAppImageGenerationDaemonLaunch', () => { - it('runs the daemon on the bundled Node of the extracted copy of this AppImage', () => { - const generation = extractGeneration() - expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({ - launch: { - generationRoot: generation, - nodePath: join(generation, 'resources', 'node-runtime', 'bin', 'node'), - entryPath: join(generation, ENTRY_IN_APPDIR), - // Match own-mount identity so either host can be adopted. - identityPath: join(appImagePath, ENTRY_IN_APPDIR) - } - }) - }) - - it('says nothing off a validated AppImage', () => { - extractGeneration() - resolveIdentity.mockReturnValue(null) - expect(resolveAppImageGenerationDaemonLaunch(input())).toBeNull() - expect(resolveAppImageGenerationDaemonLaunch(input({ environment: {} }))).toBeNull() - }) - - it('falls back when the AppImage was never extracted', () => { - expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({ - fallback: 'no-extracted-copy' - }) - }) - it('falls back when the extracted copy predates the bundled Node', () => { extractGeneration({ node: false }) expect(resolveAppImageGenerationDaemonLaunch(input())).toEqual({ @@ -101,29 +72,3 @@ describe('resolveAppImageGenerationDaemonLaunch', () => { }) }) }) - -describe('buildAppImageGenerationDaemonCommand', () => { - it.runIf(process.platform === 'linux')( - 'runs plain Node, with no Electron or AppImage runtime variables', - () => { - const launch = { - generationRoot: '/cache/ns/gen', - nodePath: '/cache/ns/gen/resources/node-runtime/bin/node', - entryPath: `/cache/ns/gen/${ENTRY_IN_APPDIR}`, - identityPath: `/apps/Orca.AppImage/${ENTRY_IN_APPDIR}` - } - const command = buildAppImageGenerationDaemonCommand(launch, ['--socket', '/s'], { - APPDIR, - APPIMAGE: '/apps/Orca.AppImage', - ELECTRON_RUN_AS_NODE: '1', - PATH: `${APPDIR}/usr/bin:/usr/bin`, - HOME: '/home/me' - }) - expect(command).toEqual({ - command: launch.nodePath, - args: [launch.entryPath, '--socket', '/s'], - env: { PATH: '/usr/bin', HOME: '/home/me' } - }) - } - ) -}) diff --git a/src/main/daemon/daemon-pty-router-newer-daemon-hold.test.ts b/src/main/daemon/daemon-pty-router-newer-daemon-hold.test.ts index 1c463f900e4..8f141943aa5 100644 --- a/src/main/daemon/daemon-pty-router-newer-daemon-hold.test.ts +++ b/src/main/daemon/daemon-pty-router-newer-daemon-hold.test.ts @@ -21,15 +21,6 @@ function setup(opts: { holding: boolean; restorable?: string[]; currentSessions? const SPAWN = { cols: 80, rows: 24 } describe('DaemonPtyRouter newer-daemon hold', () => { - it('refuses a cold restore no adopted daemon owns while a newer daemon is held', async () => { - const { current, router } = setup({ holding: true, restorable: ['newer-session'] }) - await router.discoverLegacySessions() - await expect(router.spawn({ ...SPAWN, sessionId: 'newer-session' })).rejects.toThrow( - NEWER_DAEMON_HOLD_ERROR - ) - expect(current.spawn).not.toHaveBeenCalled() - }) - // Mobile and runtime restore can re-materialize an existing ID with its agent command. it('refuses an agent-launching re-materialize of that id the same way', async () => { const { current, router } = setup({ holding: true, restorable: ['newer-session'] }) @@ -56,13 +47,6 @@ describe('DaemonPtyRouter newer-daemon hold', () => { expect(current.spawn).toHaveBeenCalledOnce() }) - it('spawns fresh terminals and ids with no saved history', async () => { - const { current, router } = setup({ holding: true }) - await router.spawn(SPAWN) - await router.spawn({ ...SPAWN, sessionId: 'pre-allocated-new-id' }) - expect(current.spawn).toHaveBeenCalledTimes(2) - }) - it('holds when the adopted inventory cannot answer', async () => { const { legacy, router } = setup({ holding: true, restorable: ['newer-session'] }) vi.mocked(legacy.listProcesses).mockRejectedValue(new Error('timeout')) @@ -80,11 +64,4 @@ describe('DaemonPtyRouter newer-daemon hold', () => { }) expect(current.spawn).toHaveBeenCalledOnce() }) - - it('changes nothing for older-daemon routing when no newer daemon is held', async () => { - const { current, router } = setup({ holding: false, restorable: ['lost-session'] }) - await router.spawn({ ...SPAWN, sessionId: 'lost-session' }) - expect(current.spawn).toHaveBeenCalledOnce() - expect(current.hasRestorableHistory).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/daemon-server-kill-attribution.test.ts b/src/main/daemon/daemon-server-kill-attribution.test.ts deleted file mode 100644 index d5c0bcf8bd2..00000000000 --- a/src/main/daemon/daemon-server-kill-attribution.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import './mock-descendant-sweep' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { DaemonServer } from './daemon-server' -import { SessionNotFoundError, type DaemonRequest } from './types' - -type DaemonServerPrivate = { - host: { kill: (sessionId: string, opts?: { immediate?: boolean }) => void | Promise } - preparations: { - pending: Map> - } - requestRouter: { - route(clientId: string, request: DaemonRequest): Promise - } -} - -describe('daemon kill attribution', () => { - let server: DaemonServer - let dir: string - - afterEach(async () => { - await server?.shutdown() - rmSync(dir, { recursive: true, force: true }) - }) - - it('records the requesting control client in the session-killed log', async () => { - dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-')) - const killLog = { log: vi.fn(), close: vi.fn() } - server = new DaemonServer({ - socketPath: join(dir, 'daemon.sock'), - tokenPath: join(dir, 'daemon.token'), - log: killLog, - spawnSubprocess: () => { - throw new Error('not used') - } - }) - const daemon = server as unknown as DaemonServerPrivate - let finishKill!: () => void - const killFinished = new Promise((resolve) => { - finishKill = resolve - }) - vi.spyOn(daemon.host, 'kill').mockReturnValue(killFinished) - - const request = daemon.requestRouter.route('control-42', { - id: 'kill-1', - type: 'kill', - payload: { sessionId: 'agent-session', immediate: true } - }) - - await vi.waitFor(() => expect(daemon.host.kill).toHaveBeenCalledOnce()) - expect(killLog.log).not.toHaveBeenCalledWith('session-killed', expect.anything()) - finishKill() - await request - - expect(killLog.log).toHaveBeenCalledWith('session-killed', { - sessionId: 'agent-session', - immediate: true, - clientId: 'control-42' - }) - }) - - it('attributes a failed kill without claiming the session was killed', async () => { - dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-')) - const killLog = { log: vi.fn(), close: vi.fn() } - server = new DaemonServer({ - socketPath: join(dir, 'daemon.sock'), - tokenPath: join(dir, 'daemon.token'), - log: killLog, - spawnSubprocess: () => { - throw new Error('not used') - } - }) - const daemon = server as unknown as DaemonServerPrivate - vi.spyOn(daemon.host, 'kill').mockRejectedValue(new Error('kill refused')) - - await expect( - daemon.requestRouter.route('control-42', { - id: 'kill-1', - type: 'kill', - payload: { sessionId: 'agent-session', immediate: true } - }) - ).rejects.toThrow('kill refused') - - expect(killLog.log).toHaveBeenCalledWith('session-kill-failed', { - sessionId: 'agent-session', - immediate: true, - clientId: 'control-42', - errorName: 'Error', - error: 'kill refused' - }) - expect(killLog.log).not.toHaveBeenCalledWith('session-killed', expect.anything()) - }) - - it('attributes a tolerated kill after canceling a pending spawn', async () => { - dir = mkdtempSync(join(tmpdir(), 'daemon-kill-attribution-')) - const killLog = { log: vi.fn(), close: vi.fn() } - server = new DaemonServer({ - socketPath: join(dir, 'daemon.sock'), - tokenPath: join(dir, 'daemon.token'), - log: killLog, - spawnSubprocess: () => { - throw new Error('not used') - } - }) - const daemon = server as unknown as DaemonServerPrivate - const pendingPreparation = { - canceled: false, - controller: new AbortController(), - clientId: 'control-42' - } - daemon.preparations.pending.set('agent-session', new Set([pendingPreparation])) - vi.spyOn(daemon.host, 'kill').mockRejectedValue(new SessionNotFoundError('agent-session')) - - await daemon.requestRouter.route('control-42', { - id: 'kill-1', - type: 'kill', - payload: { sessionId: 'agent-session', immediate: true } - }) - - expect(pendingPreparation.canceled).toBe(true) - expect(killLog.log).toHaveBeenCalledWith('session-killed', { - sessionId: 'agent-session', - immediate: true, - clientId: 'control-42' - }) - expect(killLog.log).not.toHaveBeenCalledWith('session-kill-failed', expect.anything()) - }) -}) diff --git a/src/main/daemon/daemon-severed-restart.test.ts b/src/main/daemon/daemon-severed-restart.test.ts index 63407fa5e50..89f75bcf2a8 100644 --- a/src/main/daemon/daemon-severed-restart.test.ts +++ b/src/main/daemon/daemon-severed-restart.test.ts @@ -7,14 +7,11 @@ import { getSeveredDaemon, installSeveredDaemonController, noteSeveredDaemon, - readSeveredDaemonStatus, restartSeveredDaemon } from './daemon-host-image-state' + import type { DaemonHostImageInspection } from './daemon-host-image' -import { - createSeveredDaemonController, - hasSeveredDaemonBeenReplaced -} from './daemon-severed-restart' +import { createSeveredDaemonController } from './daemon-severed-restart' const SEVERED: DaemonHostImageInspection = { verdict: 'severed', @@ -47,22 +44,6 @@ afterEach(() => { }) describe('restarting a daemon whose AppImage files are gone', () => { - it('counts every running terminal a restart would end, local fallback included', async () => { - setUp(SEVERED, [{ isAlive: true }, { isAlive: false }, { isAlive: true }], 2) - await expect(readSeveredDaemonStatus()).resolves.toEqual({ ...EXPECTED, liveSessionCount: 4 }) - }) - - it('restarts only the incarnation the caller saw, after re-reading it', async () => { - const restart = setUp(SEVERED) - await expect(restartSeveredDaemon(EXPECTED)).resolves.toEqual({ - status: 'restarted', - killedCount: 1 - }) - // Pass the PID through so teardown can recheck endpoint ownership. - expect(restart).toHaveBeenCalledWith(4288) - expect(getSeveredDaemon()).toBeNull() - }) - it('refuses when the caller saw another incarnation', async () => { const restart = setUp(SEVERED) await expect(restartSeveredDaemon({ ...EXPECTED, linuxStartTicks: '1' })).resolves.toEqual({ @@ -90,38 +71,4 @@ describe('restarting a daemon whose AppImage files are gone', () => { expect(restart).not.toHaveBeenCalled() expect(getSeveredDaemon()).toEqual(EXPECTED) }) - - it('reports nothing severed until a daemon was kept severed', async () => { - setUp(SEVERED) - clearSeveredDaemon() - await expect(readSeveredDaemonStatus()).resolves.toBeNull() - await expect(restartSeveredDaemon(EXPECTED)).resolves.toEqual({ - status: 'refused', - reason: 'not-severed' - }) - }) -}) - -describe('hasSeveredDaemonBeenReplaced', () => { - it('keeps the quarantine while the severed incarnation still owns the endpoint', () => { - setUp(SEVERED) - expect(hasSeveredDaemonBeenReplaced('/pid', () => SEVERED)).toBe(false) - expect(hasSeveredDaemonBeenReplaced('/pid', () => ({ ...SEVERED, verdict: 'unknown' }))).toBe( - false - ) - expect(getSeveredDaemon()).toEqual(EXPECTED) - }) - - it('lifts it once a verified, intact daemon replaced the severed one', () => { - setUp(SEVERED) - expect( - hasSeveredDaemonBeenReplaced('/pid', () => ({ - verdict: 'intact', - pid: 9000, - linuxStartTicks: '5', - bootId: 'boot-1' - })) - ).toBe(true) - expect(getSeveredDaemon()).toBeNull() - }) }) diff --git a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts index 5734ca01635..31474d6e25a 100644 --- a/src/main/daemon/daemon-wsl-sleep-cwd.test.ts +++ b/src/main/daemon/daemon-wsl-sleep-cwd.test.ts @@ -35,13 +35,6 @@ describe('readDaemonWslSleepCwd', () => { } }) - it("answers the shell's folder in the bridge's UNC spelling", async () => { - readRows.mockResolvedValue([shell]) - expect(await readDaemonWslSleepCwd(pane)).toBe('\\\\wsl.localhost\\Ubuntu\\home\\a\\deep') - // A live pane's distro is running: no separate running check. - expect(readRows).toHaveBeenCalledWith('Ubuntu', 3_000, { running: true }) - }) - it('gives the read at most a quarter of what is left of the Sleep, capped at 3 s', async () => { readRows.mockResolvedValue([shell]) await readDaemonWslSleepCwd(pane, Date.now() + 4_000) @@ -51,14 +44,6 @@ describe('readDaemonWslSleepCwd', () => { expect(readRows).not.toHaveBeenCalled() }) - it('gives up at its budget when the distro does not answer', async () => { - vi.useFakeTimers() - readRows.mockReturnValue(new Promise(() => {})) - const read = readDaemonWslSleepCwd(pane) - await vi.advanceTimersByTimeAsync(3_000) - expect(await read).toBeNull() - }) - it("answers quit's panes within its own budget, leaving out panes it cannot read", async () => { readRows.mockResolvedValue([shell]) const cwds = await readDaemonWslQuitCwds( @@ -90,10 +75,4 @@ describe('readDaemonWslSleepCwd', () => { await vi.advanceTimersByTimeAsync(3_000) expect(await read).toMatchObject({ cwd: null, rows: null, shells: null, timedOut: true }) }) - - it('reads nothing off Windows', async () => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - expect(await readDaemonWslSleepCwd(pane)).toBeNull() - expect(readRows).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/post-ready-flush-gate.test.ts b/src/main/daemon/post-ready-flush-gate.test.ts index 06ff64db99f..787dde7d927 100644 --- a/src/main/daemon/post-ready-flush-gate.test.ts +++ b/src/main/daemon/post-ready-flush-gate.test.ts @@ -28,20 +28,6 @@ describe('PostReadyFlushGate', () => { expect(vi.getTimerCount()).toBe(0) }) - it('does not flush immediately when armed', () => { - gate.arm() - expect(onFlush).not.toHaveBeenCalled() - }) - - it('flushes via short delay after notifyData signals the prompt draw', () => { - gate.arm() - gate.notifyData() - expect(onFlush).not.toHaveBeenCalled() - - vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS) - expect(onFlush).toHaveBeenCalledTimes(1) - }) - it('flushes via short delay when arm receives post-marker bytes evidence', () => { gate.arm(true) vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS - 1) @@ -51,27 +37,6 @@ describe('PostReadyFlushGate', () => { expect(onFlush).toHaveBeenCalledTimes(1) }) - it('flushes via wall-clock fallback when no notifyData arrives', () => { - gate.arm() - - vi.advanceTimersByTime(POST_READY_FLUSH_FALLBACK_MS) - expect(onFlush).toHaveBeenCalledTimes(1) - }) - - it('does not fallback at the old duplicate-echo race window', () => { - gate.arm() - - vi.advanceTimersByTime(50) - - expect(onFlush).not.toHaveBeenCalled() - }) - - it('ignores notifyData before arm()', () => { - gate.notifyData() - vi.advanceTimersByTime(1000) - expect(onFlush).not.toHaveBeenCalled() - }) - it('notifyData after the fallback fired is a no-op', () => { gate.arm() vi.advanceTimersByTime(POST_READY_FLUSH_FALLBACK_MS) @@ -82,16 +47,6 @@ describe('PostReadyFlushGate', () => { expect(onFlush).toHaveBeenCalledTimes(1) }) - it('only the first notifyData schedules the short-delay flush', () => { - gate.arm() - gate.notifyData() - gate.notifyData() - gate.notifyData() - - vi.advanceTimersByTime(POST_READY_FLUSH_DELAY_MS) - expect(onFlush).toHaveBeenCalledTimes(1) - }) - it('clear() cancels a pending fallback flush', () => { gate.arm() gate.clear() diff --git a/src/main/git/remote-ref-probe-cache.test.ts b/src/main/git/remote-ref-probe-cache.test.ts index 91b8b54d0bb..88f2b5ce2a0 100644 --- a/src/main/git/remote-ref-probe-cache.test.ts +++ b/src/main/git/remote-ref-probe-cache.test.ts @@ -34,20 +34,6 @@ describe('remote ref probe cache (P1-D)', () => { vi.useRealTimers() }) - it('answers concurrent lookups for one repo with a single probe', async () => { - const cache = createRemoteRefProbeCache(parseExampleRef) - gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@example.com:team/repo.git\n' }) - - const answers = await Promise.all([ - cache.get('/repo', 'origin'), - cache.get('/repo', 'origin'), - cache.get('/repo', 'origin') - ]) - - expect(answers).toEqual([{ repo: 'team/repo' }, { repo: 'team/repo' }, { repo: 'team/repo' }]) - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - it('re-probes a repo whose remotes could have changed since the miss', async () => { const cache = createRemoteRefProbeCache(parseExampleRef) gitExecFileAsyncMock.mockRejectedValueOnce(new Error("fatal: No such remote 'origin'")) @@ -64,17 +50,6 @@ describe('remote ref probe cache (P1-D)', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) }) - it('keeps a resolved ref without re-probing', async () => { - const cache = createRemoteRefProbeCache(parseExampleRef) - gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@example.com:team/repo.git\n' }) - - await expect(cache.get('/repo', 'origin')).resolves.toEqual({ repo: 'team/repo' }) - vi.setSystemTime(1_000_000 + NEGATIVE_ENTRY_TTL_MS * 10) - await expect(cache.get('/repo', 'origin')).resolves.toEqual({ repo: 'team/repo' }) - - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - it('does not let a probe abandoned as stale overwrite its successor answer', async () => { const cache = createRemoteRefProbeCache(parseExampleRef) const stalled = deferred<{ stdout: string }>() @@ -94,19 +69,6 @@ describe('remote ref probe cache (P1-D)', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) }) - it('holds a parsed-as-not-mine remote for the negative interval, then re-asks', async () => { - const cache = createRemoteRefProbeCache(parseExampleRef) - gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@elsewhere.example:team/repo.git\n' }) - - await expect(cache.get('/repo', 'origin')).resolves.toBeNull() - await expect(cache.get('/repo', 'origin')).resolves.toBeNull() - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) - - vi.setSystemTime(1_000_000 + NEGATIVE_ENTRY_TTL_MS + 1) - await expect(cache.get('/repo', 'origin')).resolves.toBeNull() - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) - }) - it('answers an SSH repo with null without running git on this machine', async () => { const cache = createRemoteRefProbeCache(parseExampleRef) diff --git a/src/main/git/remove-worktree-clean-preflight.test.ts b/src/main/git/remove-worktree-clean-preflight.test.ts index 4b0069c7d98..d14d46bc71f 100644 --- a/src/main/git/remove-worktree-clean-preflight.test.ts +++ b/src/main/git/remove-worktree-clean-preflight.test.ts @@ -49,31 +49,6 @@ describe('assertWorktreeCleanForRemoval', () => { .mockRejectedValue(new Error('git ls-files exited with code 128')) }) - it('returns without checking git status for force removals', async () => { - await expect(assertWorktreeCleanForRemoval('/repo-feature', true)).resolves.toBeUndefined() - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('passes when git status output is empty', async () => { - gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(assertWorktreeCleanForRemoval('/repo-feature')).resolves.toBeUndefined() - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], - { cwd: '/repo-feature', timeout: WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS } - ) - }) - - it('throws a dedicated dirty/untracked error when status output is non-empty', async () => { - gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '?? scratch.txt\n', stderr: '' }) - - await expect(assertWorktreeCleanForRemoval('/repo-feature')).rejects.toMatchObject({ - message: 'Worktree has uncommitted or untracked changes.', - stdout: '?? scratch.txt\n' - }) - }) - it('ignores configured linked paths without mutating them before preflight', async () => { gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '?? node_modules\0', stderr: '' }) @@ -89,19 +64,6 @@ describe('assertWorktreeCleanForRemoval', () => { ) }) - it('allows a shorter caller deadline for destructive preflight', async () => { - gitExecFileAsyncMock.mockRejectedValueOnce(new Error('git timed out.')) - - await expect( - assertWorktreeCleanForRemoval('/repo-feature', false, { timeout: 25 }) - ).rejects.toThrow('git timed out.') - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], - { cwd: '/repo-feature', timeout: 25 } - ) - }) - it('still rejects real changes when configured linked paths are ignored', async () => { gitExecFileAsyncMock.mockResolvedValueOnce({ stdout: '?? node_modules\0 M src/index.ts\0', @@ -114,13 +76,4 @@ describe('assertWorktreeCleanForRemoval', () => { }) ).rejects.toMatchObject({ message: 'Worktree has uncommitted or untracked changes.' }) }) - - it('rethrows preflight subprocess failures as-is', async () => { - const error = Object.assign(new Error('fatal: not a git repository'), { - stderr: 'fatal: not a git repository (or any of the parent directories): .git\n' - }) - gitExecFileAsyncMock.mockRejectedValueOnce(error) - - await expect(assertWorktreeCleanForRemoval('/repo-feature')).rejects.toBe(error) - }) }) diff --git a/src/main/git/status-branch-line-total-real-git.test.ts b/src/main/git/status-branch-line-total-real-git.test.ts index 32ee97540d1..297381b55ee 100644 --- a/src/main/git/status-branch-line-total-real-git.test.ts +++ b/src/main/git/status-branch-line-total-real-git.test.ts @@ -167,24 +167,6 @@ describe('branch line total against a real repository', () => { }) }) - it('counts an untracked-only branch from the untracked file contents', async () => { - const repo = await createFixtureRepo() - await write(repo, 'kept.txt', 'a\n') - const mergeBase = commitAll(repo, 'base') - await write(repo, 'src/new.ts', 'one\ntwo\nthree\n') - - const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - - expect(result.entries.map((entry) => entry.area)).toEqual(['untracked']) - expect(result.branchLineTotal).toEqual({ - added: 3, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - }) - it('excludes a binary-only change, matching numstat reporting it as "-"', async () => { const repo = await createFixtureRepo() await write(repo, 'blob.bin', Buffer.from([0, 1, 2, 3, 10, 65, 66])) @@ -203,23 +185,6 @@ describe('branch line total against a real repository', () => { }) }) - it('contributes nothing for a pure rename', async () => { - const repo = await createFixtureRepo() - await write(repo, 'f.txt', 'a\nb\nc\nd\n') - const mergeBase = commitAll(repo, 'base') - git(repo, ['mv', 'f.txt', 'g.txt']) - - const result = await getStatus(repo, { branchLineTotalMergeBase: mergeBase }) - - expect(result.branchLineTotal).toEqual({ - added: 0, - removed: 0, - mergeBase, - test: NO_LINES, - generated: NO_LINES - }) - }) - it('splits test-path and generated files out of the published total', async () => { const repo = await createFixtureRepo() await write(repo, 'src/a.ts', 'a\n') diff --git a/src/main/git/worktree-base-ref-probe.test.ts b/src/main/git/worktree-base-ref-probe.test.ts index f2e38067ad5..ee9819499a3 100644 --- a/src/main/git/worktree-base-ref-probe.test.ts +++ b/src/main/git/worktree-base-ref-probe.test.ts @@ -1,27 +1,12 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' const gitExecFileAsync = vi.hoisted(() => vi.fn()) vi.mock('./runner', () => ({ gitExecFileAsync })) -import { hasLocalWorktreeBaseRef, probeWorktreeBaseRefPresence } from './worktree-base-ref-probe' +import { probeWorktreeBaseRefPresence } from './worktree-base-ref-probe' describe('probeWorktreeBaseRefPresence', () => { - it('uses an exact show-ref probe and reports a present ref', async () => { - const runGit = vi.fn().mockResolvedValue({ stdout: '' }) - - await expect(probeWorktreeBaseRefPresence(runGit, 'refs/heads/release/2026')).resolves.toBe( - 'present' - ) - expect(runGit).toHaveBeenCalledWith([ - 'show-ref', - '--verify', - '--quiet', - '--', - 'refs/heads/release/2026' - ]) - }) - it('treats show-ref exit 1 as an absent ref', async () => { const runGit = vi.fn().mockRejectedValue(Object.assign(new Error('missing ref'), { code: 1 })) @@ -30,16 +15,6 @@ describe('probeWorktreeBaseRefPresence', () => { ) }) - it('keeps repository and transport failures inconclusive', async () => { - const runGit = vi - .fn() - .mockRejectedValue(Object.assign(new Error('not a git repository'), { code: 128 })) - - await expect(probeWorktreeBaseRefPresence(runGit, 'refs/heads/release/2026')).resolves.toBe( - 'unknown' - ) - }) - it('does not treat a string transport code as a missing ref', async () => { const runGit = vi .fn() @@ -57,47 +32,3 @@ describe('probeWorktreeBaseRefPresence', () => { expect(runGit).not.toHaveBeenCalled() }) }) - -describe('hasLocalWorktreeBaseRef', () => { - const repoPath = String.raw`C:\workspace\repo` - - function resolveOnly(present: string[]): void { - gitExecFileAsync.mockImplementation(async (args: string[]) => ({ - stdout: present.includes(args.at(-1)?.replace('^{commit}', '') ?? '') ? 'f'.repeat(40) : '', - stderr: '' - })) - } - - beforeEach(() => { - gitExecFileAsync.mockReset() - }) - - it('prefers the remote namespace for a slashed short name', async () => { - resolveOnly(['refs/remotes/origin/main']) - - await expect(hasLocalWorktreeBaseRef(repoPath, 'origin/main')).resolves.toBe(true) - expect(gitExecFileAsync).toHaveBeenCalledWith( - ['rev-parse', '--verify', '--quiet', 'refs/remotes/origin/main^{commit}'], - { cwd: repoPath } - ) - }) - - it('probes a bare commit id as an object, not as a ref', async () => { - const sha = 'a'.repeat(40) - resolveOnly([sha]) - - await expect(hasLocalWorktreeBaseRef(repoPath, sha, { wslDistro: 'Ubuntu' })).resolves.toBe( - true - ) - expect(gitExecFileAsync).toHaveBeenCalledWith( - ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`], - { cwd: repoPath, wslDistro: 'Ubuntu' } - ) - }) - - it('reports a base no namespace resolves as absent', async () => { - resolveOnly([]) - - await expect(hasLocalWorktreeBaseRef(repoPath, 'feature/topic')).resolves.toBe(false) - }) -}) diff --git a/src/main/github/pr-head-tracking-ref.test.ts b/src/main/github/pr-head-tracking-ref.test.ts index 066c0ce5d6a..abbf8b97fb5 100644 --- a/src/main/github/pr-head-tracking-ref.test.ts +++ b/src/main/github/pr-head-tracking-ref.test.ts @@ -3,15 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const { gitExecFileAsyncMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn() })) vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) -import { - githubPullRequestHeadLocalRef, - reviewHeadRemoteRefComponent, - REVIEW_HEAD_FETCH_TIMEOUT_MS -} from '../../shared/review-head-tracking-ref' import { fetchGitHubPullRequestHeadRef, fetchPrHeadTrackingRef } from './pr-head-tracking-ref' const ORIGIN_URL = 'https://github.com/acme/widgets.git' -const ORIGIN_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_URL) describe('fetchPrHeadTrackingRef', () => { beforeEach(() => { @@ -24,22 +18,6 @@ describe('fetchPrHeadTrackingRef', () => { }) }) - it('fetches into the remote-tracking ref with real git for local repos', async () => { - await fetchPrHeadTrackingRef({ path: '/repo', connectionId: null }, 'origin', 'feature/x') - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['fetch', 'origin', '+refs/heads/feature/x:refs/remotes/origin/feature/x'], - { cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } - ) - }) - - it('throws for an SSH repo, which this process does not serve', async () => { - await expect( - fetchPrHeadTrackingRef({ path: '/repo', connectionId: 'conn-1' }, 'origin', 'feature/x') - ).rejects.toThrow('SSH Git provider is not available') - expect(gitExecFileAsyncMock).not.toHaveBeenCalled() - }) - it('throws for an SSH repo named only by executionHostId', async () => { await expect( fetchPrHeadTrackingRef({ path: '/repo', executionHostId: 'ssh:gpu' }, 'origin', 'feature/x') @@ -47,21 +25,6 @@ describe('fetchPrHeadTrackingRef', () => { expect(gitExecFileAsyncMock).not.toHaveBeenCalled() }) - it('fetches a GitHub pull head into its remote-scoped Orca ref for local repos', async () => { - const localRef = await fetchGitHubPullRequestHeadRef( - { path: '/repo', connectionId: null }, - 'origin', - 42 - ) - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`], - { cwd: '/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } - ) - expect(localRef).toBe(githubPullRequestHeadLocalRef(ORIGIN_COMPONENT, 42)) - expect(localRef).toBe(`refs/orca/pull/${ORIGIN_COMPONENT}/42`) - }) - it('fails the pull-head fetch when the remote is not configured', async () => { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args[0] === 'remote' && args[1] === 'get-url') { @@ -79,21 +42,6 @@ describe('fetchPrHeadTrackingRef', () => { ) }) - it('keeps WSL routing while bounding the pull-head fetch', async () => { - await fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: null }, 'origin', 42, { - localGitExecOptions: { cwd: '/repo', wslDistro: 'Ubuntu' } - }) - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo', - wslDistro: 'Ubuntu' - }) - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['fetch', '--no-tags', 'origin', `+refs/pull/42/head:refs/orca/pull/${ORIGIN_COMPONENT}/42`], - { cwd: '/repo', wslDistro: 'Ubuntu', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } - ) - }) - it('rejects a GitHub pull-head fetch for an SSH repo', async () => { await expect( fetchGitHubPullRequestHeadRef({ path: '/repo', connectionId: 'conn-1' }, 'origin', 42) diff --git a/src/main/github/project-view/project-view-table.test.ts b/src/main/github/project-view/project-view-table.test.ts index b929b8d4fdc..ae90377ae35 100644 --- a/src/main/github/project-view/project-view-table.test.ts +++ b/src/main/github/project-view/project-view-table.test.ts @@ -51,14 +51,6 @@ beforeEach(() => { }) describe('project view layout selection', () => { - it('fetches roadmap items with the selected host and filter', async () => { - vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('roadmap', 'ROADMAP_LAYOUT')])) - const result = await getProjectViewTable({ ...args, viewId: 'roadmap' }) - expect(result).toMatchObject({ ok: true, data: { selectedView: { layout: 'ROADMAP_LAYOUT' } } }) - expect(fetchAllItems).toHaveBeenCalledWith({ ...args, query: 'status:open' }) - expect(fetchItemsCountOnly).not.toHaveBeenCalled() - }) - it('defaults to a roadmap when no table exists across all view pages', async () => { vi.mocked(fetchProjectViewsPage) .mockResolvedValueOnce(page([view('roadmap', 'ROADMAP_LAYOUT')], true)) @@ -89,22 +81,6 @@ describe('project view layout selection', () => { expect(fetchAllItems).not.toHaveBeenCalled() }) - it('fetches board items like a table', async () => { - vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('board', 'BOARD_LAYOUT')])) - const result = await getProjectViewTable({ ...args, viewId: 'board' }) - expect(result).toMatchObject({ ok: true, data: { selectedView: { layout: 'BOARD_LAYOUT' } } }) - expect(fetchAllItems).toHaveBeenCalledWith({ ...args, query: 'status:open' }) - expect(fetchItemsCountOnly).not.toHaveBeenCalled() - }) - - it('defaults to a board when neither a table nor a roadmap exists', async () => { - vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('board', 'BOARD_LAYOUT')])) - expect(await getProjectViewTable(args)).toMatchObject({ - ok: true, - data: { selectedView: { id: 'board' } } - }) - }) - it('rejects an unknown future layout without fetching items', async () => { vi.mocked(fetchProjectViewsPage).mockResolvedValue(page([view('unsupported', 'FUTURE_LAYOUT')])) expect( diff --git a/src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts b/src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts index 318bca7c851..b435fef86c4 100644 --- a/src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts +++ b/src/main/hang-watchdog/hang-watchdog-detection-loop.test.ts @@ -19,49 +19,6 @@ function loopWithClock(startAt = 0) { } describe('createHangWatchdogDetectionLoop', () => { - it('does not fire while heartbeats keep arriving', () => { - const { loop, onHangDetected, advance } = loopWithClock() - for (let i = 0; i < 100; i++) { - advance(CHECK_INTERVAL_MS) - loop.recordHeartbeat() - loop.tick() - } - expect(onHangDetected).not.toHaveBeenCalled() - }) - - it('fires once when heartbeats stop for longer than the timeout', () => { - const { loop, onHangDetected, advance } = loopWithClock() - loop.recordHeartbeat() - for (let i = 0; i < 12; i++) { - advance(CHECK_INTERVAL_MS) - loop.tick() - } - expect(onHangDetected).toHaveBeenCalledTimes(1) - advance(CHECK_INTERVAL_MS) - loop.tick() - expect(onHangDetected).toHaveBeenCalledTimes(1) - }) - - it('reports the measured stall duration, not the timeout', () => { - const { loop, onHangDetected, advance } = loopWithClock() - loop.recordHeartbeat() - for (let i = 0; i < 12; i++) { - advance(CHECK_INTERVAL_MS) - loop.tick() - } - expect(onHangDetected).toHaveBeenCalledWith(50_000) - }) - - it('does not fire at exactly the timeout boundary', () => { - const { loop, onHangDetected, advance } = loopWithClock() - loop.recordHeartbeat() - for (let i = 0; i < 9; i++) { - advance(CHECK_INTERVAL_MS) - loop.tick() - } - expect(onHangDetected).not.toHaveBeenCalled() - }) - it('treats a large tick gap as system sleep and restarts the wait', () => { const { loop, onHangDetected, advance } = loopWithClock() loop.recordHeartbeat() @@ -82,30 +39,6 @@ describe('createHangWatchdogDetectionLoop', () => { expect(onHangDetected).toHaveBeenCalledTimes(1) }) - it('reports resolution when heartbeats resume after a detected hang', () => { - const { loop, onHangDetected, onHangResolved, advance } = loopWithClock() - loop.recordHeartbeat() - for (let i = 0; i < 12; i++) { - advance(CHECK_INTERVAL_MS) - loop.tick() - } - expect(onHangDetected).toHaveBeenCalledTimes(1) - advance(CHECK_INTERVAL_MS) - loop.recordHeartbeat() - expect(onHangResolved).toHaveBeenCalledTimes(1) - expect(onHangResolved).toHaveBeenCalledWith(13 * CHECK_INTERVAL_MS) - }) - - it('does not report resolution when no hang was ever detected', () => { - const { loop, onHangResolved, advance } = loopWithClock() - for (let i = 0; i < 5; i++) { - advance(CHECK_INTERVAL_MS) - loop.recordHeartbeat() - loop.tick() - } - expect(onHangResolved).not.toHaveBeenCalled() - }) - it('can detect a second hang after the first one resolved', () => { const { loop, onHangDetected, onHangResolved, advance } = loopWithClock() loop.recordHeartbeat() diff --git a/src/main/host/electron-manual-redirect-fetch.test.ts b/src/main/host/electron-manual-redirect-fetch.test.ts index 5036a0d21ca..bd89d334893 100644 --- a/src/main/host/electron-manual-redirect-fetch.test.ts +++ b/src/main/host/electron-manual-redirect-fetch.test.ts @@ -35,13 +35,6 @@ describe('fetchWithElectronManualRedirects', () => { ) }) - it('falls back to the followed URL when the redirect has no Location', async () => { - const pending = fetchWithElectronManualRedirects('https://github.com/o.png', {}) - native.emit('redirect', 301, 'GET', 'https://avatars.example/u/2', {}) - - expect((await pending).headers.get('location')).toBe('https://avatars.example/u/2') - }) - it('streams the final response body', async () => { const pending = fetchWithElectronManualRedirects('https://github.com/o.png', {}) native.emit( diff --git a/src/main/ipc/ephemeral-vm-managed-ssh.test.ts b/src/main/ipc/ephemeral-vm-managed-ssh.test.ts index a250a63e36b..968e6a63c4e 100644 --- a/src/main/ipc/ephemeral-vm-managed-ssh.test.ts +++ b/src/main/ipc/ephemeral-vm-managed-ssh.test.ts @@ -99,16 +99,6 @@ async function provision(): Promise { }) } -it("records the managed server that serves a recipe VM's SSH host", async () => { - setupManagedSshRecipe() - expect(await provision()).toMatchObject({ - ok: true, - connectionType: 'ssh', - environmentId: 'env-managed-vm', - runtime: { connectionMode: 'ssh', runtimeEnvironmentId: 'env-managed-vm' } - }) -}) - it("reconnects a resumed VM's SSH host instead of asking for a pairing code", async () => { const { userDataPath, store } = setupManagedSshRecipe() const provisioned = await provision() diff --git a/src/main/ipc/managed-host-status-publication.test.ts b/src/main/ipc/managed-host-status-publication.test.ts index d779e99c77b..9dfa82b2646 100644 --- a/src/main/ipc/managed-host-status-publication.test.ts +++ b/src/main/ipc/managed-host-status-publication.test.ts @@ -36,21 +36,6 @@ describe('publishing a verified managed host status', () => { clearSshHostServerStatus('ssh-2') }) - it('replaces the deferred diagnostic in the host store and both subscribers', () => { - setSshHostServerStatus('ssh-1', deferred) - mocks.getState.mockReturnValue(connection('connected')) - publishHostServerStatus('ssh-1', ready) - expect(getSshHostServerStatus('ssh-1')).toEqual(ready) - expect(mocks.notify).toHaveBeenCalledWith( - 'ssh-1', - expect.objectContaining({ managedServer: ready }) - ) - expect(mocks.send).toHaveBeenCalledWith( - 'ssh:state-changed', - expect.objectContaining({ state: expect.objectContaining({ managedServer: ready }) }) - ) - }) - it('preserves disconnected contact instead of inventing a connection', () => { mocks.getState.mockReturnValue(connection('disconnected')) publishHostServerStatus('ssh-1', ready) @@ -60,41 +45,6 @@ describe('publishing a verified managed host status', () => { ) }) - it('retains the current unverifiable host evidence when publishing it', () => { - mocks.getState.mockReturnValue(connection('connected')) - const unverifiable = { - ...ready, - serving: { state: 'unverifiable', detail: 'The process is live but not answering.' } - } as const - publishHostServerStatus('ssh-1', unverifiable) - expect(getSshHostServerStatus('ssh-1')).toEqual(unverifiable) - expect(mocks.notify.mock.calls[0]?.[1].managedServer).toEqual(unverifiable) - }) - - it('records a host without a connection and leaves another host untouched', () => { - mocks.getState.mockReturnValue(undefined) - setSshHostServerStatus('ssh-2', deferred) - publishHostServerStatus('ssh-1', ready) - expect(getSshHostServerStatus('ssh-1')).toEqual(ready) - expect(getSshHostServerStatus('ssh-2')).toEqual(deferred) - expect(mocks.notify).not.toHaveBeenCalled() - expect(mocks.send).not.toHaveBeenCalled() - }) - - it("clears a verified host's deferral and unverifiable notes", () => { - mocks.getState.mockReturnValue(connection('connected')) - setSshHostServerStatus('ssh-1', { - ...deferred, - serving: { state: 'unverifiable', detail: 'No reply.' } - }) - clearManagedServerNotes('ssh-1', 'env-1') - expect(getSshHostServerStatus('ssh-1')).toEqual(ready) - expect(mocks.notify).toHaveBeenCalledWith( - 'ssh-1', - expect.objectContaining({ managedServer: ready }) - ) - }) - it('leaves a relay route, another server, or an unknown host as it was', () => { mocks.getState.mockReturnValue(connection('connected')) const relay = { kind: 'relay', reason: 'source_changed' } as const diff --git a/src/main/ipc/pty/spawn-host-env-wsl-passive-restore.test.ts b/src/main/ipc/pty/spawn-host-env-wsl-passive-restore.test.ts index bad03125350..871a51802b7 100644 --- a/src/main/ipc/pty/spawn-host-env-wsl-passive-restore.test.ts +++ b/src/main/ipc/pty/spawn-host-env-wsl-passive-restore.test.ts @@ -80,18 +80,6 @@ afterEach(() => { // Spawn env prep runs before #35813's hold: only a launch someone asked for may start the distro (E9). describe('WSL spawn host env', () => { - it('runs a launch someone asked for as a user act on its distro', async () => { - const seen: boolean[] = [] - await resolve(false, seen) - expect(seen).toEqual([true]) - }) - - it('runs a passive restore outside any user act, so its prep is gated', async () => { - const seen: boolean[] = [] - await resolve(true, seen) - expect(seen).toEqual([false]) - }) - it('never turns a passive restore with no named distro into a user act on the default one', async () => { const seen: boolean[] = [] await resolve(true, seen, { @@ -101,12 +89,6 @@ describe('WSL spawn host env', () => { expect(seen).toEqual([false]) }) - it('never turns a host-target spawn into a user act on the default distro', async () => { - const seen: boolean[] = [] - await resolve(false, seen, { target: { runtime: 'host' }, expectedWslDistro: null }) - expect(seen).toEqual([false]) - }) - it('a WSL launch someone asked for, with no named distro, acts on the default one', async () => { const seen: boolean[] = [] await resolve(false, seen, { @@ -122,9 +104,4 @@ describe('WSL spawn host env', () => { expect(mocks.blockedPath).toHaveBeenCalledWith(HOME) expect(mocks.ensureBackfill).not.toHaveBeenCalled() }) - - it('still starts the state-DB recovery when the distro runs', async () => { - await resolve(true, []) - expect(mocks.ensureBackfill).toHaveBeenCalledWith(HOME) - }) }) diff --git a/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts b/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts index f07ffd7ca46..bfc75cf7843 100644 --- a/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts +++ b/src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts @@ -98,19 +98,6 @@ describe('the quit checkpoint in a layout-owner build', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('records main’s own quit capture before staging, though the window’s save lacks it', () => { - store.setWorkspaceSession(session(), 'local') - const captured = record(PANE_A, 2) - quitRecords.push(captured) - - expect(stage(session())).toEqual({ ok: true }) - - expect(quitResumeRecordsFor).toHaveBeenCalledOnce() - expect(store.getWorkspaceSession('local').sleepingAgentSessionsByPaneKey?.[PANE_A]).toEqual( - captured - ) - }) - it('keeps a wake main recorded that the window had not seen yet', () => { // Main woke tab-b (a phone showed it) after the window last saw its record. store.setWorkspaceSession(session(), 'local') diff --git a/src/main/ipc/wsl-guest-native-program.test.ts b/src/main/ipc/wsl-guest-native-program.test.ts index 4f3faa8ac0d..64d31745d18 100644 --- a/src/main/ipc/wsl-guest-native-program.test.ts +++ b/src/main/ipc/wsl-guest-native-program.test.ts @@ -2,12 +2,9 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:f import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { resolveCliCommand } from '../../shared/node-cli-command-resolution' + import { _resetWindowsCopyVerdictsForTests, - guestNativeSpawnEnv, - isWslHostOrcadProcess, - ORCAD_WSL_HOST_ENV, resolveGuestNativeProgram } from './wsl-guest-windows-drive-path' @@ -49,29 +46,10 @@ describe.skipIf(process.platform === 'win32')('resolveGuestNativeProgram', () => install(join(drive, 'npm')) expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBeNull() }) - - it('leaves a program missing everywhere as its bare name, so the spawn fails as not installed', () => { - expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBe('claude') - }) - - it('resolves exactly as before off a WSL host (native Linux, macOS, SSH hosts, the desktop)', () => { - const windowsCopy = install(join(drive, 'npm')) - expect(resolveGuestNativeProgram('claude', options(), undefined, [])).toBe(windowsCopy) - }) }) describe.skipIf(process.platform === 'win32')('the Windows-copy check', () => { const options = () => ({ pathEnv: `${native}:${drive}/npm`, homePath: join(root, 'home') }) - const counting = () => vi.fn(resolveCliCommand) - - it('scans the drive-mounted PATH once for repeated lookups of the same PATH', () => { - install(join(drive, 'npm')) - const resolve = counting() - expect(resolveGuestNativeProgram('claude', options(), resolve, [drive])).toBeNull() - expect(resolveGuestNativeProgram('claude', options(), resolve, [drive])).toBeNull() - // One native lookup per call, one Windows-copy scan in total. - expect(resolve).toHaveBeenCalledTimes(3) - }) it('still finds a WSL install made after the verdict was cached', () => { install(join(drive, 'npm')) @@ -88,42 +66,4 @@ describe.skipIf(process.platform === 'win32')('the Windows-copy check', () => { vi.advanceTimersByTime(30_000) expect(resolveGuestNativeProgram('claude', options(), undefined, [drive])).toBeNull() }) - - it('caches nothing off a WSL host (native Linux, macOS, SSH hosts, the desktop)', () => { - const resolve = counting() - expect(resolveGuestNativeProgram('claude', options(), resolve, [])).toBe('claude') - const windowsCopy = install(join(drive, 'npm')) - expect(resolveGuestNativeProgram('claude', options(), resolve, [])).toBe(windowsCopy) - expect(resolve).toHaveBeenCalledTimes(2) - }) -}) - -describe('guestNativeSpawnEnv', () => { - it('drops Windows drive entries from a WSL-host agent child PATH', () => { - expect(guestNativeSpawnEnv({ PATH: '/usr/bin:/mnt/c/npm', HOME: '/h' }, ['/mnt/c'])).toEqual({ - PATH: '/usr/bin', - HOME: '/h' - }) - }) - - it('returns the env untouched where there are no drive mounts', () => { - const env = { PATH: '/usr/bin:/mnt/c/npm' } - expect(guestNativeSpawnEnv(env, [])).toBe(env) - }) -}) - -describe('the WSL-host gate', () => { - const marked = { [ORCAD_WSL_HOST_ENV]: '1', WSL_DISTRO_NAME: 'Ubuntu' } - - it('stays off on macOS, the Windows desktop, native Linux and SSH-host orcad', () => { - expect(isWslHostOrcadProcess(marked, 'darwin', () => true)).toBe(false) - expect(isWslHostOrcadProcess(marked, 'win32', () => true)).toBe(false) - expect(isWslHostOrcadProcess({}, 'linux', () => false)).toBe(false) - // An SSH host's orcad is launched with nohup and never gets the WSL-host marker. - expect(isWslHostOrcadProcess({ ORCA_USER_DATA: '/srv/orca' }, 'linux', () => false)).toBe(false) - }) - - it('turns on only for orcad launched as a WSL host inside the guest', () => { - expect(isWslHostOrcadProcess(marked, 'linux', () => false)).toBe(true) - }) }) diff --git a/src/main/linux-package-install-diagnostic.test.ts b/src/main/linux-package-install-diagnostic.test.ts index 14e82a0763b..5c498695ff2 100644 --- a/src/main/linux-package-install-diagnostic.test.ts +++ b/src/main/linux-package-install-diagnostic.test.ts @@ -52,59 +52,4 @@ describe('redactLinuxPackageInstallText', () => { 'ci: incident in circuit' ) }) - - it('survives an unavailable user record', () => { - vi.spyOn(os, 'userInfo').mockImplementation(() => { - throw new Error('no passwd entry') - }) - expect(diagnostic.redactLinuxPackageInstallText('dpkg: unrecoverable error', null)).toBe( - 'dpkg: unrecoverable error' - ) - }) - - it('bounds the result at 1024 characters', () => { - expect(diagnostic.redactLinuxPackageInstallText('a'.repeat(2_000), null)).toHaveLength(1_024) - expect(diagnostic.redactLinuxPackageInstallText('a'.repeat(1_024), null)).toHaveLength(1_024) - }) - - it('returns null when no visible text remains', () => { - expect(diagnostic.redactLinuxPackageInstallText('', null)).toBeNull() - expect(diagnostic.redactLinuxPackageInstallText(' \n\t ', null)).toBeNull() - expect(diagnostic.redactLinuxPackageInstallText(`${ESC}[0m`, null)).toBeNull() - expect(diagnostic.redactLinuxPackageInstallText(null, null)).toBeNull() - expect(diagnostic.redactLinuxPackageInstallText(undefined, null)).toBeNull() - }) - - it('normalizes errors, objects, and primitives', () => { - expect(diagnostic.redactLinuxPackageInstallText(new Error('pkexec failed'), null)).toBe( - 'pkexec failed' - ) - expect(diagnostic.redactLinuxPackageInstallText({ code: 127 }, null)).toBe('{"code":127}') - expect(diagnostic.redactLinuxPackageInstallText(127, null)).toBe('127') - }) - - it('returns null for an unserializable object', () => { - const circular: Record = {} - circular.self = circular - expect(diagnostic.redactLinuxPackageInstallText(circular, null)).toBeNull() - }) - - it('ignores an empty package path', () => { - expect(diagnostic.redactLinuxPackageInstallText('plain output', '')).toBe('plain output') - }) -}) - -describe('createUpdaterDiagnosticLogger', () => { - it('forwards every updater level to the matching console method', () => { - const logger = diagnostic.createUpdaterDiagnosticLogger() - logger.info('a') - logger.warn('b') - logger.error('c') - logger.debug('d') - - expect(console.info).toHaveBeenCalledWith('[autoUpdater]', 'a') - expect(console.warn).toHaveBeenCalledWith('[autoUpdater]', 'b') - expect(console.error).toHaveBeenCalledWith('[autoUpdater]', 'c') - expect(console.debug).toHaveBeenCalledWith('[autoUpdater]', 'd') - }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts index 84bcd596134..70fb6112ddf 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts @@ -147,23 +147,6 @@ it('ends the child at once when Claude refuses the interrupt, and says only that expect(texts.some((text) => text.includes("didn't stop"))).toBe(false) }) -it('ends the child when the interrupt fails, with no unconfirmed row', async () => { - fixture.claude.routes.interrupt = () => { - throw new Error('control request lost') - } - const connection = fixture.claude.connections[0]! - const eventsAtClose = stopEventsAtClose(connection) - await openTurn(connection) - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - await laneDrained() - - expect(connection.closed).toBe(true) - expect(eventsAtClose()).toBe(1) - expect(await turnOutcome()).toBe('cancellation') - expect(await statusTexts()).toEqual(['Cancellation requested.']) -}) - it('ends the child within the grace when Claude never answers the interrupt', async () => { fixture.claude.routes.interrupt = NEVER_ANSWERS const connection = fixture.claude.connections[0]! @@ -217,27 +200,6 @@ it('ends background work Claude runs when the Stop ends the child', async () => expect(connection.closed).toBe(true) }) -it('starts a new child for the next send after a Stop, on the same Claude conversation', async () => { - const connection = fixture.claude.connections[0]! - await openTurn(connection) - await stop() - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - const next = await send('Carry on.') - const resumed = await eventually(() => { - const started = fixture.claude.connections.at(-1) - expect(started).not.toBe(connection) - expect(started && wrote(started, 'Carry on.')).toBe(true) - return started! - }) - expect(fixture.store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ - nativeId: PROVIDER_SESSION_ID - }) - expect(resumed.closed).toBe(false) - expect(await dispatch(next)).toMatchObject({ state: 'pending' }) -}) - it('delivers a send issued with the pre-Stop fence during the Stop to the resumed child only', async () => { const connection = fixture.claude.connections[0]! await openTurn(connection) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts index 7fcb039399c..b11c26aff49 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts @@ -17,7 +17,6 @@ import { statusNotes } from './structured-agent-session-restart-interruption-test-harness' import type { StructuredAgentSessionHost } from './structured-agent-session-host' -import { previousExitUnverifiableRefusal } from './structured-agent-session-child-close' type Restarted = Awaited> @@ -145,16 +144,6 @@ it('continues when reading the restart offer hangs', async () => { } }, 10_000) -it('continues when the restart offer cannot be read', async () => { - const { host, dispatch } = await interruptedRestart() - const turnItemId = await cutTurn(host) - vi.spyOn(host.deps.recoveryCapsule!, 'list').mockRejectedValue(new Error('unreadable')) - - await host.restartResume.continueInterrupted(SESSION, turnItemId) - - await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce()) -}) - it('answers once Orca accepted it, while the agent is still starting', async () => { const { host, acquire, dispatch } = await interruptedRestart() const turnItemId = await cutTurn(host) @@ -217,21 +206,3 @@ it('continues a reply the user had steered before Orca stopped', async () => { await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce()) expect(sentTexts(dispatch)).toEqual([restartContinuationMessage(marker!)]) }) - -it('answers a refusal before anything was accepted, and a retry adds no note to the chat', async () => { - const { host, dispatch } = await interruptedRestart() - const turnItemId = await cutTurn(host) - const notesBefore = await statusNotes(host) - vi.spyOn(host, 'send').mockResolvedValue({ - ok: false, - refusal: previousExitUnverifiableRefusal() - }) - - const first = await host.restartResume.continueInterrupted(SESSION, turnItemId) - const retry = await host.restartResume.continueInterrupted(SESSION, turnItemId) - - expect([first.outcome, retry.outcome]).toEqual(['refused', 'refused']) - // Refusal belongs in the click response, with no journal note. - expect(await statusNotes(host)).toEqual(notesBefore) - expect(dispatch).not.toHaveBeenCalled() -}) diff --git a/src/main/orcad/orcad-daemon-supervision.test.ts b/src/main/orcad/orcad-daemon-supervision.test.ts deleted file mode 100644 index e2d8437f485..00000000000 --- a/src/main/orcad/orcad-daemon-supervision.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { - initDaemonPtyProviderMock, - disconnectDaemonMock, - shutdownDaemonMock, - daemonOwnsFreshPersistentPtysMock, - readDaemonPidRecordMock -} = vi.hoisted(() => ({ - initDaemonPtyProviderMock: vi.fn<(signal?: unknown, options?: unknown) => Promise>(), - disconnectDaemonMock: vi.fn<() => Promise>(), - shutdownDaemonMock: vi.fn<() => Promise>(), - daemonOwnsFreshPersistentPtysMock: vi.fn<() => boolean>(), - readDaemonPidRecordMock: vi.fn<() => { pid: number } | null>() -})) - -vi.mock('../daemon/daemon-provider-init', () => ({ - initDaemonPtyProvider: initDaemonPtyProviderMock -})) -vi.mock('../daemon/daemon-provider-state', () => ({ - disconnectDaemon: disconnectDaemonMock, - shutdownDaemon: shutdownDaemonMock, - daemonOwnsFreshPersistentPtys: daemonOwnsFreshPersistentPtysMock, - readDaemonPidRecord: readDaemonPidRecordMock -})) - -const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision') - -beforeEach(() => { - initDaemonPtyProviderMock.mockResolvedValue() - disconnectDaemonMock.mockResolvedValue() - shutdownDaemonMock.mockResolvedValue() - daemonOwnsFreshPersistentPtysMock.mockReturnValue(true) - readDaemonPidRecordMock.mockReturnValue({ pid: 4242 }) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) -}) - -afterEach(() => { - vi.restoreAllMocks() - vi.clearAllMocks() -}) - -describe('startOrcadDaemon', () => { - it('reports live with the daemon pid once the provider is installed', async () => { - await expect(startOrcadDaemon()).resolves.toEqual({ state: 'live', pid: 4242 }) - }) - - it('does not arm the macOS login-session death watch', async () => { - await startOrcadDaemon() - expect(initDaemonPtyProviderMock).toHaveBeenCalledWith(undefined, { - macosLoginSessionWatch: false, - recycleStaleDaemonOnEveryPlatform: true, - spawnAdmission: 'enforce' - }) - }) - - it('gives a cold Windows daemon a longer startup budget', async () => { - await startOrcadDaemon('win32') - expect(initDaemonPtyProviderMock).toHaveBeenCalledWith(undefined, { - macosLoginSessionWatch: false, - recycleStaleDaemonOnEveryPlatform: true, - spawnAdmission: 'enforce', - startupTimeoutMs: 30_000 - }) - }) - - it('retries the daemon spawn once before falling back to in-process terminals', async () => { - initDaemonPtyProviderMock.mockRejectedValueOnce(new Error('Daemon startup timed out')) - await expect(startOrcadDaemon()).resolves.toEqual({ state: 'live', pid: 4242 }) - expect(initDaemonPtyProviderMock).toHaveBeenCalledTimes(2) - }) - - it('reports degraded when fresh terminals would fall back to the local provider', async () => { - daemonOwnsFreshPersistentPtysMock.mockReturnValue(false) - const result = await startOrcadDaemon() - expect(result.state).toBe('degraded') - }) - - it('fails open when the daemon cannot start at all', async () => { - initDaemonPtyProviderMock.mockRejectedValue(new Error('node-pty is missing')) - daemonOwnsFreshPersistentPtysMock.mockReturnValue(false) - await expect(startOrcadDaemon()).resolves.toEqual({ - state: 'unavailable', - reason: 'node-pty is missing' - }) - expect(initDaemonPtyProviderMock).toHaveBeenCalledTimes(2) - }) -}) - -describe('stopOrcadDaemon', () => { - it('disconnects and never shuts the daemon down', async () => { - await stopOrcadDaemon() - expect(disconnectDaemonMock).toHaveBeenCalledTimes(1) - expect(shutdownDaemonMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-host-readiness.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-host-readiness.test.ts index bc0a9a0ea38..85d6d9c6272 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-host-readiness.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-host-readiness.test.ts @@ -40,38 +40,6 @@ describe('prepareWslMoveHost (A1)', () => { expect(stopped.add).not.toHaveBeenCalled() }) - it('adds a host for a running bridge distro, or connects the one it has', async () => { - const bridge = deps() - expect(await prepareWslMoveHost(bridge, 'ubuntu')).toBe('ready') - expect(bridge.add).toHaveBeenCalledWith('ubuntu') - const added = deps({ hasHost: () => true }) - expect(await prepareWslMoveHost(added, 'Ubuntu')).toBe('ready') - expect(added.connect).toHaveBeenCalled() - expect(added.add).not.toHaveBeenCalled() - }) - - it('reports a refused add or failed connect as failed', async () => { - const refused = deps({ - add: async () => ({ ok: false, kind: 'failed', message: 'nope' }) - }) - expect(await prepareWslMoveHost(refused, 'Ubuntu')).toBe('failed') - const broken = deps({ - hasHost: () => true, - connect: async () => { - throw new Error('pairing') - } - }) - expect(await prepareWslMoveHost(broken, 'Ubuntu')).toBe('failed') - }) - - // E11 (#33843): a host whose Remove is pending is never connected or added. - it('never connects or adds a host whose Remove is pending', async () => { - const pending = deps({ hasHost: () => true, removalPending: () => true }) - expect(await prepareWslMoveHost(pending, 'Ubuntu')).toBe('failed') - expect(pending.connect).not.toHaveBeenCalled() - expect(pending.add).not.toHaveBeenCalled() - }) - it('re-reads the pending Remove after the running-distro read', async () => { let removing = false const racing = deps({ diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.test.ts index 294f18f0d03..658096f6402 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-ui-routing-rewrite.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' -import wslMoveAgentModelUI from '../../../shared/__fixtures__/wsl-move-agent-model-ui.json' -import { projectWslMoveUi } from './wsl-move-session-projection' + import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' import type { WorkspaceCleanupDismissal } from '../../../shared/workspace-cleanup' import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture' @@ -88,22 +87,6 @@ function dismissal( } describe('WSL move UI routing rewrite', () => { - it('preserves global model visibility in the desktop snapshot consumed by the renderer', () => { - const desktop = wslMoveAgentModelUI.desktopBeforeMove - const projected = projectWslMoveUi( - desktop, - {}, - (owner) => !!owner && scope.inScope(owner), - () => true - ) - expect(projected).not.toHaveProperty('showAgentModels') - expect(projected).toEqual(wslMoveAgentModelUI.projectedProjectUI) - const updates = rewriteWslMoveUiRouting(desktop, scope) - expect(updates).not.toHaveProperty('showAgentModels') - // The renderer consumes this exact snapshot; changes to production output must update the contract. - expect({ ...desktop, ...updates }).toEqual(wslMoveAgentModelUI.desktopAfterMove) - }) - it("copies only the moved project's rows to the host's form, keeping the local ones", () => { const ui = profileUi() const updates = rewriteWslMoveUiRouting(ui, scope) @@ -200,47 +183,6 @@ describe('WSL move UI routing rewrite', () => { }) }) - it('adds the host wherever local is shown, and never removes local', () => { - const updates = rewriteWslMoveUiRouting(profileUi(), scope) - - // The legacy `local` scope resolves to a list, so the host joins it there. - expect(updates.visibleWorkspaceHostIds).toEqual(['local', HOST]) - expect(updates.workspaceHostScope).toBeUndefined() - expect(updates.agentsVisibleHostIds).toEqual([SSH, 'local', HOST]) - expect(updates.workspaceHostOrder).toEqual(['local', HOST, SSH]) - }) - - it('leaves host filters that do not show local, or show all hosts, alone', () => { - const updates = rewriteWslMoveUiRouting( - { - ...profileUi(), - workspaceHostScope: 'all', - visibleWorkspaceHostIds: null, - agentsVisibleHostIds: [SSH], - workspaceHostOrder: undefined - }, - scope - ) - - expect(updates.visibleWorkspaceHostIds).toBeUndefined() - expect(updates.agentsVisibleHostIds).toBeUndefined() - expect(updates.workspaceHostOrder).toBeUndefined() - }) - - it('keeps the local setup-prompt dismissal and lineage group beside the host ones', () => { - const ui = profileUi() - const updates = rewriteWslMoveUiRouting(ui, scope) - - expect(updates.setupScriptPromptDismissedRepoIds).toEqual([ - ...(ui.setupScriptPromptDismissedRepoIds ?? []), - `generation-v1:${HOST}\0repo-a` - ]) - expect(updates.collapsedGroups).toEqual([ - ...ui.collapsedGroups, - `lineage:${HOST}|${MOVED_ON_HOST}` - ]) - }) - it('changes nothing on a second run', () => { const first = { ...profileUi(), @@ -249,16 +191,4 @@ describe('WSL move UI routing rewrite', () => { expect(rewriteWslMoveUiRouting(first, scope)).toEqual({}) }) - - it('changes nothing for a UI that never named the moved project', () => { - const ui: WslMoveUiRoutingState = { - lastActiveWorktreeId: WINDOWS, - showDotfilesByWorktree: { [SAME_DISTRO]: true }, - collapsedGroups: [`lineage:local|${WINDOWS}`], - manualRepoOrder: [{ hostId: 'local', repoId: 'repo-win' }], - agentsVisibleHostIds: null - } - - expect(rewriteWslMoveUiRouting(ui, scope)).toEqual({}) - }) }) diff --git a/src/main/plugins/plugin-discovery.test.ts b/src/main/plugins/plugin-discovery.test.ts index ab13b381940..944720a962b 100644 --- a/src/main/plugins/plugin-discovery.test.ts +++ b/src/main/plugins/plugin-discovery.test.ts @@ -64,46 +64,6 @@ describe('project repositories', () => { }) describe('installed plugin discovery identity', () => { - it('requires a new review when an installed v2 worker has different bytes', async () => { - const pluginsDir = await tempPluginsDir() - const key = 'samples.worker' - const discoverAt = async (hash: string) => { - const versionDir = join(pluginsDir, key, hash) - await mkdir(versionDir, { recursive: true }) - await writeFile(join(pluginsDir, key, 'current'), hash) - await writeFile(join(versionDir, 'main.mjs'), 'export default () => {}') - await writeFile( - join(versionDir, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'trusted-worker', - id: 'worker', - publisher: 'samples', - name: 'Worker', - version: '1.0.0', - engines: { orca: `>=${PLUGIN_SCHEMA_NEWEST_SINCE}` }, - pluginApi: 1, - main: 'main.mjs' - }) - ) - const [plugin] = await discoverPlugins({ - pluginsDir, - devPluginPaths: [], - hostVersion: PLUGIN_SCHEMA_NEWEST_SINCE - }) - if (!plugin || isInvalidDiscoveredPlugin(plugin)) { - throw new Error('expected a valid plugin') - } - return plugin - } - - const approved = await discoverAt('a'.repeat(64)) - const updated = await discoverAt('b'.repeat(64)) - - expect(updated.consentContentHash).toBe('b'.repeat(64)) - expect(updated.consentFingerprint).not.toBe(approved.consentFingerprint) - }) - it('keeps the install directory identity when a manifest is invalid or mismatched', async () => { const pluginsDir = await tempPluginsDir() const installedKey = 'samples.expected' @@ -133,34 +93,6 @@ describe('installed plugin discovery identity', () => { expect(plugin && 'error' in plugin ? plugin.error : '').toContain('does not match') }) - it('names the version gap when a plugin for a newer Orca uses fields this build lacks', async () => { - const pluginsDir = await tempPluginsDir() - const hash = 'b'.repeat(64) - const versionDir = join(pluginsDir, 'acme.future', hash) - await mkdir(versionDir, { recursive: true }) - await writeFile(join(pluginsDir, 'acme.future', 'current'), hash) - await writeFile( - join(versionDir, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'data', - id: 'future', - publisher: 'acme', - name: 'Future', - version: '1.0.0', - engines: { orca: '>=9.0.0' }, - pluginApi: 1, - contributes: { widgets: [{ id: 'clock' }] } - }) - ) - - const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' }) - - expect(plugin && 'error' in plugin ? plugin.error : '').toBe( - 'requires Orca >=9.0.0 (this is 1.4.0)' - ) - }) - // Regression: Excalidraw 1.0.0 as installed from the catalog before the format 2 floor moved. it('loads an installed manifest whose engines floor predates its fields, but not a dev copy', async () => { const pluginsDir = await tempPluginsDir() @@ -215,17 +147,6 @@ describe('installed plugin discovery identity', () => { expect(old && 'error' in old ? old.error : '').toBe('requires Orca >=1.4.244 (this is 1.4.200)') }) - it('keeps a removable qualified identity when the current pointer is missing', async () => { - const pluginsDir = await tempPluginsDir() - const installedKey = 'samples.broken' - await mkdir(join(pluginsDir, installedKey), { recursive: true }) - - const [plugin] = await discoverPlugins({ pluginsDir, devPluginPaths: [], hostVersion: '1.4.0' }) - - expect(plugin && isInvalidDiscoveredPlugin(plugin)).toBe(true) - expect(plugin?.pluginKey).toBe(installedKey) - }) - it('rejects an oversized current pointer without an unbounded startup read', async () => { const pluginsDir = await tempPluginsDir() const installedKey = 'samples.broken' diff --git a/src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts b/src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts index 25baa992451..a8749049865 100644 --- a/src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts +++ b/src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts @@ -29,127 +29,6 @@ describePosix('live zsh subprocess tests', () => { rmSync(userDataPath, { recursive: true, force: true }) }) - it('discovers ZDOTDIR when launched inside tmux', async () => { - const xdgZshDir = join(testHome, '.config', 'zsh') - mkdirSync(xdgZshDir, { recursive: true }) - writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${xdgZshDir}"\n`) - - const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() - const config = getShellReadyLaunchConfig('/bin/zsh') - - const cleanEnv: Record = { - ...process.env, - HOME: testHome, - TMUX: '/tmp/tmux-501/default,12345,0', - TMUX_PANE: '%0' - } - delete cleanEnv.ZDOTDIR - delete cleanEnv.ORCA_ORIG_ZDOTDIR - cleanEnv.ZDOTDIR = config.env.ZDOTDIR - - const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], { - env: cleanEnv as NodeJS.ProcessEnv, - encoding: 'utf8' - }) - - expect(result.status).toBe(0) - expect(result.stdout).toContain(`ZDOTDIR=${xdgZshDir}`) - }) - - it('discovers ZDOTDIR when launched from SSH session', async () => { - const xdgZshDir = join(testHome, '.config', 'zsh') - mkdirSync(xdgZshDir, { recursive: true }) - writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${xdgZshDir}"\n`) - - const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() - const config = getShellReadyLaunchConfig('/bin/zsh') - - const cleanEnv: Record = { - ...process.env, - HOME: testHome, - SSH_CONNECTION: '10.0.0.1 12345 10.0.0.2 22', - SSH_CLIENT: '10.0.0.1 12345 22', - LC_CTYPE: 'C.UTF-8' - } - delete cleanEnv.ZDOTDIR - delete cleanEnv.ORCA_ORIG_ZDOTDIR - cleanEnv.ZDOTDIR = config.env.ZDOTDIR - - const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], { - env: cleanEnv as NodeJS.ProcessEnv, - encoding: 'utf8' - }) - - expect(result.status).toBe(0) - expect(result.stdout).toContain(`ZDOTDIR=${xdgZshDir}`) - }) - - it('handles sudo -E where HOME and ZDOTDIR mismatch', async () => { - // Inherited ZDOTDIR counts as user configuration only when it contains a startup file. - const userZdotdir = join(testHome, '.config', 'zsh') - mkdirSync(userZdotdir, { recursive: true }) - writeFileSync(join(userZdotdir, '.zshrc'), '') - - const previousZdotdir = process.env.ZDOTDIR - const previousHome = process.env.HOME - process.env.ZDOTDIR = userZdotdir - process.env.HOME = '/root' // sudo changed HOME - - try { - const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() - const config = getShellReadyLaunchConfig('/bin/zsh') - - expect(config.env.ORCA_ORIG_ZDOTDIR).toBe(userZdotdir) - } finally { - if (previousZdotdir === undefined) { - delete process.env.ZDOTDIR - } else { - process.env.ZDOTDIR = previousZdotdir - } - if (previousHome === undefined) { - delete process.env.HOME - } else { - process.env.HOME = previousHome - } - } - }) - - it('re-discovers ZDOTDIR despite stale ORCA_ORIG_ZDOTDIR from previous session', async () => { - const currentZdotdir = join(testHome, '.config', 'zsh-current') - mkdirSync(currentZdotdir, { recursive: true }) - writeFileSync(join(testHome, '.zshenv'), `export ZDOTDIR="${currentZdotdir}"\n`) - - const previousOrcaZdotdir = process.env.ORCA_ORIG_ZDOTDIR - process.env.ORCA_ORIG_ZDOTDIR = '/opt/orca-old/shell-ready/zsh' // stale wrapper path - - try { - const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady() - const config = getShellReadyLaunchConfig('/bin/zsh') - - const cleanEnv: Record = { - ...process.env, - HOME: testHome, - ORCA_ORIG_ZDOTDIR: '/opt/orca-old/shell-ready/zsh' - } - delete cleanEnv.ZDOTDIR - cleanEnv.ZDOTDIR = config.env.ZDOTDIR - - const result = spawnSync('zsh', ['-c', 'echo "ZDOTDIR=${ZDOTDIR}"'], { - env: cleanEnv as NodeJS.ProcessEnv, - encoding: 'utf8' - }) - - expect(result.status).toBe(0) - expect(result.stdout).toContain(`ZDOTDIR=${currentZdotdir}`) - } finally { - if (previousOrcaZdotdir === undefined) { - delete process.env.ORCA_ORIG_ZDOTDIR - } else { - process.env.ORCA_ORIG_ZDOTDIR = previousOrcaZdotdir - } - } - }) - it('prioritizes fresh discovery over inherited ORCA_ORIG_ZDOTDIR', async () => { const freshZdotdir = join(testHome, '.config', 'zsh-updated') mkdirSync(freshZdotdir, { recursive: true }) diff --git a/src/main/providers/pty-process-inspection.test.ts b/src/main/providers/pty-process-inspection.test.ts index edbe0877a6e..c1b5f40c2d5 100644 --- a/src/main/providers/pty-process-inspection.test.ts +++ b/src/main/providers/pty-process-inspection.test.ts @@ -19,15 +19,6 @@ describe('PTY provider process inspection', () => { expect(provider.getForegroundProcess).not.toHaveBeenCalled() }) - it('preserves a completion-sensitive provider failure', async () => { - const failure = new Error('daemon unavailable') - const inspectProcess = vi.fn().mockRejectedValue(failure) - const provider = { inspectProcess } as unknown as IPtyProvider - - await expect(inspectPtyProviderProcess(provider, 'pty-1')).rejects.toBe(failure) - expect(inspectProcess).toHaveBeenCalledExactlyOnceWith('pty-1') - }) - it('returns client-only unverifiable to the renderer when a stale PTY is gone', async () => { const provider = { hasPty: vi.fn(() => false) @@ -62,31 +53,4 @@ describe('PTY provider process inspection', () => { reason: 'transport_loss' }) }) - - it('preserves a client-only unverifiable inspection result', async () => { - const inspection = { - foregroundProcess: null, - hasChildProcesses: false, - verdict: 'unverifiable' as const, - reason: 'transport_loss' as const - } - const inspectProcess = vi.fn().mockResolvedValue(inspection) - const provider = { inspectProcess } as unknown as IPtyProvider - - await expect(inspectPtyProviderProcess(provider, 'pty-1')).resolves.toEqual(inspection) - }) - - it('falls back to the existing provider process APIs', async () => { - const getForegroundProcess = vi.fn().mockResolvedValue('codex') - const hasChildProcesses = vi.fn().mockResolvedValue(true) - const provider = { - getForegroundProcess, - hasChildProcesses - } as Pick as IPtyProvider - - await expect(inspectPtyProviderProcess(provider, 'pty-1')).resolves.toEqual({ - foregroundProcess: 'codex', - hasChildProcesses: true - }) - }) }) diff --git a/src/main/providers/windows-foreground-process-rows.test.ts b/src/main/providers/windows-foreground-process-rows.test.ts index 9129bbfc62f..6010e2bbdea 100644 --- a/src/main/providers/windows-foreground-process-rows.test.ts +++ b/src/main/providers/windows-foreground-process-rows.test.ts @@ -58,11 +58,6 @@ describe('windows process rows', () => { const scanCount = (): number => getAllProcessesMock.mock.calls.length - it('walks descendants from the native snapshot', async () => { - const candidates = await queryWindowsProcessDescendants(100) - expect(candidates?.[0]?.pid).toBe(200) - }) - it('rejects a snapshot that does not contain the querying process', async () => { // A missing self PID invalidates the table; false empty evidence could authorize teardown. getAllProcessesMock.mockImplementation((cb: (rows: unknown) => void) => { @@ -98,15 +93,6 @@ describe('windows process rows', () => { expect(rows[31]?.map((row) => row.pid)).toEqual([200]) }) - it('never answers from the TTL cache, which can predate the recycle it detects', async () => { - await queryWindowsProcessDescendants(100) - expect(scanCount()).toBe(1) - - await queryWindowsProcessDescendants(100, { fresh: true }) - - expect(scanCount()).toBe(2) - }) - it('never answers the ancestry links from the identity TTL cache either', async () => { // Ancestry uses a separate identity TTL cache; fresh teardown must bypass that cache too. await readWindowsProcessIdentityTable() diff --git a/src/main/repo-backfill-wsl-move.test.ts b/src/main/repo-backfill-wsl-move.test.ts index c07b2963713..f680cb715c5 100644 --- a/src/main/repo-backfill-wsl-move.test.ts +++ b/src/main/repo-backfill-wsl-move.test.ts @@ -102,17 +102,6 @@ describe('git remote identity enrichment under a WSL move', () => { }) describe('fork upstream backfill under a WSL move', () => { - it('leaves the moving repo unset for a later run and fills the rest', async () => { - const store = createStore() - store.addRepo(repo(MOVING)) - store.addRepo(repo(STAYING)) - - await new RuntimeRepositoryForkBackfill(() => store, vi.fn()).run() - - expect(store.getRepo(MOVING)?.upstream).toBeUndefined() - expect(store.getRepo(STAYING)?.upstream).toEqual({ owner: 'acme', repo: 'app' }) - }) - it('fills the host row, not the hidden local row with the same id', async () => { seedWslMoveCutover(testState.dir, cutover('move-1', 'destination-committed')) const store = createStore() diff --git a/src/main/repo-git-remote-identity.test.ts b/src/main/repo-git-remote-identity.test.ts index acb157ebd75..a07cf729ce1 100644 --- a/src/main/repo-git-remote-identity.test.ts +++ b/src/main/repo-git-remote-identity.test.ts @@ -25,14 +25,6 @@ describe('probeGitRemoteIdentity', () => { }) }) - it('settles on no-remote when git answers with nothing usable', async () => { - vi.mocked(gitExecFileAsync).mockResolvedValue({ stdout: '', stderr: '' }) - - await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({ - status: 'no-remote' - }) - }) - it('reports unavailable for an SSH host', async () => { await expect(probeGitRemoteIdentity('/repos/orca', 'ssh:builder')).resolves.toEqual({ status: 'unavailable' @@ -46,50 +38,4 @@ describe('probeGitRemoteIdentity', () => { }) expect(gitExecFileAsync).not.toHaveBeenCalled() }) - - it('reports unavailable when the local git command fails', async () => { - vi.mocked(gitExecFileAsync).mockRejectedValue(new Error('not a git repository')) - - await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({ - status: 'unavailable' - }) - }) - - it('bounds the local probe with a deadline and forwards the caller signal', async () => { - vi.mocked(gitExecFileAsync).mockResolvedValue({ stdout: gitlabRemote, stderr: '' }) - const controller = new AbortController() - - await probeGitRemoteIdentity('/repos/orca', 'local', { signal: controller.signal }) - - expect(gitExecFileAsync).toHaveBeenCalledWith( - ['remote', '-v'], - expect.objectContaining({ - cwd: '/repos/orca', - timeout: expect.any(Number), - signal: controller.signal - }) - ) - const [, options] = vi.mocked(gitExecFileAsync).mock.calls[0] - expect(options.timeout).toBeGreaterThan(0) - }) - - it('maps a timed-out local probe to unavailable, never no-remote', async () => { - vi.mocked(gitExecFileAsync).mockRejectedValue(new Error('git timed out.')) - - await expect(probeGitRemoteIdentity('/repos/orca', 'local')).resolves.toEqual({ - status: 'unavailable' - }) - }) - - it('maps an aborted probe to unavailable, never no-remote', async () => { - const abortError = new Error('The operation was aborted') - abortError.name = 'AbortError' - vi.mocked(gitExecFileAsync).mockRejectedValue(abortError) - const controller = new AbortController() - controller.abort() - - await expect( - probeGitRemoteIdentity('/repos/orca', 'local', { signal: controller.signal }) - ).resolves.toEqual({ status: 'unavailable' }) - }) }) diff --git a/src/main/repo-maintenance-idle-gate.test.ts b/src/main/repo-maintenance-idle-gate.test.ts deleted file mode 100644 index 6bb68e111fc..00000000000 --- a/src/main/repo-maintenance-idle-gate.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const isOnBatteryPowerMock = vi.hoisted(() => vi.fn(() => false)) -const hasPendingPreparationsMock = vi.hoisted(() => vi.fn(() => false)) -const hasRemovalsInFlightMock = vi.hoisted(() => vi.fn(() => false)) -const setProbeMock = vi.hoisted(() => vi.fn()) -const disposeMock = vi.hoisted(() => vi.fn(async () => {})) -const postponeMock = vi.hoisted(() => vi.fn()) -const powerListeners = vi.hoisted(() => new Map void>()) -const appListeners = vi.hoisted(() => new Map void>()) - -vi.mock('electron', () => ({ - app: { - on: (event: string, listener: () => void) => appListeners.set(event, listener), - off: (event: string) => appListeners.delete(event) - }, - powerMonitor: { - isOnBatteryPower: isOnBatteryPowerMock, - on: (event: string, listener: () => void) => powerListeners.set(event, listener), - off: (event: string) => powerListeners.delete(event) - } -})) - -vi.mock('./worktree-create-preparation', () => ({ - hasPendingWorktreeCreatePreparations: hasPendingPreparationsMock -})) - -vi.mock('./ipc/worktrees/worktree-ipc-context', () => ({ - hasWorktreeRemovalsInFlight: hasRemovalsInFlightMock -})) - -vi.mock('./git/local-repo-ref-maintenance', () => ({ - setRepoMaintenanceActivityProbe: setProbeMock, - disposeLocalRepoRefMaintenance: disposeMock, - postponeRepoRefMaintenance: postponeMock -})) - -import { installRepoMaintenanceIdleGate } from './repo-maintenance-idle-gate' - -function installProbe( - overrides: Partial<{ isQuitting: () => boolean; getWorkingAgentCount: () => number }> = {} -): { probe: () => boolean; uninstall: () => Promise } { - const uninstall = installRepoMaintenanceIdleGate({ - isQuitting: () => false, - getWorkingAgentCount: () => 0, - ...overrides - }) - return { probe: setProbeMock.mock.calls.at(-1)?.[0] as () => boolean, uninstall } -} - -beforeEach(() => { - isOnBatteryPowerMock.mockReturnValue(false) - hasPendingPreparationsMock.mockReturnValue(false) - hasRemovalsInFlightMock.mockReturnValue(false) - postponeMock.mockClear() - powerListeners.clear() - appListeners.clear() - setProbeMock.mockClear() - disposeMock.mockClear() -}) - -afterEach(() => { - vi.restoreAllMocks() -}) - -describe('repo maintenance idle gate', () => { - it('reports idle when nothing is happening', () => { - expect(installProbe().probe()).toBe(false) - }) - - it('vetoes while an agent is working', () => { - expect(installProbe({ getWorkingAgentCount: () => 1 }).probe()).toBe(true) - }) - - it('vetoes while a worktree create is prepared or in flight', () => { - hasPendingPreparationsMock.mockReturnValue(true) - - expect(installProbe().probe()).toBe(true) - }) - - it('vetoes while a worktree removal is deleting refs', () => { - hasRemovalsInFlightMock.mockReturnValue(true) - - expect(installProbe().probe()).toBe(true) - }) - - it('vetoes on battery power', () => { - isOnBatteryPowerMock.mockReturnValue(true) - - expect(installProbe().probe()).toBe(true) - }) - - it('vetoes during shutdown', () => { - expect(installProbe({ isQuitting: () => true }).probe()).toBe(true) - }) - - it('treats an unavailable power API as not-on-battery', () => { - isOnBatteryPowerMock.mockImplementation(() => { - throw new Error('unsupported') - }) - - expect(installProbe().probe()).toBe(false) - }) - - it('pushes the next attempt out when the machine drops onto battery', () => { - installProbe() - - powerListeners.get('on-battery')?.() - - expect(postponeMock).toHaveBeenCalledTimes(1) - }) - - it('pushes the next attempt out when the user comes back to the window', () => { - // A window left focused while the user is away fires no new focus event. - installProbe() - - appListeners.get('browser-window-focus')?.() - - expect(postponeMock).toHaveBeenCalledTimes(1) - }) - - it('cancels armed timers, unsubscribes both sources, and clears the probe when uninstalled', async () => { - await installProbe().uninstall() - - expect(disposeMock).toHaveBeenCalledTimes(1) - expect(powerListeners.has('on-battery')).toBe(false) - expect(appListeners.has('browser-window-focus')).toBe(false) - expect(setProbeMock).toHaveBeenLastCalledWith(null) - }) -}) diff --git a/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts b/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts deleted file mode 100644 index 80849633c27..00000000000 --- a/src/main/runtime/mobile-session-tabs-notify-coalescer.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createMobileSessionTabsNotifyCoalescer } from './mobile-session-tabs-notify-coalescer' - -describe('createMobileSessionTabsNotifyCoalescer', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - vi.useRealTimers() - }) - - it('coalesces a rapid burst of title/status flips into one trailing emit (repro)', () => { - // Title spinners generate bursts; publish only the latest state after the trailing window. - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - const FLIPS = 20 - for (let i = 0; i < FLIPS; i++) { - coalescer.schedule('worktree-1') - vi.advanceTimersByTime(10) - } - expect(emit).not.toHaveBeenCalled() - - vi.advanceTimersByTime(50) - - expect(emit).toHaveBeenCalledTimes(1) - expect(emit).toHaveBeenCalledWith('worktree-1') - }) - - it('force-flushes under sustained churn so the emit is never starved', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - // Sustained churn must still publish within the 250ms cap. - for (let i = 0; i < 100; i++) { - coalescer.schedule('worktree-1') - vi.advanceTimersByTime(30) - } - - expect(emit).toHaveBeenCalled() - expect(emit).toHaveBeenCalledWith('worktree-1') - }) - - it('keeps per-worktree windows independent', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.schedule('worktree-1') - coalescer.schedule('worktree-2') - vi.advanceTimersByTime(50) - - expect(emit).toHaveBeenCalledTimes(2) - expect(emit).toHaveBeenCalledWith('worktree-1') - expect(emit).toHaveBeenCalledWith('worktree-2') - }) - - it('cancel() drops a pending notify so a structural emit can supersede it', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.schedule('worktree-1') - // Structural changes emit immediately elsewhere and cancel trailing notifications. - coalescer.cancel('worktree-1') - vi.advanceTimersByTime(50) - - expect(emit).not.toHaveBeenCalled() - }) - - it('flush() emits the pending notify immediately', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.schedule('worktree-1') - coalescer.flush('worktree-1') - - expect(emit).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(50) - expect(emit).toHaveBeenCalledTimes(1) - }) - - it('flush() is a no-op when nothing is pending', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.flush('worktree-1') - - expect(emit).not.toHaveBeenCalled() - }) - - it('flushAll() drains every pending worktree (subscription close)', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.schedule('worktree-1') - coalescer.schedule('worktree-2') - coalescer.flushAll() - - expect(emit).toHaveBeenCalledTimes(2) - vi.advanceTimersByTime(50) - expect(emit).toHaveBeenCalledTimes(2) - }) - - it('dispose() drops pending timers without emitting', () => { - const emit = vi.fn() - const coalescer = createMobileSessionTabsNotifyCoalescer(emit) - - coalescer.schedule('worktree-1') - coalescer.dispose() - vi.advanceTimersByTime(50) - - expect(emit).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/pty-shell-ownership-mirror.test.ts b/src/main/runtime/pty-shell-ownership-mirror.test.ts index af3e28d535c..6a13ed71f5d 100644 --- a/src/main/runtime/pty-shell-ownership-mirror.test.ts +++ b/src/main/runtime/pty-shell-ownership-mirror.test.ts @@ -2,19 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { PtyShellOwnershipMirror } from './pty-shell-ownership-mirror' describe('PtyShellOwnershipMirror', () => { - it('arms the recovery trigger from a seeded alternate-screen state', async () => { - const confirm = vi.fn(async () => true) - const mirror = new PtyShellOwnershipMirror(confirm) - - // Restored bytes bypass scan; seed alternate-screen state so later TUI death can prove shell ownership. - mirror.seedOwner(undefined, { alternateScreen: true }) - mirror.scan('\x1b]133;D;137\x07') - - await vi.waitFor(() => expect(confirm).toHaveBeenCalledTimes(1)) - await mirror.settle() - expect(mirror.owner).toBe('shell') - }) - it('asks at the real D after refuted stray Ds, in lockstep with the host barrier', async () => { let hostGrounded = false const confirm = vi.fn(async () => hostGrounded) @@ -53,17 +40,6 @@ describe('PtyShellOwnershipMirror', () => { expect(mirror.owner).toBeUndefined() }) - it('bounds settle() when a proof hangs', async () => { - const mirror = new PtyShellOwnershipMirror(() => new Promise(() => {})) - mirror.seedOwner(undefined, { alternateScreen: true }) - mirror.scan('\x1b]133;D;137\x07') - - const start = Date.now() - await mirror.settle() - expect(Date.now() - start).toBeLessThan(2000) - expect(mirror.owner).toBeUndefined() - }) - it('retires a hung confirmation so a later candidate can still prove ownership', async () => { let calls = 0 const mirror = new PtyShellOwnershipMirror(() => { diff --git a/src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts b/src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts deleted file mode 100644 index 3ee818565d3..00000000000 --- a/src/main/runtime/rpc/methods/agent-launch-terminal-preferences.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** Forward sessionOptions to both terminal paths so the user's model/effort/mode override configured args as on structured chat. */ - -import { describe, expect, it, vi } from 'vitest' -import type { RpcContext } from '../core' -import { - CAPABLE_CLIENT, - STRUCTURED_PREFERENCE, - methodNamed, - rpcContext, - runtimeStub, - type AgentLaunchRuntimeStub as RuntimeStub -} from './agent-launch.test-fixture' - -vi.mock('./structured-agent-session-create', () => ({ - createStructuredAgentSessionForWorktree: async () => ({ - ok: true, - value: { sessionId: 'sess-1' } - }) -})) - -const { AGENT_LAUNCH_METHODS } = await import('./agent-launch') -const AGENT_LAUNCH = methodNamed(AGENT_LAUNCH_METHODS, 'agent.launch') - -const TERMINAL_ONLY = {} -const EXISTING_LAUNCH = { agent: 'claude', target: { kind: 'existing', worktree: 'id:wt-7' } } -const CREATE_LAUNCH = { - agent: 'claude', - target: { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'task' } } -} -const PICKS = { model: 'opus', effort: 'high' } - -async function launch(params: unknown, runtime: RuntimeStub, context: Partial = {}) { - const parsed = AGENT_LAUNCH.params.safeParse(params) - if (!parsed.success) { - throw new Error(parsed.error.issues[0]?.message ?? 'invalid') - } - return AGENT_LAUNCH.handler(parsed.data, rpcContext(runtime, { ...CAPABLE_CLIENT, ...context })) -} - -function terminalOptions(runtime: RuntimeStub): Record { - return runtime.createTerminal.mock.calls[0]?.[1] ?? {} -} - -function createArgs(runtime: RuntimeStub): Record { - return runtime.createManagedWorktree.mock.calls[0]?.[0] ?? {} -} - -describe('a terminal launch into an existing workspace', () => { - it('starts the agent with the picks the launch carried', async () => { - const runtime = runtimeStub({ settings: TERMINAL_ONLY }) - - await launch({ ...EXISTING_LAUNCH, sessionOptions: PICKS }, runtime) - - expect(terminalOptions(runtime)).toMatchObject({ launchPreferences: PICKS }) - }) - - it('adds no preferences when the launch carried none', async () => { - const runtime = runtimeStub({ settings: TERMINAL_ONLY }) - - await launch(EXISTING_LAUNCH, runtime) - - expect(terminalOptions(runtime)).not.toHaveProperty('launchPreferences') - }) - - it('keeps the picks through a downgrade from structured to terminal', async () => { - const runtime = runtimeStub({ - settings: STRUCTURED_PREFERENCE, - createSupport: { supported: false, reason: 'wsl' } - }) - - await launch({ ...EXISTING_LAUNCH, sessionOptions: PICKS }, runtime) - - expect(terminalOptions(runtime)).toMatchObject({ launchPreferences: PICKS }) - }) - - it('drops options that are not launch preferences', async () => { - const runtime = runtimeStub({ settings: TERMINAL_ONLY }) - - await launch({ ...EXISTING_LAUNCH, sessionOptions: { permissionMode: 'plan' } }, runtime) - - expect(terminalOptions(runtime)).not.toHaveProperty('launchPreferences') - }) -}) - -describe('a terminal launch that creates its workspace', () => { - it('starts the startup agent with the picks the launch carried', async () => { - const runtime = runtimeStub({ settings: TERMINAL_ONLY }) - - await launch({ ...CREATE_LAUNCH, sessionOptions: PICKS }, runtime) - - expect(createArgs(runtime)).toMatchObject({ startupLaunchPreferences: PICKS }) - }) - - it('sends no startup preferences when the launch carried none', async () => { - const runtime = runtimeStub({ settings: TERMINAL_ONLY }) - - await launch(CREATE_LAUNCH, runtime) - - expect(createArgs(runtime)).not.toHaveProperty('startupLaunchPreferences') - }) - - it('sends no startup preferences when the workspace gets a chat instead', async () => { - // The chat reads the same picks from its own create; a startup terminal is not created at all. - const runtime = runtimeStub({ settings: STRUCTURED_PREFERENCE }) - - await launch({ ...CREATE_LAUNCH, sessionOptions: PICKS }, runtime) - - expect(createArgs(runtime)).not.toHaveProperty('startupLaunchPreferences') - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts deleted file mode 100644 index f1992eb9b9c..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { RuntimeTerminalPromptDelivery } from '../../../../../../shared/runtime-terminal-contracts' -import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { observeWorkerTurnStart } from './worker-start-turn-observation' - -function delivery( - overrides: Partial = {} -): RuntimeTerminalPromptDelivery { - return { - requestId: 'req-1', - stages: ['input_accepted'], - provider: 'codex', - observation: 'supported', - processIncarnation: 'inc-1', - generation: 1, - baselineWorkingSequence: 0, - ...overrides - } -} - -function runtimeObserving(result: RuntimeTerminalPromptDelivery): { - runtime: OrcaRuntimeService - observe: ReturnType -} { - const observe = vi.fn().mockResolvedValue(result) - return { - runtime: { observeTerminalAgentPrompt: observe } as unknown as OrcaRuntimeService, - observe - } -} - -describe('observeWorkerTurnStart', () => { - it('treats a missing receipt as unsupported observation, never as failure', async () => { - const { runtime, observe } = runtimeObserving(delivery()) - await expect( - observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt: undefined }) - ).resolves.toEqual({ verdict: 'unsupported' }) - expect(observe).not.toHaveBeenCalled() - }) - - it('accepts a first-stage turn_started without a second observation pass', async () => { - const prompt = delivery({ stages: ['input_accepted', 'turn_started'] }) - const { runtime, observe } = runtimeObserving(prompt) - await expect( - observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt }) - ).resolves.toEqual({ verdict: 'observed', prompt }) - expect(observe).not.toHaveBeenCalled() - }) - - it('reports observed when the second-stage observer sees the turn start', async () => { - const observed = delivery({ stages: ['input_accepted', 'turn_started'] }) - const { runtime, observe } = runtimeObserving(observed) - await expect( - observeWorkerTurnStart({ - runtime, - terminalHandle: 'term_w', - prompt: delivery(), - timeoutMs: 5 - }) - ).resolves.toEqual({ verdict: 'observed', prompt: observed }) - expect(observe).toHaveBeenCalledWith('term_w', delivery(), 5) - }) - - it('reports unobserved — not dead — when a supported observation stalls', async () => { - const { runtime } = runtimeObserving(delivery()) - await expect( - observeWorkerTurnStart({ - runtime, - terminalHandle: 'term_w', - prompt: delivery(), - timeoutMs: 5 - }) - ).resolves.toMatchObject({ verdict: 'unobserved' }) - }) - - it('reports permission as positive liveness', async () => { - const observed = delivery({ observation: 'permission' }) - const { runtime } = runtimeObserving(observed) - await expect( - observeWorkerTurnStart({ - runtime, - terminalHandle: 'term_w', - prompt: delivery(), - timeoutMs: 5 - }) - ).resolves.toEqual({ verdict: 'permission', prompt: observed }) - }) - - it('treats a replaced incarnation as unobserved rather than unsupported', async () => { - const observed = delivery({ observation: 'incarnation_replaced' }) - const { runtime } = runtimeObserving(observed) - await expect( - observeWorkerTurnStart({ - runtime, - terminalHandle: 'term_w', - prompt: delivery(), - timeoutMs: 5 - }) - ).resolves.toEqual({ verdict: 'unobserved', prompt: observed }) - }) - - it('leaves an unsupported provider on the accepted receipt', async () => { - const prompt = delivery({ provider: 'unsupported', observation: 'unsupported' }) - const { runtime, observe } = runtimeObserving(prompt) - await expect( - observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt }) - ).resolves.toEqual({ verdict: 'unsupported', prompt }) - expect(observe).not.toHaveBeenCalled() - }) - - it('preserves uncertainty when observation loses the terminal binding', async () => { - const prompt = delivery() - const { runtime, observe } = runtimeObserving(prompt) - observe.mockRejectedValue(new Error('terminal_handle_stale')) - await expect( - observeWorkerTurnStart({ runtime, terminalHandle: 'term_w', prompt }) - ).resolves.toEqual({ verdict: 'unobserved', prompt }) - expect(observe).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts b/src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts index 0305aa7cb2a..9601b557d56 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-snapshot-scrollback-rows.test.ts @@ -1,9 +1,8 @@ import { describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../../orca-runtime' import { MOBILE_SNAPSHOT_BYTE_BUDGET } from '../../../scrollback-limits' -import { buildSnapshotFrameMeta } from './terminal-snapshot-payload' + import { serializeBudgetedMobileSnapshot } from './terminal-snapshot-publication' -import { isMovedPaneHistorySessionId } from '../../../../../shared/orcad-migration/orcad-migration-terminal-history' function historyRuntime(bytesPerRow: number): Pick { return { @@ -19,15 +18,6 @@ function historyRuntime(bytesPerRow: number): Pick { - it('serializes history for every subscriber, not a screen-only image', async () => { - const runtime = historyRuntime(10) - const serialized = await serializeBudgetedMobileSnapshot(runtime, 'pty-1') - expect(runtime.serializeTerminalBuffer).toHaveBeenCalledTimes(1) - expect(runtime.serializeTerminalBuffer).toHaveBeenCalledWith('pty-1', { scrollbackRows: 1000 }) - expect(serialized?.scrollbackRows).toBe(1000) - expect(serialized?.data).toBe(`${'h'.repeat(10_000)}SCREEN`) - }) - it('steps down the row ladder when history is over the byte budget', async () => { // 1000 rows is over 512 KiB, 500 rows is not. const bytesPerRow = Math.floor(MOBILE_SNAPSHOT_BYTE_BUDGET / 600) @@ -49,34 +39,4 @@ describe('subscribe snapshot of a WSL-moved pane', () => { (await serializeBudgetedMobileSnapshot(wide, 'pty-1', undefined, 5000))?.scrollbackRows ).toBe(1000) }) - - it('names only moved panes by their session id', () => { - expect(isMovedPaneHistorySessionId('repo::/w@@moved-0123456789abcdef')).toBe(true) - expect(isMovedPaneHistorySessionId('repo::/w@@a1b2c3d4')).toBe(false) - expect(isMovedPaneHistorySessionId('moved-0123456789abcdef')).toBe(false) - }) -}) - -describe('SnapshotStart scrollbackRows', () => { - const base = { kind: 'scrollback' as const, cols: 80, rows: 24, data: '' } - - it('publishes how many history rows the image carries, including zero', () => { - expect(buildSnapshotFrameMeta({ ...base, scrollbackRows: 1000 }).scrollbackRows).toBe(1000) - expect(buildSnapshotFrameMeta({ ...base, scrollbackRows: 0 }).scrollbackRows).toBe(0) - }) - - it('omits the field when the publisher does not know, so the client reads it as unknown', () => { - expect('scrollbackRows' in buildSnapshotFrameMeta(base)).toBe(false) - }) -}) - -describe('snapshot frame title', () => { - const base = { kind: 'scrollback' as const, cols: 80, rows: 24, data: '' } - - it("carries the image's title only with the seq that orders it", () => { - expect(buildSnapshotFrameMeta({ ...base, seq: 7, lastTitle: 'Claude' }).lastTitle).toBe( - 'Claude' - ) - expect('lastTitle' in buildSnapshotFrameMeta({ ...base, lastTitle: 'Claude' })).toBe(false) - }) }) diff --git a/src/main/runtime/rpc/terminal-agent-send-guard.test.ts b/src/main/runtime/rpc/terminal-agent-send-guard.test.ts index 602bd3dbb86..e5ff65f2d2d 100644 --- a/src/main/runtime/rpc/terminal-agent-send-guard.test.ts +++ b/src/main/runtime/rpc/terminal-agent-send-guard.test.ts @@ -31,35 +31,6 @@ describe('terminal agent send guard', () => { vi.useRealTimers() }) - it('rechecks a transient no-agent result before refusing a guarded send', async () => { - vi.useFakeTimers() - const getTerminalAgentStatus = vi - .fn() - .mockResolvedValueOnce({ handle: 'terminal-1', isRunningAgent: false, status: null }) - .mockResolvedValue({ handle: 'terminal-1', isRunningAgent: true, status: 'working' }) - const runtime = stubRuntime({ - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }), - getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }), - getTerminalAgentStatus, - sendTerminal: vi.fn().mockResolvedValue({ - handle: 'terminal-1', - accepted: true, - bytesWritten: 1 - }) - }) - const responsePromise = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }).dispatch( - guardedSendRequest() - ) - - await vi.advanceTimersByTimeAsync(150) - - await expect(responsePromise).resolves.toMatchObject({ - ok: true, - result: { send: { accepted: true, bytesWritten: 1 } } - }) - expect(getTerminalAgentStatus).toHaveBeenCalledTimes(2) - }) - it('rechecks a transient no-agent result immediately before the PTY write', async () => { vi.useFakeTimers() const getTerminalAgentStatus = vi diff --git a/src/main/runtime/runtime-folder-workspace-wsl-launch-scope.test.ts b/src/main/runtime/runtime-folder-workspace-wsl-launch-scope.test.ts index 6b5d01fd174..634ac3fd38a 100644 --- a/src/main/runtime/runtime-folder-workspace-wsl-launch-scope.test.ts +++ b/src/main/runtime/runtime-folder-workspace-wsl-launch-scope.test.ts @@ -69,33 +69,6 @@ describe('a runtime start in a folder workspace on a stopped WSL distro (E9)', ( expect(statsInUserAct).toEqual([true]) }) - it('treats a deduplicated CLI create as the user act too', async () => { - const run = vi.fn(async () => ({ handle: 'term-1' })) - await makeRuntime().dedupeTerminalCreate( - 'local', - `id:${TEST_FOLDER_WORKSPACE_KEY}`, - 'mutation-1', - false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the dedupe returns `run`'s result untouched; only the launch scope is under test. - run as never, - { wslUserAct: true } - ) - expect(statsInUserAct).toEqual([true]) - expect(run).toHaveBeenCalledOnce() - }) - - it('checks the folder as the user act for an agent-session create', async () => { - await makeRuntime() - .createAgentSession({ - clientOperationId: `${Date.now()}-0123456789abcdef0123456789abcdef`, - worktree: `id:${TEST_FOLDER_WORKSPACE_KEY}`, - agent: 'claude' - }) - // Later launch steps are out of scope; only the folder check's act is under test. - .catch(() => undefined) - expect(statsInUserAct[0]).toBe(true) - }) - it('checks the folder as the user act for a resume the user asked for', async () => { await makeRuntime().resumeAgentSessionInWorkspace(TEST_FOLDER_WORKSPACE_KEY, { agent: 'claude', @@ -106,19 +79,6 @@ describe('a runtime start in a folder workspace on a stopped WSL distro (E9)', ( expect(statsInUserAct[0]).toBe(true) }) - it('checks the folder as the user act for an explicit agent-session ensure', async () => { - await makeRuntime() - .ensureAgentSession({ - kind: 'explicit', - worktree: `id:${TEST_FOLDER_WORKSPACE_KEY}`, - agent: 'claude', - providerSession: { key: 'session_id', id: 'provider-session-1' } - }) - // Later launch steps are out of scope; only the folder check's act is under test. - .catch(() => undefined) - expect(statsInUserAct[0]).toBe(true) - }) - it('holds background work with Start, naming the distro, without touching the folder', async () => { await expect( makeRuntime().resolveTerminalWorkspaceLaunchScope(`id:${TEST_FOLDER_WORKSPACE_KEY}`) diff --git a/src/main/runtime/runtime-metadata.test.ts b/src/main/runtime/runtime-metadata.test.ts index fd4723010c3..2681c239b7c 100644 --- a/src/main/runtime/runtime-metadata.test.ts +++ b/src/main/runtime/runtime-metadata.test.ts @@ -28,55 +28,6 @@ describe('runtime metadata', () => { } }) - it('writes and reads runtime metadata atomically', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-')) - tempDirs.push(userDataPath) - - writeRuntimeMetadata(userDataPath, { - runtimeId: 'rt_123', - pid: 42, - transports: [ - { - kind: 'unix', - endpoint: '/tmp/orca.sock' - } - ], - authToken: 'secret', - startedAt: 100 - }) - - expect(readRuntimeMetadata(userDataPath)).toEqual({ - runtimeId: 'rt_123', - pid: 42, - transports: [ - { - kind: 'unix', - endpoint: '/tmp/orca.sock' - } - ], - authToken: 'secret', - startedAt: 100 - }) - }) - - it('clears the runtime metadata file', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-')) - tempDirs.push(userDataPath) - - writeRuntimeMetadata(userDataPath, { - runtimeId: 'rt_123', - pid: 42, - transports: [], - authToken: null, - startedAt: 100 - }) - - clearRuntimeMetadata(userDataPath) - - expect(readRuntimeMetadata(userDataPath)).toBeNull() - expect(getRuntimeMetadataPath(userDataPath)).toContain('orca-runtime.json') - }) - describe('clearRuntimeMetadataIfOwned', () => { it('clears metadata when pid and runtimeId both match', () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-')) @@ -132,14 +83,6 @@ describe('runtime metadata', () => { runtimeId: 'rt_replacement' }) }) - - it('is a no-op when no metadata exists', () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-metadata-')) - tempDirs.push(userDataPath) - - expect(() => clearRuntimeMetadataIfOwned(userDataPath, 42, 'rt_owner')).not.toThrow() - expect(readRuntimeMetadata(userDataPath)).toBeNull() - }) }) it.runIf(process.platform !== 'win32')( diff --git a/src/main/runtime/runtime-visible-catalog.test.ts b/src/main/runtime/runtime-visible-catalog.test.ts index fe8b2123279..2460913bfc4 100644 --- a/src/main/runtime/runtime-visible-catalog.test.ts +++ b/src/main/runtime/runtime-visible-catalog.test.ts @@ -11,8 +11,7 @@ vi.mock('../ssh/orcad-retained-source', () => ({ visibleFolderWorkspaces: vi.fn(() => []) })) -const { runtimeHiddenHostIds, runtimeHiddenRepos, runtimeVisibleRepos } = - await import('./runtime-visible-catalog') +const { runtimeHiddenHostIds, runtimeHiddenRepos } = await import('./runtime-visible-catalog') const sshTarget = { id: 'target-1', label: 'dev', host: 'dev', port: 22, username: 'dev' } const repo = (id: string, connectionId?: string): Repo => ({ @@ -29,30 +28,6 @@ const storeWith = (repos: Repo[], withTargets: boolean) => ({ }) describe('runtime visible catalog', () => { - it('lists what the desktop shows and names the rest as hidden', () => { - const all = [repo('local'), repo('retained')] - visibleRepos.mockImplementation((store) => store.getRepos().filter((r) => r.id !== 'retained')) - const store = storeWith(all, true) - expect(runtimeVisibleRepos(store).map((r) => r.id)).toEqual(['local']) - expect(runtimeHiddenRepos(store).hasRepo(all[1]!)).toBe(true) - expect(runtimeHiddenRepos(store).hasRepo(all[0]!)).toBe(false) - }) - - it('treats a store with no SSH targets (headless orcad) as hiding nothing of its own', () => { - visibleRepos.mockImplementation((store) => { - expect(store.getSshTargets()).toEqual([]) - return store.getRepos() - }) - const store = storeWith([repo('a')], false) - expect(runtimeVisibleRepos(store)).toHaveLength(1) - expect(runtimeHiddenRepos(store).size).toBe(0) - }) - - it('lists nothing without a store', () => { - expect(runtimeVisibleRepos(null)).toEqual([]) - expect(runtimeHiddenRepos(null).size).toBe(0) - }) - it('hides a moved local row by host while the WSL host row with the same id stays listed', () => { const local = repo('moved') const onHost: Repo = { ...repo('moved'), executionHostId: 'runtime:wsl-ubuntu' } @@ -65,22 +40,6 @@ describe('runtime visible catalog', () => { expect(hidden.hasWorktree({ repoId: 'moved', hostId: 'runtime:wsl-ubuntu' })).toBe(false) }) - it('names a host known only through hidden rows, but never this machine', () => { - visibleRepos.mockImplementation((store) => - store.getRepos().filter((r) => r.id !== 'retained' && r.id !== 'moved-local') - ) - const store = storeWith( - [ - repo('retained', 'target-1'), - repo('moved-local'), - repo('shared-a', 'target-2'), - repo('shared-b', 'target-2') - ], - true - ) - expect([...runtimeHiddenHostIds(store)]).toEqual(['ssh:target-1']) - }) - it('keeps a host that still has a visible row', () => { visibleRepos.mockImplementation((store) => store.getRepos().filter((r) => r.id !== 'a')) const store = storeWith([repo('a', 'target-2'), repo('b', 'target-2')], true) diff --git a/src/main/runtime/structured-chat-worker-start.test.ts b/src/main/runtime/structured-chat-worker-start.test.ts index d2cfb89cdce..ea0f384726c 100644 --- a/src/main/runtime/structured-chat-worker-start.test.ts +++ b/src/main/runtime/structured-chat-worker-start.test.ts @@ -153,23 +153,6 @@ describe('worker-start --terminal names a chat', () => { expect(turnText(worker.turns[1]!)).toContain(dispatchId) }) - it("reads the start as unknown when the chat's agent has not taken the task within the wait", async () => { - await openChat(COORDINATOR) - await openChat(PEER_CHAT) - const { taskId } = await coordinatorRunAndTask() - // The settlement wait running out, as for an agent still starting. - vi.spyOn(host, 'waitForSendSettlement').mockResolvedValue(undefined) - - const receipt = await startWorker({ task: taskId }) - - expect(receipt).toMatchObject({ - state: 'outcome_unknown', - turnStart: 'unobserved', - lastError: expect.stringContaining("the chat's agent had not started to take it") - }) - expect(db.getWorkerDispatch(String(receipt.dispatchId))?.state).toBe('start_unknown') - }) - it('is stopped and abandoned without closing or interrupting the chat', async () => { await openChat(COORDINATOR) const worker = await openChat(PEER_CHAT) diff --git a/src/main/runtime/terminal/layout/pane-grid-recording.test.ts b/src/main/runtime/terminal/layout/pane-grid-recording.test.ts index 46823cd43b4..dc1a0ebe551 100644 --- a/src/main/runtime/terminal/layout/pane-grid-recording.test.ts +++ b/src/main/runtime/terminal/layout/pane-grid-recording.test.ts @@ -1,11 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { - PaneGridRecorder, - PANE_GRID_FLUSH_BUDGET_MS, - PANE_GRID_RECORD_DELAY_MS -} from './pane-grid-recording' +import { PaneGridRecorder, PANE_GRID_FLUSH_BUDGET_MS } from './pane-grid-recording' const WORKSPACE = 'repo-1::/repo' @@ -42,53 +38,6 @@ afterEach(() => { }) describe('PaneGridRecorder', () => { - it('writes one grid per resize burst, the last one, to the pane showing the terminal', async () => { - vi.useFakeTimers() - const apply = vi.fn(async () => ({ ok: true })) - const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply }) - - recorder.record('pty-1', { cols: 80, rows: 24 }) - recorder.record('pty-1', { cols: 100, rows: 30 }) - await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS - 1) - expect(apply).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(1) - - expect(apply).toHaveBeenCalledTimes(1) - expect(apply).toHaveBeenCalledWith({ - type: 'setPaneGrid', - workspace: WORKSPACE, - tabId: 'tab-1', - leafId: 'leaf-1', - grid: { cols: 100, rows: 30 } - }) - }) - - it('writes nothing for a terminal no pane shows, or an unmeasured grid', async () => { - vi.useFakeTimers() - const apply = vi.fn(async () => ({ ok: true })) - const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply }) - - recorder.record('pty-other', { cols: 80, rows: 24 }) - recorder.record('pty-1', { cols: 0, rows: 0 }) - await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS) - - expect(apply).not.toHaveBeenCalled() - }) - - it('writes a waiting grid at once on flush, and has nothing to flush after', async () => { - vi.useFakeTimers() - const apply = vi.fn(async () => ({ ok: true })) - const recorder = new PaneGridRecorder({ sessions: () => [sessionBinding('pty-1')], apply }) - - recorder.record('pty-1', { cols: 90, rows: 20 }) - await recorder.flush() - - expect(apply).toHaveBeenCalledTimes(1) - expect(recorder.flush()).toBeNull() - await vi.advanceTimersByTimeAsync(PANE_GRID_RECORD_DELAY_MS) - expect(apply).toHaveBeenCalledTimes(1) - }) - it('lets a quit go on once its budget is spent while a grid write hangs', async () => { vi.useFakeTimers() const apply = vi.fn(() => new Promise(() => {})) diff --git a/src/main/source-control/repo-remote-head-branch.test.ts b/src/main/source-control/repo-remote-head-branch.test.ts index b5e05e9f419..ff30e4ae66d 100644 --- a/src/main/source-control/repo-remote-head-branch.test.ts +++ b/src/main/source-control/repo-remote-head-branch.test.ts @@ -42,13 +42,6 @@ describe('getRemoteHeadBranchName', () => { ) }) - it('returns null for a missing remote HEAD without resolving origin', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - await expect(getRemoteHeadBranchName('/repo', 'upstream')).resolves.toBeNull() - await expect(getRemoteHeadBranchName('/repo', 'upstream')).resolves.toBeNull() - expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) - }) - it('ignores a symbolic HEAD pointing into another remote', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: 'refs/remotes/upstream/HEAD\0refs/remotes/origin/main\n', diff --git a/src/main/speech/openai-api-key-store.test.ts b/src/main/speech/openai-api-key-store.test.ts index e632f14e37e..73dd4ff7ce0 100644 --- a/src/main/speech/openai-api-key-store.test.ts +++ b/src/main/speech/openai-api-key-store.test.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' + import { tmpdir } from 'node:os' import type * as Os from 'node:os' import { join } from 'node:path' @@ -77,20 +78,6 @@ describe('OpenAI speech API key store', () => { expect(() => store.readOpenAiSpeechApiKey()).toThrow('OpenAI API key could not be decrypted') }) - it('reports a stored key this host can decrypt as usable', async () => { - writeStoredOpenAiKey('encrypted-key') - const store = await loadStoreModule() - expect(store.canReadOpenAiSpeechApiKey()).toBe(true) - }) - - it('decrypts only when the key is read for an API request', async () => { - writeStoredOpenAiKey('encrypted-key') - const store = await loadStoreModule() - - expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key') - expect(safeStorageMock.decryptString).toHaveBeenCalledOnce() - }) - it('caches the decrypted key so repeated dictations do not repeatedly touch safeStorage', async () => { writeStoredOpenAiKey('encrypted-key') const store = await loadStoreModule() @@ -99,21 +86,4 @@ describe('OpenAI speech API key store', () => { expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key') expect(safeStorageMock.decryptString).toHaveBeenCalledOnce() }) - - it('uses the in-memory key after save without decrypting from safeStorage', async () => { - const store = await loadStoreModule() - - store.saveOpenAiSpeechApiKey('saved-key') - - expect(store.readOpenAiSpeechApiKey()).toBe('saved-key') - expect(safeStorageMock.decryptString).not.toHaveBeenCalled() - }) - - it('reports missing status without creating storage files', async () => { - const store = await loadStoreModule() - - expect(store.hasOpenAiSpeechApiKey()).toBe(false) - expect(existsSync(join(tempHome, '.orca'))).toBe(false) - expect(safeStorageMock.decryptString).not.toHaveBeenCalled() - }) }) diff --git a/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts b/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts index a17624c4867..5c07d7279e5 100644 --- a/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts +++ b/src/main/ssh/targets/ssh-target-orcad-dependents.test.ts @@ -1,124 +1,20 @@ import { describe, expect, it } from 'vitest' -import { - FLOATING_TERMINAL_WORKTREE_ID, - getDefaultWorkspaceSession -} from '../../../shared/constants' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' + import type { PersistedState } from '../../../shared/persisted-state-types' import type { Repo } from '../../../shared/repo-types' import { getAllWorktreeMetaForHost } from '../../persistence/loading-store/worktree-identity-metadata' import { normalizeWorktreeLinkedItemMetadata } from '../../persistence/tracking-repos/worktree-metadata-normalization' -import type { ExecutionHostId } from '../../../shared/execution-host' + import { collectDependentStateBlockers } from './ssh-target-orcad-dependents' import { emptyDependentStateStore } from './ssh-target-orcad-dependents-fixture' import { orcadTargetBlockerMessage } from './ssh-target-orcad-claims' -const HOST: ExecutionHostId = 'ssh:ssh-1' - function blockersFor(overrides: Parameters[0]) { return collectDependentStateBlockers(emptyDependentStateStore(overrides), 'ssh-1') } -function messageFor(overrides: Parameters[0]): string { - const [blocker] = blockersFor(overrides) - if (!blocker) { - throw new Error('expected a blocker') - } - return orcadTargetBlockerMessage('ssh-1', blocker) -} - describe('client state that still references an SSH target', () => { - it('finds nothing on an empty profile, or in an untouched session partition', () => { - expect(blockersFor({})).toEqual([]) - expect(blockersFor({ getWorkspaceSessionHostIds: () => ['local', HOST] })).toEqual([]) - }) - - it('ignores a connected host: the reconnect hint and global copies in its partition', () => { - const connected = { - ...getDefaultWorkspaceSession(), - activeConnectionIdsAtShutdown: ['ssh-1'], - activeWorktreeId: 'local-wt', - browserUrlHistory: [ - { - url: 'https://example.com', - normalizedUrl: 'https://example.com', - title: 'Example', - lastVisitedAt: 1, - visitCount: 1 - } - ] - } - expect( - blockersFor({ - getWorkspaceSessionHostIds: () => ['local', HOST], - getWorkspaceSession: () => connected - }) - ).toEqual([]) - }) - - it('blocks on the host session partition and names the fields holding state', () => { - const blockers = blockersFor({ - getWorkspaceSessionHostIds: () => ['local', HOST], - getWorkspaceSession: (hostId) => - hostId === HOST - ? { - ...getDefaultWorkspaceSession(), - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only whether the record is empty. - tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] } as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only whether the record is empty. - sleepingAgentSessionsByPaneKey: { 'tab-1:leaf': {} } as never - } - : getDefaultWorkspaceSession() - }) - expect(blockers).toEqual([ - { - code: 'orcad_migration_dependent_state', - category: 'client-owned-state', - dependencies: [ - { - kind: 'workspace-session', - count: 2, - names: ['tabsByWorktree', 'sleepingAgentSessionsByPaneKey'] - } - ] - } - ]) - }) - - it('blocks when the local session points its active workspace at the host', () => { - expect( - messageFor({ - getWorkspaceSession: () => ({ - ...getDefaultWorkspaceSession(), - activeWorkspaceExecutionHostId: HOST - }) - }) - ).toContain('workspace-session ×1 (active workspace)') - }) - - it('blocks on an automation that runs on the host, by name', () => { - const automation = { - name: 'Nightly build', - executionTargetType: 'ssh', - executionTargetId: 'ssh-1' - } - const elsewhere = { name: 'Other', executionTargetType: 'ssh', executionTargetId: 'ssh-2' } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only name and execution target. - const automations = [automation, elsewhere] as never - expect(messageFor({ listAutomations: () => automations })).toContain( - 'automation ×1 (Nightly build)' - ) - }) - - it('blocks on worktree metadata recorded for the host', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads the keys and host stamps. - const meta = { 'repo-1::/srv/app': { hostId: HOST } } as never - expect( - messageFor({ - getAllWorktreeMetaForHost: (hostId) => (hostId === HOST ? meta : {}) - }) - ).toContain('worktree-metadata ×1 (repo-1::/srv/app)') - }) - describe('profiles with unstamped metadata rows from an older build (#31498)', () => { const SETUP_TERMINAL_ID = 'ephemeral-setup-terminal:panel-1' // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only id, connectionId and executionHostId. @@ -186,29 +82,6 @@ describe('client state that still references an SSH target', () => { }) }) - it('blocks on a saved terminal lease of any status', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only ptyId and state. - const leases = [{ ptyId: 'pty-9', state: 'terminated' }] as never - expect(messageFor({ getSshRemotePtyLeases: () => leases })).toContain( - 'terminal-lease ×1 (pty-9 (terminated))' - ) - }) - - it('caps the names it reports but keeps the full count', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the census reads only ptyId and state. - const leases = Array.from({ length: 7 }, (_, i) => ({ - ptyId: `p${i}`, - state: 'expired' - })) as never - const [blocker] = blockersFor({ getSshRemotePtyLeases: () => leases }) - expect(blocker).toMatchObject({ - dependencies: [{ kind: 'terminal-lease', count: 7, names: expect.any(Array) }] - }) - expect( - blocker?.code === 'orcad_migration_dependent_state' && blocker.dependencies[0]?.names - ).toHaveLength(5) - }) - it('refuses as unverifiable when a store cannot be read, naming the store', () => { const blockers = blockersFor({ listAutomations: () => { diff --git a/src/main/startup/main-process-ready-persistence-cleanup.test.ts b/src/main/startup/main-process-ready-persistence-cleanup.test.ts index 6deac0e8d51..ee7765acb9d 100644 --- a/src/main/startup/main-process-ready-persistence-cleanup.test.ts +++ b/src/main/startup/main-process-ready-persistence-cleanup.test.ts @@ -1,8 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - createServeDesktopActivationGate, - type ServeDesktopActivationGate -} from './serve-desktop-activation' +import type { ServeDesktopActivationGate } from './serve-desktop-activation' const { state, foundation, runtime, i18n, launch } = vi.hoisted(() => ({ state: { @@ -47,32 +44,6 @@ beforeEach(() => { }) describe('startup persistence lifetime', () => { - it('disables activations before a failed launch closes its profile writer', async () => { - const activateWindow = vi.fn() - state.desktopActivationGate = createServeDesktopActivationGate({ - initialState: 'ready', - activateWindow - }) - const failure = new Error('runtime startup failed') - launch.mockRejectedValueOnce(failure) - let finishFreeze = (): void => {} - state.store.freezeWritesAsync.mockImplementationOnce( - () => - new Promise((resolve) => { - finishFreeze = resolve - }) - ) - const rejected = expect(initializeMainProcessReady(options)).rejects.toBe(failure) - - await vi.waitFor(() => expect(state.store.freezeWritesAsync).toHaveBeenCalledOnce()) - - expect(state.desktopActivationGate).toBeNull() - state.desktopActivationGate?.requestActivation() - expect(activateWindow).not.toHaveBeenCalled() - finishFreeze() - await rejected - }) - it('awaits writer release after a later startup phase fails', async () => { const failure = new Error('runtime startup failed') const admission = state.profileStateAdmission diff --git a/src/main/startup/renderer-heap-headroom.test.ts b/src/main/startup/renderer-heap-headroom.test.ts deleted file mode 100644 index f6b55f41afb..00000000000 --- a/src/main/startup/renderer-heap-headroom.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { computeRendererHeapCeilingMb } from './renderer-heap-headroom' - -vi.mock('electron', () => ({ - app: { - commandLine: { - appendSwitch: vi.fn(), - getSwitchValue: vi.fn(() => '') - } - } -})) - -afterEach(() => { - vi.restoreAllMocks() -}) - -const GIB = 1024 * 1024 * 1024 - -describe('computeRendererHeapCeilingMb', () => { - it('leaves Chromium default (null) below the ~8 GB gate to avoid OS memory pressure', () => { - expect(computeRendererHeapCeilingMb(4 * GIB)).toBeNull() - expect(computeRendererHeapCeilingMb(6 * GIB)).toBeNull() - expect(computeRendererHeapCeilingMb(7 * GIB)).toBeNull() - }) - - it('includes 8 GB machines that report below 8 GiB (Linux MemTotal excludes reserved RAM)', () => { - // Linux MemTotal omits reserved RAM; real 8GB machines can report ~7.7GiB. - expect(computeRendererHeapCeilingMb(7.7 * GIB)).toBe(3072) - expect(computeRendererHeapCeilingMb(7.5 * GIB)).toBe(3072) - }) - - it('raises the ceiling toward the 4 GB pointer-compression cage, floored and capped', () => { - expect(computeRendererHeapCeilingMb(8 * GIB)).toBe(3072) - expect(computeRendererHeapCeilingMb(12 * GIB)).toBe(4096) - expect(computeRendererHeapCeilingMb(16 * GIB)).toBe(4096) - expect(computeRendererHeapCeilingMb(128 * GIB)).toBe(4096) - }) - - it('honors a positive ORCA_RENDERER_HEAP_MB override regardless of RAM', () => { - expect(computeRendererHeapCeilingMb(4 * GIB, '5000')).toBe(5000) - expect(computeRendererHeapCeilingMb(128 * GIB, '4096')).toBe(4096) - }) - - it('opts out (null) for default/off/none/0/negative overrides', () => { - for (const value of ['default', 'off', 'none', '0', '-1']) { - expect(computeRendererHeapCeilingMb(16 * GIB, value)).toBeNull() - } - }) - - it('opts out (null) for a fractional override that would floor to 0 (never emits max-old-space-size=0)', () => { - for (const value of ['0.5', '0.9', '0.0001']) { - expect(computeRendererHeapCeilingMb(16 * GIB, value)).toBeNull() - } - }) - - it('falls through to RAM tiers for blank/invalid overrides', () => { - expect(computeRendererHeapCeilingMb(16 * GIB, '')).toBe(4096) - expect(computeRendererHeapCeilingMb(16 * GIB, 'abc')).toBe(4096) - }) - - it('returns null for a non-finite / non-positive RAM reading', () => { - expect(computeRendererHeapCeilingMb(Number.NaN)).toBeNull() - expect(computeRendererHeapCeilingMb(0)).toBeNull() - }) -}) - -describe('enableRendererHeapHeadroom', () => { - it('appends --max-old-space-size as a js-flags switch on a RAM-capable machine', async () => { - const { app } = await import('electron') - const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') - - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('') - - enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) - - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith( - 'js-flags', - '--max-old-space-size=4096' - ) - }) - - it('does not set a switch on low-RAM machines', async () => { - const { app } = await import('electron') - const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') - - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('') - - enableRendererHeapHeadroom({ totalMemoryBytes: 4 * GIB, env: {} }) - - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('js-flags', expect.anything()) - }) - - it('preserves an explicit prior --max-old-space-size instead of stacking a second value', async () => { - const { app } = await import('electron') - const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') - - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('--max-old-space-size=2048') - - enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) - - expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('js-flags', expect.anything()) - }) - - it('merges with an unrelated existing js-flags value', async () => { - const { app } = await import('electron') - const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') - - vi.mocked(app.commandLine.appendSwitch).mockClear() - vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('--no-opt') - - enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) - - expect(app.commandLine.appendSwitch).toHaveBeenCalledWith( - 'js-flags', - '--no-opt --max-old-space-size=4096' - ) - }) -}) diff --git a/src/main/updater-release-build-cache.test.ts b/src/main/updater-release-build-cache.test.ts index 8ecbb88f674..6eb0227c279 100644 --- a/src/main/updater-release-build-cache.test.ts +++ b/src/main/updater-release-build-cache.test.ts @@ -21,34 +21,6 @@ function createCache(load = vi.fn().mockResolvedValue([build('v1.4.160-hourly.20 } describe('ReleaseBuildListCache', () => { - it('serves a repeat request within the TTL without loading again', async () => { - const { cache, load } = createCache() - - await cache.list('hourly') - await cache.list('hourly') - - expect(load).toHaveBeenCalledTimes(1) - }) - - it('reloads once the TTL has passed', async () => { - const { cache, load, advance } = createCache() - - await cache.list('hourly') - advance(TTL_MS + 1) - await cache.list('hourly') - - expect(load).toHaveBeenCalledTimes(2) - }) - - it('reloads on force even inside the TTL', async () => { - const { cache, load } = createCache() - - await cache.list('hourly') - await cache.list('hourly', { force: true }) - - expect(load).toHaveBeenCalledTimes(2) - }) - it('shares one in-flight load between concurrent callers', async () => { const { cache, load } = createCache() @@ -58,16 +30,6 @@ describe('ReleaseBuildListCache', () => { expect(second).toBe(first) }) - it('keys by channel', async () => { - const { cache, load } = createCache() - - await cache.list('hourly') - await cache.list('daily') - await cache.list('hourly') - - expect(load.mock.calls).toEqual([['hourly'], ['daily']]) - }) - it('does not cache a failed load', async () => { const load = vi .fn() diff --git a/src/main/updater/serve-supervisor-install-park.test.ts b/src/main/updater/serve-supervisor-install-park.test.ts index 096d62e8c7b..a3176e75d75 100644 --- a/src/main/updater/serve-supervisor-install-park.test.ts +++ b/src/main/updater/serve-supervisor-install-park.test.ts @@ -1,4 +1,5 @@ -import { mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' + import { realpathSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -8,12 +9,12 @@ import { acksDir, bundleCoordinationDir, decideServeParkHold, - formatBundleIdentity, parkRecordPath, parseServeParkRecord, supervisorsDir, type ServeParkRecord } from '../../shared/serve-bundle-coordination' + import { commitServeSupervisorPark, parkServeSupervisorsForInstall, @@ -187,46 +188,4 @@ describe('parkServeSupervisorsForInstall', () => { await expect(commitServeSupervisorPark(async () => [CHILD + 1])).rejects.toThrow() expect((await readRecord())?.phase).toBe('unpark') }) - - it('a same-version reinstall still changes the bundle identity', async () => { - const plist = join(root, 'Orca.app', 'Contents', 'Info.plist') - await register(CHILD) - await parkServeSupervisorsForInstall( - executable, - [CHILD], - deps({ - sleep: async () => { - const record = await readRecord() - await mkdir(acksDir(dir), { recursive: true }) - await writeFile(join(acksDir(dir), ackFileName(record!.attemptId, process.pid)), '{}') - } - }) - ) - const before = (await readRecord())!.bundleBefore - await utimes(plist, new Date(), new Date(Date.now() + 5_000)) - expect(formatBundleIdentity(await stat(plist))).not.toBe(before) - }) -}) - -describe('decideServeParkHold', () => { - const record: ServeParkRecord = { - schemaVersion: 1, - attemptId: 'a', - installerPid: 1, - phase: 'park', - createdAt: 0, - parkDeadlineAt: 100, - commitDeadlineAt: null, - bundleBefore: 'b', - supervisorPids: [2] - } - - it('ends a park on unpark, deadline, or installer death', () => { - const facts = { now: 50, installerAlive: true, bundleNow: 'b' } - expect(decideServeParkHold(record, facts)).toBe('hold') - expect(decideServeParkHold({ ...record, phase: 'unpark' }, facts)).toBe('release') - expect(decideServeParkHold(record, { ...facts, now: 100 })).toBe('release') - expect(decideServeParkHold(record, { ...facts, installerAlive: false })).toBe('release') - expect(decideServeParkHold(null, facts)).toBe('release') - }) }) diff --git a/src/main/wsl-fish-history-cleanup.test.ts b/src/main/wsl-fish-history-cleanup.test.ts index f943f55c8f3..1874ff68009 100644 --- a/src/main/wsl-fish-history-cleanup.test.ts +++ b/src/main/wsl-fish-history-cleanup.test.ts @@ -18,20 +18,6 @@ afterEach(async () => { }) describe('deleteWslFishHistoryFile', () => { - it('uses direct argv and bounds a distro cleanup subprocess', async () => { - const run = vi.fn().mockResolvedValue(okResult) - - await deleteWslFishHistoryFile('Ubuntu Test', 'orca_0123456789abcdef', run, running) - - expect(run).toHaveBeenCalledWith({ - distro: 'Ubuntu Test', - loginPath: 'preferred', - program: 'fish', - args: ['--command', expect.stringContaining('orca_0123456789abcdef_history')], - timeoutMs: 5_000 - }) - }) - it('rejects an unsafe session before spawning', async () => { const run = vi.fn() @@ -58,17 +44,6 @@ describe('deleteWslFishHistoryFile', () => { await Promise.all([first, second]) }) - it('keeps distinct distros independent of each other', async () => { - const run = vi.fn().mockResolvedValue(okResult) - - await Promise.all([ - deleteWslFishHistoryFile('Ubuntu', 'orca_0123456789abcdef', run, running), - deleteWslFishHistoryFile('Debian', 'orca_0123456789abcdef', run, running) - ]) - - expect(run).toHaveBeenCalledTimes(2) - }) - it('permits a retry once a failed cleanup settles', async () => { const run = vi .fn() @@ -83,22 +58,6 @@ describe('deleteWslFishHistoryFile', () => { expect(run).toHaveBeenCalledTimes(2) }) - it('treats a non-zero exit as a failed cleanup even though the runner resolved', async () => { - const run = vi.fn().mockResolvedValue({ ...okResult, code: 1 }) - - await expect( - deleteWslFishHistoryFile('Ubuntu', 'orca_0123456789abcdef', run, running) - ).rejects.toThrow('wsl fish history cleanup failed') - }) - - it('treats a runner timeout as a failed cleanup', async () => { - const run = vi.fn().mockResolvedValue({ ...okResult, code: null, timedOut: true }) - - await expect( - deleteWslFishHistoryFile('Ubuntu', 'orca_0123456789abcdef', run, running) - ).rejects.toThrow('wsl fish history cleanup failed') - }) - it('does not spawn into a stopped distro and reports it for a later retry', async () => { const run = vi.fn().mockResolvedValue(okResult) diff --git a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.test.tsx b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.test.tsx index 1de15bb7e32..92bc589ec2d 100644 --- a/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.test.tsx +++ b/src/renderer/src/components/browser-pane/host-guest/use-browser-page-viewport-size-feedback.test.tsx @@ -1,11 +1,7 @@ // @vitest-environment happy-dom import { cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - toBrowserPageGuestViewportSize, - useBrowserPageViewportSizeFeedback, - type BrowserPageViewportSize -} from './use-browser-page-viewport-size-feedback' +import { useBrowserPageViewportSizeFeedback } from './use-browser-page-viewport-size-feedback' vi.mock('@/lib/ui-zoom', () => ({ getUIZoomFactor: () => 1 })) @@ -26,27 +22,6 @@ function resizeTo(width: number, height: number): void { observerCallbacks.at(-1)?.([entry] as unknown as ResizeObserverEntry[], {} as ResizeObserver) } -it('matches what the guest reported under UI zoom, page zoom and a 2x screen', () => { - const cases: [BrowserPageViewportSize, number, number, BrowserPageViewportSize][] = [ - [{ width: 569, height: 689 }, 1, 1, { width: 569, height: 689 }], - // 1x screen, 1.2 UI zoom: 410.83 CSS px is 493 DIP. - [{ width: 410.8333 * 1.2, height: 555.677 * 1.2 }, 1, 1.2, { width: 411, height: 556 }], - [{ width: 669, height: 689 }, 1, 0.9, { width: 743, height: 765 }], - // 2x screen: the screen scale joins the page zoom, so 90% divides by 1.8 and 125% by 2.5. - [{ width: 872, height: 895.5 }, 2, 0.9, { width: 969, height: 995 }], - [{ width: 1569, height: 1189 }, 2, 1.25, { width: 1255, height: 951 }], - // Blink adds 0.5, not 1, before dividing when zoomed in. - [{ width: 1000, height: 1610 }, 1, 1.1, { width: 909, height: 1464 }], - // The guest frame is rounded up to whole DIPs before the screen scale. - [{ width: 800.5, height: 600 }, 2, 0.5, { width: 1602, height: 1200 }], - // 2x screen at 1.2 UI zoom: a 731.9987 × 890.6771 CSS px box at 90%. - [{ width: 731.9987 * 1.2, height: 890.6771 * 1.2 }, 2, 0.9, { width: 976, height: 1188 }] - ] - for (const [hostDip, screenScale, pageZoomFactor, guest] of cases) { - expect(toBrowserPageGuestViewportSize(hostDip, screenScale, pageZoomFactor)).toEqual(guest) - } -}) - describe('useBrowserPageViewportSizeFeedback', () => { const showBrowserViewportSizeFeedback = vi.fn() const hideBrowserFeedback = vi.fn() @@ -78,14 +53,6 @@ describe('useBrowserPageViewportSizeFeedback', () => { ) } - it('reports a resize but not the initial measurement', () => { - renderFeedback(true) - resizeTo(800, 600) - expect(showBrowserViewportSizeFeedback).not.toHaveBeenCalled() - resizeTo(760, 600) - expect(showBrowserViewportSizeFeedback).toHaveBeenCalledWith({ width: 760, height: 600 }) - }) - it('announces the first resize when the opening measurement came before dom-ready', () => { let ready = false renderFeedback(true, () => { diff --git a/src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts b/src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts deleted file mode 100644 index aa001aaef1e..00000000000 --- a/src/renderer/src/components/browser-pane/navigate/browser-reload-action.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { BROWSER_GUEST_RECOVERY_ERROR_CODE } from '../host-guest/browser-page-guest-recovery' -import { - reloadBrowserPageWebview, - resolveBrowserReloadButtonLabelKind, - resolveBrowserReloadIntent -} from './browser-reload-action' - -const idle = { loading: false, loadErrorCode: null } -const loading = { loading: true, loadErrorCode: null } -const failed = { loading: false, loadErrorCode: -105 } -const guestFailed = { loading: false, loadErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE } - -describe('resolveBrowserReloadIntent', () => { - it('reloads an idle page from every trigger', () => { - expect(resolveBrowserReloadIntent('button', idle)).toBe('reload') - expect(resolveBrowserReloadIntent('reload', idle)).toBe('reload') - expect(resolveBrowserReloadIntent('hard-reload', idle)).toBe('hard-reload') - }) - - it('stops an in-flight load only from the toolbar button', () => { - expect(resolveBrowserReloadIntent('button', loading)).toBe('stop') - expect(resolveBrowserReloadIntent('reload', loading)).toBe('reload') - expect(resolveBrowserReloadIntent('hard-reload', loading)).toBe('hard-reload') - }) - - // Why: reload() on chrome-error:// only refreshes the error page — every entry point must retry the load. - it('routes a failed load to the retry path from the menu too', () => { - expect(resolveBrowserReloadIntent('button', failed)).toBe('retry-load') - expect(resolveBrowserReloadIntent('reload', failed)).toBe('retry-load') - expect(resolveBrowserReloadIntent('hard-reload', failed)).toBe('retry-load') - }) - - it('routes a guest-recovery failure to guest recovery from the menu too', () => { - expect(resolveBrowserReloadIntent('button', guestFailed)).toBe('retry-guest-recovery') - expect(resolveBrowserReloadIntent('reload', guestFailed)).toBe('retry-guest-recovery') - expect(resolveBrowserReloadIntent('hard-reload', guestFailed)).toBe('retry-guest-recovery') - }) - - it('prefers stop over retry when a failed page is already reloading', () => { - expect(resolveBrowserReloadIntent('button', { loading: true, loadErrorCode: -105 })).toBe( - 'stop' - ) - }) -}) - -describe('resolveBrowserReloadButtonLabelKind', () => { - it('names the button for what it actually does', () => { - expect(resolveBrowserReloadButtonLabelKind(idle)).toBe('reload') - expect(resolveBrowserReloadButtonLabelKind(loading)).toBe('stop') - expect(resolveBrowserReloadButtonLabelKind(failed)).toBe('retry') - expect(resolveBrowserReloadButtonLabelKind(guestFailed)).toBe('retry') - }) -}) - -describe('reloadBrowserPageWebview', () => { - function createWebview(overrides: Partial = {}): Electron.WebviewTag { - return { - getWebContentsId: vi.fn(() => 42), - reload: vi.fn(), - reloadIgnoringCache: vi.fn(), - ...overrides - } as unknown as Electron.WebviewTag - } - - it('reloads a live guest, honoring the cache flag', () => { - const webview = createWebview() - expect(reloadBrowserPageWebview(webview, { ignoreCache: false })).toBe('reloaded') - expect(webview.reload).toHaveBeenCalledTimes(1) - - expect(reloadBrowserPageWebview(webview, { ignoreCache: true })).toBe('reloaded') - expect(webview.reloadIgnoringCache).toHaveBeenCalledTimes(1) - }) - - // Why: a destroyed guest makes reload() throw uncaught (STA-3448) — callers must recreate the guest instead. - it('reports a missing guest without touching reload', () => { - const webview = createWebview({ - getWebContentsId: vi.fn(() => { - throw new Error('WebContents is destroyed') - }) - }) - expect(reloadBrowserPageWebview(webview, { ignoreCache: false })).toBe('guest-missing') - expect(webview.reload).not.toHaveBeenCalled() - }) - - it('reports a guest destroyed between the liveness probe and reload', () => { - const getWebContentsId = vi - .fn<() => number>() - .mockReturnValueOnce(42) - .mockImplementation(() => { - throw new Error('WebContents is destroyed') - }) - const webview = createWebview({ - getWebContentsId, - reload: vi.fn(() => { - throw new Error('The WebView must be attached to the DOM') - }) - }) - - expect(reloadBrowserPageWebview(webview, { ignoreCache: false })).toBe('guest-missing') - expect(getWebContentsId).toHaveBeenCalledTimes(2) - }) - - // Why: pre-dom-ready reload throws too, but a live guest is already loading — recovery must not replace it. - it('reports not-ready when a live guest rejects the reload', () => { - const webview = createWebview({ - reload: vi.fn(() => { - throw new Error('The WebView must be attached to the DOM') - }) - }) - expect(reloadBrowserPageWebview(webview, { ignoreCache: false })).toBe('not-ready') - }) -}) diff --git a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts index a5c17537d0e..edf85ba93ab 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-session.test.ts @@ -75,28 +75,6 @@ function setup(args: { show: ShowReply; switchOn?: boolean; onShow?: () => void } describe('RemoteBrowserPageSession.ensureRemotePage without a stored handle', () => { - // tabShow also wakes host-saved pages that have not started yet. - it('adopts the page the host runs under the row id instead of creating a second one', async () => { - const harness = setup({ show: 'runs' }) - - await expect(harness.ensure()).resolves.toBe('host-page-1') - - expect(harness.methods()).toEqual(['browser.tabShow']) - expect(harness.calls[0]?.params).toEqual({ worktree: 'id:wt-1', page: 'host-page-1' }) - expect(harness.tokens.remotePage).toBe('host-page-1') - expect(harness.stored()).toEqual({ environmentId: 'env-1', remotePageId: 'host-page-1' }) - }) - - it('creates a page when the host has none under the row id, closing nothing', async () => { - const harness = setup({ show: 'not-found' }) - - await expect(harness.ensure()).resolves.toBe('created-page') - - expect(harness.methods()).toEqual(['browser.tabShow', 'browser.tabCreate']) - expect(harness.closedMissing).toEqual([]) - expect(harness.stored()).toEqual({ environmentId: 'env-1', remotePageId: 'created-page' }) - }) - // A timeout or transient failure says nothing about the page; creating would duplicate a live one. it('surfaces any other probe failure without creating a page', async () => { const harness = setup({ show: 'other-error' }) @@ -119,12 +97,4 @@ describe('RemoteBrowserPageSession.ensureRemotePage without a stored handle', () expect(harness.stored()).toBeNull() expect(harness.tokens.remotePage).toBeNull() }) - - it('keeps creating directly with the layout-owner switch off', async () => { - const harness = setup({ show: 'runs', switchOn: false }) - - await expect(harness.ensure()).resolves.toBe('created-page') - - expect(harness.methods()).toEqual(['browser.tabCreate']) - }) }) diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-stream-activation.test.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-stream-activation.test.ts index 5957a20deac..1a2838ffa6b 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-stream-activation.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-stream-activation.test.ts @@ -70,38 +70,6 @@ describe('useRemoteBrowserStreamActivation', () => { expect(harness.open).toHaveBeenCalledTimes(2) }) - it('does not reconnect during a quick hide and show', async () => { - const harness = renderActivation() - - await act(async () => setDocumentVisibility('hidden')) - await act(async () => vi.advanceTimersByTime(WINDOW_STREAM_PARK_DELAY_MS - 1)) - await act(async () => setDocumentVisibility('visible')) - await act(async () => vi.advanceTimersByTime(WINDOW_STREAM_PARK_DELAY_MS)) - - expect(harness.closeStream).not.toHaveBeenCalled() - expect(harness.open).toHaveBeenCalledTimes(1) - }) - - it('does not open while mounted hidden', async () => { - setDocumentVisibility('hidden') - const harness = renderActivation() - expect(harness.open).not.toHaveBeenCalled() - - await act(async () => setDocumentVisibility('visible')) - expect(harness.open).toHaveBeenCalledTimes(1) - }) - - it('parks immediately when its pane becomes inactive', async () => { - const harness = renderActivation() - - await act(async () => harness.rerender({ active: false, staged: false })) - expect(harness.closeStream).toHaveBeenCalledTimes(1) - expect(harness.clearPendingRemoteWheel).toHaveBeenCalledTimes(1) - - await act(async () => harness.rerender({ active: true, staged: false })) - expect(harness.open).toHaveBeenCalledTimes(2) - }) - // Opening a staged page would race its pending create and could close the optimistic tab on failure. it('does not open a stream for an optimistically staged page', async () => { const harness = renderActivation(true, true) diff --git a/src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx b/src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx deleted file mode 100644 index c500bb16be2..00000000000 --- a/src/renderer/src/components/editor/MarkdownPreview.image-access.test.tsx +++ /dev/null @@ -1,127 +0,0 @@ -// @vitest-environment happy-dom -// -// Render real image access to verify it stays scoped to the document’s roots or folder. - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const useLocalImageSrcSpy = vi.hoisted(() => vi.fn((src?: string, ..._context: unknown[]) => src)) - -const storeState = { - openFile: vi.fn(), - activateMarkdownLink: vi.fn(), - openMarkdownPreview: vi.fn(), - setMarkdownViewMode: vi.fn(), - markdownFrontmatterVisible: {}, - setPendingEditorReveal: vi.fn(), - addDiffComment: vi.fn(), - deleteDiffComment: vi.fn(), - updateDiffComment: vi.fn(), - clearDeliveredDiffComments: vi.fn(), - keybindings: {}, - worktreesByRepo: {}, - repos: [], - folderWorkspaces: [], - projectGroups: [], - openFiles: [], - activeFileIdByWorktree: {}, - settings: { openLinksInApp: true }, - editorFontZoomLevel: 0 -} - -vi.mock('@/store', () => { - const useAppStore = Object.assign( - (selector: (s: typeof storeState) => unknown) => selector(storeState), - { getState: () => storeState } - ) - return { useAppStore } -}) -vi.mock('@/store/slices/worktree-helpers', () => ({ findWorktreeById: () => null })) -vi.mock('@/lib/file-owner-runtime-target', () => { - const getRuntimeTargetForFileOwner = ( - _state: unknown, - _worktreeId: string | null | undefined, - owner: string | null | undefined - ) => (owner ? { kind: 'environment' as const, environmentId: owner } : { kind: 'local' as const }) - return { - FILE_OWNER_UNRESOLVED_MESSAGE: 'unresolved', - getRuntimeTargetForFileOwner, - requireRuntimeTargetForFileOwner: getRuntimeTargetForFileOwner, - getRuntimeTargetForWorktreeOwner: (state: unknown, worktreeId: string | null | undefined) => - getRuntimeTargetForFileOwner(state, worktreeId, undefined) - } -}) -vi.mock('@/runtime/use-worktree-runtime-target', () => ({ - useFileOwnerRuntimeTarget: (_worktreeId: unknown, runtimeEnvironmentId?: string | null) => - runtimeEnvironmentId - ? { kind: 'environment', environmentId: runtimeEnvironmentId } - : { kind: 'local' } -})) -vi.mock('@/runtime/runtime-file-metadata-client', () => ({ - statRuntimePath: vi.fn(async () => ({ isDirectory: false })) -})) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => null })) -vi.mock('@/lib/connection-owner-resolution', () => ({ - createConnectionIdForFileSelector: () => () => null -})) -vi.mock('@/i18n/i18n', () => ({ - i18n: { language: 'en' }, - translate: (_key: string, fallback: string) => fallback -})) -vi.mock('./useLocalImageSrc', () => ({ useLocalImageSrc: useLocalImageSrcSpy })) -vi.mock('./markdown-preview-local-images', () => ({ - prewarmMarkdownPreviewLocalImages: () => ({ cancel: () => {}, done: Promise.resolve() }) -})) -vi.mock('./MermaidBlock', () => ({ default: () => null })) -vi.mock('./CodeBlockCopyButton', () => ({ - default: ({ children }: { children: React.ReactNode }) => children -})) -vi.mock('../diff-comments/DiffCommentCard', () => ({ DiffCommentCard: () => null })) -vi.mock('./NotesSendMenu', () => ({ NotesSendMenu: () => null })) -vi.mock('./MarkdownTableOfContentsPanel', () => ({ MarkdownTableOfContentsPanel: () => null })) - -import MarkdownPreview from './MarkdownPreview' - -describe('MarkdownPreview images', () => { - let container: HTMLDivElement - let root: Root - - beforeEach(() => { - vi.stubGlobal('api', { - shell: { openUrl: vi.fn(), openFileUri: vi.fn(), pathExists: vi.fn(async () => true) }, - ui: { writeClipboardText: vi.fn(async () => true) } - }) - useLocalImageSrcSpy.mockClear() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - vi.unstubAllGlobals() - }) - - it('reads each image as a resource of the document showing it', () => { - act(() => { - root.render( - - ) - }) - - expect(useLocalImageSrcSpy.mock.calls[0]?.[0]).toBe('./logo.png') - expect(useLocalImageSrcSpy.mock.calls[0]?.[4]).toEqual({ - kind: 'document-resource', - documentPath: '/notes/readme.md' - }) - }) -}) diff --git a/src/renderer/src/components/editor/editor-clean-tab-draft-invariant.test.ts b/src/renderer/src/components/editor/editor-clean-tab-draft-invariant.test.ts index 1b1c93b7076..50ae0323c2e 100644 --- a/src/renderer/src/components/editor/editor-clean-tab-draft-invariant.test.ts +++ b/src/renderer/src/components/editor/editor-clean-tab-draft-invariant.test.ts @@ -5,7 +5,7 @@ import { requestEditorFileSave } from './editor-autosave' import { __clearSelfWriteRegistryForTests } from './editor-self-write-registry' import { createEditorStore } from './editor-autosave-controller-test-fixture' import { reloadTabContentFromDisk } from './ExternalFileChangeBanner' -import { mayPushTabTextIntoModel } from './editor-stale-mount-guard' + import { stampCleanTabDiskBaseline } from './editor-clean-tab-disk-baseline' import { getDiskBaselineSignature } from '../../../../shared/disk-baseline-signature' import { GUARDED_PATH, stubGuardedDisk } from './editor-save-guarded-disk-fixture' @@ -52,22 +52,6 @@ afterEach(() => { __clearSelfWriteRegistryForTests() }) -it('undo back to the disk text drops the draft', () => { - const { store, id } = openCleanTab('disk') - store.getState().setEditorDraft(id, 'disk typed') - store.getState().markFileDirty(id, true) - store.getState().setEditorDraft(id, 'disk') - store.getState().markFileDirty(id, false) - expectNoCleanDraft(store) -}) - -it('a clean tab that gets a draft of the disk text drops it when marked clean again', () => { - const { store, id } = openCleanTab('disk') - store.getState().setEditorDraft(id, 'disk') - store.getState().markFileDirty(id, false) - expectNoCleanDraft(store) -}) - it('save completion leaves no draft on the now-clean tab', async () => { const { store, id } = openCleanTab('disk') store.getState().setEditorDraft(id, 'saved text') @@ -89,15 +73,6 @@ it('reload leaves no draft', () => { expectNoCleanDraft(store) }) -it("lets a clean record's draft reach its model, since every view shares that draft", () => { - const { store, id } = openCleanTab('disk') - // A Markdown-whitespace draft may stay on a clean tab; it is the record's text, so views show it. - store.setState({ editorDrafts: { ...store.getState().editorDrafts, [id]: 'disk ' } }) - expect(mayPushTabTextIntoModel(id)).toBe(true) - store.getState().markFileDirty(id, true) - expect(mayPushTabTextIntoModel(id)).toBe(true) -}) - it("a reload keeps a clean Markdown tab's trailing-whitespace draft, but not one over older text", () => { const { store, id } = openCleanTab('# notes', 'markdown') store.getState().setEditorDraft(id, '# notes\n\n') diff --git a/src/renderer/src/components/editor/editor-dropped-file-open.test.ts b/src/renderer/src/components/editor/editor-dropped-file-open.test.ts index 40d86a4a0d5..8ac296b36e8 100644 --- a/src/renderer/src/components/editor/editor-dropped-file-open.test.ts +++ b/src/renderer/src/components/editor/editor-dropped-file-open.test.ts @@ -1,25 +1,9 @@ import { describe, expect, it, afterEach, vi } from 'vitest' -import { - getEditorFileDropOperationContext, - shouldUploadRemoteEditorFileDrop -} from './editor-dropped-file-open' +import { getEditorFileDropOperationContext } from './editor-dropped-file-open' + import { getRuntimeTargetForWorktreeOwner } from '@/lib/file-owner-runtime-target' describe('shouldUploadRemoteEditorFileDrop', () => { - it('does not upload editor drops for local workspaces', () => { - expect(shouldUploadRemoteEditorFileDrop({ kind: 'local' }, null)).toBe(false) - }) - - it('uploads editor drops while a runtime environment is active', () => { - expect( - shouldUploadRemoteEditorFileDrop({ kind: 'environment', environmentId: 'env-1' }, null) - ).toBe(true) - }) - - it('uploads editor drops for SSH workspaces', () => { - expect(shouldUploadRemoteEditorFileDrop({ kind: 'local' }, 'ssh-1')).toBe(true) - }) - it('uses the worktree owner runtime instead of the focused runtime', () => { expect( getRuntimeTargetForWorktreeOwner( @@ -33,19 +17,6 @@ describe('shouldUploadRemoteEditorFileDrop', () => { ).toEqual({ kind: 'environment', environmentId: 'owner-runtime' }) }) - it('keeps explicit local worktree editor drops local while a runtime is focused', () => { - expect( - getRuntimeTargetForWorktreeOwner( - { - settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, - repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }], - worktreesByRepo: { 'repo-1': [{ id: 'wt-1', repoId: 'repo-1' }] } - }, - 'wt-1' - ) - ).toEqual({ kind: 'local' }) - }) - it('builds file operation context from the worktree owner instead of global focus', () => { expect( getEditorFileDropOperationContext( diff --git a/src/renderer/src/components/editor/markdown-preview-row-measurements.test.ts b/src/renderer/src/components/editor/markdown-preview-row-measurements.test.ts index 2dc2a4d3e91..b2e1c599ef3 100644 --- a/src/renderer/src/components/editor/markdown-preview-row-measurements.test.ts +++ b/src/renderer/src/components/editor/markdown-preview-row-measurements.test.ts @@ -47,18 +47,6 @@ describe('large preview loaded-row measurements', () => { expect(virtualizer.getVirtualItems().map((row) => row.size)).toEqual([94, 56]) }) - it('preserves unchanged actual heights after resetting stale measurement slots', () => { - const virtualizer = createVirtualizer() - virtualizer.getVirtualItems() - virtualizer.resizeItem(0, 94) - expect(virtualizer.getVirtualItems().map((row) => row.size)).toEqual([94, 56, 56]) - const body = document.createElement('div') - loadedRow(body, 0, 94) - refreshMarkdownPreviewRowMeasurements(virtualizer, body, true) - expect(virtualizer.getVirtualItems().map((row) => row.size)).toEqual([94, 56, 56]) - expect(virtualizer.itemSizeCache.get(0)).toBe(94) - }) - it('refreshes new content during scrolling while retaining other measured rows', () => { const virtualizer = createVirtualizer() virtualizer.getVirtualItems() diff --git a/src/renderer/src/components/editor/monaco-find-widget.test.ts b/src/renderer/src/components/editor/monaco-find-widget.test.ts deleted file mode 100644 index 6e64645c159..00000000000 --- a/src/renderer/src/components/editor/monaco-find-widget.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -// @vitest-environment happy-dom -import { describe, expect, it, vi } from 'vitest' -import { - closeMonacoFindWidget, - closeUnfocusedMonacoFindOrPreventDialogDismiss, - isMonacoFindWidgetOpen -} from './monaco-find-widget' - -function appendFindWidget( - root: ParentNode, - args: { hidden?: boolean; withCloseButton?: boolean } = {} -): { closeButton: HTMLButtonElement | null; widget: HTMLDivElement } { - const widget = document.createElement('div') - widget.className = 'find-widget visible' - if (args.hidden) { - widget.setAttribute('aria-hidden', 'true') - } - let closeButton: HTMLButtonElement | null = null - if (args.withCloseButton) { - closeButton = document.createElement('button') - closeButton.className = 'button codicon-widget-close' - widget.append(closeButton) - } - root.append(widget) - return { closeButton, widget } -} - -describe('isMonacoFindWidgetOpen', () => { - it('is closed when the widget is missing or aria-hidden', () => { - const root = document.createElement('div') - expect(isMonacoFindWidgetOpen(null)).toBe(false) - expect(isMonacoFindWidgetOpen(root)).toBe(false) - - appendFindWidget(root, { hidden: true }) - expect(isMonacoFindWidgetOpen(root)).toBe(false) - }) - - it('is open when the find widget is present and not hidden', () => { - const root = document.createElement('div') - appendFindWidget(root) - expect(isMonacoFindWidgetOpen(root)).toBe(true) - }) - - it('does not treat a find widget outside the given root as open', () => { - const dialog = document.createElement('div') - const editorRoot = document.createElement('div') - const backgroundEditor = document.createElement('div') - dialog.append(editorRoot) - document.body.append(dialog, backgroundEditor) - appendFindWidget(backgroundEditor) - expect(isMonacoFindWidgetOpen(editorRoot)).toBe(false) - expect(isMonacoFindWidgetOpen(document)).toBe(true) - dialog.remove() - backgroundEditor.remove() - }) -}) - -describe('closeMonacoFindWidget', () => { - it('clicks the close control on an open widget', () => { - const root = document.createElement('div') - const { closeButton } = appendFindWidget(root, { withCloseButton: true }) - const onClick = vi.fn() - closeButton?.addEventListener('click', onClick) - - expect(closeMonacoFindWidget(root)).toBe(true) - expect(onClick).toHaveBeenCalledTimes(1) - }) - - it('does nothing when find is closed or the close control is missing', () => { - const root = document.createElement('div') - expect(closeMonacoFindWidget(root)).toBe(false) - - appendFindWidget(root, { hidden: true, withCloseButton: true }) - expect(closeMonacoFindWidget(root)).toBe(false) - - const openRoot = document.createElement('div') - appendFindWidget(openRoot) - expect(closeMonacoFindWidget(openRoot)).toBe(false) - }) -}) - -describe('closeUnfocusedMonacoFindOrPreventDialogDismiss', () => { - it('holds the dialog when find is open and the host is focused', () => { - const root = document.createElement('div') - const { closeButton } = appendFindWidget(root, { withCloseButton: true }) - const findInput = document.createElement('input') - root.append(findInput) - const onClick = vi.fn() - closeButton?.addEventListener('click', onClick) - - expect( - closeUnfocusedMonacoFindOrPreventDialogDismiss({ - root, - eventTarget: findInput - }) - ).toBe(true) - expect(onClick).not.toHaveBeenCalled() - }) - - it('closes find and lets the dialog dismiss when find is open but unfocused', () => { - const root = document.createElement('div') - const { closeButton } = appendFindWidget(root, { withCloseButton: true }) - const nameField = document.createElement('input') - const onClick = vi.fn() - closeButton?.addEventListener('click', onClick) - - expect( - closeUnfocusedMonacoFindOrPreventDialogDismiss({ - root, - eventTarget: nameField - }) - ).toBe(false) - expect(onClick).toHaveBeenCalledTimes(1) - }) - - it('lets the dialog dismiss when this host has no open find', () => { - const root = document.createElement('div') - const outside = document.createElement('div') - appendFindWidget(outside, { withCloseButton: true }) - - expect( - closeUnfocusedMonacoFindOrPreventDialogDismiss({ - root, - eventTarget: document.createElement('input') - }) - ).toBe(false) - }) -}) diff --git a/src/renderer/src/components/editor/pdf-scale-preference.test.ts b/src/renderer/src/components/editor/pdf-scale-preference.test.ts index 51ecc701c2d..5d8da189fb2 100644 --- a/src/renderer/src/components/editor/pdf-scale-preference.test.ts +++ b/src/renderer/src/components/editor/pdf-scale-preference.test.ts @@ -1,54 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import { - applyPdfScalePreference, - clampPdfScale, - stepPdfScalePreference, - zoomPdfViewerWithWheel -} from './pdf-scale-preference' +import { zoomPdfViewerWithWheel } from './pdf-scale-preference' + import { getPinchZoomFactor } from './image-viewer-zoom' const BOUNDS = { min: 0.25, max: 5, step: 1.25 } -describe('clampPdfScale', () => { - it('clamps to the configured range', () => { - expect(clampPdfScale(0.1, BOUNDS.min, BOUNDS.max)).toBe(0.25) - expect(clampPdfScale(9, BOUNDS.min, BOUNDS.max)).toBe(5) - expect(clampPdfScale(1.5, BOUNDS.min, BOUNDS.max)).toBe(1.5) - }) -}) - -describe('applyPdfScalePreference', () => { - it('restores an absolute scale after a content reload', () => { - const viewer = { currentScale: 1, currentScaleValue: 'auto' } - applyPdfScalePreference(viewer, 2.5, BOUNDS) - expect(viewer.currentScale).toBe(2.5) - }) - - it('uses fit-to-width for the default preference', () => { - const viewer = { currentScale: 1, currentScaleValue: 'auto' } - applyPdfScalePreference(viewer, 'page-width', BOUNDS) - expect(viewer.currentScaleValue).toBe('page-width') - }) - - it('clamps an out-of-range absolute preference', () => { - const viewer = { currentScale: 1, currentScaleValue: 'auto' } - applyPdfScalePreference(viewer, 99, BOUNDS) - expect(viewer.currentScale).toBe(5) - }) -}) - -describe('stepPdfScalePreference', () => { - it('records the absolute scale so a later reload can restore it', () => { - const zoomedIn = stepPdfScalePreference(1, 'in', BOUNDS) - expect(zoomedIn.preference).toBe(1.25) - expect(zoomedIn.scale).toBe(1.25) - - const zoomedOut = stepPdfScalePreference(1.25, 'out', BOUNDS) - expect(zoomedOut.preference).toBe(1) - expect(zoomedOut.scale).toBe(1) - }) -}) - describe('zoomPdfViewerWithWheel', () => { function wheel(deltaY: number, ctrlKey = true) { return { ctrlKey, deltaY, deltaMode: 0, clientX: 300, clientY: 250, preventDefault: vi.fn() } @@ -65,14 +21,6 @@ describe('zoomPdfViewerWithWheel', () => { } } - it('leaves plain wheel scrolling alone', () => { - const viewer = viewerAt(1) - const event = wheel(-30, false) - expect(zoomPdfViewerWithWheel(viewer, event, BOUNDS)).toBeNull() - expect(event.preventDefault).not.toHaveBeenCalled() - expect(viewer.currentScale).toBe(1) - }) - it('keeps the content under the pointer in place', () => { const viewer = viewerAt(1) const event = wheel(-30) diff --git a/src/renderer/src/components/editor/rich-markdown-link-shortcut.test.ts b/src/renderer/src/components/editor/rich-markdown-link-shortcut.test.ts index ace2b9aa36c..b9be2704286 100644 --- a/src/renderer/src/components/editor/rich-markdown-link-shortcut.test.ts +++ b/src/renderer/src/components/editor/rich-markdown-link-shortcut.test.ts @@ -1,7 +1,8 @@ // @vitest-environment happy-dom import { afterEach, describe, expect, it, vi } from 'vitest' import { Editor } from '@tiptap/core' -import { NodeSelection, TextSelection } from '@tiptap/pm/state' +import { NodeSelection } from '@tiptap/pm/state' + import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html' import { createRichMarkdownExtensions } from './rich-markdown-extensions' import { createRichMarkdownHtmlSuperscriptLinkContext } from './rich-markdown-html-superscript-link-context' @@ -96,35 +97,4 @@ describe('handleRichMarkdownLinkShortcut', () => { root.remove() } }) - - it('opens an editable markdown bubble when there is no link selection', () => { - const { editor, context, root } = createEditor('plain text') - try { - editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1))) - const setLinkBubble = vi.fn() - const setEditing = vi.fn() - - handleRichMarkdownLinkShortcut({ - editor, - event: keyEvent(), - htmlSuperscriptLinkContext: context, - isEditing: false, - isMac: true, - root, - setEditing, - setLinkBubble - }) - - expect(setEditing).toHaveBeenCalledWith(true) - expect(setLinkBubble).toHaveBeenCalledWith( - expect.objectContaining({ - kind: 'markdown', - href: '' - }) - ) - } finally { - editor.destroy() - root.remove() - } - }) }) diff --git a/src/renderer/src/components/quick-open-file-history.test.ts b/src/renderer/src/components/quick-open-file-history.test.ts index ba4252a75b7..c6af0e80c21 100644 --- a/src/renderer/src/components/quick-open-file-history.test.ts +++ b/src/renderer/src/components/quick-open-file-history.test.ts @@ -44,15 +44,6 @@ beforeEach(() => { owner.current = { kind: 'local' } }) -it('records opens after closure and deduplicates visits in recency order', () => { - recordQuickOpenFileVisit(state, file('a.ts')) - recordQuickOpenFileVisit(state, file('b.ts')) - recordQuickOpenFileVisit(state, file('a.ts')) - expect( - readQuickOpenHistory(quickOpenHistoryScope(state, 'folder:one', '/folder/folder:one')) - ).toEqual(['a.ts', 'b.ts']) -}) - it('isolates workspace, SSH host and paired runtime history', () => { const localScope = quickOpenHistoryScope(state, 'folder:two', '/folder/folder:two') recordQuickOpenFileVisit(state, file('local.ts', 'folder:two')) @@ -74,35 +65,6 @@ it('isolates workspace, SSH host and paired runtime history', () => { ).toEqual([]) }) -it('bounds retained files and workspaces without losing the newest visits', () => { - for (let i = 0; i < 150; i++) { - recordQuickOpenFileVisit(state, file(`file-${i}.ts`, 'bounded-files')) - } - const paths = readQuickOpenHistory( - quickOpenHistoryScope(state, 'bounded-files', '/folder/bounded-files') - ) - expect(paths).toHaveLength(100) - expect(paths[0]).toBe('file-149.ts') - for (let i = 0; i < 70; i++) { - recordQuickOpenFileVisit(state, file('latest.ts', `bounded-owner-${i}`)) - } - expect( - readQuickOpenHistory(quickOpenHistoryScope(state, 'bounded-owner-0', '/folder/bounded-owner-0')) - ).toEqual([]) - expect( - readQuickOpenHistory( - quickOpenHistoryScope(state, 'bounded-owner-69', '/folder/bounded-owner-69') - ) - ).toEqual(['latest.ts']) -}) - -it('ignores unowned and temporary files', () => { - const scope = quickOpenHistoryScope(state, 'invalid-history', '/folder/invalid-history') - recordQuickOpenFileVisit(state, { ...file('draft.ts', 'invalid-history'), isUntitled: true }) - recordQuickOpenFileVisit(state, { ...file('diff.ts', 'invalid-history'), mode: 'diff' }) - expect(readQuickOpenHistory(scope)).toEqual([]) -}) - it('does not record a loaded file under a replacement host owner', () => { const stale: OpenFile = { ...file('stale.ts', 'owner-replacement'), diff --git a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts index 856d90de363..0123029e313 100644 --- a/src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts +++ b/src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts @@ -1,21 +1,14 @@ import { describe, expect, it } from 'vitest' import { MIN_COMPATIBLE_RUNTIME_SERVER_VERSION, - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - RUNTIME_PROTOCOL_VERSION, - TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY, - WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY + RUNTIME_PROTOCOL_VERSION } from '../../../../shared/protocol-version' + import { - evaluateHostDetails, - getActiveServerModeDescription, getHostDetailsDescription, getHostDetailsSummary, - getHostModelCapabilitySummary, - getRuntimeCapabilitiesSummary, getRuntimeServerConnectionState, isRuntimeServerTransportConnected, - isRuntimeEnvironmentRemovalBlocked, type RuntimeHostDetails } from './runtime-environment-host-details' @@ -45,153 +38,6 @@ function readyTransport( } describe('RuntimeEnvironmentsPane host details', () => { - it('summarizes loading, error, compatible, and blocked hosts', () => { - expect(getHostDetailsSummary(undefined)).toBe('Checking…') - expect(getHostDetailsSummary(details({ status: 'error', error: 'offline' }))).toBe( - 'Status unavailable' - ) - expect( - getHostDetailsSummary( - details({ - compatibility: { - kind: 'ok', - clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, - serverProtocolVersion: RUNTIME_PROTOCOL_VERSION - } - }) - ) - ).toBe('Compatible') - expect( - getHostDetailsSummary( - details({ - compatibility: { - kind: 'blocked', - reason: 'server-too-old', - clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, - serverProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - 1, - requiredServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - } - }) - ) - ).toBe('Update server') - expect( - getHostDetailsSummary( - details({ - compatibility: { - kind: 'blocked', - reason: 'client-too-old', - clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, - serverProtocolVersion: RUNTIME_PROTOCOL_VERSION, - requiredClientProtocolVersion: RUNTIME_PROTOCOL_VERSION + 1 - } - }) - ) - ).toBe('Update client') - }) - - it('evaluates runtime protocol compatibility from status aliases', () => { - expect( - evaluateHostDetails({ - runtimeId: 'runtime-old', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0, - protocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - 1, - minCompatibleMobileVersion: 0 - }) - ).toMatchObject({ kind: 'blocked', reason: 'server-too-old' }) - }) - - it('explains blocked runtime compatibility with required protocol versions', () => { - expect( - getHostDetailsDescription( - details({ - compatibility: { - kind: 'blocked', - reason: 'server-too-old', - clientProtocolVersion: RUNTIME_PROTOCOL_VERSION, - serverProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - 1, - requiredServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION - } - }) - ) - ).toContain('client requires server protocol') - }) - - it('summarizes runtime capabilities by name with overflow count', () => { - expect( - getRuntimeCapabilitiesSummary({ - runtimeId: 'runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: ['runtime.environments.v1', 'terminal.multiplex.v1'] - }) - ).toBe('runtime.environments.v1, terminal.multiplex.v1') - - expect( - getRuntimeCapabilitiesSummary({ - runtimeId: 'runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: [ - 'runtime.environments.v1', - 'browser.screencast.v1', - 'terminal.multiplex.v1', - 'project-host-setup.v1' - ] - }) - ).toBe('runtime.environments.v1, browser.screencast.v1, terminal.multiplex.v1 +1') - }) - - it('summarizes Host model capability support for version-skewed servers', () => { - expect( - getHostModelCapabilitySummary({ - runtimeId: 'runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0 - }) - ).toBe('Host model support: checking server capabilities') - - expect( - getHostModelCapabilitySummary({ - runtimeId: 'runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: [ - PROJECT_HOST_SETUP_RUNTIME_CAPABILITY, - TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY, - WORKSPACE_RUN_CONTEXT_RUNTIME_CAPABILITY - ] - }) - ).toBe('Host model support: ready') - - expect( - getHostModelCapabilitySummary({ - runtimeId: 'runtime', - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: 1, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: [PROJECT_HOST_SETUP_RUNTIME_CAPABILITY] - }) - ).toBe('Host model support: update server for task source context, workspace run context') - }) - it('distinguishes transport-up/runtime-down from an attached ready runtime', () => { // Attachment determines Disconnect and connection labels; default-server selection must not make dot/label/button disagree. expect(getRuntimeServerConnectionState(details({ status: 'ready' }))).toBe( @@ -285,15 +131,4 @@ describe('RuntimeEnvironmentsPane host details', () => { ) ).toBe('disconnected') }) - - it('explains that the choice only picks the host for new projects', () => { - expect(getActiveServerModeDescription(true)).toBe('Existing projects stay where they are.') - expect(getActiveServerModeDescription(false)).toContain('new projects on the chosen server') - }) - - it('blocks removing the active server independently of local-runtime availability', () => { - expect(isRuntimeEnvironmentRemovalBlocked('windows-2', 'windows-2')).toBe(true) - expect(isRuntimeEnvironmentRemovalBlocked(undefined, 'windows-2')).toBe(false) - expect(isRuntimeEnvironmentRemovalBlocked('local', 'windows-2')).toBe(false) - }) }) diff --git a/src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx b/src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx index 96ed07e6609..118f23dd893 100644 --- a/src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx +++ b/src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx @@ -93,38 +93,3 @@ it('still discards a brand-new server whose first connect fails', async () => { expect(remove).toHaveBeenCalledWith({ selector: 'env-new' }) }) - -it("lets main judge a saved server's own name, so its code can refresh it", async () => { - verifyAndAddFromPairingCode.mockResolvedValue({ - ok: true, - environment: saved, - runtimeStatus: { runtimeId: 'runtime-a' }, - updatedExisting: true - }) - const view = renderActions(async () => true, 'Studio') - - await act(async () => { - await view.result.current.addEnvironment(false) - }) - - expect(verifyAndAddFromPairingCode).toHaveBeenCalledWith( - expect.objectContaining({ name: 'Studio' }) - ) - expect(toastError).not.toHaveBeenCalled() -}) - -it('says a WSL host it kept was not removed yet, instead of "Removed"', async () => { - remove.mockResolvedValue({ - removed: saved, - serverStop: { stopped: false, reason: '1 terminal kept running.', verdict: 'live', kept: true } - }) - const view = renderActions(async () => true) - await act(async () => { - await view.result.current.removeEnvironment(saved) - }) - expect(toastSuccess).not.toHaveBeenCalled() - expect(toastWarning).toHaveBeenCalledWith( - 'Orca didn’t remove the host yet: 1 terminal kept running. Remove it again to retry, or connect it to keep it.', - { duration: Infinity } - ) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-drop-upload-report.test.ts b/src/renderer/src/components/terminal-pane/terminal-drop-upload-report.test.ts index a4b0813fe73..90225751ecb 100644 --- a/src/renderer/src/components/terminal-pane/terminal-drop-upload-report.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-drop-upload-report.test.ts @@ -24,70 +24,6 @@ describe('reportTerminalDropUploadSkipsAndFailures', () => { vi.mocked(toast.error).mockClear() }) - it('uses distinct translation keys for symlink-only and mixed skipped uploads', () => { - reportTerminalDropUploadSkipsAndFailures([{ reason: 'symlink' }], []) - const symlinkOnlyKey = mocks.translate.mock.calls[0]?.[0] - - mocks.translate.mockClear() - reportTerminalDropUploadSkipsAndFailures([{ reason: 'symlink' }, { reason: 'too_large' }], []) - const mixedSkipKey = mocks.translate.mock.calls[0]?.[0] - - expect(symlinkOnlyKey).toBe( - 'auto.components.terminal.pane.terminal.drop.handler.skippedSymlinks' - ) - expect(mixedSkipKey).toBe('auto.components.terminal.pane.terminal.drop.handler.skippedItems') - expect(symlinkOnlyKey).not.toBe(mixedSkipKey) - expect(toast.message).toHaveBeenCalledTimes(2) - }) - - it('reports upload failures without leaking individual paths', () => { - reportTerminalDropUploadSkipsAndFailures([], [{ reason: '/secret/project/file.txt' }]) - - expect(mocks.translate).toHaveBeenCalledWith( - 'auto.components.terminal.pane.terminal.drop.handler.failedUploads', - 'Failed to upload {{count}} files.', - { count: 1, defaultValue_one: 'Failed to upload {{count}} file.' } - ) - expect(toast.error).toHaveBeenCalledWith( - expect.not.stringContaining('/secret/project/file.txt'), - { description: expect.not.stringContaining('/secret/project/file.txt') } - ) - }) - - it('names a shared known skip reason', () => { - reportTerminalDropUploadSkipsAndFailures( - [{ reason: 'permission-denied' }, { reason: 'permission-denied' }], - [] - ) - - expect(toast.message).toHaveBeenCalledWith( - 'auto.components.terminal.pane.terminal.drop.handler.skippedItems:Skipped {{count}} items.', - { description: 'auto.lib.dropSkipReason.permissionDenied:Permission denied.' } - ) - }) - - it('gives no reason for mixed, unknown, or symlink-only skips', () => { - reportTerminalDropUploadSkipsAndFailures([{ reason: 'missing' }, { reason: 'symlink' }], []) - reportTerminalDropUploadSkipsAndFailures([{ reason: 'too_large' }], []) - reportTerminalDropUploadSkipsAndFailures([{ reason: 'symlink' }], []) - - expect(vi.mocked(toast.message).mock.calls.map((call) => call[1])).toEqual([ - { description: undefined }, - { description: undefined }, - { description: undefined } - ]) - }) - - it('keeps upload wording for failures', () => { - reportTerminalDropUploadSkipsAndFailures([], [{ reason: 'a' }, { reason: 'b' }]) - - expect(mocks.translate).toHaveBeenCalledWith( - 'auto.components.terminal.pane.terminal.drop.handler.failedUploads', - 'Failed to upload {{count}} files.', - { count: 2, defaultValue_one: 'Failed to upload {{count}} file.' } - ) - }) - it('names a shared failure category, never the host text', () => { vi.spyOn(console, 'warn').mockImplementation(() => {}) reportTerminalDropUploadSkipsAndFailures( diff --git a/src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts b/src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts deleted file mode 100644 index c7cf27b3b01..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-layout-duplicate-pty-replay.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { replayTerminalLayout } from './layout-serialization' - -const LEAF_1 = '11111111-1111-4111-8111-111111111111' -const LEAF_2 = '22222222-2222-4222-8222-222222222222' -const LEAF_3 = '33333333-3333-4333-8333-333333333333' - -describe('duplicate PTY layout replay', () => { - it('replays one surface when restored leaves point to the same PTY', () => { - const manager = { - createInitialPane: vi.fn((opts?: { leafId?: string }) => ({ - id: 1, - leafId: opts?.leafId ?? LEAF_1 - })), - splitPane: vi.fn() - } - - const restored = replayTerminalLayout( - manager as unknown as Parameters[0], - { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_2 } - }, - activeLeafId: LEAF_2, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - }, - true - ) - - expect(manager.createInitialPane).toHaveBeenCalledWith({ focus: true, leafId: LEAF_2 }) - expect(manager.splitPane).not.toHaveBeenCalled() - expect([...restored]).toEqual([[LEAF_2, 1]]) - }) - - it('reattaches the retained PTY leaf from rootless duplicate state', () => { - const manager = { - createInitialPane: vi.fn((opts?: { leafId?: string }) => ({ - id: 1, - leafId: opts?.leafId ?? LEAF_2 - })), - splitPane: vi.fn() - } - - const restored = replayTerminalLayout( - manager as unknown as Parameters[0], - { - root: null, - activeLeafId: null, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - }, - true - ) - - expect(manager.createInitialPane).toHaveBeenCalledWith({ focus: true, leafId: LEAF_1 }) - expect(manager.splitPane).not.toHaveBeenCalled() - expect([...restored]).toEqual([[LEAF_1, 1]]) - }) - - it('preserves a rootless pending leaf while pruning duplicate PTY ownership', () => { - const manager = { - createInitialPane: vi.fn((opts?: { leafId?: string }) => ({ - id: 1, - leafId: opts?.leafId ?? LEAF_2 - })), - splitPane: vi.fn() - } - - const restored = replayTerminalLayout( - manager as unknown as Parameters[0], - { - root: null, - activeLeafId: LEAF_3, - expandedLeafId: null, - ptyIdsByLeafId: { - [LEAF_1]: 'pty-agent', - [LEAF_2]: 'pty-agent' - } - }, - true - ) - - expect(manager.createInitialPane).toHaveBeenCalledWith({ focus: true, leafId: LEAF_3 }) - expect(manager.splitPane).not.toHaveBeenCalled() - expect([...restored]).toEqual([[LEAF_3, 1]]) - }) - - it('reattaches one PTY when the split repeats its bound leaf id', () => { - const manager = { - createInitialPane: vi.fn((opts?: { leafId?: string }) => ({ - id: 1, - leafId: opts?.leafId ?? LEAF_2 - })), - splitPane: vi.fn() - } - - const restored = replayTerminalLayout( - manager as unknown as Parameters[0], - { - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: LEAF_1 }, - second: { type: 'leaf', leafId: LEAF_1 } - }, - activeLeafId: LEAF_1, - expandedLeafId: null, - ptyIdsByLeafId: { [LEAF_1]: 'pty-agent' } - }, - true - ) - - expect(manager.createInitialPane).toHaveBeenCalledWith({ focus: true, leafId: LEAF_1 }) - expect(manager.splitPane).not.toHaveBeenCalled() - expect([...restored]).toEqual([[LEAF_1, 1]]) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-legacy-relay-bridge-pane.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-legacy-relay-bridge-pane.test.ts index 9db7d78242b..0579c40b6fc 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-legacy-relay-bridge-pane.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-legacy-relay-bridge-pane.test.ts @@ -44,11 +44,6 @@ const movedRows: WorktreeOperationRouteState = { ] } } -// The same workspace while this desktop still dials the SSH host directly. -const directSshRows: WorktreeOperationRouteState = { - repos: [{ id: 'repo-1', executionHostId: 'ssh:box', connectionId: 'box' }], - worktreesByRepo: { 'repo-1': [{ id: WORKTREE_ID, repoId: 'repo-1', hostId: 'ssh:box' }] } -} function hover(runtimeEnvironmentId: string | null): Promise { const { provider } = createProviderSetup( @@ -103,27 +98,4 @@ describe('file links in a relay-era pane the legacy relay bridge serves', () => }) ) }) - - it('keeps a workspace this desktop still dials over SSH off any server', () => { - expect( - resolveTerminalLinkRuntimeEnvironmentId(bridgedTransport, directSshRows, WORKTREE_ID) - ).toBeNull() - }) - - it('leaves an SSH pane the bridge does not serve as it was', () => { - bridged.ptyIds = new Set() - expect( - resolveTerminalLinkRuntimeEnvironmentId(bridgedTransport, movedRows, WORKTREE_ID) - ).toBeNull() - }) - - it("prefers a pane's own server", () => { - expect( - resolveTerminalLinkRuntimeEnvironmentId( - { ...bridgedTransport, getRuntimeEnvironmentId: () => 'env-2' }, - movedRows, - WORKTREE_ID - ) - ).toBe('env-2') - }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts b/src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts deleted file mode 100644 index 1f5b8647927..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-pty-ack-gate.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('@/lib/e2e-config', () => ({ e2eConfig: { exposeStore: false } })) - -describe('terminal-pty-ack-gate cumulative totals', () => { - const ackDataMock = vi.fn() - - beforeEach(() => { - // Fresh modules model renderer reload resetting cumulative ACK accounting. - vi.resetModules() - ackDataMock.mockClear() - ;(window as unknown as { api: unknown }).api = { pty: { ackData: ackDataMock } } - }) - - afterEach(() => { - delete (window as unknown as { api?: unknown }).api - }) - - async function loadAckGate() { - return await import('./terminal-pty-ack-gate') - } - - it('sends monotonic cumulative totals alongside per-chunk deltas', async () => { - const { ackPtyData, getProcessedPtyCharTotals } = await loadAckGate() - - ackPtyData('pty-a', 5) - ackPtyData('pty-a', 7) - ackPtyData('pty-b', 3) - - expect(ackDataMock).toHaveBeenNthCalledWith(1, 'pty-a', 5, 5) - expect(ackDataMock).toHaveBeenNthCalledWith(2, 'pty-a', 7, 12) - expect(ackDataMock).toHaveBeenNthCalledWith(3, 'pty-b', 3, 3) - expect(getProcessedPtyCharTotals()).toEqual({ 'pty-a': 12, 'pty-b': 3 }) - }) - - it('clears a PTY total so a reused id restarts from zero on both sides', async () => { - const { ackPtyData, clearProcessedPtyCharTotal, getProcessedPtyCharTotals } = - await loadAckGate() - - ackPtyData('pty-a', 9) - clearProcessedPtyCharTotal('pty-a') - - expect(getProcessedPtyCharTotals()).toEqual({}) - - ackPtyData('pty-a', 4) - expect(ackDataMock).toHaveBeenLastCalledWith('pty-a', 4, 4) - }) -}) - -describe('terminal-pty-ack-gate parse-deferred crediting', () => { - const ackDataMock = vi.fn() - - beforeEach(() => { - vi.resetModules() - ackDataMock.mockClear() - ;(window as unknown as { api: unknown }).api = { pty: { ackData: ackDataMock } } - }) - - afterEach(() => { - delete (window as unknown as { api?: unknown }).api - }) - - async function loadAckGate() { - return await import('./terminal-pty-ack-gate') - } - - it('settles an unclaimed delivery credit at return', async () => { - const { deliverPtyDataWithDeferredAck } = await loadAckGate() - - deliverPtyDataWithDeferredAck('pty-a', 42, () => {}) - - expect(ackDataMock).toHaveBeenCalledWith('pty-a', 42, 42) - }) - - it('defers a claimed credit to the scheduler callback and fires once', async () => { - const { deliverPtyDataWithDeferredAck, takeCurrentPtyDeliveryAckCredit } = await loadAckGate() - let credit: (() => void) | null = null - - deliverPtyDataWithDeferredAck('pty-a', 10, () => { - credit = takeCurrentPtyDeliveryAckCredit() - }) - - expect(ackDataMock).not.toHaveBeenCalled() - credit!() - expect(ackDataMock).toHaveBeenCalledWith('pty-a', 10, 10) - credit!() - expect(ackDataMock).toHaveBeenCalledTimes(1) - }) - - it('waits for every scheduler write produced by one delivery', async () => { - const { deliverPtyDataWithDeferredAck, takeCurrentPtyDeliveryAckCredit } = await loadAckGate() - let first: (() => void) | null = null - let second: (() => void) | null = null - - deliverPtyDataWithDeferredAck('pty-a', 5, () => { - first = takeCurrentPtyDeliveryAckCredit() - second = takeCurrentPtyDeliveryAckCredit() - }) - - expect(first).not.toBeNull() - expect(second).not.toBeNull() - first!() - expect(ackDataMock).not.toHaveBeenCalled() - second!() - expect(ackDataMock).toHaveBeenCalledWith('pty-a', 5, 5) - }) - - it('returns null outside a delivery', async () => { - const { takeCurrentPtyDeliveryAckCredit } = await loadAckGate() - expect(takeCurrentPtyDeliveryAckCredit()).toBeNull() - }) - - it('settles the credit when the handler throws so the PTY never wedges', async () => { - const { deliverPtyDataWithDeferredAck } = await loadAckGate() - - expect(() => - deliverPtyDataWithDeferredAck('pty-a', 7, () => { - throw new Error('bad sidecar') - }) - ).toThrow('bad sidecar') - expect(ackDataMock).toHaveBeenCalledWith('pty-a', 7, 7) - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx index 5baa80f2655..1a075895322 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-browse-state.test.tsx @@ -64,20 +64,6 @@ describe('useWorkspaceCleanupBrowseState', () => { vi.useRealTimers() }) - it('keeps both patches when two groups are written in one tick', () => { - const controller = mountController() - - // Batch patches in one act so stale rendered-state reads would overwrite the first patch. - act(() => { - controller.current!.patchFilters('activity', { idleMinDays: 20 }) - controller.current!.patchFilters('size', { maxBytes: 500 }) - }) - - const filters = store.getState().workspaceCleanupBrowse.filters - expect(filters.activity.idleMinDays).toBe(20) - expect(filters.size.maxBytes).toBe(500) - }) - it('keeps both patches when the same group is written twice in one tick', () => { const controller = mountController() diff --git a/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts b/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts index d10dae086ad..7134f1c251b 100644 --- a/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts +++ b/src/renderer/src/hooks/ipc-tab-switch-group-order-hydration.test.ts @@ -9,11 +9,7 @@ vi.mock('../store', () => ({ useAppStore: { getState: getStateMock } })) import { createTabsFocusActions } from '../store/slices/tabs/tabs-focus-actions' import type { TabsSliceGet, TabsSliceSet } from '../store/slices/tabs/tabs-slice-contract' -import { - handleSwitchTab, - handleSwitchTabAcrossAllTypes, - handleSwitchTerminalTab -} from './ipc-tab-switch' +import { handleSwitchTab, handleSwitchTerminalTab } from './ipc-tab-switch' const WT = 'wt-1' const GROUP = 'group-1' @@ -74,30 +70,6 @@ describe('tab-cycle chord against a group whose tabOrder is still hydrating', () vi.clearAllMocks() }) - it('switches to the group tab that group.tabOrder has not recorded yet', () => { - const store = stateWithGroupOrder(['tab-1']) - getStateMock.mockReturnValue(store) - - expect(handleSwitchTab(1)).toBe(true) - expect(store.setActiveTab).toHaveBeenCalledWith('term-2') - }) - - it('switches across all types in the same hydrating state', () => { - const store = stateWithGroupOrder(['tab-1']) - getStateMock.mockReturnValue(store) - - expect(handleSwitchTabAcrossAllTypes(-1)).toBe(true) - expect(store.setActiveTab).toHaveBeenCalledWith('term-3') - }) - - it('still cycles in the recorded order once tabOrder is complete', () => { - const store = stateWithGroupOrder(['tab-2', 'tab-1', 'tab-3']) - getStateMock.mockReturnValue(store) - - expect(handleSwitchTab(1)).toBe(true) - expect(store.setActiveTab).toHaveBeenCalledWith('term-3') - }) - it('cycles a terminal-only shortcut while the runtime row is still hydrating', () => { const store = stateWithGroupOrder(['tab-1']) store.tabsByWorktree = { [WT]: [{ id: 'term-1' }] } diff --git a/src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts b/src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts index 684baf3af0e..7aafe04562c 100644 --- a/src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts +++ b/src/renderer/src/hooks/mobile-terminal-reveal-tab-adoption.test.ts @@ -34,50 +34,6 @@ function revealSplitPaneFromMobile(harness: { } describe('mobile terminal reveal tab adoption', () => { - it('adopts the owning tab when a split pane is revealed before its panes mount (#10486)', async () => { - // Unmounted worktrees retain split PTYs only in layout; live maps may be empty. - const storeState: HarnessStoreState = createHarnessStoreState({ - tabsByWorktree: { [WORKTREE_ID]: [{ id: 'tab-split', ptyId: 'pty-a', title: 'codex' }] }, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: { - 'tab-split': { ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-b': 'pty-b' } } - } - }) - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - revealSplitPaneFromMobile(harness) - - expect(storeState.createTab).not.toHaveBeenCalled() - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'mobile-reveal', - tabId: 'tab-split', - title: 'codex', - identity: revealIdentity('tab-split') - }) - }) - - it('adopts the owning tab when neither the live map nor the layout is hydrated', async () => { - // Before layout hydration, honor the pre-minted tab ID baked into the PTY paneKey. - const storeState: HarnessStoreState = createHarnessStoreState({ - tabsByWorktree: { [WORKTREE_ID]: [{ id: 'tab-split', ptyId: 'pty-a', title: 'codex' }] }, - ptyIdsByTabId: { 'tab-split': ['pty-a'] }, - terminalLayoutsByTabId: {} - }) - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - revealSplitPaneFromMobile(harness) - - expect(storeState.createTab).not.toHaveBeenCalled() - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'mobile-reveal', - tabId: 'tab-split', - title: 'codex', - identity: revealIdentity('tab-split') - }) - }) - it('adopts the tab that records the pty when the reveal hint disagrees', async () => { // Dragging a pane changes its current tab while reveal still names its baked-in original. const storeState: HarnessStoreState = createHarnessStoreState({ @@ -107,34 +63,6 @@ describe('mobile terminal reveal tab adoption', () => { }) }) - it('adopts through the persisted layout when the PTY carries no tab id', async () => { - const storeState: HarnessStoreState = createHarnessStoreState({ - tabsByWorktree: { [WORKTREE_ID]: [{ id: 'tab-split', ptyId: 'pty-a', title: 'codex' }] }, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: { - 'tab-split': { ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-b': 'pty-b' } } - } - }) - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - harness.createTerminal({ - requestId: 'mobile-reveal', - worktreeId: WORKTREE_ID, - ptyId: 'pty-b', - leafId: 'leaf-b', - presentation: 'focused', - title: 'codex' - }) - - expect(storeState.createTab).not.toHaveBeenCalled() - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'mobile-reveal', - tabId: 'tab-split', - title: 'codex' - }) - }) - it('keeps a live binding authoritative over a stale layout row', async () => { // No tabId hint: the live pty map still pins the session to its real tab. const storeState: HarnessStoreState = createHarnessStoreState({ diff --git a/src/renderer/src/i18n/language-readiness.test.ts b/src/renderer/src/i18n/language-readiness.test.ts index 26930058c15..de07075c3e8 100644 --- a/src/renderer/src/i18n/language-readiness.test.ts +++ b/src/renderer/src/i18n/language-readiness.test.ts @@ -22,37 +22,6 @@ function installBridge( afterEach(() => vi.useRealTimers()) describe('client-local startup language', () => { - it('uses the local native snapshot over Chromium preferences and freezes it for startup', async () => { - const probe = vi.fn().mockResolvedValue({ - detectedTag: 'it-IT', - status: 'unsupported', - locale: 'en', - source: 'native' - }) - installBridge(probe) - const { initializeLanguageDetection } = await import('./language-readiness') - expect(await initializeLanguageDetection()).toMatchObject({ - detectedTag: 'it-IT', - source: 'native' - }) - await initializeLanguageDetection() - expect(probe).toHaveBeenCalledTimes(1) - expect(probe).toHaveBeenCalledWith(['fr-FR']) - }) - - it('does not replace a C-only native result with browser English', async () => { - installBridge( - vi - .fn() - .mockResolvedValue({ detectedTag: null, status: 'unknown', locale: 'en', source: 'native' }) - ) - const { initializeLanguageDetection } = await import('./language-readiness') - expect(await initializeLanguageDetection()).toMatchObject({ - status: 'unknown', - source: 'native' - }) - }) - it('uses uncertain browser fallback when an older bridge lacks the optional snapshot', async () => { installBridge() const { initializeLanguageDetection } = await import('./language-readiness') @@ -63,23 +32,6 @@ describe('client-local startup language', () => { }) }) - it('shares the main-owned browser fallback when native detection is unavailable', async () => { - const probe = vi.fn().mockResolvedValue({ - detectedTag: 'ja-JP', - status: 'supported', - locale: 'ja', - source: 'browser-fallback' - }) - installBridge(probe) - const { initializeLanguageDetection } = await import('./language-readiness') - expect(await initializeLanguageDetection()).toMatchObject({ - detectedTag: 'ja-JP', - locale: 'ja', - source: 'browser-fallback' - }) - expect(probe).toHaveBeenCalledWith(['fr-FR']) - }) - it('uses browser preferences on web/mobile without asking the server for its locale', async () => { isWebClientLocation.mockReturnValue(true) const probe = vi.fn() @@ -113,12 +65,3 @@ it('bounds startup with browser fallback and reconciles a late native result', a expect(getRendererLanguageDetection().locale).toBe('ja') expect(await initializeLanguageDetection()).toMatchObject({ locale: 'ja', source: 'native' }) }) - -it('uses browser fallback when native IPC rejects', async () => { - installBridge(() => Promise.reject(new Error('Native locale API unavailable'))) - const { initializeLanguageDetection } = await import('./language-readiness') - expect(await initializeLanguageDetection()).toMatchObject({ - locale: 'fr', - source: 'browser-fallback' - }) -}) diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts index 592b696cc2e..e9307b1126c 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts @@ -7,10 +7,10 @@ import { resetStructuredAgentLaunchPersistenceForTests, readStructuredAgentLaunchCancellationTombstoneSessionIds, retireAbsentStructuredAgentLaunchCancellationTombstonesPersisted, - retireStructuredAgentLaunchCancellationTombstonePersisted, writeStructuredAgentLaunchRecord, markStructuredAgentLaunchCancelledPersisted } from './structured-agent-session-launch-persistence' + import { structuredAgentLaunchRecordFor } from './structured-agent-session-launch-record' import type { StructuredAgentSessionLaunchIntent } from '../../launch-structured-agent-session' @@ -60,45 +60,6 @@ describe('structured agent launch persistence', () => { }) }) - it("keeps a registered agent's launch across a reload and drops a record naming no agent", () => { - localStorage.setItem( - 'orca:structuredAgentLaunches:v1', - JSON.stringify( - [ - ['grok_session', 'grok'], - ['bogus_session', 'not-an-agent'] - ].map(([sessionId, agent]) => ({ - sessionId, - agent, - lifecycle: 'pending', - surfaceAddress: { worktreeId: 'workspace', precedingTabIds: [false] }, - clientOperationId: `${sessionId}-op`, - payloadFingerprint: 'fingerprint', - expectedRuntimeFence: null - })) - ) - ) - - expect(readStructuredAgentLaunchRecord('grok_session')?.agent).toBe('grok') - expect(readStructuredAgentLaunchRecord('grok_session')?.surfaceAddress).toBeUndefined() - expect(readStructuredAgentLaunchRecord('bogus_session')).toBeUndefined() - }) - - it('keeps the host a launch was created on across a reload', () => { - writeStructuredAgentLaunchRecord({ - sessionId: 'claude_remote', - executionHostId: SERVER, - agent: 'claude', - lifecycle: 'pending', - clientOperationId: 'operation-3', - payloadFingerprint: 'fingerprint-3', - expectedRuntimeFence: null - }) - reload() - - expect(readStructuredAgentLaunchRecord('claude_remote')?.executionHostId).toBe(SERVER) - }) - // This machine cannot re-derive a paired server's seed, so a reload must show the same one. it("keeps a paired server's reported seed across a reload, and no local one", () => { const intent = ( @@ -140,49 +101,6 @@ describe('structured agent launch persistence', () => { expect(readStructuredAgentLaunchRecord('claude_local')?.seedOptions).toBeUndefined() }) - it('drops a stored seed value that does not decode', () => { - localStorage.setItem( - 'orca:structuredAgentLaunches:v1', - JSON.stringify([ - { - sessionId: 'claude_paired', - executionHostId: SERVER, - agent: 'claude', - lifecycle: 'failed', - clientOperationId: 'operation-1', - payloadFingerprint: 'fingerprint-1', - expectedRuntimeFence: null, - seedOptions: { model: 'opus', fastMode: 'maybe' } - } - ]) - ) - - expect(readStructuredAgentLaunchRecord('claude_paired')?.seedOptions).toEqual({ - model: 'opus' - }) - }) - - it('stores only content-free identity and preserves operation identity', () => { - writeStructuredAgentLaunchRecord({ - sessionId: 'claude_session', - executionHostId: 'local', - agent: 'claude', - lifecycle: 'visibility-unknown', - clientOperationId: 'operation-2', - payloadFingerprint: 'fingerprint-2', - expectedRuntimeFence: null, - resumeFrom: { providerSessionId: 'provider-thread' } - }) - - const raw = localStorage.getItem('orca:structuredAgentLaunches:v1') ?? '' - expect(raw).toContain('claude_session') - expect(raw).toContain('operation-2') - expect(raw).not.toContain('prompt') - expect(raw).not.toContain('branch') - expect(raw).not.toContain('path') - expect(readStructuredAgentLaunchRecord('claude_session')?.clientOperationId).toBe('operation-2') - }) - it('keeps when a failed launch failed across a reload, and still loads records without it', () => { writeStructuredAgentLaunchRecord({ sessionId: 'claude_session', @@ -215,15 +133,6 @@ describe('structured agent launch persistence', () => { expect(readStructuredAgentLaunchRecord('corrupt_session')).toBeUndefined() }) - it('persists cancellation tombstones by session id and retires them', () => { - markStructuredAgentLaunchCancelledPersisted('codex_session', 'local') - expect(hasStructuredAgentLaunchCancellationTombstonePersisted('codex_session')).toBe(true) - // A local chat's tombstone keeps the shape older builds read. - expect(localStorage.getItem(TOMBSTONES_KEY)).toBe('["codex_session"]') - expect(retireStructuredAgentLaunchCancellationTombstonePersisted('codex_session')).toBe(true) - expect(hasStructuredAgentLaunchCancellationTombstonePersisted('codex_session')).toBe(false) - }) - it("keeps a paired host's tombstone under that host across a reload", () => { markStructuredAgentLaunchCancelledPersisted('remote_session', SERVER) markStructuredAgentLaunchCancelledPersisted('local_session', 'local') diff --git a/src/renderer/src/lib/linear-issue-context-snapshot.test.ts b/src/renderer/src/lib/linear-issue-context-snapshot.test.ts index d8206a7aa9f..897314b47f7 100644 --- a/src/renderer/src/lib/linear-issue-context-snapshot.test.ts +++ b/src/renderer/src/lib/linear-issue-context-snapshot.test.ts @@ -52,145 +52,6 @@ function makeComment(patch: Partial = {}): LinearComment { } describe('buildLinearIssueContextSnapshot', () => { - it('includes available Linear metadata, description, children, and newest comments', () => { - const snapshot = buildLinearIssueContextSnapshot(makeIssue(), [ - makeComment({ - id: 'older', - body: 'Older note', - createdAt: '2026-05-28T13:00:00.000Z', - user: { displayName: 'Pat' } - }), - makeComment({ - id: 'newer', - body: 'Newest note', - createdAt: '2026-05-30T13:00:00.000Z', - user: { displayName: 'Sam' } - }) - ]) - - expect(snapshot).toContain('Identifier: ENG-123') - expect(snapshot).toContain('Title: Fix launch context handoff') - expect(snapshot).toContain('Priority: High (2)') - expect(snapshot).toContain('Estimate: 3') - expect(snapshot).toContain('Assignee: Brennan') - expect(snapshot).toContain('Team: Engineering (ENG)') - expect(snapshot).toContain('Workspace: Acme') - expect(snapshot).toContain('Project: Agent Launches (https://linear.app/acme/project/a)') - expect(snapshot).toContain('Labels: bug, agent') - expect(snapshot).toContain('Description:\nPass the Linear issue details into the agent.') - expect(snapshot).toContain( - '- ENG-124 Add prompt tests (https://linear.app/acme/issue/ENG-124/add-prompt-tests)' - ) - expect(snapshot.indexOf('Newest note')).toBeLessThan(snapshot.indexOf('Older note')) - }) - - it('omits optional sections when they are unavailable', () => { - const snapshot = buildLinearIssueContextSnapshot( - makeIssue({ - description: '', - project: undefined, - subIssues: [], - labels: [], - labelIds: [], - assignee: undefined, - estimate: null, - workspaceName: undefined - }) - ) - - expect(snapshot).toContain('Assignee: Unassigned') - expect(snapshot).toContain('Estimate: None') - expect(snapshot).not.toContain('Project:') - expect(snapshot).not.toContain('Labels:') - expect(snapshot).not.toContain('Description:') - expect(snapshot).not.toContain('Child issues:') - expect(snapshot).not.toContain('Recent comments:') - }) - - it('enforces section caps with explicit omission markers', () => { - const labels = Array.from( - { length: LINEAR_ISSUE_CONTEXT_CAPS.labels + 2 }, - (_, index) => `label-${index + 1}` - ) - const subIssues = Array.from( - { length: LINEAR_ISSUE_CONTEXT_CAPS.childIssues + 3 }, - (_, index) => ({ - id: `child-${index + 1}`, - identifier: `ENG-${200 + index}`, - title: `Child ${index + 1}`, - url: `https://linear.app/acme/issue/ENG-${200 + index}/child` - }) - ) - const comments = Array.from({ length: LINEAR_ISSUE_CONTEXT_CAPS.comments + 2 }, (_, index) => - makeComment({ - id: `comment-${index + 1}`, - body: `Comment ${index + 1}`, - createdAt: `2026-05-${String(20 + index).padStart(2, '0')}T13:00:00.000Z` - }) - ) - - const snapshot = buildLinearIssueContextSnapshot( - makeIssue({ - description: 'x'.repeat(LINEAR_ISSUE_CONTEXT_CAPS.descriptionChars + 100), - labels, - subIssues - }), - comments - ) - - expect(snapshot).toContain('[2 more labels]') - expect(snapshot).toContain('[3 more child issues]') - expect(snapshot).toContain('[2 older comments]') - expect(snapshot).toContain('[truncated]') - expect(snapshot).not.toContain('label-13, label-14') - expect(snapshot).not.toContain('ENG-210') - expect(snapshot).not.toContain('\n Comment 1\n') - }) - - it('sorts equal and invalid comment dates deterministically', () => { - const snapshot = buildLinearIssueContextSnapshot(makeIssue(), [ - makeComment({ id: 'invalid-b', body: 'Invalid B', createdAt: 'not-a-date' }), - makeComment({ id: 'valid-old', body: 'Valid old', createdAt: '2026-05-20T00:00:00.000Z' }), - makeComment({ id: 'valid-b', body: 'Valid B', createdAt: '2026-05-21T00:00:00.000Z' }), - makeComment({ id: 'valid-a', body: 'Valid A', createdAt: '2026-05-21T00:00:00.000Z' }), - makeComment({ id: 'invalid-a', body: 'Invalid A', createdAt: 'still-not-a-date' }) - ]) - - expect(snapshot.indexOf('Valid A')).toBeLessThan(snapshot.indexOf('Valid B')) - expect(snapshot.indexOf('Valid B')).toBeLessThan(snapshot.indexOf('Valid old')) - expect(snapshot.indexOf('Valid old')).toBeLessThan(snapshot.indexOf('Invalid A')) - expect(snapshot.indexOf('Invalid A')).toBeLessThan(snapshot.indexOf('Invalid B')) - }) - - it('caps long comment bodies with an explicit marker', () => { - const snapshot = buildLinearIssueContextSnapshot(makeIssue(), [ - makeComment({ - body: `start ${'x'.repeat(LINEAR_ISSUE_CONTEXT_CAPS.commentBodyChars + 50)} end` - }) - ]) - - expect(snapshot).toContain('start ') - expect(snapshot).toContain('[truncated]') - expect(snapshot).not.toContain(' end') - }) - - it('bounds inline metadata normalization for pasted-size Linear fields', () => { - const replace = vi.spyOn(String.prototype, 'replace') - const charCodeAt = vi.spyOn(String.prototype, 'charCodeAt') - const pastedTitle = `Fix\t pasted title ${' body\n'.repeat(40_000)}` - - const snapshot = buildLinearIssueContextSnapshot(makeIssue({ title: pastedTitle })) - - expect(snapshot).toContain('Title: Fix pasted title body body') - expect(snapshot.length).toBeLessThanOrEqual(LINEAR_ISSUE_CONTEXT_CAPS.renderedTextChars) - expect(charCodeAt.mock.calls.length).toBeLessThan(pastedTitle.length / 2) - expect( - replace.mock.calls.filter( - ([pattern]) => pattern instanceof RegExp && pattern.source === '\\s+' - ) - ).toHaveLength(0) - }) - it('applies the rendered text hard cap last and reserves the final overflow marker', () => { const subIssues = Array.from({ length: LINEAR_ISSUE_CONTEXT_CAPS.childIssues }, (_, index) => ({ id: `child-${index + 1}`, diff --git a/src/renderer/src/lib/monaco-languages/register-dotenv.test.ts b/src/renderer/src/lib/monaco-languages/register-dotenv.test.ts index 246ee86e475..290f02d3573 100644 --- a/src/renderer/src/lib/monaco-languages/register-dotenv.test.ts +++ b/src/renderer/src/lib/monaco-languages/register-dotenv.test.ts @@ -1,74 +1,13 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' + import { tokenizeMonarchDocument, tokenTypeAt } from './monarch-tokenizer-test-harness' -import { - DOTENV_LANGUAGE_ID, - dotenvLanguageConfiguration, - dotenvMonarchLanguage, - registerDotenvLanguage -} from './register-dotenv' +import { DOTENV_LANGUAGE_ID, dotenvMonarchLanguage } from './register-dotenv' function tokenizeDotenv(source: string) { return tokenizeMonarchDocument(DOTENV_LANGUAGE_ID, dotenvMonarchLanguage, source) } -function createMonacoMock(existingLanguageIds: string[] = []) { - return { - languages: { - getLanguages: vi.fn(() => existingLanguageIds.map((id) => ({ id }))), - register: vi.fn(), - setLanguageConfiguration: vi.fn(), - setMonarchTokensProvider: vi.fn() - } - } -} - -describe('registerDotenvLanguage', () => { - it('registers the dotenv language with a Monarch tokenizer', () => { - const monaco = createMonacoMock() - - registerDotenvLanguage(monaco) - - expect(monaco.languages.register).toHaveBeenCalledWith( - expect.objectContaining({ id: DOTENV_LANGUAGE_ID, filenames: ['.env'] }) - ) - expect(monaco.languages.setLanguageConfiguration).toHaveBeenCalledWith( - DOTENV_LANGUAGE_ID, - dotenvLanguageConfiguration - ) - expect(monaco.languages.setMonarchTokensProvider).toHaveBeenCalledWith( - DOTENV_LANGUAGE_ID, - dotenvMonarchLanguage - ) - }) - - it('is idempotent when the language already exists', () => { - const monaco = createMonacoMock([DOTENV_LANGUAGE_ID]) - - registerDotenvLanguage(monaco) - - expect(monaco.languages.register).not.toHaveBeenCalled() - expect(monaco.languages.setMonarchTokensProvider).not.toHaveBeenCalled() - }) -}) - describe('dotenv tokenization', () => { - it('colours comments, keys, the equals sign and values', () => { - const [comment, assignment] = tokenizeDotenv('# Database\nDB_HOST=localhost') - - expect(tokenTypeAt(comment, 0)).toBe('comment') - expect(tokenTypeAt(assignment, 0)).toBe('type.identifier') - expect(tokenTypeAt(assignment, 7)).toBe('delimiter') - expect(tokenTypeAt(assignment, 8)).toBe('string') - }) - - it('colours the export prefix', () => { - const [line] = tokenizeDotenv('export API_KEY=abc') - - expect(tokenTypeAt(line, 0)).toBe('keyword') - expect(tokenTypeAt(line, 7)).toBe('type.identifier') - expect(tokenTypeAt(line, 15)).toBe('string') - }) - it('colours quoted values, escapes and interpolation', () => { const [double, single, bare] = tokenizeDotenv( 'URL="https://${HOST}:$PORT\\n"\nRAW=\'${HOST}\'\nPATH=$HOME/bin' @@ -103,28 +42,10 @@ describe('dotenv tokenization', () => { expect(tokenTypeAt(next, 0)).toBe('type.identifier') }) - it('keeps a # without leading space inside the value', () => { - const [line] = tokenizeDotenv('COLOR=#fff') - - expect(tokenTypeAt(line, 6)).toBe('string') - }) - - it('ends an unquoted value at the end of its line', () => { - const [, next] = tokenizeDotenv('A=1 2 3\nB=2') - - expect(tokenTypeAt(next, 0)).toBe('type.identifier') - }) - it('lets a double-quoted value span lines, then resumes keys', () => { const [, middle, , after] = tokenizeDotenv('KEY="-----BEGIN\nMIIB==\n-----END"\nNEXT=1') expect(tokenTypeAt(middle, 0)).toBe('string') expect(tokenTypeAt(after, 0)).toBe('type.identifier') }) - - it('treats a blank line after a value as a fresh line', () => { - const [, , after] = tokenizeDotenv('A=1\n\n# note') - - expect(tokenTypeAt(after, 0)).toBe('comment') - }) }) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts index 919f9e07cd0..2fe4f5b9ac9 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-replay.test.ts @@ -3,7 +3,7 @@ import type { SleepingAgentSessionRecord } from '../../../shared/agent-session-r import { useAppStore } from '@/store' import { resumeSleepingAgentSessionsForWorktree } from './resume-sleeping-agent-session' import { launchAiVaultSessionInNewTab } from './launch-ai-vault-session' -import { buildWorkspaceSessionPayload } from './workspace-session' + import { createStoreSessionMockApi } from '../store/slices/store-session-test-harness' const initialAppStoreState = useAppStore.getState() @@ -84,26 +84,6 @@ describe('resumeSleepingAgentSessionsForWorktree replay protection', () => { expect(firstVisible?.layout?.activeLeafId).toBe(root?.type === 'leaf' ? root.leafId : undefined) }) - it('stores provider-session metadata in the queued startup and runtime claim', () => { - const record = makeRecord() - useAppStore.setState({ - tabsByWorktree: { 'wt-1': [] }, - sleepingAgentSessionsByPaneKey: { [record.paneKey]: record } - } as never) - - expect(resumeSleepingAgentSessionsForWorktree('wt-1')).toBe(1) - const resumedTab = useAppStore.getState().tabsByWorktree['wt-1']![0]! - const state = useAppStore.getState() - expect(state.pendingStartupByTabId[resumedTab.id]?.resumeProviderSession).toEqual( - record.providerSession - ) - expect(state.automaticAgentResumeClaimsByTabId[resumedTab.id]).toEqual({ - worktreeId: record.worktreeId, - launchAgent: record.agent, - providerSession: record.providerSession - }) - }) - it('does not fork a provider session that is already queued', () => { const record = makeRecord() useAppStore.setState({ @@ -206,23 +186,6 @@ describe('resumeSleepingAgentSessionsForWorktree replay protection', () => { expect(useAppStore.getState().automaticAgentResumeClaimsByTabId[resumedTab.id]).toBeUndefined() }) - it('does not include runtime automatic-resume claims in workspace-session payloads', () => { - useAppStore.setState({ - tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1')] }, - automaticAgentResumeClaimsByTabId: { - 'tab-1': { - worktreeId: 'wt-1', - launchAgent: 'codex', - providerSession: { key: 'session_id', id: 'sess-1' } - } - } - } as never) - - const payload = buildWorkspaceSessionPayload(useAppStore.getState()) - - expect('automaticAgentResumeClaimsByTabId' in payload).toBe(false) - }) - it('leaves explicit AI Vault resumes outside automatic-resume claims', () => { useAppStore.setState({ tabsByWorktree: { 'wt-1': [] } } as never) diff --git a/src/renderer/src/lib/resume-sleeping-agent-session-retired-binding.test.ts b/src/renderer/src/lib/resume-sleeping-agent-session-retired-binding.test.ts index 085a89bc8ff..29e91217463 100644 --- a/src/renderer/src/lib/resume-sleeping-agent-session-retired-binding.test.ts +++ b/src/renderer/src/lib/resume-sleeping-agent-session-retired-binding.test.ts @@ -101,18 +101,6 @@ describe('a resume record whose pane has no terminal bound', () => { expect(mocks.launch).toHaveBeenCalledWith(record, undefined) }) - it('a start that settled, or a disposed pane, no longer owns it', () => { - mocks.layoutOwnerIsMain = true - retiredBindingState() - holdPaneResumeInPlace(PANE_KEY, () => true)() - const disposedRelease = holdPaneResumeInPlace(PANE_KEY, () => false) - try { - expect(recordPaneIsOwnedByPreservedPane(record, useAppStore.getState())).toBe(false) - } finally { - disposedRelease() - } - }) - it('keeps the window-owned rule: an unbound pane does not own it, in flight or not', () => { retiredBindingState() const release = holdPaneResumeInPlace(PANE_KEY, () => true) diff --git a/src/renderer/src/store/slices/active-tab-owner-worktree.test.ts b/src/renderer/src/store/slices/active-tab-owner-worktree.test.ts index 8a04f79ce4b..d569adf2f44 100644 --- a/src/renderer/src/store/slices/active-tab-owner-worktree.test.ts +++ b/src/renderer/src/store/slices/active-tab-owner-worktree.test.ts @@ -19,22 +19,6 @@ beforeEach(() => { }) describe('resolveActiveTabOwnerWorktreeId', () => { - it('returns the sole owner and stays quiet', () => { - const owner = resolveActiveTabOwnerWorktreeId( - { 'wt-a': [tab('t1', 'wt-a')], 'wt-b': [tab('t2', 'wt-b')] }, - 'wt-a', - 't1' - ) - expect(owner).toBe('wt-a') - expect(recordRendererCrashBreadcrumb).not.toHaveBeenCalled() - }) - - it('returns null when no worktree owns the tab', () => { - expect(resolveActiveTabOwnerWorktreeId({ 'wt-a': [tab('t1', 'wt-a')] }, 'wt-a', 'gone')).toBe( - null - ) - }) - it('prefers the active worktree over an earlier-scanned duplicate', () => { const owner = resolveActiveTabOwnerWorktreeId( { 'wt-other': [tab('t1', 'wt-other')], 'wt-active': [tab('t1', 'wt-active')] }, @@ -70,52 +54,4 @@ describe('resolveActiveTabOwnerWorktreeId', () => { ) expect(owner).toBe('') }) - - it('breadcrumbs a given tab id once per verdict so it cannot flood the ring', () => { - const maps = { 'wt-a': [tab('t1', 'wt-a')], 'wt-b': [tab('t1', 'wt-b')] } - for (let i = 0; i < 5; i += 1) { - resolveActiveTabOwnerWorktreeId(maps, 'wt-a', 't1') - } - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(1) - }) - - // Duplicates can change verdict across worktree switches; once-per-tab guards would coalesce away one verdict forever. - it('still reports a non-converging verdict after that tab id reported a converging one', () => { - const maps = { 'wt-other': [tab('t1', 'wt-other')], 'wt-active': [tab('t1', 'wt-active')] } - resolveActiveTabOwnerWorktreeId(maps, 'wt-active', 't1') - resolveActiveTabOwnerWorktreeId(maps, 'wt-third', 't1') - resolveActiveTabOwnerWorktreeId(maps, 'wt-third', 't1') - - expect(recordRendererCrashBreadcrumb.mock.calls).toEqual([ - [ - 'terminal_tab_id_owned_by_multiple_worktrees', - { ownerCount: 2, resolvedToActiveWorktree: true } - ], - [ - 'terminal_tab_id_owned_by_multiple_worktrees', - { ownerCount: 2, resolvedToActiveWorktree: false } - ] - ]) - }) - - // Require counts too: per-worktree dedupe passes earlier cases but floods per tab ID. - it('never exceeds two crumbs for one tab id however the active worktree moves', () => { - const maps = { 'wt-a': [tab('t1', 'wt-a')], 'wt-b': [tab('t1', 'wt-b')] } - const activeWorktreeIds = ['wt-a', 'wt-b', 'wt-c', '', 'wt-d', 'wt-a'] - for (let i = 0; i < 600; i += 1) { - resolveActiveTabOwnerWorktreeId(maps, activeWorktreeIds[i % activeWorktreeIds.length], 't1') - } - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(2) - }) - - // Why: the guard set is never pruned and tab ids are minted per created tab. - it('stops recording once the per-session sample cap is reached', () => { - for (let i = 0; i < 400; i += 1) { - const id = `t-${i}` - const maps = { 'wt-a': [tab(id, 'wt-a')], 'wt-b': [tab(id, 'wt-b')] } - resolveActiveTabOwnerWorktreeId(maps, 'wt-a', id) - resolveActiveTabOwnerWorktreeId(maps, 'wt-c', id) - } - expect(recordRendererCrashBreadcrumb).toHaveBeenCalledTimes(256) - }) }) diff --git a/src/renderer/src/store/slices/browser-webview-cleanup.test.ts b/src/renderer/src/store/slices/browser-webview-cleanup.test.ts deleted file mode 100644 index 22f448b12f8..00000000000 --- a/src/renderer/src/store/slices/browser-webview-cleanup.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { BrowserPage, BrowserWorkspace } from '../../../../shared/browser-workspace-types' - -vi.mock('../../components/browser-pane/host-guest/webview-registry', () => ({ - destroyPersistentWebview: vi.fn() -})) - -import { - collectBrowserWebviewIds, - destroyWorkspaceWebviews, - destroyWorktreeBrowserGuests -} from './browser-webview-cleanup' -import { destroyPersistentWebview } from '../../components/browser-pane/host-guest/webview-registry' - -function workspace(id: string): BrowserWorkspace { - return { - id, - worktreeId: 'wt-1', - label: id, - sessionProfileId: null, - pageIds: [], - activePageId: null, - url: 'about:blank', - title: id, - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } -} - -function page(id: string, workspaceId: string): BrowserPage { - return { - id, - workspaceId, - worktreeId: 'wt-1', - url: 'about:blank', - title: id, - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } -} - -describe('collectBrowserWebviewIds', () => { - it('tracks browser page ids because webviews are keyed by page id', () => { - const ids = collectBrowserWebviewIds( - { 'wt-1': [workspace('workspace-1')] }, - { 'workspace-1': [page('page-1', 'workspace-1'), page('page-2', 'workspace-1')] } - ) - - expect([...ids].sort()).toEqual(['page-1', 'page-2']) - }) - - it('keeps legacy workspace ids only when no page records exist', () => { - const ids = collectBrowserWebviewIds({ 'wt-1': [workspace('legacy-workspace')] }, {}) - - expect([...ids]).toEqual(['legacy-workspace']) - }) -}) - -describe('destroyWorkspaceWebviews', () => { - beforeEach(() => { - vi.mocked(destroyPersistentWebview).mockClear() - }) - - it('destroys every page id for a multi-page workspace', () => { - destroyWorkspaceWebviews( - { 'workspace-1': [page('page-1', 'workspace-1'), page('page-2', 'workspace-1')] }, - 'workspace-1' - ) - - expect(destroyPersistentWebview).toHaveBeenCalledTimes(2) - expect(destroyPersistentWebview).toHaveBeenCalledWith('page-1') - expect(destroyPersistentWebview).toHaveBeenCalledWith('page-2') - }) - - it('falls back to the workspace id when no pages exist (legacy sessions)', () => { - destroyWorkspaceWebviews({}, 'legacy-workspace') - - expect(destroyPersistentWebview).toHaveBeenCalledTimes(1) - expect(destroyPersistentWebview).toHaveBeenCalledWith('legacy-workspace') - }) - - it('falls back to the workspace id when the workspace key is present but empty', () => { - destroyWorkspaceWebviews({ 'workspace-1': [] }, 'workspace-1') - - expect(destroyPersistentWebview).toHaveBeenCalledTimes(1) - expect(destroyPersistentWebview).toHaveBeenCalledWith('workspace-1') - }) -}) - -describe('destroyWorktreeBrowserGuests', () => { - beforeEach(() => { - vi.mocked(destroyPersistentWebview).mockClear() - }) - - it('destroys every guest across all of one worktree tabs, leaving other worktrees alone', () => { - destroyWorktreeBrowserGuests( - { - 'wt-1': [workspace('workspace-1'), workspace('legacy-workspace')], - 'wt-2': [workspace('workspace-2')] - }, - { - 'workspace-1': [page('page-1', 'workspace-1'), page('page-2', 'workspace-1')], - 'workspace-2': [page('page-3', 'workspace-2')] - }, - 'wt-1' - ) - - expect(destroyPersistentWebview).toHaveBeenCalledTimes(3) - expect(destroyPersistentWebview).toHaveBeenCalledWith('page-1') - expect(destroyPersistentWebview).toHaveBeenCalledWith('page-2') - // Legacy tabs without page records key their webview by the tab id. - expect(destroyPersistentWebview).toHaveBeenCalledWith('legacy-workspace') - expect(destroyPersistentWebview).not.toHaveBeenCalledWith('page-3') - }) - - it('is a no-op for a worktree without browser tabs', () => { - destroyWorktreeBrowserGuests({}, {}, 'wt-1') - - expect(destroyPersistentWebview).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts b/src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts index 90c838f54cc..935994a604e 100644 --- a/src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts +++ b/src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts @@ -22,59 +22,6 @@ describe('fetchHostWorkspaceStatuses', () => { callRuntimeRpc.mockReset() }) - it("stores the host's columns from ui.get without touching the local list", async () => { - callRuntimeRpc.mockResolvedValue({ ui: { workspaceStatuses: hostColumns } }) - const store = createUIStore() - const local = store.getState().workspaceStatuses - - await store.getState().fetchHostWorkspaceStatuses('env-1') - - expect(callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'ui.get', - undefined, - expect.anything() - ) - expect(store.getState().hostWorkspaceStatuses['env-1']?.map((status) => status.id)).toEqual([ - 'status-8', - 'status-6', - 'in-progress' - ]) - expect(store.getState().workspaceStatuses).toBe(local) - }) - - it('keeps the last columns when the host is unreachable', async () => { - const store = createUIStore() - callRuntimeRpc.mockResolvedValueOnce({ ui: { workspaceStatuses: hostColumns } }) - await store.getState().fetchHostWorkspaceStatuses('env-1') - callRuntimeRpc.mockRejectedValueOnce(new Error('offline')) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - await store.getState().fetchHostWorkspaceStatuses('env-1') - - expect(store.getState().hostWorkspaceStatuses['env-1']).toHaveLength(3) - }) - - it('stores no columns, not the defaults, when the host sends none', async () => { - callRuntimeRpc.mockResolvedValue({ ui: {} }) - const store = createUIStore() - - await store.getState().fetchHostWorkspaceStatuses('env-1') - - expect(store.getState().hostWorkspaceStatuses['env-1'] ?? []).toEqual([]) - }) - - it('keeps the stored list identity when the host resends the same columns', async () => { - callRuntimeRpc.mockResolvedValue({ ui: { workspaceStatuses: hostColumns } }) - const store = createUIStore() - await store.getState().fetchHostWorkspaceStatuses('env-1') - const first = store.getState().hostWorkspaceStatuses - - await store.getState().fetchHostWorkspaceStatuses('env-1') - - expect(store.getState().hostWorkspaceStatuses).toBe(first) - }) - it('drops a reply that arrives after a newer one', async () => { let answerOld: (value: unknown) => void = () => {} callRuntimeRpc