diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index ec1777d2172..3340e663dad 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -38,7 +38,6 @@ 1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts 5 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli.test.ts 1 test-no-polling-loop:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts -3 test-no-polling-loop:src/main/cli/packaged-cli-assets.test.ts 1 test-no-polling-loop:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts 1 test-no-polling-loop:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts 1 test-no-polling-loop:src/main/daemon/providers/adapter/testing/daemon-self-retirement-respawn.test.ts @@ -170,7 +169,6 @@ 2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts 5 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli.test.ts 1 test-no-real-time-wait:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts -3 test-no-real-time-wait:src/main/cli/packaged-cli-assets.test.ts 3 test-no-real-time-wait:src/main/codex/hooks/installation/hook-service-concurrent-launch-install.test.ts 1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts 1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts @@ -471,8 +469,7 @@ 3 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts 10 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli.test.ts 3 test-no-wall-clock:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts -1 test-no-wall-clock:src/main/cli/appimage-generation-lease.test.ts -6 test-no-wall-clock:src/main/cli/packaged-cli-assets.test.ts +1 test-no-wall-clock:src/main/cli/appimage/appimage-generation-lease.test.ts 1 test-no-wall-clock:src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts 6 test-no-wall-clock:src/main/codex/app-server/codex-app-server-client.test.ts 1 test-no-wall-clock:src/main/codex/structured/catalog/codex-usage-limits.test.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index a0f1c1fedf6..0f9c05a98e5 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -97,18 +97,18 @@ 1 src/main/claude/hook-service.ts 3 src/main/claude/statusline-install.ts 6 src/main/claude/windows-hook-files.ts -1 src/main/cli/appimage-copy-pre-extraction.ts -3 src/main/cli/appimage-extracted-root.ts -1 src/main/cli/appimage-extraction-pruning.ts -2 src/main/cli/appimage-generation-lease.ts -4 src/main/cli/appimage-generation-residency.ts -16 src/main/cli/appimage-stable-launcher.ts -1 src/main/cli/cli-command-inspection.ts -1 src/main/cli/cli-dev-launcher.ts -3 src/main/cli/cli-install-location.ts -2 src/main/cli/linux-bare-orca-dispatcher.ts -7 src/main/cli/linux-terminal-orca-cli-shim.ts -2 src/main/cli/wsl-managed-cli.ts +1 src/main/cli/appimage/appimage-copy-pre-extraction.ts +3 src/main/cli/appimage/appimage-extracted-root.ts +1 src/main/cli/appimage/appimage-extraction-pruning.ts +2 src/main/cli/appimage/appimage-generation-lease.ts +4 src/main/cli/appimage/appimage-generation-residency.ts +16 src/main/cli/appimage/appimage-stable-launcher.ts +1 src/main/cli/installation/cli-command-inspection.ts +1 src/main/cli/launchers/cli-dev-launcher.ts +3 src/main/cli/installation/cli-install-location.ts +2 src/main/cli/launchers/linux-bare-orca-dispatcher.ts +7 src/main/cli/launchers/linux-terminal-orca-cli-shim.ts +2 src/main/cli/wsl/wsl-managed-cli.ts 2 src/main/codex-accounts/codex-account-identity.ts 3 src/main/codex-accounts/codex-account-registration.ts 4 src/main/codex-accounts/codex-config-mirror.ts @@ -173,7 +173,7 @@ 1 src/main/computer/sidecar-client.ts 3 src/main/connector-cloud/connector-turn-events.ts 1 src/main/copilot/hook-service.ts -4 src/main/crash-reporting/appimage-crashpad-handler-exit.ts +4 src/main/crash-reporting/capture/appimage-crashpad-handler-exit.ts 2 src/main/credentials/credential-file-protection.ts 6 src/main/credentials/encrypted-api-key-file-store.ts 10 src/main/credentials/integration-credential-file.ts diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index 6e17989d975..214d50ab346 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -12,12 +12,12 @@ 1 src/main/browser/extensions/native-messaging/browser-extension-native-ports.ts 1 src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts 1 src/main/claude/agent-view/agent-view-bridge.ts -1 src/main/cli/appimage-serve-preparation.ts +1 src/main/cli/appimage/appimage-serve-preparation.ts 1 src/main/codex-accounts/codex-login-session.ts 1 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts -1 src/main/crash-reporting/pre-gone-host-memory.ts -1 src/main/crash-reporting/process-gone-diagnostics.ts -1 src/main/crash-reporting/renderer-heap-allocation-profile.ts +1 src/main/crash-reporting/memory/pre-gone-host-memory.ts +1 src/main/crash-reporting/process-exits/process-gone-diagnostics.ts +1 src/main/crash-reporting/memory/renderer-heap-allocation-profile.ts 1 src/main/daemon/admission/host-terminal-ledger.ts 1 src/main/daemon/admission/host-terminal-policy.ts 1 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 8cf359de2a9..37d9ee4e23a 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -1210,40 +1210,37 @@ "src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts": 902, "src/main/claude/windows-hook-files.test.ts": 356, "src/main/claude/windows-native-hook-registration.test.ts": 246, - "src/main/cli/appimage-copy-pre-extraction.test.ts": 328, - "src/main/cli/appimage-extracted-root.test.ts": 140, - "src/main/cli/appimage-extraction-pruning-namespace.test.ts": 106, - "src/main/cli/appimage-extraction-pruning.test.ts": 117, - "src/main/cli/appimage-generation-lease.test.ts": 75, - "src/main/cli/appimage-generation-residency.test.ts": 41, - "src/main/cli/appimage-payload-removal.reentrancy.test.ts": 46, - "src/main/cli/appimage-serve-preparation.test.ts": 123, - "src/main/cli/appimage-stable-launcher.test.ts": 135, - "src/main/cli/cli-command-installation-races.test.ts": 215, - "src/main/cli/cli-command-privileged-transaction.test.ts": 125, - "src/main/cli/cli-installer-appimage-ownership.test.ts": 212, - "src/main/cli/cli-installer-appimage-removal.test.ts": 320, - "src/main/cli/cli-installer-command-conflicts.test.ts": 200, - "src/main/cli/cli-installer-macos-command-path.test.ts": 221, - "src/main/cli/cli-installer-unreadable-command.test.ts": 183, - "src/main/cli/cli-installer-windows-path.test.ts": 195, + "src/main/cli/appimage/appimage-copy-pre-extraction.test.ts": 328, + "src/main/cli/appimage/appimage-extracted-root.test.ts": 140, + "src/main/cli/appimage/appimage-extraction-pruning-namespace.test.ts": 106, + "src/main/cli/appimage/appimage-extraction-pruning.test.ts": 117, + "src/main/cli/appimage/appimage-generation-lease.test.ts": 75, + "src/main/cli/appimage/appimage-generation-residency.test.ts": 41, + "src/main/cli/appimage/appimage-serve-preparation.test.ts": 123, + "src/main/cli/appimage/appimage-stable-launcher.test.ts": 135, + "src/main/cli/installation/cli-command-installation-races.test.ts": 215, + "src/main/cli/installation/cli-command-privileged-transaction.test.ts": 125, + "src/main/cli/installation/cli-installer-appimage-ownership.test.ts": 212, + "src/main/cli/installation/cli-installer-command-conflicts.test.ts": 200, + "src/main/cli/installation/cli-installer-macos-command-path.test.ts": 221, + "src/main/cli/installation/cli-installer-unreadable-command.test.ts": 183, + "src/main/cli/installation/cli-installer-windows-path.test.ts": 195, "src/main/cli/cli-installer.test.ts": 294, - "src/main/cli/keyed-promise-queue.test.ts": 41, - "src/main/cli/legacy-appimage-cli-wrapper.test.ts": 38, - "src/main/cli/linux-bare-orca-dispatcher-script.test.ts": 272, - "src/main/cli/linux-bare-orca-dispatcher.test.ts": 132, - "src/main/cli/linux-terminal-orca-cli-shim.test.ts": 149, - "src/main/cli/native-cli-powershell-argv-boundary.test.ts": 59, - "src/main/cli/orca-cli-child-path.test.ts": 93, - "src/main/cli/packaged-cli-assets.test.ts": 6862, - "src/main/cli/windows-user-path-registry.test.ts": 49, - "src/main/cli/workspace-choice-argv-boundary.test.ts": 293, - "src/main/cli/wsl-cli-installer.test.ts": 309, - "src/main/cli/wsl-cli-powershell-boundary.test.ts": 104, - "src/main/cli/wsl-cli-registration-reconciliation.test.ts": 386, - "src/main/cli/wsl-cli-registration-registry.test.ts": 150, - "src/main/cli/wsl-managed-cli.test.ts": 66, - "src/main/cli/wsl-managed-cli.wsl.test.ts": 115, + "src/shared/concurrency/keyed-serialized-operations.test.ts": 41, + "src/main/cli/appimage/legacy-appimage-cli-wrapper.test.ts": 38, + "src/main/cli/launchers/linux-bare-orca-dispatcher-script.test.ts": 272, + "src/main/cli/launchers/linux-bare-orca-dispatcher.test.ts": 132, + "src/main/cli/launchers/linux-terminal-orca-cli-shim.test.ts": 149, + "src/main/cli/launchers/native-cli-powershell-argv-boundary.test.ts": 59, + "src/main/cli/launchers/orca-cli-child-path.test.ts": 93, + "src/main/cli/packaged-assets/packaged-cli-assets.test.ts": 6862, + "src/main/cli/command-paths/windows-user-path-registry.test.ts": 49, + "src/main/cli/launchers/workspace-choice-argv-boundary.test.ts": 293, + "src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts": 104, + "src/main/cli/wsl/wsl-cli-registration-reconciliation.test.ts": 386, + "src/main/cli/wsl/wsl-cli-registration-registry.test.ts": 150, + "src/main/cli/wsl/wsl-managed-cli.test.ts": 66, + "src/main/cli/wsl/wsl-managed-cli.wsl.test.ts": 115, "src/main/codebuddy/hook-service.test.ts": 272, "src/main/codex-accounts/async-file-rename.test.ts": 1065, "src/main/codex-accounts/codex-account-identity-api-key-guard.test.ts": 55, @@ -1498,27 +1495,21 @@ "src/main/connector-cloud/connector-token-mint.test.ts": 117, "src/main/connector-cloud/connector-turn-events.test.ts": 411, "src/main/copilot/hook-service.test.ts": 180, - "src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts": 60, - "src/main/crash-reporting/crash-breadcrumb-store-leak.test.ts": 89, - "src/main/crash-reporting/crash-breadcrumb-store-orphan-cleanup.test.ts": 81, - "src/main/crash-reporting/crash-report-copy-text.test.ts": 66, - "src/main/crash-reporting/crash-report-store.test.ts": 438, - "src/main/crash-reporting/crashpad-capture-read-limit.test.ts": 298, - "src/main/crash-reporting/crashpad-capture.test.ts": 107, - "src/main/crash-reporting/durable-crash-breadcrumb.test.ts": 60, - "src/main/crash-reporting/gpu-crash-diagnostics.test.ts": 55, - "src/main/crash-reporting/gpu-crash-fallback-decision.test.ts": 45, - "src/main/crash-reporting/gpu-fallback-engagement.test.ts": 47, - "src/main/crash-reporting/minidump-crash-signature.test.ts": 87, - "src/main/crash-reporting/minidump-fault-context.test.ts": 57, - "src/main/crash-reporting/minidump-file-source.test.ts": 199, - "src/main/crash-reporting/pre-gone-host-memory.test.ts": 110, - "src/main/crash-reporting/process-gone-dedupe.test.ts": 46, - "src/main/crash-reporting/process-gone-killed-one-ordering.test.ts": 161, - "src/main/crash-reporting/process-gone-recorder.test.ts": 787, - "src/main/crash-reporting/process-gone-sibling-correlation.test.ts": 743, - "src/main/crash-reporting/renderer-heap-allocation-sites.test.ts": 62, - "src/main/crash-reporting/renderer-recovery-circuit-breaker.test.ts": 45, + "src/main/crash-reporting/breadcrumbs/crash-breadcrumb-renderer-attribution.test.ts": 60, + "src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store-orphan-cleanup.test.ts": 81, + "src/main/crash-reporting/reports/crash-report-store.test.ts": 438, + "src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.test.ts": 60, + "src/main/crash-reporting/capture/gpu-crash-diagnostics.test.ts": 55, + "src/main/crash-reporting/recovery/gpu-crash-fallback-decision.test.ts": 45, + "src/main/crash-reporting/recovery/gpu-fallback-engagement.test.ts": 47, + "src/main/crash-reporting/minidumps/minidump-crash-signature.test.ts": 87, + "src/main/crash-reporting/minidumps/minidump-fault-context.test.ts": 57, + "src/main/crash-reporting/minidumps/minidump-file-source.test.ts": 199, + "src/main/crash-reporting/process-exits/process-gone-dedupe.test.ts": 46, + "src/main/crash-reporting/process-exits/process-gone-recorder.test.ts": 787, + "src/main/crash-reporting/process-exits/process-gone-sibling-correlation.test.ts": 743, + "src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts": 62, + "src/main/crash-reporting/recovery/renderer-recovery-circuit-breaker.test.ts": 45, "src/main/credentials/saved-credential-readability.test.ts": 56, "src/main/cursor/hook-command.live-shell.test.ts": 488, "src/main/cursor/hook-service.test.ts": 360, diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 5a1587da349..f11b8563b25 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -195,7 +195,7 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/wsl/execution/wsl-executable-path.win32.test.ts', 'src/main/claude-accounts/claude-profile-history-windows.test.ts', 'src/shared/source-scan/source-tree-scan.test.ts', - 'src/main/cli/wsl-cli-powershell-boundary.test.ts', + 'src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts', 'src/main/computer/desktop-script-runtime-host.win32.test.ts', 'src/main/cursor/hook-service.test.ts', 'src/main/orca-profiles/profile-index-store.test.ts', diff --git a/src/main/automations/service.ts b/src/main/automations/service.ts index 68a601cf861..e25759b4b10 100644 --- a/src/main/automations/service.ts +++ b/src/main/automations/service.ts @@ -20,7 +20,7 @@ import { } from './run-target-resolution' import { writeAutomationRunUsage } from './run-usage-collection' import type { AutomationLauncher, AutomationTerminalLauncher } from './automation-launch' -import { runKeyedSerializedOperation } from '../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' import { clearAutomationDispatchTokens } from './dispatch-tokens' import { AutomationRunCompletionWatcher, diff --git a/src/main/claude-accounts/claude-login-process-termination.ts b/src/main/claude-accounts/claude-login-process-termination.ts index 633ebc34236..f9c8f00fc2f 100644 --- a/src/main/claude-accounts/claude-login-process-termination.ts +++ b/src/main/claude-accounts/claude-login-process-termination.ts @@ -1,7 +1,7 @@ import { spawnProcess } from '@orca/process-host' import type { ChildProcess } from 'node:child_process' import type { WindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn' -import { recordSelfInitiatedTreeKill } from '../crash-reporting/self-initiated-tree-kill-log' +import { recordSelfInitiatedTreeKill } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' import { admitSelfInitiatedTreeKill } from '../pty/process-retirement/own-chromium-tree-kill-guard' const WINDOWS_TASKKILL_TIMEOUT_MS = 5_000 diff --git a/src/main/claude/claude-folder-trust-file.ts b/src/main/claude/claude-folder-trust-file.ts index a89705f5700..42d3fdbf709 100644 --- a/src/main/claude/claude-folder-trust-file.ts +++ b/src/main/claude/claude-folder-trust-file.ts @@ -14,7 +14,7 @@ import { homedir } from 'node:os' import { lock } from 'proper-lockfile' import '../filesystem/atomic-file-publication' import { renameFileWithWindowsRetry } from '../../shared/windows-retry-file-operations' -import { runKeyedSerializedOperation } from '../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' import { parseWslUncPath } from '../../shared/wsl-paths' import { runWslProcess } from '../wsl/execution/wsl-runner' import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth/runtime-auth-types' diff --git a/src/main/cli/appimage-payload-removal.reentrancy.test.ts b/src/main/cli/appimage-payload-removal.reentrancy.test.ts deleted file mode 100644 index d144758d378..00000000000 --- a/src/main/cli/appimage-payload-removal.reentrancy.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -// Deferred removals make overlap ordering deterministic. -const { rmMock } = vi.hoisted(() => ({ rmMock: vi.fn() })) -vi.mock('node:fs/promises', () => ({ rm: rmMock })) - -const originalNoAsar = process.noAsar - -afterEach(() => { - process.noAsar = originalNoAsar - vi.resetModules() -}) - -function deferred(): { promise: Promise; resolve: () => void } { - let resolve!: () => void - const promise = new Promise((r) => { - resolve = r - }) - return { promise, resolve } -} - -describe('removeExtractedAppImagePayload reentrancy', () => { - it('keeps the flag held when the first removal rejects mid-overlap', async () => { - process.noAsar = false - const second = deferred() - rmMock.mockReset() - rmMock.mockRejectedValueOnce(new Error('EACCES')).mockReturnValueOnce(second.promise) - const { removeExtractedAppImagePayload } = await import('./appimage-payload-removal') - - const firstCall = removeExtractedAppImagePayload('/cache/gen-a') - const secondCall = removeExtractedAppImagePayload('/cache/gen-b') - - await expect(firstCall).rejects.toThrow('EACCES') - expect(process.noAsar).toBe(true) - - second.resolve() - await secondCall - expect(process.noAsar).toBe(false) - }) -}) diff --git a/src/main/cli/appimage-cache-layout.ts b/src/main/cli/appimage/appimage-cache-layout.ts similarity index 83% rename from src/main/cli/appimage-cache-layout.ts rename to src/main/cli/appimage/appimage-cache-layout.ts index 4d0c4d056ec..228e9e0f3de 100644 --- a/src/main/cli/appimage-cache-layout.ts +++ b/src/main/cli/appimage/appimage-cache-layout.ts @@ -1,8 +1,6 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path' -import { isAppImageCacheKey } from '../../shared/appimage-cache-identity' -import { LINUX_CLI_COMMAND_NAME } from './bundled-cli-launcher-path' - -export { isAppImageCacheKey } +import { isAppImageCacheKey } from '../../../shared/appimage-cache-identity' +import { LINUX_CLI_COMMAND_NAME } from '../packaged-assets/bundled-cli-launcher-path' export function resolveCachedAppImagePayloadRoot( cacheRootPath: string, diff --git a/src/main/cli/appimage-copy-pre-extraction.test.ts b/src/main/cli/appimage/appimage-copy-pre-extraction.test.ts similarity index 79% rename from src/main/cli/appimage-copy-pre-extraction.test.ts rename to src/main/cli/appimage/appimage-copy-pre-extraction.test.ts index cc7df714320..7d42a828eee 100644 --- a/src/main/cli/appimage-copy-pre-extraction.test.ts +++ b/src/main/cli/appimage/appimage-copy-pre-extraction.test.ts @@ -39,28 +39,6 @@ async function writePayload(cwd: string): Promise { const acceptCache = async (): Promise => null -describe('startAppImageCopyPreExtraction', () => { - it('unpacks a missing copy in the background without taking the CLI launcher', async () => { - const { appImagePath, cacheRootPath } = await makeFixture() - const lines: string[] = [] - - const started = preExtraction.startAppImageCopyPreExtraction({ - appImagePath, - cacheRootPath, - probeCache: acceptCache, - runExtract: async (_path, cwd) => writePayload(cwd), - log: (line) => lines.push(line) - }) - - expect(await started).toBe(true) - expect(await preExtraction.waitForAppImageCopyPreExtraction(10)).toBe(true) - const copy = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - expect(existsSync(copy.payloadLauncherPath)).toBe(true) - expect(existsSync(resolveAppImageLauncherEndpointPath(cacheRootPath, 'installed'))).toBe(false) - expect(lines.at(-1)).toContain('Unpacked this AppImage') - }) -}) - describe('preExtractDownloadedAppImageUpdate', () => { it('unpacks the download into the copy its install will run from', async () => { const { root, appImagePath, cacheRootPath } = await makeFixture() diff --git a/src/main/cli/appimage-copy-pre-extraction.ts b/src/main/cli/appimage/appimage-copy-pre-extraction.ts similarity index 98% rename from src/main/cli/appimage-copy-pre-extraction.ts rename to src/main/cli/appimage/appimage-copy-pre-extraction.ts index 64852fb3185..15371e6acd0 100644 --- a/src/main/cli/appimage-copy-pre-extraction.ts +++ b/src/main/cli/appimage/appimage-copy-pre-extraction.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { lstat, stat } from 'node:fs/promises' import { basename, dirname, isAbsolute, join } from 'node:path' -import { resolveAppImageRuntimeIdentity } from '../updater/linux-package/appimage-runtime-identity' +import { resolveAppImageRuntimeIdentity } from '../../updater/linux-package/appimage-runtime-identity' import { isAppImageExtractionComplete, resolveAppImageCacheRootPath, diff --git a/src/main/cli/appimage-extracted-root.test.ts b/src/main/cli/appimage/appimage-extracted-root.test.ts similarity index 51% rename from src/main/cli/appimage-extracted-root.test.ts rename to src/main/cli/appimage/appimage-extracted-root.test.ts index d30914ddd4c..2e3df492a27 100644 --- a/src/main/cli/appimage-extracted-root.test.ts +++ b/src/main/cli/appimage/appimage-extracted-root.test.ts @@ -1,15 +1,9 @@ -import { existsSync } from 'node:fs' -import { mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readdir, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { - ensureAppImageExtractedRoot, - readAppImageSourceOfNamespace, - resolveAppImageExtractedRoot -} from './appimage-extracted-root' -import { getAppImageActiveExtractionPath } from './appimage-extraction-pruning' -import { resolveAppImageStableLauncherPath } from './appimage-stable-launcher' +import { ensureAppImageExtractedRoot } from './appimage-extracted-root' +import { readAppImageSourceOfNamespace } from '../../../shared/appimage-cache-identity' const created: string[] = [] @@ -69,28 +63,6 @@ describe('appimage extracted root', () => { await expect(readdir(cacheRootPath)).resolves.toEqual([]) }) - it('retains one retry payload when a foreign stable launcher blocks publication', async () => { - const { appImagePath, cacheRootPath } = await makeFixture() - const root = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - const launcherPath = resolveAppImageStableLauncherPath(cacheRootPath) - let extractionCount = 0 - await mkdir(dirname(launcherPath), { recursive: true }) - await writeFile(launcherPath, '#!/usr/bin/env bash\nprintf foreign\n', { mode: 0o755 }) - - const extract = async (_path: string, cwd: string): Promise => { - extractionCount += 1 - await writePayload(cwd) - } - const options = { appImagePath, cacheRootPath, runExtract: extract } - - await expect(ensureAppImageExtractedRoot(options)).resolves.toBeNull() - await expect(ensureAppImageExtractedRoot(options)).resolves.toBeNull() - expect(extractionCount).toBe(1) - expect(existsSync(root.rootPath)).toBe(true) - expect(existsSync(getAppImageActiveExtractionPath(root.rootPath))).toBe(false) - await expect(readFile(launcherPath, 'utf8')).resolves.toContain('foreign') - }) - it.each(['directory', 'non-executable'] as const)( 'rejects a %s launcher entry', async (entryKind) => { @@ -134,60 +106,4 @@ describe('appimage extracted root', () => { expect(result).toBeNull() } ) - - it('preserves the winner when concurrent calls repair an incomplete root', async () => { - const { appImagePath, cacheRootPath } = await makeFixture() - const root = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - await mkdir(root.rootPath, { recursive: true }) - await writeFile(join(root.rootPath, 'partial'), 'interrupted') - let readyCount = 0 - let release!: () => void - const bothReady = new Promise((resolve) => { - release = resolve - }) - const runExtract = async (_path: string, cwd: string): Promise => { - readyCount += 1 - await writePayload(cwd, `winner-${readyCount}`) - if (readyCount === 2) { - release() - } - await bothReady - } - - const results = await Promise.all([ - ensureAppImageExtractedRoot({ appImagePath, cacheRootPath, runExtract }), - ensureAppImageExtractedRoot({ appImagePath, cacheRootPath, runExtract }) - ]) - - expect(results).toEqual([root, root]) - expect(['winner-1', 'winner-2']).toContain(await readFile(root.payloadLauncherPath, 'utf8')) - }) - - it('retries with the current generation when the AppImage changes during extraction', async () => { - const { appImagePath, cacheRootPath } = await makeFixture() - const initialRoot = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - let extractCount = 0 - - const result = await ensureAppImageExtractedRoot({ - appImagePath, - cacheRootPath, - runExtract: async (_path, cwd) => { - extractCount += 1 - await writePayload(cwd, `generation-${extractCount}`) - if (extractCount === 1) { - await writeFile(appImagePath, '#!/usr/bin/env bash\n# replaced during extraction\n', { - encoding: 'utf8', - mode: 0o755 - }) - } - } - }) - - const currentRoot = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - expect(extractCount).toBe(2) - expect(result).toEqual(currentRoot) - expect(result?.rootPath).not.toBe(initialRoot.rootPath) - await expect(readFile(currentRoot.payloadLauncherPath, 'utf8')).resolves.toBe('generation-2') - expect(existsSync(initialRoot.rootPath)).toBe(false) - }) }) diff --git a/src/main/cli/appimage-extracted-root.ts b/src/main/cli/appimage/appimage-extracted-root.ts similarity index 98% rename from src/main/cli/appimage-extracted-root.ts rename to src/main/cli/appimage/appimage-extracted-root.ts index 857a46dc5bc..9d97514d129 100644 --- a/src/main/cli/appimage-extracted-root.ts +++ b/src/main/cli/appimage/appimage-extracted-root.ts @@ -4,18 +4,15 @@ import { homedir } from 'node:os' import { dirname, isAbsolute, join, resolve } from 'node:path' import { runProcess } from '@orca/process-host' import { resolveCachedAppImagePayloadRoot } from './appimage-cache-layout' -export { - readAppImageSourceOfNamespace, - resolveAppImageCacheKey -} from '../../shared/appimage-cache-identity' + import { removeExtractedAppImagePayload } from './appimage-payload-removal' -import { LINUX_CLI_COMMAND_NAME } from './bundled-cli-launcher-path' +import { LINUX_CLI_COMMAND_NAME } from '../packaged-assets/bundled-cli-launcher-path' import { APPIMAGE_SOURCE_RECORD_NAME, appImageCacheDigest, appImageNamespaceKey, resolveAppImageCacheKey -} from '../../shared/appimage-cache-identity' +} from '../../../shared/appimage-cache-identity' import { APPIMAGE_EXTRACTION_TIMEOUT_MS, getAppImageActiveExtractionPath, diff --git a/src/main/cli/appimage-extraction-pruning-namespace.test.ts b/src/main/cli/appimage/appimage-extraction-pruning-namespace.test.ts similarity index 100% rename from src/main/cli/appimage-extraction-pruning-namespace.test.ts rename to src/main/cli/appimage/appimage-extraction-pruning-namespace.test.ts diff --git a/src/main/cli/appimage-extraction-pruning.test.ts b/src/main/cli/appimage/appimage-extraction-pruning.test.ts similarity index 100% rename from src/main/cli/appimage-extraction-pruning.test.ts rename to src/main/cli/appimage/appimage-extraction-pruning.test.ts diff --git a/src/main/cli/appimage-extraction-pruning.ts b/src/main/cli/appimage/appimage-extraction-pruning.ts similarity index 93% rename from src/main/cli/appimage-extraction-pruning.ts rename to src/main/cli/appimage/appimage-extraction-pruning.ts index fd896b175b2..2b45cd2704d 100644 --- a/src/main/cli/appimage-extraction-pruning.ts +++ b/src/main/cli/appimage/appimage-extraction-pruning.ts @@ -1,13 +1,21 @@ import { randomUUID } from 'node:crypto' -import { existsSync } from 'node:fs' -import type { Dirent } from 'node:fs' +import { existsSync, type Dirent } from 'node:fs' + import { lstat, readlink, readdir, rename, rm, rmdir, symlink, unlink } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' -import { APPIMAGE_SOURCE_RECORD_NAME } from '../../shared/appimage-cache-identity' -import { isAppImageCacheKey, resolveCachedAppImagePayloadRoot } from './appimage-cache-layout' +import { + APPIMAGE_SOURCE_RECORD_NAME, + isAppImageCacheKey +} from '../../../shared/appimage-cache-identity' + +import { resolveCachedAppImagePayloadRoot } from './appimage-cache-layout' import { inspectAppImageGenerationLeases } from './appimage-generation-lease' -import { residencyOfGeneration, scanResidentExecutables } from './appimage-generation-residency' -import type { ResidentExecutableScan } from './appimage-generation-residency' +import { + residencyOfGeneration, + scanResidentExecutables, + type ResidentExecutableScan +} from './appimage-generation-residency' + import { removeExtractedAppImagePayload } from './appimage-payload-removal' import { removeAppImageLegacyLiveEndpoint, diff --git a/src/main/cli/appimage-generation-lease.test.ts b/src/main/cli/appimage/appimage-generation-lease.test.ts similarity index 100% rename from src/main/cli/appimage-generation-lease.test.ts rename to src/main/cli/appimage/appimage-generation-lease.test.ts diff --git a/src/main/cli/appimage-generation-lease.ts b/src/main/cli/appimage/appimage-generation-lease.ts similarity index 93% rename from src/main/cli/appimage-generation-lease.ts rename to src/main/cli/appimage/appimage-generation-lease.ts index 4918e1be8cd..87c874800fd 100644 --- a/src/main/cli/appimage-generation-lease.ts +++ b/src/main/cli/appimage/appimage-generation-lease.ts @@ -3,27 +3,22 @@ import { randomUUID } from 'node:crypto' import { readFileSync, unlinkSync } from 'node:fs' import { lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' -import type { ProcessLivenessVerdict } from '../daemon/endpoint/identity/daemon-incarnation-evidence-types' +import type { ProcessLivenessVerdict } from '../../daemon/endpoint/identity/daemon-incarnation-evidence-types' import { parseLinuxStartTicks, readBootIdentity -} from '../agent-hooks/installation/locking/managed-hook-owner-identity' +} from '../../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveAppImageGenerationOfExecutable, - type AppImageGenerationLocation -} from '../../shared/appimage-cache-identity' -import { isAppImageCacheKey } from './appimage-cache-layout' + type AppImageGenerationLocation, + isAppImageCacheKey +} from '../../../shared/appimage-cache-identity' const LEASE_DIRECTORY_NAME = 'leases' const LEASE_SUFFIX = '.json' // A lease is written by temp-and-rename, so an unreadable one is foreign or damaged, not torn. const UNREADABLE_LEASE_GRACE_MS = 60_000 -export { - resolveAppImageGenerationOfExecutable, - type AppImageGenerationLocation -} from '../../shared/appimage-cache-identity' - type LeaseRecord = { pid: number; linuxStartTicks: string; bootId: string } export type ProcessStartTicksRead = diff --git a/src/main/cli/appimage-generation-residency.test.ts b/src/main/cli/appimage/appimage-generation-residency.test.ts similarity index 100% rename from src/main/cli/appimage-generation-residency.test.ts rename to src/main/cli/appimage/appimage-generation-residency.test.ts diff --git a/src/main/cli/appimage-generation-residency.ts b/src/main/cli/appimage/appimage-generation-residency.ts similarity index 96% rename from src/main/cli/appimage-generation-residency.ts rename to src/main/cli/appimage/appimage-generation-residency.ts index 465fac02420..939d843a433 100644 --- a/src/main/cli/appimage-generation-residency.ts +++ b/src/main/cli/appimage/appimage-generation-residency.ts @@ -1,7 +1,7 @@ // Scan executables to cover pre-lease builds and exec-to-lease races without costly process maps. import { readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs' import { resolve, sep } from 'node:path' -import type { ProcessLivenessVerdict } from '../daemon/endpoint/identity/daemon-incarnation-evidence-types' +import type { ProcessLivenessVerdict } from '../../daemon/endpoint/identity/daemon-incarnation-evidence-types' export type ProcReader = { listPids(): string[] diff --git a/src/main/cli/appimage-generation-stable-launcher.ts b/src/main/cli/appimage/appimage-generation-stable-launcher.ts similarity index 86% rename from src/main/cli/appimage-generation-stable-launcher.ts rename to src/main/cli/appimage/appimage-generation-stable-launcher.ts index 037cdf1e065..88bba7d4884 100644 --- a/src/main/cli/appimage-generation-stable-launcher.ts +++ b/src/main/cli/appimage/appimage-generation-stable-launcher.ts @@ -1,5 +1,5 @@ import { dirname, join } from 'node:path' -import { resolveAppImageGenerationOfExecutable } from './appimage-generation-lease' +import { resolveAppImageGenerationOfExecutable } from '../../../shared/appimage-cache-identity' import { isAppImageStableLauncherReady, resolveAppImageStableLauncherPath diff --git a/src/main/cli/appimage-payload-removal.ts b/src/main/cli/appimage/appimage-payload-removal.ts similarity index 100% rename from src/main/cli/appimage-payload-removal.ts rename to src/main/cli/appimage/appimage-payload-removal.ts diff --git a/src/main/cli/appimage-registration-lock.ts b/src/main/cli/appimage/appimage-registration-lock.ts similarity index 100% rename from src/main/cli/appimage-registration-lock.ts rename to src/main/cli/appimage/appimage-registration-lock.ts diff --git a/src/main/cli/appimage-serve-preparation.test.ts b/src/main/cli/appimage/appimage-serve-preparation.test.ts similarity index 100% rename from src/main/cli/appimage-serve-preparation.test.ts rename to src/main/cli/appimage/appimage-serve-preparation.test.ts diff --git a/src/main/cli/appimage-serve-preparation.ts b/src/main/cli/appimage/appimage-serve-preparation.ts similarity index 100% rename from src/main/cli/appimage-serve-preparation.ts rename to src/main/cli/appimage/appimage-serve-preparation.ts diff --git a/src/main/cli/appimage-stable-launcher.test.ts b/src/main/cli/appimage/appimage-stable-launcher.test.ts similarity index 100% rename from src/main/cli/appimage-stable-launcher.test.ts rename to src/main/cli/appimage/appimage-stable-launcher.test.ts diff --git a/src/main/cli/appimage-stable-launcher.ts b/src/main/cli/appimage/appimage-stable-launcher.ts similarity index 97% rename from src/main/cli/appimage-stable-launcher.ts rename to src/main/cli/appimage/appimage-stable-launcher.ts index ffe90fc2bba..36e1cd49d76 100644 --- a/src/main/cli/appimage-stable-launcher.ts +++ b/src/main/cli/appimage/appimage-stable-launcher.ts @@ -15,8 +15,8 @@ import { writeFileSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { LINUX_CLI_COMMAND_NAME } from './bundled-cli-launcher-path' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { LINUX_CLI_COMMAND_NAME } from '../packaged-assets/bundled-cli-launcher-path' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' const LAUNCHER_DIRECTORY_NAME = 'launcher' const LIVE_ENDPOINT_NAME = 'live' diff --git a/src/main/cli/legacy-appimage-cli-wrapper.test.ts b/src/main/cli/appimage/legacy-appimage-cli-wrapper.test.ts similarity index 100% rename from src/main/cli/legacy-appimage-cli-wrapper.test.ts rename to src/main/cli/appimage/legacy-appimage-cli-wrapper.test.ts diff --git a/src/main/cli/legacy-appimage-cli-wrapper.ts b/src/main/cli/appimage/legacy-appimage-cli-wrapper.ts similarity index 94% rename from src/main/cli/legacy-appimage-cli-wrapper.ts rename to src/main/cli/appimage/legacy-appimage-cli-wrapper.ts index 92cfd8da2ab..a4ff3173d08 100644 --- a/src/main/cli/legacy-appimage-cli-wrapper.ts +++ b/src/main/cli/appimage/legacy-appimage-cli-wrapper.ts @@ -1,4 +1,4 @@ -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' const APPIMAGE_CLI_SCRIPT = [ '(async()=>{', diff --git a/src/main/cli/cli-command-installation-races.test.ts b/src/main/cli/cli-command-installation-races.test.ts deleted file mode 100644 index 88dbfce5ae8..00000000000 --- a/src/main/cli/cli-command-installation-races.test.ts +++ /dev/null @@ -1,375 +0,0 @@ -import { - lstat, - mkdir, - mkdtemp, - readFile, - readdir, - readlink, - rm, - symlink, - unlink, - writeFile -} from 'node:fs/promises' -import type * as NodeFsPromises from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const legacyReadlinkRace = vi.hoisted(() => ({ commandPath: '', replacementTarget: '' })) -const reusedIdentity = vi.hoisted(() => ({ - path: '', - dev: null as bigint | null, - ino: null as bigint | null -})) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - lstat: async (...args: Parameters) => { - const stats = await actual.lstat(...args) - if ( - args[0] !== reusedIdentity.path || - reusedIdentity.dev === null || - reusedIdentity.ino === null - ) { - return stats - } - return Object.create(stats, { - dev: { value: reusedIdentity.dev }, - ino: { value: reusedIdentity.ino } - }) as typeof stats - }, - readlink: async (...args: Parameters) => { - const [path] = args - if (path === legacyReadlinkRace.commandPath && legacyReadlinkRace.replacementTarget) { - const replacementTarget = legacyReadlinkRace.replacementTarget - legacyReadlinkRace.commandPath = '' - legacyReadlinkRace.replacementTarget = '' - await actual.unlink(path) - await actual.symlink(replacementTarget, path) - throw Object.assign(new Error('link vanished during inspection'), { code: 'ENOENT' }) - } - return actual.readlink(...args) - } - } -}) - -vi.mock('electron', () => ({ - app: { - isPackaged: false, - getPath: () => tmpdir(), - getAppPath: () => tmpdir() - } -})) - -import { CliInstaller } from './cli-installer' -import type { CommandQuarantine } from './cli-command-filesystem-transaction' - -const createdRoots: string[] = [] - -afterEach(async () => { - legacyReadlinkRace.commandPath = '' - legacyReadlinkRace.replacementTarget = '' - reusedIdentity.path = '' - reusedIdentity.dev = null - reusedIdentity.ino = null - await Promise.all( - createdRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })) - ) -}) - -async function createMacCommandFixture() { - const root = await mkdtemp(join(tmpdir(), 'orca-cli-command-race-')) - createdRoots.push(root) - const commandDirectory = join(root, 'bin') - const commandPath = join(commandDirectory, 'orca') - const resourcesPath = join(root, 'Current.app', 'Contents', 'Resources') - const launcherPath = join(resourcesPath, 'bin', 'orca') - const staleLauncherPath = join(root, 'Old.app', 'Contents', 'Resources', 'bin', 'orca') - await mkdir(commandDirectory, { recursive: true }) - await mkdir(dirname(launcherPath), { recursive: true }) - await writeFile(launcherPath, '#!/usr/bin/env bash\n', { mode: 0o755 }) - return { root, commandDirectory, commandPath, resourcesPath, launcherPath, staleLauncherPath } -} - -function createMacInstaller( - fixture: Awaited>, - hooks: { - quarantine?: (commandPath: string) => Promise - afterQuarantine?: (quarantine: CommandQuarantine) => void - link?: (heldPath: string, commandPath: string) => Promise - } = {} -): CliInstaller { - class RaceInjectedInstaller extends CliInstaller { - protected override async quarantineCommandPath(commandPath: string) { - await hooks.quarantine?.(commandPath) - const quarantine = await super.quarantineCommandPath(commandPath) - hooks.afterQuarantine?.(quarantine) - return quarantine - } - - protected override async linkQuarantinedCommand( - heldPath: string, - commandPath: string - ): Promise { - await hooks.link?.(heldPath, commandPath) - return super.linkQuarantinedCommand(heldPath, commandPath) - } - } - - return new RaceInjectedInstaller({ - platform: 'darwin', - isPackaged: true, - userDataPath: join(fixture.root, 'user-data'), - resourcesPath: fixture.resourcesPath, - execPath: join(fixture.root, 'Current.app', 'Contents', 'MacOS', 'Orca'), - appPath: join(fixture.root, 'Current.app', 'Contents', 'Resources', 'app.asar'), - homePath: join(fixture.root, 'home'), - commandPathOverride: fixture.commandPath, - processPathEnv: fixture.commandDirectory - }) -} - -async function recoveryPath(commandDirectory: string): Promise { - const transactionName = (await readdir(commandDirectory)).find((name) => - name.startsWith('.orca-cli-') - ) - if (!transactionName) { - throw new Error('Expected a preserved CLI command transaction.') - } - return join(commandDirectory, transactionName, 'orca') -} - -async function rejectionFrom(operation: Promise): Promise { - try { - await operation - } catch (error) { - if (error instanceof Error) { - return error - } - throw error - } - throw new Error('Expected the operation to reject.') -} - -describe.skipIf(process.platform === 'win32')('CLI command filesystem races', () => { - it('restores a foreign symlink whose quarantined inode identity is reused', async () => { - const fixture = await createMacCommandFixture() - const foreignTarget = join(fixture.root, 'foreign-command') - await symlink(fixture.staleLauncherPath, fixture.commandPath) - const original = await lstat(fixture.commandPath, { bigint: true }) - let raced = false - const installer = createMacInstaller(fixture, { - quarantine: async (commandPath) => { - if (raced) { - return - } - raced = true - await unlink(commandPath) - await symlink(foreignTarget, commandPath) - }, - afterQuarantine: (quarantine) => { - if (quarantine.snapshot) { - reusedIdentity.path = quarantine.heldPath - reusedIdentity.dev = original.dev - reusedIdentity.ino = original.ino - quarantine.snapshot.identity = { - ...quarantine.snapshot.identity, - dev: original.dev, - ino: original.ino - } - } - } - }) - - await expect(installer.install()).rejects.toThrow('Refusing to replace non-Orca command') - await expect(readlink(fixture.commandPath)).resolves.toBe(foreignTarget) - expect( - (await readdir(fixture.commandDirectory)).some((name) => name.startsWith('.orca-cli-')) - ).toBe(false) - }) - - it('preserves a managed file changed in place after its final inspection', async () => { - const fixture = await createMacCommandFixture() - const oldCliPath = join(fixture.root, 'old', 'out', 'cli', 'index.js') - await writeFile( - fixture.commandPath, - [ - '#!/usr/bin/env bash', - `CLI='${oldCliPath}'`, - 'export ORCA_NODE_OPTIONS="${NODE_OPTIONS-}"', - 'export ORCA_NODE_REPL_EXTERNAL_MODULE="${NODE_REPL_EXTERNAL_MODULE-}"', - 'ELECTRON_RUN_AS_NODE=1 exec electron "$CLI" "$@"' - ].join('\n') - ) - let raced = false - const installer = createMacInstaller(fixture, { - quarantine: async (commandPath) => { - if (raced) { - return - } - raced = true - await writeFile(commandPath, 'foreign command written into the inspected inode') - } - }) - - await expect(installer.install()).rejects.toThrow('Refusing to replace non-Orca command') - await expect(readFile(fixture.commandPath, 'utf8')).resolves.toBe( - 'foreign command written into the inspected inode' - ) - }) - - it('restores a foreign symlink raced into command removal', async () => { - const fixture = await createMacCommandFixture() - const foreignTarget = join(fixture.root, 'foreign-command') - await symlink(fixture.launcherPath, fixture.commandPath) - let raced = false - const installer = createMacInstaller(fixture, { - quarantine: async (commandPath) => { - if (raced) { - return - } - raced = true - await unlink(commandPath) - await symlink(foreignTarget, commandPath) - } - }) - - await expect(installer.remove()).rejects.toThrow('Refusing to remove non-Orca command') - await expect(readlink(fixture.commandPath)).resolves.toBe(foreignTarget) - }) - - it('preserves a raced foreign directory at the reported recovery path', async () => { - const fixture = await createMacCommandFixture() - await symlink(fixture.staleLauncherPath, fixture.commandPath) - let raced = false - const installer = createMacInstaller(fixture, { - quarantine: async (commandPath) => { - if (raced) { - return - } - raced = true - await unlink(commandPath) - await mkdir(commandPath) - await writeFile(join(commandPath, 'user-data'), 'preserved') - } - }) - - const error = await rejectionFrom(installer.install()) - const heldPath = await recoveryPath(fixture.commandDirectory) - expect(error.message).toContain(heldPath) - await expect(readFile(join(heldPath, 'user-data'), 'utf8')).resolves.toBe('preserved') - await expect(lstat(fixture.commandPath)).rejects.toMatchObject({ code: 'ENOENT' }) - }) - - it('preserves both entries when the original name is reclaimed during restoration', async () => { - const fixture = await createMacCommandFixture() - const contenderTarget = join(fixture.root, 'contender-command') - await symlink(fixture.staleLauncherPath, fixture.commandPath) - let raced = false - const installer = createMacInstaller(fixture, { - quarantine: async (commandPath) => { - if (raced) { - return - } - raced = true - await unlink(commandPath) - await writeFile(commandPath, 'foreign command') - }, - link: async (_heldPath, commandPath) => { - await symlink(contenderTarget, commandPath) - } - }) - - const error = await rejectionFrom(installer.install()) - const heldPath = await recoveryPath(fixture.commandDirectory) - expect(error.message).toContain(heldPath) - await expect(readFile(heldPath, 'utf8')).resolves.toBe('foreign command') - await expect(readlink(fixture.commandPath)).resolves.toBe(contenderTarget) - }) - - it('keeps a foreign legacy Linux command when readlink loses the inspection race', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-cli-legacy-race-')) - createdRoots.push(root) - const homePath = join(root, 'home') - const commandDirectory = join(homePath, '.local', 'bin') - const resourcesPath = join(root, 'resources') - const launcherPath = join(resourcesPath, 'bin', 'orca-ide') - const legacyPath = join(commandDirectory, 'orca') - const managedLegacyTarget = join(resourcesPath, 'bin', 'orca') - const foreignTarget = join(root, 'foreign-orca') - await mkdir(commandDirectory, { recursive: true }) - await mkdir(dirname(launcherPath), { recursive: true }) - await writeFile(launcherPath, '#!/usr/bin/env bash\n', { mode: 0o755 }) - await symlink(managedLegacyTarget, legacyPath) - - legacyReadlinkRace.commandPath = legacyPath - legacyReadlinkRace.replacementTarget = foreignTarget - const installer = new CliInstaller({ - platform: 'linux', - isPackaged: true, - userDataPath: join(root, 'user-data'), - resourcesPath, - execPath: join(root, 'orca-ide'), - appPath: join(root, 'resources', 'app.asar'), - homePath, - processPathEnv: commandDirectory - }) - - await expect(installer.install()).resolves.toMatchObject({ state: 'installed' }) - await expect(readlink(legacyPath)).resolves.toBe(foreignTarget) - }) - - it('keeps a foreign legacy Linux command whose quarantined inode is reused', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-cli-legacy-identity-race-')) - createdRoots.push(root) - const homePath = join(root, 'home') - const commandDirectory = join(homePath, '.local', 'bin') - const resourcesPath = join(root, 'resources') - const launcherPath = join(resourcesPath, 'bin', 'orca-ide') - const legacyPath = join(commandDirectory, 'orca') - const managedTarget = join(resourcesPath, 'bin', 'orca') - const foreignTarget = join(root, 'foreign-orca') - await mkdir(commandDirectory, { recursive: true }) - await mkdir(dirname(launcherPath), { recursive: true }) - await writeFile(launcherPath, '#!/usr/bin/env bash\n', { mode: 0o755 }) - await symlink(managedTarget, legacyPath) - const original = await lstat(legacyPath, { bigint: true }) - - class LegacyRaceInstaller extends CliInstaller { - protected override async quarantineCommandPath(commandPath: string) { - if (commandPath === legacyPath) { - await unlink(commandPath) - await symlink(foreignTarget, commandPath) - } - const quarantine = await super.quarantineCommandPath(commandPath) - if (commandPath === legacyPath && quarantine.snapshot) { - reusedIdentity.path = quarantine.heldPath - reusedIdentity.dev = original.dev - reusedIdentity.ino = original.ino - quarantine.snapshot.identity = { - ...quarantine.snapshot.identity, - dev: original.dev, - ino: original.ino - } - } - return quarantine - } - } - - const installer = new LegacyRaceInstaller({ - platform: 'linux', - isPackaged: true, - userDataPath: join(root, 'user-data'), - resourcesPath, - execPath: join(root, 'orca-ide'), - appPath: join(root, 'resources', 'app.asar'), - homePath, - processPathEnv: commandDirectory - }) - - await expect(installer.install()).resolves.toMatchObject({ state: 'installed' }) - await expect(readlink(legacyPath)).resolves.toBe(foreignTarget) - }) -}) diff --git a/src/main/cli/cli-installer-appimage-removal.test.ts b/src/main/cli/cli-installer-appimage-removal.test.ts deleted file mode 100644 index 9483141184c..00000000000 --- a/src/main/cli/cli-installer-appimage-removal.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { existsSync } from 'node:fs' -import { mkdir, mkdtemp, readlink, rm, symlink, unlink, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ - app: { isPackaged: false, getPath: () => tmpdir(), getAppPath: () => tmpdir() } -})) - -import { resolveAppImageExtractedRoot } from './appimage-extracted-root' -import { - publishAppImageLauncherEndpoint, - resolveAppImageLauncherEndpointPath, - resolveAppImageStableLauncherPath -} from './appimage-stable-launcher' -import { CliInstaller } from './cli-installer' -import type { CliInstallerOptions } from './cli-installer-contracts' - -const created: string[] = [] - -afterEach(async () => { - await Promise.all(created.splice(0).map((path) => rm(path, { recursive: true, force: true }))) -}) - -describe.skipIf(process.platform === 'win32')('AppImage CLI removal', () => { - it.each([false, true])( - 'removes installed payloads and the legacy live endpoint (command missing: %s)', - async (removeCommandFirst) => { - const root = await mkdtemp(join(tmpdir(), 'orca-appimage-cli-remove-')) - created.push(root) - const appImagePath = join(root, 'Orca.AppImage') - const cacheRootPath = join(root, 'cache') - const commandPath = join(root, 'home', '.local', 'bin', 'orca-ide') - const resourcesPath = join(root, 'mount', 'resources') - const liveLauncherPath = join(resourcesPath, 'bin', 'orca-ide') - await mkdir(join(resourcesPath, 'bin'), { recursive: true }) - await writeFile(appImagePath, '#!/usr/bin/env bash\n', { mode: 0o755 }) - await writeFile(liveLauncherPath, '#!/usr/bin/env bash\nprintf live', { mode: 0o755 }) - const liveEndpointPath = resolveAppImageLauncherEndpointPath(cacheRootPath, 'live') - await mkdir(dirname(liveEndpointPath), { recursive: true }) - await symlink(liveLauncherPath, liveEndpointPath) - - const installer = new CliInstaller({ - platform: 'linux', - isPackaged: true, - userDataPath: join(root, 'user-data'), - resourcesPath, - execPath: join(root, 'mount', 'orca-ide'), - appPath: join(resourcesPath, 'app.asar'), - homePath: join(root, 'home'), - processPathEnv: join(root, 'home', '.local', 'bin'), - commandPathOverride: commandPath, - appImagePath, - appImageCacheRootPath: cacheRootPath, - appImageExtractRunner: async (_path, cwd) => { - const payloadDirectory = join(cwd, 'squashfs-root', 'resources', 'bin') - await mkdir(payloadDirectory, { recursive: true }) - await writeFile( - join(payloadDirectory, 'orca-ide'), - '#!/usr/bin/env bash\nprintf installed', - { - mode: 0o755 - } - ) - } - }) - - const installed = await installer.install() - const extractedRoot = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })! - expect(await readlink(commandPath)).toBe(installed.launcherPath) - expect(existsSync(extractedRoot.rootPath)).toBe(true) - if (removeCommandFirst) { - await unlink(commandPath) - } - - await expect(installer.remove()).resolves.toMatchObject({ state: 'not_installed' }) - - expect(existsSync(commandPath)).toBe(false) - expect(existsSync(extractedRoot.rootPath)).toBe(false) - expect(existsSync(resolveAppImageLauncherEndpointPath(cacheRootPath, 'installed'))).toBe( - false - ) - expect(existsSync(resolveAppImageLauncherEndpointPath(cacheRootPath, 'live'))).toBe(false) - const stableLauncherPath = resolveAppImageStableLauncherPath(cacheRootPath) - expect(existsSync(stableLauncherPath)).toBe(true) - } - ) - - it('does not remove a sibling AppImage registration or payload', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-appimage-cli-siblings-')) - created.push(root) - const cacheRootPath = join(root, 'cache') - const commandPath = join(root, 'home', '.local', 'bin', 'orca-ide') - const resourcesPath = join(root, 'mount', 'resources') - const firstAppImagePath = join(root, 'Orca-stable.AppImage') - const secondAppImagePath = join(root, 'Orca-nightly.AppImage') - await mkdir(join(resourcesPath, 'bin'), { recursive: true }) - await Promise.all([ - writeFile(firstAppImagePath, '#!/usr/bin/env bash\n', { mode: 0o755 }), - writeFile(secondAppImagePath, '#!/usr/bin/env bash\n# nightly\n', { mode: 0o755 }) - ]) - const installerOptions = (appImagePath: string, content: string): CliInstallerOptions => ({ - platform: 'linux', - isPackaged: true, - userDataPath: join(root, 'user-data'), - resourcesPath, - execPath: join(root, 'mount', 'orca-ide'), - appPath: join(resourcesPath, 'app.asar'), - homePath: join(root, 'home'), - processPathEnv: join(root, 'home', '.local', 'bin'), - commandPathOverride: commandPath, - appImagePath, - appImageCacheRootPath: cacheRootPath, - appImageExtractRunner: async (_path, cwd) => { - const payloadDirectory = join(cwd, 'squashfs-root', 'resources', 'bin') - await mkdir(payloadDirectory, { recursive: true }) - await writeFile(join(payloadDirectory, 'orca-ide'), content, { mode: 0o755 }) - } - }) - class HookedInstaller extends CliInstaller { - afterNextStatus: (() => Promise) | null = null - - override async getStatus() { - const status = await super.getStatus() - const hook = this.afterNextStatus - this.afterNextStatus = null - await hook?.() - return status - } - } - let siblingStatusReads = 0 - let rejectSiblingStatusRead = false - class TrackingInstaller extends CliInstaller { - override async getStatus() { - if (rejectSiblingStatusRead) { - throw new Error('sibling status read before registration lock release') - } - siblingStatusReads += 1 - return super.getStatus() - } - } - const firstInstaller = new HookedInstaller(installerOptions(firstAppImagePath, 'stable')) - const secondInstaller = new TrackingInstaller(installerOptions(secondAppImagePath, 'nightly')) - - await firstInstaller.install() - const firstRoot = resolveAppImageExtractedRoot({ - appImagePath: firstAppImagePath, - cacheRootPath - })! - await secondInstaller.install() - const secondRoot = resolveAppImageExtractedRoot({ - appImagePath: secondAppImagePath, - cacheRootPath - })! - - const siblingStatus = await firstInstaller.getStatus() - expect(firstInstaller.isAppImageRegistrationOwnedBySibling(siblingStatus)).toBe(true) - await rm(resolveAppImageStableLauncherPath(cacheRootPath)) - const brokenLauncherStatus = await firstInstaller.getStatus() - expect(firstInstaller.isAppImageRegistrationOwnedBySibling(brokenLauncherStatus)).toBe(false) - publishAppImageLauncherEndpoint(cacheRootPath, 'installed', secondRoot.payloadLauncherPath) - - await firstInstaller.remove() - - expect(existsSync(firstRoot.rootPath)).toBe(false) - expect(existsSync(secondRoot.rootPath)).toBe(true) - expect(existsSync(commandPath)).toBe(true) - await expect( - readlink(resolveAppImageLauncherEndpointPath(cacheRootPath, 'installed')) - ).resolves.toBe(secondRoot.payloadLauncherPath) - - await firstInstaller.install() - let siblingInstall: Promise | null = null - siblingStatusReads = 0 - firstInstaller.afterNextStatus = async () => { - rejectSiblingStatusRead = true - siblingInstall = secondInstaller.install() - } - await firstInstaller.remove() - rejectSiblingStatusRead = false - expect(siblingInstall).not.toBeNull() - await siblingInstall - - expect(siblingStatusReads).toBeGreaterThan(0) - expect(existsSync(commandPath)).toBe(true) - expect(existsSync(secondRoot.rootPath)).toBe(true) - await expect( - readlink(resolveAppImageLauncherEndpointPath(cacheRootPath, 'installed')) - ).resolves.toBe(secondRoot.payloadLauncherPath) - }) -}) diff --git a/src/main/cli/cli-installer.test.ts b/src/main/cli/cli-installer.test.ts index 40bbed18e1d..544b1e57f57 100644 --- a/src/main/cli/cli-installer.test.ts +++ b/src/main/cli/cli-installer.test.ts @@ -1,6 +1,6 @@ -import { lstat, mkdir, readFile, readdir, readlink, writeFile } from 'node:fs/promises' +import { lstat, mkdir, readlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' +import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const execFileMock = vi.hoisted(() => vi.fn()) @@ -18,9 +18,9 @@ vi.mock('node:child_process', () => ({ })) import { CliInstaller } from './cli-installer' -import { makeFixture } from './cli-installer-test-fixtures' -import { resolveAppImageExtractedRoot } from './appimage-extracted-root' -import { buildLegacyAppImageCliWrapper } from './legacy-appimage-cli-wrapper' +import { makeFixture } from './installation/cli-installer-test-fixtures' + +import { buildLegacyAppImageCliWrapper } from './appimage/legacy-appimage-cli-wrapper' // Match --appimage-extract's output directory under cwd. async function fakeAppImageExtractRunner(_appImagePath: string, cwd: string): Promise { @@ -42,80 +42,6 @@ describe('CliInstaller', () => { vi.restoreAllMocks() }) - it.skipIf(process.platform === 'win32')( - 'uses a separate orca-dev command for default development installs', - async () => { - const fixture = await makeFixture() - const homePath = join(fixture.root, 'home') - const commandDir = join(homePath, '.local', 'bin') - const installer = new CliInstaller({ - platform: 'linux', - isPackaged: false, - userDataPath: fixture.userDataPath, - execPath: '/opt/Orca/orca-ide', - appPath: fixture.appPath, - homePath, - processPathEnv: commandDir - }) - - const installed = await installer.install() - expect(installed.state).toBe('installed') - expect(installed.commandName).toBe('orca-dev') - expect(installed.commandPath).toBe(join(commandDir, 'orca-dev')) - expect(installed.launcherPath).toBe(join(fixture.userDataPath, 'cli', 'bin', 'orca-dev')) - await expect(readlink(installed.commandPath as string)).resolves.toBe(installed.launcherPath) - await expect( - readFile(join(fixture.userDataPath, 'cli', 'bin', 'orca'), 'utf8') - ).resolves.toBe(await readFile(installed.launcherPath as string, 'utf8')) - } - ) - - it.skipIf(process.platform === 'win32')( - 're-extracts and re-points the command when the AppImage is replaced', - async () => { - const fixture = await makeFixture() - const commandDir = join(fixture.root, '.local', 'bin') - const installPath = join(commandDir, 'orca-ide') - const appImagePath = join(fixture.root, 'Orca.AppImage') - const cacheRootPath = join(fixture.root, 'cache') - await writeFile(appImagePath, '#!/usr/bin/env bash\n', { - encoding: 'utf8', - mode: 0o755 - }) - const makeInstaller = (): CliInstaller => - new CliInstaller({ - platform: 'linux', - isPackaged: true, - userDataPath: fixture.userDataPath, - appPath: fixture.appPath, - appImagePath, - appImageCacheRootPath: cacheRootPath, - appImageExtractRunner: fakeAppImageExtractRunner, - commandPathOverride: installPath, - processPathEnv: commandDir - }) - - const first = await makeInstaller().install() - expect(first.state).toBe('installed') - - await writeFile(appImagePath, '#!/usr/bin/env bash\n# next version\n', { - encoding: 'utf8', - mode: 0o755 - }) - - await expect(makeInstaller().getStatus()).resolves.toMatchObject({ state: 'stale' }) - - const second = await makeInstaller().install() - expect(second.state).toBe('installed') - expect(second.launcherPath).toBe(first.launcherPath) - await expect(readlink(installPath)).resolves.toBe(second.launcherPath) - const liveRoot = resolveAppImageExtractedRoot({ appImagePath, cacheRootPath })!.rootPath - expect((await readdir(dirname(liveRoot))).sort()).toEqual( - [basename(liveRoot), 'source-appimage'].sort() - ) - } - ) - it.skipIf(process.platform === 'win32')( 'replaces and removes the legacy AppImage wrapper', async () => { @@ -158,54 +84,4 @@ describe('CliInstaller', () => { await expect(lstat(installPath)).rejects.toMatchObject({ code: 'ENOENT' }) } ) - - it.skipIf(process.platform === 'win32')( - 'removes a legacy AppImage wrapper only when it names the current AppImage', - async () => { - const fixture = await makeFixture() - const homePath = join(fixture.root, 'home') - const commandDir = join(homePath, '.local', 'bin') - const legacyCommandPath = join(commandDir, 'orca') - const appImagePath = join(fixture.root, 'Orca.AppImage') - const foreignAppImagePath = join(fixture.root, 'Other.AppImage') - const cacheRootPath = join(fixture.root, 'cache') - await mkdir(commandDir, { recursive: true }) - await writeFile(appImagePath, '#!/usr/bin/env bash\n', { - encoding: 'utf8', - mode: 0o755 - }) - await writeFile(foreignAppImagePath, '#!/usr/bin/env bash\n', { - encoding: 'utf8', - mode: 0o755 - }) - await writeFile(legacyCommandPath, buildLegacyAppImageCliWrapper(appImagePath), { - encoding: 'utf8', - mode: 0o755 - }) - - const installer = new CliInstaller({ - platform: 'linux', - isPackaged: true, - userDataPath: fixture.userDataPath, - appPath: fixture.appPath, - appImagePath, - appImageCacheRootPath: cacheRootPath, - appImageExtractRunner: fakeAppImageExtractRunner, - homePath, - processPathEnv: commandDir - }) - - await installer.install() - await expect(lstat(legacyCommandPath)).rejects.toMatchObject({ code: 'ENOENT' }) - - await writeFile(legacyCommandPath, buildLegacyAppImageCliWrapper(foreignAppImagePath), { - encoding: 'utf8', - mode: 0o755 - }) - await installer.remove() - await expect(readFile(legacyCommandPath, 'utf8')).resolves.toBe( - buildLegacyAppImageCliWrapper(foreignAppImagePath) - ) - } - ) }) diff --git a/src/main/cli/cli-installer.ts b/src/main/cli/cli-installer.ts index 4405575192c..e0a383d7e76 100644 --- a/src/main/cli/cli-installer.ts +++ b/src/main/cli/cli-installer.ts @@ -4,17 +4,17 @@ import type { CliInstallStatus } from '../../shared/cli-install-types' import { pruneAppImageExtractedRoots, removeAppImageInstalledPayloads -} from './appimage-extraction-pruning' -import { withAppImageRegistrationLock } from './appimage-registration-lock' +} from './appimage/appimage-extraction-pruning' +import { withAppImageRegistrationLock } from './appimage/appimage-registration-lock' import { isAppImageInstalledLauncherCurrent, isAppImageInstalledLauncherOwnedBySibling, resolveAppImageNamespacePath, resolveLegacyAppImageNamespacePath -} from './appimage-extracted-root' -import { isAppImageStableLauncherReady } from './appimage-stable-launcher' -import { CliPathRegistration } from './cli-path-registration' -import { removeLinuxBareOrcaDispatcher } from './linux-bare-orca-dispatcher' +} from './appimage/appimage-extracted-root' +import { isAppImageStableLauncherReady } from './appimage/appimage-stable-launcher' +import { CliPathRegistration } from './command-paths/cli-path-registration' +import { removeLinuxBareOrcaDispatcher } from './launchers/linux-bare-orca-dispatcher' export class CliInstaller extends CliPathRegistration { isAppImageRegistrationOwnedBySibling(status: CliInstallStatus): boolean { diff --git a/src/main/cli/cli-install-path-format.ts b/src/main/cli/command-paths/cli-install-path-format.ts similarity index 95% rename from src/main/cli/cli-install-path-format.ts rename to src/main/cli/command-paths/cli-install-path-format.ts index 6af5ca168d3..196de71d9a8 100644 --- a/src/main/cli/cli-install-path-format.ts +++ b/src/main/cli/command-paths/cli-install-path-format.ts @@ -1,7 +1,7 @@ import { constants } from 'node:fs' import { access, stat } from 'node:fs/promises' import { isAbsolute, relative } from 'node:path' -import { expandWindowsEnvironmentVariables } from '../../shared/windows-environment-expansion' +import { expandWindowsEnvironmentVariables } from '../../../shared/windows-environment-expansion' export function splitPathEntries(platform: NodeJS.Platform, value: string | null): string[] { if (!value) { diff --git a/src/main/cli/cli-path-registration.ts b/src/main/cli/command-paths/cli-path-registration.ts similarity index 95% rename from src/main/cli/cli-path-registration.ts rename to src/main/cli/command-paths/cli-path-registration.ts index 4040d45bd05..e0a8d02846a 100644 --- a/src/main/cli/cli-path-registration.ts +++ b/src/main/cli/command-paths/cli-path-registration.ts @@ -1,6 +1,6 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' -import { CliCommandInstallation } from './cli-command-installation' -import { isWindowsUserPathPermissionError } from './cli-install-errors' +import type { CliInstallStatus } from '../../../shared/cli-install-types' +import { CliCommandInstallation } from '../installation/cli-command-installation' +import { isWindowsUserPathPermissionError } from '../installation/cli-install-errors' import { samePathEntry, splitPathEntries } from './cli-install-path-format' export class CliPathRegistration extends CliCommandInstallation { diff --git a/src/main/cli/windows-user-path-registry.test.ts b/src/main/cli/command-paths/windows-user-path-registry.test.ts similarity index 100% rename from src/main/cli/windows-user-path-registry.test.ts rename to src/main/cli/command-paths/windows-user-path-registry.test.ts diff --git a/src/main/cli/windows-user-path-registry.ts b/src/main/cli/command-paths/windows-user-path-registry.ts similarity index 98% rename from src/main/cli/windows-user-path-registry.ts rename to src/main/cli/command-paths/windows-user-path-registry.ts index b9bace85fad..f802736d276 100644 --- a/src/main/cli/windows-user-path-registry.ts +++ b/src/main/cli/command-paths/windows-user-path-registry.ts @@ -3,7 +3,7 @@ import { WINDOWS_REG_EXPAND_SZ, WINDOWS_REG_SZ, type WindowsNativeRegistryModule -} from '../windows/windows-native-registry' +} from '../../windows/windows-native-registry' export type WindowsUserPathReadResult = | { state: 'success'; value: string | null; expandable: boolean } diff --git a/src/main/cli/cli-command-filesystem-transaction.ts b/src/main/cli/installation/cli-command-filesystem-transaction.ts similarity index 97% rename from src/main/cli/cli-command-filesystem-transaction.ts rename to src/main/cli/installation/cli-command-filesystem-transaction.ts index 6009fe3dad1..f378e4279e9 100644 --- a/src/main/cli/cli-command-filesystem-transaction.ts +++ b/src/main/cli/installation/cli-command-filesystem-transaction.ts @@ -1,10 +1,10 @@ import { createHash, randomUUID } from 'node:crypto' import { lstat, mkdir, readdir, readFile, readlink, rename, rmdir, stat } from 'node:fs/promises' import { basename, dirname, join } from 'node:path' -import type { CliInstallStatus } from '../../shared/cli-install-types' -import { isPermissionError } from '../filesystem/permission-errors' +import type { CliInstallStatus } from '../../../shared/cli-install-types' +import { isPermissionError } from '../../filesystem/permission-errors' import { isMissingError } from './cli-install-errors' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' export type EntryIdentity = { dev: bigint diff --git a/src/main/cli/cli-command-inspection.ts b/src/main/cli/installation/cli-command-inspection.ts similarity index 94% rename from src/main/cli/cli-command-inspection.ts rename to src/main/cli/installation/cli-command-inspection.ts index 1af63aace0c..1b64464cbda 100644 --- a/src/main/cli/cli-command-inspection.ts +++ b/src/main/cli/installation/cli-command-inspection.ts @@ -1,15 +1,18 @@ import { existsSync } from 'node:fs' import { lstat, readFile, readlink } from 'node:fs/promises' import { basename, dirname, resolve } from 'node:path' -import type { CliInstallMethod, CliInstallStatus } from '../../shared/cli-install-types' -import { isAppImageExtractedLauncherPath } from './appimage-extracted-root' +import type { CliInstallMethod, CliInstallStatus } from '../../../shared/cli-install-types' +import { isAppImageExtractedLauncherPath } from '../appimage/appimage-extracted-root' import { DEV_COMMAND_NAME, DEV_LAUNCHER_DIR } from './cli-install-constants' -import { buildWindowsForwarder, extractManagedUnixLauncherTarget } from './cli-dev-launcher' -import { isPermissionError } from '../filesystem/permission-errors' +import { + buildWindowsForwarder, + extractManagedUnixLauncherTarget +} from '../launchers/cli-dev-launcher' +import { isPermissionError } from '../../filesystem/permission-errors' import { isMissingError } from './cli-install-errors' import { CliInstallLocation } from './cli-install-location' -import { isPathInsideOrEqual, samePathEntry } from './cli-install-path-format' -import { extractLegacyAppImageCliWrapperTarget } from './legacy-appimage-cli-wrapper' +import { isPathInsideOrEqual, samePathEntry } from '../command-paths/cli-install-path-format' +import { extractLegacyAppImageCliWrapperTarget } from '../appimage/legacy-appimage-cli-wrapper' // Match after-install.sh's electron-builder name variants when reclaiming packaged launchers. const PACKAGED_LINUX_LAUNCHER_DIRECTORIES = ['/opt/Orca', '/opt/orca-ide', '/opt/orca'] diff --git a/src/main/cli/installation/cli-command-installation-races.test.ts b/src/main/cli/installation/cli-command-installation-races.test.ts new file mode 100644 index 00000000000..5a3a8f6fbc9 --- /dev/null +++ b/src/main/cli/installation/cli-command-installation-races.test.ts @@ -0,0 +1,102 @@ +import { mkdir, mkdtemp, readlink, rm, symlink, writeFile } from 'node:fs/promises' +import type * as NodeFsPromises from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const legacyReadlinkRace = vi.hoisted(() => ({ commandPath: '', replacementTarget: '' })) +const reusedIdentity = vi.hoisted(() => ({ + path: '', + dev: null as bigint | null, + ino: null as bigint | null +})) + +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + lstat: async (...args: Parameters) => { + const stats = await actual.lstat(...args) + if ( + args[0] !== reusedIdentity.path || + reusedIdentity.dev === null || + reusedIdentity.ino === null + ) { + return stats + } + return Object.create(stats, { + dev: { value: reusedIdentity.dev }, + ino: { value: reusedIdentity.ino } + }) as typeof stats + }, + readlink: async (...args: Parameters) => { + const [path] = args + if (path === legacyReadlinkRace.commandPath && legacyReadlinkRace.replacementTarget) { + const replacementTarget = legacyReadlinkRace.replacementTarget + legacyReadlinkRace.commandPath = '' + legacyReadlinkRace.replacementTarget = '' + await actual.unlink(path) + await actual.symlink(replacementTarget, path) + throw Object.assign(new Error('link vanished during inspection'), { code: 'ENOENT' }) + } + return actual.readlink(...args) + } + } +}) + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getPath: () => tmpdir(), + getAppPath: () => tmpdir() + } +})) + +import { CliInstaller } from '../cli-installer' + +const createdRoots: string[] = [] + +afterEach(async () => { + legacyReadlinkRace.commandPath = '' + legacyReadlinkRace.replacementTarget = '' + reusedIdentity.path = '' + reusedIdentity.dev = null + reusedIdentity.ino = null + await Promise.all( + createdRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })) + ) +}) + +describe.skipIf(process.platform === 'win32')('CLI command filesystem races', () => { + it('keeps a foreign legacy Linux command when readlink loses the inspection race', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-cli-legacy-race-')) + createdRoots.push(root) + const homePath = join(root, 'home') + const commandDirectory = join(homePath, '.local', 'bin') + const resourcesPath = join(root, 'resources') + const launcherPath = join(resourcesPath, 'bin', 'orca-ide') + const legacyPath = join(commandDirectory, 'orca') + const managedLegacyTarget = join(resourcesPath, 'bin', 'orca') + const foreignTarget = join(root, 'foreign-orca') + await mkdir(commandDirectory, { recursive: true }) + await mkdir(dirname(launcherPath), { recursive: true }) + await writeFile(launcherPath, '#!/usr/bin/env bash\n', { mode: 0o755 }) + await symlink(managedLegacyTarget, legacyPath) + + legacyReadlinkRace.commandPath = legacyPath + legacyReadlinkRace.replacementTarget = foreignTarget + const installer = new CliInstaller({ + platform: 'linux', + isPackaged: true, + userDataPath: join(root, 'user-data'), + resourcesPath, + execPath: join(root, 'orca-ide'), + appPath: join(root, 'resources', 'app.asar'), + homePath, + processPathEnv: commandDirectory + }) + + await expect(installer.install()).resolves.toMatchObject({ state: 'installed' }) + await expect(readlink(legacyPath)).resolves.toBe(foreignTarget) + }) +}) diff --git a/src/main/cli/cli-command-installation.ts b/src/main/cli/installation/cli-command-installation.ts similarity index 97% rename from src/main/cli/cli-command-installation.ts rename to src/main/cli/installation/cli-command-installation.ts index 805e20c7343..3b9d511c650 100644 --- a/src/main/cli/cli-command-installation.ts +++ b/src/main/cli/installation/cli-command-installation.ts @@ -1,11 +1,11 @@ import { link, readlink, rmdir, symlink, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' -import type { CliInstallStatus } from '../../shared/cli-install-types' +import type { CliInstallStatus } from '../../../shared/cli-install-types' import { ensureAppImageExtractedRoot, isAppImageExtractedLauncherPath, type AppImageExtractedRoot -} from './appimage-extracted-root' +} from '../appimage/appimage-extracted-root' import { CliCommandInspection } from './cli-command-inspection' import { buildMacPrivilegedSymlinkReadableCommand, @@ -22,9 +22,9 @@ import { type StableCommandInspection } from './cli-command-filesystem-transaction' import { DEV_LAUNCHER_DIR, LEGACY_LINUX_COMMAND_NAME } from './cli-install-constants' -import { buildWindowsForwarder } from './cli-dev-launcher' -import { isPermissionError } from '../filesystem/permission-errors' -import { isPathInsideOrEqual } from './cli-install-path-format' +import { buildWindowsForwarder } from '../launchers/cli-dev-launcher' +import { isPermissionError } from '../../filesystem/permission-errors' +import { isPathInsideOrEqual } from '../command-paths/cli-install-path-format' export class CliCommandInstallation extends CliCommandInspection { protected async installSymlink(status: CliInstallStatus): Promise { diff --git a/src/main/cli/cli-command-privileged-transaction.test.ts b/src/main/cli/installation/cli-command-privileged-transaction.test.ts similarity index 65% rename from src/main/cli/cli-command-privileged-transaction.test.ts rename to src/main/cli/installation/cli-command-privileged-transaction.test.ts index 6fbf63644ad..3c14ab1f2d9 100644 --- a/src/main/cli/cli-command-privileged-transaction.test.ts +++ b/src/main/cli/installation/cli-command-privileged-transaction.test.ts @@ -25,8 +25,8 @@ vi.mock('electron', () => ({ } })) -import { CliInstaller } from './cli-installer' -import { buildUnixCliLauncher } from './cli-dev-launcher' +import { CliInstaller } from '../cli-installer' +import { buildUnixCliLauncher } from '../launchers/cli-dev-launcher' const createdRoots: string[] = [] const protectedDirectories: string[] = [] @@ -78,32 +78,6 @@ function fixtureInstallerOptions(fixture: Awaited { - it('installs and removes through the generated no-overwrite shell transaction', async () => { - const fixture = await createPrivilegedFixture() - const commands: string[] = [] - const installer = new CliInstaller({ - ...fixtureInstallerOptions(fixture), - privilegedRunner: async (command) => { - commands.push(command) - await chmod(fixture.protectedDirectory, 0o700) - await executePrivilegedShell(command) - } - }) - - await chmod(fixture.protectedDirectory, 0o500) - const installed = await installer.install() - expect(installed.state).toBe('installed') - await expect(readlink(fixture.commandPath)).resolves.toBe(installed.launcherPath) - // Why: macOS enforces a symlink's own mode on readlink; a 0700 link is unreadable to other users. - expect((await lstat(fixture.commandPath)).mode & 0o777).toBe(0o755) - - await chmod(fixture.protectedDirectory, 0o500) - await expect(installer.remove()).resolves.toMatchObject({ state: 'not_installed' }) - expect(commands).toHaveLength(2) - expect(commands.every((command) => command.includes('/bin/ln -P'))).toBe(true) - expect(commands.every((command) => !command.includes('mv -f'))).toBe(true) - }) - it('restores a trailing-newline symlink inserted after privileged inspection', async () => { const fixture = await createPrivilegedFixture() const staleTarget = join(fixture.userDataPath, 'cli', 'bin', 'old', 'orca') @@ -167,56 +141,6 @@ describe.skipIf(process.platform !== 'darwin' || process.getuid?.() === 0)( ).toBe(false) }) - it('makes an unreadable link to the current launcher readable with one privileged step', async () => { - const fixture = await createPrivilegedFixture() - const commands: string[] = [] - const installer = new CliInstaller({ - ...fixtureInstallerOptions(fixture), - privilegedRunner: async (command) => { - commands.push(command) - await executePrivilegedShell(command) - } - }) - const launcherPath = (await installer.getStatus()).launcherPath - await symlink(String(launcherPath), fixture.commandPath) - await lchmod(fixture.commandPath, 0o300) - await expect(readlink(fixture.commandPath)).rejects.toMatchObject({ code: 'EACCES' }) - - await expect(installer.getStatus()).resolves.toMatchObject({ - state: 'stale', - currentTarget: null - }) - await chmod(fixture.protectedDirectory, 0o500) - await expect(installer.install()).resolves.toMatchObject({ state: 'installed' }) - expect(commands).toHaveLength(1) - expect(commands[0]).toContain('/bin/chmod -h 755') - expect((await lstat(fixture.commandPath)).mode & 0o777).toBe(0o755) - await expect(readlink(fixture.commandPath)).resolves.toBe(launcherPath) - }) - - it('repairs an unreadable link to an older Orca launcher through the transaction', async () => { - const fixture = await createPrivilegedFixture() - await symlink('/Applications/Old Orca.app/Contents/Resources/bin/orca', fixture.commandPath) - await lchmod(fixture.commandPath, 0o300) - const commands: string[] = [] - const installer = new CliInstaller({ - ...fixtureInstallerOptions(fixture), - privilegedRunner: async (command) => { - commands.push(command) - await chmod(fixture.protectedDirectory, 0o700) - await executePrivilegedShell(command) - await chmod(fixture.protectedDirectory, 0o500) - } - }) - - await chmod(fixture.protectedDirectory, 0o500) - const installed = await installer.install() - expect(installed.state).toBe('installed') - expect(commands).toHaveLength(2) - await expect(readlink(fixture.commandPath)).resolves.toBe(installed.launcherPath) - expect((await lstat(fixture.commandPath)).mode & 0o777).toBe(0o755) - }) - it('refuses an unreadable symlink that is not an Orca launcher once root makes it readable', async () => { const fixture = await createPrivilegedFixture() const foreignTarget = '/opt/other/bin/orca' diff --git a/src/main/cli/cli-install-constants.ts b/src/main/cli/installation/cli-install-constants.ts similarity index 100% rename from src/main/cli/cli-install-constants.ts rename to src/main/cli/installation/cli-install-constants.ts diff --git a/src/main/cli/cli-install-errors.ts b/src/main/cli/installation/cli-install-errors.ts similarity index 100% rename from src/main/cli/cli-install-errors.ts rename to src/main/cli/installation/cli-install-errors.ts diff --git a/src/main/cli/cli-install-location.ts b/src/main/cli/installation/cli-install-location.ts similarity index 94% rename from src/main/cli/cli-install-location.ts rename to src/main/cli/installation/cli-install-location.ts index f8a580dd3d9..4751f04462d 100644 --- a/src/main/cli/cli-install-location.ts +++ b/src/main/cli/installation/cli-install-location.ts @@ -1,28 +1,31 @@ import { existsSync } from 'node:fs' import { homedir } from 'node:os' import { basename, dirname, join } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import type { CliInstallStatus } from '../../shared/cli-install-types' +import { getAppEnvironment } from '../../../shared/app-environment' +import type { CliInstallStatus } from '../../../shared/cli-install-types' import { hasAppImagePathEnvironment, resolveAppImageRuntimeIdentity -} from '../updater/linux-package/appimage-runtime-identity' +} from '../../updater/linux-package/appimage-runtime-identity' import { getAppImageCacheRootPath, resolveAppImageExtractedRoot, type AppImageExtractionOptions -} from './appimage-extracted-root' -import { resolveGenerationStableLauncherPath } from './appimage-generation-stable-launcher' -import { getBundledLauncherPath, LINUX_CLI_COMMAND_NAME } from './bundled-cli-launcher-path' +} from '../appimage/appimage-extracted-root' +import { resolveGenerationStableLauncherPath } from '../appimage/appimage-generation-stable-launcher' +import { + getBundledLauncherPath, + LINUX_CLI_COMMAND_NAME +} from '../packaged-assets/bundled-cli-launcher-path' import { DEFAULT_MAC_COMMAND_PATH, DEV_COMMAND_NAME } from './cli-install-constants' -import { ensureDevLauncher } from './cli-dev-launcher' +import { ensureDevLauncher } from '../launchers/cli-dev-launcher' import type { CliInstallerOptions, InstallSpec } from './cli-installer-contracts' import { isExecutableFile, samePathEntry, splitPathEntries, uniquePathEntries -} from './cli-install-path-format' +} from '../command-paths/cli-install-path-format' import { runMacPrivilegedCommand, writeWindowsUserPath } from './cli-privileged-processes' import { isSameDirectoryEntry } from './cli-command-filesystem-transaction' import { @@ -30,7 +33,7 @@ import { readFreshWindowsUserPathRegistry, readWindowsUserPathRegistry, type WindowsUserPathReadResult -} from './windows-user-path-registry' +} from '../command-paths/windows-user-path-registry' export abstract class CliInstallLocation { protected abstract inspectSymlink( diff --git a/src/main/cli/cli-installer-appimage-ownership.test.ts b/src/main/cli/installation/cli-installer-appimage-ownership.test.ts similarity index 54% rename from src/main/cli/cli-installer-appimage-ownership.test.ts rename to src/main/cli/installation/cli-installer-appimage-ownership.test.ts index c2de7c9ed27..2825b112151 100644 --- a/src/main/cli/cli-installer-appimage-ownership.test.ts +++ b/src/main/cli/installation/cli-installer-appimage-ownership.test.ts @@ -1,20 +1,7 @@ -import { - lstat, - mkdir, - mkdtemp, - readlink, - readdir, - rename, - rm, - symlink, - unlink, - writeFile -} from 'node:fs/promises' +import { mkdir, mkdtemp, readlink, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { CliInstallStatus } from '../../shared/cli-install-types' -import { resolveAppImageExtractedRoot, type AppImageExtractedRoot } from './appimage-extracted-root' vi.mock('electron', () => ({ app: { @@ -24,7 +11,7 @@ vi.mock('electron', () => ({ } })) -import { CliInstaller } from './cli-installer' +import { CliInstaller } from '../cli-installer' const created: string[] = [] @@ -149,100 +136,4 @@ describe.skipIf(process.platform === 'win32')('AppImage CLI ownership', () => { await expect(readlink(fixture.commandPath)).resolves.toBe(foreignTarget) expect(extract).not.toHaveBeenCalled() }) - - it('keeps installation bound to the extracted generation', async () => { - const fixture = await makeFixture() - let extractedRoot: AppImageExtractedRoot | null = null - class ReplacingAppImageInstaller extends CliInstaller { - protected override async ensureLinuxAppImagePayload(): Promise { - extractedRoot = await super.ensureLinuxAppImagePayload() - await writeFile(fixture.appImagePath, '#!/usr/bin/env bash\n# replacement generation\n', { - mode: 0o755 - }) - return extractedRoot - } - } - - const installer = new ReplacingAppImageInstaller(installerOptions(fixture)) - const installed = await installer.install() - const capturedRoot = extractedRoot as AppImageExtractedRoot | null - - expect(capturedRoot).not.toBeNull() - expect(installed).toMatchObject({ - state: 'stale', - launcherPath: capturedRoot!.stableLauncherPath - }) - await expect(readlink(fixture.commandPath)).resolves.toBe(capturedRoot!.stableLauncherPath) - await expect(lstat(capturedRoot!.stableLauncherPath)).resolves.toBeDefined() - await expect(installer.getStatus()).resolves.toMatchObject({ state: 'stale' }) - }) - - it('repairs the stable endpoint without reclaiming the prior path owner', async () => { - const fixture = await makeFixture() - const firstInstaller = new CliInstaller(installerOptions(fixture)) - const first = await firstInstaller.install() - const firstRoot = resolveAppImageExtractedRoot({ - appImagePath: fixture.appImagePath, - cacheRootPath: fixture.cacheRootPath - })! - const relocatedPath = join(fixture.root, 'downloads', 'Orca.AppImage') - await mkdir(dirname(relocatedPath), { recursive: true }) - await rename(fixture.appImagePath, relocatedPath) - const relocatedFixture = { ...fixture, appImagePath: relocatedPath } - const relocatedInstaller = new CliInstaller(installerOptions(relocatedFixture)) - - await expect(relocatedInstaller.getStatus()).resolves.toMatchObject({ state: 'stale' }) - const repaired = await relocatedInstaller.install() - const relocatedRoot = resolveAppImageExtractedRoot({ - appImagePath: relocatedPath, - cacheRootPath: fixture.cacheRootPath - })! - - expect(repaired).toMatchObject({ state: 'installed', launcherPath: first.launcherPath }) - await expect(readlink(fixture.commandPath)).resolves.toBe(first.launcherPath) - await expect(lstat(relocatedRoot.payloadLauncherPath)).resolves.toBeDefined() - // Relocation cannot prove that no sibling AppImage still owns the prior namespace. - await expect(lstat(firstRoot.rootPath)).resolves.toBeDefined() - }) - - it('preserves a foreign command that appears at the final ownership fence', async () => { - const fixture = await makeFixture() - const predictedRoot = resolveAppImageExtractedRoot({ - appImagePath: fixture.appImagePath, - cacheRootPath: fixture.cacheRootPath - })! - const ownedOldTarget = join( - dirname(predictedRoot.rootPath), - 'a'.repeat(24), - 'resources', - 'bin', - 'orca-ide' - ) - const foreignTarget = join(fixture.root, 'foreign', 'orca-ide') - await symlink(ownedOldTarget, fixture.commandPath) - - class RacedInstaller extends CliInstaller { - private inspectionCount = 0 - - protected override async inspectSymlink( - commandPath: string, - launcherPath: string - ): Promise { - this.inspectionCount += 1 - if (this.inspectionCount === 3) { - await unlink(commandPath) - await symlink(foreignTarget, commandPath) - } - return super.inspectSymlink(commandPath, launcherPath) - } - } - - await expect(new RacedInstaller(installerOptions(fixture)).install()).rejects.toThrow( - 'Refusing to replace non-Orca command' - ) - await expect(readlink(fixture.commandPath)).resolves.toBe(foreignTarget) - expect((await readdir(fixture.commandDirectory)).some((name) => name.includes('.orca-'))).toBe( - false - ) - }) }) diff --git a/src/main/cli/cli-installer-command-conflicts.test.ts b/src/main/cli/installation/cli-installer-command-conflicts.test.ts similarity index 99% rename from src/main/cli/cli-installer-command-conflicts.test.ts rename to src/main/cli/installation/cli-installer-command-conflicts.test.ts index f5ee0e5328a..1a8170ab461 100644 --- a/src/main/cli/cli-installer-command-conflicts.test.ts +++ b/src/main/cli/installation/cli-installer-command-conflicts.test.ts @@ -17,7 +17,7 @@ vi.mock('node:child_process', () => ({ execFile: execFileMock })) -import { CliInstaller } from './cli-installer' +import { CliInstaller } from '../cli-installer' import { createPackagedMacLauncher, makeFixture } from './cli-installer-test-fixtures' describe('CliInstaller', () => { diff --git a/src/main/cli/cli-installer-contracts.ts b/src/main/cli/installation/cli-installer-contracts.ts similarity index 87% rename from src/main/cli/cli-installer-contracts.ts rename to src/main/cli/installation/cli-installer-contracts.ts index 771c7c7256e..de131ff37a8 100644 --- a/src/main/cli/cli-installer-contracts.ts +++ b/src/main/cli/installation/cli-installer-contracts.ts @@ -1,5 +1,5 @@ -import type { CliInstallMethod } from '../../shared/cli-install-types' -import type { WindowsUserPathReadResult } from './windows-user-path-registry' +import type { CliInstallMethod } from '../../../shared/cli-install-types' +import type { WindowsUserPathReadResult } from '../command-paths/windows-user-path-registry' export type CliInstallerOptions = { platform?: NodeJS.Platform diff --git a/src/main/cli/cli-installer-macos-command-path.test.ts b/src/main/cli/installation/cli-installer-macos-command-path.test.ts similarity index 99% rename from src/main/cli/cli-installer-macos-command-path.test.ts rename to src/main/cli/installation/cli-installer-macos-command-path.test.ts index 5fd24329129..1c6f421a92e 100644 --- a/src/main/cli/cli-installer-macos-command-path.test.ts +++ b/src/main/cli/installation/cli-installer-macos-command-path.test.ts @@ -17,7 +17,7 @@ vi.mock('node:child_process', () => ({ execFile: execFileMock })) -import { CliInstaller } from './cli-installer' +import { CliInstaller } from '../cli-installer' import { createPackagedMacLauncher, makeFixture } from './cli-installer-test-fixtures' async function makeBundledLauncherFixture() { diff --git a/src/main/cli/cli-installer-test-fixtures.ts b/src/main/cli/installation/cli-installer-test-fixtures.ts similarity index 100% rename from src/main/cli/cli-installer-test-fixtures.ts rename to src/main/cli/installation/cli-installer-test-fixtures.ts diff --git a/src/main/cli/cli-installer-unreadable-command.test.ts b/src/main/cli/installation/cli-installer-unreadable-command.test.ts similarity index 97% rename from src/main/cli/cli-installer-unreadable-command.test.ts rename to src/main/cli/installation/cli-installer-unreadable-command.test.ts index 58314a684ae..99ad62bd6bc 100644 --- a/src/main/cli/cli-installer-unreadable-command.test.ts +++ b/src/main/cli/installation/cli-installer-unreadable-command.test.ts @@ -1,7 +1,7 @@ import { chmod, copyFile, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { CliInstaller } from './cli-installer' +import { CliInstaller } from '../cli-installer' import { createPackagedMacLauncher, makeFixture } from './cli-installer-test-fixtures' const roots: string[] = [] diff --git a/src/main/cli/cli-installer-windows-path.test.ts b/src/main/cli/installation/cli-installer-windows-path.test.ts similarity index 98% rename from src/main/cli/cli-installer-windows-path.test.ts rename to src/main/cli/installation/cli-installer-windows-path.test.ts index a0c7f5063f4..0f4cb56561b 100644 --- a/src/main/cli/cli-installer-windows-path.test.ts +++ b/src/main/cli/installation/cli-installer-windows-path.test.ts @@ -11,11 +11,11 @@ vi.mock('electron', () => ({ } })) -import { CliInstaller } from './cli-installer' +import { CliInstaller } from '../cli-installer' import { WindowsUserPathRegistryReader, type WindowsUserPathReadResult -} from './windows-user-path-registry' +} from '../command-paths/windows-user-path-registry' import { makeFixture } from './cli-installer-test-fixtures' function userPathRead(value: string | null, expandable = false): WindowsUserPathReadResult { diff --git a/src/main/cli/cli-privileged-processes.ts b/src/main/cli/installation/cli-privileged-processes.ts similarity index 95% rename from src/main/cli/cli-privileged-processes.ts rename to src/main/cli/installation/cli-privileged-processes.ts index 9167f1f8e55..d246b236573 100644 --- a/src/main/cli/cli-privileged-processes.ts +++ b/src/main/cli/installation/cli-privileged-processes.ts @@ -1,5 +1,5 @@ import { runProcess } from '@orca/process-host' -import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' +import { quotePowerShellLiteral } from '../../../shared/powershell-native-argument' import { WINDOWS_PATH_WRITE_TIMEOUT_MS } from './cli-install-constants' export async function runMacPrivilegedCommand(command: string): Promise { diff --git a/src/main/cli/cli-dev-launcher.ts b/src/main/cli/launchers/cli-dev-launcher.ts similarity index 93% rename from src/main/cli/cli-dev-launcher.ts rename to src/main/cli/launchers/cli-dev-launcher.ts index f385e74a961..5d4cb85302b 100644 --- a/src/main/cli/cli-dev-launcher.ts +++ b/src/main/cli/launchers/cli-dev-launcher.ts @@ -1,9 +1,12 @@ import { existsSync } from 'node:fs' import { mkdir, writeFile } from 'node:fs/promises' import { dirname, isAbsolute, join } from 'node:path' -import { DEV_COMMAND_NAME, DEV_LAUNCHER_DIR } from './cli-install-constants' -import { escapeWindowsBatchValue, isAbsoluteForPlatform } from './cli-install-path-format' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { DEV_COMMAND_NAME, DEV_LAUNCHER_DIR } from '../installation/cli-install-constants' +import { + escapeWindowsBatchValue, + isAbsoluteForPlatform +} from '../command-paths/cli-install-path-format' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' export async function ensureDevLauncher(args: { platform: NodeJS.Platform diff --git a/src/main/cli/linux-bare-orca-dispatcher-script.test.ts b/src/main/cli/launchers/linux-bare-orca-dispatcher-script.test.ts similarity index 73% rename from src/main/cli/linux-bare-orca-dispatcher-script.test.ts rename to src/main/cli/launchers/linux-bare-orca-dispatcher-script.test.ts index c1280526ff9..82c75a2f20e 100644 --- a/src/main/cli/linux-bare-orca-dispatcher-script.test.ts +++ b/src/main/cli/launchers/linux-bare-orca-dispatcher-script.test.ts @@ -93,43 +93,6 @@ describe.runIf(process.platform !== 'win32')('the bare orca dispatcher as a shel runOrca(fixture, [binDir, fixture.screenReaderDir], { ORCA_CLI_BIN_DIR: '/x' }).stdout ).toBe('ORCA_CLI status\n') }) - - async function addSecondDispatcher(fixture: { root: string; dispatcherPath: string }) { - const otherBin = join(fixture.root, 'other-home', '.local', 'bin') - await mkdir(otherBin, { recursive: true }) - await writeFile(join(otherBin, 'orca'), await readFile(fixture.dispatcherPath, 'utf8'), { - mode: 0o755 - }) - return otherBin - } - - it.each(['ORCA_PANE_KEY', 'ORCA_CLI_BIN_DIR', 'ORCA_USER_DATA_PATH'])( - 'never starts the screen reader for Orca children (%s) once Orca is gone', - async (variable) => { - const fixture = await makeFixture() - const otherBin = await addSecondDispatcher(fixture) - await rm(fixture.resourcesPath, { recursive: true, force: true }) - - const result = runOrca( - fixture, - [otherBin, join(fixture.homePath, '.local', 'bin'), fixture.screenReaderDir], - { [variable]: 'set' } - ) - expect(result.status).toBe(127) - expect(result.stdout).toBe('') - expect(result.stderr).toContain('Orca is no longer installed') - } - ) - - it('never loops when the only other `orca` is another dispatcher', async () => { - const fixture = await makeFixture() - const otherBin = await addSecondDispatcher(fixture) - await rm(fixture.resourcesPath, { recursive: true, force: true }) - - const result = runOrca(fixture, [join(fixture.homePath, '.local', 'bin'), otherBin]) - expect(result.status).toBe(127) - expect(result.stderr).toContain('Orca is no longer installed') - }) }) describe.runIf(process.platform !== 'win32')('removing the bare orca dispatcher', () => { diff --git a/src/main/cli/linux-bare-orca-dispatcher.test.ts b/src/main/cli/launchers/linux-bare-orca-dispatcher.test.ts similarity index 99% rename from src/main/cli/linux-bare-orca-dispatcher.test.ts rename to src/main/cli/launchers/linux-bare-orca-dispatcher.test.ts index b0b19412683..1abacfb68cf 100644 --- a/src/main/cli/linux-bare-orca-dispatcher.test.ts +++ b/src/main/cli/launchers/linux-bare-orca-dispatcher.test.ts @@ -40,7 +40,7 @@ vi.mock('electron', () => ({ app: { isPackaged: true } })) -vi.mock('./appimage-registration-lock', () => ({ +vi.mock('../appimage/appimage-registration-lock', () => ({ withAppImageRegistrationLock: async ( cacheRootPath: string, operation: () => Promise diff --git a/src/main/cli/linux-bare-orca-dispatcher.ts b/src/main/cli/launchers/linux-bare-orca-dispatcher.ts similarity index 94% rename from src/main/cli/linux-bare-orca-dispatcher.ts rename to src/main/cli/launchers/linux-bare-orca-dispatcher.ts index 154f7b3d8ac..788f728e42b 100644 --- a/src/main/cli/linux-bare-orca-dispatcher.ts +++ b/src/main/cli/launchers/linux-bare-orca-dispatcher.ts @@ -6,17 +6,17 @@ import { dirname, join } from 'node:path' import { hasAppImagePathEnvironment, resolveAppImageRuntimeIdentity -} from '../updater/linux-package/appimage-runtime-identity' +} from '../../updater/linux-package/appimage-runtime-identity' import { ensureAppImageExtractedRoot, resolveAppImageCacheRootPath, resolveLegacyAppImageNamespacePath -} from './appimage-extracted-root' -import { pruneAppImageExtractedRoots } from './appimage-extraction-pruning' -import { resolveGenerationStableLauncherPath } from './appimage-generation-stable-launcher' -import { withAppImageRegistrationLock } from './appimage-registration-lock' -import { getBundledLauncherPath } from './bundled-cli-launcher-path' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +} from '../appimage/appimage-extracted-root' +import { pruneAppImageExtractedRoots } from '../appimage/appimage-extraction-pruning' +import { resolveGenerationStableLauncherPath } from '../appimage/appimage-generation-stable-launcher' +import { withAppImageRegistrationLock } from '../appimage/appimage-registration-lock' +import { getBundledLauncherPath } from '../packaged-assets/bundled-cli-launcher-path' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' // Only marked dispatchers may be replaced; user-owned commands must survive repeat starts. const DISPATCHER_MARKER = '# orca-serve-bare-orca-dispatcher' diff --git a/src/main/cli/linux-terminal-orca-cli-shim.test.ts b/src/main/cli/launchers/linux-terminal-orca-cli-shim.test.ts similarity index 52% rename from src/main/cli/linux-terminal-orca-cli-shim.test.ts rename to src/main/cli/launchers/linux-terminal-orca-cli-shim.test.ts index 754503b414c..8319cd73142 100644 --- a/src/main/cli/linux-terminal-orca-cli-shim.test.ts +++ b/src/main/cli/launchers/linux-terminal-orca-cli-shim.test.ts @@ -1,4 +1,4 @@ -import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -9,7 +9,7 @@ vi.mock('electron', () => ({ app: { isPackaged: true } })) -import { resolveAppImageLauncherEndpointPath } from './appimage-stable-launcher' +import { resolveAppImageLauncherEndpointPath } from '../appimage/appimage-stable-launcher' import { ensureLinuxTerminalOrcaCliShimDir } from './linux-terminal-orca-cli-shim' const created: string[] = [] @@ -30,37 +30,6 @@ afterEach(async () => { }) describe('ensureLinuxTerminalOrcaCliShimDir', () => { - it('reuses the shim path and re-asserts its exec bit', async () => { - const { userDataPath, resourcesPath } = await makeFixture() - const options = { userDataPath, resourcesPath, appImagePath: null } - - const first = ensureLinuxTerminalOrcaCliShimDir(options) - expect(first).not.toBeNull() - const shimPath = join(first!, 'orca') - chmodSync(shimPath, 0o644) - - const second = ensureLinuxTerminalOrcaCliShimDir(options) - expect(second).toBe(first) - expect(statSync(shimPath).mode & 0o111).not.toBe(0) - - const root = await mkdtemp(join(tmpdir(), 'orca-terminal-cli-shim-2-')) - created.push(root) - const otherUserData = join(root, 'user-data') - mkdirSync(join(otherUserData, 'linux-orca-cli-shim'), { recursive: true }) - writeFileSync(join(otherUserData, 'linux-orca-cli-shim', 'orca'), 'stale contents', 'utf8') - chmodSync(join(otherUserData, 'linux-orca-cli-shim', 'orca'), 0o644) - - const healed = ensureLinuxTerminalOrcaCliShimDir({ - userDataPath: otherUserData, - resourcesPath, - appImagePath: null - }) - expect(healed).not.toBeNull() - const healedPath = join(healed!, 'orca') - expect(readFileSync(healedPath, 'utf8')).toContain('orca-ide') - expect(statSync(healedPath).mode & 0o111).not.toBe(0) - }) - it.skipIf(!canFenceAppImageRuntime)( 'routes first-use AppImage terminals through a fenced current mount without a live endpoint', async () => { @@ -90,46 +59,6 @@ describe('ensureLinuxTerminalOrcaCliShimDir', () => { } ) - it.skipIf(!canFenceAppImageRuntime)( - 'refreshes restored terminals to the current AppImage mount', - async () => { - const { userDataPath, resourcesPath } = await makeFixture() - const appImagePath = join(userDataPath, 'Orca.AppImage') - await mkdir(userDataPath, { recursive: true }) - await writeFile(appImagePath, '#!/usr/bin/env bash\n', { encoding: 'utf8', mode: 0o755 }) - const cacheRootPath = join(userDataPath, 'cache') - const firstLauncher = join(resourcesPath, 'bin', 'orca-ide') - writeFileSync(firstLauncher, '#!/usr/bin/env bash\nprintf first', 'utf8') - chmodSync(firstLauncher, 0o755) - const options = { - userDataPath, - resourcesPath, - appImagePath, - appImageCacheRootPath: cacheRootPath - } - const shimDir = ensureLinuxTerminalOrcaCliShimDir(options) - const shimPath = join(shimDir!, 'orca') - const originalShim = readFileSync(shimPath, 'utf8') - - const nextResourcesPath = join(userDataPath, 'next-mount', 'resources') - const nextLauncher = join(nextResourcesPath, 'bin', 'orca-ide') - await mkdir(join(nextResourcesPath, 'bin'), { recursive: true }) - await writeFile(nextLauncher, '#!/usr/bin/env bash\nprintf next', { mode: 0o755 }) - await rm(firstLauncher) - expect( - ensureLinuxTerminalOrcaCliShimDir({ ...options, resourcesPath: nextResourcesPath }) - ).toBe(shimDir) - - const refreshedShim = readFileSync(shimPath, 'utf8') - expect(refreshedShim).not.toBe(originalShim) - expect(refreshedShim).toContain(nextLauncher) - expect(existsSync(resolveAppImageLauncherEndpointPath(cacheRootPath, 'live'))).toBe(false) - await expect( - runProcess({ program: shimPath, args: [], timeoutMs: 3_000 }) - ).resolves.toMatchObject({ code: 0, stdout: 'next' }) - } - ) - it.skipIf(!canFenceAppImageRuntime)( 'rejects a stale shim when its mount path is removed and reused', async () => { diff --git a/src/main/cli/linux-terminal-orca-cli-shim.ts b/src/main/cli/launchers/linux-terminal-orca-cli-shim.ts similarity index 94% rename from src/main/cli/linux-terminal-orca-cli-shim.ts rename to src/main/cli/launchers/linux-terminal-orca-cli-shim.ts index 1cd21bd63bc..7b7a0ad1104 100644 --- a/src/main/cli/linux-terminal-orca-cli-shim.ts +++ b/src/main/cli/launchers/linux-terminal-orca-cli-shim.ts @@ -11,18 +11,18 @@ import { dirname, join, resolve } from 'node:path' import { hasAppImagePathEnvironment, resolveAppImageRuntimeIdentity -} from '../updater/linux-package/appimage-runtime-identity' +} from '../../updater/linux-package/appimage-runtime-identity' import { getAppImageCacheRootPath, isAppImageInstalledLauncherCurrent -} from './appimage-extracted-root' +} from '../appimage/appimage-extracted-root' import { ensureAppImageStableLauncher, removeAppImageLegacyLiveEndpoint -} from './appimage-stable-launcher' -import { getBundledLauncherPath } from './bundled-cli-launcher-path' +} from '../appimage/appimage-stable-launcher' +import { getBundledLauncherPath } from '../packaged-assets/bundled-cli-launcher-path' import { buildBareOrcaCliScript } from './linux-bare-orca-dispatcher' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' const SHIM_DIR_NAME = 'linux-orca-cli-shim' diff --git a/src/main/cli/native-cli-powershell-argv-boundary.test.ts b/src/main/cli/launchers/native-cli-powershell-argv-boundary.test.ts similarity index 94% rename from src/main/cli/native-cli-powershell-argv-boundary.test.ts rename to src/main/cli/launchers/native-cli-powershell-argv-boundary.test.ts index 53883fd5919..14d32a00f3d 100644 --- a/src/main/cli/native-cli-powershell-argv-boundary.test.ts +++ b/src/main/cli/launchers/native-cli-powershell-argv-boundary.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' import { windowsPowerShellPath } from '@orca/process-host/windows-system-binary' -import { parseOrchestrationTaskDepsFlag } from '../runtime/orchestration/coordinator/dispatch/task-deps-flag' +import { parseOrchestrationTaskDepsFlag } from '../../runtime/orchestration/coordinator/dispatch/task-deps-flag' const PARENT_TASK_ID = 'task_b2a580db74d8' diff --git a/src/main/cli/orca-cli-child-path.test.ts b/src/main/cli/launchers/orca-cli-child-path.test.ts similarity index 81% rename from src/main/cli/orca-cli-child-path.test.ts rename to src/main/cli/launchers/orca-cli-child-path.test.ts index 59bedaadec6..9a5773caecf 100644 --- a/src/main/cli/orca-cli-child-path.test.ts +++ b/src/main/cli/launchers/orca-cli-child-path.test.ts @@ -1,6 +1,6 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' const shim = vi.hoisted(() => ({ ensureLinuxTerminalOrcaCliShimDir: vi.fn() })) vi.mock('./linux-terminal-orca-cli-shim', () => shim) @@ -45,23 +45,6 @@ describe('prependOrcaCliDirToChildPath', () => { expect(shim.ensureLinuxTerminalOrcaCliShimDir).not.toHaveBeenCalled() } ) - it('exports the owning packaged Linux launcher and profile together with PATH', () => { - const env = { - PATH: `/usr/bin:${SHIM_DIR}::/bin`, - ORCA_CLI_COMMAND: '/other/orca', - ORCA_USER_DATA_PATH: '/other/profile' - } - const launcher = prependOrcaCliDirToChildPath(env, { - isPackaged: true, - userDataPath: USER_DATA, - platform: 'linux' - }) - - expect(launcher).toBe(join(SHIM_DIR, 'orca')) - expect(env.ORCA_CLI_COMMAND).toBe(launcher) - expect(env.ORCA_USER_DATA_PATH).toBe(USER_DATA) - expect(env.PATH).toBe(`${SHIM_DIR}:/usr/bin:/bin`) - }) it('puts a Windows execution host CLI first on Path without a POSIX restore dir', () => { const binDir = join(USER_DATA, 'cli', 'bin') diff --git a/src/main/cli/orca-cli-child-path.ts b/src/main/cli/launchers/orca-cli-child-path.ts similarity index 89% rename from src/main/cli/orca-cli-child-path.ts rename to src/main/cli/launchers/orca-cli-child-path.ts index d5d7478a474..82d10f4b835 100644 --- a/src/main/cli/orca-cli-child-path.ts +++ b/src/main/cli/launchers/orca-cli-child-path.ts @@ -1,11 +1,11 @@ // PTY and structured children must reach this app's CLI regardless of global registration. import { delimiter, dirname, join } from 'node:path' -import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' -import { readInheritedPath } from '../ipc/pty/host-env/path' -import { resolvePathEnvKey } from '../pty/environment/windows-path-segment-merge' +import { getAppEnvironment, hasAppEnvironment } from '../../../shared/app-environment' +import { readInheritedPath } from '../../ipc/pty/host-env/path' +import { resolvePathEnvKey } from '../../pty/environment/windows-path-segment-merge' import { ensureLinuxTerminalOrcaCliShimDir } from './linux-terminal-orca-cli-shim' -import { getBundledLauncherPath } from './bundled-cli-launcher-path' -import { DEV_COMMAND_NAME } from './cli-install-constants' +import { getBundledLauncherPath } from '../packaged-assets/bundled-cli-launcher-path' +import { DEV_COMMAND_NAME } from '../installation/cli-install-constants' export type OrcaCliChildPathOptions = { isPackaged: boolean diff --git a/src/main/cli/workspace-choice-argv-boundary.test.ts b/src/main/cli/launchers/workspace-choice-argv-boundary.test.ts similarity index 100% rename from src/main/cli/workspace-choice-argv-boundary.test.ts rename to src/main/cli/launchers/workspace-choice-argv-boundary.test.ts diff --git a/src/main/cli/bundled-cli-launcher-path.ts b/src/main/cli/packaged-assets/bundled-cli-launcher-path.ts similarity index 100% rename from src/main/cli/bundled-cli-launcher-path.ts rename to src/main/cli/packaged-assets/bundled-cli-launcher-path.ts diff --git a/src/main/cli/packaged-assets/packaged-cli-assets.test.ts b/src/main/cli/packaged-assets/packaged-cli-assets.test.ts new file mode 100644 index 00000000000..31403cc55a6 --- /dev/null +++ b/src/main/cli/packaged-assets/packaged-cli-assets.test.ts @@ -0,0 +1,95 @@ +import { execFile } from 'node:child_process' + +import { copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' + +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { promisify } from 'node:util' + +import { describe, expect, it } from 'vitest' + +const execFileAsync = promisify(execFile) +const itRunsUnixShell = process.platform === 'win32' ? it.skip : it + +const linuxLauncherAsset = new URL('../../../../resources/linux/bin/orca-ide', import.meta.url) +const darwinLauncherAsset = new URL('../../../../resources/darwin/bin/orca', import.meta.url) +const unixLauncherFixtures = [ + { + name: 'Linux', + asset: linuxLauncherAsset, + appDir: ['Orca'], + launcher: ['resources', 'bin', 'orca-ide'], + executable: ['orca-ide'], + cli: ['resources', 'app.asar.unpacked', 'out', 'cli', 'index.js'] + }, + { + name: 'macOS', + asset: darwinLauncherAsset, + appDir: ['Orca.app'], + launcher: ['Contents', 'Resources', 'bin', 'orca'], + executable: ['Contents', 'MacOS', 'Orca'], + cli: ['Contents', 'Resources', 'app.asar.unpacked', 'out', 'cli', 'index.js'] + } +] as const + +describe('packaged CLI assets', () => { + itRunsUnixShell.each(unixLauncherFixtures)( + 'sanitizes node env and forwards argv verbatim through the $name launcher', + async (launcherFixture) => { + const root = await mkdtemp(join(tmpdir(), 'orca-unix-cli-env-')) + try { + const appDir = join(root, ...launcherFixture.appDir) + const launcherPath = join(appDir, ...launcherFixture.launcher) + const electronPath = join(appDir, ...launcherFixture.executable) + const cliPath = join(appDir, ...launcherFixture.cli) + + await mkdir(dirname(launcherPath), { recursive: true }) + await mkdir(dirname(electronPath), { recursive: true }) + await mkdir(dirname(cliPath), { recursive: true }) + await copyFile(launcherFixture.asset, launcherPath) + await writeFile(cliPath, '', 'utf8') + await writeFile( + electronPath, + `#!/usr/bin/env bash +node -e 'console.log(JSON.stringify({ + argv: process.argv.slice(1), + runAsNode: process.env.ELECTRON_RUN_AS_NODE, + nodeOptions: process.env.NODE_OPTIONS ?? null, + orcaNodeOptions: process.env.ORCA_NODE_OPTIONS ?? null, + nodeReplExternalModule: process.env.NODE_REPL_EXTERNAL_MODULE ?? null, + orcaNodeReplExternalModule: process.env.ORCA_NODE_REPL_EXTERNAL_MODULE ?? null +}))' -- "$@" +`, + { encoding: 'utf8', mode: 0o755 } + ) + + const result = await execFileAsync(launcherPath, ['--help', 'two words'], { + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: '0', + NODE_OPTIONS: '--trace-warnings', + NODE_REPL_EXTERNAL_MODULE: 'external-loader' + } + }) + const payload = JSON.parse(result.stdout) as { + argv: string[] + runAsNode: string + nodeOptions: string | null + orcaNodeOptions: string | null + nodeReplExternalModule: string | null + orcaNodeReplExternalModule: string | null + } + + expect(payload.argv).toEqual([cliPath, '--help', 'two words']) + expect(payload.runAsNode).toBe('1') + // Hide node options from Electron's bootstrap but preserve them for the CLI. + expect(payload.nodeOptions).toBeNull() + expect(payload.orcaNodeOptions).toBe('--trace-warnings') + expect(payload.nodeReplExternalModule).toBeNull() + expect(payload.orcaNodeReplExternalModule).toBe('external-loader') + } finally { + await rm(root, { recursive: true, force: true }) + } + } + ) +}) diff --git a/src/main/cli/packaged-cli-assets.test.ts b/src/main/cli/packaged-cli-assets.test.ts deleted file mode 100644 index 650401036db..00000000000 --- a/src/main/cli/packaged-cli-assets.test.ts +++ /dev/null @@ -1,366 +0,0 @@ -import { execFile, spawn } from 'node:child_process' -import { globSync } from 'node:fs' -import { copyFile, cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { dirname, join, sep } from 'node:path' -import { promisify } from 'node:util' -import { fileURLToPath } from 'node:url' -import { createPackageWithOptions, statFile } from '@electron/asar' -import { describe, expect, it } from 'vitest' -import { runProcess } from '@orca/process-host' -import { stagePackagedProcessHost } from '../../../config/scripts/desktop-distribution/runtime-verification/packaged-process-host-fixture.mjs' - -const require = createRequire(import.meta.url) -const execFileAsync = promisify(execFile) -const itRunsUnixShell = process.platform === 'win32' ? it.skip : it -const unixTerminationSignals = ['SIGINT', 'SIGTERM'] as const -const builderConfig = require('../../../config/electron-builder.config.cjs') as { - files?: string[] - asarUnpack?: string[] -} -const linuxLauncherAsset = new URL('../../../resources/linux/bin/orca-ide', import.meta.url) -const darwinLauncherAsset = new URL('../../../resources/darwin/bin/orca', import.meta.url) -const unixLauncherFixtures = [ - { - name: 'Linux', - asset: linuxLauncherAsset, - appDir: ['Orca'], - launcher: ['resources', 'bin', 'orca-ide'], - executable: ['orca-ide'], - cli: ['resources', 'app.asar.unpacked', 'out', 'cli', 'index.js'] - }, - { - name: 'macOS', - asset: darwinLauncherAsset, - appDir: ['Orca.app'], - launcher: ['Contents', 'Resources', 'bin', 'orca'], - executable: ['Contents', 'MacOS', 'Orca'], - cli: ['Contents', 'Resources', 'app.asar.unpacked', 'out', 'cli', 'index.js'] - } -] as const - -describe('packaged CLI assets', () => { - it('loads worktree link validation from the installed CLI', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-cli-gitlab-package-')) - const projectDir = fileURLToPath(new URL('../../../', import.meta.url)) - const source = join(root, 'app-source') - const archive = join(root, 'resources', 'app.asar') - try { - const compile = await runProcess({ - program: process.execPath, - args: [ - join(projectDir, 'node_modules', 'typescript', 'bin', 'tsc'), - '-p', - join(projectDir, 'config', 'tsconfig.build.cli.json'), - '--outDir', - join(source, 'out'), - '--composite', - 'false', - '--incremental', - 'false', - // This fixture checks the emitted package; the CLI typecheck runs separately. - '--noCheck' - ], - cwd: projectDir, - timeoutMs: 60_000 - }) - expect(compile.code, compile.stdout + compile.stderr).toBe(0) - expect(globSync('**/*.{test,spec}.{js,jsx,cjs,mjs}', { cwd: join(source, 'out') })).toEqual( - [] - ) - await mkdir(dirname(archive), { recursive: true }) - await writeFile(join(source, 'out', 'package.json'), JSON.stringify({ type: 'commonjs' })) - for (const name of ['zod', 'tweetnacl', 'smol-toml']) { - await cp( - join(projectDir, 'node_modules', name), - join(root, 'resources', 'node_modules', name), - { - recursive: true, - dereference: true - } - ) - } - await stagePackagedProcessHost(join(root, 'resources')) - await createPackageWithOptions(source, archive, { - unpack: `{${builderConfig.asarUnpack?.map((pattern) => join(source, pattern).split(sep).join('/')).join(',')}}` - }) - expect(statFile(archive, join('out', 'cli', 'index.js')).unpacked).toBe(true) - const result = await runProcess({ - program: process.execPath, - args: [ - join(`${archive}.unpacked`, 'out', 'cli', 'index.js'), - 'worktree', - 'create', - '--repo', - 'id:repo', - '--name', - 'packaged-link', - '--no-parent', - '--pr', - '0', - '--json' - ], - cwd: root, - env: { - ...process.env, - ORCA_BACKGROUND_LAUNCH: '1', - NODE_PATH: '', - NODE_OPTIONS: '', - ORCA_USER_DATA_PATH: join(root, 'user-data'), - HOME: join(root, 'home') - }, - timeoutMs: 10_000 - }) - expect(result.code, result.stderr).toBe(1) - expect(JSON.parse(result.stdout)).toMatchObject({ - ok: false, - error: { code: 'invalid_argument', message: 'Pass a positive safe integer for --pr.' } - }) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) - - itRunsUnixShell.each(unixLauncherFixtures)( - 'delivers Unix termination signals to the $name executable and releases its listener', - async (launcherFixture) => { - for (const signal of unixTerminationSignals) { - const root = await mkdtemp(join(tmpdir(), 'orca-unix-cli-signal-')) - const appDir = join(root, ...launcherFixture.appDir) - const launcherPath = join(appDir, ...launcherFixture.launcher) - const electronPath = join(appDir, ...launcherFixture.executable) - const cliPath = join(appDir, ...launcherFixture.cli) - const statePath = join(root, `${signal}-listener-state.json`) - let executablePid: number | null = null - let launcher: ReturnType | null = null - try { - await mkdir(dirname(launcherPath), { recursive: true }) - await mkdir(dirname(electronPath), { recursive: true }) - await mkdir(dirname(cliPath), { recursive: true }) - await copyFile(launcherFixture.asset, launcherPath) - await writeFile(cliPath, '', 'utf8') - await writeFile( - electronPath, - `#!/usr/bin/env node -const fs = require('node:fs') -const net = require('node:net') -const server = net.createServer() -const shutdown = () => server.close(() => process.exit(0)) -process.on('SIGINT', shutdown) -process.on('SIGTERM', shutdown) -server.listen(0, '127.0.0.1', () => { - fs.writeFileSync(process.env.ORCA_TEST_LISTENER_STATE, JSON.stringify({ - pid: process.pid, - port: server.address().port - })) -}) -`, - { encoding: 'utf8', mode: 0o755 } - ) - - launcher = spawn(launcherPath, [], { - env: { ...process.env, ORCA_TEST_LISTENER_STATE: statePath }, - stdio: 'ignore' - }) - const state = await waitForListenerState(statePath) - executablePid = state.pid - const launcherPid = launcher.pid - const launcherExitPromise = waitForChildExit(launcher, 5_000) - launcher.kill(signal) - const launcherExit = await launcherExitPromise - const exitCode = launcherExit?.[0] - const exitSignal = launcherExit?.[1] - - expect.soft(executablePid).toBe(launcherPid) - expect.soft(launcherExit).not.toBeNull() - expect.soft(exitCode).toBe(0) - expect.soft(exitSignal).toBeNull() - expect.soft(await waitForPortRelease(state.port)).toBe(true) - } finally { - if (launcher?.pid) { - await terminateSyntheticProcess(launcher.pid) - } - if (executablePid && executablePid !== launcher?.pid) { - await terminateSyntheticProcess(executablePid) - } - await rm(root, { recursive: true, force: true }) - } - } - } - ) - - itRunsUnixShell.each(unixLauncherFixtures)( - 'sanitizes node env and forwards argv verbatim through the $name launcher', - async (launcherFixture) => { - const root = await mkdtemp(join(tmpdir(), 'orca-unix-cli-env-')) - try { - const appDir = join(root, ...launcherFixture.appDir) - const launcherPath = join(appDir, ...launcherFixture.launcher) - const electronPath = join(appDir, ...launcherFixture.executable) - const cliPath = join(appDir, ...launcherFixture.cli) - - await mkdir(dirname(launcherPath), { recursive: true }) - await mkdir(dirname(electronPath), { recursive: true }) - await mkdir(dirname(cliPath), { recursive: true }) - await copyFile(launcherFixture.asset, launcherPath) - await writeFile(cliPath, '', 'utf8') - await writeFile( - electronPath, - `#!/usr/bin/env bash -node -e 'console.log(JSON.stringify({ - argv: process.argv.slice(1), - runAsNode: process.env.ELECTRON_RUN_AS_NODE, - nodeOptions: process.env.NODE_OPTIONS ?? null, - orcaNodeOptions: process.env.ORCA_NODE_OPTIONS ?? null, - nodeReplExternalModule: process.env.NODE_REPL_EXTERNAL_MODULE ?? null, - orcaNodeReplExternalModule: process.env.ORCA_NODE_REPL_EXTERNAL_MODULE ?? null -}))' -- "$@" -`, - { encoding: 'utf8', mode: 0o755 } - ) - - const result = await execFileAsync(launcherPath, ['--help', 'two words'], { - env: { - ...process.env, - ELECTRON_RUN_AS_NODE: '0', - NODE_OPTIONS: '--trace-warnings', - NODE_REPL_EXTERNAL_MODULE: 'external-loader' - } - }) - const payload = JSON.parse(result.stdout) as { - argv: string[] - runAsNode: string - nodeOptions: string | null - orcaNodeOptions: string | null - nodeReplExternalModule: string | null - orcaNodeReplExternalModule: string | null - } - - expect(payload.argv).toEqual([cliPath, '--help', 'two words']) - expect(payload.runAsNode).toBe('1') - // Hide node options from Electron's bootstrap but preserve them for the CLI. - expect(payload.nodeOptions).toBeNull() - expect(payload.orcaNodeOptions).toBe('--trace-warnings') - expect(payload.nodeReplExternalModule).toBeNull() - expect(payload.orcaNodeReplExternalModule).toBe('external-loader') - } finally { - await rm(root, { recursive: true, force: true }) - } - } - ) -}) - -async function waitForListenerState(path: string): Promise<{ pid: number; port: number }> { - const deadline = Date.now() + 5_000 - while (Date.now() < deadline) { - try { - const state: unknown = JSON.parse(await readFile(path, 'utf8')) - if ( - typeof state !== 'object' || - state === null || - !('pid' in state) || - typeof state.pid !== 'number' || - !Number.isInteger(state.pid) || - state.pid <= 0 || - !('port' in state) || - typeof state.port !== 'number' || - !Number.isInteger(state.port) || - state.port <= 0 || - state.port > 65_535 - ) { - throw new Error('Invalid launcher listener state') - } - return { pid: state.pid, port: state.port } - } catch (error) { - if (!(error instanceof SyntaxError) && (error as NodeJS.ErrnoException).code !== 'ENOENT') { - throw error - } - await new Promise((resolve) => setTimeout(resolve, 10)) - } - } - throw new Error('Timed out waiting for launcher listener state') -} - -async function waitForPortRelease(port: number): Promise { - const { createConnection } = await import('node:net') - const deadline = Date.now() + 2_000 - while (Date.now() < deadline) { - const connected = await new Promise((resolve) => { - const socket = createConnection({ host: '127.0.0.1', port }) - socket.once('connect', () => { - socket.destroy() - resolve(true) - }) - socket.once('error', () => resolve(false)) - }) - if (!connected) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 10)) - } - return false -} - -function isProcessAlive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch { - return false - } -} - -function waitForChildExit( - child: ReturnType, - timeoutMs: number -): Promise { - return new Promise((resolve) => { - if (child.exitCode !== null || child.signalCode !== null) { - resolve([child.exitCode, child.signalCode]) - return - } - const onExit = (code: number | null, signal: NodeJS.Signals | null): void => { - clearTimeout(timeout) - resolve([code, signal]) - } - const timeout = setTimeout(() => { - child.off('exit', onExit) - resolve(null) - }, timeoutMs) - child.once('exit', onExit) - }) -} - -async function terminateSyntheticProcess(pid: number): Promise { - if (!isProcessAlive(pid)) { - return - } - try { - process.kill(pid, 'SIGTERM') - } catch { - return - } - if (await waitForProcessExit(pid, 1_000)) { - return - } - try { - process.kill(pid, 'SIGKILL') - } catch { - return - } - if (!(await waitForProcessExit(pid, 1_000))) { - throw new Error(`Failed to terminate synthetic launcher process ${pid}`) - } -} - -async function waitForProcessExit(pid: number, timeoutMs: number): Promise { - const deadline = Date.now() + timeoutMs - while (Date.now() < deadline) { - if (!isProcessAlive(pid)) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 10)) - } - return !isProcessAlive(pid) -} diff --git a/src/main/cli/wsl-cli-installer.test.ts b/src/main/cli/wsl-cli-installer.test.ts deleted file mode 100644 index 9bdf1717b99..00000000000 --- a/src/main/cli/wsl-cli-installer.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' -import { execFileSync } from 'node:child_process' -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const runWslProcessMock = vi.hoisted(() => vi.fn()) - -vi.mock('../wsl/execution/wsl-runner', () => ({ - runWslProcess: runWslProcessMock -})) - -import { WslCliInstaller, _internals } from './wsl-cli-installer' - -function makeHostStatus( - launcherPath = 'C:\\Users\\me\\AppData\\Local\\Programs\\Orca\\resources\\bin\\orca.exe' -) { - return { - platform: 'win32', - commandName: 'orca', - commandPath: launcherPath, - pathDirectory: 'C:\\Users\\me\\AppData\\Local\\Programs\\Orca\\resources\\bin', - pathConfigured: true, - launcherPath, - installMethod: 'wrapper', - supported: true, - state: 'installed', - currentTarget: launcherPath, - unsupportedReason: null, - detail: null - } satisfies CliInstallStatus -} - -// Frozen from v1.4.138-rc.2: the upgrade regression only reproduces when the -// persisted managed script still names the pre-native Windows batch launcher. -const PRE_RC4_MANAGED_WSL_LAUNCHER = `#!/usr/bin/env bash -set -euo pipefail -# Orca managed WSL CLI launcher -# ORCA_WIN_LAUNCHER_B64=QzpcUHJvZ3JhbSBGaWxlc1xPcmNhXHJlc291cmNlc1xiaW5cb3JjYS5jbWQ= -ORCA_WIN_LAUNCHER='C:\\Program Files\\Orca\\resources\\bin\\orca.cmd' -ORCA_BRIDGE_PS1='/home/alice/.local/share/orca/orca-wsl-bridge.ps1' -if command -v powershell.exe >/dev/null 2>&1; then - ORCA_POWERSHELL=powershell.exe -elif [ -x /mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe ]; then - ORCA_POWERSHELL=/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -else - echo "Orca WSL CLI requires Windows interop and could not find powershell.exe." >&2 - exit 1 -fi -ORCA_BRIDGE_PS1_WIN=$(wslpath -w "$ORCA_BRIDGE_PS1") -exec "$ORCA_POWERSHELL" -NoProfile -ExecutionPolicy Bypass -File "$ORCA_BRIDGE_PS1_WIN" "$ORCA_WIN_LAUNCHER" "$@" -` - -describe('WslCliInstaller', () => { - beforeEach(() => { - runWslProcessMock.mockReset() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it.skipIf(process.platform === 'win32')( - 'rolls both files back when the command replacement fails after the bridge move', - async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-wsl-cli-rollback-')) - const home = join(root, 'home with spaces') - const commandPath = join(home, '.local', 'bin', 'orca-ide') - const bridgePath = join(home, '.local', 'share', 'orca', 'orca-wsl-bridge.ps1') - const bridge = _internals.buildWslBridgeScript() - await mkdir(join(home, '.local', 'bin'), { recursive: true }) - await mkdir(join(home, '.local', 'share', 'orca'), { recursive: true }) - await writeFile(commandPath, PRE_RC4_MANAGED_WSL_LAUNCHER, 'utf8') - await writeFile(bridgePath, bridge, 'utf8') - - const runner = async (_distro: string, command: string): Promise => { - if (command.includes('printf %s "$HOME"')) { - return home - } - if (command.includes('cat > "$command_tmp"')) { - const executableCommand = command - .split('\n') - .map((line) => (line.startsWith('mv -f "$command_tmp" ') ? 'exit 71' : line)) - .join('\n') - return execFileSync('bash', ['-c', executableCommand], { encoding: 'utf8' }) - } - if (command.includes('command -v powershell.exe')) { - return 'yes' - } - if (command.includes('case ":$PATH:"')) { - return 'yes' - } - return execFileSync('bash', ['-c', command], { encoding: 'utf8' }) - } - const installer = new WslCliInstaller({ - platform: 'win32', - distro: 'Ubuntu', - hostInstaller: { - getStatus: async () => makeHostStatus('C:\\Program Files\\Orca\\resources\\bin\\orca.exe') - }, - wslRunner: runner - }) - - try { - await expect(installer.repairManagedRegistration()).rejects.toThrow() - await expect(readFile(commandPath, 'utf8')).resolves.toBe(PRE_RC4_MANAGED_WSL_LAUNCHER) - await expect(readFile(bridgePath, 'utf8')).resolves.toBe(bridge) - } finally { - await rm(root, { recursive: true, force: true }) - } - } - ) -}) diff --git a/src/main/cli/wsl-cli-installer.ts b/src/main/cli/wsl/wsl-cli-installer.ts similarity index 96% rename from src/main/cli/wsl-cli-installer.ts rename to src/main/cli/wsl/wsl-cli-installer.ts index cfb1410ee9b..b2c33e1cc4c 100644 --- a/src/main/cli/wsl-cli-installer.ts +++ b/src/main/cli/wsl/wsl-cli-installer.ts @@ -1,8 +1,8 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' -import { getDefaultWslDistro } from '../wsl/discovery/distro-catalog' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import { describeWslProcessFailure } from '../wsl/execution/wsl-process-failure' -import { CliInstaller } from './cli-installer' +import type { CliInstallStatus } from '../../../shared/cli-install-types' +import { getDefaultWslDistro } from '../../wsl/discovery/distro-catalog' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import { describeWslProcessFailure } from '../../wsl/execution/wsl-process-failure' +import { CliInstaller } from '../cli-installer' import { buildManagedLegacyRemoveCommand, buildSafeRemoveCommand, @@ -14,7 +14,7 @@ import { getWslLauncherMarker, parseManagedLauncherTarget } from './wsl-cli-scripts' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' import { buildWslCliInstallCommand } from './wsl-cli-registration-command' import { buildWslCliStatus, diff --git a/src/main/cli/wsl-cli-powershell-boundary.test.ts b/src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts similarity index 74% rename from src/main/cli/wsl-cli-powershell-boundary.test.ts rename to src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts index d9e1685601f..dbd19324100 100644 --- a/src/main/cli/wsl-cli-powershell-boundary.test.ts +++ b/src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts @@ -1,11 +1,11 @@ import { spawnSync } from 'node:child_process' -import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises' -import { removeTree } from '../../shared/windows-transient-lock-removal' +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises' +import { removeTree } from '../../../shared/windows-transient-lock-removal' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { runProcessSync } from '@orca/process-host' -import { buildWslBridgeScript, buildWslLauncher } from './wsl-cli-scripts' + +import { buildWslBridgeScript } from './wsl-cli-scripts' const FORWARDED_ARGS = [ 'terminal', @@ -33,58 +33,6 @@ const FORWARDED_ARGS = [ ] describe('WSL CLI PowerShell boundary', () => { - it.skipIf(process.platform === 'win32')( - 'forwards the distro as one argument and omits it when absent', - async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-wsl-launcher-argv-')) - try { - const launcherPath = join(root, 'launcher.sh') - const expectedCwd = await realpath(root) - await writeFile(launcherPath, buildWslLauncher('C:\\Orca\\orca.exe', '/bridge.ps1')) - await writeFile(join(root, 'wslpath'), '#!/bin/bash\nprintf "%s" "$2"\n', { - mode: 0o700 - }) - await writeFile(join(root, 'powershell.exe'), '#!/bin/bash\nprintf "%s\\0" "$@"\n', { - mode: 0o700 - }) - for (const distro of [undefined, '', 'Ubuntu Work']) { - const env: NodeJS.ProcessEnv = { - ...process.env, - PATH: `${root}:${process.env.PATH ?? ''}` - } - delete env.WSL_DISTRO_NAME - if (distro !== undefined) { - env.WSL_DISTRO_NAME = distro - } - const result = runProcessSync({ - program: '/bin/bash', - args: [launcherPath, 'account', 'add', '--agent', 'codex'], - env, - cwd: root - }) - expect(result.code).toBe(0) - expect(result.stdout.split('\0').slice(0, -1)).toEqual([ - '-NoProfile', - '-ExecutionPolicy', - 'Bypass', - '-File', - '/bridge.ps1', - 'C:\\Orca\\orca.exe', - '-WslCwd', - expectedCwd, - ...(distro ? ['-WslDistro', distro] : []), - 'account', - 'add', - '--agent', - 'codex' - ]) - } - } finally { - await removeTree(root) - } - } - ) - it.skipIf(process.platform !== 'win32')( 'preserves native argv and exit status through Windows PowerShell 5.1', async () => { diff --git a/src/main/cli/wsl-cli-registration-command.ts b/src/main/cli/wsl/wsl-cli-registration-command.ts similarity index 94% rename from src/main/cli/wsl-cli-registration-command.ts rename to src/main/cli/wsl/wsl-cli-registration-command.ts index 575a4f2e441..8f2d42b6fcc 100644 --- a/src/main/cli/wsl-cli-registration-command.ts +++ b/src/main/cli/wsl/wsl-cli-registration-command.ts @@ -1,4 +1,4 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' +import type { CliInstallStatus } from '../../../shared/cli-install-types' import { buildManagedLegacyRemoveCommand, buildRegistrationLockPrelude, @@ -10,7 +10,7 @@ import { getWslBridgeMarker, getWslLauncherMarker } from './wsl-cli-scripts' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' const MANAGED_MARKER = getWslLauncherMarker() const BRIDGE_MANAGED_MARKER = getWslBridgeMarker() diff --git a/src/main/cli/wsl-cli-registration-operation.ts b/src/main/cli/wsl/wsl-cli-registration-operation.ts similarity index 84% rename from src/main/cli/wsl-cli-registration-operation.ts rename to src/main/cli/wsl/wsl-cli-registration-operation.ts index 4dc1119d6e3..8845ff7e08e 100644 --- a/src/main/cli/wsl-cli-registration-operation.ts +++ b/src/main/cli/wsl/wsl-cli-registration-operation.ts @@ -1,4 +1,4 @@ -import { runKeyedSerializedOperation } from './keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' const operationQueues = new Map>() diff --git a/src/main/cli/wsl-cli-registration-reconciliation.test.ts b/src/main/cli/wsl/wsl-cli-registration-reconciliation.test.ts similarity index 100% rename from src/main/cli/wsl-cli-registration-reconciliation.test.ts rename to src/main/cli/wsl/wsl-cli-registration-reconciliation.test.ts diff --git a/src/main/cli/wsl-cli-registration-reconciliation.ts b/src/main/cli/wsl/wsl-cli-registration-reconciliation.ts similarity index 95% rename from src/main/cli/wsl-cli-registration-reconciliation.ts rename to src/main/cli/wsl/wsl-cli-registration-reconciliation.ts index 8f2a1011737..a112f6921be 100644 --- a/src/main/cli/wsl-cli-registration-reconciliation.ts +++ b/src/main/cli/wsl/wsl-cli-registration-reconciliation.ts @@ -1,11 +1,11 @@ -import type { CliInstallState, CliInstallStatus } from '../../shared/cli-install-types' -import { listWslDistrosAsync } from '../wsl/discovery/distro-catalog' +import type { CliInstallState, CliInstallStatus } from '../../../shared/cli-install-types' +import { listWslDistrosAsync } from '../../wsl/discovery/distro-catalog' import { deferUntilWslDistroRunning, isWslDistroRunning, listConfirmedRunningWslDistros -} from '../wsl/discovery/wsl-background-distro-gate' -import { CliInstaller } from './cli-installer' +} from '../../wsl/discovery/wsl-background-distro-gate' +import { CliInstaller } from '../cli-installer' import { getWslCliRegistrationCandidates, recordWslCliRegistrationObservations, @@ -13,7 +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/remote-runtime/host-store/wsl-host-deployment-store' +import { readWslHostDeployments } from '../../../shared/remote-runtime/host-store/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 diff --git a/src/main/cli/wsl-cli-registration-registry.test.ts b/src/main/cli/wsl/wsl-cli-registration-registry.test.ts similarity index 100% rename from src/main/cli/wsl-cli-registration-registry.test.ts rename to src/main/cli/wsl/wsl-cli-registration-registry.test.ts diff --git a/src/main/cli/wsl-cli-registration-registry.ts b/src/main/cli/wsl/wsl-cli-registration-registry.ts similarity index 97% rename from src/main/cli/wsl-cli-registration-registry.ts rename to src/main/cli/wsl/wsl-cli-registration-registry.ts index 869c8bb1359..aec77fba2fd 100644 --- a/src/main/cli/wsl-cli-registration-registry.ts +++ b/src/main/cli/wsl/wsl-cli-registration-registry.ts @@ -1,7 +1,10 @@ import { mkdir, readFile } from 'node:fs/promises' import { join } from 'node:path' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { getKeyedSerializedQueueTail, runKeyedSerializedOperation } from './keyed-promise-queue' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' +import { + getKeyedSerializedQueueTail, + runKeyedSerializedOperation +} from '../../../shared/concurrency/keyed-serialized-operations' import { normalizeWslDistroKey } from './wsl-cli-registration-operation' const REGISTRY_FILE_NAME = 'wsl-cli-registrations.json' diff --git a/src/main/cli/wsl-cli-scripts.ts b/src/main/cli/wsl/wsl-cli-scripts.ts similarity index 98% rename from src/main/cli/wsl-cli-scripts.ts rename to src/main/cli/wsl/wsl-cli-scripts.ts index 85796f1f42c..be9e7c8ec78 100644 --- a/src/main/cli/wsl-cli-scripts.ts +++ b/src/main/cli/wsl/wsl-cli-scripts.ts @@ -1,5 +1,5 @@ -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' -import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' +import { quotePowerShellLiteral } from '../../../shared/powershell-native-argument' const MANAGED_MARKER = '# Orca managed WSL CLI launcher' const BRIDGE_MANAGED_MARKER = '# Orca managed WSL CLI PowerShell bridge' diff --git a/src/main/cli/wsl-cli-status.ts b/src/main/cli/wsl/wsl-cli-status.ts similarity index 97% rename from src/main/cli/wsl-cli-status.ts rename to src/main/cli/wsl/wsl-cli-status.ts index e046adbe248..e17c69badd5 100644 --- a/src/main/cli/wsl-cli-status.ts +++ b/src/main/cli/wsl/wsl-cli-status.ts @@ -1,6 +1,6 @@ -import type { CliInstallStatus } from '../../shared/cli-install-types' +import type { CliInstallStatus } from '../../../shared/cli-install-types' import { getBridgePathFromCommandPath, getPosixDirname } from './wsl-cli-scripts' -import { quotePosixShellDoubleQuotedApostrophe } from '../../shared/shell/launch/shell-argument-quoting' +import { quotePosixShellDoubleQuotedApostrophe } from '../../../shared/shell/launch/shell-argument-quoting' const WSL_COMMAND_NAME = 'orca-ide' diff --git a/src/main/cli/wsl-managed-cli.test.ts b/src/main/cli/wsl/wsl-managed-cli.test.ts similarity index 100% rename from src/main/cli/wsl-managed-cli.test.ts rename to src/main/cli/wsl/wsl-managed-cli.test.ts diff --git a/src/main/cli/wsl-managed-cli.ts b/src/main/cli/wsl/wsl-managed-cli.ts similarity index 85% rename from src/main/cli/wsl-managed-cli.ts rename to src/main/cli/wsl/wsl-managed-cli.ts index 903ce0c5d87..80d4119ea44 100644 --- a/src/main/cli/wsl-managed-cli.ts +++ b/src/main/cli/wsl/wsl-managed-cli.ts @@ -1,11 +1,14 @@ import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' import { join } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../shared/app-environment' import { windowsPowerShellPath } from '@orca/process-host/windows-system-binary' -import { writeShellWrapperFiles } from '../pty/shell-startup/shell-wrapper-file-writer' -import { getBundledLauncherPath, LINUX_CLI_COMMAND_NAME } from './bundled-cli-launcher-path' -import { DEV_COMMAND_NAME } from './cli-install-constants' +import { writeShellWrapperFiles } from '../../pty/shell-startup/shell-wrapper-file-writer' +import { + getBundledLauncherPath, + LINUX_CLI_COMMAND_NAME +} from '../packaged-assets/bundled-cli-launcher-path' +import { DEV_COMMAND_NAME } from '../installation/cli-install-constants' import { buildColocatedWslLauncher, buildWslBridgeScript } from './wsl-cli-scripts' /** Packaged builds share `orca-ide` with guest registration; dev builds get their own name. */ diff --git a/src/main/cli/wsl-managed-cli.wsl.test.ts b/src/main/cli/wsl/wsl-managed-cli.wsl.test.ts similarity index 70% rename from src/main/cli/wsl-managed-cli.wsl.test.ts rename to src/main/cli/wsl/wsl-managed-cli.wsl.test.ts index 896fe004b2b..6951ba07e73 100644 --- a/src/main/cli/wsl-managed-cli.wsl.test.ts +++ b/src/main/cli/wsl/wsl-managed-cli.wsl.test.ts @@ -3,12 +3,12 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { buildWslExecArgs } from '../../shared/wsl-login-shell-command' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' -import { addOrcaWslInteropEnv } from '../pty/shell-startup/wsl-orca-env' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import { buildWslExecArgs } from '../../../shared/wsl-login-shell-command' +import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { addOrcaWslInteropEnv } from '../../pty/shell-startup/wsl-orca-env' import { getManagedWslCliDir } from './wsl-managed-cli' -import { buildLocalShellReadyWrapperFiles } from '../providers/local-pty/local-pty-shell-ready-wrapper-fileset' +import { buildLocalShellReadyWrapperFiles } from '../../providers/local-pty/local-pty-shell-ready-wrapper-fileset' // Explicit opt-in: never require a developer's WSL installation for unit tests. const enabled = process.platform === 'win32' && process.env.ORCA_TEST_MANAGED_WSL === '1' @@ -75,40 +75,6 @@ async function withManagedCli( } } -it.skipIf(!enabled)( - 'executes the managed bridge after bash startup resets PATH, without guest registration', - () => - withManagedCli(async ({ env, guestRoot, root, userDataPath, wsl }) => { - writeFileSync(join(root, '.bash_profile'), 'export PATH=/usr/bin:/bin\n') - const shell = (command: string) => - wsl([ - 'env', - `HOME=${guestRoot}`, - 'PATH=/usr/bin:/bin', - 'bash', - '--rcfile', - `${guestRoot}/wrapper/bash/rcfile`, - '-ic', - command - ]) - - const result = await shell('orca-dev "two words" "literal $" | cat') - expect(result.code, result.stderr).toBe(0) - expect(result.stderr).toContain('bridge stderr') - expect(result.stdout).toContain('"argv":["two words","literal $"]') - expect(result.stdout).toContain(JSON.stringify(userDataPath)) - expect(result.stdout).toContain('"handle":"term_managed_fixture"') - expect((await shell('orca-dev --exit')).code).toBe(23) - - env.ORCA_WSL_CLI_DIR = join(root, 'missing-cli') - const missing = await shell('echo SHELL_CONTINUED') - expect(missing.code).toBe(0) - expect(missing.stdout).toContain('SHELL_CONTINUED') - expect(missing.stderr).toContain('Check WSL Windows-drive mount options') - }), - 90_000 -) - // Why a PTY: the zsh restore runs from the first-prompt hook, which `zsh -c` never reaches. it.skipIf(!enabled)( 'executes the managed bridge from an interactive zsh after .zshrc resets PATH', diff --git a/src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts b/src/main/crash-reporting/breadcrumbs/crash-breadcrumb-renderer-attribution.test.ts similarity index 100% rename from src/main/crash-reporting/crash-breadcrumb-renderer-attribution.test.ts rename to src/main/crash-reporting/breadcrumbs/crash-breadcrumb-renderer-attribution.test.ts diff --git a/src/main/crash-reporting/crash-breadcrumb-store-orphan-cleanup.test.ts b/src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store-orphan-cleanup.test.ts similarity index 100% rename from src/main/crash-reporting/crash-breadcrumb-store-orphan-cleanup.test.ts rename to src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store-orphan-cleanup.test.ts diff --git a/src/main/crash-reporting/crash-breadcrumb-store.ts b/src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store.ts similarity index 98% rename from src/main/crash-reporting/crash-breadcrumb-store.ts rename to src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store.ts index 5e1d8dbc6cc..34beb87429c 100644 --- a/src/main/crash-reporting/crash-breadcrumb-store.ts +++ b/src/main/crash-reporting/breadcrumbs/crash-breadcrumb-store.ts @@ -1,9 +1,11 @@ import { sanitizeCrashReportBreadcrumbs, - sanitizeCrashReportDetails, - type CrashReportBreadcrumbData, - type CrashReportBreadcrumb -} from '../../shared/crash-reporting' + sanitizeCrashReportDetails +} from '../../../shared/crash-report-redaction' +import type { + CrashReportBreadcrumbData, + CrashReportBreadcrumb +} from '../../../shared/crash-reporting' const MAX_BREADCRUMBS = 30 const MAX_RETAINED_BREADCRUMBS = 10 diff --git a/src/main/crash-reporting/durable-crash-breadcrumb.test.ts b/src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.test.ts similarity index 98% rename from src/main/crash-reporting/durable-crash-breadcrumb.test.ts rename to src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.test.ts index 750c387c68a..e2c105b1088 100644 --- a/src/main/crash-reporting/durable-crash-breadcrumb.test.ts +++ b/src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' import { recordDurableCrashBreadcrumb } from './durable-crash-breadcrumb' -import { _resetTracerForTests, setActiveSink, type TracerSink } from '../observability/tracer' +import { _resetTracerForTests, setActiveSink, type TracerSink } from '../../observability/tracer' type CapturingSink = TracerSink & { records: unknown[]; flushMock: ReturnType } diff --git a/src/main/crash-reporting/durable-crash-breadcrumb.ts b/src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.ts similarity index 86% rename from src/main/crash-reporting/durable-crash-breadcrumb.ts rename to src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.ts index 0a6951ce656..8645be8ab0d 100644 --- a/src/main/crash-reporting/durable-crash-breadcrumb.ts +++ b/src/main/crash-reporting/breadcrumbs/durable-crash-breadcrumb.ts @@ -1,11 +1,11 @@ import { sanitizeCrashReportDetails, - sanitizeCrashReportString, - type CrashReportBreadcrumbData -} from '../../shared/crash-reporting' -import { flushActiveSink, startSpan } from '../observability/tracer' + sanitizeCrashReportString +} from '../../../shared/crash-report-redaction' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' +import { flushActiveSink, startSpan } from '../../observability/tracer' import { recordCoalescedCrashBreadcrumb, recordCrashBreadcrumb } from './crash-breadcrumb-store' -import { getMainProcessLifecycleIdentity } from './main-process-lifecycle-identity' +import { getMainProcessLifecycleIdentity } from '../process-exits/main-process-lifecycle-identity' function buildLifecycleData(data?: CrashReportBreadcrumbData): CrashReportBreadcrumbData { // Main identity distinguishes renderer replacement from an app relaunch. diff --git a/src/main/crash-reporting/appimage-crashpad-handler-exit.ts b/src/main/crash-reporting/capture/appimage-crashpad-handler-exit.ts similarity index 94% rename from src/main/crash-reporting/appimage-crashpad-handler-exit.ts rename to src/main/crash-reporting/capture/appimage-crashpad-handler-exit.ts index 7692abf5d67..19f60d9eddb 100644 --- a/src/main/crash-reporting/appimage-crashpad-handler-exit.ts +++ b/src/main/crash-reporting/capture/appimage-crashpad-handler-exit.ts @@ -4,7 +4,7 @@ import { readdirSync, readlinkSync, statSync } from 'node:fs' // posix: /proc paths are Linux-only, and tests run this matcher on every host. import { posix } from 'node:path' -import { resolveAppImageRuntimeIdentity } from '../updater/linux-package/appimage-runtime-identity' +import { resolveAppImageRuntimeIdentity } from '../../updater/linux-package/appimage-runtime-identity' function listPids(): number[] { try { diff --git a/src/main/crash-reporting/crashpad-capture.ts b/src/main/crash-reporting/capture/crashpad-capture.ts similarity index 98% rename from src/main/crash-reporting/crashpad-capture.ts rename to src/main/crash-reporting/capture/crashpad-capture.ts index 9a74e3deba9..47b9c9c1663 100644 --- a/src/main/crash-reporting/crashpad-capture.ts +++ b/src/main/crash-reporting/capture/crashpad-capture.ts @@ -1,16 +1,16 @@ // Keep raw process-memory dumps local; extract text signatures to identify crashes. -import { constants as fsConstants } from 'node:fs' -import type { Dirent } from 'node:fs' +import { constants as fsConstants, type Dirent } from 'node:fs' + import { open, readdir, rm, stat } from 'node:fs/promises' import path from 'node:path' import { app, crashReporter } from 'electron' import { installAppImageCrashpadHandlerExit } from './appimage-crashpad-handler-exit' -import { createMinidumpFileSource, observeMinidumpExtent } from './minidump-file-source' +import { createMinidumpFileSource, observeMinidumpExtent } from '../minidumps/minidump-file-source' import { parseMinidumpCrashSignature, type MinidumpCrashSignature -} from './minidump-crash-signature' +} from '../minidumps/minidump-crash-signature' // Crashpad writes asynchronously after process-gone; poll briefly to avoid missing its dump. const DUMP_WAIT_TIMEOUT_MS = 8_000 diff --git a/src/main/crash-reporting/capture/gpu-crash-diagnostics.test.ts b/src/main/crash-reporting/capture/gpu-crash-diagnostics.test.ts new file mode 100644 index 00000000000..84c5f7c9f1d --- /dev/null +++ b/src/main/crash-reporting/capture/gpu-crash-diagnostics.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it, vi } from 'vitest' +import { buildGpuCrashDiagnostics, GpuCrashDiagnosticsRecorder } from './gpu-crash-diagnostics' + +const FEATURE_STATUS = { + gpu_compositing: 'enabled', + rasterization: 'enabled', + webgl: 'enabled', + webgl2: 'enabled', + video_decode: 'enabled' +} + +describe('buildGpuCrashDiagnostics', () => { + it('degrades malformed or unavailable GPU info without copying arbitrary fields', () => { + expect( + buildGpuCrashDiagnostics( + { + level: 'basic', + info: { + gpuDevice: [{ active: true, vendorId: Number.NaN, secret: 'do not copy' }], + machineModelName: 'do not copy' + } + }, + { webgl: 'unavailable', unexpected: 'do not copy' } + ) + ).toEqual({ + gpuInfoLevel: 'basic', + gpuDeviceCount: 1, + gpuWebglStatus: 'unavailable' + }) + expect(buildGpuCrashDiagnostics(null, null)).toEqual({ gpuInfoLevel: 'unavailable' }) + }) +}) + +describe('GpuCrashDiagnosticsRecorder', () => { + it('does not let stalled GPU info block crash recovery', async () => { + const never = Promise.withResolvers().promise + const recordBreadcrumb = vi.fn() + const provider = { + getGPUInfo: vi.fn(() => never), + getGPUFeatureStatus: vi.fn(() => FEATURE_STATUS) + } + const recorder = new GpuCrashDiagnosticsRecorder({ + provider, + recordBreadcrumb, + recordTimeoutMs: 0 + }) + + await recorder.record() + + expect(recordBreadcrumb).toHaveBeenCalledWith( + expect.objectContaining({ gpuInfoLevel: 'unavailable' }) + ) + }) +}) diff --git a/src/main/crash-reporting/gpu-crash-diagnostics.ts b/src/main/crash-reporting/capture/gpu-crash-diagnostics.ts similarity index 98% rename from src/main/crash-reporting/gpu-crash-diagnostics.ts rename to src/main/crash-reporting/capture/gpu-crash-diagnostics.ts index 251984bf031..25378c18cad 100644 --- a/src/main/crash-reporting/gpu-crash-diagnostics.ts +++ b/src/main/crash-reporting/capture/gpu-crash-diagnostics.ts @@ -1,4 +1,4 @@ -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' type GpuInfoLevel = 'basic' | 'complete' const DEFAULT_GPU_CRASH_DIAGNOSTICS_WAIT_MS = 1_000 diff --git a/src/main/crash-reporting/crash-breadcrumb-store-leak.test.ts b/src/main/crash-reporting/crash-breadcrumb-store-leak.test.ts deleted file mode 100644 index 71d622320d6..00000000000 --- a/src/main/crash-reporting/crash-breadcrumb-store-leak.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - recordCoalescedCrashBreadcrumb, - clearCrashBreadcrumbsForTest, - getCoalescedKeyCountForTest -} from './crash-breadcrumb-store' - -// MAX_COALESCE_KEYS is module-private; mirror its value here. -const MAX_COALESCE_KEYS = 128 - -describe('coalescedBreadcrumbs stays bounded (leak regression)', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) - clearCrashBreadcrumbsForTest() - }) - - afterEach(() => { - clearCrashBreadcrumbsForTest() - vi.useRealTimers() - }) - - it('caps the map even with an unbounded stream of distinct agentType keys', () => { - // Hold time fixed so expiry cannot relieve the size-cap pressure. - for (let i = 0; i < 1000; i++) { - recordCoalescedCrashBreadcrumb({ - name: 'agent_state', - coalesceKey: `agent:type-${i}:working`, - minIntervalMs: 30_000 - }) - } - expect(getCoalescedKeyCountForTest()).toBeLessThanOrEqual(MAX_COALESCE_KEYS) - }) -}) diff --git a/src/main/crash-reporting/crash-report-copy-text.test.ts b/src/main/crash-reporting/crash-report-copy-text.test.ts deleted file mode 100644 index 3379ac8e294..00000000000 --- a/src/main/crash-reporting/crash-report-copy-text.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { formatCrashReportCopyText } from './crash-report-copy-text' - -describe('formatCrashReportCopyText', () => { - it('appends only sanitized report and diagnostic omission failure fields', () => { - const text = formatCrashReportCopyText('[Crash Report]', { - error: 'proxy failed at C:\\Users\\alice\\Orca', - diagnosticContext: { - status: 'not_uploaded', - reason: 'timeout token=super-secret-value\n- Forged field: hidden', - internalEndpointError: 'must-not-cross-copy-boundary' - }, - internalTransportFailure: 'must-not-cross-copy-boundary' - }) - - expect(text).toContain('Submission failure:') - expect(text).toContain('Report error: proxy failed at [redacted-path]') - expect(text).toContain('Diagnostic logs not uploaded: timeout token=[redacted]') - expect(text).not.toContain('\n- Forged field') - expect(text).not.toContain('alice') - expect(text).not.toContain('must-not-cross-copy-boundary') - }) - - it('includes a sanitized uploaded ticket without accepting unrelated fields', () => { - const text = formatCrashReportCopyText('[Crash Report]', { - error: 'report link failed', - diagnosticContext: { - status: 'uploaded', - ticketId: 'ticket-123', - bundleSubmissionId: 'not-allow-listed' - } - }) - - expect(text).toContain('Diagnostic ticket uploaded but not linked: ticket-123') - expect(text).not.toContain('not-allow-listed') - }) -}) diff --git a/src/main/crash-reporting/crashpad-capture-read-limit.test.ts b/src/main/crash-reporting/crashpad-capture-read-limit.test.ts deleted file mode 100644 index 0e8ed038ff8..00000000000 --- a/src/main/crash-reporting/crashpad-capture-read-limit.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -import type * as FsModule from 'node:fs/promises' -import type * as ParserModule from './minidump-crash-signature' -import { constants as fsConstants } from 'node:fs' -import { - mkdtemp, - mkdir, - open, - rm, - rename, - symlink, - truncate, - utimes, - writeFile -} from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' - -const state = vi.hoisted(() => { - const callbacks: { - afterStat?: (path: string) => Promise - afterOpenStat?: (path: string) => Promise - } = {} - const parsedBytes: number[] = [] - const closedPaths: string[] = [] - return { callbacks, parsedBytes, closedPaths } -}) -vi.mock('electron', () => ({ - app: { getPath: () => '/unused' }, - crashReporter: { start: vi.fn() } -})) -vi.mock('node:fs/promises', async (original) => { - const fs = await original() - return { - ...fs, - open: async (...args: Parameters) => { - const handle = await fs.open(...args) - const readStat = handle.stat.bind(handle) - const close = handle.close.bind(handle) - return Object.assign(handle, { - stat: async () => { - const stats = await readStat() - await state.callbacks.afterOpenStat?.(String(args[0])) - return stats - }, - close: async () => { - await close() - state.closedPaths.push(String(args[0])) - } - }) - }, - stat: async (...args: Parameters) => { - const stats = await fs.stat(...args) - await state.callbacks.afterStat?.(String(args[0])) - return stats - } - } -}) -vi.mock('./minidump-crash-signature', async (original) => { - const parser = await original() - return { - ...parser, - parseMinidumpCrashSignature: ( - ...args: Parameters - ) => { - state.parsedBytes.push(args[0].byteLength) - return parser.parseMinidumpCrashSignature(...args) - } - } -}) -import { _setCrashpadCaptureStateForTest, captureMinidumpSignature } from './crashpad-capture' - -const LIMIT = 64 * 1024 * 1024 -const CRASHED_AT = 1_700_000_000_000 -let directory: string -function rendererDump() { - const dump = Buffer.alloc(131) - dump.writeUInt32LE(0x504d444d, 0) - dump.writeUInt32LE(0xa793, 4) - dump.writeUInt32LE(1, 8) - dump.writeUInt32LE(32, 12) - dump.writeUInt32LE(0x43500001, 32) - dump.writeUInt32LE(52, 36) - dump.writeUInt32LE(44, 40) - dump.writeUInt32LE(1, 44) - dump.writeUInt32LE(12, 80) - dump.writeUInt32LE(96, 84) - dump.writeUInt32LE(1, 96) - dump.writeUInt32LE(108, 100) - dump.writeUInt32LE(118, 104) - dump.writeUInt32LE(5, 108) - dump.write('ptype', 112) - dump.writeUInt32LE(8, 118) - dump.write('renderer', 122) - return dump -} -async function file(name: string, newer = false, bytes = rendererDump()) { - const path = join(directory, 'new', name) - await writeFile(path, bytes) - await utimes(path, CRASHED_AT / 1000, (CRASHED_AT + (newer ? 100 : 0)) / 1000) - return path -} -function capture() { - return captureMinidumpSignature(CRASHED_AT, { - expectedProcessType: 'renderer', - timeoutMs: 0, - now: () => CRASHED_AT - }) -} -beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-crashpad-limit-')) - await mkdir(join(directory, 'new')) - state.callbacks.afterStat = undefined - state.callbacks.afterOpenStat = undefined - state.parsedBytes.length = 0 - state.closedPaths.length = 0 - _setCrashpadCaptureStateForTest({ dumpDirectory: directory, started: true }) -}) -afterEach(async () => { - _setCrashpadCaptureStateForTest(null) - await rm(directory, { recursive: true, force: true }) -}) - -it.each(['growth', 'replacement'] as const)( - 'captures %s past the initial limit without a whole-file allocation', - async (kind) => { - const next = await file('next.dmp') - const unfinished = rendererDump() - unfinished.writeUInt32LE(0, 0) - const race = await file('racing.dmp', true, unfinished) - state.callbacks.afterStat = async (path) => { - if (path !== race) { - return - } - state.callbacks.afterStat = undefined - if (kind === 'replacement') { - await rename(race, join(directory, 'retired.bin')) - await writeFile(race, unfinished) - } - await truncate(race, LIMIT + 1024 * 1024) - const handle = await open(race, 'r+') - try { - await handle.write(rendererDump().subarray(0, 4), 0, 4, 0) - } finally { - await handle.close() - } - } - const result = await capture() - expect(state.parsedBytes).toEqual([LIMIT + 1024 * 1024]) - expect(result?.filePath).toBe(race) - expect(next).not.toBe(race) - } -) - -it('ignores an already oversize candidate without parsing it', async () => { - const next = await file('next.dmp') - const path = await file('oversize.dmp', true) - await truncate(path, LIMIT + 1024 * 1024) - const result = await capture() - expect(result?.filePath).toBe(next) - expect(state.parsedBytes).toEqual([131]) -}) - -it('can recover partial-header rejection after completed-path promotion', async () => { - const path = await file('partial.dmp', false, Buffer.from('MDMP')) - const promoted = join(directory, 'pending', 'partial.dmp') - let clock = CRASHED_AT - const result = await captureMinidumpSignature(CRASHED_AT, { - expectedProcessType: 'renderer', - timeoutMs: 500, - now: () => clock, - sleep: async (ms) => { - clock += ms - await writeFile(path, rendererDump()) - await mkdir(join(directory, 'pending')) - await rename(path, promoted) - } - }) - expect(result?.filePath).toBe(promoted) - expect(state.parsedBytes).toEqual([4, 131]) -}) - -it('preserves the opened dump when later growth exceeds the limit', async () => { - const next = await file('next.dmp') - const race = await file('racing.dmp', true) - let grew = false - state.callbacks.afterOpenStat = async (path) => { - if (path !== race) { - return - } - state.callbacks.afterOpenStat = undefined - grew = true - await truncate(race, LIMIT + 1024 * 1024) - } - const result = await capture() - expect(grew).toBe(true) - expect(result?.filePath).toBe(race) - expect(result?.sizeBytes).toBe(131) - expect(state.parsedBytes).toEqual([131]) - expect(state.closedPaths).toEqual([race]) - expect((await capture())?.filePath).toBe(next) -}) - -it('captures a size-zero opened dump that gains contents before its first read', async () => { - const race = await file('racing.dmp', false, Buffer.alloc(0)) - state.callbacks.afterOpenStat = async (path) => { - if (path === race) { - state.callbacks.afterOpenStat = undefined - await writeFile(path, rendererDump()) - } - } - const result = await capture() - expect(result?.filePath).toBe(race) - expect(result?.signature.processType).toBe('renderer') - expect(result?.sizeBytes).toBe(131) -}) - -it.skipIf(!fsConstants.O_NOFOLLOW)( - 'skips a swapped symlink and captures another valid dump', - async () => { - const next = await file('next.dmp') - const race = await file('swapped.dmp', true) - state.callbacks.afterStat = async (path) => { - if (path === race) { - state.callbacks.afterStat = undefined - await rm(race) - await symlink(next, race) - } - } - expect((await capture())?.filePath).toBe(next) - expect(state.parsedBytes).toEqual([131]) - expect(state.closedPaths).toEqual([next]) - } -) - -it.each(['missing', 'directory'] as const)('skips a candidate replaced by %s', async (kind) => { - const next = await file('next.dmp') - const race = await file('swapped.dmp', true) - state.callbacks.afterStat = async (path) => { - if (path === race) { - state.callbacks.afterStat = undefined - await rm(race) - if (kind === 'directory') { - await mkdir(race) - } - } - } - expect((await capture())?.filePath).toBe(next) - expect(state.parsedBytes).toEqual([131]) - expect(state.closedPaths).toContain(next) -}) diff --git a/src/main/crash-reporting/crashpad-capture.test.ts b/src/main/crash-reporting/crashpad-capture.test.ts deleted file mode 100644 index e5fd5b0c932..00000000000 --- a/src/main/crash-reporting/crashpad-capture.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { mkdtemp, mkdir, readdir, rm, utimes, writeFile } from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const parseMinidumpCrashSignatureMock = vi.hoisted(() => vi.fn()) - -vi.mock('electron', () => ({ - app: { getPath: () => '/unused-in-tests' }, - crashReporter: { start: vi.fn() } -})) -vi.mock('./minidump-crash-signature', () => ({ - parseMinidumpCrashSignature: parseMinidumpCrashSignatureMock -})) - -import { - _pruneCrashpadDumpsForTest, - _setCrashpadCaptureStateForTest, - captureMinidumpSignature, - waitForCrashMinidump -} from './crashpad-capture' - -let dumpDir: string - -/** Minimal but valid minidump header with a zero-stream directory. */ -function emptyDump(): Buffer { - const buf = Buffer.alloc(32) - buf.writeUInt32LE(0x504d444d, 0) - buf.writeUInt32LE(0xa793, 4) - buf.writeUInt32LE(0, 8) - buf.writeUInt32LE(32, 12) - return buf -} - -async function writeDump(relativePath: string, mtimeMs: number, contents = emptyDump()) { - const filePath = path.join(dumpDir, relativePath) - await mkdir(path.dirname(filePath), { recursive: true }) - await writeFile(filePath, contents) - const seconds = mtimeMs / 1000 - await utimes(filePath, seconds, seconds) - return filePath -} - -const CRASHED_AT = 1_700_000_000_000 - -beforeEach(async () => { - parseMinidumpCrashSignatureMock.mockReset() - parseMinidumpCrashSignatureMock.mockReturnValue({ annotations: {} }) - dumpDir = await mkdtemp(path.join(os.tmpdir(), 'orca-crashpad-')) - _setCrashpadCaptureStateForTest({ dumpDirectory: dumpDir, started: true }) -}) - -afterEach(async () => { - _setCrashpadCaptureStateForTest(null) - await rm(dumpDir, { recursive: true, force: true }) -}) - -describe('waitForCrashMinidump', () => { - it('gives up at the deadline instead of polling forever', async () => { - let clock = CRASHED_AT - const sleep = async (ms: number) => { - clock += ms - } - - const dump = await waitForCrashMinidump(CRASHED_AT, { - timeoutMs: 1_000, - now: () => clock, - sleep - }) - - expect(dump).toBeNull() - expect(clock).toBeLessThanOrEqual(CRASHED_AT + 1_250) - }) -}) - -describe('captureMinidumpSignature', () => { - it('claims a dump once so another report cannot reuse it', async () => { - const expected = await writeDump(path.join('reports', 'crash.dmp'), CRASHED_AT + 100) - - const first = await captureMinidumpSignature(CRASHED_AT, { - timeoutMs: 0, - now: () => CRASHED_AT - }) - const second = await captureMinidumpSignature(CRASHED_AT, { - timeoutMs: 0, - now: () => CRASHED_AT - }) - - expect(first?.filePath).toBe(expected) - expect(second).toBeNull() - }) - - it('leaves a mismatched dump available for its own process report', async () => { - const gpuDump = await writeDump( - path.join('reports', 'gpu.dmp'), - CRASHED_AT + 100, - Buffer.from('gpu-process') - ) - parseMinidumpCrashSignatureMock.mockReturnValue({ - processType: 'gpu-process', - annotations: {} - }) - - const renderer = await captureMinidumpSignature(CRASHED_AT, { - expectedProcessType: 'renderer', - timeoutMs: 0, - now: () => CRASHED_AT - }) - const gpu = await captureMinidumpSignature(CRASHED_AT, { - expectedProcessType: 'gpu-process', - timeoutMs: 0, - now: () => CRASHED_AT - }) - - expect(renderer).toBeNull() - expect(gpu?.filePath).toBe(gpuDump) - }) -}) - -describe('Crashpad dump pruning', () => { - it('keeps the newest dumps within the byte budget', async () => { - await writeDump(path.join('reports', 'old.dmp'), CRASHED_AT, Buffer.alloc(8)) - await writeDump(path.join('reports', 'middle.dmp'), CRASHED_AT + 100, Buffer.alloc(8)) - await writeDump(path.join('reports', 'new.dmp'), CRASHED_AT + 200, Buffer.alloc(8)) - - await _pruneCrashpadDumpsForTest(16) - - expect((await readdir(path.join(dumpDir, 'reports'))).sort()).toEqual(['middle.dmp', 'new.dmp']) - }) - - it('keeps a dump already claimed by a persisted crash report', async () => { - await writeDump(path.join('reports', 'claimed.dmp'), CRASHED_AT + 200, Buffer.alloc(8)) - const captured = await captureMinidumpSignature(CRASHED_AT, { - timeoutMs: 0, - now: () => CRASHED_AT - }) - expect(captured?.filePath).toBe(path.join(dumpDir, 'reports', 'claimed.dmp')) - // Make another dump newest so only the persisted claim protects this one. - await writeDump(path.join('reports', 'newest.dmp'), CRASHED_AT + 400, Buffer.alloc(8)) - - await _pruneCrashpadDumpsForTest(8) - - expect((await readdir(path.join(dumpDir, 'reports'))).sort()).toEqual([ - 'claimed.dmp', - 'newest.dmp' - ]) - }) -}) diff --git a/src/main/crash-reporting/gpu-crash-diagnostics.test.ts b/src/main/crash-reporting/gpu-crash-diagnostics.test.ts deleted file mode 100644 index b180920dcb1..00000000000 --- a/src/main/crash-reporting/gpu-crash-diagnostics.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { buildGpuCrashDiagnostics, GpuCrashDiagnosticsRecorder } from './gpu-crash-diagnostics' - -const FEATURE_STATUS = { - gpu_compositing: 'enabled', - rasterization: 'enabled', - webgl: 'enabled', - webgl2: 'enabled', - video_decode: 'enabled' -} - -const BASIC_INFO = { - gpuDevice: [ - { - active: false, - vendorId: 0x8086, - deviceId: 0x9a49, - vendorString: 'Intel', - deviceString: 'Integrated GPU' - }, - { - active: true, - vendorId: 0x10de, - deviceId: 0x2684, - vendorString: 'NVIDIA', - deviceString: 'Discrete GPU', - driverVendor: 'NVIDIA', - driverVersion: '32.0.15.6094' - } - ], - auxAttributes: { - glVendor: 'Google Inc.', - glRenderer: 'ANGLE (NVIDIA, D3D11)', - glVersion: 'OpenGL ES 3.0' - } -} - -function deferred(): { - promise: Promise - resolve: (value: T) => void -} { - let resolvePromise: ((value: T) => void) | undefined - const promise = new Promise((resolve) => { - resolvePromise = resolve - }) - return { - promise, - resolve: (value) => resolvePromise?.(value) - } -} - -describe('buildGpuCrashDiagnostics', () => { - it('degrades malformed or unavailable GPU info without copying arbitrary fields', () => { - expect( - buildGpuCrashDiagnostics( - { - level: 'basic', - info: { - gpuDevice: [{ active: true, vendorId: Number.NaN, secret: 'do not copy' }], - machineModelName: 'do not copy' - } - }, - { webgl: 'unavailable', unexpected: 'do not copy' } - ) - ).toEqual({ - gpuInfoLevel: 'basic', - gpuDeviceCount: 1, - gpuWebglStatus: 'unavailable' - }) - expect(buildGpuCrashDiagnostics(null, null)).toEqual({ gpuInfoLevel: 'unavailable' }) - }) -}) - -describe('GpuCrashDiagnosticsRecorder', () => { - it('warms only complete info and records one breadcrumb across a crash burst', async () => { - const recordBreadcrumb = vi.fn() - const provider = { - getGPUInfo: vi.fn(async (level: 'basic' | 'complete') => ({ - ...BASIC_INFO, - gpuDevice: BASIC_INFO.gpuDevice.map((device) => ({ - ...device, - ...(level === 'complete' ? { driverVersion: 'complete-driver' } : {}) - })) - })), - getGPUFeatureStatus: vi.fn(() => FEATURE_STATUS) - } - const recorder = new GpuCrashDiagnosticsRecorder({ provider, recordBreadcrumb }) - - recorder.warm() - await vi.waitFor(() => { - expect(provider.getGPUInfo).toHaveBeenCalledTimes(1) - }) - await Promise.resolve() - await recorder.record() - await recorder.record() - - expect(provider.getGPUInfo).toHaveBeenCalledOnce() - expect(provider.getGPUInfo).toHaveBeenCalledWith('complete') - - expect(recordBreadcrumb).toHaveBeenCalledTimes(1) - expect(recordBreadcrumb).toHaveBeenCalledWith( - expect.objectContaining({ - gpuInfoLevel: 'complete', - gpuVendorId: 0x10de, - gpuDeviceId: 0x2684, - gpuDriverVersion: 'complete-driver' - }) - ) - }) - - it('uses promptly available basic info when complete collection is still pending', async () => { - const complete = deferred() - const recordBreadcrumb = vi.fn() - const provider = { - getGPUInfo: vi.fn((level: 'basic' | 'complete') => - level === 'basic' ? Promise.resolve(BASIC_INFO) : complete.promise - ), - getGPUFeatureStatus: vi.fn(() => FEATURE_STATUS) - } - const recorder = new GpuCrashDiagnosticsRecorder({ provider, recordBreadcrumb }) - - recorder.warm() - expect(provider.getGPUInfo).toHaveBeenCalledOnce() - expect(provider.getGPUInfo).toHaveBeenCalledWith('complete') - await recorder.record() - - expect(recordBreadcrumb).toHaveBeenCalledWith( - expect.objectContaining({ - gpuInfoLevel: 'basic', - gpuVendorId: 0x10de, - gpuDriverVersion: '32.0.15.6094' - }) - ) - complete.resolve(BASIC_INFO) - }) - - it('shares pending capture work and releases it when complete info arrives first', async () => { - const complete = deferred() - const basic = deferred() - const recordBreadcrumb = vi.fn() - const provider = { - getGPUInfo: vi.fn((level: 'basic' | 'complete') => - level === 'basic' ? basic.promise : complete.promise - ), - getGPUFeatureStatus: vi.fn(() => FEATURE_STATUS) - } - const recorder = new GpuCrashDiagnosticsRecorder({ provider, recordBreadcrumb }) - - recorder.warm() - const first = recorder.record() - const second = recorder.record() - - expect(second).toBe(first) - expect(recordBreadcrumb).not.toHaveBeenCalled() - complete.resolve(BASIC_INFO) - await first - expect(recordBreadcrumb).toHaveBeenCalledOnce() - expect(recordBreadcrumb).toHaveBeenCalledWith( - expect.objectContaining({ gpuInfoLevel: 'complete' }) - ) - }) - - it('does not let stalled GPU info block crash recovery', async () => { - const never = Promise.withResolvers().promise - const recordBreadcrumb = vi.fn() - const provider = { - getGPUInfo: vi.fn(() => never), - getGPUFeatureStatus: vi.fn(() => FEATURE_STATUS) - } - const recorder = new GpuCrashDiagnosticsRecorder({ - provider, - recordBreadcrumb, - recordTimeoutMs: 0 - }) - - await recorder.record() - - expect(recordBreadcrumb).toHaveBeenCalledWith( - expect.objectContaining({ gpuInfoLevel: 'unavailable' }) - ) - }) -}) diff --git a/src/main/crash-reporting/pre-gone-host-memory.ts b/src/main/crash-reporting/memory/pre-gone-host-memory.ts similarity index 98% rename from src/main/crash-reporting/pre-gone-host-memory.ts rename to src/main/crash-reporting/memory/pre-gone-host-memory.ts index efe7fe187e4..c06c31c434b 100644 --- a/src/main/crash-reporting/pre-gone-host-memory.ts +++ b/src/main/crash-reporting/memory/pre-gone-host-memory.ts @@ -1,4 +1,4 @@ -import type { CrashReportDetailValue } from '../../shared/crash-reporting' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' import { readSwapVolumeFreeSpace } from './swap-volume-free-space' import { getSystemMemoryDetails, diff --git a/src/main/crash-reporting/renderer-heap-allocation-profile.ts b/src/main/crash-reporting/memory/renderer-heap-allocation-profile.ts similarity index 98% rename from src/main/crash-reporting/renderer-heap-allocation-profile.ts rename to src/main/crash-reporting/memory/renderer-heap-allocation-profile.ts index 2de15f41fd0..a09aa66bdd3 100644 --- a/src/main/crash-reporting/renderer-heap-allocation-profile.ts +++ b/src/main/crash-reporting/memory/renderer-heap-allocation-profile.ts @@ -1,9 +1,9 @@ import type { WebContents } from 'electron' -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import { RENDERER_HEAP_ALLOCATION_PROFILE_BREADCRUMB, recordCrashBreadcrumb -} from './crash-breadcrumb-store' +} from '../breadcrumbs/crash-breadcrumb-store' import { readSamplingProfile, summarizeSamplingProfile, diff --git a/src/main/crash-reporting/renderer-heap-allocation-sites.test.ts b/src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts similarity index 82% rename from src/main/crash-reporting/renderer-heap-allocation-sites.test.ts rename to src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts index a959bed2386..fa401cf5fc0 100644 --- a/src/main/crash-reporting/renderer-heap-allocation-sites.test.ts +++ b/src/main/crash-reporting/memory/renderer-heap-allocation-sites.test.ts @@ -65,17 +65,3 @@ describe('summarizeSamplingProfile', () => { expect(summary.site01).toBe('1KB (other script)') }) }) - -describe('site length', () => { - it('drops whole caller frames to stay inside the crumb string budget', () => { - const long = 'a'.repeat(48) - let node = leaf(frame(long, `${BUNDLE}${'b'.repeat(60)}.js`), 1) - for (let depth = 0; depth < 3; depth++) { - node = { ...leaf(frame(long, `${BUNDLE}${'b'.repeat(60)}.js`), 0), children: [node] } - } - const [site] = sitesOf(node) - - expect(site.length).toBeLessThanOrEqual(240) - expect(site.endsWith('.js:10:5')).toBe(true) - }) -}) diff --git a/src/main/crash-reporting/renderer-heap-allocation-sites.ts b/src/main/crash-reporting/memory/renderer-heap-allocation-sites.ts similarity index 98% rename from src/main/crash-reporting/renderer-heap-allocation-sites.ts rename to src/main/crash-reporting/memory/renderer-heap-allocation-sites.ts index d9f65aa7399..98aa4c8cccf 100644 --- a/src/main/crash-reporting/renderer-heap-allocation-sites.ts +++ b/src/main/crash-reporting/memory/renderer-heap-allocation-sites.ts @@ -1,4 +1,4 @@ -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' const MAX_SITES = 12 const MAX_STACK_FRAMES = 4 diff --git a/src/main/crash-reporting/swap-volume-free-space.ts b/src/main/crash-reporting/memory/swap-volume-free-space.ts similarity index 100% rename from src/main/crash-reporting/swap-volume-free-space.ts rename to src/main/crash-reporting/memory/swap-volume-free-space.ts diff --git a/src/main/crash-reporting/system-memory-details.ts b/src/main/crash-reporting/memory/system-memory-details.ts similarity index 98% rename from src/main/crash-reporting/system-memory-details.ts rename to src/main/crash-reporting/memory/system-memory-details.ts index d54deed50b3..8f663ea9b29 100644 --- a/src/main/crash-reporting/system-memory-details.ts +++ b/src/main/crash-reporting/memory/system-memory-details.ts @@ -1,4 +1,4 @@ -import type { CrashReportDetailValue } from '../../shared/crash-reporting' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' import type { SwapVolumeFreeSpace } from './swap-volume-free-space' // Post-exit memory can look healthier; pre-gone samples retain earlier pressure evidence. diff --git a/src/main/crash-reporting/minidump-file-source.test.ts b/src/main/crash-reporting/minidump-file-source.test.ts deleted file mode 100644 index 780ba9347bc..00000000000 --- a/src/main/crash-reporting/minidump-file-source.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { mkdtemp, open, rm, truncate, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { createMinidumpFileSource, observeMinidumpExtent } from './minidump-file-source' -import { parseMinidumpCrashSignature } from './minidump-crash-signature' - -const roots: string[] = [] -const LINE = '[8104:1234:0815/143022.123456:FATAL:render_frame_impl.cc(4821)] Check failed: !x.' -const ERROR = '[8104:1234:0815/143022.123456:ERROR:file.cc(12)] Check failed: earlier.' -const BLOCK = 1024 * 1024 - -function header(): Buffer { - const bytes = Buffer.alloc(32) - bytes.writeUInt32LE(0x504d444d, 0) - bytes.writeUInt32LE(32, 12) - return bytes -} - -async function sourceFile() { - const root = await mkdtemp(join(tmpdir(), 'orca-minidump-source-')) - roots.push(root) - const path = join(root, 'dump.dmp') - await writeFile(path, header()) - return path -} - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -it.each([1, 2])( - 'stops observing a growing size-zero dump after the deadline at page %i', - async (pages) => { - const path = await sourceFile() - const handle = await open(path, 'r+') - const pageBytes = 64 * 1024 - try { - await handle.truncate(3 * pageBytes) - const read = vi.spyOn(handle, 'read') - let observations = 0 - const now = () => (++observations >= pages ? 10 : 0) - - expect(await observeMinidumpExtent(handle, 0, { deadlineMs: 10, now })).toBe( - pages * pageBytes - ) - expect(read).toHaveBeenCalledTimes(pages) - expect(observations).toBe(pages) - } finally { - await handle.close() - } - } -) - -it.each([-96, -40, -1, 0, 1, 40, 96])( - 'preserves marker and full text at block boundary %+d', - async (delta) => { - const path = await sourceFile() - const handle = await open(path, 'r+') - const line = LINE + 'x'.repeat(4000 - LINE.length) - try { - await handle.write(Buffer.from(`${line}\0`), 0, line.length + 1, BLOCK + delta) - const { size } = await handle.stat() - const streamed = await parseMinidumpCrashSignature(createMinidumpFileSource(handle, size)) - const complete = await handle.readFile() - expect(streamed).toEqual(await parseMinidumpCrashSignature(complete)) - expect(streamed?.checkMessage).toBe(line) - } finally { - await handle.close() - } - } -) - -it('preserves severity priority across blocks and scans a large sparse dump with bounded reads', async () => { - const path = await sourceFile() - const handle = await open(path, 'r+') - const size = 80 * 1024 * 1024 - try { - await handle.write(Buffer.from(`${ERROR}\0`), 0, ERROR.length + 1, 4096) - await handle.write(Buffer.from(`${LINE}\0`), 0, LINE.length + 1, size - LINE.length - 1) - const source = createMinidumpFileSource(handle, size) - let maxRead = 0 - let reads = 0 - const result = await parseMinidumpCrashSignature({ - byteLength: size, - read: async (offset, length) => { - maxRead = Math.max(maxRead, length) - reads++ - return source.read(offset, length) - } - }) - expect(result?.checkMessage).toBe(LINE) - expect(maxRead).toBeLessThanOrEqual(BLOCK + 4096) - expect(reads).toBeLessThan(400) - } finally { - await handle.close() - } -}) - -it('reads annotations through large RVAs without buffering skipped process memory', async () => { - const path = await sourceFile() - const handle = await open(path, 'r+') - const rva = 80 * 1024 * 1024 - try { - const prefix = Buffer.alloc(44) - header().copy(prefix) - prefix.writeUInt32LE(1, 8) - prefix.writeUInt32LE(0x43500001, 32) - prefix.writeUInt32LE(52, 36) - prefix.writeUInt32LE(rva, 40) - await handle.write(prefix, 0, prefix.length, 0) - const info = Buffer.alloc(52 + 12 + 10 + 13) - info.writeUInt32LE(1, 0) - info.writeUInt32LE(12, 36) - info.writeUInt32LE(rva + 52, 40) - info.writeUInt32LE(1, 52) - info.writeUInt32LE(rva + 64, 56) - info.writeUInt32LE(rva + 74, 60) - info.writeUInt32LE(5, 64) - info.write('ptype', 68) - info.writeUInt32LE(8, 74) - info.write('renderer', 78) - await handle.write(info, 0, info.length, rva) - const source = createMinidumpFileSource(handle, rva + info.length) - const reads: number[] = [] - const result = await parseMinidumpCrashSignature( - { - byteLength: source.byteLength, - read: async (offset, length) => { - reads.push(length) - return source.read(offset, length) - } - }, - { expectedProcessType: 'browser' } - ) - expect(result).toEqual({ annotations: { ptype: 'renderer' }, processType: 'renderer' }) - expect(Math.max(...reads)).toBeLessThan(64) - } finally { - await handle.close() - } -}) - -it('does not read outside the opened extent, including truncation and EOF', async () => { - const path = await sourceFile() - const handle = await open(path, 'r+') - try { - const source = createMinidumpFileSource(handle, 32) - await handle.write(Buffer.from(LINE), 0, LINE.length, 32) - expect(await source.read(32, 4)).toEqual(Buffer.alloc(0)) - expect((await parseMinidumpCrashSignature(source))?.checkMessage).toBeUndefined() - await truncate(path, 4) - const truncated = createMinidumpFileSource(handle, 32) - expect(await parseMinidumpCrashSignature(truncated)).toBeNull() - } finally { - await handle.close() - } -}) - -it('avoids rereading distant name and module-table pages for a 1,042-module renderer', async () => { - const path = await sourceFile() - const handle = await open(path, 'r+') - const count = 1042 - const namesOffset = 1024 * 1024 - const moduleOffset = 56 - const exceptionOffset = moduleOffset + 4 + count * 108 - try { - const table = Buffer.alloc(exceptionOffset + 40) - header().copy(table) - table.writeUInt32LE(2, 8) - table.writeUInt32LE(4, 32) - table.writeUInt32LE(4 + count * 108, 36) - table.writeUInt32LE(moduleOffset, 40) - table.writeUInt32LE(6, 44) - table.writeUInt32LE(40, 48) - table.writeUInt32LE(exceptionOffset, 52) - table.writeUInt32LE(count, moduleOffset) - const names = Buffer.alloc(count * 32) - for (let index = 0; index < count; index++) { - const record = moduleOffset + 4 + index * 108 - table.writeBigUInt64LE(BigInt(index * 4096), record) - table.writeUInt32LE(4096, record + 8) - table.writeUInt32LE(namesOffset + index * 32, record + 20) - const name = Buffer.from(`module${index}`, 'utf16le') - names.writeUInt32LE(name.length, index * 32) - name.copy(names, index * 32 + 4) - } - table.writeUInt32LE(0x80000003, exceptionOffset + 8) - table.writeBigUInt64LE(BigInt((count - 1) * 4096 + 1), exceptionOffset + 24) - await handle.write(table, 0, table.length, 0) - await handle.write(names, 0, names.length, namesOffset) - const read = vi.spyOn(handle, 'read') - const result = await parseMinidumpCrashSignature( - createMinidumpFileSource(handle, namesOffset + names.length) - ) - expect(result?.faultingModule).toBe(`module${count - 1}`) - expect(result?.faultingModuleOffset).toBe('0x1') - expect(read.mock.calls.length).toBeLessThanOrEqual(8) - } finally { - await handle.close() - } -}) diff --git a/src/main/crash-reporting/minidump-crash-signature.test.ts b/src/main/crash-reporting/minidumps/minidump-crash-signature.test.ts similarity index 100% rename from src/main/crash-reporting/minidump-crash-signature.test.ts rename to src/main/crash-reporting/minidumps/minidump-crash-signature.test.ts diff --git a/src/main/crash-reporting/minidump-crash-signature.ts b/src/main/crash-reporting/minidumps/minidump-crash-signature.ts similarity index 100% rename from src/main/crash-reporting/minidump-crash-signature.ts rename to src/main/crash-reporting/minidumps/minidump-crash-signature.ts diff --git a/src/main/crash-reporting/minidump-crashpad-annotations.ts b/src/main/crash-reporting/minidumps/minidump-crashpad-annotations.ts similarity index 100% rename from src/main/crash-reporting/minidump-crashpad-annotations.ts rename to src/main/crash-reporting/minidumps/minidump-crashpad-annotations.ts diff --git a/src/main/crash-reporting/minidump-embedded-check.ts b/src/main/crash-reporting/minidumps/minidump-embedded-check.ts similarity index 100% rename from src/main/crash-reporting/minidump-embedded-check.ts rename to src/main/crash-reporting/minidumps/minidump-embedded-check.ts diff --git a/src/main/crash-reporting/minidump-fault-context.test.ts b/src/main/crash-reporting/minidumps/minidump-fault-context.test.ts similarity index 86% rename from src/main/crash-reporting/minidump-fault-context.test.ts rename to src/main/crash-reporting/minidumps/minidump-fault-context.test.ts index 3ceeddeb5d6..1d3e692706c 100644 --- a/src/main/crash-reporting/minidump-fault-context.test.ts +++ b/src/main/crash-reporting/minidumps/minidump-fault-context.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { minidumpSignatureDetails, parseMinidumpCrashSignature } from './minidump-crash-signature' +import { parseMinidumpCrashSignature } from './minidump-crash-signature' const STREAM_TYPE_MODULE_LIST = 4 const STREAM_TYPE_MEMORY_LIST = 5 @@ -101,33 +101,6 @@ function buildFaultDump(options: FaultDump): Buffer { } describe('minidump fault context', () => { - it('reports a write AV into the faulting frame and the executed bytes', async () => { - const rip = 0x7ff6_3941_3f88n - const rsp = 0x8a_3a03_d000n - const dump = buildFaultDump({ - code: 0xc0000005, - rip, - rsp, - params: [1n, rsp + 0x3c8n], - memory: [ - { start: rip - 1n, bytes: Buffer.concat([Buffer.from([0x80]), CODE, Buffer.from([0x4c])]) } - ], - platformId: VER_PLATFORM_WIN32_NT, - modules: [{ base: rip - 0x23d3f88n, size: 0x9000000, name: 'C:\\Orca\\Orca.exe' }] - }) - - const signature = await parseMinidumpCrashSignature(dump) - const details = minidumpSignatureDetails(signature!) - - expect(details).toMatchObject({ - minidumpExceptionCode: '0xc0000005', - minidumpExceptionAccess: 'write', - minidumpFaultAddress: '0x8a3a03d3c8', - minidumpFaultStackPointerDelta: 0x3c8, - minidumpCodeBytes: CODE.toString('hex') - }) - }) - it('omits the stack delta for a fault far from the stack and for non-x64 contexts', async () => { const far = await parseMinidumpCrashSignature( buildFaultDump({ code: 0xc0000005, rip: 0x1000n, rsp: 0x10_0000_0000n, params: [0n, 0x20n] }) diff --git a/src/main/crash-reporting/minidump-fault-context.ts b/src/main/crash-reporting/minidumps/minidump-fault-context.ts similarity index 100% rename from src/main/crash-reporting/minidump-fault-context.ts rename to src/main/crash-reporting/minidumps/minidump-fault-context.ts diff --git a/src/main/crash-reporting/minidumps/minidump-file-source.test.ts b/src/main/crash-reporting/minidumps/minidump-file-source.test.ts new file mode 100644 index 00000000000..105046442e9 --- /dev/null +++ b/src/main/crash-reporting/minidumps/minidump-file-source.test.ts @@ -0,0 +1,44 @@ +import { mkdtemp, open, rm, truncate, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { createMinidumpFileSource } from './minidump-file-source' +import { parseMinidumpCrashSignature } from './minidump-crash-signature' + +const roots: string[] = [] +const LINE = '[8104:1234:0815/143022.123456:FATAL:render_frame_impl.cc(4821)] Check failed: !x.' + +function header(): Buffer { + const bytes = Buffer.alloc(32) + bytes.writeUInt32LE(0x504d444d, 0) + bytes.writeUInt32LE(32, 12) + return bytes +} + +async function sourceFile() { + const root = await mkdtemp(join(tmpdir(), 'orca-minidump-source-')) + roots.push(root) + const path = join(root, 'dump.dmp') + await writeFile(path, header()) + return path +} + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +it('does not read outside the opened extent, including truncation and EOF', async () => { + const path = await sourceFile() + const handle = await open(path, 'r+') + try { + const source = createMinidumpFileSource(handle, 32) + await handle.write(Buffer.from(LINE), 0, LINE.length, 32) + expect(await source.read(32, 4)).toEqual(Buffer.alloc(0)) + expect((await parseMinidumpCrashSignature(source))?.checkMessage).toBeUndefined() + await truncate(path, 4) + const truncated = createMinidumpFileSource(handle, 32) + expect(await parseMinidumpCrashSignature(truncated)).toBeNull() + } finally { + await handle.close() + } +}) diff --git a/src/main/crash-reporting/minidump-file-source.ts b/src/main/crash-reporting/minidumps/minidump-file-source.ts similarity index 100% rename from src/main/crash-reporting/minidump-file-source.ts rename to src/main/crash-reporting/minidumps/minidump-file-source.ts diff --git a/src/main/crash-reporting/minidump-stream-reader.ts b/src/main/crash-reporting/minidumps/minidump-stream-reader.ts similarity index 100% rename from src/main/crash-reporting/minidump-stream-reader.ts rename to src/main/crash-reporting/minidumps/minidump-stream-reader.ts diff --git a/src/main/crash-reporting/pre-gone-host-memory.test.ts b/src/main/crash-reporting/pre-gone-host-memory.test.ts deleted file mode 100644 index 81218242a47..00000000000 --- a/src/main/crash-reporting/pre-gone-host-memory.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { setSystemMemoryInfoReaderForTest } from './system-memory-details' -import { - setSwapVolumeFreeSpaceReaderForTest, - type SwapVolumeFreeSpace -} from './swap-volume-free-space' -import { samplePreGoneSystemMemory } from './pre-gone-host-memory' -import { - buildProcessGoneCrashDetails, - resetPreGoneCrashSamplingForTest -} from './process-gone-diagnostics' - -type MetricFixture = { - pid: number - creationTime: number - type: string - memory: { workingSetSize: number; peakWorkingSetSize?: number; privateBytes?: number } -} - -const { appMetricsMock } = vi.hoisted(() => ({ - appMetricsMock: vi.fn<() => MetricFixture[]>(() => []) -})) - -vi.mock('electron', () => ({ app: { getAppMetrics: appMetricsMock } })) - -const BROWSER_AND_RENDERER: MetricFixture[] = [ - { pid: 10, creationTime: 1, type: 'Browser', memory: { workingSetSize: 1024 * 250 } }, - { - pid: 11, - creationTime: 2, - type: 'Tab', - memory: { workingSetSize: 1024 * 400, peakWorkingSetSize: 1024 * 420, privateBytes: 1024 * 260 } - } -] - -const UNDER_COMMIT_PRESSURE = { - total: 16_000 * 1024, - free: 400 * 1024, - swapTotal: 48_000 * 1024, - swapFree: 200 * 1024 -} - -const AFTER_THE_CORPSE_RELEASED = { - total: 16_000 * 1024, - free: 3_000 * 1024, - swapTotal: 48_000 * 1024, - swapFree: 2_900 * 1024 -} - -const BEFORE_THE_STORM = { - total: 16_000 * 1024, - free: 9_000 * 1024, - swapTotal: 48_000 * 1024, - swapFree: 30_000 * 1024 -} - -describe('pre-gone host memory', () => { - beforeEach(() => { - resetPreGoneCrashSamplingForTest() - setSystemMemoryInfoReaderForTest(null) - setSwapVolumeFreeSpaceReaderForTest(null) - appMetricsMock.mockClear() - appMetricsMock.mockReturnValue(BROWSER_AND_RENDERER) - }) - - it('will not let a statfs that outlived its tick qualify the win32 commit verdict', async () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform')! - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers() - let resolveVolume: (value: SwapVolumeFreeSpace) => void = () => {} - try { - setSystemMemoryInfoReaderForTest(() => BEFORE_THE_STORM) - setSwapVolumeFreeSpaceReaderForTest( - () => - new Promise((resolve) => { - resolveVolume = resolve - }) - ) - void samplePreGoneSystemMemory(0) - - // Later ticks refresh host memory while the original statfs remains pending. - setSystemMemoryInfoReaderForTest(() => UNDER_COMMIT_PRESSURE) - await samplePreGoneSystemMemory(10_000) - await samplePreGoneSystemMemory(20_000) - - resolveVolume({ freeMB: 40_000, volume: 'C:' }) - await vi.advanceTimersByTimeAsync(0) - - vi.setSystemTime(20_000) - const stale = buildProcessGoneCrashDetails({}, 'renderer') - expect(stale.systemMemoryPreGoneSwapFreeMB).toBe(200) - expect(stale.systemMemoryPreGoneSwapVolumeFreeMB).toBe(40_000) - expect(stale.systemMemoryPreGoneSampleAgeMs).toBe(0) - expect(stale.systemMemoryPreGoneSwapVolumeAgeMs).toBe(20_000) - expect(stale.systemMemoryPreGonePressureSignal).toBe('available-commit-unqualified') - - setSwapVolumeFreeSpaceReaderForTest(() => Promise.resolve({ freeMB: 900, volume: 'C:' })) - await samplePreGoneSystemMemory(30_000) - vi.setSystemTime(30_000) - const fresh = buildProcessGoneCrashDetails({}, 'renderer') - expect(fresh.systemMemoryPreGoneSwapVolumeFreeMB).toBe(900) - expect(fresh.systemMemoryPreGoneSwapVolumeAgeMs).toBe(0) - expect(fresh.systemMemoryPreGonePressureSignal).toBe('available-commit-volume-cotimed') - } finally { - vi.useRealTimers() - Object.defineProperty(process, 'platform', platform) - } - }) - - it('will not let ticks with a failed host read pass a stale statfs off as co-timed', async () => { - const platform = Object.getOwnPropertyDescriptor(process, 'platform')! - Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) - vi.useFakeTimers() - let resolveVolume: (value: SwapVolumeFreeSpace) => void = () => {} - try { - setSystemMemoryInfoReaderForTest(() => BEFORE_THE_STORM) - setSwapVolumeFreeSpaceReaderForTest( - () => - new Promise((resolve) => { - resolveVolume = resolve - }) - ) - void samplePreGoneSystemMemory(0) - - setSystemMemoryInfoReaderForTest(() => null) - await samplePreGoneSystemMemory(10_000) - await samplePreGoneSystemMemory(20_000) - - resolveVolume({ freeMB: 40_000, volume: 'C:' }) - await vi.advanceTimersByTimeAsync(0) - - vi.setSystemTime(25_000) - const details = buildProcessGoneCrashDetails({}, 'renderer') - expect(details.systemMemoryPreGoneSwapVolumeAgeMs).toBe(25_000) - expect(details.systemMemoryPreGonePressureSignal).toBe('available-commit-unqualified') - } finally { - vi.useRealTimers() - Object.defineProperty(process, 'platform', platform) - } - }) - - it('commits the host reading without waiting on the swap-volume statfs', async () => { - setSystemMemoryInfoReaderForTest(() => UNDER_COMMIT_PRESSURE) - setSwapVolumeFreeSpaceReaderForTest(() => new Promise(() => {})) - - void samplePreGoneSystemMemory(Date.now() - 5_000) - expect(buildProcessGoneCrashDetails({}, 'renderer').systemMemoryPreGoneSwapFreeMB).toBe(200) - - setSystemMemoryInfoReaderForTest(() => AFTER_THE_CORPSE_RELEASED) - void samplePreGoneSystemMemory(Date.now()) - expect(buildProcessGoneCrashDetails({}, 'renderer').systemMemoryPreGoneSwapFreeMB).toBe(2_900) - }) -}) diff --git a/src/main/crash-reporting/expected-teardown-state.ts b/src/main/crash-reporting/process-exits/expected-teardown-state.ts similarity index 100% rename from src/main/crash-reporting/expected-teardown-state.ts rename to src/main/crash-reporting/process-exits/expected-teardown-state.ts diff --git a/src/main/crash-reporting/main-process-lifecycle-identity.ts b/src/main/crash-reporting/process-exits/main-process-lifecycle-identity.ts similarity index 100% rename from src/main/crash-reporting/main-process-lifecycle-identity.ts rename to src/main/crash-reporting/process-exits/main-process-lifecycle-identity.ts diff --git a/src/main/crash-reporting/process-gone-classification.ts b/src/main/crash-reporting/process-exits/process-gone-classification.ts similarity index 98% rename from src/main/crash-reporting/process-gone-classification.ts rename to src/main/crash-reporting/process-exits/process-gone-classification.ts index 60b3d5f8406..72a8272b743 100644 --- a/src/main/crash-reporting/process-gone-classification.ts +++ b/src/main/crash-reporting/process-exits/process-gone-classification.ts @@ -1,4 +1,4 @@ -import { STT_UTILITY_PROCESS_NAME } from '../speech/stt-worker-process' +import { STT_UTILITY_PROCESS_NAME } from '../../speech/stt-worker-process' export type ProcessGoneSource = 'renderer' | 'child' export type ExpectedTeardownScope = 'none' | 'renderer-reload' | 'app-shutdown' diff --git a/src/main/crash-reporting/process-gone-dedupe.test.ts b/src/main/crash-reporting/process-exits/process-gone-dedupe.test.ts similarity index 100% rename from src/main/crash-reporting/process-gone-dedupe.test.ts rename to src/main/crash-reporting/process-exits/process-gone-dedupe.test.ts diff --git a/src/main/crash-reporting/process-gone-dedupe.ts b/src/main/crash-reporting/process-exits/process-gone-dedupe.ts similarity index 100% rename from src/main/crash-reporting/process-gone-dedupe.ts rename to src/main/crash-reporting/process-exits/process-gone-dedupe.ts diff --git a/src/main/crash-reporting/process-gone-diagnostics.ts b/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts similarity index 96% rename from src/main/crash-reporting/process-gone-diagnostics.ts rename to src/main/crash-reporting/process-exits/process-gone-diagnostics.ts index d7a66b7c344..34e4be0e3e8 100644 --- a/src/main/crash-reporting/process-gone-diagnostics.ts +++ b/src/main/crash-reporting/process-exits/process-gone-diagnostics.ts @@ -1,16 +1,14 @@ import { app } from 'electron' -import { - sanitizeCrashReportDetails, - type CrashReportDetailValue -} from '../../shared/crash-reporting' -import { getSystemMemoryDetails, memoryKBFieldMB } from './system-memory-details' -import { getStartupRtPrioOutcome, readZeroRtTimeLimit } from '../startup/linux-rttime-limit' +import { sanitizeCrashReportDetails } from '../../../shared/crash-report-redaction' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' +import { getSystemMemoryDetails, memoryKBFieldMB } from '../memory/system-memory-details' +import { getStartupRtPrioOutcome, readZeroRtTimeLimit } from '../../startup/linux-rttime-limit' import { PRE_GONE_SYSTEM_MEMORY_SAMPLE_INTERVAL_MS, preGoneSystemMemoryDetails, resetPreGoneSystemMemorySamplingForTest, startPreGoneSystemMemorySampling -} from './pre-gone-host-memory' +} from '../memory/pre-gone-host-memory' type ProcessMetricLike = { pid?: unknown diff --git a/src/main/crash-reporting/process-gone-recorder.test.ts b/src/main/crash-reporting/process-exits/process-gone-recorder.test.ts similarity index 98% rename from src/main/crash-reporting/process-gone-recorder.test.ts rename to src/main/crash-reporting/process-exits/process-gone-recorder.test.ts index 483af25c0a0..3342db2520a 100644 --- a/src/main/crash-reporting/process-gone-recorder.test.ts +++ b/src/main/crash-reporting/process-exits/process-gone-recorder.test.ts @@ -10,11 +10,14 @@ vi.mock('electron', () => ({ getAppMetrics: appMetricsMock } })) -import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' +import { + clearCrashBreadcrumbsForTest, + getCrashBreadcrumbSnapshot +} from '../breadcrumbs/crash-breadcrumb-store' import { ProcessGoneDedupe } from './process-gone-dedupe' import { recordProcessGoneCrash, type ProcessGoneCrashEvent } from './process-gone-recorder' import { resetProcessGoneSiblingCorrelationForTest } from './process-gone-sibling-correlation' -import { _resetTracerForTests, setActiveSink, type TracerSink } from '../observability/tracer' +import { _resetTracerForTests, setActiveSink, type TracerSink } from '../../observability/tracer' type CapturingSink = TracerSink & { records: unknown[]; flushMock: ReturnType } diff --git a/src/main/crash-reporting/process-gone-recorder.ts b/src/main/crash-reporting/process-exits/process-gone-recorder.ts similarity index 93% rename from src/main/crash-reporting/process-gone-recorder.ts rename to src/main/crash-reporting/process-exits/process-gone-recorder.ts index 6445ecf0419..1ed3845cfe5 100644 --- a/src/main/crash-reporting/process-gone-recorder.ts +++ b/src/main/crash-reporting/process-exits/process-gone-recorder.ts @@ -1,19 +1,19 @@ import os from 'node:os' import { app } from 'electron' +import { isCrashReportReason } from '../../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import { - isCrashReportReason, sanitizeCrashReportDetails, - sanitizeCrashReportString, - type CrashReportBreadcrumbData -} from '../../shared/crash-reporting' -import { decodePosixWaitStatus, describePosixWaitStatus } from '../../shared/posix-wait-status' -import { rendererCrashBreadcrumbOrigin } from '../../shared/crash-breadcrumb-origin' -import type { CrashReportStore } from './crash-report-store' -import { getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' + sanitizeCrashReportString +} from '../../../shared/crash-report-redaction' +import { decodePosixWaitStatus, describePosixWaitStatus } from '../../../shared/posix-wait-status' +import { rendererCrashBreadcrumbOrigin } from '../../../shared/crash-breadcrumb-origin' +import type { CrashReportStore } from '../reports/crash-report-store' +import { getCrashBreadcrumbSnapshot } from '../breadcrumbs/crash-breadcrumb-store' import { recordCoalescedDurableCrashBreadcrumb, recordDurableCrashBreadcrumb -} from './durable-crash-breadcrumb' +} from '../breadcrumbs/durable-crash-breadcrumb' import { correlateChildProcessDeath, trackRendererSiblingAttribution @@ -41,9 +41,9 @@ import { captureMinidumpSignature, scheduleCrashpadDumpPrune, type CapturedMinidump -} from './crashpad-capture' -import { minidumpSignatureDetails } from './minidump-crash-signature' -import { flushActiveSink, startSpan } from '../observability/tracer' +} from '../capture/crashpad-capture' +import { minidumpSignatureDetails } from '../minidumps/minidump-crash-signature' +import { flushActiveSink, startSpan } from '../../observability/tracer' export type ProcessGoneCrashEvent = { source: ProcessGoneSource diff --git a/src/main/crash-reporting/process-gone-sibling-attribution.ts b/src/main/crash-reporting/process-exits/process-gone-sibling-attribution.ts similarity index 96% rename from src/main/crash-reporting/process-gone-sibling-attribution.ts rename to src/main/crash-reporting/process-exits/process-gone-sibling-attribution.ts index 2fff7364443..44367a12f26 100644 --- a/src/main/crash-reporting/process-gone-sibling-attribution.ts +++ b/src/main/crash-reporting/process-exits/process-gone-sibling-attribution.ts @@ -1,11 +1,11 @@ import type { CrashReportBreadcrumbData, CrashReportDetailValue -} from '../../shared/crash-reporting' +} from '../../../shared/crash-reporting' import { recordCoalescedDurableCrashBreadcrumb, recordDurableCrashBreadcrumb -} from './durable-crash-breadcrumb' +} from '../breadcrumbs/durable-crash-breadcrumb' import { collectLateSiblingAttributions, observeChildProcessDeath, diff --git a/src/main/crash-reporting/process-gone-sibling-correlation.test.ts b/src/main/crash-reporting/process-exits/process-gone-sibling-correlation.test.ts similarity index 93% rename from src/main/crash-reporting/process-gone-sibling-correlation.test.ts rename to src/main/crash-reporting/process-exits/process-gone-sibling-correlation.test.ts index cccd0a2990e..25b928a77be 100644 --- a/src/main/crash-reporting/process-gone-sibling-correlation.test.ts +++ b/src/main/crash-reporting/process-exits/process-gone-sibling-correlation.test.ts @@ -7,11 +7,14 @@ vi.mock('electron', () => ({ } })) -import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store' +import { + clearCrashBreadcrumbsForTest, + getCrashBreadcrumbSnapshot +} from '../breadcrumbs/crash-breadcrumb-store' import { ProcessGoneDedupe } from './process-gone-dedupe' import { recordProcessGoneCrash, type ProcessGoneCrashEvent } from './process-gone-recorder' import { resetProcessGoneSiblingCorrelationForTest } from './process-gone-sibling-correlation' -import { _resetTracerForTests } from '../observability/tracer' +import { _resetTracerForTests } from '../../observability/tracer' const noMinidump = async () => null diff --git a/src/main/crash-reporting/process-gone-sibling-correlation.ts b/src/main/crash-reporting/process-exits/process-gone-sibling-correlation.ts similarity index 98% rename from src/main/crash-reporting/process-gone-sibling-correlation.ts rename to src/main/crash-reporting/process-exits/process-gone-sibling-correlation.ts index aa98800905d..b9eafc67fca 100644 --- a/src/main/crash-reporting/process-gone-sibling-correlation.ts +++ b/src/main/crash-reporting/process-exits/process-gone-sibling-correlation.ts @@ -1,4 +1,4 @@ -import type { CrashReportDetailValue } from '../../shared/crash-reporting' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' // Correlation is timing evidence only; never use it to discard a renderer crash report. diff --git a/src/main/crash-reporting/self-initiated-tree-kill-log.ts b/src/main/crash-reporting/process-exits/self-initiated-tree-kill-log.ts similarity index 96% rename from src/main/crash-reporting/self-initiated-tree-kill-log.ts rename to src/main/crash-reporting/process-exits/self-initiated-tree-kill-log.ts index 69e89d1141a..aac79b43917 100644 --- a/src/main/crash-reporting/self-initiated-tree-kill-log.ts +++ b/src/main/crash-reporting/process-exits/self-initiated-tree-kill-log.ts @@ -1,6 +1,6 @@ -import type { CrashReportDetailValue } from '../../shared/crash-reporting' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' import type { ProcessTreeKillScope } from '@orca/process-host/process-tree-kill-gate' -import { recordCoalescedDurableCrashBreadcrumb } from './durable-crash-breadcrumb' +import { recordCoalescedDurableCrashBreadcrumb } from '../breadcrumbs/durable-crash-breadcrumb' // Reports see only kills recorded in Electron main; remote-host rings and uninstrumented paths are absent. // An empty count does not prove Orca issued no kill. diff --git a/src/main/crash-reporting/suppressed-process-gone-breadcrumb.ts b/src/main/crash-reporting/process-exits/suppressed-process-gone-breadcrumb.ts similarity index 92% rename from src/main/crash-reporting/suppressed-process-gone-breadcrumb.ts rename to src/main/crash-reporting/process-exits/suppressed-process-gone-breadcrumb.ts index 97b6c1c72f0..5aa7e0c7d1b 100644 --- a/src/main/crash-reporting/suppressed-process-gone-breadcrumb.ts +++ b/src/main/crash-reporting/process-exits/suppressed-process-gone-breadcrumb.ts @@ -1,4 +1,4 @@ -import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' import type { ExpectedTeardownScope } from './process-gone-classification' function safeString(value: unknown): string | undefined { diff --git a/src/main/crash-reporting/process-gone-killed-one-ordering.test.ts b/src/main/crash-reporting/process-gone-killed-one-ordering.test.ts deleted file mode 100644 index dc8ff2c5e08..00000000000 --- a/src/main/crash-reporting/process-gone-killed-one-ordering.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ - app: { - getVersion: () => '1.2.3-test', - getAppMetrics: () => [] - } -})) - -import { clearCrashBreadcrumbsForTest } from './crash-breadcrumb-store' -import { - markSystemSessionEnding, - resetExpectedTeardownStateForTest, - resolveExpectedTeardownScope, - WINDOWS_SESSION_END_CRASH_SUPPRESSION_WINDOW_MS -} from './expected-teardown-state' -import { ProcessGoneDedupe } from './process-gone-dedupe' -import { recordProcessGoneCrash, type ProcessGoneCrashEvent } from './process-gone-recorder' -import { resetProcessGoneSiblingCorrelationForTest } from './process-gone-sibling-correlation' - -const noMinidump = async () => null -const attachDetails = async () => null - -function event(overrides: Partial = {}): ProcessGoneCrashEvent { - return { - source: 'renderer', - processType: 'renderer', - reason: 'killed', - exitCode: 1, - expectedTeardown: 'none', - details: { processType: 'renderer' }, - ...overrides - } -} - -const gpuKill = event({ - source: 'child', - processType: 'GPU', - details: { serviceName: 'GPU', type: 'GPU' } -}) -const networkServiceKill = event({ - source: 'child', - processType: 'Utility', - details: { - name: 'Network Service', - serviceName: 'network.mojom.NetworkService', - type: 'Utility' - } -}) -const rendererKill = event() - -function currentTeardownScope() { - return resolveExpectedTeardownScope({ - isQuitting: false, - isQuittingForUpdate: false, - isExpectedRendererReload: false - }) -} - -let now: number - -beforeEach(() => { - now = 1_000 - resetExpectedTeardownStateForTest(() => now) - clearCrashBreadcrumbsForTest() - resetProcessGoneSiblingCorrelationForTest() -}) - -afterEach(() => { - vi.restoreAllMocks() - resetExpectedTeardownStateForTest() - clearCrashBreadcrumbsForTest() - resetProcessGoneSiblingCorrelationForTest() -}) - -describe('recordProcessGoneCrash killed/1 ordering', () => { - it('reports R3 after matching recoverable sibling churn', () => { - const record = vi.fn().mockResolvedValue({ id: 'report-1' }) - const dedupe = new ProcessGoneDedupe() - - recordProcessGoneCrash({ record } as never, gpuKill, dedupe) - recordProcessGoneCrash({ record } as never, networkServiceKill, dedupe) - recordProcessGoneCrash({ record, attachDetails } as never, rendererKill, dedupe, noMinidump) - - expect(record).toHaveBeenCalledOnce() - expect(record).toHaveBeenCalledWith( - expect.objectContaining({ - // Concurrent victims provide no evidence that one process caused the other's death. - details: expect.objectContaining({ - crashAttribution: 'concurrent-process-deaths', - siblingProcessDeathCount: 2 - }), - breadcrumbs: expect.arrayContaining([ - expect.objectContaining({ - name: 'process_gone_suppressed', - data: expect.objectContaining({ source: 'child', processType: 'GPU' }) - }), - expect.objectContaining({ - name: 'process_gone_suppressed', - data: expect.objectContaining({ - source: 'child', - serviceName: 'network.mojom.NetworkService' - }) - }) - ]) - }) - ) - }) - - it('suppresses the fleet sequence only after independent session-end intent', () => { - const record = vi.fn().mockResolvedValue({ id: 'report-1' }) - const dedupe = new ProcessGoneDedupe() - markSystemSessionEnding() - const expectedTeardown = currentTeardownScope() - - recordProcessGoneCrash({ record } as never, event({ ...gpuKill, expectedTeardown }), dedupe) - recordProcessGoneCrash( - { record } as never, - event({ ...networkServiceKill, expectedTeardown }), - dedupe - ) - recordProcessGoneCrash( - { record } as never, - event({ ...rendererKill, expectedTeardown }), - dedupe - ) - - expect(expectedTeardown).toBe('app-shutdown') - expect(record).not.toHaveBeenCalled() - }) - - it('durably reports killed/1 after the session-end window expires', () => { - const record = vi.fn().mockResolvedValue({ id: 'report-1' }) - markSystemSessionEnding() - now += WINDOWS_SESSION_END_CRASH_SUPPRESSION_WINDOW_MS - const expectedTeardown = currentTeardownScope() - - recordProcessGoneCrash( - { record } as never, - event({ ...rendererKill, expectedTeardown }), - new ProcessGoneDedupe() - ) - - expect(expectedTeardown).toBe('none') - expect(record).toHaveBeenCalledOnce() - }) - - it('keeps a renderer report filed when session-end intent arrives later', () => { - const record = vi.fn().mockResolvedValue({ id: 'report-1' }) - const scopeBeforeSessionEnd = currentTeardownScope() - - recordProcessGoneCrash( - { record } as never, - event({ ...rendererKill, expectedTeardown: scopeBeforeSessionEnd }), - new ProcessGoneDedupe() - ) - markSystemSessionEnding() - const scopeAfterSessionEnd = currentTeardownScope() - recordProcessGoneCrash( - { record } as never, - event({ ...rendererKill, expectedTeardown: scopeAfterSessionEnd }), - new ProcessGoneDedupe() - ) - - expect(scopeBeforeSessionEnd).toBe('none') - expect(scopeAfterSessionEnd).toBe('app-shutdown') - expect(record).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/crash-reporting/gpu-crash-fallback-decision.test.ts b/src/main/crash-reporting/recovery/gpu-crash-fallback-decision.test.ts similarity index 100% rename from src/main/crash-reporting/gpu-crash-fallback-decision.test.ts rename to src/main/crash-reporting/recovery/gpu-crash-fallback-decision.test.ts diff --git a/src/main/crash-reporting/gpu-crash-fallback-decision.ts b/src/main/crash-reporting/recovery/gpu-crash-fallback-decision.ts similarity index 100% rename from src/main/crash-reporting/gpu-crash-fallback-decision.ts rename to src/main/crash-reporting/recovery/gpu-crash-fallback-decision.ts diff --git a/src/main/crash-reporting/gpu-fallback-engagement.test.ts b/src/main/crash-reporting/recovery/gpu-fallback-engagement.test.ts similarity index 82% rename from src/main/crash-reporting/gpu-fallback-engagement.test.ts rename to src/main/crash-reporting/recovery/gpu-fallback-engagement.test.ts index d43d7a7d74d..49c8445aa2c 100644 --- a/src/main/crash-reporting/gpu-fallback-engagement.test.ts +++ b/src/main/crash-reporting/recovery/gpu-fallback-engagement.test.ts @@ -82,17 +82,4 @@ describe('engageGpuFallbackAfterCrashBurst', () => { expect(handlers.clearMarker).not.toHaveBeenCalled() expect(handlers.onPromptFailed).toHaveBeenCalledWith(error) }) - - it('does not relaunch when a quit began while the prompt was open', async () => { - const { handlers } = createHandlers({ isQuitting: () => true }) - await engageGpuFallbackAfterCrashBurst(ENGAGEMENT, handlers) - expect(handlers.restartIntoSafeGraphics).not.toHaveBeenCalled() - expect(handlers.clearMarker).not.toHaveBeenCalled() - }) - - it('does not claim a restart when the marker could not be written', async () => { - const { handlers } = createHandlers({ persistMarker: vi.fn(() => false) }) - await engageGpuFallbackAfterCrashBurst(ENGAGEMENT, handlers) - expect(handlers.restartIntoSafeGraphics).not.toHaveBeenCalled() - }) }) diff --git a/src/main/crash-reporting/gpu-fallback-engagement.ts b/src/main/crash-reporting/recovery/gpu-fallback-engagement.ts similarity index 100% rename from src/main/crash-reporting/gpu-fallback-engagement.ts rename to src/main/crash-reporting/recovery/gpu-fallback-engagement.ts diff --git a/src/main/crash-reporting/gpu-fallback-recovered-launch.ts b/src/main/crash-reporting/recovery/gpu-fallback-recovered-launch.ts similarity index 97% rename from src/main/crash-reporting/gpu-fallback-recovered-launch.ts rename to src/main/crash-reporting/recovery/gpu-fallback-recovered-launch.ts index e8c7463333e..6c4fe3e9d81 100644 --- a/src/main/crash-reporting/gpu-fallback-recovered-launch.ts +++ b/src/main/crash-reporting/recovery/gpu-fallback-recovered-launch.ts @@ -1,5 +1,5 @@ import { dialog, type BrowserWindow, type MessageBoxOptions } from 'electron' -import { translateMain } from '../i18n/main-i18n' +import { translateMain } from '../../i18n/main-i18n' export type GpuFallbackRecoveredLaunchDecision = 'keep-safe' | 'retry-hardware' diff --git a/src/main/crash-reporting/gpu-fallback-restart-prompt.ts b/src/main/crash-reporting/recovery/gpu-fallback-restart-prompt.ts similarity index 96% rename from src/main/crash-reporting/gpu-fallback-restart-prompt.ts rename to src/main/crash-reporting/recovery/gpu-fallback-restart-prompt.ts index 662b33aac51..169664974af 100644 --- a/src/main/crash-reporting/gpu-fallback-restart-prompt.ts +++ b/src/main/crash-reporting/recovery/gpu-fallback-restart-prompt.ts @@ -1,5 +1,5 @@ import { dialog, type BrowserWindow, type MessageBoxOptions } from 'electron' -import { translateMain } from '../i18n/main-i18n' +import { translateMain } from '../../i18n/main-i18n' export type GpuFallbackRestartDecision = 'restart' | 'continue' diff --git a/src/main/crash-reporting/low-commit-oom-recovery-gate.ts b/src/main/crash-reporting/recovery/low-commit-oom-recovery-gate.ts similarity index 94% rename from src/main/crash-reporting/low-commit-oom-recovery-gate.ts rename to src/main/crash-reporting/recovery/low-commit-oom-recovery-gate.ts index 90e9080af60..e635bf57b41 100644 --- a/src/main/crash-reporting/low-commit-oom-recovery-gate.ts +++ b/src/main/crash-reporting/recovery/low-commit-oom-recovery-gate.ts @@ -1,6 +1,6 @@ -import type { CrashReportDetailValue } from '../../shared/crash-reporting' -import { preGoneSystemMemoryDetails } from './pre-gone-host-memory' -import { getSystemMemoryDetails, SYSTEM_MEMORY_KEY_PREFIX } from './system-memory-details' +import type { CrashReportDetailValue } from '../../../shared/crash-reporting' +import { preGoneSystemMemoryDetails } from '../memory/pre-gone-host-memory' +import { getSystemMemoryDetails, SYSTEM_MEMORY_KEY_PREFIX } from '../memory/system-memory-details' // Repeated reloads can immediately OOM again while Windows commit remains exhausted. export const LOW_COMMIT_REPEAT_OOM_WINDOW_MS = 5 * 60_000 diff --git a/src/main/crash-reporting/renderer-recovery-circuit-breaker.test.ts b/src/main/crash-reporting/recovery/renderer-recovery-circuit-breaker.test.ts similarity index 100% rename from src/main/crash-reporting/renderer-recovery-circuit-breaker.test.ts rename to src/main/crash-reporting/recovery/renderer-recovery-circuit-breaker.test.ts diff --git a/src/main/crash-reporting/renderer-recovery-circuit-breaker.ts b/src/main/crash-reporting/recovery/renderer-recovery-circuit-breaker.ts similarity index 100% rename from src/main/crash-reporting/renderer-recovery-circuit-breaker.ts rename to src/main/crash-reporting/recovery/renderer-recovery-circuit-breaker.ts diff --git a/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts b/src/main/crash-reporting/reports/crash-feedback-diagnostic-bundle.ts similarity index 87% rename from src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts rename to src/main/crash-reporting/reports/crash-feedback-diagnostic-bundle.ts index b06828578fb..2072224c13f 100644 --- a/src/main/crash-reporting/crash-feedback-diagnostic-bundle.ts +++ b/src/main/crash-reporting/reports/crash-feedback-diagnostic-bundle.ts @@ -1,12 +1,11 @@ import os from 'node:os' import { app } from 'electron' -import { - sanitizeCrashReportString, - type CrashReportDiagnosticBundle -} from '../../shared/crash-reporting' -import { collectDiagnosticBundle, getDiagnosticsStatus } from '../observability' -import { resolveDiagnosticOrcaChannel } from '../observability/diagnostic-upload-endpoint' -import type { FeedbackDiagnosticBundleAttachment, FeedbackSubmitResult } from '../ipc/feedback' +import { sanitizeCrashReportString } from '../../../shared/crash-report-redaction' +import type { CrashReportDiagnosticBundle } from '../../../shared/crash-reporting-diagnostic-bundle' +import { collectDiagnosticBundle, getDiagnosticsStatus } from '../../observability/index' +import { resolveDiagnosticOrcaChannel } from '../../observability/diagnostic-upload-endpoint' +import type { FeedbackDiagnosticBundleAttachment } from '../../ipc/feedback-request' +import type { FeedbackSubmitResult } from '../../../shared/feedback-submit-contract' const CRASH_REPORT_LOG_LOOKBACK_MINUTES = 3 * 24 * 60 diff --git a/src/main/crash-reporting/crash-report-copy-text.ts b/src/main/crash-reporting/reports/crash-report-copy-text.ts similarity index 91% rename from src/main/crash-reporting/crash-report-copy-text.ts rename to src/main/crash-reporting/reports/crash-report-copy-text.ts index 681b8bd9e85..a23bbfd1314 100644 --- a/src/main/crash-reporting/crash-report-copy-text.ts +++ b/src/main/crash-reporting/reports/crash-report-copy-text.ts @@ -1,7 +1,5 @@ -import { - sanitizeCrashReportString, - type CrashReportCopySubmissionFailure -} from '../../shared/crash-reporting' +import { sanitizeCrashReportString } from '../../../shared/crash-report-redaction' +import type { CrashReportCopySubmissionFailure } from '../../../shared/crash-reporting' function sanitizedNonEmptyString(value: unknown): string | null { if (typeof value !== 'string') { diff --git a/src/main/crash-reporting/crash-report-store.test.ts b/src/main/crash-reporting/reports/crash-report-store.test.ts similarity index 51% rename from src/main/crash-reporting/crash-report-store.test.ts rename to src/main/crash-reporting/reports/crash-report-store.test.ts index 7aa546299e3..6fb277becf6 100644 --- a/src/main/crash-reporting/crash-report-store.test.ts +++ b/src/main/crash-reporting/reports/crash-report-store.test.ts @@ -7,13 +7,13 @@ const { grantDirAclAsyncMock } = vi.hoisted(() => ({ grantDirAclAsyncMock: vi.fn().mockResolvedValue(undefined) })) -vi.mock('../windows/windows-directory-acl', async (importOriginal) => { +vi.mock('../../windows/windows-directory-acl', async (importOriginal) => { const actual = (await importOriginal()) as Record return { ...actual, grantDirAclAsync: grantDirAclAsyncMock } }) import { CrashReportStore } from './crash-report-store' -import type { CrashReportCreateInput } from '../../shared/crash-reporting' +import type { CrashReportCreateInput } from '../../../shared/crash-reporting' const tempDirs: string[] = [] @@ -56,23 +56,6 @@ afterEach(async () => { }) describe('CrashReportStore', () => { - it('records sanitized pending reports and returns the latest pending report', async () => { - const { store } = await createStore() - - const report = await store.record(input()) - - expect(report.status).toBe('pending') - expect(report.details.path).toBe('[redacted-path]') - expect(report.breadcrumbs).toEqual([ - { - createdAt: '2026-05-16T01:00:00.000Z', - name: 'workspace_opened', - data: { path: '[redacted-path]', ssh: false } - } - ]) - await expect(store.getLatestPending()).resolves.toMatchObject({ id: report.id }) - }) - it('persists a submitted dismissed report as sent', async () => { const { store, filePath } = await createStore() const report = await store.record(input()) @@ -92,51 +75,6 @@ describe('CrashReportStore', () => { await expect(store.listRecent()).resolves.toHaveLength(5) }) - it('waits for an in-flight crash write before reading the pending report', async () => { - const { store } = await createStore() - - const recordPromise = store.record(input()) - const pendingPromise = store.getLatestPending() - const report = await recordPromise - - await expect(pendingPromise).resolves.toMatchObject({ id: report.id, status: 'pending' }) - }) - - it('repairs the Windows userData ACL and retries a denied crash write', async () => { - const { store, filePath } = await createStore() - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - const permissionError = Object.assign(new Error('permission denied'), { code: 'EPERM' }) - const writeFileSpy = vi.spyOn(fs, 'writeFile').mockRejectedValueOnce(permissionError) - - const report = await store.record(input()) - - expect(grantDirAclAsyncMock).toHaveBeenCalledWith(path.dirname(filePath)) - expect(writeFileSpy).toHaveBeenCalledTimes(2) - await expect(store.getLatestPending()).resolves.toMatchObject({ id: report.id }) - }) - - it.each(['EPERM', 'EACCES', 'EBUSY'] as const)( - 'recovers a pending report after a transient Windows %s read failure', - async (code) => { - const { store, filePath } = await createStore() - const report = await store.record(input()) - const reloaded = new CrashReportStore(filePath) - vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') - const readError = Object.assign(new Error('temporary read failure'), { code }) - const readFileSpy = vi.spyOn(fs, 'readFile').mockRejectedValueOnce(readError) - - await expect(reloaded.getLatestPending()).resolves.toMatchObject({ id: report.id }) - - expect(readFileSpy).toHaveBeenCalledTimes(2) - if (code === 'EBUSY') { - expect(grantDirAclAsyncMock).not.toHaveBeenCalled() - } else { - expect(grantDirAclAsyncMock).toHaveBeenCalledOnce() - expect(grantDirAclAsyncMock).toHaveBeenCalledWith(path.dirname(filePath)) - } - } - ) - it('removes its temp file after a terminal write failure', async () => { const { store, filePath } = await createStore() const ioError = Object.assign(new Error('disk error'), { code: 'EIO' }) diff --git a/src/main/crash-reporting/crash-report-store.ts b/src/main/crash-reporting/reports/crash-report-store.ts similarity index 96% rename from src/main/crash-reporting/crash-report-store.ts rename to src/main/crash-reporting/reports/crash-report-store.ts index 3317e81087b..a5e22e0adf0 100644 --- a/src/main/crash-reporting/crash-report-store.ts +++ b/src/main/crash-reporting/reports/crash-report-store.ts @@ -3,16 +3,18 @@ import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' import { app } from 'electron' -import { grantDirAclAsync } from '../windows/windows-directory-acl' -import { isPermissionError } from '../filesystem/permission-errors' +import { grantDirAclAsync } from '../../windows/windows-directory-acl' +import { isPermissionError } from '../../filesystem/permission-errors' import { formatCrashReportText, - sanitizeCrashReportBreadcrumbs, - sanitizeCrashReportDetails, type CrashReportCreateInput, type CrashReportRecord, type CrashReportStatus -} from '../../shared/crash-reporting' +} from '../../../shared/crash-reporting' +import { + sanitizeCrashReportBreadcrumbs, + sanitizeCrashReportDetails +} from '../../../shared/crash-report-redaction' const MAX_REPORTS = 5 const RELATED_CRASH_WINDOW_MS = 5_000 diff --git a/src/main/daemon/daemon-entry.ts b/src/main/daemon/daemon-entry.ts index 6f867f9422b..4c7d677d9a5 100644 --- a/src/main/daemon/daemon-entry.ts +++ b/src/main/daemon/daemon-entry.ts @@ -27,7 +27,7 @@ import { } from './pty-subprocess/daemon-native-pty-exception' import { startDaemonScopeDeathWatch } from './process-scopes/daemon-scope-death-watch' import { isWindowsProcessTableAvailable } from '../windows/windows-process-table' -import { leaseAppImageGenerationForCurrentProcess } from '../cli/appimage-generation-lease' +import { leaseAppImageGenerationForCurrentProcess } from '../cli/appimage/appimage-generation-lease' import { createDaemonShutdownDeadline } from './launch/daemon-shutdown-deadline' async function main(): Promise { diff --git a/src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts b/src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts index 50f368caaa0..d237d347131 100644 --- a/src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts +++ b/src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts @@ -7,7 +7,7 @@ import { resolveAppImageRuntimeIdentity } from '../../../updater/linux-package/a import { isAppImageExtractionComplete, resolveAppImageExtractedRoot -} from '../../../cli/appimage-extracted-root' +} from '../../../cli/appimage/appimage-extracted-root' import { envWithoutAppImageRuntime } from '../../../pty/shell-startup/appimage-terminal-env' import type { DurableDaemonScopeCommand } from '../../process-scopes/daemon-cgroup-scope' diff --git a/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts b/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts index bef798b0037..531d87a36c0 100644 --- a/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts +++ b/src/main/daemon/executable-host/linux/testing/daemon-appimage-copy-host.electron.test.ts @@ -39,7 +39,7 @@ import { removeTestRoot } from '../../../../orcad/orcad-daemon-teardown-fixture' import { locatePinnedNodeForTests } from '../../../../orcad/orcad-node-slot-fixture' -import { resolveAppImageExtractedRoot } from '../../../../cli/appimage-extracted-root' +import { resolveAppImageExtractedRoot } from '../../../../cli/appimage/appimage-extracted-root' const ENTRY_IN_APPDIR = 'resources/app.asar.unpacked/out/main/daemon-entry.js' const requireFromTest = createRequire(import.meta.url) diff --git a/src/main/daemon/launch/daemon-out-of-process-launcher.ts b/src/main/daemon/launch/daemon-out-of-process-launcher.ts index cd36a620284..d5ca5ad7bde 100644 --- a/src/main/daemon/launch/daemon-out-of-process-launcher.ts +++ b/src/main/daemon/launch/daemon-out-of-process-launcher.ts @@ -25,7 +25,7 @@ import { resolveAppImageDaemonLaunch } from '../executable-host/linux/daemon-appimage-launch' import { resolveAppImageGenerationDaemonLaunch } from '../executable-host/linux/daemon-appimage-generation-launch' -import { waitForAppImageCopyPreExtraction } from '../../cli/appimage-copy-pre-extraction' +import { waitForAppImageCopyPreExtraction } from '../../cli/appimage/appimage-copy-pre-extraction' import { launchMacDaemonFromStableBundle } from '../executable-host/macos/macos-daemon-launchd' import { DAEMON_RECOVERY_BUDGET_MS, daemonRecoveryProbeTimeoutMs } from './daemon-recovery-budget' import { cleanupDaemonForProtocol } from './daemon-protocol-cleanup' diff --git a/src/main/daemon/shell-readiness/testing/shell-ready-bash-wrapper.test.ts b/src/main/daemon/shell-readiness/testing/shell-ready-bash-wrapper.test.ts index bec5535c5bf..d9fbf343f8f 100644 --- a/src/main/daemon/shell-readiness/testing/shell-ready-bash-wrapper.test.ts +++ b/src/main/daemon/shell-readiness/testing/shell-ready-bash-wrapper.test.ts @@ -6,7 +6,7 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:f import type * as DaemonBashRcfileModule from '../daemon-bash-shell-ready-rcfile' import { getBashShellReadyRcfileContent } from '../../../providers/local-pty/local-pty-shell-ready-bash-rcfile' import { getDaemonBashShellReadyRcfileContent } from '../daemon-bash-shell-ready-rcfile' -import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' +import { prependOrcaCliDirToChildPath } from '../../../cli/launchers/orca-cli-child-path' import { expectBashOsc133Lifecycle, runInteractiveBashRcfile diff --git a/src/main/git/worktrees/removal/worktree-removal.ts b/src/main/git/worktrees/removal/worktree-removal.ts index 4661be47afb..8799659ead8 100644 --- a/src/main/git/worktrees/removal/worktree-removal.ts +++ b/src/main/git/worktrees/removal/worktree-removal.ts @@ -11,8 +11,9 @@ import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation' import { deleteBranchAfterWorktreeRemoval } from './worktree-branch-removal' import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing' -import type { RemoveWorktreeOptions } from '../worktree-operation-options' + import { + type RemoveWorktreeOptions, getErrorCode, gitExecOptions, normalizeLocalBranchRef @@ -25,7 +26,7 @@ import { runUnderWorktreeDeleteLimit } from './worktree-delete-limit' import { removeWindowsCheckout, usesNativeWindowsRemoval } from './windows-worktree-removal' import { listWorktreesStrict } from '../catalog/worktree-listing' import { isWorktreePathMissing } from '../../../workspaces/removal/worktree-removal-safety' -import { runKeyedSerializedOperation } from '../../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../../shared/concurrency/keyed-serialized-operations' const branchCleanupQueueByRepo = new Map>() diff --git a/src/main/github/pr-refresh-event-publisher.ts b/src/main/github/pr-refresh-event-publisher.ts index 50d21b652ef..8dc831b7950 100644 --- a/src/main/github/pr-refresh-event-publisher.ts +++ b/src/main/github/pr-refresh-event-publisher.ts @@ -6,7 +6,7 @@ import type { GitHubPRRefreshSkippedReason, PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' -import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { prRefreshRenderers } from './pr-refresh-renderer-port' // `aliases`: every checkout the read stood for (one read can serve several linked to the same PR). diff --git a/src/main/github/pr-refresh-validation-backoff.test.ts b/src/main/github/pr-refresh-validation-backoff.test.ts index 7bacc73fee1..a67436916ac 100644 --- a/src/main/github/pr-refresh-validation-backoff.test.ts +++ b/src/main/github/pr-refresh-validation-backoff.test.ts @@ -4,7 +4,7 @@ const { recordCoalescedCrashBreadcrumbMock } = vi.hoisted(() => ({ recordCoalescedCrashBreadcrumbMock: vi.fn() })) -vi.mock('../crash-reporting/crash-breadcrumb-store', () => ({ +vi.mock('../crash-reporting/breadcrumbs/crash-breadcrumb-store', () => ({ recordCoalescedCrashBreadcrumb: recordCoalescedCrashBreadcrumbMock })) diff --git a/src/main/github/pr-refresh-validation-backoff.ts b/src/main/github/pr-refresh-validation-backoff.ts index 8f8ea56b4b6..768b65c0bc6 100644 --- a/src/main/github/pr-refresh-validation-backoff.ts +++ b/src/main/github/pr-refresh-validation-backoff.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import { resolve } from 'node:path' -import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' const VALIDATION_BACKOFF_TTL_MS = 5 * 60_000 const MAX_VALIDATION_BACKOFF_ENTRIES = 256 diff --git a/src/main/hang-watchdog/previous-hang-detection.ts b/src/main/hang-watchdog/previous-hang-detection.ts index 2137499ae6e..1c2abcaffd7 100644 --- a/src/main/hang-watchdog/previous-hang-detection.ts +++ b/src/main/hang-watchdog/previous-hang-detection.ts @@ -1,7 +1,7 @@ import { renameSync } from 'node:fs' import { resolveObservabilityConsent } from '../observability' import { hasActiveTraceSink } from '../observability/tracer' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { consumeHangDetectionMarker, hangDetectionMarkerPath, diff --git a/src/main/index.ts b/src/main/index.ts index 031844c5af0..0c82953abbc 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -24,7 +24,7 @@ import { isDivergedProfileStateFailure, profileStateStartupFailureClass } from './persistence/profile-state/startup/profile-state-startup-failure' -import { recordDurableCrashBreadcrumb } from './crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from './crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { chooseProfileStateCopy, chooseProfileStateRepair, @@ -36,7 +36,7 @@ import { profileStateRepairSectionApproval } from '../shared/profile-state-recov import { prepareEarlyMainUiLanguage, translateMain } from './i18n/main-i18n' import { ProfileStateRecoveryRequiredError } from './persistence/profile-state/recovery/profile-state-recovery-required' import { getProfileUserDataPath } from './orca-profiles/profile-storage-paths' -import { leaseAppImageGenerationForCurrentProcess } from './cli/appimage-generation-lease' +import { leaseAppImageGenerationForCurrentProcess } from './cli/appimage/appimage-generation-lease' import { deleteLegacyWslHostWakeList } from './wsl/host-lifecycle/wsl-host-early-wake' import { configureWslHostsGateFromDisk } from './wsl/host-lifecycle/wsl-host-gate-startup' import { configureRemoteRuntimeE2EEV2HostLatch } from '../shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch' diff --git a/src/main/ipc/cli.ts b/src/main/ipc/cli.ts index 63c40c6142e..e5d175e85ce 100644 --- a/src/main/ipc/cli.ts +++ b/src/main/ipc/cli.ts @@ -1,21 +1,21 @@ import { ipcMain } from 'electron' import type { CliInstallStatus } from '../../shared/cli-install-types' -import { resolveAppImageCacheKey } from '../cli/appimage-extracted-root' +import { resolveAppImageCacheKey } from '../../shared/appimage-cache-identity' import { CliInstaller } from '../cli/cli-installer' -import { runKeyedSerializedOperation } from '../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' import { forgetWslCliRegistration, recordWslCliRegistrationInstalled, recordWslCliRegistrationRemoved -} from '../cli/wsl-cli-registration-registry' -import { WslCliInstaller } from '../cli/wsl-cli-installer' +} from '../cli/wsl/wsl-cli-registration-registry' +import { WslCliInstaller } from '../cli/wsl/wsl-cli-installer' import { deletedDistroWslCliStatus, notRunningWslCliStatus, unreachableWslCliStatus, WslCliUnreachableError -} from '../cli/wsl-cli-status' -import { runSerializedWslCliRegistrationOperation } from '../cli/wsl-cli-registration-operation' +} from '../cli/wsl/wsl-cli-status' +import { runSerializedWslCliRegistrationOperation } from '../cli/wsl/wsl-cli-registration-operation' import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' import { getDefaultWslDistro } from '../wsl/discovery/distro-catalog' diff --git a/src/main/ipc/crash-reporting/crash-reporting-renderer-breadcrumbs.ts b/src/main/ipc/crash-reporting/crash-reporting-renderer-breadcrumbs.ts index 971869a0cb2..26622d96501 100644 --- a/src/main/ipc/crash-reporting/crash-reporting-renderer-breadcrumbs.ts +++ b/src/main/ipc/crash-reporting/crash-reporting-renderer-breadcrumbs.ts @@ -6,7 +6,7 @@ import { import { recordCoalescedCrashBreadcrumb, recordCrashBreadcrumb -} from '../../crash-reporting/crash-breadcrumb-store' +} from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { startSpan } from '../../observability/tracer' import { TERMINAL_WEBGL_DIAGNOSTIC_BREADCRUMB } from '../../../shared/terminal/diagnostics/terminal-webgl-diagnostics' diff --git a/src/main/ipc/crash-reporting/crash-reporting-renderer-error-report.ts b/src/main/ipc/crash-reporting/crash-reporting-renderer-error-report.ts index b87c7cb1281..37fde1f327e 100644 --- a/src/main/ipc/crash-reporting/crash-reporting-renderer-error-report.ts +++ b/src/main/ipc/crash-reporting/crash-reporting-renderer-error-report.ts @@ -10,9 +10,9 @@ import { UNRELIABLE_BOUNDARY_ATTRIBUTION, UNRELIABLE_BOUNDARY_ATTRIBUTION_NOTE } from '../../../shared/react-update-depth-attribution' -import type { CrashReportStore } from '../../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' import { rendererCrashBreadcrumbOrigin } from '../../../shared/crash-breadcrumb-origin' -import { getCrashBreadcrumbSnapshot } from '../../crash-reporting/crash-breadcrumb-store' +import { getCrashBreadcrumbSnapshot } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' export const recentRendererErrorReportKeys = new Map() diff --git a/src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts b/src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts index 5a2f6dac1e5..207565d376e 100644 --- a/src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts +++ b/src/main/ipc/crash-reporting/crash-reporting-replay-guard-wedge-burst.test.ts @@ -4,7 +4,7 @@ import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot, recordCrashBreadcrumb -} from '../../crash-reporting/crash-breadcrumb-store' +} from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { recordRendererBreadcrumbFromRenderer } from './crash-reporting-renderer-breadcrumbs' type SpanOptions = { attributes: Record } diff --git a/src/main/ipc/crash-reporting/crash-reporting-sendable-reports.ts b/src/main/ipc/crash-reporting/crash-reporting-sendable-reports.ts index 333cdbedd79..4c8317f641a 100644 --- a/src/main/ipc/crash-reporting/crash-reporting-sendable-reports.ts +++ b/src/main/ipc/crash-reporting/crash-reporting-sendable-reports.ts @@ -1,4 +1,4 @@ -import type { CrashReportStore } from '../../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' export const inFlightSubmissions = new Set() export const submittedReportIds = new Set() diff --git a/src/main/ipc/crash-reporting/crash-reporting-submission.ts b/src/main/ipc/crash-reporting/crash-reporting-submission.ts index 0f0f6748e9c..6472bb9b1e3 100644 --- a/src/main/ipc/crash-reporting/crash-reporting-submission.ts +++ b/src/main/ipc/crash-reporting/crash-reporting-submission.ts @@ -8,12 +8,12 @@ import { formatUncapturedCrashReportText } from '../../../shared/crash-reporting' import { submitFeedback } from '../feedback' -import type { CrashReportStore } from '../../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' import { diagnosticBundleForReportOnlyRetry, prepareCrashDiagnosticBundle, resolveSubmittedDiagnosticBundle -} from '../../crash-reporting/crash-feedback-diagnostic-bundle' +} from '../../crash-reporting/reports/crash-feedback-diagnostic-bundle' import { getRequestedCrashReport, inFlightSubmissions, diff --git a/src/main/ipc/crash-reporting/crash-reporting.ts b/src/main/ipc/crash-reporting/crash-reporting.ts index df022718fc7..da8291e69f4 100644 --- a/src/main/ipc/crash-reporting/crash-reporting.ts +++ b/src/main/ipc/crash-reporting/crash-reporting.ts @@ -4,13 +4,13 @@ import { type CrashReportSubmitArgs, formatCrashReportText } from '../../../shared/crash-reporting' -import type { CrashReportStore } from '../../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' import { rendererCrashBreadcrumbOrigin } from '../../../shared/crash-breadcrumb-origin' import { assertClipboardTextWriteWithinLimit, isClipboardTextWriteTooLargeError } from '../../../shared/clipboard-text' -import { formatCrashReportCopyText } from '../../crash-reporting/crash-report-copy-text' +import { formatCrashReportCopyText } from '../../crash-reporting/reports/crash-report-copy-text' import { recentRendererErrorReportKeys, recordRendererErrorReport @@ -19,7 +19,7 @@ import { recordRendererBreadcrumbFromRenderer } from './crash-reporting-renderer import { profiledRendererFor, profileRendererMemoryBreadcrumb -} from '../../crash-reporting/renderer-heap-allocation-profile' +} from '../../crash-reporting/memory/renderer-heap-allocation-profile' import { getLatestPendingReport, getLatestSendableReport, diff --git a/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts b/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts index eca4862f633..0c36980e9e5 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-staging.test.ts @@ -37,7 +37,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).wslUncDeleteMock ) vi.mock( - '../../crash-reporting/crash-breadcrumb-store', + '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ diff --git a/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts b/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts index 3a85f5280c4..7af180afb3a 100644 --- a/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts +++ b/src/main/ipc/filesystem/filesystem-pull-request-linked-issue-lifetime.test.ts @@ -39,7 +39,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).wslUncDeleteMock ) vi.mock( - '../../crash-reporting/crash-breadcrumb-store', + '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ diff --git a/src/main/ipc/filesystem/filesystem-read-handlers.ts b/src/main/ipc/filesystem/filesystem-read-handlers.ts index c93a3f126f8..b6d7dcbbb46 100644 --- a/src/main/ipc/filesystem/filesystem-read-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-read-handlers.ts @@ -22,7 +22,7 @@ import { import { isPathAbsentError } from './access/filesystem-path-containment' import { listMarkdownDocuments } from '../markdown-documents' import { getLocalGitOptionsForRegisteredWorktree } from '../local-worktree-runtime-options' -import { recordCrashBreadcrumb } from '../../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { buildReadDirErrorBreadcrumb, type ReadDirThrowSite } from '../readdir-error-diagnostics' import type { FilesystemHandlerContext } from './filesystem-handler-context' import { registerFilesystemChunkReadHandler } from './filesystem-chunk-read-handler' diff --git a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts index b715be4c2f1..a4e9e31742a 100644 --- a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts +++ b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts @@ -49,7 +49,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).wslUncDeleteMock ) vi.mock( - '../../crash-reporting/crash-breadcrumb-store', + '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ diff --git a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts index 7cf064866dd..e37577bb026 100644 --- a/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts +++ b/src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts @@ -45,7 +45,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).wslUncDeleteMock ) vi.mock( - '../../crash-reporting/crash-breadcrumb-store', + '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ diff --git a/src/main/ipc/filesystem/filesystem.test.ts b/src/main/ipc/filesystem/filesystem.test.ts index 28318569871..a8bbce81e38 100644 --- a/src/main/ipc/filesystem/filesystem.test.ts +++ b/src/main/ipc/filesystem/filesystem.test.ts @@ -43,7 +43,7 @@ vi.mock( async () => (await import('./filesystem-test-harness')).wslUncDeleteMock ) vi.mock( - '../../crash-reporting/crash-breadcrumb-store', + '../../crash-reporting/breadcrumbs/crash-breadcrumb-store', async () => (await import('./filesystem-test-harness')).crashBreadcrumbMock ) vi.mock('../../git/source-control/commit-changes', async (importOriginal) => ({ diff --git a/src/main/ipc/filesystem/local-disk-write-precondition.ts b/src/main/ipc/filesystem/local-disk-write-precondition.ts index e54f3f099e9..b550fc8ad30 100644 --- a/src/main/ipc/filesystem/local-disk-write-precondition.ts +++ b/src/main/ipc/filesystem/local-disk-write-precondition.ts @@ -16,7 +16,7 @@ import { } from '../../../shared/file-write/file-write-disk-precondition' import { readlink, realpath, stat, writeFile } from 'node:fs/promises' import { basename, dirname, join, normalize, resolve } from 'node:path' -import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' import { serializedParentDirectoryKey } from '../../filesystem/destination-serialized-local-rename' import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' import { diff --git a/src/main/ipc/pty-claude-agent-view-readiness.test.ts b/src/main/ipc/pty-claude-agent-view-readiness.test.ts index 5d446710807..cb678ed7ea3 100644 --- a/src/main/ipc/pty-claude-agent-view-readiness.test.ts +++ b/src/main/ipc/pty-claude-agent-view-readiness.test.ts @@ -36,7 +36,7 @@ vi.mock('../telemetry/client', () => vi.mock('../telemetry/classify-error', () => import('./pty/pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty/pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../memory/pty-registry', () => diff --git a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts index b46881130cb..e88c9e85c39 100644 --- a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts +++ b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts @@ -39,7 +39,7 @@ vi.mock('../telemetry/client', () => vi.mock('../telemetry/classify-error', () => import('./pty/pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty/pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../memory/pty-registry', () => diff --git a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts index d5139e457ab..2ebabc0eb7e 100644 --- a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts +++ b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts @@ -42,7 +42,7 @@ vi.mock('../telemetry/client', () => vi.mock('../telemetry/classify-error', () => import('./pty/pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty/pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../memory/pty-registry', () => diff --git a/src/main/ipc/pty/delivery/pending.ts b/src/main/ipc/pty/delivery/pending.ts index 48ca6b444d8..71ccc572383 100644 --- a/src/main/ipc/pty/delivery/pending.ts +++ b/src/main/ipc/pty/delivery/pending.ts @@ -9,7 +9,7 @@ import { advanceDroppedSynchronizedOutputLatch } from '../../../../shared/terminal/protocol/escape/terminal-synchronized-output-scan' import { redactPtyIdForDiagnostics } from '../../../../shared/terminal/pty/diagnostics/pty-delivery-diagnostics' -import { recordCrashBreadcrumb } from '../../../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { terminalOutputBacklogCapChars } from '../../../../shared/terminal/replay/terminal-scrollback-policy' import { isHiddenPtyDeliveryGateEnabled } from './pty-hidden-delivery-gate' import type { PendingPtyData } from './pty-pending-data-drain-contract' diff --git a/src/main/ipc/pty/host-env/assembly.ts b/src/main/ipc/pty/host-env/assembly.ts index 8fbb59ecc82..2e2b35582de 100644 --- a/src/main/ipc/pty/host-env/assembly.ts +++ b/src/main/ipc/pty/host-env/assembly.ts @@ -12,8 +12,8 @@ import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { wslHookRelayManager } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { wslInteropHealthMonitor } from '../../../wsl/execution/wsl-interop-health' import { piTitlebarExtensionService } from '../../../pi/titlebar-extension-service' -import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' -import { getManagedWslCliDir, getWslCliCommandName } from '../../../cli/wsl-managed-cli' +import { prependOrcaCliDirToChildPath } from '../../../cli/launchers/orca-cli-child-path' +import { getManagedWslCliDir, getWslCliCommandName } from '../../../cli/wsl/wsl-managed-cli' import { stripLegacyTerminalShimEnv } from '../../../pty/shell-startup/legacy-terminal-shim-dir' import { mergePersistedWindowsPath } from '../../../pty/environment/windows-environment-path' import { resolveCodexShellLaunchPreflightCommand } from '../../../pty/shell-startup/codex-shell-launch-preflight' diff --git a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts index daa8444df1d..15106d5b651 100644 --- a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts +++ b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts @@ -24,8 +24,10 @@ vi.mock('../../../agent-hooks/wsl-relay/wsl-hook-relay-manager', () => ({ vi.mock('../../../pi/titlebar-extension-service', () => ({ piTitlebarExtensionService: { buildPtyEnv: () => ({}), buildFreshOmpEnv: () => ({}) } })) -vi.mock('../../../cli/orca-cli-child-path', () => ({ prependOrcaCliDirToChildPath: () => {} })) -vi.mock('../../../cli/wsl-managed-cli', () => ({ +vi.mock('../../../cli/launchers/orca-cli-child-path', () => ({ + prependOrcaCliDirToChildPath: () => {} +})) +vi.mock('../../../cli/wsl/wsl-managed-cli', () => ({ getManagedWslCliDir: () => undefined, getWslCliCommandName: () => 'orca-ide' })) diff --git a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts index 17b5a04200b..2f0e6ce96da 100644 --- a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts +++ b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts @@ -42,7 +42,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts index 631df8b569e..7766d3392c3 100644 --- a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts +++ b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts @@ -35,7 +35,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts index 5079597303f..594e4a22394 100644 --- a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts +++ b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts @@ -33,7 +33,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts index 44f80f22199..3ae41c7b8a3 100644 --- a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts +++ b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts @@ -33,7 +33,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-ipc-test-constants.ts b/src/main/ipc/pty/pty-ipc-test-constants.ts index b9a61daab61..3118a932c5a 100644 --- a/src/main/ipc/pty/pty-ipc-test-constants.ts +++ b/src/main/ipc/pty/pty-ipc-test-constants.ts @@ -1,7 +1,7 @@ -import { it, vi } from 'vitest' -import type { Mock } from 'vitest' +import { it, vi, type Mock } from 'vitest' + import { join, posix } from 'node:path' -import { getBundledLauncherPath } from '../../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../../cli/packaged-assets/bundled-cli-launcher-path' import { resolveWindowsShellLaunchArgs } from '../../providers/windows-shell-args' export type PlatformGatedTest = ( diff --git a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts index 42cbace177e..eaa4f871787 100644 --- a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts +++ b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts @@ -34,7 +34,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-pane-restart-replace.test.ts b/src/main/ipc/pty/pty-pane-restart-replace.test.ts index 025d9c87195..12150e52464 100644 --- a/src/main/ipc/pty/pty-pane-restart-replace.test.ts +++ b/src/main/ipc/pty/pty-pane-restart-replace.test.ts @@ -38,7 +38,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts index a519ac4c3f2..1487ae1f706 100644 --- a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts +++ b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts @@ -33,7 +33,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts index afe9e6f188b..a26d14744c9 100644 --- a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts +++ b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts @@ -33,7 +33,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts index 0e3c9c93970..a98a4cd2f43 100644 --- a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts +++ b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts @@ -33,7 +33,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts index 374fcd7c691..2321328f301 100644 --- a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts +++ b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts @@ -38,7 +38,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts index 91dbd5afd6b..c3008c54838 100644 --- a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts +++ b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts @@ -39,7 +39,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/pty-write-ipc-validation.test.ts b/src/main/ipc/pty/pty-write-ipc-validation.test.ts index 56c13db1847..28e7899473d 100644 --- a/src/main/ipc/pty/pty-write-ipc-validation.test.ts +++ b/src/main/ipc/pty/pty-write-ipc-validation.test.ts @@ -34,7 +34,7 @@ vi.mock('../../telemetry/client', () => vi.mock('../../telemetry/classify-error', () => import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../cli/launchers/linux-terminal-orca-cli-shim', () => import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../memory/pty-registry', () => diff --git a/src/main/ipc/pty/register-handlers.ts b/src/main/ipc/pty/register-handlers.ts index db906ee9e55..6fbf48782d8 100644 --- a/src/main/ipc/pty/register-handlers.ts +++ b/src/main/ipc/pty/register-handlers.ts @@ -66,7 +66,7 @@ import { resolveCodexResumeLaunch, stripSequencedStartupResumeArgv } from './host-env/codex-resume' -import { ensureLinuxTerminalOrcaCliShimDir } from '../../cli/linux-terminal-orca-cli-shim' +import { ensureLinuxTerminalOrcaCliShimDir } from '../../cli/launchers/linux-terminal-orca-cli-shim' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' export function registerPtyHandlers( diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 1e92599e1df..e6d650ab58c 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -94,7 +94,7 @@ import type { CodexAccountService } from '../../codex-accounts/service' import type { ClaudeAccountService } from '../../claude-accounts/service' import type { AutomationService } from '../../automations/service' import type { AgentAwakeService } from '../../power/agent-awake-service' -import type { CrashReportStore } from '../../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../../crash-reporting/reports/crash-report-store' import type { KeybindingService } from '../../keybindings/keybinding-service' import type { AiVaultPrepareSessionResumeArgs, diff --git a/src/main/native-chat/agent-session-context-snapshots.ts b/src/main/native-chat/agent-session-context-snapshots.ts index 14898f385c5..33693cffe1f 100644 --- a/src/main/native-chat/agent-session-context-snapshots.ts +++ b/src/main/native-chat/agent-session-context-snapshots.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto' import { rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' -import { runKeyedSerializedOperation } from '../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../shared/concurrency/keyed-serialized-operations' import { renameFileWithWindowsRetryAsync } from '../../shared/windows-retry-file-operations' import { ensureOwnedTempStagingRoot, diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-task-queue.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-task-queue.ts index 67aa76e0f2b..d66b7fdd6e5 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-task-queue.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-task-queue.ts @@ -1,4 +1,4 @@ -import { runKeyedSerializedOperation } from '../../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../../shared/concurrency/keyed-serialized-operations' import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' export class StructuredAgentSessionTaskQueue { diff --git a/src/main/orcad/orcad-cli-launcher.ts b/src/main/orcad/orcad-cli-launcher.ts index 7d9aa9010ae..ed39f5c49bb 100644 --- a/src/main/orcad/orcad-cli-launcher.ts +++ b/src/main/orcad/orcad-cli-launcher.ts @@ -7,7 +7,7 @@ import { ORCAD_WINDOWS_CLI_LAUNCHER_FILENAME } from '../../shared/orcad-artifacts' import { nodeFileContentsEqual } from '../../shared/file-content/node-file-content-equality' -import { buildUnixCliLauncher } from '../cli/cli-dev-launcher' +import { buildUnixCliLauncher } from '../cli/launchers/cli-dev-launcher' import { writeFileAtomically } from '../filesystem/atomic-file-publication' import { resolveOrcadInstallRoot, resolveUserDataPath } from './orcad-app-paths' diff --git a/src/main/persistence/profile-state/writer/profile-state-writer-diagnostics.ts b/src/main/persistence/profile-state/writer/profile-state-writer-diagnostics.ts index 95f89664c10..f450cd838ab 100644 --- a/src/main/persistence/profile-state/writer/profile-state-writer-diagnostics.ts +++ b/src/main/persistence/profile-state/writer/profile-state-writer-diagnostics.ts @@ -2,7 +2,7 @@ import type { CrashReportBreadcrumbData } from '../../../../shared/crash-reporti import { recordCoalescedDurableCrashBreadcrumb, recordDurableCrashBreadcrumb -} from '../../../crash-reporting/durable-crash-breadcrumb' +} from '../../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { getSystemPowerState } from '../../../power/system-power-lifecycle' import { profileStateWriterFailureOutcome } from './profile-state-writer-errors' diff --git a/src/main/power/system-resume-broadcast.test.ts b/src/main/power/system-resume-broadcast.test.ts index 704c805488c..ec7335afbac 100644 --- a/src/main/power/system-resume-broadcast.test.ts +++ b/src/main/power/system-resume-broadcast.test.ts @@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot -} from '../crash-reporting/crash-breadcrumb-store' +} from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { registerSystemResumeBroadcast } from './system-resume-broadcast' vi.mock('electron', () => ({ diff --git a/src/main/power/system-resume-broadcast.ts b/src/main/power/system-resume-broadcast.ts index 2488f3d0f90..2ea42dbae09 100644 --- a/src/main/power/system-resume-broadcast.ts +++ b/src/main/power/system-resume-broadcast.ts @@ -1,5 +1,5 @@ import { BrowserWindow, powerMonitor } from 'electron' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { publishSystemResume, publishSystemSuspend } from './system-power-lifecycle' export const SYSTEM_RESUMED_CHANNEL = 'system:resumed' diff --git a/src/main/provider-process/managed-provider-process-fallback-tree.test.ts b/src/main/provider-process/managed-provider-process-fallback-tree.test.ts index 77c19808177..b66c44bb33f 100644 --- a/src/main/provider-process/managed-provider-process-fallback-tree.test.ts +++ b/src/main/provider-process/managed-provider-process-fallback-tree.test.ts @@ -20,7 +20,7 @@ vi.mock('../pty/process-retirement/pty-descendant-termination', () => ({ vi.mock('../pty/process-retirement/pty-descendant-exit-verification', () => ({ terminateDescendantSnapshotWithVerdict: os.verifySnapshot })) -vi.mock('../crash-reporting/self-initiated-tree-kill-log', () => ({ +vi.mock('../crash-reporting/process-exits/self-initiated-tree-kill-log', () => ({ recordSelfInitiatedTreeKill: vi.fn() })) diff --git a/src/main/provider-process/provider-group-orphan-guard.ts b/src/main/provider-process/provider-group-orphan-guard.ts index cfc9b546ae5..5792f763630 100644 --- a/src/main/provider-process/provider-group-orphan-guard.ts +++ b/src/main/provider-process/provider-group-orphan-guard.ts @@ -1,5 +1,5 @@ import { hasUnambiguousStartTime } from '../pty/process-retirement/pty-descendant-termination' -import { recordSelfInitiatedTreeKill } from '../crash-reporting/self-initiated-tree-kill-log' +import { recordSelfInitiatedTreeKill } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' import { setTimeout as delay } from 'node:timers/promises' import { readPosixProcessRow, type ProcessRowRead } from './provider-process-row-read' diff --git a/src/main/provider-process/provider-process-teardown.test.ts b/src/main/provider-process/provider-process-teardown.test.ts index d4edc4fe151..4555695ec7e 100644 --- a/src/main/provider-process/provider-process-teardown.test.ts +++ b/src/main/provider-process/provider-process-teardown.test.ts @@ -1,6 +1,6 @@ import type { ChildProcess } from 'node:child_process' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { resetSelfInitiatedTreeKillLogForTest } from '../crash-reporting/self-initiated-tree-kill-log' +import { resetSelfInitiatedTreeKillLogForTest } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' import type { DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' import { terminateProviderProcessTree as terminateWithEvidence } from './provider-process-teardown' diff --git a/src/main/provider-process/provider-process-teardown.ts b/src/main/provider-process/provider-process-teardown.ts index c751abeea98..773a3c11032 100644 --- a/src/main/provider-process/provider-process-teardown.ts +++ b/src/main/provider-process/provider-process-teardown.ts @@ -8,7 +8,7 @@ import { type DescendantTreeVerdict } from '../pty/process-retirement/pty-descendant-exit-verification' import { terminateWindowsProcessTree } from '../pty/process-retirement/windows-process-tree-kill' -import { recordSelfInitiatedTreeKill } from '../crash-reporting/self-initiated-tree-kill-log' +import { recordSelfInitiatedTreeKill } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' /** What the teardown observed of the descendants; null when it signalled but observed nothing. */ diff --git a/src/main/provider-process/provider-tree-kill-attribution.test.ts b/src/main/provider-process/provider-tree-kill-attribution.test.ts index dc6ae9f9c2e..45a4fe286a6 100644 --- a/src/main/provider-process/provider-tree-kill-attribution.test.ts +++ b/src/main/provider-process/provider-tree-kill-attribution.test.ts @@ -5,7 +5,7 @@ import { proveClaudeChildExit } from '../claude/claude-agent-sdk-exit-proof' import { findSelfInitiatedTreeKills, resetSelfInitiatedTreeKillLogForTest -} from '../crash-reporting/self-initiated-tree-kill-log' +} from '../crash-reporting/process-exits/self-initiated-tree-kill-log' import { spawnManagedProviderProcess } from './managed-provider-process' vi.mock('node:child_process', async (importOriginal) => ({ diff --git a/src/main/pty/process-retirement/orca-chromium-process-pids.ts b/src/main/pty/process-retirement/orca-chromium-process-pids.ts index afa05c3e1ee..d944161eea6 100644 --- a/src/main/pty/process-retirement/orca-chromium-process-pids.ts +++ b/src/main/pty/process-retirement/orca-chromium-process-pids.ts @@ -1,5 +1,5 @@ import { getAppEnvironment, hasAppEnvironment } from '../../../shared/app-environment' -import { recordCoalescedDurableCrashBreadcrumb } from '../../crash-reporting/durable-crash-breadcrumb' +import { recordCoalescedDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' /** * Guard Windows PID-based kills; stale metrics must not prevent root termination through its handle. diff --git a/src/main/pty/process-retirement/own-chromium-tree-kill-guard.ts b/src/main/pty/process-retirement/own-chromium-tree-kill-guard.ts index 199e28f831b..5114d24d65d 100644 --- a/src/main/pty/process-retirement/own-chromium-tree-kill-guard.ts +++ b/src/main/pty/process-retirement/own-chromium-tree-kill-guard.ts @@ -2,7 +2,7 @@ import { recordRefusedOwnChromiumTreeKill, recordSelfInitiatedTreeKill, type SelfInitiatedTreeKillScope -} from '../../crash-reporting/self-initiated-tree-kill-log' +} from '../../crash-reporting/process-exits/self-initiated-tree-kill-log' import { readOrcaChromiumProcessPids } from './orca-chromium-process-pids' import { setProcessTreeKillGate } from '@orca/process-host/process-tree-kill-gate' diff --git a/src/main/pty/process-retirement/posix-pty-process-groups.test.ts b/src/main/pty/process-retirement/posix-pty-process-groups.test.ts index fa4728a971c..02f3821dc41 100644 --- a/src/main/pty/process-retirement/posix-pty-process-groups.test.ts +++ b/src/main/pty/process-retirement/posix-pty-process-groups.test.ts @@ -24,7 +24,7 @@ vi.mock('node:fs/promises', async (importOriginal) => ({ ...(await importOriginal()), readFile: readFileMock })) -vi.mock('../../crash-reporting/self-initiated-tree-kill-log', () => ({ +vi.mock('../../crash-reporting/process-exits/self-initiated-tree-kill-log', () => ({ recordSelfInitiatedTreeKill: recordSelfInitiatedTreeKillMock })) vi.mock('@orca/process-host', () => ({ diff --git a/src/main/pty/process-retirement/posix-pty-process-groups.ts b/src/main/pty/process-retirement/posix-pty-process-groups.ts index 598e693c70b..6c1acd312db 100644 --- a/src/main/pty/process-retirement/posix-pty-process-groups.ts +++ b/src/main/pty/process-retirement/posix-pty-process-groups.ts @@ -1,5 +1,5 @@ import { hasControllingTty } from '../../../shared/posix-controlling-terminal' -import { recordSelfInitiatedTreeKill } from '../../crash-reporting/self-initiated-tree-kill-log' +import { recordSelfInitiatedTreeKill } from '../../crash-reporting/process-exits/self-initiated-tree-kill-log' import { parseProcessRows, readLinuxProcessSessionId, diff --git a/src/main/pty/process-retirement/refused-tree-kill-root-termination.test.ts b/src/main/pty/process-retirement/refused-tree-kill-root-termination.test.ts index fbe42538b96..c4bc907c5e9 100644 --- a/src/main/pty/process-retirement/refused-tree-kill-root-termination.test.ts +++ b/src/main/pty/process-retirement/refused-tree-kill-root-termination.test.ts @@ -20,11 +20,11 @@ import { } from '../../../shared/app-environment' import { installMainProcessTreeKillGate } from './own-chromium-tree-kill-guard' import { setProcessTreeKillGate } from '@orca/process-host/process-tree-kill-gate' -import { resetSelfInitiatedTreeKillLogForTest } from '../../crash-reporting/self-initiated-tree-kill-log' +import { resetSelfInitiatedTreeKillLogForTest } from '../../crash-reporting/process-exits/self-initiated-tree-kill-log' import { clearCrashBreadcrumbsForTest, getCrashBreadcrumbSnapshot -} from '../../crash-reporting/crash-breadcrumb-store' +} from '../../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { _resetTracerForTests, setActiveSink } from '../../observability/tracer' import { signalProcessTree } from '@orca/process-host/process-tree-termination' diff --git a/src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts b/src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts index 50789ea0caf..ff7026ba2b5 100644 --- a/src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts +++ b/src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts @@ -12,7 +12,7 @@ import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' import { findSelfInitiatedTreeKills, resetSelfInitiatedTreeKillLogForTest -} from '../../crash-reporting/self-initiated-tree-kill-log' +} from '../../crash-reporting/process-exits/self-initiated-tree-kill-log' import { installMainProcessTreeKillGate } from './own-chromium-tree-kill-guard' import { terminateWindowsProcessTree } from './windows-process-tree-kill' diff --git a/src/main/pty/shell-startup/codex-preflight-profile-path-rewrite.test.ts b/src/main/pty/shell-startup/codex-preflight-profile-path-rewrite.test.ts index 9168c01b0c1..a5eec633168 100644 --- a/src/main/pty/shell-startup/codex-preflight-profile-path-rewrite.test.ts +++ b/src/main/pty/shell-startup/codex-preflight-profile-path-rewrite.test.ts @@ -11,7 +11,7 @@ import { import { tmpdir } from 'node:os' import { delimiter, join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { getBundledLauncherPath } from '../../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../../cli/packaged-assets/bundled-cli-launcher-path' import { getDaemonBashShellReadyRcfileContent } from '../../daemon/shell-readiness/daemon-bash-shell-ready-rcfile' import { resolveCodexShellLaunchPreflightCommand } from './codex-shell-launch-preflight' diff --git a/src/main/pty/shell-startup/codex-shell-launch-preflight.ts b/src/main/pty/shell-startup/codex-shell-launch-preflight.ts index 7cbd3fd69da..f8bc628d5a7 100644 --- a/src/main/pty/shell-startup/codex-shell-launch-preflight.ts +++ b/src/main/pty/shell-startup/codex-shell-launch-preflight.ts @@ -1,5 +1,5 @@ import { accessSync, constants, statSync } from 'node:fs' -import { getBundledLauncherPath } from '../../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../../cli/packaged-assets/bundled-cli-launcher-path' export type CodexShellLaunchPreflightCommandOptions = { hooksEnabled: boolean diff --git a/src/main/runtime/agent-session/environment/structured-session-child-env.ts b/src/main/runtime/agent-session/environment/structured-session-child-env.ts index 37bec85bfcf..cd0efc1d189 100644 --- a/src/main/runtime/agent-session/environment/structured-session-child-env.ts +++ b/src/main/runtime/agent-session/environment/structured-session-child-env.ts @@ -11,7 +11,7 @@ import { } from '../../../../shared/agent-session/lifecycle/agent-session-caller-env' import { ORCA_STRUCTURED_SESSION_ENV } from '../../../../shared/structured-session-marker' import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolution' -import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' +import { prependOrcaCliDirToChildPath } from '../../../cli/launchers/orca-cli-child-path' import { AGENT_PANE_HOOK_ENV_KEYS } from '../../../ipc/pty/host-env/spawn-env-keys' import { resolveStructuredWorkerIdentityForSession } from '../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' diff --git a/src/main/runtime/integrations/skill/runtime-skill-command-surface.ts b/src/main/runtime/integrations/skill/runtime-skill-command-surface.ts index 64e5463ae1b..b5952ca8ea8 100644 --- a/src/main/runtime/integrations/skill/runtime-skill-command-surface.ts +++ b/src/main/runtime/integrations/skill/runtime-skill-command-surface.ts @@ -1,5 +1,5 @@ import '../../../../shared/git/admission/git-admission-state' -import '../../../crash-reporting/main-process-lifecycle-identity' +import '../../../crash-reporting/process-exits/main-process-lifecycle-identity' import { join } from 'node:path' import { assertAgentSkillSharingAllowed, diff --git a/src/main/runtime/integrations/skill/runtime-skill-install-commands.ts b/src/main/runtime/integrations/skill/runtime-skill-install-commands.ts index e316bde615b..6baab44d34a 100644 --- a/src/main/runtime/integrations/skill/runtime-skill-install-commands.ts +++ b/src/main/runtime/integrations/skill/runtime-skill-install-commands.ts @@ -1,5 +1,5 @@ import '../../../../shared/git/admission/git-admission-state' -import '../../../crash-reporting/main-process-lifecycle-identity' +import '../../../crash-reporting/process-exits/main-process-lifecycle-identity' import { join } from 'node:path' import { detectInstalledAgentsWithShellPathHydration } from '../../../preflight/installed-agent-detection' import { executeSkillInstallRequest } from '../../../skills/install/skill-install-request' diff --git a/src/main/runtime/integrations/skill/runtime-skill-install-queries.ts b/src/main/runtime/integrations/skill/runtime-skill-install-queries.ts index 36ecc608fc5..9e130bb6ffd 100644 --- a/src/main/runtime/integrations/skill/runtime-skill-install-queries.ts +++ b/src/main/runtime/integrations/skill/runtime-skill-install-queries.ts @@ -1,5 +1,5 @@ import '../../../../shared/git/admission/git-admission-state' -import '../../../crash-reporting/main-process-lifecycle-identity' +import '../../../crash-reporting/process-exits/main-process-lifecycle-identity' import { homedir } from 'node:os' import { dirname, join } from 'node:path' import { detectInstalledAgentsWithShellPathHydration } from '../../../preflight/installed-agent-detection' diff --git a/src/main/runtime/push/desktop-push-service.ts b/src/main/runtime/push/desktop-push-service.ts index 795b4a0df81..7b0c7b18a8b 100644 --- a/src/main/runtime/push/desktop-push-service.ts +++ b/src/main/runtime/push/desktop-push-service.ts @@ -5,7 +5,7 @@ import type { MobilePushRegisterInput, MobilePushRegisterResult } from '../../../shared/mobile-push-contract' -import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' import type { DeviceRegistry } from '../rpc/server/pairing/device-registry' import type { OrcaRuntimeService } from '../orca-runtime' import type { OrcaRuntimeRpcServer } from '../rpc/server/runtime-rpc' diff --git a/src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts b/src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts index c6332972e48..c526811a0ab 100644 --- a/src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts +++ b/src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts @@ -10,7 +10,7 @@ import { } from '../../../../shared/claude-agent-teams-tmux-compat' import { getAppEnvironment, hasAppEnvironment } from '../../../../shared/app-environment' import { getOrcaCliCommandNameForPlatform } from '../../../../shared/orca-cli-command-name' -import { getBundledLauncherPath } from '../../../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../../../cli/packaged-assets/bundled-cli-launcher-path' import { resolvePathEnvKey } from '../../../pty/environment/windows-path-segment-merge' export type ClaudeAgentTeamsLaunchPlan = { diff --git a/src/main/startup/browser-process-user-agent-ordering.test.ts b/src/main/startup/browser-process-user-agent-ordering.test.ts index 3abb64ebf82..5fde1f3358a 100644 --- a/src/main/startup/browser-process-user-agent-ordering.test.ts +++ b/src/main/startup/browser-process-user-agent-ordering.test.ts @@ -185,12 +185,12 @@ vi.mock('../claude-usage/store') vi.mock('../codex-usage/store') vi.mock('../opencode-usage/store') vi.mock('../browser/document-preview/doc-preview-protocol') -vi.mock('../crash-reporting/crashpad-capture') -vi.mock('../crash-reporting/crash-report-store') -vi.mock('../crash-reporting/crash-breadcrumb-store') -vi.mock('../crash-reporting/durable-crash-breadcrumb') -vi.mock('../crash-reporting/gpu-crash-diagnostics') -vi.mock('../crash-reporting/main-process-lifecycle-identity') +vi.mock('../crash-reporting/capture/crashpad-capture') +vi.mock('../crash-reporting/reports/crash-report-store') +vi.mock('../crash-reporting/breadcrumbs/crash-breadcrumb-store') +vi.mock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb') +vi.mock('../crash-reporting/capture/gpu-crash-diagnostics') +vi.mock('../crash-reporting/process-exits/main-process-lifecycle-identity') vi.mock('./ensure-virtual-display', () => ({ ensureVirtualDisplayForHeadlessServe: vi.fn(), hasUsableLinuxDisplay: () => true, diff --git a/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts b/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts index ad865245f40..32983147666 100644 --- a/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts +++ b/src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts @@ -31,7 +31,7 @@ import { DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, GpuCrashFallbackTracker -} from '../crash-reporting/gpu-crash-fallback-decision' +} from '../crash-reporting/recovery/gpu-crash-fallback-decision' import { readGpuFallbackMarker, writeGpuFallbackMarker, diff --git a/src/main/startup/gpu-lifecycle.ts b/src/main/startup/gpu-lifecycle.ts index 2bc119f1401..db00f19a618 100644 --- a/src/main/startup/gpu-lifecycle.ts +++ b/src/main/startup/gpu-lifecycle.ts @@ -11,12 +11,12 @@ import { import { handleGpuFallbackRecoveredLaunch, promptForGpuFallbackRecoveredLaunch -} from '../crash-reporting/gpu-fallback-recovered-launch' -import { promptForGpuFallbackRestart } from '../crash-reporting/gpu-fallback-restart-prompt' -import { engageGpuFallbackAfterCrashBurst } from '../crash-reporting/gpu-fallback-engagement' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' -import { GpuCrashDiagnosticsRecorder } from '../crash-reporting/gpu-crash-diagnostics' +} from '../crash-reporting/recovery/gpu-fallback-recovered-launch' +import { promptForGpuFallbackRestart } from '../crash-reporting/recovery/gpu-fallback-restart-prompt' +import { engageGpuFallbackAfterCrashBurst } from '../crash-reporting/recovery/gpu-fallback-engagement' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { GpuCrashDiagnosticsRecorder } from '../crash-reporting/capture/gpu-crash-diagnostics' import { isInstallDirAclRepairExhausted, isInstallDirAclRepairPending, diff --git a/src/main/startup/linux-dev-shm-policy.ts b/src/main/startup/linux-dev-shm-policy.ts index e8475153eb1..da3356395a7 100644 --- a/src/main/startup/linux-dev-shm-policy.ts +++ b/src/main/startup/linux-dev-shm-policy.ts @@ -1,6 +1,6 @@ import { statfsSync } from 'node:fs' import { app } from 'electron' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' const DEV_SHM_PATH = '/dev/shm' const DEV_SHM_OVERRIDE_ENV_VAR = 'ORCA_DEV_SHM' diff --git a/src/main/startup/linux-realtime-scheduling-guard.ts b/src/main/startup/linux-realtime-scheduling-guard.ts index e74c4763b8c..f21f480878d 100644 --- a/src/main/startup/linux-realtime-scheduling-guard.ts +++ b/src/main/startup/linux-realtime-scheduling-guard.ts @@ -1,6 +1,6 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { runProcess } from '@orca/process-host' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { allowsRealtimePriority, readZeroRtTimeLimit, diff --git a/src/main/startup/main-process-error-guards.test.ts b/src/main/startup/main-process-error-guards.test.ts index ba32996e935..cc198e46458 100644 --- a/src/main/startup/main-process-error-guards.test.ts +++ b/src/main/startup/main-process-error-guards.test.ts @@ -7,7 +7,7 @@ afterEach(() => { describe('main-process fatal error guards (issue #9441)', () => { it('never throws when the breadcrumb sink fails', async () => { vi.resetModules() - vi.doMock('../crash-reporting/durable-crash-breadcrumb', () => ({ + vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: vi.fn(() => { throw new Error('sink offline') }) @@ -26,7 +26,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('bounds and isolates console formatting for hostile rejection values', async () => { vi.resetModules() const record = vi.fn() - vi.doMock('../crash-reporting/durable-crash-breadcrumb', () => ({ + vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: record })) const { recordFatalMainProcessError } = await import('./main-process-error-guards') @@ -61,7 +61,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('caps oversized rejection diagnostics before recording or logging', async () => { vi.resetModules() const record = vi.fn() - vi.doMock('../crash-reporting/durable-crash-breadcrumb', () => ({ + vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: record })) const { recordFatalMainProcessError } = await import('./main-process-error-guards') @@ -82,7 +82,7 @@ describe('main-process fatal error guards (issue #9441)', () => { it('rethrows non-pipe errors outside the uncaughtException handler', async () => { vi.resetModules() - vi.doMock('../crash-reporting/durable-crash-breadcrumb', () => ({ + vi.doMock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: vi.fn() })) const { installUncaughtPipeErrorGuard } = await import('./main-process-error-guards') diff --git a/src/main/startup/main-process-error-guards.ts b/src/main/startup/main-process-error-guards.ts index f722afb1abe..1f65cc51d36 100644 --- a/src/main/startup/main-process-error-guards.ts +++ b/src/main/startup/main-process-error-guards.ts @@ -1,4 +1,4 @@ -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { removeBootstrapFatalExitGuard } from './bootstrap-fatal-exit-guard' type FatalMainProcessErrorKind = 'main_uncaught_exception' | 'main_unhandled_rejection' diff --git a/src/main/startup/main-process-i18n-menu.ts b/src/main/startup/main-process-i18n-menu.ts index c75bac814cf..a586fb49562 100644 --- a/src/main/startup/main-process-i18n-menu.ts +++ b/src/main/startup/main-process-i18n-menu.ts @@ -7,7 +7,7 @@ import { } from '../menu/register-app-menu' import { zoomDashboardPopoutIfFocused } from '../window/dashboard-popout-window' import { zoomWorkspaceSpaceWindowIfFocused } from '../window/workspace-space-window' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' import { mainProcessState as state } from './main-process-state' import { getAppMenuQuitHandlers, diff --git a/src/main/startup/main-process-observers.ts b/src/main/startup/main-process-observers.ts index 473327c15a0..b1e9fef30f0 100644 --- a/src/main/startup/main-process-observers.ts +++ b/src/main/startup/main-process-observers.ts @@ -13,7 +13,7 @@ import { installHookStatusSessionTabsRepublish } from '../agent-hooks/runtime/ho import { initTelemetry, track } from '../telemetry/client' import { setCodexTrustGrantTelemetry } from '../codex/trust/grants/codex-trust-grant-telemetry' import { initObservability } from '../observability/index' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { reportPreviousHangDetection } from '../hang-watchdog/previous-hang-detection' import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path' import { recoverPendingSkillTransactions } from '../skills/transaction-state/skill-transaction-startup-recovery' diff --git a/src/main/startup/main-process-preflight.ts b/src/main/startup/main-process-preflight.ts index 4257b987d56..7422887c61f 100644 --- a/src/main/startup/main-process-preflight.ts +++ b/src/main/startup/main-process-preflight.ts @@ -86,10 +86,10 @@ import { initOpenCodeUsagePath } from '../opencode-usage/store' import { initMuseUsagePath } from '../muse-usage/store' import { registerDocPreviewSchemePrivileges } from '../browser/document-preview/doc-preview-protocol' import { PRIVILEGED_CUSTOM_SCHEMES } from './privileged-custom-schemes' -import { startCrashpadCapture } from '../crash-reporting/crashpad-capture' -import { CrashReportStore } from '../crash-reporting/crash-report-store' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' -import { getMainProcessLifecycleIdentity } from '../crash-reporting/main-process-lifecycle-identity' +import { startCrashpadCapture } from '../crash-reporting/capture/crashpad-capture' +import { CrashReportStore } from '../crash-reporting/reports/crash-report-store' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { getMainProcessLifecycleIdentity } from '../crash-reporting/process-exits/main-process-lifecycle-identity' import { ensureVirtualDisplayForHeadlessServe, hasUsableLinuxDisplay, diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 267a7ac675e..6d94fca06e8 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -61,7 +61,7 @@ import { updateGpuAccelerationAboutPanel } from './gpu-lifecycle' import { logWslCliReconciliationResults, reconcileManagedWslCliRegistrations -} from '../cli/wsl-cli-registration-reconciliation' +} from '../cli/wsl/wsl-cli-registration-reconciliation' import { createWslCliReconciliationStartupBarrier } from './wsl-cli-reconciliation-startup-barrier' import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' diff --git a/src/main/startup/main-process-ready-runtime.ts b/src/main/startup/main-process-ready-runtime.ts index cb50c15cffe..10889bba800 100644 --- a/src/main/startup/main-process-ready-runtime.ts +++ b/src/main/startup/main-process-ready-runtime.ts @@ -10,11 +10,11 @@ import { browserManager } from '../browser/guest-lifecycle/manager/browser-manag import { configureBrowserClientPageAutomationRuntime } from '../browser/client-pages/execution/browser-client-page-automation-runtime' import { BrowserExpectedUrlMismatch } from '../../shared/browser/client-hosting/browser-expected-url' import { BrowserClientPageCommandError } from '../browser/client-pages/execution/browser-client-page-command-failure' -import { startPreGoneCrashSampling } from '../crash-reporting/process-gone-diagnostics' +import { startPreGoneCrashSampling } from '../crash-reporting/process-exits/process-gone-diagnostics' import { refuseRealtimeSchedulingUnderZeroRtTime } from './linux-realtime-scheduling-guard' import { recordProcessGoneCrash } from './main-window-lifecycle-flags' import { handleGpuChildCrash } from './gpu-lifecycle' -import { isGpuFallbackCrashCandidate } from '../crash-reporting/gpu-crash-fallback-decision' +import { isGpuFallbackCrashCandidate } from '../crash-reporting/recovery/gpu-crash-fallback-decision' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' diff --git a/src/main/startup/main-process-runtime-launch.ts b/src/main/startup/main-process-runtime-launch.ts index ad2061004d6..d6443259642 100644 --- a/src/main/startup/main-process-runtime-launch.ts +++ b/src/main/startup/main-process-runtime-launch.ts @@ -38,7 +38,7 @@ import { showRuntimeRpcStartupFailureDialog } from '../runtime/rpc/server/runtime-rpc-startup-failure' import { registerCliForHeadlessServe } from './serve-cli-registration' -import { startAppImageCopyPreExtraction } from '../cli/appimage-copy-pre-extraction' +import { startAppImageCopyPreExtraction } from '../cli/appimage/appimage-copy-pre-extraction' import { scheduleAllPendingHistoryTreeRemovals } from '../pty/history/terminal-history-deletion' import { triggerStartupNotificationRegistration } from '../ipc/startup-notification-registration' import { startDesktopPushService } from './main-process-push-startup' diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 5ab0fa0048f..3bb76f1a7da 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -59,7 +59,7 @@ import { recordObservedAgentStatusPaneIdentity } from '../runtime/terminal/identity/agent-status-observed-pane-identity' import { startAgentStateRulesLiveUpdates } from '../runtime/agent-state-rules/agent-state-rules-live-update' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { getRuntimeEnvironmentRegistryRoot } from '../ipc/runtime-environments/runtime-environment-registry-root' import { openOffscreenBrowserPageLink } from '../runtime/browser/commands/offscreen-browser-page-link' diff --git a/src/main/startup/main-process-state.ts b/src/main/startup/main-process-state.ts index 82583be7f9f..dc665ad1b1b 100644 --- a/src/main/startup/main-process-state.ts +++ b/src/main/startup/main-process-state.ts @@ -17,7 +17,7 @@ import type { DesktopRelayServiceInstaller } from '../runtime/mobile-cloud-relay import type { DesktopPushService } from '../runtime/push/desktop-push-service' import type { StarNagService } from '../star-nag/service' import type { AgentAwakeService } from '../power/agent-awake-service' -import type { CrashReportStore } from '../crash-reporting/crash-report-store' +import type { CrashReportStore } from '../crash-reporting/reports/crash-report-store' import type { AutomationService } from '../automations/service' import type { PluginService } from '../plugins/plugin-service' import type { PluginKillListService } from '../plugins/catalog/plugin-kill-list-service' @@ -45,8 +45,8 @@ import { DEFAULT_GPU_CRASH_FALLBACK_THRESHOLD, DEFAULT_GPU_CRASH_FALLBACK_WINDOW_MS, GpuCrashFallbackTracker -} from '../crash-reporting/gpu-crash-fallback-decision' -import type { GpuCrashDiagnosticsRecorder } from '../crash-reporting/gpu-crash-diagnostics' +} from '../crash-reporting/recovery/gpu-crash-fallback-decision' +import type { GpuCrashDiagnosticsRecorder } from '../crash-reporting/capture/gpu-crash-diagnostics' import { createWebContentsTimedFlag } from './web-contents-timed-flag' import type { ProfileStateStorageClassification } from '../persistence/profile-state/database/profile-state-storage-classification' import type { ProfileStateRuntimeAdmission } from '../persistence/profile-state/access/profile-state-access' diff --git a/src/main/startup/main-window-actions.ts b/src/main/startup/main-window-actions.ts index 16a5bf71a73..e6ad7d3caf8 100644 --- a/src/main/startup/main-window-actions.ts +++ b/src/main/startup/main-window-actions.ts @@ -12,8 +12,8 @@ import { isNativeBrowserPopupWindow } from '../browser/guest-lifecycle/popups/pr import type { UpdateCheckOptions } from '../../shared/update-status-types' import type { AppMenuQuitHandlers } from '../menu/app-menu-quit-item' import type { createWebContentsTimedFlag } from './web-contents-timed-flag' -import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordCrashBreadcrumb } from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { checkForUpdatesFromMenu, isQuittingForUpdate } from '../updater/updater-service' import { createSystemTray, diff --git a/src/main/startup/main-window-controller.ts b/src/main/startup/main-window-controller.ts index 13789f9f34b..94643295e52 100644 --- a/src/main/startup/main-window-controller.ts +++ b/src/main/startup/main-window-controller.ts @@ -3,9 +3,9 @@ import { createMainWindow, loadMainWindow } from '../window/createMainWindow' import { recordCrashBreadcrumb, recordCoalescedCrashBreadcrumb -} from '../crash-reporting/crash-breadcrumb-store' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' -import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-gone-classification' +} from '../crash-reporting/breadcrumbs/crash-breadcrumb-store' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' +import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-exits/process-gone-classification' import { resolveConsent } from '../telemetry/consent' import { trackAppOpenedOnce } from '../telemetry/client' import { ensureWindowsUserDataAclGrant } from './windows-user-data-acl' diff --git a/src/main/startup/main-window-lifecycle-flags.ts b/src/main/startup/main-window-lifecycle-flags.ts index 7e565f5c8b3..d469966e990 100644 --- a/src/main/startup/main-window-lifecycle-flags.ts +++ b/src/main/startup/main-window-lifecycle-flags.ts @@ -1,6 +1,6 @@ -import { resolveExpectedTeardownScope } from '../crash-reporting/expected-teardown-state' -import type { ExpectedTeardownScope } from '../crash-reporting/process-gone-classification' -import { recordProcessGoneCrash as recordProcessGoneCrashEvent } from '../crash-reporting/process-gone-recorder' +import { resolveExpectedTeardownScope } from '../crash-reporting/process-exits/expected-teardown-state' +import type { ExpectedTeardownScope } from '../crash-reporting/process-exits/process-gone-classification' +import { recordProcessGoneCrash as recordProcessGoneCrashEvent } from '../crash-reporting/process-exits/process-gone-recorder' import { isQuittingForUpdate } from '../updater/updater-service' import { mainProcessState as state } from './main-process-state' diff --git a/src/main/startup/quit/app-relaunch.test.ts b/src/main/startup/quit/app-relaunch.test.ts index a3dc656c892..3299a686550 100644 --- a/src/main/startup/quit/app-relaunch.test.ts +++ b/src/main/startup/quit/app-relaunch.test.ts @@ -15,7 +15,7 @@ vi.mock('../../windows/windows-administrator-status', () => ({ vi.mock('../../daemon/providers/lifecycle/daemon-provider-restart', () => ({ restartDaemon: vi.fn(async () => {}) })) -vi.mock('../../crash-reporting/durable-crash-breadcrumb', () => ({ +vi.mock('../../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock })) diff --git a/src/main/startup/quit/app-relaunch.ts b/src/main/startup/quit/app-relaunch.ts index 35b3ffee9a2..36a56856e6f 100644 --- a/src/main/startup/quit/app-relaunch.ts +++ b/src/main/startup/quit/app-relaunch.ts @@ -1,6 +1,6 @@ import { app } from 'electron' import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { runWithLaunchPath } from '../hydrate-shell-path' import { getWindowsAdministratorRelaunchOptions } from '../../windows/windows-administrator-restart' diff --git a/src/main/startup/serve-cli-registration.ts b/src/main/startup/serve-cli-registration.ts index 5af5fd39b54..e4925df94ba 100644 --- a/src/main/startup/serve-cli-registration.ts +++ b/src/main/startup/serve-cli-registration.ts @@ -1,8 +1,8 @@ import { app } from 'electron' import { resolveAppImageRuntimeIdentity } from '../updater/linux-package/appimage-runtime-identity' -import { prepareAppImageCopyForServe } from '../cli/appimage-serve-preparation' +import { prepareAppImageCopyForServe } from '../cli/appimage/appimage-serve-preparation' import { CliInstaller } from '../cli/cli-installer' -import { installLinuxBareOrcaDispatcher } from '../cli/linux-bare-orca-dispatcher' +import { installLinuxBareOrcaDispatcher } from '../cli/launchers/linux-bare-orca-dispatcher' /** Headless serve has no renderer to run the normal cli:install flow, so it registers here. */ export async function registerCliForHeadlessServe(): Promise { diff --git a/src/main/startup/windows-install-dir-acl-probe.ts b/src/main/startup/windows-install-dir-acl-probe.ts index 3f6e635b059..bf1ea6b91de 100644 --- a/src/main/startup/windows-install-dir-acl-probe.ts +++ b/src/main/startup/windows-install-dir-acl-probe.ts @@ -4,7 +4,7 @@ import { sanitizeCrashReportString, type CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { loadWindowsSecurity, type WindowsDacl } from '../../shared/windows-security-addon' import { ACCESS_ALLOWED_ACE_TYPE, diff --git a/src/main/startup/windows-install-dir-package-acl-repair.ts b/src/main/startup/windows-install-dir-package-acl-repair.ts index 6dc507a84ed..970f4923327 100644 --- a/src/main/startup/windows-install-dir-package-acl-repair.ts +++ b/src/main/startup/windows-install-dir-package-acl-repair.ts @@ -4,7 +4,7 @@ import { sanitizeCrashReportString, type CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { installDirPackageGrants, RESTRICTED_APP_PACKAGES_SID, diff --git a/src/main/updater/updater-events.test.ts b/src/main/updater/updater-events.test.ts index 6338b83e7fb..267b7bb98dc 100644 --- a/src/main/updater/updater-events.test.ts +++ b/src/main/updater/updater-events.test.ts @@ -36,7 +36,7 @@ vi.mock('./linux-package/linux-update-package-type', () => ({ isExternallyManagedLinuxInstall: isExternallyManagedLinuxInstallMock })) -vi.mock('../cli/appimage-copy-pre-extraction', () => ({ +vi.mock('../cli/appimage/appimage-copy-pre-extraction', () => ({ preExtractDownloadedAppImageUpdate: preExtractUpdateMock })) vi.mock('./releases/updater-changelog', () => ({ fetchChangelog: vi.fn().mockResolvedValue(null) })) diff --git a/src/main/updater/updater-events.ts b/src/main/updater/updater-events.ts index 652f6238f5e..9ee180c0801 100644 --- a/src/main/updater/updater-events.ts +++ b/src/main/updater/updater-events.ts @@ -16,7 +16,7 @@ import { } from './linux-package/linux-package-downloaded-status' import { isExternallyManagedLinuxInstall } from './linux-package/linux-update-package-type' import * as linuxPackageRecovery from './linux-package/linux-package-update-recovery' -import { preExtractDownloadedAppImageUpdate } from '../cli/appimage-copy-pre-extraction' +import { preExtractDownloadedAppImageUpdate } from '../cli/appimage/appimage-copy-pre-extraction' const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 const AUTO_UPDATE_RETRY_INTERVAL_MS = 60 * 60 * 1000 diff --git a/src/main/updater/updater-lifecycle-diagnostics.ts b/src/main/updater/updater-lifecycle-diagnostics.ts index fe4d60f12dc..4bb340c383d 100644 --- a/src/main/updater/updater-lifecycle-diagnostics.ts +++ b/src/main/updater/updater-lifecycle-diagnostics.ts @@ -1,5 +1,5 @@ import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' export function recordUpdaterLifecycle( event: string, diff --git a/src/main/window/createMainWindow-close-confirmation.test.ts b/src/main/window/createMainWindow-close-confirmation.test.ts index 648e8612ab4..ad620060a01 100644 --- a/src/main/window/createMainWindow-close-confirmation.test.ts +++ b/src/main/window/createMainWindow-close-confirmation.test.ts @@ -32,7 +32,7 @@ vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', import { createMainWindow, WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS } from './createMainWindow' import { ipcMain } from 'electron' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' +import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' import { attachClientPageRendererMock, browserWindowMock, diff --git a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts b/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts index 591077f57f6..7ee68f4178a 100644 --- a/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts +++ b/src/main/window/createMainWindow-low-commit-oom-recovery.test.ts @@ -21,13 +21,13 @@ vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', }) import { createMainWindow } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' +import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' import { resetPreGoneSystemMemorySamplingForTest, samplePreGoneSystemMemory -} from '../crash-reporting/pre-gone-host-memory' -import { setSystemMemoryInfoReaderForTest } from '../crash-reporting/system-memory-details' -import { setSwapVolumeFreeSpaceReaderForTest } from '../crash-reporting/swap-volume-free-space' +} from '../crash-reporting/memory/pre-gone-host-memory' +import { setSystemMemoryInfoReaderForTest } from '../crash-reporting/memory/system-memory-details' +import { setSwapVolumeFreeSpaceReaderForTest } from '../crash-reporting/memory/swap-volume-free-space' import { createRendererRecoveryWindowHarness, resetMainWindowMocks, diff --git a/src/main/window/createMainWindow-markdown-editor-focus.test.ts b/src/main/window/createMainWindow-markdown-editor-focus.test.ts index 266da4c502e..a49f4e214b9 100644 --- a/src/main/window/createMainWindow-markdown-editor-focus.test.ts +++ b/src/main/window/createMainWindow-markdown-editor-focus.test.ts @@ -15,7 +15,7 @@ vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => import { createMainWindow } from './createMainWindow' import { ipcMain } from 'electron' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' +import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' import { browserWindowMock, buildFromTemplateMock, diff --git a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts b/src/main/window/createMainWindow-renderer-crash-recovery.test.ts index f7af4315088..abf52e7510f 100644 --- a/src/main/window/createMainWindow-renderer-crash-recovery.test.ts +++ b/src/main/window/createMainWindow-renderer-crash-recovery.test.ts @@ -22,11 +22,11 @@ vi.mock('../browser/client-pages/renderer/browser-client-page-renderer-runtime', import { createMainWindow } from './createMainWindow' import { ipcMain } from 'electron' -import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-gone-classification' +import { shouldRecoverRendererAfterProcessGone } from '../crash-reporting/process-exits/process-gone-classification' import { resetExpectedTeardownStateForTest, resolveExpectedTeardownScope -} from '../crash-reporting/expected-teardown-state' +} from '../crash-reporting/process-exits/expected-teardown-state' import { attachClientPageRendererMock, browserWindowMock, diff --git a/src/main/window/createMainWindow-user-quit-close.test.ts b/src/main/window/createMainWindow-user-quit-close.test.ts index aae0a67723d..8726de70d0c 100644 --- a/src/main/window/createMainWindow-user-quit-close.test.ts +++ b/src/main/window/createMainWindow-user-quit-close.test.ts @@ -15,7 +15,7 @@ vi.mock('../browser/guest-lifecycle/manager/browser-manager', async () => import { ipcMain } from 'electron' import { createMainWindow, WINDOW_QUIT_RENDERER_ACK_TIMEOUT_MS } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' +import { resetExpectedTeardownStateForTest } from '../crash-reporting/process-exits/expected-teardown-state' import { browserWindowMock, resetMainWindowMocks } from './createMainWindow-test-harness' import { markUserQuitWindowClose } from './user-quit-window-close' diff --git a/src/main/window/createMainWindow.ts b/src/main/window/createMainWindow.ts index 72101f46410..b3bbef5bd24 100644 --- a/src/main/window/createMainWindow.ts +++ b/src/main/window/createMainWindow.ts @@ -8,8 +8,8 @@ import { formatBrowserClientHostIdArgument } from '../../shared/browser/client-h import { formatWindowMaterialArgument, resolveWindowMaterial } from '../../shared/window-material' import { windowMaterialOptions } from './window-material-options' import { rememberWindowMaterial } from './window-material-suppression' -import { markSystemSessionEnding } from '../crash-reporting/expected-teardown-state' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { markSystemSessionEnding } from '../crash-reporting/process-exits/expected-teardown-state' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { clearTrustedUIRendererWebContentsId, setTrustedUIRendererWebContentsId } from '../ipc/ui' import { flushUnsavedCloudSessions } from '../orca-profiles/cloud-session/profile-cloud-session-owner' import type { Store } from '../persistence/loading-store/store' diff --git a/src/main/window/main-window-contracts.ts b/src/main/window/main-window-contracts.ts index bb3a1d88f1a..91937c3b16b 100644 --- a/src/main/window/main-window-contracts.ts +++ b/src/main/window/main-window-contracts.ts @@ -1,5 +1,5 @@ import type { KeybindingOverrides } from '../../shared/keybindings' -import type { LowCommitOomVerdict } from '../crash-reporting/low-commit-oom-recovery-gate' +import type { LowCommitOomVerdict } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' import type { RecoveryExhaustionCause, RecoveryReloadMilestone, diff --git a/src/main/window/main-window-focus-lifecycle.ts b/src/main/window/main-window-focus-lifecycle.ts index e1636afca5d..ba9c1380998 100644 --- a/src/main/window/main-window-focus-lifecycle.ts +++ b/src/main/window/main-window-focus-lifecycle.ts @@ -9,8 +9,8 @@ import { DEFAULT_RENDERER_RECOVERY_MAX_RECOVERIES, DEFAULT_RENDERER_RECOVERY_WINDOW_MS, RendererRecoveryCircuitBreaker -} from '../crash-reporting/renderer-recovery-circuit-breaker' -import { createLowCommitOomRecoveryGate } from '../crash-reporting/low-commit-oom-recovery-gate' +} from '../crash-reporting/recovery/renderer-recovery-circuit-breaker' +import { createLowCommitOomRecoveryGate } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' import { buildEditableContextMenuTemplate, matchingRichMarkdownContextMenuTableTarget, diff --git a/src/main/window/renderer-launch-failure-probe.test.ts b/src/main/window/renderer-launch-failure-probe.test.ts index 877e177bd12..f762eac4d86 100644 --- a/src/main/window/renderer-launch-failure-probe.test.ts +++ b/src/main/window/renderer-launch-failure-probe.test.ts @@ -5,7 +5,7 @@ const { runProcessMock, recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({ recordDurableCrashBreadcrumbMock: vi.fn() })) vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('../crash-reporting/durable-crash-breadcrumb', () => ({ +vi.mock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordDurableCrashBreadcrumb: recordDurableCrashBreadcrumbMock })) diff --git a/src/main/window/renderer-launch-failure-probe.ts b/src/main/window/renderer-launch-failure-probe.ts index 49a052e5bfe..9127b53da17 100644 --- a/src/main/window/renderer-launch-failure-probe.ts +++ b/src/main/window/renderer-launch-failure-probe.ts @@ -1,5 +1,5 @@ import { runProcess } from '@orca/process-host' -import { recordDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { errnoCodeOrUnknown } from '../../shared/errno-code' /** 'ok' when a throwaway child could start, the spawn errno (EAGAIN = per-user process limit), or 'skipped' on Windows. */ diff --git a/src/main/window/renderer-liveness-at-death.test.ts b/src/main/window/renderer-liveness-at-death.test.ts index f1e2e584be6..58d2ed252a2 100644 --- a/src/main/window/renderer-liveness-at-death.test.ts +++ b/src/main/window/renderer-liveness-at-death.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import { beforeEach, describe, expect, it, vi } from 'vitest' const recordCoalescedDurableCrashBreadcrumb = vi.fn() -vi.mock('../crash-reporting/durable-crash-breadcrumb', () => ({ +vi.mock('../crash-reporting/breadcrumbs/durable-crash-breadcrumb', () => ({ recordCoalescedDurableCrashBreadcrumb: (...args: unknown[]) => recordCoalescedDurableCrashBreadcrumb(...args) })) diff --git a/src/main/window/renderer-liveness-at-death.ts b/src/main/window/renderer-liveness-at-death.ts index 564bcc2ff58..cd2bf0c9e73 100644 --- a/src/main/window/renderer-liveness-at-death.ts +++ b/src/main/window/renderer-liveness-at-death.ts @@ -1,5 +1,5 @@ import type { BrowserWindow } from 'electron' -import { recordCoalescedDurableCrashBreadcrumb } from '../crash-reporting/durable-crash-breadcrumb' +import { recordCoalescedDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' /** Windows killed/exit1 cannot identify Task Manager, EDR or Orca as the cause. Retain prior hang/load state to distinguish users terminating a frozen app from unexplained external kills. */ export type RendererLivenessAtDeath = { diff --git a/src/main/window/renderer-recovery-reload-watchdog.ts b/src/main/window/renderer-recovery-reload-watchdog.ts index 7b1f92f135c..e86d18fae6d 100644 --- a/src/main/window/renderer-recovery-reload-watchdog.ts +++ b/src/main/window/renderer-recovery-reload-watchdog.ts @@ -1,7 +1,7 @@ -import { app } from 'electron' -import type { BrowserWindow } from 'electron' -import { isSystemSessionEnding } from '../crash-reporting/expected-teardown-state' -import type { LowCommitOomVerdict } from '../crash-reporting/low-commit-oom-recovery-gate' +import { app, type BrowserWindow } from 'electron' + +import { isSystemSessionEnding } from '../crash-reporting/process-exits/expected-teardown-state' +import type { LowCommitOomVerdict } from '../crash-reporting/recovery/low-commit-oom-recovery-gate' import type { CreateMainWindowOptions, MainWindowLoadObserver } from './main-window-contracts' import { mainWindowLoadErrorCode } from './main-window-load-error-code' diff --git a/src/main/windows/windows-administrator-restart.ts b/src/main/windows/windows-administrator-restart.ts index 9ed2b689793..4c1d9d75763 100644 --- a/src/main/windows/windows-administrator-restart.ts +++ b/src/main/windows/windows-administrator-restart.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { win32 } from 'node:path' import { app } from 'electron' import { quoteWindowsArgument } from '@orca/process-host/windows-command-line' -import { getBundledLauncherPath } from '../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../cli/packaged-assets/bundled-cli-launcher-path' import { getWindowsAdministratorStatus } from './windows-administrator-status' const RESTART_LOCAL_TERMINALS_ARG = '--orca-restart-local-terminals-as-administrator' diff --git a/src/main/windows/windows-administrator-status.ts b/src/main/windows/windows-administrator-status.ts index bd9eeb1b6c5..ba9a01fc318 100644 --- a/src/main/windows/windows-administrator-status.ts +++ b/src/main/windows/windows-administrator-status.ts @@ -1,7 +1,7 @@ import { join } from 'node:path' import { runProcess } from '@orca/process-host' import { getAppEnvironment } from '../../shared/app-environment' -import { getBundledLauncherPath } from '../cli/bundled-cli-launcher-path' +import { getBundledLauncherPath } from '../cli/packaged-assets/bundled-cli-launcher-path' let status: Promise | undefined diff --git a/src/main/windows/windows-pty-job.test.ts b/src/main/windows/windows-pty-job.test.ts index a6149250db2..61a23f420c7 100644 --- a/src/main/windows/windows-pty-job.test.ts +++ b/src/main/windows/windows-pty-job.test.ts @@ -4,7 +4,7 @@ import type { IPty } from 'node-pty' const { recordSelfInitiatedTreeKillMock } = vi.hoisted(() => ({ recordSelfInitiatedTreeKillMock: vi.fn() })) -vi.mock('../crash-reporting/self-initiated-tree-kill-log', () => ({ +vi.mock('../crash-reporting/process-exits/self-initiated-tree-kill-log', () => ({ recordSelfInitiatedTreeKill: recordSelfInitiatedTreeKillMock })) diff --git a/src/main/windows/windows-pty-job.ts b/src/main/windows/windows-pty-job.ts index ae1e382e9fd..3f871b88e1a 100644 --- a/src/main/windows/windows-pty-job.ts +++ b/src/main/windows/windows-pty-job.ts @@ -1,6 +1,6 @@ import type { IPty } from 'node-pty' import { createRequire } from 'node:module' -import { recordSelfInitiatedTreeKill } from '../crash-reporting/self-initiated-tree-kill-log' +import { recordSelfInitiatedTreeKill } from '../crash-reporting/process-exits/self-initiated-tree-kill-log' /** Kernel job handles own ConPTY descendants across PID reuse/reparenting (#9045/#10475/#10087). Per-PTY jobs make explicit teardown exact without kill-on-close, preserving background children on clean shell exit. */ diff --git a/src/main/workspace-hooks/hook-orca-cli-env.ts b/src/main/workspace-hooks/hook-orca-cli-env.ts index 503f1c84e36..35e7b9955e4 100644 --- a/src/main/workspace-hooks/hook-orca-cli-env.ts +++ b/src/main/workspace-hooks/hook-orca-cli-env.ts @@ -1,7 +1,7 @@ import { getAppEnvironment, hasAppEnvironment } from '../../shared/app-environment' import { toLinuxPath } from '../../shared/wsl-paths' -import { prependOrcaCliDirToChildPath } from '../cli/orca-cli-child-path' -import { getManagedWslCliDir, getWslCliCommandName } from '../cli/wsl-managed-cli' +import { prependOrcaCliDirToChildPath } from '../cli/launchers/orca-cli-child-path' +import { getManagedWslCliDir, getWslCliCommandName } from '../cli/wsl/wsl-managed-cli' import { WSL_MANAGED_CLI_PATH_RESTORE } from '../wsl/execution/wsl-managed-cli-path-restore' // A hook isn't a pane: an Orca started from an Orca terminal must not lend that pane's identity. diff --git a/src/main/workspaces/removal/worktree-removal-acceptance-queue.ts b/src/main/workspaces/removal/worktree-removal-acceptance-queue.ts index b8be7718f9f..e602a577461 100644 --- a/src/main/workspaces/removal/worktree-removal-acceptance-queue.ts +++ b/src/main/workspaces/removal/worktree-removal-acceptance-queue.ts @@ -1,4 +1,4 @@ -import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' const acceptanceQueueByRepo = new Map>() diff --git a/src/main/wsl/discovery/wsl-distro-holder.ts b/src/main/wsl/discovery/wsl-distro-holder.ts index 6e5b466664d..ea5fdd2b838 100644 --- a/src/main/wsl/discovery/wsl-distro-holder.ts +++ b/src/main/wsl/discovery/wsl-distro-holder.ts @@ -1,4 +1,4 @@ -import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' import { spawnDetachedWithoutInheritance } from '@orca/process-host/isolated-detached-spawn' import { queryWindowsProcess } from '../../daemon/endpoint/identity/daemon-process-inspection' import { diff --git a/src/main/wsl/orcad/wsl-orcad-host-account-push.ts b/src/main/wsl/orcad/wsl-orcad-host-account-push.ts index c86572a7486..1ab7a92a980 100644 --- a/src/main/wsl/orcad/wsl-orcad-host-account-push.ts +++ b/src/main/wsl/orcad/wsl-orcad-host-account-push.ts @@ -10,7 +10,7 @@ import { type WslOrcadAccountEnvDependencies } from './wsl-orcad-account-env' import type { WslOrcadHostCapabilityVerdict } from './wsl-orcad-host-environments' -import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import { runKeyedSerializedOperation } from '../../../shared/concurrency/keyed-serialized-operations' export type WslOrcadHostAccountPush = { environmentId: string diff --git a/src/main/cli/keyed-promise-queue.test.ts b/src/shared/concurrency/keyed-serialized-operations.test.ts similarity index 93% rename from src/main/cli/keyed-promise-queue.test.ts rename to src/shared/concurrency/keyed-serialized-operations.test.ts index 1a74574382c..31abc454cfc 100644 --- a/src/main/cli/keyed-promise-queue.test.ts +++ b/src/shared/concurrency/keyed-serialized-operations.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest' -import { getKeyedSerializedQueueTail, runKeyedSerializedOperation } from './keyed-promise-queue' +import { + getKeyedSerializedQueueTail, + runKeyedSerializedOperation +} from './keyed-serialized-operations' describe('runKeyedSerializedOperation', () => { it('propagates rejections to the caller but never through the stored tail', async () => { diff --git a/src/main/cli/keyed-promise-queue.ts b/src/shared/concurrency/keyed-serialized-operations.ts similarity index 100% rename from src/main/cli/keyed-promise-queue.ts rename to src/shared/concurrency/keyed-serialized-operations.ts diff --git a/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts b/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts index eb9d6e2fa30..8163f207ddc 100644 --- a/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts +++ b/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts @@ -59,7 +59,7 @@ vi.mock('../../src/main/telemetry/client', () => vi.mock('../../src/main/telemetry/classify-error', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock()) ) -vi.mock('../../src/main/cli/linux-terminal-orca-cli-shim', () => +vi.mock('../../src/main/cli/launchers/linux-terminal-orca-cli-shim', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock()) ) vi.mock('../../src/main/memory/pty-registry', () =>