From 918bbcbe6e87c009ff1bfcccebdcef0bf932641c Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 12 Nov 2026 13:06:44 -0800 Subject: [PATCH 01/44] test: remove manifest inventories and one profile policy sample (#41648) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - .../plugin-execution-profile.test.ts | 26 --------- .../plugins/manifest/plugin-manifest.test.ts | 55 +------------------ 3 files changed, 1 insertion(+), 81 deletions(-) delete mode 100644 src/shared/plugins/contributions/plugin-execution-profile.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2892db33f7b..d6dc8e43bfd 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6603,7 +6603,6 @@ "src/shared/plugins/contributions/plugin-command-replaces.test.ts": 230, "src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227, "src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238, - "src/shared/plugins/contributions/plugin-execution-profile.test.ts": 164, "src/shared/plugins/contributions/plugin-panel-contribution.test.ts": 240, "src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts": 232, "src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147, diff --git a/src/shared/plugins/contributions/plugin-execution-profile.test.ts b/src/shared/plugins/contributions/plugin-execution-profile.test.ts deleted file mode 100644 index 8a0ea19fc27..00000000000 --- a/src/shared/plugins/contributions/plugin-execution-profile.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { PLUGIN_MANIFEST_V2_SINCE } from '../manifest/plugin-schema-field-docs' -import { parsePluginManifest } from '../manifest/plugin-manifest' - -function manifestInput(): Record { - return { - manifestVersion: 2, - execution: 'data', - id: 'demo', - publisher: 'samples', - name: 'Demo', - version: '1.2.0', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` } - } -} - -describe('execution profiles', () => { - it('rejects v2 contributions beyond the declared profile', () => { - const parsed = parsePluginManifest({ - ...manifestInput(), - execution: 'data', - contributes: { commands: [{ id: 'open', title: 'Open', action: 'view.tasks' }] } - }) - expect(parsed).toMatchObject({ ok: false, error: expect.stringContaining('execution') }) - }) -}) diff --git a/src/shared/plugins/manifest/plugin-manifest.test.ts b/src/shared/plugins/manifest/plugin-manifest.test.ts index 31ca4c139ca..ed6e13b73c9 100644 --- a/src/shared/plugins/manifest/plugin-manifest.test.ts +++ b/src/shared/plugins/manifest/plugin-manifest.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' -import { PLUGIN_MANIFEST_V2_SINCE } from './plugin-schema-field-docs' -import { PLUGIN_COMMAND_LIMIT, parsePluginManifest, pluginManifestSchema } from './plugin-manifest' +import { parsePluginManifest } from './plugin-manifest' function manifest(overrides: Record = {}): Record { return { @@ -54,56 +53,4 @@ describe('pluginManifestSchema boundaries', () => { } }) }) - - it('refuses format 1 names in format 2', () => { - const result = parsePluginManifest({ - ...manifest({ capabilities: [{ kind: 'storage' }] }), - manifestVersion: 2, - execution: 'data', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` } - }) - - expect(result.ok).toBe(false) - }) - - it('rejects duplicate contribution ids', () => { - const parsed = pluginManifestSchema.safeParse( - manifest({ - main: 'main.mjs', - contributes: { - panels: [ - { id: 'dashboard', title: 'One', entry: 'one.html' }, - { id: 'dashboard', title: 'Two', entry: 'two.html' } - ], - commands: [ - { id: 'run', title: 'One' }, - { id: 'run', title: 'Two' } - ], - events: [] - } - }) - ) - - expect(parsed.success).toBe(false) - if (!parsed.success) { - expect(parsed.error.issues.map((issue) => issue.message)).toEqual( - expect.arrayContaining(['duplicate panels id: dashboard', 'duplicate commands id: run']) - ) - } - }) - - it('caps contribution arrays before they reach renderer or worker registries', () => { - const commands = Array.from({ length: PLUGIN_COMMAND_LIMIT + 1 }, (_, index) => ({ - id: `command-${index}`, - title: `Command ${index}` - })) - expect( - parsePluginManifest( - manifest({ - main: 'main.mjs', - contributes: { panels: [], commands, events: [] } - }) - ).ok - ).toBe(false) - }) }) From 267602a89502792f6b75dae5f4942627977d910b Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:17:33 -0800 Subject: [PATCH 02/44] test(artifacts): restore publishing permission regression tests (#41364) * test(artifacts): restore publishing permission regression tests #41012 and #41007 removed the tests that guard #40948 (new profiles allow artifact publishing, profiles saved before the setting stay off, web clients fail closed until the host grant is mirrored) and #40982 (moving a project between profiles must not grant publishing to an older profile). Restore them against current paths. Each fails when the code it guards is reverted. * test(artifacts): keep only guards that fail when their fix is reverted Drop the explicit opt-out and explicit-choice transfer cases: saved values already win in both paths, so reverting #40948 or #40982 does not fail them. Name the web test for what it checks: the local fallback, not host mirroring. --- .../profile-project-transfer.test.ts | 37 +++++++++++++ ...rsistence-artifact-sharing-default.test.ts | 54 +++++++++++++++++++ .../web-artifact-sharing-setting.test.ts | 18 +++++++ 3 files changed, 109 insertions(+) create mode 100644 src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts create mode 100644 src/renderer/src/web/preload-api/web-artifact-sharing-setting.test.ts diff --git a/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts index 823124fa78d..9c90b6a65cc 100644 --- a/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts @@ -66,6 +66,15 @@ async function loadTransferModule() { return import('./profile-project-transfer') } +function transferMove( + transfer: Awaited>['transferOrcaProfileProject'] +) { + return transfer( + { sourceProfileId: 'personal', targetProfileId: 'work', repoId: 'repo-1', mode: 'move' }, + testState.dir + ) +} + function profile(id: string, name: string): OrcaProfileIndex['profiles'][number] { return { id, @@ -135,6 +144,22 @@ function makeState(overrides: Partial = {}): PersistedState { } } +// A profile saved before artifactSharingEnabled existed carries no defaults for it. +function writeOlderProfileStateDatabase( + profileId: string, + settings: Record, + repos: Repo[] = [] +): void { + const databasePath = profileDatabasePath(profileId) + mkdirSync(join(databasePath, '..'), { recursive: true }) + const opened = openProfileStateDatabase(databasePath, profileId) + try { + importProfileStateJson(opened.db, JSON.stringify({ settings, repos })) + } finally { + opened.db.close() + } +} + describe('profile project transfer', () => { beforeEach(() => { testState.dir = mkdtempSync(join(tmpdir(), 'orca-profile-transfer-')) @@ -200,4 +225,16 @@ describe('profile project transfer', () => { expect(readProfileStateDatabase('personal').repos).toHaveLength(1) expect(existsSync(intentPath)).toBe(true) }) + + it('moves a project without granting publishing permission to either older profile', async () => { + writeOlderProfileStateDatabase('personal', {}, [makeRepo()]) + writeOlderProfileStateDatabase('work', {}) + const { transferOrcaProfileProject } = await loadTransferModule() + + expect(transferMove(transferOrcaProfileProject)).toMatchObject({ status: 'transferred' }) + expect(readProfileStateDatabase('personal').settings).not.toHaveProperty( + 'artifactSharingEnabled' + ) + expect(readProfileStateDatabase('work').settings).not.toHaveProperty('artifactSharingEnabled') + }) }) diff --git a/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts b/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts new file mode 100644 index 00000000000..116f79f70b8 --- /dev/null +++ b/src/main/persistence/applying-settings/persistence-artifact-sharing-default.test.ts @@ -0,0 +1,54 @@ +import { closeTestStores, testState, createStore, writeDataFile } from '../persistence-test-harness' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { rmSync, mkdtempSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), + decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) + } +})) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: () => ({ nth_repo_added: 2 }) +})) + +function writeSettings(settings: Record): void { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) +} + +describe('artifact sharing default', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) + }) + + afterEach(async () => { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) + }) + + it('allows publishing on a new profile and keeps it after a reload', async () => { + const store = createStore() + expect(store.getSettings().artifactSharingEnabled).toBe(true) + store.flush() + await closeTestStores() + expect(createStore().getSettings().artifactSharingEnabled).toBe(true) + }) + + it('keeps publishing off for a stored profile saved before the setting existed', () => { + writeSettings({ showArtifactsButton: false }) + expect(createStore().getSettings().artifactSharingEnabled).toBe(false) + }) +}) diff --git a/src/renderer/src/web/preload-api/web-artifact-sharing-setting.test.ts b/src/renderer/src/web/preload-api/web-artifact-sharing-setting.test.ts new file mode 100644 index 00000000000..3c4c5a235a1 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-artifact-sharing-setting.test.ts @@ -0,0 +1,18 @@ +// @vitest-environment happy-dom +import { beforeEach, expect, it, vi } from 'vitest' +import { getStoredSettings } from './web-preferences-store' +import { SETTINGS_STORAGE_KEY } from './web-storage' + +vi.mock('./web-runtime-session', () => ({ + webRuntimeState: { activeEnvironment: null }, + requireActiveEnvironmentOrNull: () => null +})) + +beforeEach(() => localStorage.clear()) + +it('keeps publishing off in the web fallback until a stored web setting grants it', () => { + expect(getStoredSettings().artifactSharingEnabled).toBe(false) + + localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify({ artifactSharingEnabled: true })) + expect(getStoredSettings().artifactSharingEnabled).toBe(true) +}) From 098fdce3b4a99a05bab997c571ad10abe6401a84 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:17:38 -0800 Subject: [PATCH 03/44] Prevent missing workspace names from crashing cleanup and sorting (#10062) * fix(workspaces): guard missing display names in cleanup and sorting * fix(cleanup): normalize missing names in active facets --- .../workspace-cleanup-candidate.ts | 4 +-- .../workspace-space-analysis.ts | 5 ++- .../workspace-space-worktree-row.ts | 2 +- .../workspace-space-presentation.ts | 7 +++-- .../workspace-cleanup-facets.ts | 2 +- .../workspace-cleanup-filter-sort.ts | 7 +++-- .../workspace-cleanup-query.test.ts | 27 ++++++++++++++++ .../workspace-port-groups.test.ts | 31 +++++++++++++++++++ .../workspace-ports/workspace-port-groups.ts | 5 +-- .../worktree-display-name-order.test.ts | 8 +++++ .../display/worktree-display-name-order.ts | 11 +++++-- .../worktree-catalog-visibility.test.ts | 23 ++++++++++++++ .../listing/worktree-catalog-visibility.ts | 3 +- 13 files changed, 119 insertions(+), 16 deletions(-) create mode 100644 src/renderer/src/components/workspace-cleanup/workspace-cleanup-query.test.ts create mode 100644 src/renderer/src/lib/workspace-ports/workspace-port-groups.test.ts create mode 100644 src/renderer/src/lib/workspace/display/worktree-display-name-order.test.ts create mode 100644 src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.test.ts diff --git a/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts b/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts index a0e8e2c70b3..da08e814517 100644 --- a/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts +++ b/src/main/ipc/workspace-cleanup/workspace-cleanup-candidate.ts @@ -70,7 +70,7 @@ export async function buildWorkspaceCleanupCandidate(args: { repoName: repo.displayName, connectionId: repo.connectionId ?? null, executionHostId: getWorktreeExecutionHostId(worktree, repo), - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', branch: shortWorkspaceCleanupBranchName(worktree.branch), path: worktree.path, reasons, @@ -115,7 +115,7 @@ export function buildWorkspaceCleanupCandidateFromError( repoName: repo.displayName, connectionId: repo.connectionId ?? null, executionHostId: getWorktreeExecutionHostId(worktree, repo), - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', branch: shortWorkspaceCleanupBranchName(worktree.branch), path: worktree.path, reasons: getWorkspaceCleanupInactivityReasonsForWorkspace(worktree, scannedAt), diff --git a/src/main/workspaces/space-analysis/workspace-space-analysis.ts b/src/main/workspaces/space-analysis/workspace-space-analysis.ts index 7e745c307bf..843abf5bef2 100644 --- a/src/main/workspaces/space-analysis/workspace-space-analysis.ts +++ b/src/main/workspaces/space-analysis/workspace-space-analysis.ts @@ -128,7 +128,10 @@ export async function analyzeWorkspaceSpace( const repos = repoResults.map((result) => result.summary) const worktrees = repoResults .flatMap((result) => result.worktrees) - .sort((a, b) => b.sizeBytes - a.sizeBytes || a.displayName.localeCompare(b.displayName)) + .sort( + (a, b) => + b.sizeBytes - a.sizeBytes || (a.displayName ?? '').localeCompare(b.displayName ?? '') + ) throwIfWorkspaceSpaceScanAborted(options.signal) const summary = summarizeWorkspaceSpaceRows(worktrees) let unavailableRepoCount = 0 diff --git a/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts b/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts index 7efc50600d0..56696c38b17 100644 --- a/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts +++ b/src/main/workspaces/space-analysis/workspace-space-worktree-row.ts @@ -33,7 +33,7 @@ function createBaseWorktreeRow(repo: Repo, worktree: Worktree, scannedAt: number executionHostId: getWorktreeExecutionHostId(worktree, repo), repoDisplayName: repo.displayName, repoPath: repo.path, - displayName: worktree.displayName, + displayName: worktree.displayName ?? '', path: worktree.path, branch: worktree.branch, isMainWorktree: worktree.isMainWorktree, diff --git a/src/renderer/src/components/status-bar/workspace-space-presentation.ts b/src/renderer/src/components/status-bar/workspace-space-presentation.ts index f8ac72c1bb1..18d0fac5906 100644 --- a/src/renderer/src/components/status-bar/workspace-space-presentation.ts +++ b/src/renderer/src/components/status-bar/workspace-space-presentation.ts @@ -1,3 +1,4 @@ +import { compareDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import { detectAgentStatusFromTitle } from '../../../../shared/agent-status/title/agent-title-status' import { isAgentStatusFresh, @@ -187,11 +188,11 @@ function compareRows( case 'size': return left.sizeBytes - right.sizeBytes case 'name': - return left.displayName.localeCompare(right.displayName) + return compareDisplayName(left.displayName, right.displayName) case 'repo': return ( left.repoDisplayName.localeCompare(right.repoDisplayName) || - left.displayName.localeCompare(right.displayName) + compareDisplayName(left.displayName, right.displayName) ) case 'activity': return left.lastActivityAt - right.lastActivityAt @@ -209,7 +210,7 @@ export function sortWorkspaceSpaceRows( return ( primary || right.sizeBytes - left.sizeBytes || - left.displayName.localeCompare(right.displayName) + compareDisplayName(left.displayName, right.displayName) ) }) } diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facets.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facets.ts index 05b38f93c17..c809dca9e69 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facets.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facets.ts @@ -118,7 +118,7 @@ export function buildWorkspaceCleanupFacets( identity: hostIdentity, repoId: candidate.repoId, repoName: candidate.repoName, - displayName: candidate.displayName, + displayName: candidate.displayName ?? '', path: candidate.path, branch, hostId: worktree?.hostId ?? getWorkspaceCleanupCandidateHostId(candidate), diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-filter-sort.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-filter-sort.ts index 144354e86b2..ce286db125c 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-filter-sort.ts +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-filter-sort.ts @@ -1,3 +1,4 @@ +import { compareDisplayName } from '@/lib/workspace/display/worktree-display-name-order' import { isWorkspaceCleanupHeadLanded, type WorkspaceCleanupCandidate @@ -94,7 +95,7 @@ export function sortWorkspaceCleanupCandidates( primary || left.lastActivityAt - right.lastActivityAt || left.repoName.localeCompare(right.repoName) || - left.displayName.localeCompare(right.displayName) + compareDisplayName(left.displayName, right.displayName) ) }) } @@ -125,11 +126,11 @@ function compareWorkspaceCleanupCandidates( case 'activity': return left.lastActivityAt - right.lastActivityAt case 'name': - return left.displayName.localeCompare(right.displayName) + return compareDisplayName(left.displayName, right.displayName) case 'repo': return ( left.repoName.localeCompare(right.repoName) || - left.displayName.localeCompare(right.displayName) + compareDisplayName(left.displayName, right.displayName) ) case 'review': return ( diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-query.test.ts b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-query.test.ts new file mode 100644 index 00000000000..fad0636825e --- /dev/null +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-query.test.ts @@ -0,0 +1,27 @@ +import { expect, it } from 'vitest' +import { createDefaultWorkspaceCleanupFilterState } from '../../../../shared/workspace-cleanup/workspace-cleanup-filter-model' +import { makeFacetCandidate } from './workspace-cleanup-facet.test.fixture' +import { queryWorkspaceCleanupCandidates } from './workspace-cleanup-query' + +it.each(['name', 'last-activity'] as const)( + 'sorts an older candidate without a display name by %s', + (field) => { + const named = makeFacetCandidate({ + worktreeId: 'named', + displayName: 'Beta', + lastActivityAt: 0 + }) + const unnamed = makeFacetCandidate({ worktreeId: 'unnamed', lastActivityAt: 0 }) + Reflect.deleteProperty(unnamed, 'displayName') + + const result = queryWorkspaceCleanupCandidates([named, unnamed], { + filters: createDefaultWorkspaceCleanupFilterState(), + sort: { field, direction: 'asc' } + }) + + expect(result.rows.map((row) => [row.worktreeId, row.displayName])).toEqual([ + ['unnamed', ''], + ['named', 'Beta'] + ]) + } +) diff --git a/src/renderer/src/lib/workspace-ports/workspace-port-groups.test.ts b/src/renderer/src/lib/workspace-ports/workspace-port-groups.test.ts new file mode 100644 index 00000000000..d1dce3b5993 --- /dev/null +++ b/src/renderer/src/lib/workspace-ports/workspace-port-groups.test.ts @@ -0,0 +1,31 @@ +import { expect, it } from 'vitest' +import type { WorkspacePort } from '../../../../shared/workspace-ports' +import { getWorkspacePortGroups } from './workspace-port-groups' + +it('normalizes missing owner names in the sorted port groups', () => { + const port = ( + worktreeId: string, + displayName: string, + number: number + ): Extract => ({ + id: `${worktreeId}:${number}`, + bindHost: '127.0.0.1', + connectHost: '127.0.0.1', + port: number, + protocol: 'http', + kind: 'workspace', + owner: { worktreeId, repoId: 'repo', displayName, path: '/workspace', confidence: 'cwd' } + }) + const unnamed = port('unnamed', '', 3001) + Reflect.deleteProperty(unnamed.owner, 'displayName') + const groups = getWorkspacePortGroups({ + platform: 'linux', + scannedAt: 0, + ports: [port('named', 'Beta', 3000), unnamed] + }) + + expect(groups.map(({ worktreeId, displayName }) => [worktreeId, displayName])).toEqual([ + ['unnamed', ''], + ['named', 'Beta'] + ]) +}) diff --git a/src/renderer/src/lib/workspace-ports/workspace-port-groups.ts b/src/renderer/src/lib/workspace-ports/workspace-port-groups.ts index 8270610c736..baca70c9e37 100644 --- a/src/renderer/src/lib/workspace-ports/workspace-port-groups.ts +++ b/src/renderer/src/lib/workspace-ports/workspace-port-groups.ts @@ -1,3 +1,4 @@ +import { compareDisplayName } from '../workspace/display/worktree-display-name-order' import type { WorkspacePort, WorkspacePortScanResult } from '../../../../shared/workspace-ports' export type WorkspacePortGroup = { @@ -69,7 +70,7 @@ export function getWorkspacePortGroups( groupsByWorktreeId.set(port.owner.worktreeId, { worktreeId: port.owner.worktreeId, repoId: port.owner.repoId, - displayName: port.owner.displayName, + displayName: port.owner.displayName ?? '', ports: [port] }) } @@ -78,7 +79,7 @@ export function getWorkspacePortGroups( .map((group) => ({ ...group, ports: [...group.ports].sort(comparePorts) })) .sort( (a, b) => - a.displayName.localeCompare(b.displayName) || + compareDisplayName(a.displayName, b.displayName) || (a.ports[0]?.port ?? 0) - (b.ports[0]?.port ?? 0) ) workspaceGroupsCache.set(scan, groups) diff --git a/src/renderer/src/lib/workspace/display/worktree-display-name-order.test.ts b/src/renderer/src/lib/workspace/display/worktree-display-name-order.test.ts new file mode 100644 index 00000000000..962188a2191 --- /dev/null +++ b/src/renderer/src/lib/workspace/display/worktree-display-name-order.test.ts @@ -0,0 +1,8 @@ +import { expect, it } from 'vitest' +import { compareDisplayName } from './worktree-display-name-order' + +it('orders absent workspace names as empty names', () => { + expect(compareDisplayName(undefined, 'Beta')).toBeLessThan(0) + expect(compareDisplayName('Beta', null)).toBeGreaterThan(0) + expect(compareDisplayName(undefined, null)).toBe(0) +}) diff --git a/src/renderer/src/lib/workspace/display/worktree-display-name-order.ts b/src/renderer/src/lib/workspace/display/worktree-display-name-order.ts index ae59181b971..7a281da232c 100644 --- a/src/renderer/src/lib/workspace/display/worktree-display-name-order.ts +++ b/src/renderer/src/lib/workspace/display/worktree-display-name-order.ts @@ -1,6 +1,13 @@ import type { Worktree } from '../../../../../shared/worktree/types' -// Persisted/discovered rows can lack required displayName (crash 99657ab1); coalesce before comparing. +// Persisted/discovered rows can lack required displayName (crash 99657ab1). +export function compareDisplayName( + a: string | null | undefined, + b: string | null | undefined +): number { + return (a ?? '').localeCompare(b ?? '') +} + export function compareWorktreeDisplayName(a: Worktree, b: Worktree): number { - return (a.displayName ?? '').localeCompare(b.displayName ?? '') + return compareDisplayName(a.displayName, b.displayName) } diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.test.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.test.ts new file mode 100644 index 00000000000..051aee99b6c --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.test.ts @@ -0,0 +1,23 @@ +import { expect, it } from 'vitest' +import { makeWorktree } from '../worktree.test-fixture' +import { toVisibleWorktree } from './worktree-catalog-visibility' + +it.each([ + { branch: 'refs/heads/feature/foo', path: '/repo/workspace', expected: 'feature/foo' }, + { branch: '', path: 'C:\\repos\\app\\folder', expected: 'folder' } +])('fills a missing name from branch or folder: $expected', ({ branch, path, expected }) => { + const detected = { + ...makeWorktree({ + id: 'workspace', + repoId: 'repo', + branch, + path + }), + ownership: 'orca-managed' as const, + selectedCheckout: false, + visible: true + } + Reflect.deleteProperty(detected, 'displayName') + + expect(toVisibleWorktree(detected).displayName).toBe(expected) +}) diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.ts index 6ac0d1207e0..b4436aebbb2 100644 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.ts +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-visibility.ts @@ -1,3 +1,4 @@ +import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' import { structuralValuesEqualIgnoringUndefined } from '../../../../../../shared/structural-value-equality' import { catalogRowsEqual } from '../../../../lib/catalog-reconciliation/catalog-row-reconciliation' import type { DetectedWorktreeListResult, Worktree } from '../../../../../../shared/worktree/types' @@ -49,5 +50,5 @@ export function toVisibleWorktree( visible: _visible, ...base } = worktree - return base + return { ...base, displayName: base.displayName || resolveWorktreeDisplayName(base) } } From ed3062af0937fb40f4a89266b1d3e237788b8a36 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 12 Nov 2026 13:19:53 -0800 Subject: [PATCH 04/44] test: remove low-value catalog and marketplace inventories (#41655) * test: remove low-value catalog detail and policy samples * test: remove low-value marketplace and kill-list inventories --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - .../catalog/plugin-catalog-release.test.ts | 68 ---------- .../catalog/plugin-detail-fields.test.ts | 30 ----- .../plugins/catalog/plugin-kill-list.test.ts | 41 +----- .../catalog/plugin-marketplace.test.ts | 127 +----------------- .../plugin-file-validation.test.ts | 27 +--- 6 files changed, 3 insertions(+), 291 deletions(-) delete mode 100644 src/shared/plugins/catalog/plugin-detail-fields.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index d6dc8e43bfd..ae84f5be7f6 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6596,7 +6596,6 @@ "src/shared/plugins/authoring/plugin-host-typings.test.ts": 2140, "src/shared/plugins/catalog/plugin-catalog-release.test.ts": 229, "src/shared/plugins/catalog/plugin-catalog.test.ts": 630, - "src/shared/plugins/catalog/plugin-detail-fields.test.ts": 171, "src/shared/plugins/catalog/plugin-kill-list.test.ts": 195, "src/shared/plugins/catalog/plugin-marketplace.test.ts": 246, "src/shared/plugins/catalog/plugin-repository-link.test.ts": 205, diff --git a/src/shared/plugins/catalog/plugin-catalog-release.test.ts b/src/shared/plugins/catalog/plugin-catalog-release.test.ts index f41bafbe165..e8929abdd25 100644 --- a/src/shared/plugins/catalog/plugin-catalog-release.test.ts +++ b/src/shared/plugins/catalog/plugin-catalog-release.test.ts @@ -50,18 +50,6 @@ function check(record: PluginCatalogRelease, subject = manifest()): string | nul }) } -function manifestInput(): Record { - return { - manifestVersion: 2, - execution: 'data', - id: 'demo', - publisher: 'samples', - name: 'Demo', - version: '1.2.0', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` } - } -} - describe('catalog releases', () => { it('drops only the summary items this client cannot read', () => { const parsed = pluginCatalogReleaseSchema.parse({ @@ -74,13 +62,6 @@ describe('catalog releases', () => { expect(parsed.contributes).toEqual([{ kind: 'panels', name: 'Dash' }]) }) - it('rejects a release type its profile cannot run or this client cannot install', () => { - expect(() => release({ types: ['worker'] })).toThrow('data cannot declare worker') - expect( - pluginCatalogReleaseSchema.safeParse({ ...release(), types: ['file-viewer'] }).success - ).toBe(false) - }) - it.each([ ['commit', { resolvedCommit: 'd'.repeat(40) }, 'commit'], ['bytes', { contentHash: 'e'.repeat(64) }, 'bytes'] @@ -141,19 +122,6 @@ describe('catalog releases', () => { 'plugin name does not match the catalog release' ) }) - - it('requires a v2 manifest', () => { - const v1 = parsePluginManifest({ - ...manifestInput(), - manifestVersion: 1, - pluginApi: 1, - execution: undefined - }) - if (!v1.ok) { - throw new Error(v1.error) - } - expect(check(release(), v1.manifest)).toContain('version 2 manifest') - }) }) describe('catalog release summaries', () => { @@ -180,40 +148,4 @@ describe('catalog release summaries', () => { pluginCatalogReleaseError({ ...base, release: { ...listed, capabilities: ['secrets:own'] } }) ).toBe('the listed capabilities do not match the catalog release') }) - - it('drops unreadable summaries and images instead of hiding the release', () => { - const parsed = pluginCatalogReleaseSchema.parse({ - ...release(), - contributes: [{ kind: 'widgets', name: 'x' }], - capabilities: ['root'], - images: { - cover: { path: '../escape.png', alt: 'x', sha256: 'f'.repeat(64), width: 1, height: 1 } - } - }) - expect(parsed.contributes).toBeUndefined() - expect(parsed.capabilities).toBeUndefined() - expect(parsed.images).toBeUndefined() - }) -}) - -describe('catalog theme previews', () => { - it('keeps hex palettes and drops anything else', () => { - const palette = { - label: 'Dusk', - base: 'dark', - background: '#1b1430', - foreground: '#e8e0ff', - accent: '#c38bff', - surface: '#241843' - } - expect( - pluginCatalogReleaseSchema.parse({ ...release(), themePreview: [palette] }).themePreview - ).toEqual([palette]) - expect( - pluginCatalogReleaseSchema.parse({ - ...release(), - themePreview: [{ ...palette, background: 'url(https://example.com/x)' }] - }).themePreview - ).toBeUndefined() - }) }) diff --git a/src/shared/plugins/catalog/plugin-detail-fields.test.ts b/src/shared/plugins/catalog/plugin-detail-fields.test.ts deleted file mode 100644 index 194e9b506fd..00000000000 --- a/src/shared/plugins/catalog/plugin-detail-fields.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { pluginCatalogReleaseSchema } from './plugin-catalog-release' - -const release = { - version: '1.2.0', - commit: 'c'.repeat(40), - contentHash: 'f'.repeat(64), - execution: 'data', - minimumOrca: '1.4.0', - types: ['interface-language'] -} - -describe('plugin detail fields', () => { - it('drops invalid catalog release details instead of hiding the release', () => { - const parsed = pluginCatalogReleaseSchema.parse({ - ...release, - license: 'MIT; rm -rf', - repository: 'http://github.com/acme/demo', - homepage: 'javascript:alert(1)', - updatedAt: 'last week', - changelog: 'x'.repeat(2_001) - }) - expect(parsed.license).toBeUndefined() - expect(parsed.repository).toBeUndefined() - expect(parsed.homepage).toBeUndefined() - expect(parsed.updatedAt).toBeUndefined() - expect(parsed.changelog).toBeUndefined() - }) -}) diff --git a/src/shared/plugins/catalog/plugin-kill-list.test.ts b/src/shared/plugins/catalog/plugin-kill-list.test.ts index c85a1069801..821f7f4a361 100644 --- a/src/shared/plugins/catalog/plugin-kill-list.test.ts +++ b/src/shared/plugins/catalog/plugin-kill-list.test.ts @@ -1,11 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - PLUGIN_KILL_LIST_ENTRY_LIMIT, - findKilledPlugin, - isPluginKillListTooFarInFuture, - pluginKillListSchema, - type PluginKillList -} from './plugin-kill-list' +import { pluginKillListSchema } from './plugin-kill-list' function entry(pluginKey = 'community.unsafe'): Record { return { @@ -16,17 +10,6 @@ function entry(pluginKey = 'community.unsafe'): Record { } describe('pluginKillListSchema', () => { - it('ignores fields a later list adds so old clients keep revoking', () => { - const parsed = pluginKillListSchema.parse({ - version: 1, - generatedAt: '2026-07-12T20:00:00Z', - plugins: [{ ...entry(), contentHash: 'f'.repeat(64) }], - revoked: [] - }) - - expect(findKilledPlugin(parsed, 'community.unsafe')).toEqual(entry()) - }) - it('drops only the entries it cannot read, and keeps one entry per plugin', () => { const parsed = pluginKillListSchema.parse({ version: 1, @@ -41,26 +24,4 @@ describe('pluginKillListSchema', () => { }) expect(parsed.plugins).toEqual([entry()]) }) - - it('caps the revocation document size by entry count', () => { - const plugins = Array.from({ length: PLUGIN_KILL_LIST_ENTRY_LIMIT + 1 }, (_, index) => - entry(`publisher.plugin-${index}`) - ) - expect( - pluginKillListSchema.safeParse({ - version: 1, - generatedAt: '2026-07-12T20:00:00Z', - plugins - }).success - ).toBe(false) - }) -}) - -describe('isPluginKillListTooFarInFuture', () => { - const list = (generatedAt: string): PluginKillList => - pluginKillListSchema.parse({ version: 1, generatedAt, plugins: [entry()] }) - - it('flags a snapshot that would freeze out every later revocation', () => { - expect(isPluginKillListTooFarInFuture(list('9999-12-31T23:59:59Z'))).toBe(true) - }) }) diff --git a/src/shared/plugins/catalog/plugin-marketplace.test.ts b/src/shared/plugins/catalog/plugin-marketplace.test.ts index 992143c7b8e..e1cfbf620e4 100644 --- a/src/shared/plugins/catalog/plugin-marketplace.test.ts +++ b/src/shared/plugins/catalog/plugin-marketplace.test.ts @@ -1,109 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - OFFICIAL_MARKETPLACE_REPOSITORY, - PLUGIN_MARKETPLACE_CATEGORY_LIMIT, - PLUGIN_MARKETPLACE_ENTRY_LIMIT, - isOfficialMarketplaceGitSource, - isOfficialOrganizationGitSource, - isSameGitRepository, - pluginMarketplaceSchema -} from './plugin-marketplace' - -function listing(id = 'community.nord'): Record { - return { - id, - source: { kind: 'git', url: 'https://github.com/community/nord.git', ref: 'v1.0.0' }, - description: 'A theme pack', - categories: ['themes'] - } -} - -describe('pluginMarketplaceSchema', () => { - it.each([ - ['root', { name: 'Plugins', owner: 'team', plugins: [], extra: true }], - ['entry', { name: 'Plugins', owner: 'team', plugins: [{ ...listing(), official: true }] }], - [ - 'source', - { - name: 'Plugins', - owner: 'team', - plugins: [ - { - ...listing(), - source: { - kind: 'git', - url: 'https://github.com/community/nord.git', - ref: 'main', - depth: 1 - } - } - ] - } - ] - ])('rejects unknown keys at the %s boundary', (_boundary, marketplace) => { - expect(pluginMarketplaceSchema.safeParse(marketplace).success).toBe(false) - }) - - it.each([ - ['an unqualified id', { ...listing(), id: 'nord' }], - [ - 'a missing ref', - { - ...listing(), - source: { kind: 'git', url: 'https://github.com/community/nord.git', ref: '' } - } - ], - [ - 'an executable Git transport', - { - ...listing(), - source: { kind: 'git', url: 'ext::sh -c exploit', ref: 'main' } - } - ], - ['a duplicate category', { ...listing(), categories: ['themes', 'themes'] }], - [ - 'too many categories', - { - ...listing(), - categories: Array.from( - { length: PLUGIN_MARKETPLACE_CATEGORY_LIMIT + 1 }, - (_, index) => `category-${index}` - ) - } - ] - ])('rejects %s', (_label, entry) => { - expect( - pluginMarketplaceSchema.safeParse({ name: 'Plugins', owner: 'team', plugins: [entry] }) - .success - ).toBe(false) - }) - - it('rejects duplicate plugin identities', () => { - const parsed = pluginMarketplaceSchema.safeParse({ - name: 'Plugins', - owner: 'team', - plugins: [listing(), listing()] - }) - - expect(parsed.success).toBe(false) - if (!parsed.success) { - expect(parsed.error.issues).toEqual( - expect.arrayContaining([ - expect.objectContaining({ message: 'duplicate plugin id: community.nord' }) - ]) - ) - } - }) - - it('caps the marketplace entry count', () => { - const plugins = Array.from({ length: PLUGIN_MARKETPLACE_ENTRY_LIMIT + 1 }, (_, index) => - listing(`publisher.plugin-${index}`) - ) - expect( - pluginMarketplaceSchema.safeParse({ name: 'Plugins', owner: 'team', plugins }).success - ).toBe(false) - }) -}) +import { isOfficialOrganizationGitSource, isSameGitRepository } from './plugin-marketplace' describe('marketplace provenance contracts', () => { it('does not trust lookalike organizations or hosts', () => { @@ -115,27 +11,6 @@ describe('marketplace provenance contracts', () => { false ) }) - - it('rejects a listing whose Git host starts with a dash or contains ..', () => { - for (const url of ['git@-oProxyCommand=evil:a/b.git', 'https://github..com/a/b.git']) { - expect( - pluginMarketplaceSchema.safeParse({ - name: 'Community plugins', - owner: 'community', - plugins: [{ ...listing(), source: { kind: 'git', url, ref: 'main' } }] - }).success - ).toBe(false) - } - }) - - it('recognizes only the canonical official marketplace repository', () => { - expect( - isOfficialMarketplaceGitSource( - `git@github.com:stablyai/${OFFICIAL_MARKETPLACE_REPOSITORY}.git` - ) - ).toBe(true) - expect(isOfficialMarketplaceGitSource('git@github.com:stablyai/plugins.git')).toBe(false) - }) }) describe('isSameGitRepository', () => { diff --git a/src/shared/plugins/installation/plugin-file-validation.test.ts b/src/shared/plugins/installation/plugin-file-validation.test.ts index cf2f2a8abc6..4bfa27f930a 100644 --- a/src/shared/plugins/installation/plugin-file-validation.test.ts +++ b/src/shared/plugins/installation/plugin-file-validation.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - catalogEntryFixture, - catalogFixture, - v2ManifestFixture -} from '../manifest/plugin-json-schema.test-fixture' +import { catalogEntryFixture, catalogFixture } from '../manifest/plugin-json-schema.test-fixture' import { validatePluginFile } from './plugin-file-validation' const VALID_RELEASE = { @@ -38,27 +34,6 @@ describe('validatePluginFile', () => { ]) }) - it('refuses publishers that are or imitate a reserved name', () => { - expect( - validatePluginFile('orca-plugin.json', v2ManifestFixture({ publisher: 'orca-team' })) - ).toEqual(['publisher: "orca-team" is reserved for official Orca plugins; use your own name']) - expect( - validatePluginFile('orca-plugin.json', v2ManifestFixture({ publisher: 'stablyai' })) - ).toEqual([]) - expect( - validatePluginFile( - 'orca-catalog.json', - catalogFixture([catalogEntryFixture({ id: 'openai.x' })]) - ) - ).toEqual([expect.stringContaining('plugins[0].id: publisher "openai" is reserved')]) - }) - - it('refuses a newer catalog format', () => { - expect( - validatePluginFile('orca-catalog.json', { ...catalogFixture([]), catalogVersion: 3 }) - ).toEqual(['uses catalog format 3; update Orca to browse this catalog']) - }) - it('checks catalog images against the files in the catalog repository', () => { const be32 = (n: number) => [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255] const png = (w: number, h: number) => From 3cfdd60d3bb089112ec2d0cc650e81fad474367a Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:23:42 +0000 Subject: [PATCH 05/44] fix(computer): check macOS click targets are enabled, in view and uncovered before clicking (#41519) * fix(computer): check macOS click targets are enabled, in view and on top before sending input * fix(computer): scope macOS click cover checks to the target window * fix(computer): scroll before trusting container hits and stop hit walks at the shared container * refactor(computer): share the one-scroll rule in the macOS click check --- .../Sources/OrcaComputerUseMacOS/main.swift | 150 ++++++++++-- .../ElementActionability.swift | 209 +++++++++++++++++ .../ElementActionabilityTests.swift | 221 ++++++++++++++++++ skill-guides/orca-computer-use.md | 3 +- src/cli/skills/bundled-skill-guides.ts | 3 +- src/shared/computer-use-error-recovery.ts | 16 ++ src/shared/computer-use-runtime-types.ts | 1 + 7 files changed, 588 insertions(+), 15 deletions(-) create mode 100644 native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ElementActionability.swift create mode 100644 native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ElementActionabilityTests.swift diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index 4ca1844479e..43ab1f782f3 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -813,6 +813,7 @@ final class Provider { } if let elementIndex = try optionalInteger(params, "elementIndex") { let record = try element(snapshot, elementIndex) + try requireEnabled(record, snapshot: snapshot) if !foreground { try requireBackgroundClickAllowed(backgroundClickHit(record.element, snapshot: snapshot)) } @@ -832,22 +833,20 @@ final class Provider { actionName: actionName ) } - if let point = center(record.localFrame, in: snapshot.windowBounds) { - try clickPointer(at: point, button: button, count: count, modifiers: modifiers, snapshot: snapshot, foreground: foreground, element: record.element) - guard unselectedRow else { - return actionMetadata( - path: "synthetic", - fallbackReason: "actionUnsupported", - verification: unverifiedAction(reason: "synthetic_input") - ) - } - return rowClickMetadata( - try RowSelectionClick.confirm(record.element, ax: rowSelection), + let point = try pointerTarget(record, snapshot: snapshot) + try clickPointer(at: point, button: button, count: count, modifiers: modifiers, snapshot: snapshot, foreground: foreground, element: record.element) + guard unselectedRow else { + return actionMetadata( path: "synthetic", - actionName: nil + fallbackReason: "actionUnsupported", + verification: unverifiedAction(reason: "synthetic_input") ) } - throw ProviderError.coded("element_not_clickable", "element \(record.index) has no clickable frame") + return rowClickMetadata( + try RowSelectionClick.confirm(record.element, ax: rowSelection), + path: "synthetic", + actionName: nil + ) } let point = try coordinatePoint(params: params, xKey: "x", yKey: "y", snapshot: snapshot) try clickPointer(at: point, button: button, count: count, modifiers: modifiers, snapshot: snapshot, foreground: foreground) @@ -873,6 +872,38 @@ final class Provider { } } + private func requireEnabled(_ record: ElementRecord, snapshot: Snapshot) throws { + let ax = AccessibilityActionability(pid: snapshot.app.pid) + let enabled = ElementActionability.waitUntilEnabled(record.element, ax: ax) + if ax.unanswered { throw AccessibilityMessaging.appNotResponding(snapshot.app.name) } + guard enabled else { throw notEnabledError(record) } + } + + /// The screen point a pointer click on the element should use, once it is enabled, in view and on top there. + private func pointerTarget(_ record: ElementRecord, snapshot: Snapshot) throws -> CGPoint { + // Why: its own wait budget, so time spent enabling or trying AXPress cannot cut short the settle after a scroll. + let ax = AccessibilityActionability(pid: snapshot.app.pid) + let target = try ElementActionability.pointerTarget(record.element, windowFrame: snapshot.windowBounds, ax: ax) + if ax.unanswered { throw AccessibilityMessaging.appNotResponding(snapshot.app.name) } + switch target { + case let .ready(point): + return point + case .notEnabled: + throw notEnabledError(record) + case .noFrame: + throw ProviderError.coded("element_not_clickable", "element \(record.index) has no clickable frame; no click was sent") + case let .outOfView(scrolled): + let reason = scrolled ? "is still out of view after scrolling it into view" : "is out of view and cannot be scrolled into view" + throw ProviderError.coded("element_not_clickable", "element \(record.index) \(reason), so no click was sent; scroll its container, run get-app-state again and retry") + case let .covered(by: cover): + throw ProviderError.coded("element_not_clickable", "element \(record.index) is covered by \(describeElement(cover)), so no click was sent; close or finish what covers it, run get-app-state again and retry") + } + } + + private func notEnabledError(_ record: ElementRecord) -> ProviderError { + .coded("element_not_enabled", "element \(record.index) is disabled, so no input was sent; do what enables it first, then run get-app-state and retry once its line no longer lists disabled") + } + private func performClickAction(record: ElementRecord, mouseButton: MouseButtonSelection) throws -> String? { if mouseButton == .right { return try performAction(record.element, "AXShowMenu") ? "AXShowMenu" : nil @@ -893,6 +924,10 @@ final class Provider { guard let action else { throw ProviderError.coded("action_not_supported", "'\(requested)' is not a valid secondary action for element \(record.index)") } + // Why: scrolling a control into view does not operate it. + if action != "AXScrollToVisible" { + try requireEnabled(record, snapshot: snapshot) + } guard try performAction(record.element, action) else { throw ProviderError.coded("accessibility_error", "AXUIElementPerformAction(\(action)) failed") } @@ -903,6 +938,7 @@ final class Provider { let snapshot = try currentSnapshot(params: params) let record = try element(snapshot, try requiredInteger(params, "elementIndex")) let expected = try requiredStringAllowingEmpty(params, "value") + try requireEnabled(record, snapshot: snapshot) guard isSettable(record.element, kAXValueAttribute as String) else { throw ProviderError.coded("value_not_settable", "element \(record.index) is not settable") } @@ -1980,6 +2016,94 @@ private final class AccessibilityRowSelection: RowSelectionAccessibility { } } +/// Once the app stops answering, later reads return nothing at once so a hung app costs one timeout, not dozens. +private final class AccessibilityActionability: ElementActionabilityAccessibility { + private let appElement: AXUIElement + // Why: wall time, since one slow AX read can take the full 3 s messaging timeout. + private let deadline = CFAbsoluteTimeGetCurrent() + 0.5 + private(set) var unanswered = false + + init(pid: pid_t) { + appElement = AXUIElementCreateApplication(pid) + } + + func isEnabled(_ element: AXUIElement) -> Bool? { + read(element, kAXEnabledAttribute as String) as? Bool + } + + func frame(of element: AXUIElement) -> CGRect? { + var point = CGPoint.zero + var size = CGSize.zero + guard let position = read(element, kAXPositionAttribute as String), + let extent = read(element, kAXSizeAttribute as String), + CFGetTypeID(position) == AXValueGetTypeID(), + CFGetTypeID(extent) == AXValueGetTypeID(), + AXValueGetValue(position as! AXValue, .cgPoint, &point), + AXValueGetValue(extent as! AXValue, .cgSize, &size) + else { + return nil + } + return CGRect(origin: point, size: size) + } + + func role(of element: AXUIElement) -> String? { + read(element, kAXRoleAttribute as String) as? String + } + + func parent(of element: AXUIElement) -> AXUIElement? { + guard let value = read(element, kAXParentAttribute as String), CFGetTypeID(value) == AXUIElementGetTypeID() else { + return nil + } + return (value as! AXUIElement) + } + + func isSame(_ lhs: AXUIElement, _ rhs: AXUIElement) -> Bool { + CFEqual(lhs, rhs) + } + + func isModal(_ window: AXUIElement) -> Bool { + read(window, kAXModalAttribute as String) as? Bool == true + } + + /// Asks the target app itself: background input reaches it whatever other apps' windows are on top. + func element(at point: CGPoint) -> AXUIElement? { + guard !unanswered, Float(point.x).isFinite, Float(point.y).isFinite else { return nil } + var found: AXUIElement? + let start = CFAbsoluteTimeGetCurrent() + let result = AXUIElementCopyElementAtPosition(appElement, Float(point.x), Float(point.y), &found) + unanswered = AccessibilityMessaging.timedOut(result, since: start) + return result == .success ? found : nil + } + + func scrollToVisible(_ element: AXUIElement) throws -> Bool { + try performAction(element, "AXScrollToVisible") + } + + func waitBeforeRetry() -> Bool { + let interval = 0.05 + guard !unanswered, CFAbsoluteTimeGetCurrent() + interval < deadline else { return false } + Thread.sleep(forTimeInterval: interval) + return true + } + + private func read(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { + guard !unanswered else { return nil } + var value: CFTypeRef? + let start = CFAbsoluteTimeGetCurrent() + let result = AXUIElementCopyAttributeValue(element, attribute as CFString, &value) + unanswered = AccessibilityMessaging.timedOut(result, since: start) + return result == .success ? value : nil + } +} + +private func describeElement(_ element: AXUIElement) -> String { + let role = stringAttribute(element, kAXRoleAttribute as String) ?? "an element" + guard let label = stringAttribute(element, kAXTitleAttribute as String) ?? stringAttribute(element, kAXDescriptionAttribute as String) else { + return role + } + return "\(role) \"\(preview(label, maxLength: 60))\"" +} + private func frame(_ element: AXUIElement, windowBounds: CGRect) -> CGRect? { var positionValue: CFTypeRef? var sizeValue: CFTypeRef? diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ElementActionability.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ElementActionability.swift new file mode 100644 index 00000000000..0360ebf6919 --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/ElementActionability.swift @@ -0,0 +1,209 @@ +import CoreGraphics + +/// The accessibility reads an element action needs before it sends input, so the policy runs against a fake tree in tests. +public protocol ElementActionabilityAccessibility { + associatedtype Element + /// AXEnabled; nil when the element does not publish it. + func isEnabled(_ element: Element) -> Bool? + /// Frame in global top-left screen points. + func frame(of element: Element) -> CGRect? + func role(of element: Element) -> String? + func parent(of element: Element) -> Element? + func isSame(_ lhs: Element, _ rhs: Element) -> Bool + /// AXModal: an app-modal window blocks input to the app's other windows. + func isModal(_ window: Element) -> Bool + /// The target app's own topmost element at a screen point; nil when the app cannot say. + func element(at point: CGPoint) -> Element? + /// Asks the app to scroll the element into view; false when the element does not offer that. + func scrollToVisible(_ element: Element) throws -> Bool + /// Pauses before the next check; false once the wait budget is spent. + func waitBeforeRetry() -> Bool +} + +/// Checks that an element can take an action before any input is sent: it is enabled and, for pointer +/// input, it is in view (scrolled there if needed) and is what the app hit-tests under the click point. +public enum ElementActionability { + public enum PointerTarget { + case ready(CGPoint) + case notEnabled + case noFrame + /// Nothing of the element shows inside its window and scroll areas. + case outOfView(scrolled: Bool) + /// Another element is on top at every point tried. + case covered(by: Element) + } + + static let maxAncestorDepth = 64 + + /// Waits briefly for a disabled element to enable; an element that publishes no AXEnabled counts as enabled. + public static func waitUntilEnabled(_ element: AX.Element, ax: AX) -> Bool { + while ax.isEnabled(element) == false { + guard ax.waitBeforeRetry() else { return false } + } + return true + } + + /// Where a pointer click on the element lands, re-checked until it holds or the wait budget runs out. + public static func pointerTarget( + _ element: AX.Element, + windowFrame: CGRect, + ax: AX + ) throws -> PointerTarget { + var scrolled = false + var scrollTried = false + var settledFrame: CGRect? + var last: PointerTarget = .noFrame + // Why: one scroll at most, so a target that keeps failing cannot scroll the user's view around. + func scrollOnce() throws -> Bool { + guard !scrollTried else { return false } + scrollTried = true + scrolled = try ax.scrollToVisible(element) + return scrolled + } + repeat { + guard ax.isEnabled(element) != false else { + last = .notEnabled + continue + } + guard let frame = ax.frame(of: element), frame.width > 0, frame.height > 0 else { + return .noFrame + } + // Why: a scroll can animate, and a click mid-animation lands where the element used to be. + if scrolled, settledFrame.map({ !framesMatch($0, frame) }) ?? true { + settledFrame = frame + last = .outOfView(scrolled: true) + continue + } + let (clip, ancestors) = clipRect(of: element, windowFrame: windowFrame, ax: ax) + let visible = frame.intersection(clip) + // Why: an element bigger than its viewport cannot be brought fully into view, so it is clicked where it shows. + let fits = frame.width <= clip.width && frame.height <= clip.height + if visible.isEmpty || (fits && !visible.contains(CGPoint(x: frame.midX, y: frame.midY))), try scrollOnce() { + last = .outOfView(scrolled: true) + continue + } + guard !visible.isEmpty else { + last = .outOfView(scrolled: scrolled) + if scrolled { continue } + return last + } + switch hitTarget(element, visible: visible, ancestors: ancestors, ax: ax) { + case let .direct(point): + return .ready(point) + case let .ancestorOnly(point): + // Why: a scroller not exposed as AXScrollArea (a web overflow div) can hide the element behind its own container. + guard try scrollOnce() else { return .ready(point) } + last = .outOfView(scrolled: true) + case let .covered(by: cover): + last = .covered(by: cover) + // Why: a table or sticky header inside the scroll area can cover a row that scrolling would clear. + _ = try scrollOnce() + } + } while ax.waitBeforeRetry() + return last + } + + /// The part of the screen the element can show in (its window and every scroll area it sits in), plus its ancestors. + static func clipRect( + of element: AX.Element, + windowFrame: CGRect, + ax: AX + ) -> (CGRect, [AX.Element]) { + var visible = windowFrame + var ancestors: [AX.Element] = [] + var current = element + for _ in 0.. { + /// The element, inside it, or a hit that shows nothing covers it. + case direct(CGPoint) + /// Only the element's own ancestors answered, as when it is see-through to hit tests. + case ancestorOnly(CGPoint) + case covered(by: Element) + } + + static func hitTarget( + _ element: AX.Element, + visible: CGRect, + ancestors: [AX.Element], + ax: AX + ) -> Hit { + var ancestorPoint: CGPoint? + var coveredBy: AX.Element? + for point in candidatePoints(in: visible) { + guard let hit = ax.element(at: point) else { return .direct(point) } + switch owner(of: hit, element, ancestors: ancestors, ax: ax) { + case .clear: + return .direct(point) + case .ancestor: + ancestorPoint = ancestorPoint ?? point + case .cover: + coveredBy = coveredBy ?? hit + } + } + if let ancestorPoint { return .ancestorOnly(ancestorPoint) } + // SAFETY: candidatePoints is never empty, so a loop without a direct or ancestor hit recorded a cover. + return .covered(by: coveredBy!) + } + + private enum HitOwner { + /// The element, inside it, or a hit that shows nothing of the target window is on top. + case clear + case ancestor + case cover + } + + private static func owner( + of hit: AX.Element, + _ element: AX.Element, + ancestors: [AX.Element], + ax: AX + ) -> HitOwner { + if ancestors.contains(where: { ax.isSame($0, hit) }) { return .ancestor } + var current = hit + for _ in 0.. [CGPoint] { + let center = CGPoint(x: rect.midX, y: rect.midY) + let quarters = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)].map { + CGPoint(x: rect.minX + rect.width * $0.0, y: rect.minY + rect.height * $0.1) + } + return [center] + quarters + } + + private static func framesMatch(_ lhs: CGRect, _ rhs: CGRect) -> Bool { + abs(lhs.minX - rhs.minX) < 0.5 && abs(lhs.minY - rhs.minY) < 0.5 + && abs(lhs.width - rhs.width) < 0.5 && abs(lhs.height - rhs.height) < 0.5 + } +} diff --git a/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ElementActionabilityTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ElementActionabilityTests.swift new file mode 100644 index 00000000000..92a411fa7b2 --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/ElementActionabilityTests.swift @@ -0,0 +1,221 @@ +import CoreGraphics +import OrcaComputerUseMacOSCore +import XCTest + +final class ElementActionabilityTests: XCTestCase { + private final class FakeTree: ElementActionabilityAccessibility { + struct Node { + var role: String + var parent: Int? + var frame: CGRect + var enabled: Bool? = true + var modal = false + /// Hides the parts of descendants outside its frame from hit tests, as a scroller does. + var clips = false + /// Where the node sits after AXScrollToVisible; nil when it offers no scroll. + var scrollsTo: CGRect? + } + + var nodes: [Int: Node] + var retriesLeft = 5 + var onRetry: (FakeTree) -> Void = { _ in } + private(set) var scrollRequests = 0 + + init(_ nodes: [Int: Node]) { + self.nodes = nodes + } + + func isEnabled(_ element: Int) -> Bool? { nodes[element]?.enabled } + func frame(of element: Int) -> CGRect? { nodes[element]?.frame } + func role(of element: Int) -> String? { nodes[element]?.role } + func parent(of element: Int) -> Int? { nodes[element]?.parent } + func isSame(_ lhs: Int, _ rhs: Int) -> Bool { lhs == rhs } + func isModal(_ window: Int) -> Bool { nodes[window]?.modal == true } + + /// The highest-numbered node under the point is on top. + func element(at point: CGPoint) -> Int? { + nodes.keys.filter { shows($0, at: point) }.max() + } + + private func shows(_ id: Int, at point: CGPoint) -> Bool { + guard let node = nodes[id], node.frame.contains(point) else { return false } + var ancestor = node.parent + while let current = ancestor.flatMap({ nodes[$0] }) { + if current.clips, !current.frame.contains(point) { return false } + ancestor = current.parent + } + return true + } + + func scrollToVisible(_ element: Int) throws -> Bool { + guard let target = nodes[element]?.scrollsTo else { return false } + scrollRequests += 1 + nodes[element]?.frame = target + return true + } + + func waitBeforeRetry() -> Bool { + guard retriesLeft > 0 else { return false } + retriesLeft -= 1 + onRetry(self) + return true + } + } + + private let window = CGRect(x: 0, y: 0, width: 400, height: 300) + + /// A window with a scroll area showing y 0-200 and a button inside it. + private func scrollingWindow(button: FakeTree.Node) -> FakeTree { + FakeTree([ + 1: .init(role: "AXWindow", parent: nil, frame: window), + 2: .init(role: "AXScrollArea", parent: 1, frame: CGRect(x: 0, y: 0, width: 400, height: 200), clips: true), + 3: button, + ]) + } + + func testADisabledElementIsRefusedWithoutAPoint() throws { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 10, width: 80, height: 20), enabled: false)) + + guard case .notEnabled = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("a disabled button must not get a click point") + } + XCTAssertFalse(ElementActionability.waitUntilEnabled(3, ax: tree)) + } + + func testAnElementThatEnablesWithinTheWaitIsClicked() { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 10, width: 80, height: 20), enabled: false)) + tree.onRetry = { $0.nodes[3]?.enabled = true } + + XCTAssertTrue(ElementActionability.waitUntilEnabled(3, ax: tree)) + } + + func testAnElementBelowTheScrolledAreaIsScrolledIntoViewThenClicked() throws { + let tree = scrollingWindow(button: .init( + role: "AXButton", + parent: 2, + frame: CGRect(x: 10, y: 250, width: 80, height: 20), + scrollsTo: CGRect(x: 10, y: 150, width: 80, height: 20) + )) + + guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("the button should be clickable once scrolled into view") + } + XCTAssertEqual(tree.scrollRequests, 1) + XCTAssertEqual(point, CGPoint(x: 50, y: 160)) + } + + func testAnElementThatCannotBeScrolledIntoViewIsRefused() throws { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 250, width: 80, height: 20))) + + guard case .outOfView(scrolled: false) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("a button clipped by its scroll area must not be clicked") + } + } + + func testAnElementBiggerThanItsScrollAreaIsClickedWhereItShowsWithoutScrolling() throws { + let tree = scrollingWindow(button: .init( + role: "AXGroup", + parent: 2, + frame: CGRect(x: 0, y: 100, width: 400, height: 1000), + scrollsTo: CGRect(x: 0, y: 0, width: 400, height: 1000) + )) + + guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("the visible part of the group should take the click") + } + XCTAssertEqual(tree.scrollRequests, 0) + XCTAssertEqual(point, CGPoint(x: 200, y: 150)) + } + + func testACoveredElementIsRefusedAndNamesWhatCoversIt() throws { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 10, width: 80, height: 20))) + tree.nodes[4] = .init(role: "AXSheet", parent: 1, frame: CGRect(x: 0, y: 0, width: 400, height: 100)) + + guard case let .covered(by: cover) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("a button under a sheet must not be clicked") + } + XCTAssertEqual(cover, 4) + } + + func testARowUnderAStickyHeaderIsScrolledClearThenClicked() throws { + let tree = scrollingWindow(button: .init( + role: "AXRow", + parent: 2, + frame: CGRect(x: 0, y: 0, width: 100, height: 20), + scrollsTo: CGRect(x: 0, y: 40, width: 100, height: 20) + )) + tree.nodes[4] = .init(role: "AXGroup", parent: 2, frame: CGRect(x: 0, y: 0, width: 400, height: 30)) + + guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("the row should be clicked once scrolled out from under the header") + } + XCTAssertEqual(tree.scrollRequests, 1) + XCTAssertEqual(point, CGPoint(x: 50, y: 50)) + } + + func testAnotherWindowOfTheAppOnTopDoesNotCoverTheTarget() throws { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 10, y: 10, width: 80, height: 20))) + tree.nodes[5] = .init(role: "AXWindow", parent: nil, frame: CGRect(x: 0, y: 0, width: 200, height: 200)) + + guard case .ready = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("background input goes to the target window even under another window of the app") + } + + tree.nodes[5]?.modal = true + guard case .covered(by: 5) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("an app-modal window on top blocks input to the target window") + } + } + + func testAPartlyCoveredElementIsClickedWhereItShows() throws { + let tree = scrollingWindow(button: .init(role: "AXButton", parent: 2, frame: CGRect(x: 0, y: 0, width: 100, height: 100))) + tree.nodes[4] = .init(role: "AXGroup", parent: 2, frame: CGRect(x: 0, y: 0, width: 60, height: 100)) + + guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("the uncovered right half should take the click") + } + XCTAssertEqual(point, CGPoint(x: 75, y: 25)) + } + + func testAHitOnTheElementsOwnChildCountsAsTheElement() throws { + let tree = scrollingWindow(button: .init(role: "AXRow", parent: 2, frame: CGRect(x: 0, y: 0, width: 100, height: 20))) + tree.nodes[4] = .init(role: "AXStaticText", parent: 3, frame: CGRect(x: 0, y: 0, width: 100, height: 20)) + + guard case .ready = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("a hit on the row's own text is a hit on the row") + } + } + + func testAnElementHiddenByAScrollerThatIsNotAScrollAreaIsScrolledIntoViewFirst() throws { + // A web overflow div shows as AXGroup (2), so only the window (1) answers below it. + let tree = FakeTree([ + 1: .init(role: "AXWindow", parent: nil, frame: window), + 2: .init(role: "AXGroup", parent: 1, frame: CGRect(x: 0, y: 0, width: 400, height: 100), clips: true), + 3: .init( + role: "AXLink", + parent: 2, + frame: CGRect(x: 10, y: 150, width: 80, height: 20), + scrollsTo: CGRect(x: 10, y: 50, width: 80, height: 20) + ), + ]) + + guard case let .ready(point) = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("the link should be clicked once scrolled into its container's view") + } + XCTAssertEqual(tree.scrollRequests, 1) + XCTAssertEqual(point, CGPoint(x: 50, y: 60)) + } + + func testAHitOnTheElementsAncestorMeansNothingCoversIt() throws { + // The group (9) is above the image (3) in hit order, as when the image ignores hit tests. + let tree = FakeTree([ + 1: .init(role: "AXWindow", parent: nil, frame: window), + 3: .init(role: "AXImage", parent: 9, frame: CGRect(x: 10, y: 10, width: 20, height: 20)), + 9: .init(role: "AXGroup", parent: 1, frame: window), + ]) + + guard case .ready = try ElementActionability.pointerTarget(3, windowFrame: window, ax: tree) else { + return XCTFail("a hit on the element's own ancestor is not a covering element") + } + } +} diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 62718ae0921..8cc9609a614 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -172,7 +172,8 @@ Slack: the accessibility tree may be shallow while the screenshot contains usefu - `unsupported_capability`: the provider or desktop environment cannot do that action; use a semantic alternative or install the missing dependency if the message names one. - `action_not_supported`: inspect the element's listed actions and retry with one of those names, or use click/set-value when appropriate. - `value_not_settable`: the element cannot accept direct value writes; focus it and use keyboard input only when the returned state can be inspected. -- `element_not_clickable`: the element has no actionable frame; use a parent/child element with a frame or choose window-local coordinates from the latest screenshot. +- `element_not_clickable`: no click was sent. If the message says the element is covered, deal with what covers it (a dialog, sheet or popover), then click again from a fresh `get-app-state`; never click by coordinates to get past the cover. If it is out of view, scroll its container first. Otherwise the element has no actionable frame; use a parent/child element with a frame or choose window-local coordinates from the latest screenshot. +- `element_not_enabled`: the element is disabled (its line lists `disabled`), so nothing was sent. Do what enables it first, then act once a fresh `get-app-state` no longer lists it as disabled. - `invalid_argument`: fix the command flags; do not retry the same command unchanged. - `action_timeout`: inspect current state before retrying, then use a simpler semantic action or `--no-screenshot` if observation is slow. - `verification_failed`: the write was read back and the element holds a different value, so the action failed. Run `get-app-state` to see which field changed. For editable text, click the intended field and confirm focus, select all (`cmd+a` on macOS, `ctrl+a` on Windows/Linux), then use `type-text` and inspect the resulting value instead of repeating `set-value`. diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 692505b818a..8f7e90423c3 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1191,7 +1191,8 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "- `unsupported_capability`: the provider or desktop environment cannot do that action; use a semantic alternative or install the missing dependency if the message names one.", "- `action_not_supported`: inspect the element's listed actions and retry with one of those names, or use click/set-value when appropriate.", "- `value_not_settable`: the element cannot accept direct value writes; focus it and use keyboard input only when the returned state can be inspected.", - "- `element_not_clickable`: the element has no actionable frame; use a parent/child element with a frame or choose window-local coordinates from the latest screenshot.", + "- `element_not_clickable`: no click was sent. If the message says the element is covered, deal with what covers it (a dialog, sheet or popover), then click again from a fresh `get-app-state`; never click by coordinates to get past the cover. If it is out of view, scroll its container first. Otherwise the element has no actionable frame; use a parent/child element with a frame or choose window-local coordinates from the latest screenshot.", + "- `element_not_enabled`: the element is disabled (its line lists `disabled`), so nothing was sent. Do what enables it first, then act once a fresh `get-app-state` no longer lists it as disabled.", "- `invalid_argument`: fix the command flags; do not retry the same command unchanged.", "- `action_timeout`: inspect current state before retrying, then use a simpler semantic action or `--no-screenshot` if observation is slow.", "- `verification_failed`: the write was read back and the element holds a different value, so the action failed. Run `get-app-state` to see which field changed. For editable text, click the intended field and confirm focus, select all (`cmd+a` on macOS, `ctrl+a` on Windows/Linux), then use `type-text` and inspect the resulting value instead of repeating `set-value`.", diff --git a/src/shared/computer-use-error-recovery.ts b/src/shared/computer-use-error-recovery.ts index ac43c974643..ee858c96dc6 100644 --- a/src/shared/computer-use-error-recovery.ts +++ b/src/shared/computer-use-error-recovery.ts @@ -72,10 +72,26 @@ export function computerUseErrorRecoveryData( 'Do not infer valid indexes from `elementCount` or reuse indexes after navigation, scrolling, focus changes, or delays.' ) case 'element_not_clickable': + if (message?.includes(' is covered by ')) { + return recoverWith( + 'Run `orca computer get-app-state --app --json` and deal with what covers the element first (answer or close the dialog, sheet or popover).', + 'Then click the element again using an index from the fresh tree; do not click by coordinates to get past the cover.' + ) + } + if (message?.includes(' out of view')) { + return recoverWith( + "Scroll the element's container with `orca computer scroll`, then run `orca computer get-app-state --app --json` and click the element using an index from the fresh tree." + ) + } return recoverWith( 'Choose a nearby parent or child element that has an actionable frame.', 'If using coordinates, derive window-local coordinates from the latest screenshot/state for the same target window.' ) + case 'element_not_enabled': + return recoverWith( + 'The element is disabled, so nothing was sent. Do what enables it first (for example fill required fields), then run `orca computer get-app-state --app --json` and act once its line no longer lists `disabled`.', + 'Do not retry the same action unchanged or click it by coordinates instead.' + ) case 'action_not_supported': return recoverWith( 'Inspect the element in a fresh `get-app-state` result and use one of its advertised secondary actions.', diff --git a/src/shared/computer-use-runtime-types.ts b/src/shared/computer-use-runtime-types.ts index ee3a38e260a..1b853a115dd 100644 --- a/src/shared/computer-use-runtime-types.ts +++ b/src/shared/computer-use-runtime-types.ts @@ -10,6 +10,7 @@ export const COMPUTER_ERROR_CODES = { permission_denied: 'permission_denied', element_not_found: 'element_not_found', element_not_clickable: 'element_not_clickable', + element_not_enabled: 'element_not_enabled', action_not_supported: 'action_not_supported', value_not_settable: 'value_not_settable', invalid_argument: 'invalid_argument', From e4f0bbbe02e7c14f85c1c0ef4671ad1568b6cb1f Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:25:08 -0800 Subject: [PATCH 06/44] fix(native-chat): Enter on the chosen answer confirms instead of deselecting (#41635) * fix(native-chat): Enter on the chosen answer confirms instead of deselecting In a single-select question without previews, Enter on the already-chosen row now does what the footer says (Next/Submit) rather than clearing the pick. Click, Space and digits still toggle; Enter on an unchosen row still picks and auto-advances; preview, free-text and confirm-button paths are unchanged. Replace the class-name assertions in the answer card test with behavior: focus without aria-pressed, and Skip becoming a button named Submit. * test(native-chat): Enter on the chosen last-step answer submits once * fix(native-chat): option rows handle Enter themselves, so async cards confirm too The async question card does not take focus, so the card-level key hook is off there and a native Enter on the chosen row clicked it off. Each option row now handles Enter (pick, or Next/Submit on the chosen single-select row) and prevents the native click; the hook keeps digits and arrows. Click, Space, digits and multi-select toggling are unchanged. Adds a test through the real async caller. * test(native-chat): drive async-card Enter through an enabled, focused row The send mock now reports the created message, so the returned row is enabled; assert it is enabled and focused before pressing Enter. --- .../prompts/NativeChatQuestionCard.test.tsx | 99 +++++++++++++++---- .../prompts/NativeChatQuestionCard.tsx | 8 +- .../prompts/NativeChatQuestionOption.tsx | 22 ++++- ...eChatStructuredAsyncQuestion.send.test.tsx | 42 ++++++++ .../prompts/use-native-chat-question-keys.ts | 9 +- 5 files changed, 147 insertions(+), 33 deletions(-) diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx index 10dddf73699..c9623b7a161 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx @@ -2,6 +2,7 @@ import { act } from 'react' import { createRoot } from 'react-dom/client' +import { getByRole, queryByRole } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { NativeChatQuestionCard } from './NativeChatQuestionCard' @@ -139,31 +140,87 @@ describe('NativeChatQuestionCard', () => { /> ) }) - act(() => vi.runAllTimers()) const rows = container.querySelectorAll('button[aria-pressed]') - const confirmButton = (): HTMLButtonElement => - [...container.querySelectorAll('button')].find((button) => - /^(Skip|Submit)/.test(button.textContent ?? '') - )! expect(document.activeElement).toBe(rows[0]) - // Focus is a ring only; the picked look (primary border, fill) is reserved for aria-pressed rows. - expect(rows[0]!.getAttribute('aria-pressed')).toBe('false') - expect(rows[0]!.className).not.toMatch(/(^|\s)(focus:)?bg-accent(\s|$)/) - expect(rows[0]!.parentElement!.className).not.toContain('border-primary') - expect(confirmButton().textContent).toBe('Skip') + expect([...rows].map((row) => row.getAttribute('aria-pressed'))).toEqual(['false', 'false']) + expect(getByRole(container, 'button', { name: 'Skip' })).toBeTruthy() act(() => rows[1]!.click()) + expect([...rows].map((row) => row.getAttribute('aria-pressed'))).toEqual(['false', 'true']) + // The Enter hint is aria-hidden, so the button is still named "Submit". + expect(getByRole(container, 'button', { name: 'Submit' })).toBeTruthy() + expect(queryByRole(container, 'button', { name: 'Skip' })).toBeNull() + }) + + it('confirms with Enter on the chosen single-select row instead of deselecting it', () => { + vi.useFakeTimers() + container.setAttribute('data-native-chat-root', 'true') + const onAnswer = vi.fn() + act(() => { + root.render( + {}} + shouldFocus + /> + ) + }) + const rows = (): HTMLButtonElement[] => [ + ...container.querySelectorAll('button[aria-pressed]') + ] + act(() => rows()[0]!.click()) + act(() => vi.runAllTimers()) + expect(rows()[0]!.textContent).toContain('Two') + + pressKey({ key: 'ArrowLeft' }, rows()[0]!) + expect(rows()[0]!.textContent).toContain('Tabs') + expect(rows()[0]!.getAttribute('aria-pressed')).toBe('true') + expect(getByRole(container, 'button', { name: 'Next' })).toBeTruthy() + act(() => rows()[0]!.focus()) + pressKey({ key: 'Enter' }, rows()[0]!) + act(() => vi.runAllTimers()) + expect(rows()[0]!.textContent).toContain('Two') + + pressKey({ key: 'ArrowLeft' }, rows()[0]!) + expect(rows()[0]!.getAttribute('aria-pressed')).toBe('true') + // Click still toggles the chosen row off. + act(() => rows()[0]!.click()) + expect(rows()[0]!.getAttribute('aria-pressed')).toBe('false') + expect(onAnswer).not.toHaveBeenCalled() + }) + it('submits with a second Enter on the last step instead of deselecting the pick', () => { + vi.useFakeTimers() + container.setAttribute('data-native-chat-root', 'true') + const onAnswer = vi.fn() + act(() => { + root.render( + {}} + shouldFocus + /> + ) + }) + const rows = container.querySelectorAll('button[aria-pressed]') + act(() => rows[1]!.focus()) + pressKey({ key: 'Enter' }, rows[1]!) expect(rows[1]!.getAttribute('aria-pressed')).toBe('true') - expect(rows[1]!.parentElement!.className).toContain('border-primary') - expect(rows[0]!.parentElement!.className).not.toContain('border-primary') - // The Enter hint is decoration; the button's name stays "Submit". - const submit = confirmButton() - expect(submit.querySelector('[aria-hidden]')?.textContent).toBe('↵') - expect( - [...submit.childNodes] - .filter((node) => !(node instanceof Element && node.hasAttribute('aria-hidden'))) - .map((node) => node.textContent) - .join('') - ).toBe('Submit') + // Before the auto-advance fires, Enter on the chosen row submits it. + pressKey({ key: 'Enter' }, rows[1]!) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [1], other: '' }]) + act(() => vi.runAllTimers()) + expect(onAnswer).toHaveBeenCalledTimes(1) }) }) diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx index 0cfef61f3a3..a9ecedd7c5e 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx @@ -158,8 +158,8 @@ export function NativeChatQuestionCard({ } } - // Briefly show a single-select pick before advancing; picking again retracts it. With previews, - // a pick stays put: a digit focuses its row, and Enter on the chosen row confirms. + // Briefly show a single-select pick before advancing; clicking it again retracts it, while Enter on + // the chosen row confirms. With previews, a pick stays put and a digit only focuses its row. const pickOption = ( optionIndex: number, via: 'pointer' | 'digit' | 'enter' = 'pointer' @@ -171,7 +171,8 @@ export function NativeChatQuestionCard({ ?.querySelectorAll('button[aria-pressed]') [optionIndex]?.focus() } - if (showsPreviews && cur.includes(optionIndex)) { + // Enter on a chosen single-select row does what the footer says (Next/Submit), never deselects. + if (cur.includes(optionIndex) && (showsPreviews || (via === 'enter' && !q.multiSelect))) { if (via === 'enter') { confirm(true) } @@ -322,6 +323,7 @@ export function NativeChatQuestionCard({ selected={(selections[index] ?? []).includes(i)} disabled={isSubmitting} onSelect={() => pickOption(i)} + onEnter={() => pickOption(i, 'enter')} /> ))} diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx index c1aa703cf76..8ac95ad2520 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx @@ -14,7 +14,8 @@ export function NativeChatQuestionOption({ preview, selected, disabled, - onSelect + onSelect, + onEnter }: { badge: string initialFocus: boolean @@ -25,6 +26,8 @@ export function NativeChatQuestionOption({ selected: boolean disabled: boolean onSelect: () => void + /** Enter on the row: the card picks it, or confirms when it is the chosen single-select row. */ + onEnter: () => void }): React.JSX.Element { return ( // The tile wraps the row and its preview, so the preview reads as part of the picked option. @@ -40,6 +43,23 @@ export function NativeChatQuestionOption({ type="button" disabled={disabled} onClick={onSelect} + // On the row, not the card's key hook, so Enter works when the card did not take focus; + // preventDefault stops the native Enter click from toggling the row instead. + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) { + return + } + event.preventDefault() + if ( + !event.repeat && + !event.metaKey && + !event.ctrlKey && + !event.altKey && + !event.shiftKey + ) { + onEnter() + } + }} aria-pressed={selected} data-native-chat-prompt-card-focus-target={initialFocus || undefined} // Focus is an inset ring, never the selected fill, so the row that opens focused does not read as picked. diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatStructuredAsyncQuestion.send.test.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatStructuredAsyncQuestion.send.test.tsx index f3a3b828e1e..bdb3af60892 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatStructuredAsyncQuestion.send.test.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatStructuredAsyncQuestion.send.test.tsx @@ -133,4 +133,46 @@ describe('async question send ownership', () => { ) ).toBe(true) }) + it('submits with Enter on the chosen option even though the async card does not take focus', () => { + const send = vi.fn((_text, _images, request) => { + request?.onCreated?.(send.mock.calls.length === 1 ? 'answer' : 'retry') + return true + }) + const render = (submissions: AgentJournalSubmission[] = []) => + act(() => + root.render( + + ) + ) + const blue = () => + [...container.querySelectorAll('button[aria-pressed]')].find((node) => + node.textContent?.includes('Blue') + )! + render() + act(() => blue().dispatchEvent(new MouseEvent('click', { bubbles: true }))) + act(() => vi.advanceTimersByTime(200)) + expect(send).toHaveBeenCalledTimes(1) + // The first delivery is uncertain, so the card comes back with Blue still chosen. + render([{ ...pendingAnswer, dispatchState: 'unknown' }]) + expect(blue().getAttribute('aria-pressed')).toBe('true') + // A real keyboard user can reach the row: it is enabled and holds focus. + expect(blue().disabled).toBe(false) + act(() => blue().focus()) + expect(document.activeElement).toBe(blue()) + const enter = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }) + act(() => { + blue().dispatchEvent(enter) + }) + // Enter submits like the footer's Submit; it neither deselects nor lets the native click run. + expect(enter.defaultPrevented).toBe(true) + expect(send).toHaveBeenCalledTimes(2) + expect(blue().getAttribute('aria-pressed')).toBe('true') + }) }) diff --git a/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts b/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts index 41799448529..28ef126efc0 100644 --- a/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts +++ b/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts @@ -7,7 +7,7 @@ export function useNativeChatQuestionKeys( cardRef: RefObject, enabled: boolean, optionCount: number, - onPick: (optionIndex: number, via: 'digit' | 'enter') => void, + onPick: (optionIndex: number, via: 'digit') => void, onStep: (delta: 1 | -1) => boolean ): void { const onKeyDown = useEffectEvent((event: KeyboardEvent): void => { @@ -36,10 +36,6 @@ export function useNativeChatQuestionKeys( event.altKey || (event.shiftKey && !isNumberKey) ) { - // Prevent the button's native Enter click from bypassing the shortcut guard. - if (event.key === 'Enter' && focusedIndex !== -1) { - event.preventDefault() - } return } if (isNumberKey) { @@ -80,9 +76,6 @@ export function useNativeChatQuestionKeys( if (onStep(event.key === 'ArrowRight' ? 1 : -1)) { event.preventDefault() } - } else if (event.key === 'Enter' && focusedIndex !== -1) { - event.preventDefault() - onPick(focusedIndex, 'enter') } }) useEffect(() => { From 3bec2aa636f7a5f4ddd6ae1175946ea035c85c05 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:27:23 -0800 Subject: [PATCH 07/44] fix(source-control): keep merged reviews visible after an equivalent local rebase (#41100) * fix(source-control): keep merged reviews visible after an equivalent local rebase * fix(source-control): retry proofs after fetching missing review heads * fix(source-control): compare merged-review deltas without decoding * fix(source-control): retry unproven equivalence after history fetches --- .../client/lookup/branch-lookup-resolution.ts | 13 +- .../refresh/merged-pr-head-membership.ts | 38 ++++ .../merge-requests/merge-request-lookup.ts | 1 + .../merged-mr-commit-membership.ts | 16 +- ...d-review-head-equivalence-real-git.test.ts | 207 ++++++++++++++++++ .../merged-review-head-equivalence.ts | 164 ++++++++++++++ 6 files changed, 434 insertions(+), 5 deletions(-) create mode 100644 src/main/github/pull-requests/refresh/merged-pr-head-membership.ts create mode 100644 src/main/source-control/merged-review-head-equivalence-real-git.test.ts create mode 100644 src/main/source-control/merged-review-head-equivalence.ts diff --git a/src/main/github/client/lookup/branch-lookup-resolution.ts b/src/main/github/client/lookup/branch-lookup-resolution.ts index aa09c96bbd6..6483362fb30 100644 --- a/src/main/github/client/lookup/branch-lookup-resolution.ts +++ b/src/main/github/client/lookup/branch-lookup-resolution.ts @@ -1,7 +1,7 @@ import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import type { ghRepoExecOptions } from '../../repositories/github-repository-identity' import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' -import { isCommitPartOfMergedPR } from '../../pull-requests/refresh/merged-pr-commit-membership' +import { mergedPRHeadMembership } from '../../pull-requests/refresh/merged-pr-head-membership' import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo' import { shouldHideNonOpenReviewOnDefaultBranch } from '../../../source-control/repo-default-branch' import { getGitHubApiRepositoryForRemote } from '../../repositories/github-api-repository-remote-probe' @@ -99,11 +99,16 @@ export async function resolvePRForBranchOutcome(input: { if (!candidateRepo || !headOid) { return 'unknown' } - const membership = await isCommitPartOfMergedPR({ + const membership = await mergedPRHeadMembership({ ownerRepo: candidateRepo, prNumber: candidate.number, - commitOid: headOid, - ghOptions + prHeadOid: candidate.headRefOid, + baseRefName: candidate.baseRefName, + headOid, + ghOptions, + repoPath, + connectionId, + localGitOptions }) if (membership === 'contained') { confirmedContainedHeadOid = headOid diff --git a/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts b/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts new file mode 100644 index 00000000000..26a9d1da6bd --- /dev/null +++ b/src/main/github/pull-requests/refresh/merged-pr-head-membership.ts @@ -0,0 +1,38 @@ +import type { GitHubRepositoryIdentity as OwnerRepo } from '../../../../shared/github/repositories/repository-identity' +import type { GitHubRepoExecOptions } from '../../repositories/github-api-repository' +import type { HostedReviewLocalGitOptions } from '../../../source-control/hosted-review-git-options' +import { isCommitPartOfMergedPR } from './merged-pr-commit-membership' +import type { MergedReviewCommitMembership as MergedPRCommitMembership } from '../../../source-control/merged-review-membership-memo' +import { mergedReviewHeadIsEquivalent } from '../../../source-control/merged-review-head-equivalence' + +/** PR-history membership, or a local proof that HEAD is an equivalent rebase GitHub never saw. */ +export async function mergedPRHeadMembership(args: { + ownerRepo: OwnerRepo + prNumber: number + prHeadOid: string | undefined + baseRefName: string | undefined + headOid: string + ghOptions: GitHubRepoExecOptions + repoPath: string + connectionId?: string | null + localGitOptions: HostedReviewLocalGitOptions +}): Promise { + const membership = await isCommitPartOfMergedPR({ + ownerRepo: args.ownerRepo, + prNumber: args.prNumber, + commitOid: args.headOid, + ghOptions: args.ghOptions + }) + if (membership === 'contained') { + return membership + } + const equivalent = await mergedReviewHeadIsEquivalent({ + repoPath: args.repoPath, + connectionId: args.connectionId, + localGitOptions: args.localGitOptions, + reviewHeadOid: args.prHeadOid, + baseBranchName: args.baseRefName, + headOid: args.headOid + }) + return equivalent ? 'contained' : membership +} diff --git a/src/main/gitlab/merge-requests/merge-request-lookup.ts b/src/main/gitlab/merge-requests/merge-request-lookup.ts index 616f1abcd11..bb946ecc0e6 100644 --- a/src/main/gitlab/merge-requests/merge-request-lookup.ts +++ b/src/main/gitlab/merge-requests/merge-request-lookup.ts @@ -230,6 +230,7 @@ export async function getMergeRequestForBranch( iid: info.number, headOid: currentHead, revisionHeadSha: info.headSha, + baseRefName: info.baseRefName, diffRefs: raw.diff_refs, connectionId, localGitOptions, diff --git a/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts b/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts index 864f846944e..ca6ed0095d8 100644 --- a/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts +++ b/src/main/gitlab/merge-requests/merged-mr-commit-membership.ts @@ -11,6 +11,7 @@ import { glabHostnameArgs, glabRepoExecOptions } from '../projects/gitlab-projec import type { LocalGitExecOptions } from '../projects/gitlab-known-host-probe' import type { ProjectRef } from '../projects/project-ref-parser' import { encodedProject } from '../projects/project-path-encoding' +import { mergedReviewHeadIsEquivalent } from '../../source-control/merged-review-head-equivalence' const membershipMemo = new MergedReviewMembershipMemo>({ weight: (ids) => 1024 + 256 * ids.size, @@ -87,6 +88,7 @@ export async function mergedMRContainsHead( iid: number headOid: string revisionHeadSha?: string + baseRefName?: string diffRefs?: unknown userRefresh?: boolean } @@ -142,5 +144,17 @@ export async function mergedMRContainsHead( load, { refreshFailed: args.userRefresh } ) - return ids.has(args.headOid.toLowerCase()) ? 'contained' : 'not-contained' + if (ids.has(args.headOid.toLowerCase())) { + return 'contained' + } + // A local rebase mints a SHA GitLab never saw; prove it adds nothing beyond the merged MR. + const equivalent = await mergedReviewHeadIsEquivalent({ + repoPath: args.repoPath, + connectionId: args.connectionId, + localGitOptions: args.localGitOptions, + reviewHeadOid: args.revisionHeadSha, + baseBranchName: args.baseRefName, + headOid: args.headOid + }) + return equivalent ? 'contained' : 'not-contained' } diff --git a/src/main/source-control/merged-review-head-equivalence-real-git.test.ts b/src/main/source-control/merged-review-head-equivalence-real-git.test.ts new file mode 100644 index 00000000000..d2cf8090963 --- /dev/null +++ b/src/main/source-control/merged-review-head-equivalence-real-git.test.ts @@ -0,0 +1,207 @@ +import { runProcessSync } from '@orca/process-host' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { mergedReviewHeadIsEquivalent } from './merged-review-head-equivalence' +import { getLocalGitCapabilityCache } from '../git/command-runner/host-routing/git-capability-state' +import { isUnsupportedMergeTreeWriteTreeError } from '../../shared/git/branches/git-merge-tree-capability' + +describe('merged review head equivalence (real Git)', () => { + let repoPath = '' + const gitWithInput = (args: string[], input?: string | Uint8Array, cwd = repoPath): string => { + const result = runProcessSync({ program: 'git', args, cwd, input }) + if (result.code !== 0) { + throw new Error(result.stderr) + } + return result.stdout.trim() + } + const git = (...args: string[]): string => gitWithInput(args) + const commit = (file: string, content: string, message: string): string => { + writeFileSync(join(repoPath, file), content) + git('add', file) + git('commit', '--quiet', '-m', message) + return git('rev-parse', 'HEAD') + } + const prove = (reviewHeadOid: string, headOid: string, connectionId?: string) => + mergedReviewHeadIsEquivalent({ + repoPath, + connectionId, + localGitOptions: {}, + reviewHeadOid, + baseBranchName: 'main', + headOid + }) + + beforeEach(() => { + repoPath = mkdtempSync(join(tmpdir(), 'orca-merged-review-equivalence-')) + git('init', '--quiet') + git('symbolic-ref', 'HEAD', 'refs/heads/main') + git('config', 'user.name', 'Orca Test') + git('config', 'user.email', 'orca@example.test') + git('config', 'commit.gpgSign', 'false') + git('config', 'core.hooksPath', '.git/no-hooks') + commit('shared.txt', 'a\nb\nc\nd\ne\nf\n', 'base') + }) + + afterEach(() => { + rmSync(repoPath, { recursive: true, force: true }) + }) + + // Review edits line 1; main later edits line 6 of the same file, then the branch is rebased locally. + function rebasedReview(reviewFile = 'shared.txt'): { reviewHead: string; rebasedHead: string } { + git('checkout', '--quiet', '-b', 'feature') + const reviewHead = commit(reviewFile, 'A\nb\nc\nd\ne\nf\n', 'review') + git('checkout', '--quiet', 'main') + commit('shared.txt', 'a\nb\nc\nd\ne\nF\n', 'upstream change') + git('update-ref', 'refs/remotes/origin/main', 'HEAD') + git('checkout', '--quiet', 'feature') + git('rebase', '--quiet', 'origin/main') + return { reviewHead, rebasedHead: git('rev-parse', 'HEAD') } + } + + function shallowRebasedReview() { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + git('branch', 'review', reviewHead) + const shallowPath = join(repoPath, 'shallow') + git('init', '--quiet', shallowPath) + const fetch = (depth: string) => + gitWithInput( + [ + 'fetch', + '--quiet', + depth, + pathToFileURL(repoPath).href, + '+refs/heads/main:refs/remotes/origin/main', + '+refs/heads/review:refs/remotes/origin/review', + '+refs/heads/feature:refs/remotes/origin/feature' + ], + undefined, + shallowPath + ) + fetch('--depth=1') + return { + request: { + repoPath: shallowPath, + localGitOptions: {}, + reviewHeadOid: reviewHead, + baseBranchName: 'main', + headOid: rebasedHead + }, + deepen: () => fetch('--unshallow') + } + } + + it('proves a rebase when main edited the same file on Git with write-tree support', async ({ + skip + }) => { + const { reviewHead, rebasedHead } = rebasedReview() + try { + git('merge-tree', '--write-tree', 'origin/main', reviewHead) + } catch (error) { + if (isUnsupportedMergeTreeWriteTreeError(error)) { + skip() + } + throw error + } + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + }) + + it('proves a separate-file rebase through the older-Git exact-diff fallback', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + const capabilities = getLocalGitCapabilityCache({ cwd: repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + const extraHead = commit('local.txt', 'unpushed\n', 'local work') + await expect(prove(reviewHead, extraHead)).resolves.toBe(false) + } finally { + capabilities.clear() + } + }) + + it('refuses distinct non-UTF-8 paths with identical blobs in the older-Git fallback', async () => { + const base = git('rev-parse', 'HEAD') + const blob = gitWithInput(['hash-object', '-w', '--stdin'], 'review content\n') + const tree = (pathByte: number) => + gitWithInput( + ['mktree', '-z'], + Buffer.concat([Buffer.from(`100644 blob ${blob}\tpath-`), Buffer.from([pathByte, 0])]) + ) + const reviewHead = git('commit-tree', tree(0xff), '-p', base, '-m', 'review') + const localHead = git('commit-tree', tree(0xfe), '-p', base, '-m', 'local rename') + git('update-ref', 'refs/remotes/origin/main', base) + const capabilities = getLocalGitCapabilityCache({ cwd: repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(prove(reviewHead, localHead)).resolves.toBe(false) + } finally { + capabilities.clear() + } + }) + + it('retries a same-commit proof after shallow history is deepened', async () => { + const { request, deepen } = shallowRebasedReview() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(false) + deepen() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(true) + }) + + it('retries a same-commit proof after deepening through the older-Git fallback', async () => { + const { request, deepen } = shallowRebasedReview() + const capabilities = getLocalGitCapabilityCache({ cwd: request.repoPath }) + capabilities.rememberUnsupported('merge-tree-write-tree') + try { + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(false) + deepen() + await expect(mergedReviewHeadIsEquivalent(request)).resolves.toBe(true) + } finally { + capabilities.clear() + } + }) + + it('rechecks a cached proof after the remote base is rewritten', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + git('update-ref', 'refs/remotes/origin/main', 'main^') + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(false) + }) + + it('retries after a missing review commit becomes available', async () => { + const { reviewHead, rebasedHead } = rebasedReview('feature.txt') + const objectPath = join( + repoPath, + '.git', + 'objects', + reviewHead.slice(0, 2), + reviewHead.slice(2) + ) + const object = readFileSync(objectPath) + rmSync(objectPath) + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(false) + writeFileSync(objectPath, object) + await expect(prove(reviewHead, rebasedHead)).resolves.toBe(true) + }) + + it('refuses a rebased head that carries extra work', async () => { + const { reviewHead } = rebasedReview() + const extraHead = commit('local.txt', 'unpushed\n', 'local work') + await expect(prove(reviewHead, extraHead)).resolves.toBe(false) + }) + + it('refuses a reused branch name whose head is just main with the review merged', async () => { + git('checkout', '--quiet', '-b', 'feature') + const reviewHead = commit('shared.txt', 'A\nb\nc\nd\ne\nf\n', 'review') + git('checkout', '--quiet', 'main') + git('merge', '--quiet', '--squash', 'feature') + git('commit', '--quiet', '-m', 'squash') + git('update-ref', 'refs/remotes/origin/main', 'HEAD') + await expect(prove(reviewHead, git('rev-parse', 'HEAD'))).resolves.toBe(false) + }) + + it('does not probe an SSH repository path on this host', async () => { + const { reviewHead, rebasedHead } = rebasedReview() + await expect(prove(reviewHead, rebasedHead, 'ssh-connection')).resolves.toBe(false) + }) +}) diff --git a/src/main/source-control/merged-review-head-equivalence.ts b/src/main/source-control/merged-review-head-equivalence.ts new file mode 100644 index 00000000000..f9771f5cbdb --- /dev/null +++ b/src/main/source-control/merged-review-head-equivalence.ts @@ -0,0 +1,164 @@ +import { gitExecFileAsync, gitExecFileAsyncBuffer } from '../git/command-runner/git-exec-file' +import { gitOptionsForWorktree } from '../git/command-runner/git-runtime-options' +import { createLocalGitObjectQuarantine } from '../git/objects/local-git-object-quarantine' +import { withLocalGitCapabilityCacheForExecution } from '../git/command-runner/host-routing/git-capability-state' +import { isUnsupportedMergeTreeWriteTreeError } from '../../shared/git/branches/git-merge-tree-capability' +import { MergedReviewMembershipMemo } from './merged-review-membership-memo' +import type { HostedReviewLocalGitOptions } from './hosted-review-git-options' + +type Proof = 'equivalent' | 'unproven' + +const BASE_REMOTES = ['origin', 'upstream'] +const GIT_OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ +// A fetch can make an unproven result provable without changing any commit IDs. +const proofMemo = new MergedReviewMembershipMemo({ + weight: () => 1, + maxWeight: 200, + ttl: (proof) => (proof === 'equivalent' ? 6 * 60 * 60_000 : 0) +}) + +/** + * True when HEAD is a remote base commit plus exactly the merged review's changes (an equivalent + * rebase), so the workspace holds no work beyond the merged review. Unprovable cases return false. + */ +export async function mergedReviewHeadIsEquivalent(args: { + repoPath: string + connectionId?: string | null + localGitOptions: HostedReviewLocalGitOptions + reviewHeadOid: string | undefined + baseBranchName: string | undefined + headOid: string +}): Promise { + const reviewHead = args.reviewHeadOid?.trim().toLowerCase() ?? '' + const head = args.headOid.trim().toLowerCase() + const baseBranch = args.baseBranchName?.trim() ?? '' + // SSH repo paths live on the remote host, which runs its own lookup with local Git. + if ( + args.connectionId || + !GIT_OBJECT_ID.test(reviewHead) || + !GIT_OBJECT_ID.test(head) || + reviewHead === head || + !baseBranch || + baseBranch.startsWith('-') + ) { + return false + } + try { + const gitOptions = { + ...gitOptionsForWorktree(args.repoPath, args.localGitOptions), + timeout: 10_000 + } + // Missing review objects may arrive on the next fetch; do not retain that inconclusive result. + await gitExecFileAsync(['cat-file', '-e', `${reviewHead}^{commit}`], gitOptions) + const baseTips: string[] = [] + for (const remote of BASE_REMOTES) { + try { + const { stdout } = await gitExecFileAsync( + ['rev-parse', '--verify', `refs/remotes/${remote}/${baseBranch}^{commit}`], + gitOptions + ) + const tip = stdout.trim() + if (GIT_OBJECT_ID.test(tip)) { + baseTips.push(tip) + } + } catch { + // Missing remote bases cannot establish equivalence. + } + } + const key = JSON.stringify([ + args.localGitOptions.wslDistro ?? null, + args.repoPath, + baseTips, + reviewHead, + head + ]) + const proof = await proofMemo.read(key, async () => { + try { + return await proveEquivalence( + args.repoPath, + args.localGitOptions, + reviewHead, + baseTips, + head + ) + } catch { + return 'unproven' + } + }) + return proof === 'equivalent' + } catch { + return false + } +} + +async function proveEquivalence( + repoPath: string, + localGitOptions: HostedReviewLocalGitOptions, + reviewHead: string, + baseTips: string[], + head: string +): Promise { + const gitOptions = { ...gitOptionsForWorktree(repoPath, localGitOptions), timeout: 10_000 } + const read = async (argv: string[]) => (await gitExecFileAsync(argv, gitOptions)).stdout.trim() + const headTree = await read(['rev-parse', '--verify', `${head}^{tree}`]) + for (const baseTip of baseTips) { + let base: string + try { + base = await read(['merge-base', head, baseTip]) + } catch { + continue + } + // A base with HEAD's tree means HEAD adds nothing itself, e.g. a reused branch name at main. + if (!GIT_OBJECT_ID.test(base) || (await read(['rev-parse', `${base}^{tree}`])) === headTree) { + continue + } + const proven = await withLocalGitCapabilityCacheForExecution( + { cwd: repoPath, wslDistro: localGitOptions.wslDistro }, + (capabilities) => + capabilities.runWithFallback( + 'merge-tree-write-tree', + async () => { + const run = (env: NodeJS.ProcessEnv | undefined) => + gitExecFileAsync(['merge-tree', '--write-tree', base, reviewHead], { + ...gitOptions, + ...(env ? { env } : {}) + }) + try { + // Quarantine the throwaway merged tree; probe support before older Git sees a quarantine. + const { stdout } = capabilities.isKnownSupported('merge-tree-write-tree') + ? await createLocalGitObjectQuarantine(repoPath, localGitOptions).run(run) + : await run(undefined) + return stdout.split('\n', 1)[0].trim() === headTree + } catch (error) { + if (isUnsupportedMergeTreeWriteTreeError(error)) { + throw error + } + // Conflicts and missing review objects cannot prove equivalence. + return false + } + }, + // Git < 2.38: exact per-path mode/blob transitions only match when base never touched them. + async () => { + const reviewBase = await read(['merge-base', reviewHead, base]) + const delta = async (from: string, to: string) => + ( + await gitExecFileAsyncBuffer( + ['diff-tree', '-r', '-z', '--no-abbrev', '--no-renames', from, to], + gitOptions + ) + ).stdout + const [reviewDelta, headDelta] = await Promise.all([ + delta(reviewBase, reviewHead), + delta(base, head) + ]) + return reviewDelta.length > 0 && reviewDelta.equals(headDelta) + }, + isUnsupportedMergeTreeWriteTreeError + ) + ) + if (proven) { + return 'equivalent' + } + } + return 'unproven' +} From 55f3e12e6aa26e272c6b369a8ff378cde7f59a03 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 12 Nov 2026 13:31:54 -0800 Subject: [PATCH 08/44] test: remove plugin policy inventories and generated equality check (#41662) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../plugin-language-pack-artifact.test.ts | 102 ------------------ .../plugin-vm-recipe-artifact.test.ts | 10 -- .../authoring/plugin-host-typings.test.ts | 11 -- 3 files changed, 123 deletions(-) diff --git a/src/shared/plugins/artifacts/plugin-language-pack-artifact.test.ts b/src/shared/plugins/artifacts/plugin-language-pack-artifact.test.ts index 1dc367127a7..5b43092b0d4 100644 --- a/src/shared/plugins/artifacts/plugin-language-pack-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-language-pack-artifact.test.ts @@ -44,96 +44,6 @@ describe('plugin language-pack artifacts', () => { ).toMatchObject({ ok: false, error: expect.stringContaining('protected security copy') }) }) - it.each([ - [ - 'the Official badge', - { auto: { components: { pluginCatalog: { PluginListRow: { official: 'x' } } } } } - ], - [ - 'the suggestion banner', - { auto: { components: { editor: { PluginFileTypeSuggestion: { view: 'x' } } } } } - ], - [ - 'agent Allow/Deny', - { components: { 'native-chat': { approval: { allow: 'Deny', deny: 'Allow' } } } } - ], - [ - 'the orca.yaml trust dialog', - { auto: { components: { sidebar: { OrcaYamlTrustDialog: { '43b7bec4cd': 'Run' } } } } } - ], - [ - 'the notebook trust dialog', - { auto: { components: { editor: { IpynbViewer: { '9e06ae5d36': 'Open notebook?' } } } } } - ], - ['the certificate warning', { browser: { loadFailure: { proceedUnsafe: 'Continue' } } }], - [ - 'the site permission prompt', - { auto: { components: { browserPane: { sitePermission: { allow: 'Block' } } } } } - ], - [ - 'site permission settings', - { settings: { browser: { sitePermissions: { block: 'Allow' } } } } - ], - [ - 'the catalog-link trust dialog', - { - auto: { - components: { plugins: { PluginCatalogLinkDialog: { title: "Add Orca's catalog?" } } } - } - } - ], - [ - 'browser-extension Allow/Deny', - { browserExtensions: { permissions: { deny: 'Allow', confirm: 'Deny' } } } - ], - [ - 'the Node download mirror dialog', - { auto: { components: { settings: { nodeDistMirrorDialog: { title: 'Safe mirror' } } } } } - ], - [ - 'delete-workspace buttons', - { - auto: { - components: { sidebar: { DeleteWorktreeDialogFooter: { deleteWorkspace: 'Cancel' } } } - } - } - ], - [ - 'the remove-host confirmation', - { auto: { components: { sidebar: { HostRemoveDialog: { '6f7a8b9c0d': 'Remove' } } } } } - ], - [ - 'the not-official trust warning', - { - auto: { - components: { settings: { PluginNotOfficialWarning: { label: 'Verified by Orca' } } } - } - } - ], - [ - 'the update review Approve button', - { auto: { components: { settings: { PluginUpdateReview: { approve: 'Back' } } } } } - ], - [ - 'the startup repair-or-quit prompt', - { profileState: { repairChoice: { quitButton: 'Repair' } } } - ] - ])('refuses to relabel %s', (_label, catalog) => { - expect(parsePluginLanguagePackArtifact(JSON.stringify(catalog))).toMatchObject({ - ok: false, - error: expect.stringContaining('protected security copy') - }) - }) - - it.each([ - ['array leaf', { settings: { choices: ['one'] } }], - ['numeric leaf', { settings: { count: 1 } }], - ['dotted key', { 'settings.title': 'Title' }], - ['prototype key', JSON.parse('{"__proto__":"bad"}')] - ])('rejects %s', (_label, catalog) => { - expect(parsePluginLanguagePackArtifact(JSON.stringify(catalog)).ok).toBe(false) - }) - describe('string limits', () => { const english = englishSourceLookup({ common: { retry: 'Retry', detail: 'Line one\nLine two' }, @@ -142,18 +52,6 @@ describe('plugin language-pack artifacts', () => { const parse = (catalog: unknown, strictness?: 'strict' | 'tolerant') => parsePluginLanguagePackArtifact(JSON.stringify(catalog), strictness, english) - it.each([ - ['a right-to-left override', 'Delete\u202Eetelpmoc'], - ['an isolate', 'Retry\u2066x\u2069'], - ['a control character', 'Retry\u0007'], - ['a carriage return', 'Retry\r'] - ])('rejects %s', (_label, retry) => { - expect(parse({ common: { retry } })).toMatchObject({ - ok: false, - error: expect.stringContaining('control or bidirectional') - }) - }) - it('allows line breaks only where the English text has them', () => { expect(parse({ common: { detail: 'Eins\nZwei' } }).ok).toBe(true) expect(parse({ common: { retry: 'Run this first:\ncurl x | sh' } })).toMatchObject({ diff --git a/src/shared/plugins/artifacts/plugin-vm-recipe-artifact.test.ts b/src/shared/plugins/artifacts/plugin-vm-recipe-artifact.test.ts index e52090e7681..64f9b041c92 100644 --- a/src/shared/plugins/artifacts/plugin-vm-recipe-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-vm-recipe-artifact.test.ts @@ -41,14 +41,4 @@ describe('plugin VM recipe artifacts', () => { expect(recipe).toMatchObject({ destroyDisabled: true }) expect(recipe.destroy).toBeUndefined() }) - - it('rejects NUL bytes and commands beyond the bounded artifact contract', () => { - for (const create of ['bad\0command', 'x'.repeat(32 * 1024 + 1)]) { - expect(() => - parsePluginVmRecipeArtifact( - JSON.stringify({ schemaVersion: 1, id: 'bounded', name: 'Bounded', create }) - ) - ).toThrow() - } - }) }) diff --git a/src/shared/plugins/authoring/plugin-host-typings.test.ts b/src/shared/plugins/authoring/plugin-host-typings.test.ts index 9b70116099d..4c67d401d84 100644 --- a/src/shared/plugins/authoring/plugin-host-typings.test.ts +++ b/src/shared/plugins/authoring/plugin-host-typings.test.ts @@ -1,14 +1,9 @@ -import { readFileSync } from 'node:fs' -import path from 'node:path' import { describe, expect, it } from 'vitest' -import { PLUGIN_HOST_TYPINGS_FILE, renderPluginHostTypings } from './plugin-host-typings' import { authorTypingsDiagnostics, authorTypingsProgram } from './plugin-author-typings.test-fixture' -const REPO_ROOT = path.resolve(import.meta.dirname, '../../../..') - // One contract, declared once and read by the frame, the worker and the components panel. const PROTOCOL = ` export type Todo = { id: string; title: string; done: boolean } @@ -159,12 +154,6 @@ host.dispose() ` describe('author typings', () => { - it('checks in the host typings generated from the host API table', () => { - const checkedIn = readFileSync(path.join(REPO_ROOT, PLUGIN_HOST_TYPINGS_FILE), 'utf8') - // Run `pnpm generate:plugin-author-typings` when this fails. - expect(checkedIn).toBe(renderPluginHostTypings()) - }) - it('type-check a frame script, a worker main and a components panel', () => { const program = authorTypingsProgram({ 'protocol.ts': PROTOCOL, From 0664f1c9bb1c9bd96163266f115de606a184a9c9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:32:43 -0800 Subject: [PATCH 09/44] fix: hide deleted workspaces while background cleanup finishes (#41483) * Retire workspaces after durable removal acceptance * Refuse plugin fallback into retiring workspaces * Complete plugin workspace test fixture identity * Restore removal helper bindings and complete test doubles * Configure durable removal storage in runtime test fixtures * Initialize durable removal fixtures before exercising cleanup * Preserve descendants and explicit parent choices during removal * Guard cached lineage traversal against catalog rescans * Explain cleanup ownership before workspace name fallbacks * Match automatic branch handling for empty overrides * Use valid optional removal facts in traversal fixtures --- .../worktree-add-pending-removal.test.ts | 31 ++- src/main/ipc/worktree-metadata-merge.ts | 2 + src/main/ipc/worktree-remote.ts | 26 ++- .../register-worktree-removal-handlers.ts | 28 ++- .../remove-registered-local-worktree.ts | 16 +- .../orca-runtime-test-lifecycle.spec.ts | 13 +- ...removal-and-reconciliation-part-03.spec.ts | 3 +- .../worktree-removal-failed-retry.spec.ts | 20 +- .../worktree-rm-cli.integration.test.ts | 206 ++++++++++++++++++ ...worktree-removal-marker-projection.test.ts | 123 +++++++++++ .../repo-worktree-row-resolution.test.ts | 115 ++++++++++ .../catalog/repo-worktree-row-resolution.ts | 41 ++-- .../runtime-branch-reuse-real-git.test.ts | 98 ++++++++- ...runtime-local-worktree-create-candidate.ts | 29 ++- .../runtime-worktree-lineage-controller.ts | 4 + .../runtime-worktree-ps-summaries.ts | 2 + ...time-failed-local-worktree-removal.test.ts | 17 +- ...ntime-registered-local-worktree-removal.ts | 16 +- .../workspaces/removal/workspace-removal.ts | 14 +- ...orktree-background-removal-records.test.ts | 174 ++++++++++++++- .../worktree-background-removal.test.ts | 37 ++-- .../removal/worktree-background-removal.ts | 148 +++++-------- .../removal/worktree-failed-removal.test.ts | 17 +- .../removal/worktree-removal-failure.ts | 8 +- .../removal/worktree-removal-leftover.ts | 7 +- .../removal/worktree-removal-listing.ts | 59 ++++- .../removal/worktree-removal-records.ts | 12 +- .../removal/worktree-removal-reservations.ts | 65 ++++++ .../removal/worktree-removal-settlement.ts | 82 +++++++ .../removal/worktree-removal-table.ts | 45 +++- .../cmd-j/palette-filter-options.ts | 3 +- .../cmd-j/task-search-activation.ts | 3 +- .../ComposerParentWorktreePicker.test.tsx | 43 +++- .../ComposerParentWorktreePicker.tsx | 15 +- .../view/plugin-view-editor-workspace.test.ts | 82 +++++++ .../view/plugin-view-editor-workspace.ts | 31 ++- .../view/plugin-view-workspace-pick.ts | 5 +- ...older-workspace-attached-worktrees.test.ts | 153 ++++++++++++- .../folder-workspace-attached-worktrees.ts | 15 +- .../parenting/worktree-parent-candidates.ts | 5 +- .../listing/desktop-workspace-row-facts.ts | 3 +- .../worktree-jump-palette-create-worktree.ts | 2 + .../linear-issue-workspace-attachment.ts | 4 +- .../active-worktree-removal-successor.test.ts | 19 ++ .../active-worktree-removal-successor.ts | 46 ++++ .../activation/worktree-activation.ts | 3 +- .../worktrees/worktree-palette-search.ts | 7 +- .../worktree-create-parent-pick.test.ts | 54 +++++ .../create/worktree-create-parent-pick.ts | 10 +- src/shared/runtime-worktree-contracts.ts | 2 + src/shared/sidebar-list/paired-server-rows.ts | 9 + .../sidebar-list/sidebar-feed-rows.test.ts | 73 ++++++- .../sidebar-list/sidebar-feed-worktrees.ts | 6 + src/shared/sidebar-list/visible-worktrees.ts | 11 +- src/shared/sidebar-list/workspace-rows.ts | 6 + src/shared/worktree/removal-visibility.ts | 8 + src/shared/worktree/removal.ts | 2 +- src/shared/worktree/types.ts | 6 +- 58 files changed, 1822 insertions(+), 262 deletions(-) create mode 100644 src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts create mode 100644 src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts create mode 100644 src/main/workspaces/removal/worktree-removal-reservations.ts create mode 100644 src/main/workspaces/removal/worktree-removal-settlement.ts create mode 100644 src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts create mode 100644 src/shared/worktree/removal-visibility.ts diff --git a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts index a45c2af7ff2..434c26bf11e 100644 --- a/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts +++ b/src/main/git/worktrees/creation/worktree-add-pending-removal.test.ts @@ -1,4 +1,8 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' const { gitExecFileAsyncMock, gitExecFileSyncMock, translateWslOutputPathsMock } = vi.hoisted( () => ({ @@ -27,12 +31,16 @@ import { addWorktree } from './worktree-add' import { registerWorktreeSuiteHooks } from '../testing/worktree-test-harness' import { _resetPendingWorktreeRemovalsForTests, - startBackgroundWorktreeRemoval + _settlePendingWorktreeRemovalsForTests, + loadWorktreeRemovalRecords, + startBackgroundWorktreeRemoval, + stopBackgroundWorktreeRemovals, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' registerWorktreeSuiteHooks() -function startDeleting(): void { +async function startDeleting(): Promise { void startBackgroundWorktreeRemoval({ removal: { worktreeId: 'repo-1::/repo-feature', @@ -42,18 +50,27 @@ function startDeleting(): void { deleteBranch: true, force: false }, - run: () => new Promise(() => {}), + run: (signal) => new Promise((resolve) => signal.addEventListener('abort', () => resolve({}))), publish: () => {} }) + await waitForWorktreeRemovalAcceptance('repo-1::/repo-feature') } describe('addWorktree while Orca deletes a checkout in the background', () => { - afterEach(() => { + let directory = '' + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-add-pending-removal-')) + await loadWorktreeRemovalRecords(directory) + }) + afterEach(async () => { + stopBackgroundWorktreeRemovals() + await _settlePendingWorktreeRemovalsForTests() _resetPendingWorktreeRemovalsForTests() + await removeTree(directory) }) it('refuses the same path with a clear message and runs no git', async () => { - startDeleting() + await startDeleting() await expect(addWorktree('/repo', '/repo-feature', 'other-branch')).rejects.toThrow( 'Orca is still deleting the workspace at /repo-feature. Cleanup is pending; try again shortly.' ) @@ -61,7 +78,7 @@ describe('addWorktree while Orca deletes a checkout in the background', () => { }) it('refuses the same branch, which the delete removes when it finishes', async () => { - startDeleting() + await startDeleting() await expect( addWorktree('/repo', '/repo-elsewhere', 'feature/test', undefined, false, false, { checkoutExistingBranch: true diff --git a/src/main/ipc/worktree-metadata-merge.ts b/src/main/ipc/worktree-metadata-merge.ts index a2c7f353f30..cd865fb0ffb 100644 --- a/src/main/ipc/worktree-metadata-merge.ts +++ b/src/main/ipc/worktree-metadata-merge.ts @@ -52,6 +52,8 @@ export function mergeWorktree( ...(git.isSparse === true ? { isSparse: true } : {}), isMainWorktree: git.isMainWorktree, ...(git.removalError ? { removalError: git.removalError } : {}), + ...(git.removing ? { removing: true } : {}), + ...(git.removalRecorded ? { removalRecorded: true } : {}), // Automatic labels follow the live branch; persisted values are only authoritative when pinned. displayName: meta?.displayNameIsPinned === false diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 879d3fb20bc..0678db03256 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -172,7 +172,10 @@ import { retireGeneratedWorktreeName } from '../workspaces/removal/retirement/worktree-name-retirement' import { createRetiredNameLookup } from '../../shared/worktree/retired-name-registry' -import { findPendingWorktreeRemovalConflict } from '../workspaces/removal/worktree-removal-table' +import { + assertNoPendingWorktreeRemovalConflict, + findPendingWorktreeRemovalConflict +} from '../workspaces/removal/worktree-removal-table' import { exactNameBranchConflict, exactNameLateCollision, @@ -1221,6 +1224,27 @@ async function performLocalWorktreeCreate( const shouldRetireGeneratedName = args.nameWasGenerated === true && isGeneratedWorktreeCreateName(sanitizedName) const exactName = args.branchIntent === 'create-exact' + if (args.nameWasGenerated !== true || args.branchNameOverride) { + assertNoPendingWorktreeRemovalConflict(repo.path, { + worktreePath: + args.nameWasGenerated === true + ? undefined + : ensurePathWithinWorkspace( + computeWorktreePath(sanitizedName, repo.path, worktreePathSettings, workspaceRoot), + workspaceRoot + ), + branch: + args.branchNameOverride || + (await resolveCreateBranchName( + repo.path, + undefined, + sanitizedName, + settings, + username, + localWorktreeGitOptions + )) + }) + } if ( args.branchIntent === 'open-existing' && args.branchNameOverride && diff --git a/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts b/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts index 3fcd9e4b50c..1c0a878a0c9 100644 --- a/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts +++ b/src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts @@ -20,7 +20,8 @@ import { resolveRepoForExecutionHost } from '../repo-host-ownership' import { withNestedPreservedBranches } from '../../../workspaces/removal/nested-worktree-removal-plan' import { finishAcceptedWorktreeRemoval, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue' import { assertWslMoveRepoWritable } from '../../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard' @@ -83,18 +84,21 @@ export function registerWorktreeRemovalHandlers(context: WorktreeIpcContext): vo areWorktreePathsEqual(item.path, worktreePath) ) const executionArgs = expectedCheckout ? { ...args, expectedCheckout } : args - const accept = async (): Promise => + const accept = async (): Promise => { // Another client may acquire removal while this request waits for acceptance. - waitForPendingWorktreeRemoval(args.worktreeId, removalHostId) - ? { removing: true } - : executeWorktreeRemoval( - context, - executionArgs, - repo, - repoId, - worktreePath, - removalHostId - ) + if (waitForPendingWorktreeRemoval(args.worktreeId, removalHostId)) { + await waitForWorktreeRemovalAcceptance(args.worktreeId, removalHostId) + return { removing: true } + } + return executeWorktreeRemoval( + context, + executionArgs, + repo, + repoId, + worktreePath, + removalHostId + ) + } // Read before the purge drops the row; listeners hear `removed` after it. const removedIdentity = worktreeHostIdentity(store, args.worktreeId, removalHostId) let accepted: RemoveWorktreeResult diff --git a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts index ad96e979e03..58293ebfd47 100644 --- a/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts +++ b/src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts @@ -39,7 +39,8 @@ import { import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup' import { removesInBackground, - startBackgroundWorktreeRemoval + startBackgroundWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' import { worktreeHostIdentity } from '../../../persistence/worktree-meta-host-identity' @@ -175,8 +176,10 @@ export async function removeRegisteredLocalWorktree( return result }, publish: () => runtime.publishWorktreeRemovalChange(repoId), + admissionFailed: () => removalGate.finish(false), cleanupPushTargetRemote: cleanupPushTarget }) + await waitForWorktreeRemovalAcceptance(args.worktreeId) return { removing: true } } @@ -268,12 +271,11 @@ async function finishLocalWorktreeRemoval({ removalHostId, args.snapshotPruneBatchId ) - preservedBranchCleanupByScope.delete( - preservedBranchCleanupScopeKey({ - worktreeId: args.worktreeId, - hostId: removalHostId - }) - ) + const cleanupScopeKey = preservedBranchCleanupScopeKey({ + worktreeId: args.worktreeId, + hostId: removalHostId + }) + preservedBranchCleanupByScope.delete(cleanupScopeKey) invalidateAuthorizedRootsCacheForRepo(store, repoId) removalCompleted = true return {} diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts index 9b03263f197..f39fee39101 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-lifecycle.spec.ts @@ -1,4 +1,7 @@ import './runtime-test-module-registration.spec' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { MOCK_GIT_WORKTREES, addGitHubIssueCommentMock, @@ -85,7 +88,7 @@ import { _resetTerminalViewAttributesForTest } from '../terminal/view/terminal-v import { addSparseWorktree } from '../../git/worktrees/creation/worktree-sparse-add' import { addWorktree } from '../../git/worktrees/creation/worktree-add' import { advertisedUrlWatcher } from '../../ports/advertised-url-watcher' -import { afterAll, afterEach, beforeEach, vi, type MockInstance } from 'vitest' +import { afterAll, afterEach, beforeAll, beforeEach, vi, type MockInstance } from 'vitest' import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' import { stopStructuredAgentSessionRuntime } from '../agent-session/structured-agent-session-runtime' import { assertWorktreeCleanForRemoval } from '../../git/worktrees/removal/worktree-removal-preflight' @@ -128,6 +131,7 @@ import { _settlePendingWorktreeRemovalsForTests } from '../../workspaces/removal/worktree-background-removal' import { _resetCanonicalRepoKeyCacheForTests } from '../../git/repositories/canonical-repo-key' +import { setWorktreeRemovalRecordsDirectory } from '../../workspaces/removal/worktree-removal-table' awaitBackgroundRemovalsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) commitFakeSpawnsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) @@ -135,6 +139,7 @@ commitFakeSpawnsInRuntimeTests(runtimeMockOrcaRuntimeService.prototype) function resetRuntimeTestMocks(): void { _resetCanonicalRepoKeyCacheForTests() _resetPendingWorktreeRemovalsForTests() + setWorktreeRemovalRecordsDirectory(removalRecordsDirectory) // Chromium commands install only at Electron entry; Node hosts must refuse browser RPCs without them. setRuntimeBrowserCommandsFactory((host) => new RuntimeBrowserCommands(host), { clientHosting: true @@ -378,6 +383,11 @@ function resetRuntimeTestMocks(): void { let registrationSpy: | MockInstance | undefined +let removalRecordsDirectory = '' + +beforeAll(async () => { + removalRecordsDirectory = await mkdtemp(join(tmpdir(), 'orca-runtime-removal-records-')) +}) beforeEach(() => { resetRuntimeTestMocks() @@ -405,4 +415,5 @@ export { resetRuntimeTestMocks } afterAll(async () => { await stopStructuredAgentSessionRuntime() + await rm(removalRecordsDirectory, { recursive: true, force: true }) }) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts index f15dc34b58b..ae6898acc6e 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts @@ -96,8 +96,9 @@ describe('OrcaRuntimeService', () => { hostId: 'ssh:host-b' }) + const remoteRefusal = expect(remote).rejects.toThrow('selector_not_found') await localStarted.promise - await expect(remote).rejects.toThrow('selector_not_found') + await remoteRefusal finishRemovals.resolve() await expect(local).resolves.toEqual({}) diff --git a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts index 3cc3289ed47..cae57710711 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts @@ -71,9 +71,7 @@ describe('runtime Delete on a failed delete’s leftover', () => { force, waitForBackgroundRemoval: false }) - ).rejects.toThrow( - `${leftover} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - ) + ).rejects.toThrow(/folder was left on disk/) } await _settlePendingWorktreeRemovalsForTests() @@ -88,14 +86,22 @@ describe('runtime Delete on a failed delete’s leftover', () => { ]) }) - it('ends the row once the user removed the folder', async () => { + it('keeps the failure after manual folder removal until explicit retry finishes cleanup', async () => { const runtime = createWorktreeRemovalRuntime() await rm(leftover, { recursive: true, force: true }) const detected = await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`) - - expect(detected.worktrees.find((row) => row.id === leftoverId)).toBeUndefined() - await vi.waitFor(async () => expect(await readWorktreeRemovalRecords(directory)).toEqual([])) + expect(detected.worktrees.find((row) => row.id === leftoverId)).toMatchObject({ + removalError: FAILURE + }) + await runtime.removeManagedWorktree(`id:${leftoverId}`, { waitForBackgroundRemoval: true }) + await _settlePendingWorktreeRemovalsForTests() + expect( + (await runtime.listDetectedManagedWorktrees(`id:${TEST_REPO_ID}`)).worktrees.find( + (row) => row.id === leftoverId + ) + ).toBeUndefined() + expect(await readWorktreeRemovalRecords(directory)).toEqual([]) expect(removeWorktree).not.toHaveBeenCalled() }) }) diff --git a/src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts b/src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts new file mode 100644 index 00000000000..c5862a3bfbf --- /dev/null +++ b/src/main/runtime/rpc/methods/workspaces/worktree-rm-cli.integration.test.ts @@ -0,0 +1,206 @@ +import { execFile } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, realpath, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { + partialRuntimeStore, + storeRepo, + storeWorktreeMeta +} from '../../../orca-runtime-tests/runtime-store-partial-fixture' +import type { WorktreeMeta } from '../../../../../shared/worktree/meta-types' +import type { Repo } from '../../../../../shared/repo-types' +import type { HostWorktreeTarget } from '../../../../../shared/worktree/host-qualified-identity' + +import * as appEnvironment from '../../../../../shared/app-environment' +import type { SshTarget } from '../../../../../shared/ssh-types' + +import { getRuntimeMetadataPath } from '../../../../../shared/runtime-bootstrap' + +import { UnixSocketTransport } from '../../transports/unix-socket-transport' +import { RpcDispatcher } from '../../dispatcher' +import { WORKTREE_METHODS } from './worktree' +import { STATUS_METHODS } from '../host-management/status' +import type { RpcRequest } from '../../core' +import { WorkspaceLifecycleQueue } from '../../../workspaces/lifecycle/workspace-lifecycle-queue' +import { installRealWorkerThreadChildProcesses } from '../../../../worker-thread-child-process/worker-thread-child-process-real.test-fixtures' +import { removeTree } from '../../../../../shared/windows-transient-lock-removal' +import { + _resetPendingWorktreeRemovalsForTests, + _settlePendingWorktreeRemovalsForTests, + loadWorktreeRemovalRecords +} from '../../../../workspaces/removal/worktree-background-removal' + +installRealWorkerThreadChildProcesses() +const cliPath = '../../../../../cli/index' +const { main }: { main: (argv: string[], cwd: string) => Promise } = await import(cliPath) + +const exec = promisify(execFile) +let directory = '' +let repoPath = '' +let checkout = '' +let id = '' +let repo: Repo +let folderRepo: Repo +let repos: Repo[] +let sshTargets: SshTarget[] +let meta: Record +let socket: UnixSocketTransport +let runtime: RemovalRuntime +let dispatcher: RpcDispatcher +const stopped = vi.fn(async () => {}) +const git = async (...args: string[]) => (await exec('git', args, { cwd: repoPath })).stdout.trim() +class RemovalRuntime extends OrcaRuntimeService { + override readonly workspaceLifecycle = new WorkspaceLifecycleQueue() +} +async function discover(endpoint: string) { + await writeFile( + getRuntimeMetadataPath(directory), + JSON.stringify({ + runtimeId: runtime.getRuntimeId(), + pid: process.pid, + transports: [{ kind: process.platform === 'win32' ? 'named-pipe' : 'unix', endpoint }], + authToken: 'test', + startedAt: 1 + }) + ) +} +beforeEach(async () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + directory = await realpath(await mkdtemp(join(tmpdir(), 'orca-cli-rm-'))) + await loadWorktreeRemovalRecords(directory) + repoPath = join(directory, 'repo') + checkout = join(directory, 'checkout') + id = `repo::${checkout}` + stopped.mockClear() + vi.stubEnv('ORCA_USER_DATA_PATH', directory) + vi.stubEnv('ORCA_PAIRING_CODE', '') + vi.stubEnv('ORCA_REMOTE_PAIRING', '') + vi.stubEnv('ORCA_ENVIRONMENT', '') + await mkdir(repoPath) + await git('init', '-q') + await git('checkout', '-qb', 'main') + await git('config', 'user.email', 'rm@example.invalid') + await git('config', 'user.name', 'CLI Removal') + await git('config', 'maintenance.auto', 'false') + await git('config', 'gc.auto', '0') + await writeFile(join(repoPath, 'file'), 'seed') + await git('add', '.') + await git('commit', '-qm', 'seed') + await git('worktree', 'add', '-qb', 'task', checkout) + await writeFile(join(checkout, 'file'), 'task change') + await git('-C', checkout, 'commit', '-qam', 'task') + await git('merge', '--squash', 'task') + await git('commit', '-qm', 'squashed task') + repo = storeRepo({ id: 'repo', path: repoPath }) + folderRepo = storeRepo({ id: 'folder-repo', path: directory, kind: 'folder' }) + repos = [repo, folderRepo] + sshTargets = [] + vi.spyOn(appEnvironment, 'getAppEnvironment').mockReturnValue({ + getPath: () => directory, + getAppPath: () => directory, + getVersion: () => 'test', + isPackaged: () => false, + onWillQuit: () => {}, + exit: () => {}, + getAppMetrics: () => [] + }) + meta = { [id]: storeWorktreeMeta({ displayName: 'task', instanceId: 'task', hostId: 'local' }) } + const store = partialRuntimeStore({ + getRepos: () => repos, + getSshTargets: () => sshTargets, + getRepo: (repoId) => repos.find((r) => r.id === repoId), + getAllWorktreeMeta: () => meta, + getWorktreeMeta: (key) => meta[key], + setWorktreeMeta: ({ id: key }: HostWorktreeTarget, value: Partial) => + (meta[key] = { ...storeWorktreeMeta(), ...meta[key], ...value }), + removeWorktreeMeta: ({ id: key }: HostWorktreeTarget) => { + delete meta[key] + }, + getAllWorktreeLineage: () => ({}), + getAllWorkspaceLineage: () => ({}), + getProjects: () => [], + getProfileStorageDirectory: () => directory, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, + flushOrThrow: () => {} + }) + runtime = new RemovalRuntime(store) + vi.spyOn(runtime, 'machineNameReady').mockResolvedValue(undefined) + vi.spyOn(runtime, 'acquireFileWatcherRemoval').mockResolvedValue({ finish: async () => {} }) + vi.spyOn(runtime, 'closeFileWatchersForRemoval').mockResolvedValue(undefined) + vi.spyOn(runtime, 'stopPtysForDestructiveWorktreeRemoval').mockImplementation(stopped) + vi.spyOn(runtime, 'notifyWorktreesChanged').mockImplementation(() => {}) + dispatcher = new RpcDispatcher({ runtime, methods: [...STATUS_METHODS, ...WORKTREE_METHODS] }) + const kind = process.platform === 'win32' ? 'named-pipe' : 'unix' + const endpoint = + process.platform === 'win32' + ? String.raw`\\.\pipe\orca-rm-${process.pid}` + : join(directory, 'rpc.sock') + socket = new UnixSocketTransport({ kind, endpoint }) + socket.onMessage((message, reply) => { + const request: RpcRequest = JSON.parse(message) + void dispatcher.dispatch(request).then((response) => reply(JSON.stringify(response))) + }) + await socket.start() + await discover(endpoint) +}) +afterEach(async () => { + await _settlePendingWorktreeRemovalsForTests() + _resetPendingWorktreeRemovalsForTests() + await socket?.stop() + vi.unstubAllEnvs() + vi.restoreAllMocks() + process.exitCode = 0 + await removeTree(directory) +}) + +it.each<{ flags: string[]; deleted: boolean }>([ + { flags: [], deleted: false }, + { flags: ['--force'], deleted: false }, + { flags: ['--delete-branch'], deleted: true } +])( + 'runs CLI $flags through actual RPC/runtime/background Git, deleted=$deleted', + async ({ flags, deleted }) => { + // Existing branches have preservation metadata; explicit opt-in must override it. + meta[id].preserveBranchOnDelete = flags.includes('--delete-branch') + const head = await git('rev-parse', 'task') + await main(['worktree', 'rm', '--worktree', `id:${id}`, ...flags, '--json'], repoPath) + expect(process.exitCode).not.toBe(1) + await _settlePendingWorktreeRemovalsForTests() + expect(existsSync(checkout)).toBe(false) + expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe( + deleted ? '' : 'task' + ) + if (!deleted) { + expect(await git('rev-parse', 'task')).toBe(head) + } + } +) + +function warnings() { + return vi + .mocked(console.error) + .mock.calls.filter(([value]) => String(value).includes('host is older')) +} + +it('reports actual safe branch preservation when forced checkout removal cannot delete the branch', async () => { + await writeFile(join(checkout, 'unmerged'), 'only on task') + await git('-C', checkout, 'add', 'unmerged') + await git('-C', checkout, 'commit', '-qm', 'unmerged') + const head = await git('rev-parse', 'task') + await main(['worktree', 'rm', '--worktree', `id:${id}`, '--delete-branch', '--force'], repoPath) + expect(process.exitCode).not.toBe(1) + expect(existsSync(checkout)).toBe(false) + expect(await git('rev-parse', 'task')).toBe(head) + expect(vi.mocked(console.log)).toHaveBeenCalledWith('removed: true') + expect(vi.mocked(console.error)).toHaveBeenCalledWith( + 'warning: local branch "task" was kept because Git could not safely delete it' + ) + expect(warnings()).toHaveLength(0) +}) diff --git a/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts new file mode 100644 index 00000000000..1c64ffde30b --- /dev/null +++ b/src/main/runtime/rpc/workspace-client-views/worktree-removal-marker-projection.test.ts @@ -0,0 +1,123 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types' +import { NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/protocol-version' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../shared/electron-remote-runtime-client-capabilities' +import { remoteRuntimeClientCapabilities } from '../../../../shared/remote-runtime/remote-runtime-client-capabilities' +import type { + RuntimeWorktreeListResult, + RuntimeWorktreePsResult +} from '../../../../shared/runtime-worktree-contracts' +import { + _resetPendingWorktreeRemovalsForTests, + _settlePendingWorktreeRemovalsForTests, + startBackgroundWorktreeRemoval, + loadWorktreeRemovalRecords, + waitForWorktreeRemovalAcceptance +} from '../../../workspaces/removal/worktree-background-removal' +import { snapshotPendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-listing' +import { + projectWorktreeListRemovals, + projectWorktreePsRemovals +} from './worktree-removal-marker-projection' + +const removingId = 'repo-1::/work/feature' +const keptId = 'repo-1::/work/other' + +function listResult(): RuntimeWorktreeListResult { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only id, hostId and the counts. + return { + worktrees: [ + { id: removingId, hostId: 'local' }, + { id: keptId, hostId: 'local' } + ], + totalCount: 2, + truncated: false + } as unknown as RuntimeWorktreeListResult +} + +function psResult(): RuntimeWorktreePsResult { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the projection reads only worktreeId, hostId and the counts. + return { + worktrees: [ + { worktreeId: removingId, hostId: 'local' }, + { worktreeId: keptId, hostId: 'local' } + ], + totalCount: 2, + truncated: false + } as unknown as RuntimeWorktreePsResult +} + +describe('worktree listings while a checkout is being deleted', () => { + let directory = '' + let cleanup = Promise.withResolvers() + beforeEach(async () => { + cleanup = Promise.withResolvers() + directory = await mkdtemp(join(tmpdir(), 'orca-marker-projection-')) + await loadWorktreeRemovalRecords(directory) + void startBackgroundWorktreeRemoval({ + removal: { + worktreeId: removingId, + repoId: 'repo-1', + repoPath: '/work/repo', + worktree: { path: '/work/feature', branch: 'refs/heads/feature', head: 'abc' }, + deleteBranch: true, + force: false + }, + run: () => cleanup.promise, + publish: () => {} + }) + await waitForWorktreeRemovalAcceptance(removingId) + }) + + afterEach(async () => { + cleanup.resolve({}) + await _settlePendingWorktreeRemovalsForTests() + _resetPendingWorktreeRemovalsForTests() + await rm(directory, { recursive: true, force: true }) + }) + + it('marks the row for a desktop or web client that negotiated the marker', () => { + const context = { clientCapabilities: ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } + expect( + projectWorktreeListRemovals(listResult(), context, snapshotPendingWorktreeRemovals()) + .worktrees + ).toEqual([ + { id: removingId, hostId: 'local', removing: true, removalRecorded: true }, + { id: keptId, hostId: 'local' } + ]) + expect( + projectWorktreePsRemovals(psResult(), context, snapshotPendingWorktreeRemovals()).worktrees + ).toEqual([ + { worktreeId: removingId, hostId: 'local', removing: true, removalRecorded: true }, + { worktreeId: keptId, hostId: 'local' } + ]) + }) + + it('leaves the row out for a client that would show it as a normal workspace', () => { + // An older desktop or web build, the CLI, the phone, and an in-process caller alike. + for (const clientCapabilities of [ + [], + undefined, + NATIVE_REMOTE_RUNTIME_CLIENT_CAPABILITIES, + remoteRuntimeClientCapabilities() + ]) { + const list = projectWorktreeListRemovals( + listResult(), + { clientCapabilities }, + snapshotPendingWorktreeRemovals() + ) + expect(list.worktrees.map((row) => row.id)).toEqual([keptId]) + expect(list.totalCount).toBe(1) + const ps = projectWorktreePsRemovals( + psResult(), + { clientCapabilities }, + snapshotPendingWorktreeRemovals() + ) + expect(ps.worktrees.map((row) => row.worktreeId)).toEqual([keptId]) + expect(ps.totalCount).toBe(1) + } + }) +}) diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts index 7418e2203ed..180c0b3773f 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.test.ts @@ -1,3 +1,8 @@ +import { + joinResolvedWorktreeScans, + type ResolvedWorktreeRepoScans +} from './resolved-worktree-scan-join' +import { getRepoHostIdentityForParts } from '../../../../shared/repo-host-identity' import { describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../shared/repo-types' @@ -9,12 +14,18 @@ import type { Store } from '../../../persistence/loading-store/store' import { mergeWorktreeMetaForWrite } from '../../../persistence/loading-store/worktree-metadata/worktree-meta-write-normalization' import { buildDetectedGitWorktrees } from '../../../ipc/worktrees/listing/ssh-worktree-fallback' import { + projectRepoWorktreeRows, resolveRepoWorktreeRows, resolveScopedWorktreeIdRow, scanRepoWorktreeRows, type RepoWorktreeRowDeps } from './repo-worktree-row-resolution' import type { HostWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' +import { + pendingWorktreeRemovals, + recordedWorktreeRemovals, + finishedWorktreeRemovals +} from '../../../workspaces/removal/worktree-removal-table' import { bumpLocalWorktreeScanGeneration } from '../../../workspaces/catalog/local-worktree-scan-generation' function repo( @@ -234,3 +245,107 @@ describe('folder-to-Git checkout identity', () => { } ) }) + +describe('durable removal projection onto cached host rows', () => { + it('retires admitted rows without another scan and fences old rows after cleanup, only on their host', async () => { + const local = repo('shared', '/local/repo', { executionHostId: 'local' }) + const remote = repo('shared', '/remote/repo', { executionHostId: 'ssh:builder' }) + const deps = createDeps([local, remote]) + const scan = await scanRepoWorktreeRows(deps, local, new Map()) + const id = 'shared::/same/worktree' + const record = { + worktreeId: id, + repoId: local.id, + repoPath: local.path, + worktreePath: '/same/worktree', + branch: 'feature', + head: 'abc123', + deleteBranch: false, + force: false, + requestedAt: 1 + } + pendingWorktreeRemovals.set(id, record) + try { + expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([{ id }]) + expect(projectRepoWorktreeRows(deps, local, scan, {})[0].removalRecorded).toBeUndefined() + recordedWorktreeRemovals.add(record) + expect(projectRepoWorktreeRows(deps, local, scan, {})).toMatchObject([ + { id, removing: true, removalRecorded: true } + ]) + expect(projectRepoWorktreeRows(deps, remote, scan, {})[0].removalRecorded).toBeUndefined() + pendingWorktreeRemovals.delete(id) + finishedWorktreeRemovals.add(record) + expect(projectRepoWorktreeRows(deps, local, scan, {})).toEqual([]) + expect(projectRepoWorktreeRows(deps, remote, scan, {})).toMatchObject([{ id }]) + } finally { + pendingWorktreeRemovals.delete(id) + } + }) +}) + +it.each([ + [12, 750], + [120, 7500] +])( + 'keeps removal witnesses repo-scoped without recopying on metadata joins (%i repos, %i removals)', + (repoCount, removalCount) => { + const repos = Array.from({ length: repoCount }, (_, i) => + repo(`fleet-${i}`, `/fleet/${i}`, { executionHostId: 'local' }) + ) + const deps = createDeps(repos) + const scans: ResolvedWorktreeRepoScans = new Map( + repos.map((owner) => [ + getRepoHostIdentityForParts(owner.id, 'local'), + { ok: true, worktrees: [], gitRun: null } + ]) + ) + const records = Array.from({ length: removalCount }, (_, i) => ({ + worktreeId: `fleet-0::/retiring/${i}`, + repoId: 'fleet-0', + repoPath: '/fleet/0', + worktreePath: `/retiring/${i}`, + branch: `feature-${i}`, + head: 'abc123', + force: false, + deleteBranch: false, + requestedAt: 1 + })) + for (const record of records) { + pendingWorktreeRemovals.set(record.worktreeId, record) + recordedWorktreeRemovals.add(record) + } + const firstScan = scans.get(getRepoHostIdentityForParts('fleet-0', 'local'))! + firstScan.worktrees = [gitWorktree('/retiring/0')] + try { + const joined = joinResolvedWorktreeScans(deps.store, () => deps, scans) + expect(joined.worktrees).toMatchObject([{ id: records[0].worktreeId, removalRecorded: true }]) + expect([...scans.values()].map((scan) => scan.removals?.size ?? 0)).toEqual([ + removalCount, + ...Array(repoCount - 1).fill(0) + ]) + const witnesses = firstScan.removals! + const enumerateWitnesses = vi.spyOn(witnesses, Symbol.iterator) + const enumerateGlobal = vi.spyOn(pendingWorktreeRemovals, Symbol.iterator) + try { + deps.metaById[records[0].worktreeId] = mergeWorktreeMetaForWrite(undefined, { + displayName: 'changed metadata' + }) + joinResolvedWorktreeScans(deps.store, () => deps, scans) + // Unrelated metadata cannot invalidate removal membership: no witness entries need copying. + expect(enumerateWitnesses).not.toHaveBeenCalled() + expect(enumerateGlobal).not.toHaveBeenCalled() + expect(firstScan.removals).toBe(witnesses) + } finally { + enumerateWitnesses.mockRestore() + enumerateGlobal.mockRestore() + } + pendingWorktreeRemovals.delete(records[0].worktreeId) + finishedWorktreeRemovals.add(records[0]) + expect(joinResolvedWorktreeScans(deps.store, () => deps, scans).worktrees).toEqual([]) + } finally { + for (const record of records) { + pendingWorktreeRemovals.delete(record.worktreeId) + } + } + } +) diff --git a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts index 90fa1563064..d959f401f3b 100644 --- a/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts +++ b/src/main/runtime/workspaces/catalog/repo-worktree-row-resolution.ts @@ -5,7 +5,8 @@ import { splitWorktreeIdForFilesystem, worktreeIdentityKey } from '../../../../shared/worktree/id' -import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' import { readAllWorktreeMetaForHost, readWorktreeMetaForHost @@ -32,6 +33,11 @@ import { getLocalWorktreeScanGeneration } from '../../../workspaces/catalog/loca import { getRepoOwnedWorktreeMeta } from '../../../workspaces/catalog/worktree-metadata-ownership' import { resolveLocalProjectRuntimesForRepos } from '../../../workspaces/execution-host/local-project-runtime-resolution' import type { RuntimeWorktreeScanResult } from './repo-worktree-resolution-scan' +import { + projectCachedWorktreeRemovals, + type WorktreeRemovalWitnessScan +} from '../../../workspaces/removal/worktree-removal-listing' +import { pendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-table' type RepoWorktreeRowStore = Pick< RuntimeStore, @@ -110,19 +116,23 @@ export function listStoredWorktreeRowsForRepo( } /** One git repo's checkouts as its scan saw them; carries no metadata, which is joined at read. */ -export type RepoWorktreeRowsScan = { ok: boolean; worktrees: GitWorktreeInfo[] } +export type RepoWorktreeRowsScan = { + ok: boolean + worktrees: GitWorktreeInfo[] +} & WorktreeRemovalWitnessScan /** The scan half of `resolveRepoWorktreeRows`: slow, and the only part that awaits. */ export async function scanRepoWorktreeRows( - deps: Pick< - RepoWorktreeRowDeps, - 'store' | 'scanRepo' | 'getCachedSuccessfulScan' | 'claimLineagePrune' - >, + deps: Omit, repo: Repo, projectRuntimeByRepoId: ReadonlyMap, repoOwnerCount = deps.store.getRepos().filter((candidate) => candidate.id === repo.id).length ): Promise { const { store } = deps + const removals = + getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID + ? pendingWorktreeRemovals.snapshotForRepo(repo.id) + : undefined const scanGeneration = getLocalWorktreeScanGeneration(repo.id) // Absorb rejection before withTimeout: rejection preserves shipped empty results, but timeout restores last-known rows. const scan: RuntimeWorktreeScanResult = (await withTimeout( @@ -139,15 +149,12 @@ export async function scanRepoWorktreeRows( } const gitWorktrees = preserveFolderUpgradeWorktreePath(repo, scan.worktrees) // Cached reads must not re-prune against a generation captured after their rows were observed. - const lineage = !scan.ok - ? null - : deps.claimLineagePrune - ? deps.claimLineagePrune(scan) - : { scanGeneration } + const lineage = + scan.ok && (deps.claimLineagePrune ? deps.claimLineagePrune(scan) : { scanGeneration }) if (lineage) { pruneLineageForMissingRepoWorktrees(store, repo, gitWorktrees, lineage) } - return { ok: scan.ok, worktrees: gitWorktrees } + return { ok: scan.ok, worktrees: gitWorktrees, removals, projectedRemovals: removals } } /** The join half: a repo's rows from a scan and the metadata as it is now. Synchronous. */ @@ -178,7 +185,7 @@ export function projectRepoWorktreeRows( })) } const expectedHostId = getRepoExecutionHostId(repo) - return (scan?.worktrees ?? []).map((gitWorktree) => { + const rows = (scan?.worktrees ?? []).map((gitWorktree) => { const worktreeId = `${repo.id}::${gitWorktree.path}` const meta = readWorktreeMetaForHost(store, worktreeId, expectedHostId) ?? @@ -198,11 +205,13 @@ export function projectRepoWorktreeRows( branch: gitWorktree.branch, isBare: gitWorktree.isBare, isMainWorktree: gitWorktree.isMainWorktree - }, - displayName: merged.displayName, - comment: merged.comment + } } }) + if (expectedHostId !== LOCAL_EXECUTION_HOST_ID || !scan) { + return rows + } + return projectCachedWorktreeRemovals(repo.id, scan, rows, (row) => row.id) } /** Resolution owns durable identity stamping; memory projection never calls this wrapper. */ diff --git a/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts b/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts index 6b0b8bf52f0..32f7df40264 100644 --- a/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts +++ b/src/main/runtime/workspaces/creation/runtime-branch-reuse-real-git.test.ts @@ -12,7 +12,10 @@ import { addSparseWorktree } from '../../../git/worktrees/creation/worktree-spar import { addWorktree } from '../../../git/worktrees/creation/worktree-add' import { openWorktreeCreatePathClaim } from '../../../workspaces/creation/worktree-create-in-flight' import { exactNameLateCollision } from '../../../workspaces/creation/worktree-create-exact-name' -import { pendingWorktreeRemovals } from '../../../workspaces/removal/worktree-removal-table' +import { + failedWorktreeRemovals, + pendingWorktreeRemovals +} from '../../../workspaces/removal/worktree-removal-table' import { runtimePathExists } from '../catalog/runtime-worktree-filesystem' import { WorktreeCreate } from '../../../../shared/rpc-contract/worktree-create-params' import { buildManagedWorktreeCreateArgs } from '../../rpc/methods/workspaces/worktree-create-args' @@ -299,6 +302,95 @@ describe('explicit branch reuse with real Git', () => { }) }) +describe('cleanup ownership before candidate fallbacks', () => { + it.each(['pending branch', 'failed branch reuse', 'failed path', 'empty branch override'])( + 'explains %s before suffixing or missing-branch guidance', + async (scenario) => { + const f = await fixture() + const path = join(scenario === 'empty branch override' ? f.root : f.workspaceRoot, 'reserved') + const failed = scenario !== 'pending branch' + const records = failed ? failedWorktreeRemovals : pendingWorktreeRemovals + const record = { + worktreeId: `repo::${path}`, + repoId: 'repo', + repoPath: f.repoPath, + worktreePath: path, + branch: 'reserved', + head: f.initialTip, + deleteBranch: true, + force: true, + requestedAt: 0, + ...(failed ? { failure: { message: 'permission denied', failedAt: 1 } } : {}) + } + records.set(record.worktreeId, record) + if (scenario === 'pending branch') { + await git(f.repoPath, 'branch', 'reserved') + } else if (scenario === 'failed path') { + await mkdir(path, { recursive: true }) + } + try { + await expect( + f.candidate({ + name: + scenario === 'failed path' || scenario === 'empty branch override' + ? 'reserved' + : 'free-name', + branchNameOverride: + scenario === 'failed path' + ? undefined + : scenario === 'empty branch override' + ? '' + : 'reserved', + branchIntent: scenario === 'failed branch reuse' ? 'open-existing-v2' : 'create-new' + }) + ).rejects.toThrow(failed ? 'Retry deleting it before reusing' : 'Cleanup is pending') + expect(records.get(record.worktreeId)).toBe(record) + expect(await git(f.repoPath, 'branch', '--list', 'reserved-2')).toBe('') + await expect(runtimePathExists(join(f.workspaceRoot, 'free-name-2'))).resolves.toBe(false) + } finally { + records.delete(record.worktreeId) + } + } + ) + + it('keeps generated allocation and ordinary collision suffixes', async () => { + const f = await fixture() + const path = join(f.workspaceRoot, 'nautilus') + const record = { + worktreeId: `repo::${path}`, + repoId: 'repo', + repoPath: f.repoPath, + worktreePath: path, + branch: 'nautilus', + head: f.initialTip, + deleteBranch: true, + force: true, + requestedAt: 0 + } + pendingWorktreeRemovals.set(record.worktreeId, record) + try { + const generated = await f.candidate({ + name: 'nautilus', + nameWasGenerated: true, + branchNameOverride: undefined, + branchIntent: 'create-new' + }) + expect(generated.worktreePath).toBe(join(f.workspaceRoot, 'nautilus-2')) + expect(generated.branchName).toBe('nautilus-2') + await git(f.repoPath, 'branch', 'occupied') + const ordinary = await f.candidate({ + name: 'ordinary', + branchNameOverride: 'occupied', + branchIntent: 'create-new' + }) + expect(ordinary.branchName).toBe('occupied-2') + expect(ordinary.worktreePath).toBe(join(f.workspaceRoot, 'ordinary-2')) + } finally { + pendingWorktreeRemovals.delete(record.worktreeId) + } + }) +}) + describe('exact-name create with real Git', () => { const exact = (name: string) => ({ name, @@ -356,7 +448,9 @@ describe('exact-name create with real Git', () => { expect(foreign.claim(path)).toBe(true) } try { - await expect(f.candidate(exact('Login fix'))).rejects.toMatchObject(refused) + await (holder === 'a pending removal' + ? expect(f.candidate(exact('Login fix'))).rejects.toThrow('Cleanup is pending') + : expect(f.candidate(exact('Login fix'))).rejects.toMatchObject(refused)) const probe = openWorktreeCreatePathClaim() expect(probe.claim(path)).toBe(holder !== 'an in-flight create') probe.release() diff --git a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts index 278d8fc9d61..3841db1cbbe 100644 --- a/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts +++ b/src/main/runtime/workspaces/creation/runtime-local-worktree-create-candidate.ts @@ -39,7 +39,10 @@ import { resolveCreateBranchName } from './runtime-worktree-create-git' import { runtimePathExists } from '../catalog/runtime-worktree-filesystem' -import { findPendingWorktreeRemovalConflict } from '../../../workspaces/removal/worktree-removal-table' +import { + assertNoPendingWorktreeRemovalConflict, + findPendingWorktreeRemovalConflict +} from '../../../workspaces/removal/worktree-removal-table' import type { WorktreeCreatePathClaim } from '../../../workspaces/creation/worktree-create-in-flight' import type { RuntimeStore } from '../../construction/runtime-store-contract' import type { HostedReviewExecutionOptions } from '../../../source-control/hosted-review-git-options' @@ -80,7 +83,6 @@ export async function resolveRuntimeLocalWorktreeCreateCandidate(args: { let branchName = '' let checkoutExistingBranch = false let selectedExistingLocalBranchName: string | null = null - let selectedReuseBranchName: string | null = null let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false @@ -100,7 +102,28 @@ export async function resolveRuntimeLocalWorktreeCreateCandidate(args: { ) : null const isRetiredName = retiredNameRegistry ? createRetiredNameLookup(retiredNameRegistry) : null - selectedReuseBranchName = await resolveLegacyRemoteBranch({ ...args, sanitizedName }) + if (args.request.nameWasGenerated !== true || args.request.branchNameOverride) { + assertNoPendingWorktreeRemovalConflict(args.repo.path, { + worktreePath: + args.request.nameWasGenerated === true + ? undefined + : ensurePathWithinWorkspace( + computeWorktreePath(sanitizedName, args.repo.path, args.worktreePathSettings), + args.workspaceRoot + ), + branch: + args.request.branchNameOverride || + (await resolveCreateBranchName( + args.repo.path, + undefined, + sanitizedName, + args.settings, + args.username, + args.localWorktreeGitOptions + )) + }) + } + let selectedReuseBranchName = await resolveLegacyRemoteBranch({ ...args, sanitizedName }) if (selectedReuseBranchName) { branchName = selectedReuseBranchName } diff --git a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts index 9cc4280d781..24c0e6a8ef7 100644 --- a/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts +++ b/src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import { isCrossStoreInferredSource, type CrossStoreInferredSource, @@ -48,6 +49,9 @@ type RuntimeWorktreeLineageDependencies = { } function worktreeParent(worktree: ResolvedWorktree): ResolvedWorkspaceParent { + if (isWorktreeRetiredByRemoval(worktree)) { + throw new Error('selector_not_found') + } return { type: 'worktree', workspaceKey: worktreeWorkspaceKey(worktree.id), diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-summaries.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-summaries.ts index 4301af74aa9..b265a080ab9 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-summaries.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-ps-summaries.ts @@ -88,6 +88,8 @@ export function buildRuntimeWorktreePsSummaries(args: { hasHostSidebarActivity: false, ...getWorkspaceRowKindFacts(worktree, repo), ...(worktree.removalError ? { removalError: worktree.removalError } : {}), + ...(worktree.removing ? { removing: true } : {}), + ...(worktree.removalRecorded ? { removalRecorded: true } : {}), ...(worktree.instanceId !== undefined ? { worktreeInstanceId: worktree.instanceId } : {}), ...(lineage?.worktreeInstanceId !== undefined ? { lineageWorktreeInstanceId: lineage.worktreeInstanceId } diff --git a/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts b/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts index c6bef70cad1..a249cee2918 100644 --- a/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts +++ b/src/main/runtime/workspaces/removal/runtime-failed-local-worktree-removal.test.ts @@ -149,9 +149,6 @@ async function deleteRow(purged: string[], stopPtys = vi.fn(async () => {})): Pr return error } -const refusal = (): string => - `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` - /** A delete a quit interrupted, finished at the next start, where Git fails on the locked file. */ function failStartupFinish(): Promise { return finishAtStartup([]) @@ -282,7 +279,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part const purged: string[] = [] const stopPtys = vi.fn(async () => {}) - expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error) expect(existsSync(lockedFile)).toBe(true) expect(stopPtys).not.toHaveBeenCalled() expect(purged).toEqual([]) @@ -309,7 +306,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') const purged: string[] = [] - expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged)).toBeInstanceOf(Error) expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') expect(removeHostTree).not.toHaveBeenCalled() @@ -405,7 +402,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part const retried = retryFailedWorktreeRemoval(worktreeId, 'local', (record) => interruptedLocalWorktreeRemovalJob(record, jobHost(purged)) ) - await expect(retried).rejects.toThrow(refusal()) + await expect(retried).rejects.toThrow(/folder was left on disk/) await _settlePendingWorktreeRemovalsForTests() expect(existsSync(join(worktreePath, 'unsaved.txt'))).toBe(true) @@ -481,7 +478,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await writeFile(join(worktreePath, 'notes.txt'), 'mine\n') }) - expect(String(await deleteRow(purged, stopPtys))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged, stopPtys)).toBeInstanceOf(Error) expect(await readFile(join(worktreePath, 'notes.txt'), 'utf8')).toBe('mine\n') expect(removeHostTree).not.toHaveBeenCalled() @@ -493,7 +490,7 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part await rm(join(worktreePath, '.git')) const purged: string[] = [] - expect(String(await finishAtStartup(purged))).toBe(`Error: ${refusal()}`) + expect(await finishAtStartup(purged)).toBeInstanceOf(Error) expect(existsSync(join(worktreePath, '.git'))).toBe(false) expect(existsSync(lockedFile)).toBe(true) @@ -501,9 +498,9 @@ describe.skipIf(process.platform !== 'darwin')('a worktree delete Git fails part expect(await isRegistered(worktreePath)).toBe(false) expect(await git(['branch', '--list', 'feature'])).toBe('') expect(purged).toEqual([]) - expect(await listedRows()).toEqual([{ path: worktreePath, removalError: refusal() }]) + expect(await listedRows()).toEqual([{ path: worktreePath, removalError: expect.any(String) }]) - expect(String(await deleteRow(purged))).toBe(`Error: ${refusal()}`) + expect(await deleteRow(purged)).toBeInstanceOf(Error) expect(existsSync(lockedFile)).toBe(true) await rm(worktreePath, { recursive: true }) diff --git a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts index cb942c3efbb..158e4fb057b 100644 --- a/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts +++ b/src/main/runtime/workspaces/removal/runtime-registered-local-worktree-removal.ts @@ -34,7 +34,8 @@ import type { RuntimeWorktreeRemovalTarget } from '../catalog/runtime-worktree-s import { removesInBackground, startBackgroundWorktreeRemoval, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-background-removal' import { runSerializedWorktreeRemovalAcceptance } from '../../../workspaces/removal/worktree-removal-acceptance-queue' @@ -44,11 +45,14 @@ export function removeRuntimeRegisteredLocalWorktree( ): Promise { return runSerializedWorktreeRemovalAcceptance( args.repo.path, - async (): Promise => + async (): Promise => { // Recheck after queue wait: another client may already have accepted this deletion. - waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch) - ? { removing: true } - : acceptRuntimeRegisteredLocalWorktreeRemoval(args) + if (waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch)) { + await waitForWorktreeRemovalAcceptance(args.target.id) + return { removing: true } + } + return acceptRuntimeRegisteredLocalWorktreeRemoval(args) + } ) } @@ -208,8 +212,10 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: { return result }, publish: () => args.publish(), + admissionFailed: () => gate.finish(false), cleanupPushTargetRemote: () => cleanupRemovedWorktreePushTarget(args) }) + await waitForWorktreeRemovalAcceptance(args.target.id) return { removing: true, ...acceptedFields } } diff --git a/src/main/runtime/workspaces/removal/workspace-removal.ts b/src/main/runtime/workspaces/removal/workspace-removal.ts index f5da6f57cf3..e71734c87a2 100644 --- a/src/main/runtime/workspaces/removal/workspace-removal.ts +++ b/src/main/runtime/workspaces/removal/workspace-removal.ts @@ -13,7 +13,10 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' -import { finishAcceptedWorktreeRemoval } from '../../../workspaces/removal/worktree-background-removal' +import { + finishAcceptedWorktreeRemoval, + waitForWorktreeRemovalAcceptance +} from '../../../workspaces/removal/worktree-background-removal' import { preservedBranchCleanupScopeKey } from '../../../../shared/git/branches/preserved-branch-cleanup' import { getRuntimeWorktreeRemovalOptionsKey, @@ -91,6 +94,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp // Why: a retry or a second client asking while Git still deletes joins that removal. const pending = this.joinPendingWorktreeRemoval(removalTarget.id, options) if (pending) { + await waitForWorktreeRemovalAcceptance(removalTarget.id, cleanupHostId) return options.waitForBackgroundRemoval ? await pending : { removing: true } } // Identity read now: the purge drops the row before listeners hear `removed`. @@ -105,13 +109,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends RuntimeWorksp worktreeId: removalTarget.id, hostId: cleanupHostId }) - const optionsKey = getRuntimeWorktreeRemovalOptionsKey({ - force, - runHooks, - allowUnverifiedPtyStop, - allowFailedArchiveHook, - deleteBranch: options.deleteBranch - }) + const optionsKey = getRuntimeWorktreeRemovalOptionsKey(options) const inFlightRemoval = this.removeManagedWorktreeInFlight.get( cleanupScopeKey, removalTarget.id, diff --git a/src/main/workspaces/removal/worktree-background-removal-records.test.ts b/src/main/workspaces/removal/worktree-background-removal-records.test.ts index 766593102fe..b7bb55be801 100644 --- a/src/main/workspaces/removal/worktree-background-removal-records.test.ts +++ b/src/main/workspaces/removal/worktree-background-removal-records.test.ts @@ -7,16 +7,24 @@ import { _settlePendingWorktreeRemovalsForTests, loadWorktreeRemovalRecords, resumeInterruptedWorktreeRemovals, + retryFailedWorktreeRemoval, startBackgroundWorktreeRemoval, stopBackgroundWorktreeRemovals, - waitForPendingWorktreeRemoval + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance } from './worktree-background-removal' import { projectPendingWorktreeRemovals, - snapshotPendingWorktreeRemovals + snapshotPendingWorktreeRemovals, + withUnregisteredRemovalCheckouts } from './worktree-removal-listing' import type * as WorktreeRemovalRecords from './worktree-removal-records' -import { readWorktreeRemovalRecords } from './worktree-removal-records' +import { readWorktreeRemovalRecords, writeWorktreeRemovalRecords } from './worktree-removal-records' +import { + assertNoPendingWorktreeRemovalConflict, + pendingWorktreeRemovals, + persistWorktreeRemovalRecords +} from './worktree-removal-table' vi.mock('./worktree-removal-records', async (importOriginal) => { const actual = await importOriginal() @@ -25,6 +33,9 @@ vi.mock('./worktree-removal-records', async (importOriginal) => { writeWorktreeRemovalRecords: vi.fn(actual.writeWorktreeRemovalRecords) } }) +const actualRemovalRecords = await vi.importActual( + './worktree-removal-records' +) const removal = { worktreeId: 'repo-1::/work/feature', @@ -38,12 +49,17 @@ const isPending = (): boolean => waitForPendingWorktreeRemoval(removal.worktreeI let directory = '' beforeEach(async () => { + vi.mocked(writeWorktreeRemovalRecords).mockImplementation( + actualRemovalRecords.writeWorktreeRemovalRecords + ) directory = await mkdtemp(join(tmpdir(), 'orca-worktree-removal-records-')) await loadWorktreeRemovalRecords(directory) }) afterEach(async () => { vi.useRealTimers() + vi.restoreAllMocks() + vi.mocked(writeWorktreeRemovalRecords).mockReset() _resetPendingWorktreeRemovalsForTests() await rm(directory, { recursive: true, force: true }) }) @@ -101,9 +117,39 @@ describe('durable worktree removal records', () => { }) it('marks the row as removing after a restart and finishes it with the same job', async () => { + let releaseWrite!: () => void + const writing = new Promise((resolve) => { + releaseWrite = resolve + }) + vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(async (...args) => { + await writing + await actualRemovalRecords.writeWorktreeRemovalRecords(...args) + }) const job = interruptedJob() void startBackgroundWorktreeRemoval({ removal, ...job }) - await vi.waitFor(() => expect(job.started()).toBe(true)) + const initial: { id: string; hostId?: 'local' }[] = [{ id: removal.worktreeId }] + expect( + projectPendingWorktreeRemovals( + initial, + (row) => row.id, + true, + snapshotPendingWorktreeRemovals() + ) + ).toEqual(initial) + expect( + projectPendingWorktreeRemovals( + initial, + (row) => row.id, + false, + snapshotPendingWorktreeRemovals() + ) + ).toEqual(initial) + expect(() => + assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' }) + ).toThrow('Cleanup is pending') + expect(await readWorktreeRemovalRecords(directory)).toEqual([]) + releaseWrite() + await waitForWorktreeRemovalAcceptance(removal.worktreeId) stopBackgroundWorktreeRemovals() await _settlePendingWorktreeRemovalsForTests() @@ -117,7 +163,10 @@ describe('durable worktree removal records', () => { ] expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) - ).toEqual([{ id: removal.worktreeId, removing: true }, { id: 'repo-1::/work/other' }]) + ).toEqual([ + { id: removal.worktreeId, removing: true, removalRecorded: true }, + { id: 'repo-1::/work/other' } + ]) expect( projectPendingWorktreeRemovals( rows, @@ -142,6 +191,119 @@ describe('durable worktree removal records', () => { expect(isPending()).toBe(false) expect(await readWorktreeRemovalRecords(directory)).toEqual([]) await expect(joined).resolves.toEqual({}) - expect(publish).toHaveBeenCalledTimes(1) + }) + + it('retains the prior failure while a retry is unadmitted and after its save is refused', async () => { + const failed = { + worktreeId: removal.worktreeId, + repoId: removal.repoId, + repoPath: removal.repoPath, + worktreePath: directory, + branch: 'feature', + head: 'abc', + deleteBranch: true, + force: false, + requestedAt: 1, + failure: { message: 'Files are busy. Retry deletion.', failedAt: 2 } + } + await actualRemovalRecords.writeWorktreeRemovalRecords(directory, () => [failed]) + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + let refuseWrite!: (error: Error) => void + const writing = new Promise((_resolve, reject) => { + refuseWrite = reject + }) + vi.mocked(writeWorktreeRemovalRecords).mockImplementationOnce(() => writing) + const run = vi.fn(async () => ({})) + const retried = retryFailedWorktreeRemoval( + removal.worktreeId, + 'local', + () => ({ + run, + publish: () => {} + }), + true + ) + const refusal = expect(retried).rejects.toThrow('Could not start deletion') + expect( + projectPendingWorktreeRemovals<{ id: string; hostId?: 'local' }>( + [{ id: removal.worktreeId }], + (row) => row.id, + true, + snapshotPendingWorktreeRemovals() + ) + ).toEqual([{ id: removal.worktreeId, removalError: failed.failure.message }]) + expect(await withUnregisteredRemovalCheckouts(removal.repoId, [])).toHaveLength(1) + await persistWorktreeRemovalRecords() + expect(await readWorktreeRemovalRecords(directory)).toEqual([failed]) + refuseWrite(new Error('Disk full')) + await refusal + await _settlePendingWorktreeRemovalsForTests() + expect(run).not.toHaveBeenCalled() + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeUndefined() + expect(() => + assertNoPendingWorktreeRemovalConflict('/work/repo', { branch: 'feature' }) + ).toThrow('Retry deleting it before reusing its path or branch') + expect(await readWorktreeRemovalRecords(directory)).toEqual([failed]) + }) + + it('never resumes a refused force deletion captured alongside another repo admission', async () => { + let releaseWrite!: () => void + const writing = new Promise((resolve) => { + releaseWrite = resolve + }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + let refuseSecond!: (error: Error) => void + const secondWrite = new Promise((_resolve, reject) => { + refuseSecond = reject + }) + let secondReservedAtSnapshot = false + vi.mocked(writeWorktreeRemovalRecords) + .mockImplementationOnce(async (directory, current, committed) => { + await writing + await actualRemovalRecords.writeWorktreeRemovalRecords( + directory, + () => { + secondReservedAtSnapshot = pendingWorktreeRemovals.has('repo-2::/other/force') + return current() + }, + committed + ) + }) + .mockImplementationOnce(() => secondWrite) + .mockRejectedValueOnce(new Error('No space for a cleanup rewrite')) + void startBackgroundWorktreeRemoval({ removal, ...interruptedJob() }) + const refused = startBackgroundWorktreeRemoval({ + removal: { + ...removal, + worktreeId: 'repo-2::/other/force', + repoId: 'repo-2', + repoPath: '/other/repo', + worktree: { path: '/other/force', branch: 'refs/heads/force', head: 'def' }, + force: true + }, + run: async () => ({}), + publish: () => {} + }) + const refusal = expect(refused).rejects.toThrow('Could not start deletion') + releaseWrite() + await waitForWorktreeRemovalAcceptance(removal.worktreeId) + expect(secondReservedAtSnapshot).toBe(true) + expect(pendingWorktreeRemovals.has('repo-2::/other/force')).toBe(true) + refuseSecond(new Error('No space for the second record')) + await refusal + await persistWorktreeRemovalRecords() + stopBackgroundWorktreeRemovals() + await _settlePendingWorktreeRemovalsForTests() + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(directory) + + expect( + (await readWorktreeRemovalRecords(directory)).map((record) => record.worktreeId) + ).toEqual([removal.worktreeId]) + expect(waitForPendingWorktreeRemoval('repo-2::/other/force')).toBeUndefined() + expect(waitForPendingWorktreeRemoval(removal.worktreeId)).toBeDefined() }) }) diff --git a/src/main/workspaces/removal/worktree-background-removal.test.ts b/src/main/workspaces/removal/worktree-background-removal.test.ts index 830b069ffca..51ed36ee159 100644 --- a/src/main/workspaces/removal/worktree-background-removal.test.ts +++ b/src/main/workspaces/removal/worktree-background-removal.test.ts @@ -1,9 +1,14 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ExecutionHostId } from '../../../shared/execution-host' import { _resetPendingWorktreeRemovalsForTests, _settlePendingWorktreeRemovalsForTests, startBackgroundWorktreeRemoval, + loadWorktreeRemovalRecords, + waitForWorktreeRemovalAcceptance, waitForPendingWorktreeRemoval } from './worktree-background-removal' @@ -33,8 +38,14 @@ function deferred(): { promise: Promise; resolve: (value: T) => void } { } describe('background worktree removal', () => { - afterEach(() => { + let directory = '' + beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-background-removal-')) + await loadWorktreeRemovalRecords(directory) + }) + afterEach(async () => { _resetPendingWorktreeRemovalsForTests() + await rm(directory, { recursive: true, force: true }) }) it('resolves with the delete result once Git finishes, after the row has left the table', async () => { @@ -47,6 +58,7 @@ describe('background worktree removal', () => { }) expect(isPending()).toBe(true) + await waitForWorktreeRemovalAcceptance(removal.worktreeId) expect(pendingAtPublish).toEqual([true]) git.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } }) @@ -58,10 +70,9 @@ describe('background worktree removal', () => { expect(pendingAtPublish).toEqual([true, false]) }) - it('answers a request whose delete a concurrent removal of the same worktree replaced', async () => { + it('joins concurrent requests to the one recorded deletion', async () => { // The desktop IPC and runtime RPC removal paths coalesce separately, so both can be accepted. const first = deferred>() - const second = deferred<{ preservedBranch: { branchName: string; head: string } }>() const firstResult = startBackgroundWorktreeRemoval({ removal, run: () => first.promise, @@ -69,18 +80,13 @@ describe('background worktree removal', () => { }) const secondResult = startBackgroundWorktreeRemoval({ removal, - run: () => second.promise, + run: () => new Promise(() => {}), publish: () => {} }) first.resolve({}) await expect(firstResult).resolves.toEqual({}) - expect(isPending()).toBe(true) - - second.resolve({ preservedBranch: { branchName: 'feature', head: 'abc' } }) - await expect(secondResult).resolves.toEqual({ - preservedBranch: { branchName: 'feature', head: 'abc' } - }) + await expect(secondResult).resolves.toEqual({}) await _settlePendingWorktreeRemovalsForTests() expect(isPending()).toBe(false) }) @@ -129,12 +135,13 @@ describe('background worktree removal', () => { ).not.toThrow() }) - it('marks rows for clients that read the marker and omits them for clients that do not', () => { + it('marks rows for clients that read the marker and omits them for clients that do not', async () => { void startBackgroundWorktreeRemoval({ removal, run: () => new Promise(() => {}), publish: () => {} }) + await waitForWorktreeRemovalAcceptance(removal.worktreeId) const rows = [ { id: removal.worktreeId, hostId: 'local' as const }, { id: 'repo-1::/work/other' }, @@ -144,7 +151,7 @@ describe('background worktree removal', () => { expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) ).toEqual([ - { id: removal.worktreeId, hostId: 'local', removing: true }, + { id: removal.worktreeId, hostId: 'local', removing: true, removalRecorded: true }, { id: 'repo-1::/work/other' }, { id: removal.worktreeId, hostId: 'ssh:box' } ]) @@ -185,10 +192,10 @@ describe('background worktree removal', () => { for (const clientReadsMarker of [true, false]) { expect( projectPendingWorktreeRemovals(rows, (row) => row.id, clientReadsMarker, pendingAtScan) - ).toEqual([{ id: other.worktreeId }]) + ).toEqual([{ id: other.worktreeId, removalError: 'git failed' }]) } expect( projectPendingWorktreeRemovals(rows, (row) => row.id, true, snapshotPendingWorktreeRemovals()) - ).toBe(rows) + ).toEqual([{ id: removal.worktreeId }, { id: other.worktreeId, removalError: 'git failed' }]) }) }) diff --git a/src/main/workspaces/removal/worktree-background-removal.ts b/src/main/workspaces/removal/worktree-background-removal.ts index 4d016dbc1dd..c8da3913a78 100644 --- a/src/main/workspaces/removal/worktree-background-removal.ts +++ b/src/main/workspaces/removal/worktree-background-removal.ts @@ -1,3 +1,15 @@ +import { + addPendingRemoval, + assertAcceptedBranchChoice, + settlementsByWorktreeId, + waitForPendingWorktreeRemoval, + type RemovalSettlement +} from './worktree-removal-settlement' +export { + waitForPendingWorktreeRemoval, + waitForWorktreeRemovalAcceptance, + finishAcceptedWorktreeRemoval +} from './worktree-removal-settlement' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' import type { GitWorktreeInfo } from '../../../shared/worktree/types' @@ -13,8 +25,9 @@ import { finishedWorktreeRemovals, pendingWorktreeRemovals, persistWorktreeRemovalRecords, - setWorktreeRemovalRecordsDirectory, - worktreeCheckoutExists + recordedWorktreeRemovals, + recordWorktreeRemoval, + setWorktreeRemovalRecordsDirectory } from './worktree-removal-table' export type BackgroundWorktreeRemovalJob = { @@ -24,16 +37,11 @@ export type BackgroundWorktreeRemovalJob = { publish: () => void /** Clean the push-target remote even when Git partially fails. */ cleanupPushTargetRemote?: () => Promise -} - -type RemovalSettlement = { - result: Promise - resolve: (result: RemoveWorktreeResult) => void - reject: (error: unknown) => void + /** Release teardown fences when durable admission fails before run can take ownership. */ + admissionFailed?: () => Promise } const jobsByWorktreeId = new Map>() -const settlementsByWorktreeId = new Map() const stopControllers = new Set() // Loaded removals' terminal/watcher fences, held until the resumed job takes its own gate. const startupFencesByWorktreeId = new Map() @@ -48,7 +56,7 @@ export async function loadWorktreeRemovalRecords( for (const record of await readWorktreeRemovalRecords(directory)) { if (record.failure) { // Removed repos have no listing to clear a failed-removal record. - if (hasRepo(record.repoId) && (await worktreeCheckoutExists(record.worktreePath))) { + if (hasRepo(record.repoId)) { failedWorktreeRemovals.set(record.worktreeId, record) } else { droppedFailure = true @@ -56,7 +64,8 @@ export async function loadWorktreeRemovalRecords( continue } if (!pendingWorktreeRemovals.has(record.worktreeId)) { - addPendingRemoval(record) + recordedWorktreeRemovals.add(record) + addPendingRemoval(record).accept() try { startupFencesByWorktreeId.set( record.worktreeId, @@ -78,57 +87,6 @@ export function releaseStartupRemovalFence(worktreeId: string): void { startupFencesByWorktreeId.delete(worktreeId) } -function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement { - let resolve!: RemovalSettlement['resolve'] - let reject!: RemovalSettlement['reject'] - const result = new Promise((settle, fail) => { - resolve = settle - reject = fail - }) - // Older clients and restart-resumed jobs may have no caller to handle a rejection. - result.catch(() => {}) - const settlement = { result, resolve, reject } - failedWorktreeRemovals.delete(record.worktreeId) - pendingWorktreeRemovals.set(record.worktreeId, record) - settlementsByWorktreeId.set(record.worktreeId, settlement) - return settlement -} - -/** Pending removals are host-local; never join a same-ID checkout on another host. */ -export function waitForPendingWorktreeRemoval( - worktreeId: string, - hostId?: ExecutionHostId, - deleteBranch?: boolean -): Promise | undefined { - if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) { - return undefined - } - assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch) - return settlementsByWorktreeId.get(worktreeId)?.result -} - -function assertAcceptedBranchChoice( - record: WorktreeRemovalRecord | undefined, - deleteBranch: boolean | undefined -): void { - if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) { - throw new Error( - `Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.` - ) - } -} - -/** Await the delete while preserving the acceptance result fields. */ -export async function finishAcceptedWorktreeRemoval( - accepted: T, - worktreeId: string, - hostId?: ExecutionHostId -): Promise> { - const { removing, ...acceptance } = accepted - const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined - return pending ? { ...acceptance, ...(await pending) } : acceptance -} - export function removesInBackground( worktreePath: string, options: { wslDistro?: string } @@ -145,6 +103,14 @@ export function startBackgroundWorktreeRemoval( > & { worktree: Pick } } & BackgroundWorktreeRemovalJob ): Promise { + const pending = waitForPendingWorktreeRemoval( + args.removal.worktreeId, + undefined, + args.removal.deleteBranch + ) + if (pending) { + return pending + } const { worktree, ...accepted } = args.removal const record: WorktreeRemovalRecord = { ...accepted, @@ -154,8 +120,7 @@ export function startBackgroundWorktreeRemoval( requestedAt: Date.now() } const settlement = addPendingRemoval(record) - runBackgroundWorktreeRemoval(record, args, persistWorktreeRemovalRecords()) - publishSafely(args.publish) + runBackgroundWorktreeRemoval(record, args, recordWorktreeRemoval(record)) return settlement.result } @@ -167,6 +132,10 @@ export function retryFailedWorktreeRemoval( force?: boolean, deleteBranch?: boolean ): Promise | undefined { + const pending = waitForPendingWorktreeRemoval(worktreeId, hostId, deleteBranch) + if (pending) { + return pending + } const failed = (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID ? failedWorktreeRemovals.get(worktreeId) @@ -189,8 +158,7 @@ export function retryFailedWorktreeRemoval( return job.run(stopSignal) } } - runBackgroundWorktreeRemoval(record, leftoverOnly, persistWorktreeRemovalRecords()) - publishSafely(job.publish) + runBackgroundWorktreeRemoval(record, leftoverOnly, recordWorktreeRemoval(record)) return settlement.result } @@ -240,7 +208,31 @@ async function settleBackgroundWorktreeRemoval( recorded: Promise, stopSignal: AbortSignal ): Promise { - await waitForRecordWrite(record, recorded) + try { + await recorded + } catch (error) { + const refusal = new Error( + 'Could not start deletion. The workspace is still on disk; reopen any stopped terminals and try again.', + { cause: error } + ) + if (pendingWorktreeRemovals.get(record.worktreeId) === record) { + pendingWorktreeRemovals.delete(record.worktreeId) + settlementsByWorktreeId.delete(record.worktreeId) + } + try { + await job.admissionFailed?.() + } catch (cleanupError) { + console.warn('[worktrees] failed to release refused removal', cleanupError) + } + settlement?.refuse(refusal) + settlement?.reject(refusal) + publishSafely(job.publish) + return + } + if (settlement) { + settlement.accept() + } + publishSafely(job.publish) let settle: (settlement: RemovalSettlement) => void let failure: WorktreeRemovalRecord['failure'] try { @@ -285,28 +277,6 @@ async function settleBackgroundWorktreeRemoval( } } -// Prefer a durable resume record, but do not hold deletion indefinitely on stalled disk writes. -const RECORD_WRITE_WAIT_MS = 2_000 - -async function waitForRecordWrite( - record: WorktreeRemovalRecord, - recorded: Promise -): Promise { - let timer: ReturnType | undefined - const timedOut = await Promise.race([ - recorded.then(() => false), - new Promise((resolve) => { - timer = setTimeout(() => resolve(true), RECORD_WRITE_WAIT_MS) - }) - ]) - clearTimeout(timer) - if (timedOut) { - console.warn( - `[worktrees] removal record for ${record.worktreePath} not on disk after ${RECORD_WRITE_WAIT_MS} ms; deleting anyway` - ) - } -} - function publishSafely(publish: () => void): void { try { publish() diff --git a/src/main/workspaces/removal/worktree-failed-removal.test.ts b/src/main/workspaces/removal/worktree-failed-removal.test.ts index a53b2b4d97f..53870503ea0 100644 --- a/src/main/workspaces/removal/worktree-failed-removal.test.ts +++ b/src/main/workspaces/removal/worktree-failed-removal.test.ts @@ -124,7 +124,7 @@ describe('a delete that fails after Git dropped the registration', () => { false, snapshotPendingWorktreeRemovals() ) - ).toEqual(rows) + ).toEqual([{ id: worktreeId, removalError: GIT_ERROR }]) // Nothing fences the leftover: a failed delete must not block terminals indefinitely. beginTerminalInstall(checkout)() }) @@ -230,14 +230,21 @@ describe('a delete that fails after Git dropped the registration', () => { ]) }) - it('ends at the next listing once the checkout is deleted outside Orca', async () => { + it('keeps an absent-folder failure across restart until explicit cleanup succeeds', async () => { await failRemoval() await rm(checkout, { recursive: true }) + _resetPendingWorktreeRemovalsForTests() + await loadWorktreeRemovalRecords(join(directory, 'profile')) + expect(await listRows()).toEqual([mainWorktree, leftoverRow()]) + const retried = retryFailedWorktreeRemoval(worktreeId, 'local', () => ({ + run: async () => ({}), + publish: () => {} + })) + await expect(retried).resolves.toEqual({}) + await _settlePendingWorktreeRemovalsForTests() expect(await listRows()).toEqual([mainWorktree]) - await vi.waitFor(async () => - expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([]) - ) + expect(await readWorktreeRemovalRecords(join(directory, 'profile'))).toEqual([]) }) it('ends at startup once its repo is removed from Orca, leaving the files', async () => { diff --git a/src/main/workspaces/removal/worktree-removal-failure.ts b/src/main/workspaces/removal/worktree-removal-failure.ts index 0aea6fbd3f2..d711f22f7d3 100644 --- a/src/main/workspaces/removal/worktree-removal-failure.ts +++ b/src/main/workspaces/removal/worktree-removal-failure.ts @@ -13,18 +13,18 @@ export async function failureLeftByGit( error: unknown, cleanupPushTargetRemote: (() => Promise) | undefined ): Promise { - if (!(await worktreeCheckoutExists(record.worktreePath))) { - return undefined - } const message = error instanceof Error ? error.message : String(error) const failure = { message: message.replace( / Close (?:that program|any program using it) and delete again\.$/, () => - ` Close any program using it. You may need to delete the remaining folder at ${record.worktreePath} manually to finish removing this workspace.` + ` Close any program using it, then retry deletion. If you removed the folder at ${record.worktreePath} yourself, retry deletion to finish cleanup.` ), failedAt: Date.now() } + if (!(await worktreeCheckoutExists(record.worktreePath))) { + return failure + } try { const registered = await registeredRemovalCheckout(record) if (registered) { diff --git a/src/main/workspaces/removal/worktree-removal-leftover.ts b/src/main/workspaces/removal/worktree-removal-leftover.ts index 3ec38498863..ca6a13e2742 100644 --- a/src/main/workspaces/removal/worktree-removal-leftover.ts +++ b/src/main/workspaces/removal/worktree-removal-leftover.ts @@ -14,6 +14,7 @@ import type { WorktreeRemovalRecord } from './worktree-removal-records' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { CLIENT_REMOVAL_HOME } from './worktree-removal-home-guard' import { failedWorktreeRemovals, worktreeCheckoutExists } from './worktree-removal-table' +import { waitForWorktreeRemovalAcceptance } from './worktree-removal-settlement' import { assertWorktreeDoesNotContainRegisteredWorktree, canSafelyRemoveOrphanedWorktreeDirectory @@ -90,5 +91,9 @@ export async function retryFailedRemovalUnlessRegistered( if (failed && !usesNativeWindowsRemoval(worktreePath, localOptions)) { await assertUnregisteredCheckoutGone(failed.worktreePath, registeredWorktrees) } - return retry() !== undefined + if (retry() === undefined) { + return false + } + await waitForWorktreeRemovalAcceptance(worktreeId) + return true } diff --git a/src/main/workspaces/removal/worktree-removal-listing.ts b/src/main/workspaces/removal/worktree-removal-listing.ts index 6ff79174512..a12bd5cc4db 100644 --- a/src/main/workspaces/removal/worktree-removal-listing.ts +++ b/src/main/workspaces/removal/worktree-removal-listing.ts @@ -11,6 +11,7 @@ import { finishedWorktreeRemovals, pendingWorktreeRemovals, persistWorktreeRemovalRecords, + recordedWorktreeRemovals, worktreeCheckoutExists } from './worktree-removal-table' @@ -42,7 +43,9 @@ export async function withUnregisteredRemovalCheckouts( droppedFailure = true return row }) - const unlisted = [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()].filter( + const unlisted = [ + ...new Map([...pendingWorktreeRemovals, ...failedWorktreeRemovals]).values() + ].filter( (record) => record.repoId === repoId && !gitWorktrees.some((worktree) => areWorktreePathsEqual(worktree.path, record.worktreePath)) @@ -51,8 +54,8 @@ export async function withUnregisteredRemovalCheckouts( for (const record of unlisted) { const failed = failedWorktreeRemovals.get(record.worktreeId) === record if ( - (await worktreeCheckoutExists(record.worktreePath)) && - (!failed || (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath))) + (!failed && (await worktreeCheckoutExists(record.worktreePath))) || + (failed && (await isUnregisteredRemovalLeftover(record.repoPath, record.worktreePath))) ) { leftovers.push({ path: record.worktreePath, @@ -80,26 +83,46 @@ export function snapshotPendingWorktreeRemovals(): PendingWorktreeRemovals { /** Older clients cannot read removing markers; omit pending rows they already dropped on acceptance. */ export function projectPendingWorktreeRemovals< - T extends { hostId?: ExecutionHostId; removing?: true } + T extends { + hostId?: ExecutionHostId + removing?: true + removalRecorded?: true + removalError?: string + } >( rows: T[], idOf: (row: T) => string, clientReadsMarker: boolean, pendingAtScan: PendingWorktreeRemovals ): T[] { - if (pendingWorktreeRemovals.size === 0 && pendingAtScan.size === 0) { + if ( + pendingWorktreeRemovals.size === 0 && + pendingAtScan.size === 0 && + failedWorktreeRemovals.size === 0 + ) { return rows } const projected: T[] = [] for (const row of rows) { const id = idOf(row) const local = row.hostId === undefined || row.hostId === LOCAL_EXECUTION_HOST_ID - if (local && pendingWorktreeRemovals.has(id)) { + const pending = local ? pendingWorktreeRemovals.get(id) : undefined + if (pending && recordedWorktreeRemovals.has(pending)) { if (clientReadsMarker) { - projected.push({ ...row, removing: true }) + projected.push({ ...row, removing: true, removalRecorded: true }) } continue } + const failed = local ? failedWorktreeRemovals.get(id) : undefined + if (failed) { + projected.push({ + ...row, + removing: undefined, + removalRecorded: undefined, + removalError: failed.failure?.message + }) + continue + } const scanned = local ? pendingAtScan.get(id) : undefined // Git was read before deletion finished; do not resurrect the stale row as a failed delete. if (!scanned || !finishedWorktreeRemovals.has(scanned)) { @@ -108,3 +131,25 @@ export function projectPendingWorktreeRemovals< } return projected } + +export type WorktreeRemovalWitnessScan = { + removals?: PendingWorktreeRemovals + projectedRemovals?: PendingWorktreeRemovals +} + +/** Reuse repo-local witnesses across metadata joins; replace them only when reservations change. */ +export function projectCachedWorktreeRemovals( + repoId: string, + scan: WorktreeRemovalWitnessScan, + rows: T[], + idOf: (row: T) => string +): T[] { + const current = pendingWorktreeRemovals.snapshotForRepo(repoId) + if (scan.projectedRemovals !== current) { + if (current.size > 0) { + scan.removals = new Map([...(scan.removals ?? []), ...current]) + } + scan.projectedRemovals = current + } + return projectPendingWorktreeRemovals(rows, idOf, true, scan.removals ?? current) +} diff --git a/src/main/workspaces/removal/worktree-removal-records.ts b/src/main/workspaces/removal/worktree-removal-records.ts index a7bd71c18ed..6a255568d30 100644 --- a/src/main/workspaces/removal/worktree-removal-records.ts +++ b/src/main/workspaces/removal/worktree-removal-records.ts @@ -22,7 +22,7 @@ export type WorktreeRemovalRecord = { deleteBranch: boolean force: boolean requestedAt: number - /** Git dropped registration; branch/remote cleanup ran, but the folder remains. */ + /** Cleanup failed; files, Git ownership or metadata may still need an explicit retry. */ failure?: WorktreeRemovalFailure } @@ -97,13 +97,15 @@ export async function readWorktreeRemovalRecords( /** Read current records when the queued write runs so newer state wins. */ export function writeWorktreeRemovalRecords( directory: string, - current: () => WorktreeRemovalRecord[] + current: () => WorktreeRemovalRecord[], + committed?: () => void ): Promise { const file = worktreeRemovalRecordsFile(directory) - return withSidecarSnapshotQueue(file, () => - writeSidecarSnapshot(file, { + return withSidecarSnapshotQueue(file, async () => { + await writeSidecarSnapshot(file, { version: RECORDS_VERSION, removals: current() } satisfies PersistedWorktreeRemovalRecords) - ) + committed?.() + }) } diff --git a/src/main/workspaces/removal/worktree-removal-reservations.ts b/src/main/workspaces/removal/worktree-removal-reservations.ts new file mode 100644 index 00000000000..94f7d4de80e --- /dev/null +++ b/src/main/workspaces/removal/worktree-removal-reservations.ts @@ -0,0 +1,65 @@ +import type { WorktreeRemovalRecord } from './worktree-removal-records' + +const NO_REMOVALS: ReadonlyMap = new Map() + +/** Repo snapshots change only with their reservations, never with unrelated metadata joins. */ +export class WorktreeRemovalReservations extends Map { + private readonly byRepo = new Map>() + private readonly snapshots = new Map>() + + override set(id: string, record: WorktreeRemovalRecord): this { + const previous = this.get(id) + if (previous === record) { + return this + } + if (previous) { + this.removeRepoRecord(id, previous.repoId) + } + super.set(id, record) + let records = this.byRepo.get(record.repoId) + if (!records) { + records = new Map() + this.byRepo.set(record.repoId, records) + } + records.set(id, record) + this.snapshots.delete(record.repoId) + return this + } + + override delete(id: string): boolean { + const previous = this.get(id) + if (!previous) { + return false + } + this.removeRepoRecord(id, previous.repoId) + return super.delete(id) + } + + override clear(): void { + super.clear() + this.byRepo.clear() + this.snapshots.clear() + } + + snapshotForRepo(repoId: string): ReadonlyMap { + const records = this.byRepo.get(repoId) + if (!records) { + return NO_REMOVALS + } + let snapshot = this.snapshots.get(repoId) + if (!snapshot) { + snapshot = new Map(records) + this.snapshots.set(repoId, snapshot) + } + return snapshot + } + + private removeRepoRecord(id: string, repoId: string): void { + const records = this.byRepo.get(repoId) + records?.delete(id) + if (records?.size === 0) { + this.byRepo.delete(repoId) + } + this.snapshots.delete(repoId) + } +} diff --git a/src/main/workspaces/removal/worktree-removal-settlement.ts b/src/main/workspaces/removal/worktree-removal-settlement.ts new file mode 100644 index 00000000000..ee9f9c085cd --- /dev/null +++ b/src/main/workspaces/removal/worktree-removal-settlement.ts @@ -0,0 +1,82 @@ +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' +import type { RemoveWorktreeResult } from '../../../shared/worktree/create-types' +import type { WorktreeRemovalRecord } from './worktree-removal-records' +import { pendingWorktreeRemovals } from './worktree-removal-table' + +export type RemovalSettlement = { + accepted: Promise + accept: () => void + refuse: (error: unknown) => void + result: Promise + resolve: (result: RemoveWorktreeResult) => void + reject: (error: unknown) => void +} + +export const settlementsByWorktreeId = new Map() + +export function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement { + let accept!: RemovalSettlement['accept'] + let refuse!: RemovalSettlement['refuse'] + const accepted = new Promise((resolve, reject) => { + accept = resolve + refuse = reject + }) + accepted.catch(() => {}) + let resolve!: RemovalSettlement['resolve'] + let reject!: RemovalSettlement['reject'] + const result = new Promise((settle, fail) => { + resolve = settle + reject = fail + }) + // Older clients and restart-resumed jobs may have no caller to handle a rejection. + result.catch(() => {}) + const settlement = { accepted, accept, refuse, result, resolve, reject } + pendingWorktreeRemovals.set(record.worktreeId, record) + settlementsByWorktreeId.set(record.worktreeId, settlement) + return settlement +} + +/** Acceptance is separate from completion so CLI outcomes can keep waiting for Git. */ +export function waitForWorktreeRemovalAcceptance( + worktreeId: string, + hostId?: ExecutionHostId +): Promise | undefined { + return (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID + ? settlementsByWorktreeId.get(worktreeId)?.accepted + : undefined +} + +/** Pending removals are host-local; never join a same-ID checkout on another host. */ +export function waitForPendingWorktreeRemoval( + worktreeId: string, + hostId?: ExecutionHostId, + deleteBranch?: boolean +): Promise | undefined { + if ((hostId ?? LOCAL_EXECUTION_HOST_ID) !== LOCAL_EXECUTION_HOST_ID) { + return undefined + } + assertAcceptedBranchChoice(pendingWorktreeRemovals.get(worktreeId), deleteBranch) + return settlementsByWorktreeId.get(worktreeId)?.result +} + +export function assertAcceptedBranchChoice( + record: WorktreeRemovalRecord | undefined, + deleteBranch: boolean | undefined +): void { + if (record && deleteBranch !== undefined && record.deleteBranch !== deleteBranch) { + throw new Error( + `Orca already accepted removal of ${record.worktreePath} with a different branch choice. That cleanup may already have run; check the branch before retrying.` + ) + } +} + +/** Await the delete while preserving the acceptance result fields. */ +export async function finishAcceptedWorktreeRemoval( + accepted: T, + worktreeId: string, + hostId?: ExecutionHostId +): Promise> { + const { removing, ...acceptance } = accepted + const pending = removing ? waitForPendingWorktreeRemoval(worktreeId, hostId) : undefined + return pending ? { ...acceptance, ...(await pending) } : acceptance +} diff --git a/src/main/workspaces/removal/worktree-removal-table.ts b/src/main/workspaces/removal/worktree-removal-table.ts index 069bfea06df..363fab881aa 100644 --- a/src/main/workspaces/removal/worktree-removal-table.ts +++ b/src/main/workspaces/removal/worktree-removal-table.ts @@ -1,9 +1,11 @@ +import { WorktreeRemovalReservations } from './worktree-removal-reservations' import { lstat } from 'node:fs/promises' import { getErrorCode } from '../../git/worktrees/worktree-operation-options' import { areWorktreePathsEqual } from '../../git/worktrees/catalog/worktree-path-comparison' import { writeWorktreeRemovalRecords, type WorktreeRemovalRecord } from './worktree-removal-records' -export const pendingWorktreeRemovals = new Map() +export const pendingWorktreeRemovals = new WorktreeRemovalReservations() +export const recordedWorktreeRemovals = new WeakSet() // Failed leftovers stay visible until gone/replaced or their repo is removed; never retry without a request. export const failedWorktreeRemovals = new Map() // In-flight listings retain completed records only until their stale Git read is projected. @@ -18,14 +20,41 @@ export function persistWorktreeRemovalRecords(): Promise { if (!recordsDirectory) { return Promise.resolve() } - return writeWorktreeRemovalRecords(recordsDirectory, () => [ - ...pendingWorktreeRemovals.values(), - ...failedWorktreeRemovals.values() - ]).catch((error: unknown) => { + return writeWorktreeRemovalRecords(recordsDirectory, journalRecords).catch((error: unknown) => { console.warn('[worktrees] failed to persist worktree removal records', error) }) } +function journalRecords(candidate?: WorktreeRemovalRecord): WorktreeRemovalRecord[] { + const records = new Map(failedWorktreeRemovals) + for (const record of pendingWorktreeRemovals.values()) { + if (recordedWorktreeRemovals.has(record)) { + records.set(record.worktreeId, record) + } + } + if (candidate) { + records.set(candidate.worktreeId, candidate) + } + return [...records.values()] +} + +/** Commit only this admission; unrelated reservations must never reach a restart's journal. */ +export function recordWorktreeRemoval(record: WorktreeRemovalRecord): Promise { + if (!recordsDirectory) { + return Promise.reject( + new Error('Could not start deletion. Reopen the workspace and try again.') + ) + } + return writeWorktreeRemovalRecords( + recordsDirectory, + () => journalRecords(record), + () => { + recordedWorktreeRemovals.add(record) + failedWorktreeRemovals.delete(record.worktreeId) + } + ) +} + /** Unreadable counts as present: only a checkout proven gone ends a failed delete. */ export async function worktreeCheckoutExists(worktreePath: string): Promise { try { @@ -46,7 +75,7 @@ export function findPendingWorktreeRemovalConflict( target: { worktreePath?: string; branch?: string } ): WorktreeRemovalRecord | undefined { const branch = target.branch?.replace(/^refs\/heads\//, '') - for (const removal of pendingWorktreeRemovals.values()) { + for (const removal of [...pendingWorktreeRemovals.values(), ...failedWorktreeRemovals.values()]) { if (!areWorktreePathsEqual(removal.repoPath, repoPath)) { continue } @@ -67,7 +96,9 @@ export function assertNoPendingWorktreeRemovalConflict( const removal = findPendingWorktreeRemovalConflict(repoPath, target) if (removal) { throw new Error( - `Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.` + removal.failure + ? `Cleanup failed for the workspace at ${removal.worktreePath}. Retry deleting it before reusing its path or branch.` + : `Orca is still deleting the workspace at ${removal.worktreePath}. Cleanup is pending; try again shortly.` ) } } diff --git a/src/renderer/src/components/cmd-j/palette-filter-options.ts b/src/renderer/src/components/cmd-j/palette-filter-options.ts index 8bae0b17996..4a35710e7a7 100644 --- a/src/renderer/src/components/cmd-j/palette-filter-options.ts +++ b/src/renderer/src/components/cmd-j/palette-filter-options.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import { getRepoDisplayLabelKey, getRepoDisplayLabelsByPath @@ -140,7 +141,7 @@ export function buildPaletteFilterModel({ const worktreeCountByHostId = new Map() const worktreeCountByRepoId = new Map() for (const worktree of worktrees) { - if (worktree.isArchived) { + if (worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) { continue } const hostId = resolveWorktreeFilterHostId(worktree, repoById, defaultHostId) diff --git a/src/renderer/src/components/cmd-j/task-search-activation.ts b/src/renderer/src/components/cmd-j/task-search-activation.ts index d91c784d676..b5a5a9d61ec 100644 --- a/src/renderer/src/components/cmd-j/task-search-activation.ts +++ b/src/renderer/src/components/cmd-j/task-search-activation.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import { useAppStore } from '@/store' import { getPaletteWorktreeExecutionHostId } from '@/lib/workspace/search/palette-repo-resolution' import { getWorkspaceAttachments } from '../../../../shared/workspace-attachments/workspace-attachments' @@ -56,7 +57,7 @@ export function findCmdJTaskWorkspace( return undefined } return workspaces - .filter((workspace) => !workspace.isArchived) + .filter((workspace) => !workspace.isArchived && !isWorktreeRetiredByRemoval(workspace)) .find((workspace) => getWorkspaceAttachments(workspace).some((item) => { if ( diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx index 5fdd9e245fd..5fe6028bf60 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx +++ b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx @@ -159,19 +159,28 @@ beforeEach(() => { afterEach(cleanup) describe('ComposerParentWorktreePicker', () => { - it('restricts candidates to the active folder workspace subtree', () => { + it('offers live folder descendants through retired roots and intermediate parents', () => { const attached = makeWorktree({ id: 'attached', displayName: 'Attached', - instanceId: 'attached-instance' + instanceId: 'attached-instance', + removing: true, + removalRecorded: true }) const nested = makeWorktree({ id: 'nested', displayName: 'Nested', instanceId: 'nested-instance' }) + const bridge = makeWorktree({ + id: 'bridge', + instanceId: 'bridge-instance', + removing: true, + removalRecorded: true + }) + const leaf = makeWorktree({ id: 'leaf', displayName: 'Leaf', instanceId: 'leaf-instance' }) const outside = makeWorktree({ id: 'outside', displayName: 'Outside' }) - seed([attached, nested, outside]) + seed([attached, nested, bridge, leaf, outside]) storeState.workspaceLineageByChildKey = { [worktreeWorkspaceKey(attached.id)]: { childWorkspaceKey: worktreeWorkspaceKey(attached.id), @@ -192,23 +201,45 @@ describe('ComposerParentWorktreePicker', () => { origin: 'manual', capture: { source: 'manual-action', confidence: 'explicit' }, createdAt: 2 + }, + [bridge.id]: { + worktreeId: bridge.id, + worktreeInstanceId: 'bridge-instance', + parentWorktreeId: nested.id, + parentWorktreeInstanceId: 'nested-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 3 + }, + [leaf.id]: { + worktreeId: leaf.id, + worktreeInstanceId: 'leaf-instance', + parentWorktreeId: bridge.id, + parentWorktreeInstanceId: 'bridge-instance', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 4 } } - + const onChange = vi.fn() render( ) fireEvent.click(trigger()) const labels = candidateLabels().join(' ') - expect(labels).toContain('Attached') + expect(labels).not.toContain('Attached') + expect(labels).not.toContain('bridge') expect(labels).toContain('Nested') + expect(labels).toContain('Leaf') expect(labels).not.toContain('Outside') + fireEvent.click(rows().find((row) => row.textContent?.includes('Leaf'))!) + expect(onChange).toHaveBeenCalledWith('leaf') }) it('closes an open popover when the drawer collapses the trigger', () => { diff --git a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx index 2606c2dd035..47c245cc8fb 100644 --- a/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx +++ b/src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { Check, ChevronsUpDown, GitBranch } from 'lucide-react' @@ -68,11 +69,10 @@ type ComposerParentWorktreePickerProps = { activeFolderWorkspaceId?: string | null } -type ParentWorktreeCandidateListProps = { - repoId: string - executionHostId?: ExecutionHostId | null - projectId?: string | null - value: string | null +type ParentWorktreeCandidateListProps = Omit< + ComposerParentWorktreePickerProps, + 'onChange' | 'disabled' | 'activeFolderWorkspaceId' +> & { activeFolderWorkspaceId: string | null onSelect: (id: string | null) => void } @@ -104,7 +104,9 @@ function ComposerParentWorktreePickerImpl({ (row) => getWorktreeHostIdentity(row) === value ) : getIndexedWorktreeById(selectWorktreesByRepo(s), value) - return parent && !parent.isArchived ? parent.displayName : null + return parent && !parent.isArchived && !isWorktreeRetiredByRemoval(parent) + ? parent.displayName + : null }) // Close during render when the drawer disables its trigger; portaled content would otherwise linger through a stale-open frame. @@ -251,6 +253,7 @@ function ParentWorktreeCandidateList({ .filter( (candidate) => !candidate.isArchived && + !isWorktreeRetiredByRemoval(candidate) && ((folderSubtreeIds === null && isCrossStoreCandidate(candidate)) || (sharesWorktreeLineageBoundary(childBoundary, { ...candidate, diff --git a/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts b/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts new file mode 100644 index 00000000000..dafde43ea40 --- /dev/null +++ b/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts @@ -0,0 +1,82 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { showWorkspaceForFile } from './plugin-view-editor-workspace' +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' + +const activation = vi.hoisted(() => ({ activateAndRevealWorkspace: vi.fn() })) +vi.mock('@/lib/workspace/activation/worktree-activation', () => activation) +const initialState = useAppStore.getState() +afterEach(() => { + useAppStore.setState(initialState, true) + vi.clearAllMocks() +}) + +it('refuses a retired file owner without registering its deleting directory as a folder', async () => { + const addRepoPath = vi.fn() + const row = makeWorktree({ + id: 'r::/work/feature', + repoId: 'r', + path: '/work/feature', + hostId: 'local', + removing: true, + removalRecorded: true + }) + useAppStore.setState({ + worktreesByRepo: { r: [row] }, + folderWorkspaces: [], + activeWorktreeId: null, + addRepoPath + }) + await expect( + showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature') + ).resolves.toBeNull() + expect(addRepoPath).not.toHaveBeenCalled() + expect(activation.activateAndRevealWorkspace).not.toHaveBeenCalled() + + useAppStore.setState({ worktreesByRepo: { r: [{ ...row, removalRecorded: undefined }] } }) + await expect( + showWorkspaceForFile(['/work/feature/document.ext'], '/work/feature') + ).resolves.toMatchObject({ worktreeId: row.id }) + expect(addRepoPath).not.toHaveBeenCalled() + expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, { + providesInitialSurface: true, + executionHostId: 'local' + }) +}) + +it('still registers a genuinely unowned file folder and opens it', async () => { + const row = makeWorktree({ + id: 'added::/new/folder', + repoId: 'added', + path: '/new/folder', + hostId: 'local' + }) + const addRepoPath = vi.fn(async () => { + useAppStore.setState({ worktreesByRepo: { added: [row] } }) + return { + id: 'added', + path: '/new/folder', + displayName: 'added', + badgeColor: 'blue', + addedAt: 1 + } + }) + const fetchWorktrees = vi.fn().mockResolvedValue(true) + useAppStore.setState({ + worktreesByRepo: {}, + folderWorkspaces: [], + activeWorktreeId: null, + addRepoPath, + fetchWorktrees + }) + await expect( + showWorkspaceForFile(['/new/folder/document.ext'], '/new/folder') + ).resolves.toMatchObject({ worktreeId: row.id, addedRepoId: 'added' }) + expect(addRepoPath).toHaveBeenCalledWith('/new/folder', 'folder', { runtimeEnvironmentId: null }) + expect(fetchWorktrees).toHaveBeenCalledWith('added') + expect(activation.activateAndRevealWorkspace).toHaveBeenCalledWith(row.id, { + providesInitialSurface: true, + executionHostId: 'local' + }) +}) diff --git a/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.ts b/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.ts index 94569ec9533..7ba2f0ff727 100644 --- a/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.ts +++ b/src/renderer/src/components/plugins/view/plugin-view-editor-workspace.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import { toWorktreeRelativePath } from '../../../../../shared/terminal/links/terminal-links' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import type { FolderWorkspace } from '../../../../../shared/folder-workspaces/folder-workspace-types' @@ -10,7 +11,14 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' -type WorkspaceRow = { id: string; path: string; hostId?: string; isArchived?: boolean } +type WorkspaceRow = { + id: string + path: string + hostId?: string + isArchived?: boolean + removing?: true + removalRecorded?: true +} export type PluginEditorWorkspace = { worktreeId: string @@ -47,7 +55,7 @@ export function findWorkspaceShowingFile( let best: (PluginEditorWorkspace & { depth: number; active: boolean }) | null = null for (const worktree of workspaces) { const local = worktree.hostId === undefined || worktree.hostId === LOCAL_EXECUTION_HOST_ID - if (!local || worktree.isArchived) { + if (!local || worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) { continue } for (const filePath of paths) { @@ -74,21 +82,34 @@ export function findWorkspaceShowingFile( /** * The workspace to open `paths[0]` in, made active: one that shows the file, else its folder added - * as a folder workspace on this machine. Null when Orca could not add the folder. + * as a folder workspace on this machine. Null when it is being deleted or could not be added. */ export async function showWorkspaceForFile( paths: readonly string[], fallbackFolder: string ): Promise { - const find = (): PluginEditorWorkspace | null => { + const find = (): PluginEditorWorkspace | null | 'removing' => { const state = useAppStore.getState() const rows = [ ...Object.values(selectWorktreesByRepo(state) ?? {}).flat(), ...folderWorkspaceRows(selectFolderWorkspaces(state)) ] + if ( + rows.some( + (row) => + (row.hostId === undefined || row.hostId === LOCAL_EXECUTION_HOST_ID) && + isWorktreeRetiredByRemoval(row) && + paths.some((path) => toWorktreeRelativePath(path, row.path) !== null) + ) + ) { + return 'removing' + } return findWorkspaceShowingFile(rows, paths, state.activeWorktreeId) } let found = find() + if (found === 'removing') { + return null + } let addedRepoId: string | undefined if (!found) { const state = useAppStore.getState() @@ -101,7 +122,7 @@ export async function showWorkspaceForFile( addedRepoId = repo.id found = find() } - if (!found) { + if (!found || found === 'removing') { return null } const state = useAppStore.getState() diff --git a/src/renderer/src/components/plugins/view/plugin-view-workspace-pick.ts b/src/renderer/src/components/plugins/view/plugin-view-workspace-pick.ts index ae1cb54e0cb..d05b6695105 100644 --- a/src/renderer/src/components/plugins/view/plugin-view-workspace-pick.ts +++ b/src/renderer/src/components/plugins/view/plugin-view-workspace-pick.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import { folderWorkspaceKey } from '../../../../../shared/workspace-scope' import { getFolderWorkspaceWorktreeHostId } from '../../../../../shared/folder-workspaces/folder-workspace-worktree' @@ -7,6 +8,8 @@ type PickableWorktree = { id: string hostId?: string isArchived?: boolean + removing?: true + removalRecorded?: true lastActivityAt?: number } @@ -22,7 +25,7 @@ export function pickWorkspaceToShow( hostId === undefined || hostId === LOCAL_EXECUTION_HOST_ID const worktree = Object.values(worktreesByRepo ?? {}) .flat() - .filter((each) => !each.isArchived && isLocal(each.hostId)) + .filter((each) => !each.isArchived && !isWorktreeRetiredByRemoval(each) && isLocal(each.hostId)) .reduce( (best, each) => !best || (each.lastActivityAt ?? 0) > (best.lastActivityAt ?? 0) ? each : best, diff --git a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts index 904c12a5d16..3b1f4be50c8 100644 --- a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts +++ b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.test.ts @@ -1,13 +1,19 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { getFolderWorkspaceWorktree } from '../../../../shared/folder-workspaces/folder-workspace-worktree' import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' -import { resolveSidebarLineageParentIdentities } from '../../../../shared/sidebar-list/worktree-lineage-projection' +import { + getProjectedWorktreeLineageChildrenByParentId, + resolveSidebarLineageParentIdentities +} from '../../../../shared/sidebar-list/worktree-lineage-projection' import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' import type { Worktree } from '../../../../shared/worktree/types' import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' -import { getAttachedWorktreesForFolderWorkspace } from './folder-workspace-attached-worktrees' +import { + getAttachedWorktreesForFolderWorkspace, + getLineageChildrenByParentId +} from './folder-workspace-attached-worktrees' function makeFolder(id = 'folder-1'): FolderWorkspace { return { @@ -258,3 +264,144 @@ it('attaches cross-store roots only to the resolved host when folder IDs collide expect(local.childWorktrees).toEqual([]) expect(paired.owners.map((owner) => owner.worktree.id)).toEqual(['root', 'child']) }) + +it('retires an attached worktree at durable admission while legacy pending rows remain visible', () => { + const child = makeWorktree({ id: 'repo-1::/retiring', removing: true }) + const list = (row: Worktree) => + getAttachedWorktreesForFolderWorkspace({ + activeWorkspaceKey: folderWorkspaceKey('folder-1'), + activeWorktreeId: null, + folderWorkspaces: [makeFolder()], + workspaceLineageByChildKey: { [row.id]: makeWorkspaceLineage(row) }, + worktreeLineageById: {}, + worktreesByRepo: { 'repo-1': [row] }, + crossStoreChildrenByFolderId: new Map() + }).childWorktrees.map((row) => row.id) + expect(list(child)).toEqual(['repo-1::/retiring']) + expect(list({ ...child, removalRecorded: true })).toEqual([]) +}) + +it.each([false, true])( + 'keeps live descendants through retired bridges, retired cross-store root=%s', + (retiredRoot) => { + const hostId = retiredRoot ? 'ssh:box' : 'local' + const root = makeWorktree({ + id: 'root', + hostId, + instanceId: 'root', + removing: retiredRoot ? true : undefined, + removalRecorded: retiredRoot ? true : undefined + }) + const bridge = makeWorktree({ + id: 'bridge', + hostId, + instanceId: 'bridge', + removing: true, + removalRecorded: true + }) + const child = makeWorktree({ id: 'child', hostId, instanceId: 'child' }) + const leaf = makeWorktree({ id: 'leaf', hostId, instanceId: 'leaf' }) + const lineage = { + bridge: edge(bridge, root, 2), + child: edge(child, bridge, 3), + leaf: edge(leaf, child, 4) + } + const result = getAttachedWorktreesForFolderWorkspace({ + activeWorkspaceKey: folderWorkspaceKey('folder-1'), + activeWorktreeId: null, + folderWorkspaces: [makeFolder()], + workspaceLineageByChildKey: retiredRoot ? {} : { root: makeWorkspaceLineage(root) }, + worktreeLineageById: lineage, + worktreesByRepo: { 'repo-1': [root, bridge, child, leaf] }, + lineageParentIdentities: new Map([ + [getWorktreeHostIdentity(root), 'local|folder:folder-1'], + [getWorktreeHostIdentity(bridge), getWorktreeHostIdentity(root)], + [getWorktreeHostIdentity(child), getWorktreeHostIdentity(bridge)], + [getWorktreeHostIdentity(leaf), getWorktreeHostIdentity(child)] + ]), + crossStoreChildrenByFolderId: new Map(retiredRoot ? [['folder-1', [root]]] : []) + }) + expect(result.owners.map((owner) => owner.worktree.id)).toEqual( + retiredRoot ? ['child', 'leaf'] : ['root', 'child', 'leaf'] + ) + expect(result.childWorktrees.map((row) => row.id).sort()).toEqual( + retiredRoot ? ['child', 'leaf'] : ['child', 'leaf', 'root'] + ) + expect(result.rootChildWorktrees.map((row) => row.id).sort()).toEqual( + retiredRoot ? ['child'] : ['child', 'root'] + ) + expect([...result.lineageChildrenByParentId]).toEqual([ + [getWorktreeHostIdentity(child), [leaf]] + ]) + } +) + +it('traverses retired chains with at most two visits per vertex and edge at N and 10N', () => { + for (const size of [100, 1000]) { + const nodes = Array.from({ length: size }, (_, index) => + makeWorktree({ + id: `node-${index}`, + instanceId: `instance-${index}`, + removing: index < size - 1 ? true : undefined, + removalRecorded: index < size - 1 ? true : undefined + }) + ) + const rows = new Map(nodes.map((row) => [row.id, row])) + let catalogEnumerations = 0 + let catalogReads = 0 + const lineage = new Proxy( + Object.fromEntries( + nodes.slice(1).map((row, index) => [row.id, edge(row, nodes[index], index)]) + ), + { + ownKeys: (target) => { + catalogEnumerations++ + return Reflect.ownKeys(target) + }, + get: (target, key) => { + catalogReads++ + return typeof key === 'string' ? target[key] : undefined + } + } + ) + // The existing index is shared; count the two required reachability/emission passes over it. + const adjacency = getProjectedWorktreeLineageChildrenByParentId(lineage, rows) + let edgeVisits = 0 + for (const children of adjacency.values()) { + for (let index = 0; index < children.length; index++) { + const child = children[index] + Object.defineProperty(children, index, { + configurable: true, + get: () => { + edgeVisits++ + return child + } + }) + } + } + const vertexVisits = vi.spyOn(adjacency, 'get') + const rowValues = vi.spyOn(rows, 'values') + const rowIterator = vi.spyOn(rows, Symbol.iterator) + const rowReads = vi.spyOn(rows, 'get') + catalogEnumerations = 0 + catalogReads = 0 + try { + const result = getLineageChildrenByParentId(lineage, rows, new Set([nodes[0].id])) + expect([...result.values()].flat().map((row) => row.id)).toEqual([`node-${size - 1}`]) + expect(vertexVisits.mock.calls.length).toBeGreaterThanOrEqual(size) + expect(vertexVisits.mock.calls.length).toBeLessThanOrEqual(2 * size) + expect(edgeVisits).toBeGreaterThanOrEqual(size - 1) + expect(edgeVisits).toBeLessThanOrEqual(2 * (size - 1)) + expect(catalogEnumerations).toBe(0) + expect(catalogReads).toBe(0) + expect(rowValues).not.toHaveBeenCalled() + expect(rowIterator).not.toHaveBeenCalled() + expect(rowReads.mock.calls.length).toBeLessThanOrEqual(size) + } finally { + vertexVisits.mockRestore() + rowValues.mockRestore() + rowIterator.mockRestore() + rowReads.mockRestore() + } + } +}) diff --git a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts index 169736a8f02..68c4d2e2b74 100644 --- a/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts +++ b/src/renderer/src/components/right-sidebar/folder-workspace-attached-worktrees.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' @@ -126,16 +127,22 @@ export function getAttachedWorktreesForFolderWorkspace({ rootLineageByChildId.set(child.worktreeId, entries) } const members = new Map() + const visited = new Set() const queue: Worktree[] = [] const add = (worktree: Worktree, attachedAt: number) => { const identity = getWorktreeHostIdentity(worktree) if ( worktree.isArchived || - members.has(identity) || + visited.has(identity) || selectedById.get(worktree.id) !== worktree ) { return } + visited.add(identity) + queue.push(worktree) + if (isWorktreeRetiredByRemoval(worktree)) { + return + } members.set(identity, { worktreeId: worktree.id, repoId: worktree.repoId, @@ -143,7 +150,6 @@ export function getAttachedWorktreesForFolderWorkspace({ worktree, attachedAt }) - queue.push(worktree) } for (const row of rows.values()) { const lineage = rootLineageByChildId @@ -231,7 +237,8 @@ export function getLineageChildrenByParentId( const descendantsByParentId = new Map() for (const parentId of includedIds) { const children = (projectedChildrenByParentId.get(parentId) ?? []).filter( - (child) => includedIds.has(child.id) && !child.isArchived + (child) => + includedIds.has(child.id) && !child.isArchived && !isWorktreeRetiredByRemoval(child) ) if (children.length > 0) { descendantsByParentId.set(parentId, children) @@ -245,7 +252,7 @@ export function getLineageChildrenByParentId( return descendantsByParentId } -/** Exported so the composer's parent picker offers exactly the roots this view attaches. */ +/** Resolve traversal roots even when retirement makes only their descendants selectable. */ export function getLineageChildWorktree( lineage: WorkspaceLineage, worktreeById: Map diff --git a/src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-candidates.ts b/src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-candidates.ts index 277e65c1e29..1c3c0e2da70 100644 --- a/src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-candidates.ts +++ b/src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-candidates.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility' import { getWorktreeExecutionHostId, type ExecutionHostId @@ -59,7 +60,7 @@ export function worktreeParentPlacementFor({ const isCrossStoreParent = crossStoreParentEligibility(child, parentIdentities) const closesLoop = closesResolvedLoop(child, worktrees, parentIdentities) return (candidate) => { - if (closesLoop(candidate)) { + if (isWorktreeRetiredByRemoval(candidate) || closesLoop(candidate)) { return null } if ( @@ -126,6 +127,7 @@ function crossStoreParentEligibility( store !== undefined && store !== childStore && !candidate.isArchived && + !isWorktreeRetiredByRemoval(candidate) && Boolean(candidate.instanceId) && getWorktreeHostIdentity(candidate) !== currentParent ) @@ -179,6 +181,7 @@ export function isEligibleWorktreeParent({ childHostId !== null && getWorktreeOwnerHostId(candidateParent, repoMap) === childHostId && !candidateParent.isArchived && + !isWorktreeRetiredByRemoval(candidateParent) && canAssignWorktreeParent({ child, candidateParent, diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts b/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts index 20d3ddf0160..ce645740c42 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/desktop-workspace-row-facts.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility' import { getWorktreeExecutionHostId, type ExecutionHostId @@ -43,7 +44,7 @@ export function buildDesktopWorkspaceRowFactReader( return repo ? getWorktreeExecutionHostId(worktree, repo, inputs.defaultHostId) : null } return { - isArchived: (worktree) => worktree.isArchived, + isArchived: (worktree) => worktree.isArchived || isWorktreeRetiredByRemoval(worktree), ...hiddenProjectRowFacts(inputs.hiddenProjects), isFolderWorkspace: (worktree) => parseWorkspaceKey(worktree.id)?.type === 'folder', repoId: (worktree) => worktree.repoId, diff --git a/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts b/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts index fd63ae84f89..776e70894e8 100644 --- a/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts +++ b/src/renderer/src/components/worktree-jump/worktree-jump-palette-create-worktree.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../shared/worktree/removal-visibility' import { worktreeMatchesGitHubNumber } from '@/lib/work-items/github/github-work-item-workspace-attachment' import { getPaletteWorktreeExecutionHostId } from '@/lib/workspace/search/palette-repo-resolution' import { findRepoForHost } from '@/store/repos/repo-host-identity' @@ -184,6 +185,7 @@ export function createWorktreeJumpPaletteWorktreeHandler({ const matches = workspaces.filter( (worktree) => !worktree.isArchived && + !isWorktreeRetiredByRemoval(worktree) && worktreeMatchesGitHubNumber( worktree, ghNumber, diff --git a/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.ts b/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.ts index 38b5ec9d892..d9e56dcd3e5 100644 --- a/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.ts +++ b/src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import type { LinearIssue } from '../../../../../shared/linear/issue-types' import { getWorkspaceAttachments } from '../../../../../shared/workspace-attachments/workspace-attachments' import type { Worktree } from '../../../../../shared/worktree/types' @@ -96,6 +97,7 @@ export function findLinearIssueWorkspaceAttachment( worktrees.filter( (worktree) => !worktree.isArchived && + !isWorktreeRetiredByRemoval(worktree) && getWorkspaceAttachments(worktree).some( (item) => item.provider === 'linear' && @@ -112,7 +114,7 @@ export function buildLinearIssueWorkspaceAttachmentIndex( ): LinearIssueWorkspaceAttachmentIndex { const index = new Map() for (const worktree of worktrees) { - if (worktree.isArchived) { + if (worktree.isArchived || isWorktreeRetiredByRemoval(worktree)) { continue } const identifiers = new Set( diff --git a/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts b/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts index 3abb60a5a0a..2d5b8f2a374 100644 --- a/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts +++ b/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts @@ -97,6 +97,25 @@ const resolution = { } describe('deleting the active workspace', () => { + it('navigates on durable retirement while retaining the checkout and its draft state', async () => { + const store = setup() + const before = store.getState() + store.setState({ worktreesByRepo: { repo1: [{ ...active, removing: true }, sibling, main] } }) + await Promise.resolve() + expect(activateAndRevealWorktree).not.toHaveBeenCalled() + store.setState({ + worktreesByRepo: { + repo1: [{ ...active, removing: true, removalRecorded: true }, sibling, main] + } + }) + await Promise.resolve() + expect(activateAndRevealWorktree).toHaveBeenCalledWith(sibling.id, { + revealInSidebar: false, + executionHostId: 'local' + }) + expect(store.getState().worktreesByRepo.repo1.find((row) => row.id === active.id)).toBeDefined() + expect(store.getState().tabsByWorktree).toBe(before.tabsByWorktree) + }) it('respects a user closing the last browser tab after startup dropped its row', async () => { const store = setup() layoutMain = await drawTabsFromMain(store) diff --git a/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.ts b/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.ts index 01b5b1da7b5..68184606317 100644 --- a/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.ts +++ b/src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.ts @@ -21,6 +21,7 @@ import { } from '../../../../../shared/execution-host' import type { Repo } from '../../../../../shared/repo-types' import type { Worktree } from '../../../../../shared/worktree/types' +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' type RemovedActiveRow = { @@ -81,6 +82,7 @@ export function pickActiveWorktreeSuccessor( const siblings = (selectWorktreesByRepo(state)[removed.repoId] ?? []).filter( (worktree) => !getDeleteStateForWorktreeHost(worktree, state.deleteStateByWorktreeId)?.isDeleting && + !isWorktreeRetiredByRemoval(worktree) && !isHostedOnRuntimeOwnedSshTarget(worktree, repoById) && !isHiddenAsleep?.(worktree) ) @@ -135,6 +137,44 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () = return row && !isScoped(row) ? row : null } witness = observe() + const retireAcceptedSelection = (state: AppState): boolean => { + const removed = listedActiveRow(state) + const row = removed ? findListedRow(state, removed.id, removed.hostId) : undefined + if (!removed || !row || !isWorktreeRetiredByRemoval(row) || isScoped(removed)) { + return false + } + const scheduled = ++generation + queueMicrotask(() => { + const current = store.getState() + const active = findListedRow(current, removed.id, removed.hostId) + if ( + generation !== scheduled || + current.activeView !== 'terminal' || + current.activePendingCreationId !== null || + current.activeWorktreeId !== removed.id || + current.activeWorkspaceExecutionHostId !== removed.hostId || + !active || + !isWorktreeRetiredByRemoval(active) + ) { + return + } + witness = null + const successor = pickActiveWorktreeSuccessor( + current, + removed, + getSidebarSleepingSweepRetainedIds() + ) + if (successor) { + activateAndRevealWorktree(successor.id, { + revealInSidebar: false, + executionHostId: successor.hostId + }) + } else { + current.setActiveWorktree(null) + } + }) + return true + } const unsubscribeIntent = subscribeWorktreeDeselectionIntent((scope, entering) => { if (!scope || entering) { if (scope) { @@ -178,6 +218,9 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () = return } if (next.activeWorktreeId !== null) { + if (retireAcceptedSelection(next)) { + return + } const listed = observe() // An unlisted pointer to the witness is a row dropped before its selection clears. if (listed || witness?.id !== next.activeWorktreeId) { @@ -226,6 +269,9 @@ export function installActiveWorktreeRemovalSuccessor(store = useAppStore): () = } }) }) + if (store.getState().activeView === 'terminal') { + retireAcceptedSelection(store.getState()) + } return () => { generation += 1 unsubscribeIntent() diff --git a/src/renderer/src/lib/workspace/activation/worktree-activation.ts b/src/renderer/src/lib/workspace/activation/worktree-activation.ts index 13575aa01cf..4d4aa867970 100644 --- a/src/renderer/src/lib/workspace/activation/worktree-activation.ts +++ b/src/renderer/src/lib/workspace/activation/worktree-activation.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../shared/worktree/removal-visibility' import { runtimeEnvironmentIdOrLocalUnlessTwin } from '../ownership/worktree-runtime-owner' import { noteUserWorkspaceOpen } from './workspace-switch-user-act' import { useAppStore } from '@/store/index' @@ -158,7 +159,7 @@ export function activateAndRevealWorktreeWithOutcome( return { opened: { primaryTabId: null } } } const wt = state.getKnownWorktreeById(worktreeId, opts?.executionHostId) - if (!wt) { + if (!wt || isWorktreeRetiredByRemoval(wt)) { return { refused: { reason: 'workspace-missing', failureNotified: false } } } const pendingCreationId = findPendingWorktreeCreationId(state.pendingWorktreeCreations, wt.id) diff --git a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.ts b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.ts index fbca7684aae..f22e66dfc66 100644 --- a/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.ts +++ b/src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility' import { matchPaletteDocument } from '../../../../../../shared/palette-match/match-document' import { preparePaletteQuery } from '../../../../../../shared/palette-match/palette-query' import type { MatchRange } from '../../../../../../shared/palette-match/normalized-text' @@ -76,7 +77,11 @@ export function isPaletteSearchableWorktree( worktree: Worktree, hiddenProjects: HiddenProjects ): boolean { - return !worktree.isArchived && !hiddenProjects.isRowHidden(worktree) + return ( + !worktree.isArchived && + !isWorktreeRetiredByRemoval(worktree) && + !hiddenProjects.isRowHidden(worktree) + ) } export function getWorktreePaletteSearchScope(args: { diff --git a/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.test.ts b/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.test.ts index a15d88ae965..2c85c275d4a 100644 --- a/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.test.ts +++ b/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.test.ts @@ -4,6 +4,11 @@ import { createTestStore } from '../worktrees-slice-test-harness' import { makeWorktree } from '../worktree.test-fixture' import { TEST_REPO } from '../../../repos/repo.test-fixture' import { resolveWorktreeCreateParent } from './worktree-create-parent-pick' +import { makeFolderWorkspace } from '../../../folder-workspaces/folder-workspace.test-fixture' +import { + buildLocalWorktreeCreateArgs, + buildRuntimeWorktreeCreateParams +} from './worktree-create-payload' describe('worktree creation parent resolution', () => { it('drops a hostless local parent when a same-ID repository is targeted remotely', () => { @@ -93,3 +98,52 @@ describe('a composer parent picked on another machine', () => { }) }) }) + +it('drops a retained parent pick after durable removal, but keeps legacy pending picks', () => { + const store = createTestStore() + const parent = makeWorktree({ + id: 'repo1::/parent', + repoId: 'repo1', + hostId: 'local', + displayName: 'Parent', + removing: true + }) + store.setState({ + repos: [TEST_REPO], + worktreesByRepo: { repo1: [parent] }, + folderWorkspaces: [makeFolderWorkspace()], + activeWorkspaceKey: 'folder:folder-1' + }) + expect(resolveWorktreeCreateParent(store.getState(), parent.id, 'local').staleBeforeCreate).toBe( + false + ) + expect(resolveWorktreeCreateParent(store.getState(), undefined, 'local').parentWorkspace).toBe( + 'folder:folder-1' + ) + store.setState({ worktreesByRepo: { repo1: [{ ...parent, removalRecorded: true }] } }) + for (const pick of [parent.id, `local|${parent.id}`]) { + const selection = resolveWorktreeCreateParent(store.getState(), pick, 'local') + expect(selection).toEqual({ + pickedDisplayName: 'Parent', + staleBeforeCreate: true + }) + const request = { + repoId: TEST_REPO.id, + name: 'child', + baseBranch: 'main', + setupDecision: 'skip' as const + } + const attempt = { name: 'child', parentWorkspace: selection.parentWorkspace } + for (const payload of [ + buildLocalWorktreeCreateArgs(request, attempt), + buildRuntimeWorktreeCreateParams(request, attempt) + ]) { + expect(payload).not.toHaveProperty('parentWorkspace') + expect(payload).not.toHaveProperty('crossStoreParent') + expect(payload).not.toHaveProperty('parentWorkspaceOrigin') + } + expect( + resolveWorktreeCreateParent(store.getState(), pick, 'runtime:other').crossStoreParentRow + ).toBeUndefined() + } +}) diff --git a/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.ts b/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.ts index 66bdf6fdaf6..eba7a5a8749 100644 --- a/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.ts +++ b/src/renderer/src/store/slices/worktrees/create/worktree-create-parent-pick.ts @@ -1,3 +1,4 @@ +import { isWorktreeRetiredByRemoval } from '../../../../../../shared/worktree/removal-visibility' import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { resolveWorktreeDisplayName } from '@/lib/workspace/display/worktree-default-display-name' @@ -89,7 +90,7 @@ export function resolveWorktreeCreateParent( (candidate) => getWorktreeHostIdentity(candidate) === requestedParentWorktreeId ) // The pick outlives a destination change; a parent now on the creation host is an ordinary one. - if (row && !row.isArchived && !isOnCreationHost(row)) { + if (row && !row.isArchived && !isWorktreeRetiredByRemoval(row) && !isOnCreationHost(row)) { return { crossStoreParentRow: row, pickedParentWorktreeId: row.id, @@ -97,7 +98,7 @@ export function resolveWorktreeCreateParent( staleBeforeCreate: false } } - if (!row || row.isArchived) { + if (!row || row.isArchived || isWorktreeRetiredByRemoval(row)) { return { pickedDisplayName: row ? resolveWorktreeDisplayName(row).trim() : null, staleBeforeCreate: true @@ -109,8 +110,11 @@ export function resolveWorktreeCreateParent( isOnCreationHost ) } - const usable = picked && !picked.isArchived ? picked.id : undefined const pickedDisplayName = picked ? resolveWorktreeDisplayName(picked).trim() : null + if (picked && isWorktreeRetiredByRemoval(picked)) { + return { pickedDisplayName, staleBeforeCreate: true } + } + const usable = picked && !picked.isArchived ? picked.id : undefined if (usable) { return { parentWorkspace: worktreeWorkspaceKey(usable), diff --git a/src/shared/runtime-worktree-contracts.ts b/src/shared/runtime-worktree-contracts.ts index 7d8e68293f1..96b2dd22ff7 100644 --- a/src/shared/runtime-worktree-contracts.ts +++ b/src/shared/runtime-worktree-contracts.ts @@ -137,6 +137,8 @@ export type RuntimeWorktreePsSummary = { agents: RuntimeWorktreeAgentRow[] /** See `Worktree.removing`; sent only to clients that advertise background removal. */ removing?: true + /** The owning host committed removal intent before publishing this row. */ + removalRecorded?: true /** See `GitWorktreeInfo.removalError`. */ removalError?: string /** Host-derived workspace kinds. Missing defaultBranch retains reader guesses; other missing flags show the row. diff --git a/src/shared/sidebar-list/paired-server-rows.ts b/src/shared/sidebar-list/paired-server-rows.ts index 1585091a8f7..2a71651abb8 100644 --- a/src/shared/sidebar-list/paired-server-rows.ts +++ b/src/shared/sidebar-list/paired-server-rows.ts @@ -45,6 +45,9 @@ const PairedServerWorkspaceRowSchema = z // Server-owned sorting/filter/lineage facts; older desktops omit them. Lineage is the checked edge, not the raw record. WorkspaceRowSchema.pick({ isMainWorktree: true, + removing: true, + removalRecorded: true, + removalError: true, isUnread: true, instanceId: true, lineage: true, @@ -124,6 +127,9 @@ export function pairedServerRowOfWorktree( branch: worktree.branch, displayName: worktree.displayName, isArchived: worktree.isArchived, + ...(worktree.removing ? { removing: true } : {}), + ...(worktree.removalRecorded ? { removalRecorded: true } : {}), + ...(worktree.removalError ? { removalError: worktree.removalError } : {}), isPinned: worktree.isPinned, isMainWorktree: worktree.isMainWorktree, isUnread: worktree.isUnread, @@ -180,6 +186,9 @@ const ServerWorktreePsRowSchema = z.object({ branch: z.string().catch(''), displayName: z.string().catch(''), isArchived: z.boolean().catch(false), + removing: z.literal(true).optional().catch(undefined), + removalRecorded: z.literal(true).optional().catch(undefined), + removalError: z.string().optional().catch(undefined), isPinned: z.boolean().catch(false), isMainWorktree: z.boolean().catch(false), unread: z.boolean().optional().catch(undefined), diff --git a/src/shared/sidebar-list/sidebar-feed-rows.test.ts b/src/shared/sidebar-list/sidebar-feed-rows.test.ts index c176ee80d54..b592acf3750 100644 --- a/src/shared/sidebar-list/sidebar-feed-rows.test.ts +++ b/src/shared/sidebar-list/sidebar-feed-rows.test.ts @@ -4,16 +4,18 @@ import type { ProjectGroup } from '../project-group-types' import type { Repo } from '../repo-types' import { NO_WORKSPACE_ROW_FILTERS } from '../workspace-view/workspace-row-filters' import { ALL_GROUP_KEY } from './group-keys' +import { IDLE_WORKSPACE_ACTIVITY } from './workspace-activity-facts' +import { composeWorktreeHostIdentity } from '../worktree/host-qualified-identity' import type { HostSectionRow } from './host-section-rows' import { normalizePairedServerRow } from './paired-server-rows' import type { SidebarFeedDomains } from './sidebar-feed-domains' import { buildSidebarFeedRows, + planSidebarFeedRows, type SidebarFeedCatalog, type SidebarFeedView } from './sidebar-feed-rows' -import { IDLE_WORKSPACE_ACTIVITY } from './workspace-activity-facts' -import { composeWorktreeHostIdentity } from '../worktree/host-qualified-identity' +import { indexSidebarFeed, rankSidebarFeedWorktrees } from './sidebar-feed-index' function repo(id: string, overrides: Partial = {}): Repo { return { id, path: `/${id}`, displayName: id, badgeColor: '', addedAt: 0, ...overrides } @@ -70,6 +72,73 @@ function outline(rows: readonly HostSectionRow[]): string[] { }) } +it('retires only recorded deletions through paired feed, pins, forced reveal and lineage', () => { + const rows = [ + normalizePairedServerRow('runtime:a', { + worktreeId: 'r::/p', + repoId: 'r', + worktreeInstanceId: 'p', + isPinned: true, + removing: true, + removalRecorded: true + }), + normalizePairedServerRow('runtime:a', { + worktreeId: 'r::/c', + repoId: 'r', + worktreeInstanceId: 'c', + parentWorktreeId: 'r::/p', + lineageWorktreeInstanceId: 'c', + parentWorktreeInstanceId: 'p' + }), + normalizePairedServerRow('runtime:a', { + worktreeId: 'r::/legacy', + repoId: 'r', + removing: true + }), + normalizePairedServerRow('runtime:a', { + worktreeId: 'r::/failed', + repoId: 'r', + removalError: 'Cleanup failed. Retry deletion.' + }), + normalizePairedServerRow('runtime:b', { worktreeId: 'r::/p', repoId: 'r' }) + ].flatMap((row) => row ?? []) + const repos = [ + repo('r', { executionHostId: 'runtime:a' }), + repo('r', { executionHostId: 'runtime:b' }) + ] + const inputs = domains({ + pairedServerHosts: new Map( + ['runtime:a', 'runtime:b'].map((hostId) => [ + hostId, + { freshness: 'live' as const, host: null } + ]) + ), + pairedServerRows: new Map(rows.map((row) => [row.key, row])) + }) + const settings = view({ pinnedDisplayPolicy: 'duplicate-in-groups' }) + const index = indexSidebarFeed(inputs, repos) + const planned = planSidebarFeedRows( + inputs, + index, + catalog(repos), + settings, + rankSidebarFeedWorktrees(index, 'recent'), + { forcedVisibleWorktreeIds: ['r::/p'] } + ) + expect(planned.visibleWorktrees.map((row) => `${row.hostId}|${row.id}`).sort()).toEqual([ + 'runtime:a|r::/c', + 'runtime:a|r::/failed', + 'runtime:a|r::/legacy', + 'runtime:b|r::/p' + ]) + const built = buildSidebarFeedRows(inputs, catalog(repos), settings) + expect(outline(built.sectionRows)).toContain('runtime:a|r::/c@0') + expect(outline(built.sectionRows)).not.toContain('runtime:a|r::/p@0') + expect(built.visibleWorktrees.find((row) => row.id === 'r::/failed')?.removalError).toBe( + 'Cleanup failed. Retry deletion.' + ) +}) + describe('buildSidebarFeedRows nests each paired server’s own lineage', () => { const serverRows = (hostId: 'runtime:a' | 'runtime:b', recentAt: number) => [ diff --git a/src/shared/sidebar-list/sidebar-feed-worktrees.ts b/src/shared/sidebar-list/sidebar-feed-worktrees.ts index 29824d445c3..1f45300fd1d 100644 --- a/src/shared/sidebar-list/sidebar-feed-worktrees.ts +++ b/src/shared/sidebar-list/sidebar-feed-worktrees.ts @@ -49,6 +49,9 @@ type FeedRowFields = Pick< Pick< WorkspaceRow, | 'isMainWorktree' + | 'removing' + | 'removalRecorded' + | 'removalError' | 'isUnread' | 'instanceId' | 'lineage' @@ -106,6 +109,9 @@ function readFeedRow( linkedLinearIssue: null, isMainWorktree: row.isMainWorktree ?? false, isArchived: row.isArchived, + ...(row.removing ? { removing: true } : {}), + ...(row.removalRecorded ? { removalRecorded: true } : {}), + ...(row.removalError ? { removalError: row.removalError } : {}), isPinned: row.isPinned, isUnread: row.isUnread ?? false, workspaceStatus: row.workspaceStatus, diff --git a/src/shared/sidebar-list/visible-worktrees.ts b/src/shared/sidebar-list/visible-worktrees.ts index 7e5d1fc1aab..4089253b6d1 100644 --- a/src/shared/sidebar-list/visible-worktrees.ts +++ b/src/shared/sidebar-list/visible-worktrees.ts @@ -1,6 +1,7 @@ import type { WorktreeLineage } from '../worktree/lineage-types' import type { Worktree } from '../worktree/types' import { getWorktreeHostIdentity } from '../worktree/host-qualified-identity' +import { isWorktreeRetiredByRemoval } from '../worktree/removal-visibility' import { filterWorkspaceRows, type WorkspaceRowFactReader, @@ -49,7 +50,10 @@ export function selectVisibleSidebarWorktrees({ // Hidden projects are no filter: neither a reveal nor a child's lineage brings their rows back. const ancestorByIdentity = withoutHiddenProjectRows(everyAncestorByIdentity, facts) - let all = filterWorkspaceRows(rows, filters, facts) + let all = filterWorkspaceRows(rows, filters, { + ...facts, + isArchived: (row) => facts.isArchived(row) || isWorktreeRetiredByRemoval(row) + }) if (forcedVisibleWorktreeIds && forcedVisibleWorktreeIds.length > 0) { const includedIds = new Set(all.map((worktree) => worktree.id)) @@ -57,7 +61,7 @@ export function selectVisibleSidebarWorktrees({ const worktree = includedIds.has(worktreeId) ? undefined : [...ancestorByIdentity.values()].find((candidate) => candidate.id === worktreeId) - if (worktree) { + if (worktree && !isWorktreeRetiredByRemoval(worktree)) { includedIds.add(worktreeId) all.push(worktree) } @@ -123,6 +127,9 @@ function addVisibleLineageAncestors( // An older peer's loop reaches a row again before it is included. const visiting = new Set() const addWithAncestors = (worktree: Worktree): void => { + if (isWorktreeRetiredByRemoval(worktree)) { + return + } const identity = getWorktreeHostIdentity(worktree) if (included.has(identity) || visiting.has(identity)) { return diff --git a/src/shared/sidebar-list/workspace-rows.ts b/src/shared/sidebar-list/workspace-rows.ts index d406d306155..a9d82d0114e 100644 --- a/src/shared/sidebar-list/workspace-rows.ts +++ b/src/shared/sidebar-list/workspace-rows.ts @@ -71,6 +71,9 @@ export const WorkspaceRowSchema = z.object({ workspaceLineage: WorkspaceLineageEdgeSchema, isPinned: z.boolean(), isArchived: z.boolean(), + removing: z.literal(true).optional(), + removalRecorded: z.literal(true).optional(), + removalError: z.string().optional(), isUnread: z.boolean(), workspaceStatus: z.string(), comment: z.string(), @@ -144,6 +147,9 @@ function toWorkspaceRow( ...(workspaceLineage !== undefined ? { workspaceLineage } : {}), isPinned: worktree.isPinned, isArchived: worktree.isArchived, + ...(worktree.removing ? { removing: true } : {}), + ...(worktree.removalRecorded ? { removalRecorded: true } : {}), + ...(worktree.removalError ? { removalError: worktree.removalError } : {}), isUnread: worktree.isUnread, workspaceStatus: worktree.workspaceStatus ?? DEFAULT_WORKSPACE_STATUS_ID, comment: worktree.comment, diff --git a/src/shared/worktree/removal-visibility.ts b/src/shared/worktree/removal-visibility.ts new file mode 100644 index 00000000000..58e62cb52ef --- /dev/null +++ b/src/shared/worktree/removal-visibility.ts @@ -0,0 +1,8 @@ +import type { GitWorktreeInfo } from './types' + +/** Legacy removing markers do not prove the owner can resume cleanup after restart. */ +export function isWorktreeRetiredByRemoval( + row: Pick +): boolean { + return row.removing === true && row.removalRecorded === true +} diff --git a/src/shared/worktree/removal.ts b/src/shared/worktree/removal.ts index 4f07ade9502..a1f3719bca1 100644 --- a/src/shared/worktree/removal.ts +++ b/src/shared/worktree/removal.ts @@ -3,7 +3,7 @@ import type { GitWorktreeInfo, Worktree } from './types' export function unregisteredFolderRefusal(worktreePath: string): Error { return new Error( - `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Delete the folder yourself to finish removing this workspace.` + `${worktreePath} is no longer a Git worktree, so its folder was left on disk. Remove the remaining folder yourself, then retry deletion to finish cleanup.` ) } diff --git a/src/shared/worktree/types.ts b/src/shared/worktree/types.ts index 3bf89f8e919..bff4e81b77f 100644 --- a/src/shared/worktree/types.ts +++ b/src/shared/worktree/types.ts @@ -62,6 +62,9 @@ export type GitWorktreeInfo = { isMainWorktree: boolean /** Local delete failed after Git deregistration; list the leftover so Delete can retry. */ removalError?: string + removing?: true + /** The owning host durably recorded this pending deletion. Older hosts omit it. */ + removalRecorded?: true } /** Read HEAD/branch without spawning Git to refresh background head moves without structural worktrees:changed fanout. */ @@ -164,9 +167,6 @@ export type Worktree = { mobileDiffReview?: MobileDiffReviewState automationProvenance?: AutomationWorkspaceProvenance cliProvenance?: CliWorkspaceProvenance - /** The host is deleting this checkout in the background; Git lists it until that finishes. - * Sent only to clients that advertise `worktree.background-removal.v1`. */ - removing?: true } & GitWorktreeInfo /** Only CLI-created workspaces carry this; missing means not CLI-created, including older rows. */ From cd933ae08ebed74a1fc4ceb29a477ef5e8884555 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:35:26 +0000 Subject: [PATCH 10/44] feat(computer-use): add orca computer wait for text, enabled controls and window titles (#41433) * feat(computer-use): add orca computer wait for text, enabled controls and window titles * fix(computer-use): bound wait reads by the deadline and wait out missing Linux/Windows windows * fix(computer-use): read disabled traits after role text with parentheses and bound the capability probe --- docs/site/content/docs/cli/computer-use.mdx | 12 + native/computer-use-linux/runtime.py | 24 +- .../computer-use-linux/runtime_render_test.py | 15 ++ .../Sources/OrcaComputerUseMacOS/main.swift | 1 + native/computer-use-windows/runtime.ps1 | 10 +- skill-guides/orca-computer-use.md | 20 +- src/cli/computer/computer-tree-query.test.ts | 14 ++ src/cli/computer/computer-tree-query.ts | 21 +- src/cli/computer/computer-wait-command.ts | 73 ++++++ src/cli/computer/computer-wait.test.ts | 166 +++++++++++++ src/cli/computer/computer-wait.ts | 229 ++++++++++++++++++ src/cli/computer/computer.ts | 2 + src/cli/discovery/command-scoped-flag-help.ts | 10 + src/cli/discovery/root-help-text-primary.ts | 1 + src/cli/dispatch/handler-group-manifest.ts | 1 + src/cli/skills/bundled-skill-guides.ts | 20 +- src/cli/specs/computer.ts | 23 ++ .../desktop-script-provider-bridge.ts | 2 +- src/shared/computer-use-runtime-types.ts | 2 + src/shared/computer-wait-timeout.ts | 2 + 20 files changed, 635 insertions(+), 13 deletions(-) create mode 100644 src/cli/computer/computer-tree-query.test.ts create mode 100644 src/cli/computer/computer-wait-command.ts create mode 100644 src/cli/computer/computer-wait.test.ts create mode 100644 src/cli/computer/computer-wait.ts create mode 100644 src/shared/computer-wait-timeout.ts diff --git a/docs/site/content/docs/cli/computer-use.mdx b/docs/site/content/docs/cli/computer-use.mdx index be075f766f0..4f6b8f31ae7 100644 --- a/docs/site/content/docs/cli/computer-use.mdx +++ b/docs/site/content/docs/cli/computer-use.mdx @@ -39,6 +39,18 @@ Element indexes are scoped to the latest `get-app-state` result and may be **spa Action results return only the accessibility-tree lines that changed since the last state for that window (`~` changed, `+` added, `-` removed), marked by `snapshot.treeDiff`; pass `--full-tree` to get the whole tree. To find one control in a large window, `get-app-state --query ` prints only matching elements and their ancestors, and `--max-elements ` caps the output. +## Waiting for the app + +Instead of sleeping between actions, wait for what the app should show next. `wait` returns as soon as the condition holds, prints the matching elements or windows, and fails with `wait_timeout` after `--timeout` milliseconds (default 10000, at most 120000): + +```bash +orca computer wait --app com.apple.TextEdit --text "Saved" --json +orca computer wait --app com.apple.TextEdit --enabled "Continue" --json +orca computer wait --app com.apple.TextEdit --window-title "Save As" --json +``` + +`--text` matches element lines the same way as `get-app-state --query`. `--enabled` holds once elements containing the text exist and none of them is disabled. `--window-title` checks the window titles `list-windows` reports (on Windows, only the main window's). `wait` only reads the app and keeps checking while the app or window doesn't exist yet. `--enabled` needs a runtime whose provider marks disabled elements (`supports.observation.disabledState` in `capabilities`). + ## Multi-window apps ```bash diff --git a/native/computer-use-linux/runtime.py b/native/computer-use-linux/runtime.py index b276ecd05dc..c81e3812534 100644 --- a/native/computer-use-linux/runtime.py +++ b/native/computer-use-linux/runtime.py @@ -135,8 +135,11 @@ def pid_of(node): def has_state(node, state): - state_set = attempt(node.get_state_set) - return bool(state_set is not None and attempt(lambda: state_set.contains(state), False)) + return state_set_contains(attempt(node.get_state_set), state) + + +def state_set_contains(state_set, state, default=False): + return bool(state_set is not None and attempt(lambda: state_set.contains(state), default)) class GeometryReader: @@ -401,8 +404,17 @@ def accessible_id(node): return str(attempt(node.get_accessible_id, "") or "") +def is_disabled(state_set): + # Why: toolkits set ENABLED and SENSITIVE on usable nodes; a node whose states can't be read is not called disabled. + usable = [getattr(Atspi.StateType, name, None) for name in ("ENABLED", "SENSITIVE")] + if state_set is None or None in usable: + return False + return not any(state_set_contains(state_set, state, True) for state in usable) + + def record(node, index, path): role = role_of(node) + state_set = attempt(node.get_state_set) return { "index": index, "runtimeId": path, @@ -412,7 +424,8 @@ def record(node, index, path): "localizedControlType": role, "className": str(attempt(node.get_toolkit_name, "") or ""), "value": string_value(node), - "isSelected": has_state(node, Atspi.StateType.SELECTED), + "isSelected": state_set_contains(state_set, Atspi.StateType.SELECTED), + "isDisabled": is_disabled(state_set), "nativeWindowHandle": 0, "frame": None, "actions": action_labels(node), @@ -500,7 +513,8 @@ def render_accessibility_tree(root, root_path, compact_browser_tabs=False, geome if geometry_nodes is not None: geometry_nodes[id(item)] = node role_label = item["localizedControlType"] or item["controlType"] - line = f'{item["index"]} {role_label} {sanitize_text(title)}'.rstrip() + traits = " (disabled)" if item["isDisabled"] else "" + line = f'{item["index"]} {role_label}{traits} {sanitize_text(title)}'.rstrip() line += formatted_value(role_key, title, item["value"]) if generic_summary and generic_summary != title: line += ", Text: " + sanitize_text(generic_summary) @@ -1264,7 +1278,7 @@ def handshake_response(): "supports": { "apps": {"list": True, "bundleIds": False, "pids": True}, "windows": {"list": True, "targetById": False, "targetByIndex": True, "focus": False, "moveResize": False}, - "observation": {"screenshot": has_screenshot, "annotatedScreenshot": False, "elementFrames": True, "ocr": False}, + "observation": {"screenshot": has_screenshot, "annotatedScreenshot": False, "elementFrames": True, "ocr": False, "disabledState": True}, "actions": { "click": True, "typeText": True, diff --git a/native/computer-use-linux/runtime_render_test.py b/native/computer-use-linux/runtime_render_test.py index 5c31d6126f4..6e997611596 100644 --- a/native/computer-use-linux/runtime_render_test.py +++ b/native/computer-use-linux/runtime_render_test.py @@ -18,6 +18,8 @@ class FakeStateType: SHOWING = 4 FOCUSED = 5 EDITABLE = 6 + ENABLED = 7 + SENSITIVE = 8 class FakeStateSet: @@ -668,6 +670,19 @@ class RuntimeRenderTest(unittest.TestCase): keys.assert_not_called() paste.assert_not_called() + def test_tree_marks_controls_without_enabled_or_sensitive_state_disabled(self): + disabled = FakeAccessible("push button", "Continue") + disabled.get_state_set = lambda: FakeStateSet(FakeStateType.SHOWING) + enabled = FakeAccessible("push button", "Cancel") + enabled.get_state_set = lambda: FakeStateSet(FakeStateType.ENABLED, FakeStateType.SENSITIVE) + unreadable = FakeAccessible("push button", "Help") + root = FakeAccessible("frame", "Form", children=[disabled, enabled, unreadable]) + with SnapshotFixture(root): + lines = runtime.make_snapshot("Fixture", False)["treeLines"] + self.assertIn("\t1 push button (disabled) Continue", lines) + self.assertIn("\t2 push button Cancel", lines) + self.assertIn("\t3 push button Help", lines) + def test_compacted_browser_records_keep_their_own_frames_and_indexes(self): tabs = [FakeAccessible("page tab", f"Tab {i}", value="1" if i == 9 else "") for i in range(10)] buttons = [FakeAccessible("button", f"Other {i}") for i in range(10)] diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index 43ab1f782f3..9a43b296403 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -553,6 +553,7 @@ final class Provider { "annotatedScreenshot": false, "elementFrames": true, "ocr": false, + "disabledState": true, ], "actions": [ "click": true, diff --git a/native/computer-use-windows/runtime.ps1 b/native/computer-use-windows/runtime.ps1 index 6ac335bbe97..b8d86341d86 100644 --- a/native/computer-use-windows/runtime.ps1 +++ b/native/computer-use-windows/runtime.ps1 @@ -761,12 +761,17 @@ function New-OrcaElementRecord($Element, [int]$Index, $WindowFrame) { className = Get-OrcaProperty $Element "ClassName" value = Get-OrcaValueText $Element isSelected = Test-OrcaElementSelected $Element + isDisabled = Test-OrcaElementDisabled $Element nativeWindowHandle = $nativeWindowHandle frame = Get-OrcaElementFrame $Element $WindowFrame actions = @(Get-OrcaActions $Element) } } +function Test-OrcaElementDisabled($Element) { + try { return -not [bool]$Element.Current.IsEnabled } catch { return $false } +} + function Test-OrcaElementSelected($Element) { try { $pattern = $Element.GetCurrentPattern([Windows.Automation.SelectionItemPattern]::Pattern) @@ -824,7 +829,8 @@ function Render-OrcaTree($RootElement, $WindowFrame, [bool]$CompactBrowserTabs = $records.Add($record) $nextIndex.Value++ - $line = "$($record.index) $role $(Format-OrcaSnapshotText $title)".TrimEnd() + $traits = if ($record.isDisabled) { " (disabled)" } else { "" } + $line = "$($record.index) $role$traits $(Format-OrcaSnapshotText $title)".TrimEnd() $line += Format-OrcaValueSegment $roleKey $title $record.value if (-not [string]::IsNullOrWhiteSpace($genericSummary) -and $genericSummary -ne $title) { $line += ", Text: " + (Format-OrcaSnapshotText $genericSummary) @@ -1099,7 +1105,7 @@ function Get-OrcaHandshake { supports = [pscustomobject]@{ apps = [pscustomobject]@{ list = $true; bundleIds = $false; pids = $true } windows = [pscustomobject]@{ list = $true; targetById = $true; targetByIndex = $true; focus = $false; moveResize = $false } - observation = [pscustomobject]@{ screenshot = $true; annotatedScreenshot = $false; elementFrames = $true; ocr = $false } + observation = [pscustomobject]@{ screenshot = $true; annotatedScreenshot = $false; elementFrames = $true; ocr = $false; disabledState = $true } actions = [pscustomobject]@{ click = $true typeText = $true diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 8cc9609a614..4e1506d0e88 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -46,6 +46,22 @@ In a large window, look for one control with `get-app-state --query `: it ORCA computer get-app-state --app com.apple.finder --query Downloads --json ``` +## Waiting + +Never `sleep` between actions. When the UI changes on its own after an action (a save finishes, a dialog opens, a button becomes clickable), wait for the change with `wait`. It returns as soon as the condition holds and prints the matching elements or windows; it fails with `wait_timeout` if the condition does not hold in time (default 10 s, `--timeout ` up to 120000). + +```text +ORCA computer wait --app --text "Saved" --json +ORCA computer wait --app --enabled "Continue" --json +ORCA computer wait --app --window-title "Save As" --json +``` + +- `--text `: an element line contains the text (case-insensitive, like `--query`). +- `--enabled `: an element contains the text and none of the elements containing it is disabled. Use text only the intended control shows; a label that repeats the button text also has to be enabled. +- `--window-title `: one of the app's windows has the text in its title, as `list-windows` reports them. Then target that window with its `--window-id` or `--window-index`. On Windows, `list-windows` reports only the app's main window, so wait for a dialog with `--text` instead. + +`wait` only reads the app; it never acts, raises or restores a window. The app or window may be missing at first; `wait` keeps checking until it appears. Element indexes in the output come from a fresh tree, so you can act on them next. + ## App Selectors Prefer bundle IDs from `list-apps`; names are acceptable when unambiguous. Use `pid:` only when bundle ID or name matching is ambiguous. @@ -67,6 +83,7 @@ ORCA computer list-apps --json ORCA computer list-windows --app --json ORCA computer get-app-state --app --json ORCA computer get-app-state --app --restore-window --json +ORCA computer wait --app (--text | --enabled | --window-title ) [--timeout ] --json ORCA computer click --app --element-index --json ORCA computer click --app --x 100 --y 100 --json ORCA computer click --app --x 100 --y 100 --modifiers CmdOrCtrl+Shift --json @@ -157,7 +174,7 @@ ORCA computer set-value --app com.microsoft.edgemac --element-index { + it.each([ + ['12 (disabled) File', true], + ['\t3 push button (selected, disabled, settable) Save', true], + ['4 action (primary) (disabled) Continue', true], + ['5 push button (selected) Save (beta)', false], + ['6 push button Continue, Description: Next step', false] + ])('reads %s as disabled=%s', (line, disabled) => { + expect(isComputerTreeElementDisabled({ index: 0, depth: 0, lines: [line] })).toBe(disabled) + }) +}) diff --git a/src/cli/computer/computer-tree-query.ts b/src/cli/computer/computer-tree-query.ts index a7971a81f3e..08e141f2df6 100644 --- a/src/cli/computer/computer-tree-query.ts +++ b/src/cli/computer/computer-tree-query.ts @@ -13,9 +13,7 @@ export type ComputerTreeQuery = { export function queryComputerTreeText(treeText: string, options: ComputerTreeQuery): string { const { header, elements, footer } = parseComputerTreeText(treeText) const needle = options.query?.toLowerCase() - const candidates = needle - ? elements.filter((element) => elementText(element).toLowerCase().includes(needle)) - : elements + const candidates = needle ? computerTreeElementsMatching(elements, needle) : elements const shown = options.maxElements === undefined ? candidates : candidates.slice(0, options.maxElements) const shownSet = new Set(shown) @@ -33,6 +31,23 @@ export function queryComputerTreeText(treeText: string, options: ComputerTreeQue return joinComputerTreeText(header, note ? [note, ...body] : body, footer) } +// Case-insensitive, like --query, over each element's line without its index. +export function computerTreeElementsMatching( + elements: ComputerTreeElement[], + query: string +): ComputerTreeElement[] { + const needle = query.toLowerCase() + return elements.filter((element) => elementText(element).toLowerCase().includes(needle)) +} + +// Providers render traits after the role, whose own text may hold parentheses: `12 button (selected, disabled) Save`. +const DISABLED_TRAIT = + /\((?:(?:selected|expanded|settable), )*disabled(?:, (?:selected|expanded|settable))*\)/u + +export function isComputerTreeElementDisabled(element: ComputerTreeElement): boolean { + return DISABLED_TRAIT.test(element.lines[0]) +} + function elementText(element: ComputerTreeElement): string { return element.lines[0].trimStart().replace(/^\d+ ?/u, '') } diff --git a/src/cli/computer/computer-wait-command.ts b/src/cli/computer/computer-wait-command.ts new file mode 100644 index 00000000000..16852c07b0b --- /dev/null +++ b/src/cli/computer/computer-wait-command.ts @@ -0,0 +1,73 @@ +import { + COMPUTER_WAIT_DEFAULT_TIMEOUT_MS, + COMPUTER_WAIT_MAX_TIMEOUT_MS +} from '../../shared/computer-wait-timeout' +import { + formatComputerWaitSnapshot, + formatComputerWaitWindows, + waitForComputerSnapshot, + waitForComputerWindowTitle, + type ComputerWaitCondition +} from './computer-wait' +import type { CommandHandler } from '../dispatch/dispatch' +import { + getOptionalPositiveIntegerFlag, + getOptionalStringFlag, + getRequiredStringFlag +} from '../arguments/flags' +import { printResult } from '../output/command-result-output' +import { RuntimeClientError } from '../runtime/types' +import { getComputerCommandTarget } from './computer-command-target' +import { getComputerWindowTargetFlags } from './computer-action-flags' + +export const runComputerWait: CommandHandler = async ({ flags, client, cwd, json }) => { + const condition = getComputerWaitCondition(flags) + const timeoutMs = getComputerWaitTimeoutMs(flags) + const windowTarget = getComputerWindowTargetFlags(flags) + if (condition.kind === 'window-title') { + if (Object.keys(windowTarget).length > 0) { + throw new RuntimeClientError( + 'invalid_argument', + "--window-title waits across all of the app's windows; drop --window-id and --window-index" + ) + } + const app = getRequiredStringFlag(flags, 'app') + const result = await waitForComputerWindowTitle(client, condition, app, timeoutMs) + printResult(result, json, formatComputerWaitWindows) + return + } + const target = await getComputerCommandTarget(flags, cwd, client) + const result = await waitForComputerSnapshot( + client, + condition, + { ...target, ...windowTarget }, + timeoutMs + ) + printResult(result, json, formatComputerWaitSnapshot) +} + +function getComputerWaitCondition(flags: Map): ComputerWaitCondition { + const conditions = (['text', 'enabled', 'window-title'] as const).flatMap((kind) => { + const value = getOptionalStringFlag(flags, kind) + return value === undefined ? [] : [{ kind, value }] + }) + if (conditions.length !== 1) { + throw new RuntimeClientError( + 'invalid_argument', + 'Pass exactly one of --text , --enabled or --window-title ' + ) + } + return conditions[0] +} + +function getComputerWaitTimeoutMs(flags: Map): number { + const timeoutMs = + getOptionalPositiveIntegerFlag(flags, 'timeout') ?? COMPUTER_WAIT_DEFAULT_TIMEOUT_MS + if (timeoutMs > COMPUTER_WAIT_MAX_TIMEOUT_MS) { + throw new RuntimeClientError( + 'invalid_argument', + `--timeout must be at most ${COMPUTER_WAIT_MAX_TIMEOUT_MS} ms` + ) + } + return timeoutMs +} diff --git a/src/cli/computer/computer-wait.test.ts b/src/cli/computer/computer-wait.test.ts new file mode 100644 index 00000000000..96ede0e5102 --- /dev/null +++ b/src/cli/computer/computer-wait.test.ts @@ -0,0 +1,166 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const callMock = vi.fn() + +type RuntimeClientModule = typeof RuntimeClientExports + +vi.mock('../runtime/client', async (importOriginal) => ({ + ...(await importOriginal()), + RuntimeClient: class { + call = callMock + getCliStatus = vi.fn() + openOrca = vi.fn() + } +})) + +import { main } from '../index' +import type * as RuntimeClientExports from '../runtime/client' +import { RuntimeRpcFailureError } from '../runtime/types' +import { okFixture, queueFixtures } from '../runtime/fixtures/runtime-rpc-fixtures' + +describe('orca computer wait', () => { + beforeEach(() => { + callMock.mockReset() + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) + process.exitCode = undefined + }) + + afterEach(() => { + vi.restoreAllMocks() + }) + + it('polls until the text appears, waiting out a window that is not open yet', async () => { + callMock.mockRejectedValueOnce( + new RuntimeRpcFailureError({ + id: 'req_0', + ok: false, + error: { code: 'window_not_found', message: 'no window' }, + _meta: { runtimeId: 'runtime-1' } + }) + ) + queueFixtures( + callMock, + okFixture('req_1', snapshot('0 window Editor\n\t1 text Saving…')), + okFixture('req_2', snapshot('0 window Editor\n\t1 text All changes saved\n\t2 button Close')) + ) + + await run('--text', 'saved') + + expect(callMock).toHaveBeenCalledTimes(3) + expect(callMock).toHaveBeenLastCalledWith( + 'computer.getAppState', + { session: 'manual', app: 'TextEdit', noScreenshot: true }, + expect.anything() + ) + const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0]) + expect(output.result.wait).toMatchObject({ kind: 'text', value: 'saved' }) + expect(output.result.snapshot.treeText).toContain('1 text All changes saved') + expect(output.result.snapshot.treeText).not.toContain('2 button Close') + }) + + it('waits until every element containing the text is enabled', async () => { + queueFixtures( + callMock, + okFixture('req_caps', capabilities(true)), + okFixture( + 'req_1', + snapshot('0 window Form\n\t1 text Press Continue\n\t2 button (disabled) Continue') + ), + okFixture('req_2', snapshot('0 window Form\n\t1 text Press Continue\n\t2 button Continue')) + ) + + await run('--enabled', 'Continue') + + expect(callMock).toHaveBeenCalledTimes(3) + expect(process.exitCode).toBeUndefined() + }) + + it('refuses --enabled on a provider that does not mark disabled elements', async () => { + queueFixtures(callMock, okFixture('req_caps', capabilities(undefined))) + + await run('--enabled', 'Continue') + + expect(callMock).toHaveBeenCalledTimes(1) + expect(process.exitCode).toBe(1) + expect(errorOutput()).toContain('unsupported_capability') + }) + + it('fails with wait_timeout and what it last saw', async () => { + callMock.mockResolvedValue(okFixture('req_1', snapshot('0 window Editor\n\t1 text Saving…'))) + + await run('--text', 'saved', '--timeout', '1') + + expect(process.exitCode).toBe(1) + const error = errorOutput() + expect(error).toContain('wait_timeout') + expect(error).toContain('no element contains \\"saved\\"') + }) + + it('waits for a window title across the app windows', async () => { + queueFixtures( + callMock, + okFixture('req_1', windows(['Untitled'])), + okFixture('req_2', windows(['Untitled', 'Save As'])) + ) + + await run('--window-title', 'save as') + + expect(callMock).toHaveBeenLastCalledWith( + 'computer.listWindows', + { app: 'TextEdit' }, + expect.anything() + ) + const output = JSON.parse(vi.mocked(console.log).mock.calls[0][0]) + expect(output.result.windows.map((window: { title: string }) => window.title)).toEqual([ + 'Save As' + ]) + }) +}) + +async function run(...args: string[]): Promise { + await main( + ['computer', 'wait', '--session', 'manual', '--app', 'TextEdit', ...args, '--json'], + '/tmp/repo' + ) +} + +function errorOutput(): string { + return vi + .mocked(console.log) + .mock.calls.map((call) => String(call[0])) + .join('\n') +} + +function snapshot(treeText: string) { + return { + snapshot: { + id: 'snap', + app: { name: 'TextEdit', bundleId: 'com.apple.TextEdit', pid: 7 }, + window: { title: 'Editor', width: 800, height: 600 }, + coordinateSpace: 'window', + treeText: `App=com.apple.TextEdit (pid 7)\nWindow: "Editor"\n\n${treeText}`, + elementCount: 3, + focusedElementId: null + }, + screenshot: null, + screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' } + } +} + +function capabilities(disabledState: boolean | undefined) { + return { + platform: 'linux', + provider: 'orca-computer-use-linux', + providerVersion: '1', + protocolVersion: 1, + supports: { observation: { screenshot: true, disabledState } } + } +} + +function windows(titles: string[]) { + return { + app: { name: 'TextEdit', bundleId: 'com.apple.TextEdit', pid: 7 }, + windows: titles.map((title, index) => ({ title, index, id: index, width: 800, height: 600 })) + } +} diff --git a/src/cli/computer/computer-wait.ts b/src/cli/computer/computer-wait.ts new file mode 100644 index 00000000000..520e5375d23 --- /dev/null +++ b/src/cli/computer/computer-wait.ts @@ -0,0 +1,229 @@ +import type { + ComputerListWindowsResult, + ComputerProviderCapabilities, + ComputerSnapshotResult, + ComputerWindowListWindow +} from '../../shared/computer-use-runtime-types' +import { parseComputerTreeText } from '../../shared/computer-use-tree-text' +import { + computerTreeElementsMatching, + isComputerTreeElementDisabled, + queryComputerTreeText +} from './computer-tree-query' +import { cliErrorCode } from '../output/cli-error' +import { formatGetAppState, formatListWindows } from './computer-format' +import type { RuntimeClient } from '../runtime/client' +import { RuntimeClientError } from '../runtime/types' +import type { RuntimeRpcSuccess } from '../../shared/runtime-rpc-envelope' + +export type ComputerWaitCondition = + | { kind: 'text'; value: string } + | { kind: 'enabled'; value: string } + | { kind: 'window-title'; value: string } + +type ComputerTreeWaitCondition = Exclude + +export type ComputerWaitSummary = ComputerWaitCondition & { elapsedMs: number } + +export type ComputerWaitSnapshotResult = ComputerSnapshotResult & { wait: ComputerWaitSummary } + +export type ComputerWaitWindowsResult = ComputerListWindowsResult & { wait: ComputerWaitSummary } + +const POLL_INTERVAL_MS = 250 +// Why: a read started near the deadline still gets long enough to answer for a large window. +const MIN_READ_TIMEOUT_MS = 2_000 +// Why: the app or window may not exist yet; waiting for it to appear is part of the wait. +const NOT_YET_CODES = new Set(['app_not_found', 'window_not_found', 'window_stale']) + +type Poll = { + call: (timeoutMs: number) => Promise> + check: (result: T) => string | null +} + +// Polls the same reads every provider and runtime version serves, so the wait needs no host support. +export async function waitForComputerSnapshot( + client: RuntimeClient, + condition: ComputerTreeWaitCondition, + params: Record, + timeoutMs: number +): Promise> { + const startedAt = Date.now() + if (condition.kind === 'enabled') { + await assertDisabledStateSupported(client, Math.max(timeoutMs, MIN_READ_TIMEOUT_MS)) + } + const { response, elapsedMs } = await pollUntil(condition, startedAt, timeoutMs, { + call: (readTimeoutMs) => + client.call( + 'computer.getAppState', + { ...params, noScreenshot: true }, + { timeoutMs: readTimeoutMs } + ), + check: (result) => snapshotMiss(condition, result.snapshot.treeText) + }) + const { snapshot } = response.result + return { + ...response, + result: { + ...response.result, + snapshot: { + ...snapshot, + treeText: queryComputerTreeText(snapshot.treeText, { query: condition.value }) + }, + wait: { ...condition, elapsedMs } + } + } +} + +export async function waitForComputerWindowTitle( + client: RuntimeClient, + condition: Extract, + app: string, + timeoutMs: number +): Promise> { + const { response, elapsedMs } = await pollUntil(condition, Date.now(), timeoutMs, { + call: (readTimeoutMs) => + client.call( + 'computer.listWindows', + { app }, + { timeoutMs: readTimeoutMs } + ), + check: (result) => windowTitleMiss(result.windows, condition.value) + }) + return { + ...response, + result: { + ...response.result, + windows: matchingWindows(response.result.windows, condition.value), + wait: { ...condition, elapsedMs } + } + } +} + +function snapshotMiss(condition: ComputerTreeWaitCondition, treeText: string): string | null { + const matches = computerTreeElementsMatching( + parseComputerTreeText(treeText).elements, + condition.value + ) + if (matches.length === 0) { + return `no element contains "${condition.value}"` + } + if (condition.kind === 'text') { + return null + } + const disabled = matches.filter(isComputerTreeElementDisabled) + if (disabled.length === 0) { + return null + } + return `${disabled.length} of ${matches.length} matching elements are disabled: ${disabled + .slice(0, 3) + .map((element) => element.lines[0].trim()) + .join(' | ')}` +} + +function windowTitleMiss(windows: ComputerWindowListWindow[], title: string): string | null { + if (matchingWindows(windows, title).length > 0) { + return null + } + if (windows.length > 0 && windows.every((window) => window.title === '')) { + return 'every window title is empty (on macOS, window titles need the Screen Recording permission)' + } + return `its windows are ${windows.map((window) => `"${window.title}"`).join(', ') || 'none'}` +} + +function matchingWindows( + windows: ComputerWindowListWindow[], + title: string +): ComputerWindowListWindow[] { + const needle = title.toLowerCase() + return windows.filter((window) => window.title.toLowerCase().includes(needle)) +} + +async function assertDisabledStateSupported( + client: RuntimeClient, + readTimeoutMs: number +): Promise { + const { result } = await client.call( + 'computer.capabilities', + {}, + { timeoutMs: readTimeoutMs } + ) + if (result.supports.observation.disabledState !== true) { + // Why: without the trait every element reads as enabled, so the wait would pass at once. + throw new RuntimeClientError( + 'unsupported_capability', + `The ${result.provider} computer-use provider on this host does not report disabled elements, so --enabled cannot be checked. Update Orca on that host, or wait with --text instead.` + ) + } +} + +async function pollUntil( + condition: ComputerWaitCondition, + startedAt: number, + timeoutMs: number, + poll: Poll +): Promise<{ response: RuntimeRpcSuccess; elapsedMs: number }> { + for (;;) { + let miss: string + try { + const remainingMs = timeoutMs - (Date.now() - startedAt) + const response = await poll.call(Math.max(remainingMs, MIN_READ_TIMEOUT_MS)) + const result = poll.check(response.result) + if (result === null) { + return { response, elapsedMs: Date.now() - startedAt } + } + miss = result + } catch (error) { + const code = cliErrorCode(error) + if (code === 'runtime_timeout' && Date.now() - startedAt >= timeoutMs) { + miss = 'the last read did not answer before the deadline' + } else if (code && NOT_YET_CODES.has(code)) { + miss = `${code}: ${error instanceof Error ? error.message : String(error)}` + } else { + throw error + } + } + const remainingMs = timeoutMs - (Date.now() - startedAt) + if (remainingMs <= 0) { + throw waitTimeoutError(condition, timeoutMs, miss) + } + await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_INTERVAL_MS, remainingMs))) + } +} + +function waitTimeoutError( + condition: ComputerWaitCondition, + timeoutMs: number, + lastSeen: string +): RuntimeClientError { + const goal = + condition.kind === 'text' + ? `an element containing "${condition.value}"` + : condition.kind === 'enabled' + ? `elements containing "${condition.value}" to be enabled` + : `a window titled "${condition.value}"` + return new RuntimeClientError( + 'wait_timeout', + `Timed out after ${timeoutMs} ms waiting for ${goal}; last check: ${lastSeen}.`, + { + nextSteps: [ + 'Run `orca computer get-app-state --app --json` to see what the app shows now.', + 'If the app is still working, wait again with a longer --timeout; otherwise match text the tree actually shows.', + ...(condition.kind === 'enabled' + ? ['Every matching element must be enabled, so use text only the intended control shows.'] + : []) + ] + } + ) +} + +export function formatComputerWaitSnapshot(result: ComputerWaitSnapshotResult): string { + return `${waitHeadline(result.wait)}\n${formatGetAppState(result)}` +} + +export function formatComputerWaitWindows(result: ComputerWaitWindowsResult): string { + return `${waitHeadline(result.wait)}\n${formatListWindows(result)}` +} + +function waitHeadline(wait: ComputerWaitSummary): string { + return `Condition --${wait.kind} "${wait.value}" held after ${wait.elapsedMs} ms.` +} diff --git a/src/cli/computer/computer.ts b/src/cli/computer/computer.ts index af844b40ef5..7a5745c5ec1 100644 --- a/src/cli/computer/computer.ts +++ b/src/cli/computer/computer.ts @@ -12,6 +12,7 @@ import { getRequiredStringFlag } from '../arguments/flags' import { queryComputerTreeText } from './computer-tree-query' +import { runComputerWait } from './computer-wait-command' import { RuntimeClientError } from '../runtime/types' import { formatComputerAction, @@ -95,6 +96,7 @@ export const COMPUTER_HANDLERS: Record = { } printResult(result, json, formatGetAppState) }, + 'computer wait': runComputerWait, 'computer click': async ({ flags, client, cwd, json }) => { assertComputerAppFlag(flags) const observeFlags = getComputerActionObserveFlags(flags) diff --git a/src/cli/discovery/command-scoped-flag-help.ts b/src/cli/discovery/command-scoped-flag-help.ts index a3ecbf8389d..b23764dd9f4 100644 --- a/src/cli/discovery/command-scoped-flag-help.ts +++ b/src/cli/discovery/command-scoped-flag-help.ts @@ -1,3 +1,5 @@ +import { COMPUTER_WAIT_DEFAULT_TIMEOUT_MS } from '../../shared/computer-wait-timeout' + // File focus differs from terminal create's shared --focus help. const FILE_OPEN_FOCUS_HELP = "--focus Bring the user to the file (switches Orca's window to its worktree)" @@ -20,6 +22,14 @@ const COMMAND_SCOPED_FLAG_HELP: Record> = { query: '--query Show only elements whose line contains this text, with their ancestors' }, + 'computer wait': { + text: '--text Wait until an element line contains this text', + enabled: + '--enabled Wait until elements containing this text exist and none is disabled', + 'window-title': + "--window-title Wait until one of the app's windows has this in its title", + timeout: `--timeout How long to wait before failing with wait_timeout (default ${COMPUTER_WAIT_DEFAULT_TIMEOUT_MS})` + }, 'reference find': { query: '--query Full URL or native issue key such as STA-1234', repo: '--repo Filter by workspace repository membership', diff --git a/src/cli/discovery/root-help-text-primary.ts b/src/cli/discovery/root-help-text-primary.ts index a58515e3b2a..d073961bd86 100644 --- a/src/cli/discovery/root-help-text-primary.ts +++ b/src/cli/discovery/root-help-text-primary.ts @@ -186,6 +186,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' computer list-apps List running apps available to computer-use', ' computer list-windows List visible windows for a target app', ' computer get-app-state Capture a compact accessibility snapshot of an app', + ' computer wait Wait until an app shows text, enables a control, or opens a window', ' computer click Click an app element or window coordinate', ' computer perform-secondary-action Run an advertised accessibility action', ' computer scroll Scroll an app element', diff --git a/src/cli/dispatch/handler-group-manifest.ts b/src/cli/dispatch/handler-group-manifest.ts index b1671a76bb2..44bbf6624ff 100644 --- a/src/cli/dispatch/handler-group-manifest.ts +++ b/src/cli/dispatch/handler-group-manifest.ts @@ -187,6 +187,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'computer permissions', 'computer list-windows', 'computer get-app-state', + 'computer wait', 'computer click', 'computer perform-secondary-action', 'computer scroll', diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 8f7e90423c3..33aeaf25c71 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1065,6 +1065,22 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "ORCA computer get-app-state --app com.apple.finder --query Downloads --json", "```", "", + "## Waiting", + "", + "Never `sleep` between actions. When the UI changes on its own after an action (a save finishes, a dialog opens, a button becomes clickable), wait for the change with `wait`. It returns as soon as the condition holds and prints the matching elements or windows; it fails with `wait_timeout` if the condition does not hold in time (default 10 s, `--timeout ` up to 120000).", + "", + "```text", + "ORCA computer wait --app --text \"Saved\" --json", + "ORCA computer wait --app --enabled \"Continue\" --json", + "ORCA computer wait --app --window-title \"Save As\" --json", + "```", + "", + "- `--text `: an element line contains the text (case-insensitive, like `--query`).", + "- `--enabled `: an element contains the text and none of the elements containing it is disabled. Use text only the intended control shows; a label that repeats the button text also has to be enabled.", + "- `--window-title `: one of the app's windows has the text in its title, as `list-windows` reports them. Then target that window with its `--window-id` or `--window-index`. On Windows, `list-windows` reports only the app's main window, so wait for a dialog with `--text` instead.", + "", + "`wait` only reads the app; it never acts, raises or restores a window. The app or window may be missing at first; `wait` keeps checking until it appears. Element indexes in the output come from a fresh tree, so you can act on them next.", + "", "## App Selectors", "", "Prefer bundle IDs from `list-apps`; names are acceptable when unambiguous. Use `pid:` only when bundle ID or name matching is ambiguous.", @@ -1086,6 +1102,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "ORCA computer list-windows --app --json", "ORCA computer get-app-state --app --json", "ORCA computer get-app-state --app --restore-window --json", + "ORCA computer wait --app (--text | --enabled | --window-title ) [--timeout ] --json", "ORCA computer click --app --element-index --json", "ORCA computer click --app --x 100 --y 100 --json", "ORCA computer click --app --x 100 --y 100 --modifiers CmdOrCtrl+Shift --json", @@ -1176,7 +1193,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "ORCA computer press-key --app com.microsoft.edgemac --key Return --json", "```", "", - "Spotify: refresh after playback clicks; the UI often changes asynchronously.", + "Spotify: the UI often changes asynchronously after playback clicks; `wait --text` for the change instead of re-reading in a loop.", "", "Slack: the accessibility tree may be shallow while the screenshot contains useful information. Reading visible Slack UI is fine when requested; sending messages or triggering workflows still needs explicit permission.", "", @@ -1195,6 +1212,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "- `element_not_enabled`: the element is disabled (its line lists `disabled`), so nothing was sent. Do what enables it first, then act once a fresh `get-app-state` no longer lists it as disabled.", "- `invalid_argument`: fix the command flags; do not retry the same command unchanged.", "- `action_timeout`: inspect current state before retrying, then use a simpler semantic action or `--no-screenshot` if observation is slow.", + "- `wait_timeout`: the condition did not hold in time. Run `get-app-state` to see what the app shows; wait again with a longer `--timeout` only if it is still working, otherwise match text the tree actually shows.", "- `verification_failed`: the write was read back and the element holds a different value, so the action failed. Run `get-app-state` to see which field changed. For editable text, click the intended field and confirm focus, select all (`cmd+a` on macOS, `ctrl+a` on Windows/Linux), then use `type-text` and inspect the resulting value instead of repeating `set-value`.", "- `screenshot_failed`: use `--no-screenshot` if tree state is enough; if the message names Screen Recording or screenshots permission, run `ORCA computer permissions --id screenshots --json`.", "- `accessibility_error`: run `ORCA computer capabilities --json`; if the message names Accessibility permission, run `ORCA computer permissions --id accessibility --json`.", diff --git a/src/cli/specs/computer.ts b/src/cli/specs/computer.ts index 6ddc43e110a..bd4ea9d5c8d 100644 --- a/src/cli/specs/computer.ts +++ b/src/cli/specs/computer.ts @@ -1,5 +1,9 @@ import type { CommandSpec } from '../discovery/command-spec' import { CLI_GLOBAL_FLAGS as GLOBAL_FLAGS } from '../../shared/cli-argument-boundary' +import { + COMPUTER_WAIT_DEFAULT_TIMEOUT_MS, + COMPUTER_WAIT_MAX_TIMEOUT_MS +} from '../../shared/computer-wait-timeout' const COMPUTER_FLAGS = [...GLOBAL_FLAGS, 'worktree', 'session', 'app'] const COMPUTER_WINDOW_TARGET_FLAGS = ['window-id', 'window-index'] @@ -43,6 +47,25 @@ export const COMPUTER_COMMAND_SPECS: CommandSpec[] = [ 'orca computer get-app-state --app [--window-id | --window-index ] [--worktree | --session ] [--query ] [--max-elements ] [--restore-window] [--no-screenshot] [--json]', allowedFlags: [...COMPUTER_OBSERVE_FLAGS, 'query', 'max-elements'] }, + { + path: ['computer', 'wait'], + summary: 'Wait until an app shows text, enables a control, or opens a window', + usage: + 'orca computer wait --app (--text | --enabled | --window-title ) [--timeout ] [--window-id | --window-index ] [--worktree | --session ] [--json]', + allowedFlags: [ + ...COMPUTER_FLAGS, + ...COMPUTER_WINDOW_TARGET_FLAGS, + 'text', + 'enabled', + 'window-title', + 'timeout' + ], + notes: [ + 'Polls the accessibility tree (or, for --window-title, the window list) until the condition holds, then prints the matching elements or windows. Matching is a case-insensitive substring, like get-app-state --query.', + '--enabled holds once an element contains the text and no element containing it is disabled.', + `--timeout defaults to ${COMPUTER_WAIT_DEFAULT_TIMEOUT_MS} ms (at most ${COMPUTER_WAIT_MAX_TIMEOUT_MS}); on timeout the command fails with wait_timeout.` + ] + }, { path: ['computer', 'click'], summary: 'Click an app element or window coordinate, optionally with modifiers', diff --git a/src/main/computer/desktop-script/desktop-script-provider-bridge.ts b/src/main/computer/desktop-script/desktop-script-provider-bridge.ts index 1e75632529b..75cc71d6938 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-bridge.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-bridge.ts @@ -220,7 +220,7 @@ export function mapBridgeError(message: string): RuntimeClientError { return new RuntimeClientError('screenshot_failed', text) } if ( - /window_not_found|No top-level(?: AT-SPI| UI Automation)? window|has no (?:on-screen |accessibility )?window|could not match accessibility window|unknown window(?:_index| id)?/i.test( + /window_not_found|windowNotFound|No top-level(?: AT-SPI| UI Automation)? window|has no (?:on-screen |accessibility )?window|could not match accessibility window|unknown window(?:_index| id)?/i.test( text ) ) { diff --git a/src/shared/computer-use-runtime-types.ts b/src/shared/computer-use-runtime-types.ts index 1b853a115dd..42de55e7b3c 100644 --- a/src/shared/computer-use-runtime-types.ts +++ b/src/shared/computer-use-runtime-types.ts @@ -160,6 +160,8 @@ export type ComputerProviderCapabilities = { ocr: boolean // Absent from runtimes that predate action-result tree diffs. treeDiff?: boolean + // Tree lines mark disabled elements with a `(disabled)` trait. Absent from older Linux and Windows providers. + disabledState?: boolean } actions: { click: boolean diff --git a/src/shared/computer-wait-timeout.ts b/src/shared/computer-wait-timeout.ts new file mode 100644 index 00000000000..e89358603cc --- /dev/null +++ b/src/shared/computer-wait-timeout.ts @@ -0,0 +1,2 @@ +export const COMPUTER_WAIT_DEFAULT_TIMEOUT_MS = 10_000 +export const COMPUTER_WAIT_MAX_TIMEOUT_MS = 120_000 From 2b79a2e6dde1b5ea521f738bb4ed4d346c78c4c1 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:35:34 -0800 Subject: [PATCH 11/44] Improve web sidebar default (#13731) --- .../web/preload-api/web-preferences-store.ts | 1 - .../web-right-sidebar-default.test.ts | 25 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/renderer/src/web/preload-api/web-right-sidebar-default.test.ts diff --git a/src/renderer/src/web/preload-api/web-preferences-store.ts b/src/renderer/src/web/preload-api/web-preferences-store.ts index e06f0135613..e3b111ebace 100644 --- a/src/renderer/src/web/preload-api/web-preferences-store.ts +++ b/src/renderer/src/web/preload-api/web-preferences-store.ts @@ -77,7 +77,6 @@ export function getStoredSettings(): GlobalSettings { const settings = mergeSettings( { ...defaults, - rightSidebarOpenByDefault: false, activeRuntimeEnvironmentId: null }, migratedStored diff --git a/src/renderer/src/web/preload-api/web-right-sidebar-default.test.ts b/src/renderer/src/web/preload-api/web-right-sidebar-default.test.ts new file mode 100644 index 00000000000..bda518cdcf9 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-right-sidebar-default.test.ts @@ -0,0 +1,25 @@ +// @vitest-environment happy-dom +import { beforeEach, expect, it, vi } from 'vitest' +import { createWebUiApi } from './web-ui-api' + +const runtime = vi.hoisted(() => ({ call: vi.fn() })) +vi.mock('./web-runtime-calls', () => ({ callRuntimeResult: runtime.call })) +vi.mock('./web-runtime-session', () => ({ + webRuntimeState: { activeEnvironment: null }, + requireActiveEnvironmentOrNull: () => ({ id: 'host' }) +})) + +beforeEach(() => { + localStorage.clear() + runtime.call.mockReset() +}) + +it('opens the right sidebar when the host cannot answer, and keeps a later close', async () => { + runtime.call.mockRejectedValue(new Error('host unavailable')) + const ui = createWebUiApi() + + expect((await ui.get()).rightSidebarOpen).toBe(true) + + await ui.set({ rightSidebarOpen: false }) + expect((await ui.get()).rightSidebarOpen).toBe(false) +}) From 2434a63be94d8f7fe09a9e35e17f8c4b412faca1 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:41:50 -0800 Subject: [PATCH 12/44] fix(tab-group): keep a grabbable tab in narrow tab-group strips (#41249) * fix(tab-group): keep a grabbable tab in narrow tab-group strips Tabs were the only shrinkable item in a pane's strip, and the only drag source, so a narrow pane clipped them to 0px while +, quick commands, the pane-actions menu and the reserved window-chrome spacers kept their width. Give the tab area a 40px floor and let the action chrome clip before it. * test(tab-group): open the right sidebar so the narrow-strip e2e is platform-neutral * test(tab-group): assert the dragged tab moves between strips in the DOM * fix(tab-group): hide strip actions whole instead of clipping their focus targets Narrow strips clipped the new-tab, quick-command and pane-actions buttons behind the 40px tab floor, so Tab could focus a control that was mostly or entirely out of view. Measure the room left after the reserved spacers and drop each control whole, and so out of Tab order, below the width where it fits: quick commands first, then pane actions, then new tab (groups with a tab only). Close split pane stays in every tab's context menu. The e2e now measures only pixels that start a tab drag (not the close button), drags from that run, and walks the strip with Tab at normal and narrow widths, asserting every focused control is fully visible. * fix(tab-group): offer quick commands from pane actions when the strip hides them When a narrow strip folds the quick-command button away, the pane actions menu now carries the same Quick Commands submenu the terminal and chat menus use, so running or adding a command still works from the strip. The narrow-strip e2e no longer sleeps or casts: it retries the first Tab until focus lands in the strip, and a new test checks the menu offers quick commands only when the button is hidden. * fix(tab-group): drop the window-drag gap before strip controls clip With the right sidebar closed, the 40px window-drag gap only shrank after the tab bar hit its floor, so "+" and the actions clipped behind it while the width rules said they fit. Hide the gap below the width where it and every control fit, so the existing thresholds hold. Adds an e2e that sweeps the top-right strip with the right sidebar closed and asserts no focused strip control is clipped. --- .../components/tab-bar/tab-bar-surface.tsx | 11 +- .../tab-group/TabGroupPaneActionsMenu.tsx | 110 +++++--- .../components/tab-group/TabGroupPanel.tsx | 55 ++-- .../e2e/narrow-tab-group-drag-handle.spec.ts | 259 ++++++++++++++++++ 4 files changed, 377 insertions(+), 58 deletions(-) create mode 100644 tests/e2e/narrow-tab-group-drag-handle.spec.ts diff --git a/src/renderer/src/components/tab-bar/tab-bar-surface.tsx b/src/renderer/src/components/tab-bar/tab-bar-surface.tsx index 5cca3dd85bf..c91c819b111 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-surface.tsx +++ b/src/renderer/src/components/tab-bar/tab-bar-surface.tsx @@ -116,6 +116,7 @@ export function renderTabBarSurface( activeClientHostedBrowserRowId }) + const hasTabs = orderedItems.length + clientHostedBrowserRows.length > 0 return (
{tabStripOverflowState.hasOverflow ? ( @@ -148,7 +149,10 @@ export function renderTabBarSurface( {/* Why: no-drag lets tab interactions work inside the titlebar's drag region (outer container stays window-draggable). */}
+ {/* Why: below 86px (40 tab floor + 36 "+" + 8 action padding + 2 sub-pixel slack) "+" would only clip; hide it whole so Tab never lands on it. Empty groups keep it. */} - - - { - if (!isFocused) { - event.preventDefault() - } - }} - > - onCloseGroup()}> - - {t('auto.components.tab.group.TabGroupPanel.closePaneColumn', 'Close split pane')} - - - - - {t('auto.components.tab.group.TabGroupPanel.9acaf92093', 'Pane Actions')} - - + <> + + + + + + + + { + if (!isFocused) { + event.preventDefault() + } + }} + > + {quickCommands.menu ? ( + <> + {quickCommands.menu} + + + ) : null} + onCloseGroup()}> + + {t('auto.components.tab.group.TabGroupPanel.closePaneColumn', 'Close split pane')} + + + + + {t('auto.components.tab.group.TabGroupPanel.9acaf92093', 'Pane Actions')} + + + {quickCommands.dialog} + ) } diff --git a/src/renderer/src/components/tab-group/TabGroupPanel.tsx b/src/renderer/src/components/tab-group/TabGroupPanel.tsx index 8cd380515eb..d272a399f3d 100644 --- a/src/renderer/src/components/tab-group/TabGroupPanel.tsx +++ b/src/renderer/src/components/tab-group/TabGroupPanel.tsx @@ -1,4 +1,4 @@ -import { Suspense, useCallback, useMemo } from 'react' +import { Suspense, useCallback, useMemo, useRef } from 'react' import { lazyWithRetry as lazy } from '@/app-shell/startup/lazy-with-retry' import { useDroppable } from '@dnd-kit/core' import { useAppStore } from '../../store/index' @@ -77,6 +77,7 @@ export default function TabGroupPanel({ const sidebarOpen = useAppStore((state) => state.sidebarOpen) const reserveRightTitlebarSpace = reserveClosedExplorerToggleSpace && !rightSidebarOpen const model = useTabGroupWorkspaceModel({ groupId, worktreeId }) + const quickCommandsSlotRef = useRef(null) const { activeTab, agentSessionItems, @@ -252,8 +253,9 @@ export default function TabGroupPanel({ /> ) + // Why: actions hide before the tab bar's floor is reached; min-w-0 + clipping is only a backstop so reserved spacers stay clear. const actionChromeClassName = cn( - 'ml-1.5 flex shrink-0 items-center gap-0.5 transition-opacity duration-150', + 'flex min-w-0 items-center gap-0.5 overflow-hidden pl-1.5 pr-0.5 transition-opacity duration-150', !isFocused && 'opacity-50 hover:opacity-100 focus-within:opacity-100' ) return ( @@ -285,12 +287,12 @@ export default function TabGroupPanel({ {/* Omit external strips entirely because hidden duplicates would still register competing drag sortables. */} {tabStrip !== 'attached' ? null : (
-
+
{/* Why: Electron drag hit-test respects no-drag only on DOM descendants, not z-index siblings, so this no-drag spacer keeps the collapsed left-sidebar's floating toggle clickable. */} {reserveCollapsedSidebarHeaderSpace && !sidebarOpen ? (
) : null} -
{tabBar}
- {/* Why: overflowing tabs eat all strip whitespace; keep a window-drag handle while the right sidebar header is closed. */} - {reserveRightTitlebarSpace ?
: null} -
- - {hasSplitGroups ? ( - + {/* Why: the tab-strip container excludes the reserved spacers, so width rules see only the room tabs and actions share. */} +
+
{tabBar}
+ {/* Why: overflowing tabs eat all strip whitespace; keep a window-drag handle while the right sidebar header is closed. It goes first in narrow strips: 203 = 40 gap + 163 for the tab floor and every control, so controls never clip behind it. */} + {reserveRightTitlebarSpace ? ( +
) : null} +
+ {/* Why: drop an action whole (and from Tab order) once it can't fit beside the tab floor and "+", never leave a clipped focus target. + 163 = 40 tab + 36 "+" + 8 padding + 47 widest collapsed quick-command trigger + 2 gap + 28 pane actions + 2 sub-pixel slack; 114 = 40 + 36 + 8 + 28 + 2. */} +
+ +
+ {hasSplitGroups ? ( +
+ +
+ ) : null} +
{/* Why: Electron drag hit-test respects no-drag only on DOM descendants, not z-index siblings, so this no-drag spacer keeps the floating right-sidebar toggle + window controls clickable. */} {reserveRightTitlebarSpace ? ( diff --git a/tests/e2e/narrow-tab-group-drag-handle.spec.ts b/tests/e2e/narrow-tab-group-drag-handle.spec.ts new file mode 100644 index 00000000000..c61c42a31b1 --- /dev/null +++ b/tests/e2e/narrow-tab-group-drag-handle.spec.ts @@ -0,0 +1,259 @@ +import type { Page } from '@stablyai/playwright-test' +import { test, expect } from './helpers/orca-app' +import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' + +type NarrowLayout = { leftGroupId: string; rightGroupId: string; rightTabId: string } + +async function buildThreeColumns( + page: Page, + worktreeId: string, + rightSidebarOpen = true +): Promise { + return page.evaluate( + ({ id, rightSidebarOpen }) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('window.__store is not available') + } + state.setSidebarOpen(false) + // Open by default so the right column reserves no window-controls space, which differs per platform. + state.setRightSidebarOpen(rightSidebarOpen) + const leftGroupId = state.activeGroupIdByWorktree[id] ?? state.groupsByWorktree[id]?.[0]?.id + if (!leftGroupId) { + throw new Error('No root tab group') + } + const middleGroupId = state.createEmptySplitGroup(id, leftGroupId, 'right') + if (!middleGroupId) { + throw new Error('Middle split was not created') + } + state.createTab(id, middleGroupId, undefined, { activate: true }) + const rightGroupId = state.createEmptySplitGroup(id, middleGroupId, 'right') + if (!rightGroupId) { + throw new Error('Right split was not created') + } + const rightTab = state.createTab(id, rightGroupId, undefined, { activate: true }) + const rightTabId = + window.__store + ?.getState() + .unifiedTabsByWorktree[id]?.find( + (tab) => tab.contentType === 'terminal' && tab.entityId === rightTab.id + )?.id ?? '' + return { leftGroupId, rightGroupId, rightTabId } + }, + { id: worktreeId, rightSidebarOpen } + ) +} + +async function narrowRightColumns(page: Page, worktreeId: string): Promise { + await page.evaluate((id) => { + const state = window.__store?.getState() + // Root 80/20, then 45/55 inside it: the right column is about 98px wide, under 120px. + state?.setTabGroupSplitRatio(id, '', 0.8) + state?.setTabGroupSplitRatio(id, 'second', 0.45) + }, worktreeId) +} + +/** Widest run of strip pixels where a press starts a tab drag: a tab, but not its close button or other inner controls. */ +async function draggableTabRun(page: Page, groupId: string): Promise<{ width: number; x: number }> { + return page.evaluate((id) => { + const strip = document.querySelector(`[data-tab-group-strip-id="${id}"]`) + if (!strip) { + return { width: 0, x: 0 } + } + const rect = strip.getBoundingClientRect() + const y = rect.top + rect.height / 2 + let best = { width: 0, x: 0 } + let runStart = 0 + let run = 0 + for (let x = Math.ceil(rect.left); x < rect.right; x++) { + const hit = document.elementFromPoint(x, y) + const tab = hit?.closest('[data-tab-id]') + const draggable = tab && strip.contains(tab) && !hit?.closest('button, input') + if (draggable) { + runStart = run === 0 ? x : runStart + run++ + if (run > best.width) { + best = { width: run, x: runStart + run / 2 } + } + } else { + run = 0 + } + } + return best + }, groupId) +} + +type FocusedControl = { label: string; fullyVisible: boolean } | 'in-tab' | null + +/** The strip control holding focus (null outside the strip, 'in-tab' for a tab's own controls) and whether all of it is visible. */ +async function focusedStripControl(page: Page, groupId: string): Promise { + return page.evaluate((id) => { + const el = document.activeElement + const stripEl = document.querySelector(`[data-tab-group-strip-id="${id}"]`) + if (!(el instanceof HTMLElement) || !stripEl?.contains(el)) { + return null + } + if (el.closest('[data-tab-id]')) { + return 'in-tab' + } + const r = el.getBoundingClientRect() + const y = r.top + r.height / 2 + const shows = (x: number): boolean => { + const hit = document.elementFromPoint(x, y) + return Boolean(hit && (hit === el || el.contains(hit))) + } + return { + label: el.getAttribute('aria-label') ?? el.textContent?.trim() ?? el.tagName, + fullyVisible: r.width > 0 && shows(r.left + 1) && shows(r.right - 1) + } + }, groupId) +} + +/** Tab through a strip from its first tab; report each strip control (not a tab's own close button) that took focus. */ +async function tabThroughStrip( + page: Page, + groupId: string +): Promise<{ label: string; fullyVisible: boolean }[]> { + const tab = page.locator(`[data-tab-group-strip-id="${groupId}"] [data-tab-id]`).first() + // Why: focusing a group can hand focus to its terminal a beat later, so retry until Tab from the tab lands in the strip. + await expect + .poll(async () => { + await tab.focus() + await page.keyboard.press('Tab') + return focusedStripControl(page, groupId) + }) + .not.toBeNull() + let focused = await focusedStripControl(page, groupId) + const visited: { label: string; fullyVisible: boolean }[] = [] + for (let i = 0; i < 8 && focused; i++) { + if (focused !== 'in-tab') { + visited.push(focused) + } + await page.keyboard.press('Tab') + focused = await focusedStripControl(page, groupId) + } + return visited +} + +test('a narrow tab group keeps a grabbable tab and can be dragged into another group', async ({ + orcaPage +}) => { + await orcaPage.setViewportSize({ width: 1280, height: 800 }) + await waitForSessionReady(orcaPage) + const worktreeId = await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + + const layout = await buildThreeColumns(orcaPage, worktreeId) + const rightStrip = orcaPage.locator(`[data-tab-group-strip-id="${layout.rightGroupId}"]`) + await expect.poll(async () => (await rightStrip.boundingBox())?.width ?? 0).toBeGreaterThan(200) + + // At normal width the strip's controls are all reachable by Tab and fully visible. + const wideFocus = await tabThroughStrip(orcaPage, layout.rightGroupId) + expect(wideFocus.map((control) => control.label)).toEqual( + expect.arrayContaining(['New tab', 'Pane Actions']) + ) + expect(wideFocus.filter((control) => !control.fullyVisible)).toEqual([]) + + await narrowRightColumns(orcaPage, worktreeId) + await expect.poll(async () => (await rightStrip.boundingBox())?.width ?? 0).toBeLessThan(120) + + await expect + .poll(async () => (await draggableTabRun(orcaPage, layout.rightGroupId)).width) + .toBeGreaterThanOrEqual(16) + + // Keyboard users only reach controls they can see: anything that would clip is hidden instead. + const narrowFocus = await tabThroughStrip(orcaPage, layout.rightGroupId) + expect(narrowFocus.map((control) => control.label)).toContain('New tab') + expect(narrowFocus.filter((control) => !control.fullyVisible)).toEqual([]) + + const run = await draggableTabRun(orcaPage, layout.rightGroupId) + const tabBox = await rightStrip.locator('[data-tab-id]').first().boundingBox() + const leftBody = await orcaPage + .locator(`[data-tab-group-body-id="${layout.leftGroupId}"]`) + .boundingBox() + if (!tabBox || !leftBody) { + throw new Error('Drag geometry missing') + } + const startX = run.x + const startY = tabBox.y + tabBox.height / 2 + await orcaPage.mouse.move(startX, startY) + await orcaPage.mouse.down() + await orcaPage.mouse.move(startX - 20, startY + 10, { steps: 4 }) + await orcaPage.mouse.move(leftBody.x + leftBody.width / 2, leftBody.y + leftBody.height / 2, { + steps: 12 + }) + await orcaPage.mouse.up() + + await expect + .poll(() => + orcaPage.evaluate( + ({ id, tabId }) => + window.__store?.getState().unifiedTabsByWorktree[id]?.find((t) => t.id === tabId) + ?.groupId, + { id: worktreeId, tabId: layout.rightTabId } + ) + ) + .toBe(layout.leftGroupId) + // The user sees the tab move: the left strip gains it and the right strip no longer shows it. + const leftStrip = orcaPage.locator(`[data-tab-group-strip-id="${layout.leftGroupId}"]`) + await expect(leftStrip.locator('[data-tab-id]')).toHaveCount(2) + await expect(rightStrip.locator('[data-tab-id]')).toHaveCount(0) +}) + +test('a strip too narrow for quick commands offers them in the pane actions menu', async ({ + orcaPage +}) => { + await orcaPage.setViewportSize({ width: 1280, height: 800 }) + await waitForSessionReady(orcaPage) + const worktreeId = await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + + const layout = await buildThreeColumns(orcaPage, worktreeId) + const rightStrip = orcaPage.locator(`[data-tab-group-strip-id="${layout.rightGroupId}"]`) + const paneActions = rightStrip.getByRole('button', { name: 'Pane Actions' }) + const quickCommandsItem = orcaPage.getByRole('menuitem', { name: 'Quick Commands' }) + + // Normal width shows the quick-command button, so the menu does not repeat it. + await expect(rightStrip.getByRole('button', { name: 'Add quick command' })).toBeVisible() + await paneActions.click() + await expect(orcaPage.getByRole('menuitem', { name: 'Close split pane' })).toBeVisible() + await expect(quickCommandsItem).toHaveCount(0) + await orcaPage.keyboard.press('Escape') + + // Root 80/20, then 25/75 inside it: about 134px, too narrow for quick commands but not for the menu. + await orcaPage.evaluate((id) => { + const state = window.__store?.getState() + state?.setTabGroupSplitRatio(id, '', 0.8) + state?.setTabGroupSplitRatio(id, 'second', 0.25) + }, worktreeId) + await expect(rightStrip.getByRole('button', { name: 'Add quick command' })).toBeHidden() + await paneActions.click() + await expect(quickCommandsItem).toBeVisible() +}) + +test('with the right sidebar closed, no focused strip control is clipped at any width', async ({ + orcaPage +}) => { + await orcaPage.setViewportSize({ width: 1280, height: 800 }) + await waitForSessionReady(orcaPage) + const worktreeId = await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + + // The top-right strip now also holds the window-drag gap and the reserved toggle/window-controls space. + const layout = await buildThreeColumns(orcaPage, worktreeId, false) + for (const secondRatio of [0.15, 0.3, 0.45, 0.6]) { + await orcaPage.evaluate( + ({ id, ratio }) => { + const state = window.__store?.getState() + state?.setTabGroupSplitRatio(id, '', 0.8) + state?.setTabGroupSplitRatio(id, 'second', ratio) + }, + { id: worktreeId, ratio: secondRatio } + ) + const focus = await tabThroughStrip(orcaPage, layout.rightGroupId) + expect( + focus.filter((control) => !control.fullyVisible), + `ratio ${secondRatio}` + ).toEqual([]) + } +}) From d373f9ba38943f796270f7ec4835bda4aabbd86d Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:41:55 -0800 Subject: [PATCH 13/44] fix(skills): stop calling another Orca build's skill copy out of date (#40706) * fix(skills): stop calling another Orca build's skill copy out of date Every Orca build on a host (the installed app, dev builds, the CLI, a paired server) shares one skills folder, and each one auto-updates it to the text it ships. A build only recognises SKILL.md text from itself or older releases, so a copy a newer build (or a dev build) wrote looked like a user edit: the nudge said "An installed Orca skill is out of date" and Update offered to replace it with older text. Whenever Orca writes a skill it now leaves a marker, ~/.agents/.orca-skill-digests//, on the disk of the host that plans. A copy whose bytes match a marker plans as leave 'other-build': it reads as current, is never nudged, and silent update leaves it alone. A user edit changes the bytes, so it is still asked about. A paired server plans and records on its own disk, so the client never compares hosts. * fix(skills): mark copies already at this build's digest so other builds see them as Orca's A copy that already equals this build's bundle plans keep-only, so no write ever recorded its marker, and copies written before the marker existed stayed 'edited' to any other build. Executing a plan now records the marker whenever a location holds this build's bytes, and the silent update records it for keep-only entries. The startup scan asks the host (this machine or a paired server) once per session to run that keep-only update, so an already-current build marks its copy on its first run. Preview stays read-only. * chore(skills): drop unreachable other-build setup copy and document touched planners 'other-build' leaves are always replaceable, so the non-replaceable setup attention lookup never selects one; it now shares the generic fallback and its dedicated string is removed. Add short docstrings to the touched planning, execution and copy functions. * fix(skills): retry the startup marker when the host did not record it A marking-only call kept its session mark even when the host never ran the recording, so a failed or busy call left the copy unmarked for the rest of the session. Release the mark when the call rejects, another update held the target, or the host reports the skill busy or changed, so the next plan refresh asks again. A host without silent update keeps its mark, avoiding a call per scan. * fix(skills): include Codex session's P2 fixes; warn only when a marker call may have written Includes two P2 review fixes from a Codex session in this worktree: - A newly selected agent links to a recognized other-build shared copy instead of being left as shared-not-current, and execution re-checks that shared copy so the dependent link is skipped if it changed after planning. - Installed-skill views refresh after every silent-update call, since a marking-only call re-plans on the host and can still update a copy. A rejected marking-only call now shows the uncertain-outcome warning only when the request reached a paired host and its reply was lost. A refusal before sending, or the host's own error reply, cannot hide a write: the mark is released for retry without a warning. Calls that started real updates keep warning on any rejection. Restores the docstrings removed in that session. * fix(skills): stop retrying a failed skill marker on every plan refresh Every marker call ends in a plan refresh, and a refresh re-scans. Freeing the mark after a busy or failed call made each refresh ask again, so a host that stayed busy or unreachable looped without end. Ask once per target, skill and bytes per session; a later session, a manual update or any write of the skill records the marker instead. * fix(skills): recognise another build's copy under a skill's former name A build from before a rename records its marker under the former name. Check that marker for former-name copies too, so a renamed build no longer calls such a copy edited and nudges about it. A user edit, a cloud receipt or extra files still keep the copy as it was. * fix(skills): warn about any failed skill update that may have reached the host A paired host's timeout or lost reply also arrives as an RPC error, so an RPC error is no proof that nothing was written. Only a refusal before sending now stays quiet. * fix(skills): send a silent skill update only to the host that was checked Pin the update to the runtime and pairing that answered the capability check, so a re-pair while the check awaits cannot send it to another host. * fix(skills): record markers without updating, and never offer to replace another build's copy A marker call now asks the host to record copies already at its bytes and nothing else, so it can never write a skill and needs no warning or re-plan; hosts that predate it reject the request and write nothing. It is sent only in a scan that starts no update. Another build's copy is no longer offered for Replace, which could downgrade it, and its dialog line reads "Kept: written by another Orca version". * fix(skills): keep other-build setup current across host pairings * fix(skills): preserve other-build prerequisites during migration --- .../skill/runtime-bundled-skill-install.ts | 8 +- .../bundled-skill-installation.ts | 2 +- .../bundled-skill-other-build.test.ts | 198 ++++++++++++++++++ .../bundled-skill-plan-execution.ts | 50 ++++- .../bundled-skill-plan.ts | 57 ++--- .../bundled-skill-targets.ts | 13 ++ .../bundled-skill-written-digests.ts | 64 ++++++ .../renamed-skill-placement.ts | 11 +- .../skill-freshness-auto-update.test.ts | 168 +++++++++++++++ .../freshness/skill-freshness-auto-update.ts | 49 ++++- .../skills/freshness/skill-plan-op-copy.ts | 26 ++- .../setup/bundled-skill-setup-result-copy.ts | 9 +- src/renderer/src/i18n/locales/en.json | 4 +- .../runtime-bundled-skills-client.test.ts | 83 ++++++++ .../bundled/runtime-bundled-skills-client.ts | 37 ++-- src/shared/bundled-skill-plan.ts | 7 +- src/shared/bundled-skill-summary.test.ts | 45 ++++ src/shared/bundled-skill-summary.ts | 23 +- 18 files changed, 786 insertions(+), 68 deletions(-) create mode 100644 src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts create mode 100644 src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts create mode 100644 src/renderer/src/components/skills/freshness/skill-freshness-auto-update.test.ts create mode 100644 src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.test.ts create mode 100644 src/shared/bundled-skill-summary.test.ts diff --git a/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts b/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts index af262a95740..03f5974bbd6 100644 --- a/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts +++ b/src/main/runtime/integrations/skill/runtime-bundled-skill-install.ts @@ -67,10 +67,14 @@ export async function executeLocalBundledSkills( export async function autoUpdateLocalBundledSkills( host: RuntimeSkillCommandHost, - { names }: BundledSkillAutoUpdateRequest + { names, recordOnly }: BundledSkillAutoUpdateRequest ): Promise { const input = await appInput(host, {}) - const result = await autoUpdateInstalledBundledSkills({ ...input, names }) + const result = await autoUpdateInstalledBundledSkills({ + ...input, + names, + ...(recordOnly ? { recordOnly } : {}) + }) clearSkillDiscoveryCaches() return result } diff --git a/src/main/skills/bundled-skill-install/bundled-skill-installation.ts b/src/main/skills/bundled-skill-install/bundled-skill-installation.ts index c15c4ffa2f0..b05d4ea61de 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-installation.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-installation.ts @@ -38,7 +38,7 @@ export async function installBundledSkills( /** Silent path: updates only hash-verified Orca copies of `names`, planned under the same locks. */ export async function autoUpdateInstalledBundledSkills( - input: BundledSkillServiceInput & { names: readonly string[] } + input: BundledSkillServiceInput & { names: readonly string[]; recordOnly?: boolean } ): Promise { return autoUpdateBundledSkills({ ...withDefaults(input), names: input.names }) } diff --git a/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts b/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts new file mode 100644 index 00000000000..897a4017fd3 --- /dev/null +++ b/src/main/skills/bundled-skill-install/bundled-skill-other-build.test.ts @@ -0,0 +1,198 @@ +import { createHash } from 'node:crypto' +import { appendFile, lstat, readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + bundledSkillInstallAction, + bundledSkillNudgeEntries, + bundledSkillNudgeKey, + bundledSkillPlanState +} from '../../../shared/bundled-skill-summary' +import type { BundledSkillSource } from './bundled-skill-sources' +import { + autoUpdateInstalledBundledSkills, + previewBundledSkillInstall +} from './bundled-skill-installation' +import { + makeSkillHome, + NAME, + NEW_SOURCE, + NEW_TEXT, + OLD_TEXT, + previewAndInstall, + removeSkillHomes, + serviceInput, + writeCopy, + type SkillHome +} from './testing/bundled-skill-home' + +afterEach(removeSkillHomes) + +const digest = (text: string) => createHash('sha256').update(text).digest('hex') +const NEWER_TEXT = `---\nname: ${NAME}\ndescription: Newer\n---\n\nNewer body\n` +/** A newer Orca build on the same host: it knows every older text, but no older build knows its text. */ +const NEWER_SOURCE: BundledSkillSource = { + name: NAME, + text: NEWER_TEXT, + releasedDigests: [digest(OLD_TEXT), digest(NEW_TEXT), digest(NEWER_TEXT)] +} + +const DEV_TEXT = `---\nname: ${NAME}\ndescription: Dev\n---\n\nDev branch body\n` +/** A dev build whose bundle never shipped `NEW_TEXT`, so it cannot recognise that copy by hash. */ +const DEV_SOURCE: BundledSkillSource = { + name: NAME, + text: DEV_TEXT, + releasedDigests: [digest(OLD_TEXT), digest(DEV_TEXT)] +} + +const asBuild = (home: SkillHome, source: BundledSkillSource) => ({ + ...serviceInput(home), + sources: [source] +}) +const autoUpdateAs = (home: SkillHome, source: BundledSkillSource) => + autoUpdateInstalledBundledSkills({ ...asBuild(home, source), names: [NAME] }) +const hasMarker = (home: SkillHome, text: string) => + lstat(join(home.home, '.agents', '.orca-skill-digests', NAME, digest(text))).then( + () => true, + () => false + ) + +describe("another Orca build's copy on the same host", () => { + it('links a newly selected agent to a recognized shared copy', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEWER_TEXT) + await autoUpdateAs(home, NEWER_SOURCE) + + const input = { ...serviceInput(home, { agents: ['cursor'] }), sources: [NEW_SOURCE] } + await previewAndInstall(input) + + expect((await lstat(home.cursor)).isSymbolicLink()).toBe(true) + expect(await readFile(join(home.cursor, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + }) + + it('automatically migrates a former-name agent copy to a recognized shared copy', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEWER_TEXT) + await autoUpdateAs(home, NEWER_SOURCE) + await writeCopy(join(home.home, '.claude', 'skills', 'former-test-skill'), OLD_TEXT) + + await autoUpdateAs(home, { ...NEW_SOURCE, aliases: ['former-test-skill'] }) + + expect((await lstat(home.claude)).isSymbolicLink()).toBe(true) + expect(await readFile(join(home.claude, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + }) + + it('is not reported out of date or downgraded by an older build, until the user edits it', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, OLD_TEXT) + await previewAndInstall(asBuild(home, NEWER_SOURCE)) + + const plan = await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(plan.skills[0].ops.map((op) => [op.kind, op.reason])).toEqual([ + ['leave', 'other-build'], + // Claude's link into the shared copy is already right. + ['keep', undefined] + ]) + // Replacing it may downgrade it, so the dialog and setup button never offer to. + expect(plan.skills[0].ops[0].replaceable).toBe(false) + // Setup counts it as installed: nothing to run, replace or fix. + expect(bundledSkillInstallAction(plan)).toEqual({ kind: 'none' }) + expect(bundledSkillPlanState(plan.skills[0])).toBe('current') + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + expect(bundledSkillNudgeKey('local', plan)).toBeNull() + + await autoUpdateInstalledBundledSkills({ ...asBuild(home, NEW_SOURCE), names: [NAME] }) + expect(await readFile(join(home.shared, 'SKILL.md'), 'utf8')).toBe(NEWER_TEXT) + + // The record lives on the planned host's home: the same bytes no Orca wrote elsewhere still count as an edit. + const elsewhere = await makeSkillHome() + await writeCopy(elsewhere.shared, NEWER_TEXT) + const elsewherePlan = await previewBundledSkillInstall(asBuild(elsewhere, NEW_SOURCE)) + expect(elsewherePlan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + + await appendFile(join(home.shared, 'SKILL.md'), '\nmy note\n') + const edited = await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(edited.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + expect(bundledSkillNudgeEntries(edited).map((entry) => entry.name)).toEqual([NAME]) + }) + + it("marks a copy already at the build's own digest when its keep-only update runs", async () => { + const home = await makeSkillHome() + // Written before markers existed; the build that owns these bytes sees it as current. + await writeCopy(home.shared, NEW_TEXT) + expect(await hasMarker(home, NEW_TEXT)).toBe(false) + + const result = await autoUpdateAs(home, NEW_SOURCE) + expect(result.skills).toEqual([]) + expect(await hasMarker(home, NEW_TEXT)).toBe(true) + + const plan = await previewBundledSkillInstall(asBuild(home, DEV_SOURCE)) + expect(plan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'other-build' }) + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + }) + + it("is not reported out of date when another build installed it under the skill's former name", async () => { + const home = await makeSkillHome() + const FORMER_NAME = 'former-test-skill' + const FORMER_DEV_TEXT = `---\nname: ${FORMER_NAME}\ndescription: Dev\n---\n\nFormer dev body\n` + // A build from before the rename, whose text the renamed build never shipped. + const formerBuild = asBuild(home, { + name: FORMER_NAME, + text: FORMER_DEV_TEXT, + releasedDigests: [digest(FORMER_DEV_TEXT)] + }) + await previewAndInstall(formerBuild) + + const renamed = asBuild(home, { ...NEW_SOURCE, aliases: [FORMER_NAME] }) + const plan = await previewBundledSkillInstall({ ...renamed, installedOnly: true }) + expect(plan.skills.flatMap((skill) => skill.ops.map((op) => op.reason))).not.toContain('edited') + expect(bundledSkillNudgeEntries(plan)).toEqual([]) + + // A user edit to that former-name copy is still asked about. + await appendFile(join(home.home, '.agents', 'skills', FORMER_NAME, 'SKILL.md'), '\nmy note\n') + const edited = await previewBundledSkillInstall({ ...renamed, installedOnly: true }) + expect(bundledSkillNudgeEntries(edited).map((entry) => entry.name)).toEqual([NAME]) + }) + + it('records a current copy on a record-only request but never updates a released one', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEW_TEXT) + const recordOnly = { ...asBuild(home, NEW_SOURCE), names: [NAME], recordOnly: true } + + expect((await autoUpdateInstalledBundledSkills(recordOnly)).skills).toEqual([]) + expect(await hasMarker(home, NEW_TEXT)).toBe(true) + + // A copy at an older release text would be silently updated, but not by a record-only request. + await writeCopy(home.shared, OLD_TEXT) + expect((await autoUpdateInstalledBundledSkills(recordOnly)).skills).toEqual([]) + expect(await readFile(join(home.shared, 'SKILL.md'), 'utf8')).toBe(OLD_TEXT) + expect(await hasMarker(home, OLD_TEXT)).toBe(false) + }) + + it('writes no marker from a preview alone', async () => { + const home = await makeSkillHome() + await writeCopy(home.shared, NEW_TEXT) + + await previewBundledSkillInstall(asBuild(home, NEW_SOURCE)) + expect(await hasMarker(home, NEW_TEXT)).toBe(false) + const plan = await previewBundledSkillInstall(asBuild(home, DEV_SOURCE)) + expect(plan.skills[0].ops[0]).toMatchObject({ kind: 'leave', reason: 'edited' }) + }) + + it("records a paired server's marker on the server's own disk, never the client's", async () => { + const client = await makeSkillHome() + const server = await makeSkillHome() + await writeCopy(client.shared, NEW_TEXT) + await writeCopy(server.shared, NEW_TEXT) + + // The server runs its own keep-only update against its own home. + await autoUpdateAs(server, NEW_SOURCE) + expect(await hasMarker(server, NEW_TEXT)).toBe(true) + expect(await hasMarker(client, NEW_TEXT)).toBe(false) + + const serverPlan = await previewBundledSkillInstall(asBuild(server, DEV_SOURCE)) + const clientPlan = await previewBundledSkillInstall(asBuild(client, DEV_SOURCE)) + expect(serverPlan.skills[0].ops[0]).toMatchObject({ reason: 'other-build' }) + expect(clientPlan.skills[0].ops[0]).toMatchObject({ reason: 'edited' }) + }) +}) diff --git a/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts b/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts index 5e77eda552f..d18609ed54d 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-plan-execution.ts @@ -8,7 +8,10 @@ import type { BundledSkillOutcome, BundledSkillPlanEntry } from '../../../shared/bundled-skill-plan' -import { isBundledSkillAutoUpdateOp } from '../../../shared/bundled-skill-summary' +import { + holdsCurrentBundledSkillCopy, + isBundledSkillAutoUpdateOp +} from '../../../shared/bundled-skill-summary' import type { BundledSkillSource } from './bundled-skill-sources' import { classifyBundledSkillPath } from './bundled-skill-classification' import { filesystemErrorCode } from './bundled-skill-filesystem-error' @@ -25,6 +28,7 @@ import { } from './bundled-skill-folder-swap' import { findBundledSkillSource } from './bundled-skill-source-selection' import { withBundledSkillTargetLocks } from './bundled-skill-target-locks' +import { recordBundledSkillDigestWritten } from './bundled-skill-written-digests' export type BundledSkillExecuteInput = BundledSkillPlanInput & { /** Per-lock wait; the shared 5s default applies when unset. */ @@ -116,7 +120,12 @@ async function applyContent(run: SkillRun, op: BundledSkillOp): Promise { const statuses = new Map() const ops: BundledSkillOpOutcome[] = [] @@ -211,9 +221,28 @@ async function runSkill(run: SkillRun): Promise { statuses.set(op.path, outcome.strandedPath ? 'done' : outcome.status) ops.push(outcome) } + if ( + holdsCurrentBundledSkillCopy(run.entry) || + run.entry.ops.some((op) => op.content === 'files' && statuses.get(op.path) === 'done') + ) { + await recordOrcaCopy(run.input, run.entry) + } return { name: run.entry.name, status: 'ran', ops } } +/** + * Lets other Orca builds on this host recognise these bytes as Orca's, not a user edit. + * Execution only: preview stays read-only. + */ +function recordOrcaCopy(input: BundledSkillExecuteInput, entry: BundledSkillPlanEntry) { + return recordBundledSkillDigestWritten( + input.filesystem, + input.destination.homeDirectory, + entry.name, + entry.digest + ) +} + /** Re-plan under all target locks and require the previewed digest; stale previews must write nothing. */ export async function executeBundledSkillPlan( input: BundledSkillExecuteInput, @@ -242,10 +271,11 @@ export async function executeBundledSkillPlan( /** * Plans each named installed skill under its locks and applies only hash-verified released-copy * updates; edited, foreign or interrupted locations are never touched. Each write re-checks its - * location, and one skill's failure leaves the others' outcomes intact. + * location, and one skill's failure leaves the others' outcomes intact. `recordOnly` skips every + * update and only records copies that already hold this build's bytes. */ export async function autoUpdateBundledSkills( - input: BundledSkillExecuteInput & { names: readonly string[] } + input: BundledSkillExecuteInput & { names: readonly string[]; recordOnly?: boolean } ): Promise { const unrun = (status: 'changed' | 'busy'): BundledSkillInstallResult => ({ scope: input.destination.scope, @@ -258,12 +288,22 @@ export async function autoUpdateBundledSkills( const safe = entry.ops.filter(isBundledSkillAutoUpdateOp) const required = new Set(safe.flatMap((op) => (op.requires ? [op.requires] : []))) const ops = entry.ops.filter( - (op) => safe.includes(op) || (op.kind === 'keep' && required.has(op.path)) + (op) => + safe.includes(op) || + (required.has(op.path) && + (op.kind === 'keep' || + (op.kind === 'leave' && + op.reason === 'other-build' && + op.cleanup.every((item) => item.action === 'delete')))) ) - if (ops.length > 0) { + if (ops.length > 0 && !input.recordOnly) { const source = findBundledSkillSource(input.sources, entry.name) skills.push(await runSkill({ input, entry: { ...entry, ops }, source })) } + // An already-current copy (keep-only, so nothing ran) written before markers existed. + if (holdsCurrentBundledSkillCopy(entry)) { + await recordOrcaCopy(input, entry) + } } return { scope: plan.scope, skills } }) diff --git a/src/main/skills/bundled-skill-install/bundled-skill-plan.ts b/src/main/skills/bundled-skill-install/bundled-skill-plan.ts index ecf4fe428bb..8cce67ecb15 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-plan.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-plan.ts @@ -1,5 +1,5 @@ import { bundledSkillDigestOf } from './bundled-skill-plan-identity' -import { dirname, join, resolve } from 'node:path' +import { join } from 'node:path' import type { BundledSkillOp, BundledSkillPlan, @@ -20,9 +20,10 @@ import type { BundledSkillFilesystem } from './bundled-skill-filesystem' import { recoverySiblings } from './bundled-skill-swap-recovery' import { findBundledSkillSource } from './bundled-skill-source-selection' import { planFormerSkillPlacements } from './renamed-skill-placement' +import { isOtherBuildCopy } from './bundled-skill-written-digests' import { bundledSkillPathKey, - resolveBundledSkillRealPath, + linkPointsAt, resolveBundledSkillTargets, type BundledSkillTargetRequest, type BundledSkillTargetRoot @@ -54,7 +55,8 @@ type SkillContext = { sharedRoot?: BundledSkillTargetRoot } -type SharedTarget = { path: string; realPath: string; current: boolean } +// `otherBuild`: the shared folder holds another Orca build's copy, so links to it are already right. +type SharedTarget = { path: string; realPath: string; current: boolean; otherBuild?: boolean } const WRITES_SHARED_CURRENT = new Set([ 'keep', @@ -63,18 +65,6 @@ const WRITES_SHARED_CURRENT = new Set([ 'replace' ]) -async function linkPointsAt( - filesystem: BundledSkillFilesystem, - path: string, - rawTarget: string, - realPath: string -): Promise { - const resolved = - (await filesystem.realpath(path)) ?? - resolve(await resolveBundledSkillRealPath(filesystem, dirname(path)), rawTarget) - return bundledSkillPathKey(resolved) === bundledSkillPathKey(realPath) -} - type PlannedTarget = { op: BundledSkillOp holdsOrcaCopy: boolean @@ -82,8 +72,16 @@ type PlannedTarget = { leaves: BundledSkillOp[] } -const ORCA_COPY_CLASSES = new Set(['current', 'released', 'edited']) +type PlannedFolderClass = BundledSkillFolderClass | 'other-build' +const ORCA_COPY_CLASSES = new Set([ + 'current', + 'released', + 'edited', + 'other-build' +]) + +/** Classifies one root's copy of the skill and decides its op, including another build's copy. */ async function planTarget( context: SkillContext, root: BundledSkillTargetRoot, @@ -108,13 +106,19 @@ async function planTarget( context.digest, context.sharedRoot ) - let folderClass: BundledSkillFolderClass = classified.folderClass + let folderClass: PlannedFolderClass = classified.folderClass // Cloud receipts identify a different package; a current replaced copy must settle as keep. if ( (folderClass === 'released' || folderClass === 'edited') && (await hasCloudReceipt(stateDirectory, stateKeys)) ) { folderClass = 'other' + } else if ( + folderClass === 'edited' && + (await isOtherBuildCopy(filesystem, context.input.destination, context.source, observed)) + ) { + // A newer build's bytes are unknown here; never call them stale or offer to downgrade them. + folderClass = 'other-build' } const { restoreFrom, cleanup } = await recoverySiblings( filesystem, @@ -158,14 +162,12 @@ async function planTarget( if (!shared) { return files('write') } - if (!shared.current && former.installed) { - return files('write') - } - if (!shared.current) { - return leave('shared-not-current', false) + if (!shared.current && !(shared.otherBuild && filesystem.supportsLinks)) { + return former.installed ? files('write') : leave('shared-not-current', false) } return filesystem.supportsLinks ? linkToShared('link', shared) : files('copy') case 'edited': + case 'other-build': case 'other': break } @@ -174,12 +176,15 @@ async function planTarget( observed.kind === 'link' && (await linkPointsAt(filesystem, path, observed.target, shared.realPath)) ) { - return shared.current + return shared.current || shared.otherBuild ? { ...base, kind: 'keep', cleanup } : leave('shared-not-current', false) } if (context.force !== 'all' && !context.force.has(bundledSkillPathKey(path))) { - return leave(folderClass === 'edited' ? 'edited' : 'other', true) + // Replacing another build's copy may downgrade it, so only an explicit --force offers that. + return folderClass === 'other-build' + ? leave('other-build', false) + : leave(folderClass === 'edited' ? 'edited' : 'other', true) } return shared?.current && filesystem.supportsLinks ? linkToShared('replace', shared) @@ -224,6 +229,7 @@ async function planTarget( } } +/** Plans the shared root first, then agent roots, which may link to the shared copy. */ async function planSkill( input: BundledSkillPlanInput, roots: readonly BundledSkillTargetRoot[], @@ -244,7 +250,8 @@ async function planSkill( ? { path: sharedTarget.op.path, realPath: join(sharedRoot.realPath, source.name), - current: WRITES_SHARED_CURRENT.has(sharedTarget.op.kind) + current: WRITES_SHARED_CURRENT.has(sharedTarget.op.kind), + otherBuild: sharedTarget.op.reason === 'other-build' } : null const planAgents = async (target: SharedTarget | null) => { diff --git a/src/main/skills/bundled-skill-install/bundled-skill-targets.ts b/src/main/skills/bundled-skill-install/bundled-skill-targets.ts index 8a43cfc0d64..653c60643b3 100644 --- a/src/main/skills/bundled-skill-install/bundled-skill-targets.ts +++ b/src/main/skills/bundled-skill-install/bundled-skill-targets.ts @@ -111,3 +111,16 @@ export async function resolveBundledSkillTargets( } return [...roots.values()] } + +/** Whether the link at `path` (raw target `rawTarget`) resolves to `realPath`. */ +export async function linkPointsAt( + filesystem: BundledSkillFilesystem, + path: string, + rawTarget: string, + realPath: string +): Promise { + const resolved = + (await filesystem.realpath(path)) ?? + resolve(await resolveBundledSkillRealPath(filesystem, dirname(path)), rawTarget) + return bundledSkillPathKey(resolved) === bundledSkillPathKey(realPath) +} diff --git a/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts b/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts new file mode 100644 index 00000000000..d505db57c9a --- /dev/null +++ b/src/main/skills/bundled-skill-install/bundled-skill-written-digests.ts @@ -0,0 +1,64 @@ +import { join } from 'node:path' +import type { BundledSkillObserved } from '../../../shared/bundled-skill-plan' +import type { BundledSkillFilesystem } from './bundled-skill-filesystem' + +const SHA256_HEX = /^[0-9a-f]{64}$/u + +/** + * Why on the planned host's disk, not in userData: every Orca build on a host (installed app, + * dev builds, a CLI, a paired server) shares one skills folder but has its own userData. A build + * reads what the others wrote, so a copy a newer build installed is not mistaken for a user edit. + */ +function writtenDigestPath(homeDirectory: string, name: string, digest: string): string { + return join(homeDirectory, '.agents', '.orca-skill-digests', name, digest) +} + +/** Whether some Orca build on this host installed `SKILL.md` text with this digest. */ +export async function wasBundledSkillDigestWritten( + filesystem: BundledSkillFilesystem, + homeDirectory: string, + name: string, + digest: string +): Promise { + if (!SHA256_HEX.test(digest)) { + return false + } + const stat = await filesystem.stat(writtenDigestPath(homeDirectory, name, digest)) + return stat?.kind === 'directory' +} + +/** One empty marker folder per digest: idempotent, append-only, and safe for concurrent builds. */ +export async function recordBundledSkillDigestWritten( + filesystem: BundledSkillFilesystem, + homeDirectory: string, + name: string, + digest: string +): Promise { + if (!SHA256_HEX.test(digest)) { + return + } + // Best effort: a missing marker only means another build may ask about this copy once. + await filesystem + .ensureDirectory(writtenDigestPath(homeDirectory, name, digest)) + .catch(() => undefined) +} + +/** An unknown single-file copy whose bytes some Orca build on this host wrote: not a user edit. */ +export async function isOtherBuildCopy( + filesystem: BundledSkillFilesystem, + destination: { homeDirectory: string }, + source: { name: string }, + observed: BundledSkillObserved +): Promise { + return ( + observed.kind === 'folder' && + observed.entries.length === 1 && + observed.skillDigest !== null && + (await wasBundledSkillDigestWritten( + filesystem, + destination.homeDirectory, + source.name, + observed.skillDigest + )) + ) +} diff --git a/src/main/skills/bundled-skill-install/renamed-skill-placement.ts b/src/main/skills/bundled-skill-install/renamed-skill-placement.ts index 9cf51ce3ba1..3e681b8cfb1 100644 --- a/src/main/skills/bundled-skill-install/renamed-skill-placement.ts +++ b/src/main/skills/bundled-skill-install/renamed-skill-placement.ts @@ -9,6 +9,7 @@ import { import { classifyBundledSkillPath } from './bundled-skill-classification' import type { BundledSkillPlanInput } from './bundled-skill-plan' import { recoverySiblings } from './bundled-skill-swap-recovery' +import { isOtherBuildCopy } from './bundled-skill-written-digests' import { bundledSkillPathKey, type BundledSkillTargetRoot } from './bundled-skill-targets' export async function planFormerSkillPlacements( @@ -80,9 +81,13 @@ export async function planFormerSkillPlacements( reason ?? (observed.kind === 'unreadable' ? 'unreadable' - : classified.folderClass === 'edited' - ? 'edited' - : 'other') + : classified.folderClass !== 'edited' + ? 'other' + : // A build from before the rename recorded these bytes under the former name. + !cloud && + (await isOtherBuildCopy(filesystem, input.destination, { name }, observed)) + ? 'other-build' + : 'edited') }) continue } diff --git a/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.test.ts b/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.test.ts new file mode 100644 index 00000000000..8f32ddd4ee2 --- /dev/null +++ b/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.test.ts @@ -0,0 +1,168 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { BundledSkillPlan } from '../../../../../shared/bundled-skill-plan' +import type { BundledSkillTarget } from '@/lib/skills/runtime/bundled-skill-target' + +const autoUpdate = vi.hoisted(() => vi.fn()) +const toastWarning = vi.hoisted(() => vi.fn()) +const skillsChanged = vi.hoisted(() => vi.fn()) +vi.mock('sonner', () => ({ toast: { warning: toastWarning } })) +vi.mock('@/store/index', () => ({ + useAppStore: { getState: () => ({ runtimeEnvironments: [] }) } +})) +vi.mock('@/runtime/skills/bundled/runtime-bundled-skills-client', () => ({ + autoUpdateBundledSkillsOnTarget: autoUpdate +})) +vi.mock('@/hooks/skills/discovery/installed-agent-skill-discovery', () => ({ + notifyInstalledAgentSkillsChanged: skillsChanged +})) + +const { _resetSkillFreshnessAutoUpdate, autoUpdateUnmodifiedSkills } = + await import('./skill-freshness-auto-update') +const { getSkillUpdateRun } = await import('./skill-update-run-store') +const { RuntimeRpcCallError } = await import('@/runtime/rpc/calls/runtime-rpc-result') + +const DIGEST = 'a'.repeat(64) + +/** Every location already holds this build's bytes: the plan is keep-only. */ +const currentPlan: BundledSkillPlan = { + scope: 'global', + homeDirectory: '/home/me', + planDigest: 'p'.repeat(64), + skills: [ + { + name: 'orca-cli', + digest: DIGEST, + ops: [ + { + kind: 'keep', + path: '/home/me/.agents/skills/orca-cli', + role: 'shared', + agents: [], + observed: { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: DIGEST }, + cleanup: [] + } + ] + } + ] +} + +afterEach(() => { + _resetSkillFreshnessAutoUpdate() + autoUpdate.mockReset() + toastWarning.mockReset() + skillsChanged.mockReset() +}) + +describe('startup scan of an already-current host', () => { + it.each<[string, BundledSkillTarget]>([ + ['this machine', { kind: 'local' }], + ['a paired server', { kind: 'environment', environmentId: 'server-1' }] + ])('asks %s once to record its current copy, without claiming it', async (_, target) => { + autoUpdate.mockResolvedValue({ scope: 'global', skills: [] }) + + expect(autoUpdateUnmodifiedSkills(target, currentPlan).size).toBe(0) + await vi.waitFor(() => + expect(autoUpdate).toHaveBeenCalledWith(target, ['orca-cli'], { recordOnly: true }) + ) + autoUpdateUnmodifiedSkills(target, currentPlan) + expect(autoUpdate).toHaveBeenCalledTimes(1) + }) + + it.each<[string, () => Promise]>([ + ['the record-only call keeps failing', () => Promise.reject(new Error('offline'))], + [ + 'a sent record-only call times out', + () => + Promise.reject( + new RuntimeRpcCallError({ + id: '1', + ok: false, + error: { code: 'timeout', message: 'Timed out waiting for the remote Orca runtime' }, + _meta: { runtimeId: 'r' } + }) + ) + ], + [ + 'the host keeps reporting the skill busy', + () => + Promise.resolve({ + scope: 'global', + skills: [{ name: 'orca-cli', status: 'busy', ops: [] }] + }) + ] + ])('asks only once per session, without a warning or re-plan, when %s', async (_, reply) => { + const target: BundledSkillTarget = { kind: 'environment', environmentId: 'server-1' } + autoUpdate.mockImplementation(reply) + // The nudge re-plans on every skills-changed signal and scans the fresh plan, as in the app. + // Capped so a regression fails instead of spinning forever. + let refreshes = 0 + skillsChanged.mockImplementation(() => { + refreshes += 1 + if (refreshes < 5) { + autoUpdateUnmodifiedSkills(target, currentPlan) + } + }) + + autoUpdateUnmodifiedSkills(target, currentPlan) + // The run is marked running synchronously, so this first passes after the call has settled. + await vi.waitFor(() => expect(getSkillUpdateRun('runtime:server-1').state).toBe('idle')) + autoUpdateUnmodifiedSkills(target, currentPlan) + + expect(autoUpdate).toHaveBeenCalledTimes(1) + expect(refreshes).toBe(0) + // A record-only call can never write a skill, so no failure of it is worth a warning. + expect(toastWarning).not.toHaveBeenCalled() + }) +}) + +describe('silent update of a released copy', () => { + const RELEASED = 'b'.repeat(64) + const releasedPlan: BundledSkillPlan = { + ...currentPlan, + skills: [ + { + name: 'orca-cli', + digest: DIGEST, + ops: [ + { + kind: 'update', + path: '/home/me/.agents/skills/orca-cli', + role: 'shared', + agents: [], + observed: { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: RELEASED }, + cleanup: [] + } + ] + }, + { + name: 'orchestration', + digest: DIGEST, + ops: [ + { + kind: 'keep', + path: '/home/me/.agents/skills/orchestration', + role: 'shared', + agents: [], + observed: { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: DIGEST }, + cleanup: [] + } + ] + } + ] + } + + it('updates without a record-only request in the same scan, and warns when the reply is lost', async () => { + const target: BundledSkillTarget = { kind: 'environment', environmentId: 'server-1' } + autoUpdate.mockRejectedValueOnce(new Error('timed out')) + autoUpdate.mockResolvedValue({ scope: 'global', skills: [] }) + + expect([...autoUpdateUnmodifiedSkills(target, releasedPlan)]).toEqual(['orca-cli']) + expect(autoUpdate).toHaveBeenCalledWith(target, ['orca-cli'], { recordOnly: false }) + await vi.waitFor(() => expect(toastWarning).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(skillsChanged).toHaveBeenCalledTimes(1)) + + // The re-plan after the update records the current copy on its own. + autoUpdateUnmodifiedSkills(target, releasedPlan) + expect(autoUpdate).toHaveBeenLastCalledWith(target, ['orchestration'], { recordOnly: true }) + }) +}) diff --git a/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.ts b/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.ts index 1f267b74b50..f195a26109c 100644 --- a/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.ts +++ b/src/renderer/src/components/skills/freshness/skill-freshness-auto-update.ts @@ -4,7 +4,10 @@ import type { BundledSkillPlan, BundledSkillPlanEntry } from '../../../../../shared/bundled-skill-plan' -import { isBundledSkillAutoUpdateOp } from '../../../../../shared/bundled-skill-summary' +import { + holdsCurrentBundledSkillCopy, + isBundledSkillAutoUpdateOp +} from '../../../../../shared/bundled-skill-summary' import { notifyInstalledAgentSkillsChanged } from '@/hooks/skills/discovery/installed-agent-skill-discovery' import { bundledSkillTargetKey, @@ -12,6 +15,7 @@ import { } from '@/lib/skills/runtime/bundled-skill-target' import { translate } from '@/i18n/i18n' import { autoUpdateBundledSkillsOnTarget } from '@/runtime/skills/bundled/runtime-bundled-skills-client' +import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' import { useAppStore } from '@/store/index' import { getSkillUpdateRun, runAutomaticSkillUpdate } from './skill-update-run-store' @@ -19,6 +23,11 @@ import { getSkillUpdateRun, runAutomaticSkillUpdate } from './skill-update-run-s type AttemptState = 'running' | 'settled' // Keyed by target; each scan prunes what it no longer observes, so the map stays plan-sized. const attemptsByTarget = new Map>() +// Current copies asked to record their marker this session; one per host pairing, skill and bytes. +// Why never released on failure: a retry would re-run on every plan refresh while the host stays +// busy or unreachable. A missing marker is best effort; the next session, a manual update, or any +// later write of the skill records it. +const markedCopies = new Set() /** Drop settled attempts for states this scan no longer sees; running ones still own their skills. */ function pruneAttempts(targetKey: string, liveKeys: ReadonlySet): void { @@ -154,15 +163,39 @@ export function autoUpdateUnmodifiedSkills( keys.push(key) } } - if (started.length > 0) { + // Why: a copy already at this build's digest plans keep-only, so no update ever runs to mark it. + // Asked when no update starts, as a record-only call that can never write a skill. + const recordOnly = started.length === 0 + // Why the pairing revision: a re-pair may put a different machine behind the same server ID. + const host = + target.kind === 'environment' ? getRuntimeEnvironmentRevision(target.environmentId) : undefined + const marking = + canStart && recordOnly + ? entries.flatMap(({ entry, key }) => { + const mark = `${targetKey}#${host ?? ''}:${entry.name}@${entry.digest}` + return !key && !markedCopies.has(mark) && holdsCurrentBundledSkillCopy(entry) + ? [{ name: entry.name, mark }] + : [] + }) + : [] + for (const { mark } of marking) { + markedCopies.add(mark) + } + const names = recordOnly ? marking.map(({ name }) => name) : started + if (names.length > 0) { // The host re-plans under its locks and re-checks each location right before writing. - void runAutomaticSkillUpdate(target, started, () => - autoUpdateBundledSkillsOnTarget(target, started) + void runAutomaticSkillUpdate(target, names, () => + autoUpdateBundledSkillsOnTarget(target, names, { recordOnly }) ) .then( (ran) => reportPreservedEdits(ran?.value ?? null), // Settling the keys below means the same state is never retried; the nudge takes over. - () => reportUncertainOutcome(target, plan) + // A record-only call writes no skill, so its failure has nothing to warn about. + () => { + if (!recordOnly) { + reportUncertainOutcome(target, plan) + } + } ) .catch(() => undefined) .finally(() => { @@ -171,7 +204,10 @@ export function autoUpdateUnmodifiedSkills( for (const key of keys) { settled.set(key, 'settled') } - notifyInstalledAgentSkillsChanged() + // Markers never change this build's own plan, so only an update needs a re-plan. + if (!recordOnly) { + notifyInstalledAgentSkillsChanged() + } }) } return owned @@ -180,6 +216,7 @@ export function autoUpdateUnmodifiedSkills( /** @internal - tests need a clean module between cases. */ export function _resetSkillFreshnessAutoUpdate(): void { attemptsByTarget.clear() + markedCopies.clear() } /** @internal - lets tests prove the attempt map stays bounded. */ diff --git a/src/renderer/src/components/skills/freshness/skill-plan-op-copy.ts b/src/renderer/src/components/skills/freshness/skill-plan-op-copy.ts index 9c23388d04e..afc98c8ee65 100644 --- a/src/renderer/src/components/skills/freshness/skill-plan-op-copy.ts +++ b/src/renderer/src/components/skills/freshness/skill-plan-op-copy.ts @@ -37,6 +37,7 @@ export function updatedSkillsLabel( : updated } +/** Translated reason Orca left a location alone; unknown reasons from newer hosts fall back. */ export function leaveReasonText( reason: string | null | undefined, t: Translate = translate @@ -47,6 +48,11 @@ export function leaveReasonText( switch (reason) { case 'edited': return t('auto.components.skills.skillPlanOpCopy.edited', 'Skill edited outside Orca') + case 'other-build': + return t( + 'auto.components.skills.skillPlanOpCopy.otherBuild', + 'Installed by another Orca version' + ) case 'other': return t('auto.components.skills.skillPlanOpCopy.other', 'A different skill uses this name') case 'unwritable': @@ -87,13 +93,19 @@ export function locationStateText(location: BundledSkillLocation): string { 'keep-link': () => translate('auto.components.skills.skillPlanOpCopy.keepLink', 'Link, no change'), leave: () => - translate( - 'auto.components.skills.skillPlanOpCopy.updateSkipped', - 'Update skipped: {{value0}}', - { - value0: leaveReasonText(location.reason) - } - ), + // Another build's copy was never meant to update, so it is kept rather than skipped. + location.reason === 'other-build' + ? translate( + 'auto.components.skills.skillPlanOpCopy.otherBuildKept', + 'Kept: written by another Orca version' + ) + : translate( + 'auto.components.skills.skillPlanOpCopy.updateSkipped', + 'Update skipped: {{value0}}', + { + value0: leaveReasonText(location.reason) + } + ), unknown: () => translate('auto.components.skills.skillPlanOpCopy.needsAttention', 'Needs attention') } diff --git a/src/renderer/src/components/skills/setup/bundled-skill-setup-result-copy.ts b/src/renderer/src/components/skills/setup/bundled-skill-setup-result-copy.ts index 76a7a75989a..a8c7ea52c8c 100644 --- a/src/renderer/src/components/skills/setup/bundled-skill-setup-result-copy.ts +++ b/src/renderer/src/components/skills/setup/bundled-skill-setup-result-copy.ts @@ -28,12 +28,17 @@ const RESULT_HEADLINE_ORDER: readonly BundledSkillOutcomeText[] = [ 'Linked' ] +/** Why setup can't finish: the first location Orca must leave and can't replace. */ export function bundledSkillSetupAttentionMessage(plan: BundledSkillPlan): string { const blocked = plan.skills .flatMap((entry) => entry.ops) .find( (op) => - op.kind === 'leave' && !op.replaceable && op.reason && isBundledSkillLeaveReason(op.reason) + op.kind === 'leave' && + !op.replaceable && + op.reason !== 'other-build' && + op.reason && + isBundledSkillLeaveReason(op.reason) ) switch (blocked?.reason) { case 'unwritable': @@ -67,6 +72,8 @@ export function bundledSkillSetupAttentionMessage(plan: BundledSkillPlan): strin 'auto.components.settings.bundledSkillSetupCopy.attentionSharedNotCurrent', 'Needs attention · The shared copy this folder uses is not Orca’s' ) + // Another build's copy is kept, never a blocker, so it never reaches here; listed for exhaustiveness. + case 'other-build': case undefined: return translate('auto.components.skills.skillPlanOpCopy.needsAttention', 'Needs attention') } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 40a6c5c343d..2af4228bba0 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -6491,7 +6491,9 @@ "updateSkipped": "Update skipped: {{value0}}", "updateAvailable": "Update available", "repairAvailable": "Repair available", - "installAvailable": "Install available" + "installAvailable": "Install available", + "otherBuild": "Installed by another Orca version", + "otherBuildKept": "Kept: written by another Orca version" }, "installResult": { "installed": "Installed and verified.", diff --git a/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.test.ts b/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.test.ts new file mode 100644 index 00000000000..9057f11d54d --- /dev/null +++ b/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.test.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { autoUpdateBundledSkillsOnTarget } from './runtime-bundled-skills-client' +import { clearRuntimeCompatibilityCache } from '../../rpc/compatibility/runtime-compatibility-cache' +import { replaceRuntimeEnvironmentRevisions } from '../../rpc/environment-revisions/runtime-environment-revision' +import { BUNDLED_ORCA_SKILL_AUTO_UPDATE_CAPABILITY } from '../../../../../shared/skill-install-capability' +import { + MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + RUNTIME_PROTOCOL_VERSION +} from '../../../../../shared/protocol-version' + +const ENVIRONMENT_ID = 'server-1' +const target = { kind: 'environment' as const, environmentId: ENVIRONMENT_ID } + +type CallArgs = { + selector: string + method: string + params?: unknown + expectedEnvironmentPairingRevision?: number + expectedEnvironmentRuntimeId?: string +} +const call = vi.fn<(args: CallArgs) => unknown>() + +function setPairingRevision(pairingRevision: number): void { + replaceRuntimeEnvironmentRevisions([{ id: ENVIRONMENT_ID, createdAt: 1, pairingRevision }]) +} + +function status(runtimeId: string) { + return { + id: 'status', + ok: true, + result: { + runtimeId, + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, + capabilities: [BUNDLED_ORCA_SKILL_AUTO_UPDATE_CAPABILITY] + }, + _meta: { runtimeId } + } +} + +beforeEach(() => { + clearRuntimeCompatibilityCache() + setPairingRevision(41) + call.mockReset() + vi.stubGlobal('window', { api: { runtimeEnvironments: { call } } }) +}) + +describe('silent skill update on a paired server', () => { + it('sends the update only to the runtime and pairing that answered the capability check', async () => { + call.mockImplementation(async (args) => + args.method === 'status.get' + ? status('runtime-a') + : { id: 'u', ok: true, result: { scope: 'global', skills: [] }, _meta: {} } + ) + + await autoUpdateBundledSkillsOnTarget(target, ['orca-cli'], { recordOnly: true }) + + expect(call).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'skills.autoUpdateBundledOrca', + params: { names: ['orca-cli'], recordOnly: true }, + expectedEnvironmentPairingRevision: 41, + expectedEnvironmentRuntimeId: 'runtime-a' + }) + ) + }) + + it('never sends the update when the server is re-paired while the capability check awaits', async () => { + call.mockImplementation(async (args) => { + if (args.method === 'status.get') { + // Another host takes over this saved server before its status answer arrives. + setPairingRevision(42) + return status('runtime-b') + } + return { id: 'u', ok: true, result: { scope: 'global', skills: [] }, _meta: {} } + }) + + await expect(autoUpdateBundledSkillsOnTarget(target, ['orca-cli'])).rejects.toThrow() + expect(call).not.toHaveBeenCalledWith( + expect.objectContaining({ method: 'skills.autoUpdateBundledOrca' }) + ) + }) +}) diff --git a/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.ts b/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.ts index a290a3446d0..ec096cc075b 100644 --- a/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.ts +++ b/src/renderer/src/runtime/skills/bundled/runtime-bundled-skills-client.ts @@ -11,7 +11,10 @@ import { import { bundledSkillNames } from '../../../../../shared/bundled-skill-names' import type { BundledSkillTarget } from '@/lib/skills/runtime/bundled-skill-target' import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' -import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof' +import { + runtimeEnvironmentCapabilityProof, + runtimeEnvironmentSupportsCapability +} from '../../rpc/compatibility/runtime-capability-proof' const BUNDLED_SKILL_PLAN_TIMEOUT_MS = 60_000 const BUNDLED_SKILL_EXECUTE_TIMEOUT_MS = 5 * 60_000 @@ -94,30 +97,38 @@ export async function executeBundledSkillsOnTarget( ) } -/** Silently updates hash-verified copies of `names`; null when the host predates it, so the caller asks instead. */ +/** + * Silently updates hash-verified copies of `names`; null when the host predates it, so the caller asks instead. + * `recordOnly` only records copies already at the host's bytes and never updates a skill. + */ export async function autoUpdateBundledSkillsOnTarget( target: BundledSkillTarget, - names: string[] + names: string[], + options: { recordOnly?: boolean } = {} ): Promise { if (target.kind === 'ssh') { return null } + const request = { names, ...(options.recordOnly ? { recordOnly: true as const } : {}) } if (target.kind !== 'environment') { - return window.api.skills.bundledAutoUpdate({ names }) + return window.api.skills.bundledAutoUpdate(request) } - if ( - !(await runtimeEnvironmentSupportsCapability( - target.environmentId, - BUNDLED_ORCA_SKILL_AUTO_UPDATE_CAPABILITY - )) || - !(await supportsSelectedNames(target.environmentId, names)) - ) { + // Why pinned: a re-pair while these probes await must not send this write to a different host. + const proof = await runtimeEnvironmentCapabilityProof( + target.environmentId, + BUNDLED_ORCA_SKILL_AUTO_UPDATE_CAPABILITY + ) + if (!proof.supported || !(await supportsSelectedNames(target.environmentId, names))) { return null } return callRuntimeRpc( { kind: 'environment', environmentId: target.environmentId }, 'skills.autoUpdateBundledOrca', - { names }, - { timeoutMs: BUNDLED_SKILL_EXECUTE_TIMEOUT_MS } + request, + { + timeoutMs: BUNDLED_SKILL_EXECUTE_TIMEOUT_MS, + expectedEnvironmentRuntimeId: proof.runtimeId, + expectedEnvironmentPairingRevision: proof.pairingRevision + } ) } diff --git a/src/shared/bundled-skill-plan.ts b/src/shared/bundled-skill-plan.ts index bd4207e983f..3c62921f9ad 100644 --- a/src/shared/bundled-skill-plan.ts +++ b/src/shared/bundled-skill-plan.ts @@ -20,6 +20,8 @@ export function isBundledSkillOpKind(value: string): value is BundledSkillOpKind export const BUNDLED_SKILL_LEAVE_REASONS = Object.freeze([ 'edited', + /** A copy another Orca build (newer, or a dev build) installed; its bytes are unknown here. */ + 'other-build', 'other', 'unwritable', 'unreadable', @@ -161,7 +163,10 @@ export const BundledSkillAutoUpdateRequestSchema = z.strictObject({ names: z .array(z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/u)) .min(1) - .max(64) + .max(64), + /** Only record which copies already hold this build's bytes; never update any skill. Hosts + * that predate it reject the request, so they write nothing either. */ + recordOnly: z.literal(true).optional() }) export type BundledSkillAutoUpdateRequest = z.infer // Desktop IPC may target a chat provider without a CLI on PATH; the remote v1 schema stays frozen. diff --git a/src/shared/bundled-skill-summary.test.ts b/src/shared/bundled-skill-summary.test.ts new file mode 100644 index 00000000000..8b40536315d --- /dev/null +++ b/src/shared/bundled-skill-summary.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import type { BundledSkillOp, BundledSkillPlan } from './bundled-skill-plan' +import { bundledSkillNudgeKey, summarizeBundledSkillPlan } from './bundled-skill-summary' + +const folder = { kind: 'folder', entries: ['SKILL.md:file'], skillDigest: 'a'.repeat(64) } as const + +function op(fields: Partial): BundledSkillOp { + return { + kind: 'keep', + path: '/home/me/.agents/skills/x', + role: 'shared', + agents: [], + observed: folder, + cleanup: [], + ...fields + } +} + +/** A plan as a paired server returns it: planned on the server's disk against the server's own bundle. */ +const serverPlan = (ops: BundledSkillOp[]): BundledSkillPlan => ({ + scope: 'global', + homeDirectory: '/home/me', + skills: [{ name: 'orca-cli', digest: 'b'.repeat(64), ops }], + planDigest: 'c'.repeat(64) +}) + +describe('another Orca build’s copy in a planned host’s plan', () => { + it('reads as current and is never offered as an update', () => { + const plan = serverPlan([ + op({ kind: 'leave', reason: 'other-build', replaceable: true }), + op({ + path: '/home/me/.claude/skills/x', + role: 'agent', + observed: { kind: 'link', target: 'x' } + }) + ]) + + expect(summarizeBundledSkillPlan(plan)).toMatchObject({ + badge: null, + hasWork: false, + skills: [{ name: 'orca-cli', state: 'current' }] + }) + expect(bundledSkillNudgeKey('runtime:server-1', plan)).toBeNull() + }) +}) diff --git a/src/shared/bundled-skill-summary.ts b/src/shared/bundled-skill-summary.ts index b156e9f8dcf..1162718ccb6 100644 --- a/src/shared/bundled-skill-summary.ts +++ b/src/shared/bundled-skill-summary.ts @@ -37,6 +37,7 @@ const OP_PLAN_STATE: Readonly> export const BUNDLED_SKILL_LEAVE_REASON_TEXT: Readonly> = { edited: 'Skill edited outside Orca', + 'other-build': 'Installed by another Orca version', other: 'A different skill uses this name', unwritable: "Orca can't write to this folder", unreadable: "Orca can't read every file", @@ -57,11 +58,12 @@ export const BUNDLED_SKILL_PLAN_OP_TEXT: Readonly< restore: 'Repair' } +/** One location's summary state; other owners' and other builds' copies read as current. */ function opPlanState( op: Pick ): BundledSkillPlanState { - // Other owners’ same-named skills are listed without flagging them. - if (op.kind === 'leave' && op.reason === 'other') { + // Other owners’ same-named skills, and another Orca build's copy, are listed without flagging them. + if (op.kind === 'leave' && (op.reason === 'other' || op.reason === 'other-build')) { return 'current' } return op.previous?.length @@ -135,10 +137,15 @@ export function bundledSkillInstallAction(plan: BundledSkillPlan): BundledSkillI if (paths.length > 0) { return { kind: 'replace', paths } } + // Another Orca build's copy is kept on purpose: an installed skill, not one to fix. const current = plan.skills.length > 0 && plan.skills.every( - (entry) => entry.ops.length > 0 && entry.ops.every((op) => op.kind === 'keep') + (entry) => + entry.ops.length > 0 && + entry.ops.every( + (op) => op.kind === 'keep' || (op.kind === 'leave' && op.reason === 'other-build') + ) ) return { kind: current ? 'none' : 'attention' } } @@ -166,6 +173,16 @@ export function isBundledSkillAutoUpdateOp( ) } +/** A location already holds exactly this build's bytes; executing records it as Orca's copy. */ +export function holdsCurrentBundledSkillCopy(entry: BundledSkillPlanEntry): boolean { + return entry.ops.some( + (op) => + op.kind === 'keep' && + op.observed.kind === 'folder' && + op.observed.skillDigest === entry.digest + ) +} + function opNeedsConsent(op: BundledSkillOp, autoUpdating: boolean): boolean { // An old copy holding edits Orca has not yet backed up waits on the user, never on deletion. if (op.cleanup.some((item) => item.action === 'backup')) { From c55af116d142c7ae598c1ab7a3cfd49ece800bf0 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:49:12 -0800 Subject: [PATCH 14/44] fix(native-chat): keep final reply spacing consistent (#41440) * fix(native-chat): keep reply spacing consistent at transcript end * test(native-chat): remove unrelated inline visual fork case --- .../native-chat-appearance-style.ts | 4 +- .../native-chat-response-actions-hang.ts | 10 +- .../slots/native-chat-transcript-input.ts | 2 - .../native-chat-transcript-slots.test.ts | 22 +++++ .../slots/native-chat-transcript-slots.ts | 3 +- .../slots/use-native-chat-transcript-slots.ts | 6 +- .../media/visuals/NativeChatInlineVisual.tsx | 4 +- .../rows/NativeChatReplyGap.fixture.tsx | 94 +++++++++++++++++++ 8 files changed, 127 insertions(+), 18 deletions(-) create mode 100644 src/renderer/src/components/native-chat/messages/rows/NativeChatReplyGap.fixture.tsx diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts index a7ad3d10708..1158d85a482 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts @@ -15,9 +15,9 @@ import { terminalChatSelectionMix } from '@/app-shell/appearance/chat-selection- import type { GlobalSettings } from '../../../../../shared/global-settings-types' export const NATIVE_CHAT_APPEARANCE_ROOT_CLASS = 'native-chat-appearance bg-chat-canvas' -// Bottom padding clears 20px control overhang; rail padding also covers its 34px overlay on macOS without scrollbar gutters. +// One fixed bottom gap: the last row never hangs its controls; rail padding covers its 34px macOS overlay. export function nativeChatTranscriptOuterClass(railVisible: boolean): string { - return railVisible ? 'px-9 pt-10 pb-10' : 'px-3 pt-10 pb-10 sm:px-4' + return railVisible ? 'px-9 pt-10 pb-5' : 'px-3 pt-10 pb-5 sm:px-4' } export const NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS = 'mx-auto flex w-full max-w-(--chat-content-max-width) flex-col gap-5 px-[5px]' diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts index 86477296a54..8da798ea106 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-response-actions-hang.ts @@ -1,5 +1,5 @@ -// Response controls sit on the left. They may hang into the gap below only when nothing else on the -// left starts there; otherwise they would touch the next item, so they keep their own height. +// Response controls sit on the left. They may hang into the gap above the person's own bubble, where +// nothing else on the left starts; elsewhere, the transcript's last row included, they keep their height. import { type NativeChatRowTypography, @@ -64,8 +64,6 @@ function slotHoldsControls( * controls stay in flow. Runs after `endsResponse` and `continuesTurn` are known. */ export function markNativeChatResponseActionsHang( drawn: readonly NativeChatTranscriptSlot[], - /** A left-side row draws under the last slot (the live activity line, the awaiting-input row). */ - tailRowBelow: boolean, typography?: NativeChatRowTypography ): void { // Newest first, carrying what draws next: a send that never reached the journal draws after the @@ -88,7 +86,9 @@ export function markNativeChatResponseActionsHang( } if ( !slotDrawsAfterMessage(slot) && - (next === undefined ? !tailRowBelow : slotOpensWithPersonBubble(next)) + // The last row never hangs, so the gap to the composer is the same whatever the turn ends on. + next !== undefined && + slotOpensWithPersonBubble(next) ) { slot.actionsHang = true } else if (slotHoldsControls(slot, typography)) { diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts index 5caae49a239..91efb9c108a 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-input.ts @@ -38,6 +38,4 @@ export type NativeChatTranscriptSlotsInput = { subagentChoices?: NativeChatSubagentChoices /** The open reasoning block the live activity line discloses: its row takes no slot meanwhile. */ liveReasoningId?: string | null - /** A left-side row draws under the last slot: the live activity line or the awaiting-input row. */ - tailRowBelow?: boolean } diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts index cf809b4e2a4..a6725a8eff4 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.test.ts @@ -184,6 +184,28 @@ describe('transcript slots', () => { } ) + it("hangs response controls only above the person's next message, never on the last row", () => { + const visualReply = text('visual', 'Here is the trend.\n\n::orca-visual{file="trend.html"}') + const hangs = (messages: NativeChatMessage[]) => + build(messages).map((slot) => [slot.message.id, slot.actionsHang === true]) + + expect(hangs([text('u1', 'Hi', 'user'), text('reply', 'Hello')])).toEqual([ + ['u1', false], + ['reply', false] + ]) + expect(hangs([text('u1', 'Chart it', 'user'), visualReply])).toEqual([ + ['u1', false], + ['visual', false] + ]) + expect( + hangs([text('u1', 'Hi', 'user'), text('reply', 'Hello'), text('u2', 'Thanks', 'user')]) + ).toEqual([ + ['u1', false], + ['reply', true], + ['u2', false] + ]) + }) + it('draws the completed plan outside collapsed work', () => { const plan: NativeChatMessage = { ...text('plan', '# Proposed change', 'system'), diff --git a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts index dbbba160294..170731386b1 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/native-chat-transcript-slots.ts @@ -131,7 +131,6 @@ export function buildNativeChatTranscript( subagentSections: sections = NO_NATIVE_CHAT_SUBAGENT_SECTIONS, subagentChoices: choices = NO_NATIVE_CHAT_SUBAGENT_CHOICES, liveReasoningId = null, - tailRowBelow = false, forkOffer } = input const settledTurnKeys = new Set( @@ -313,7 +312,7 @@ export function buildNativeChatTranscript( slot.continuesTurn = true } } - markNativeChatResponseActionsHang(drawn, tailRowBelow, typography) + markNativeChatResponseActionsHang(drawn, typography) return { slots: drawn, forkPoint: forkOffer diff --git a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts index c738d723e7e..92bb31c8821 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts +++ b/src/renderer/src/components/native-chat/conversation/slots/use-native-chat-transcript-slots.ts @@ -20,7 +20,7 @@ import type { NativeChatTranscriptSlotsInput } from './native-chat-transcript-in export function useNativeChatTranscriptSlots({ line, ...input -}: Omit & { +}: Omit & { line: { /** The row drawn under the transcript, if any. */ tailRow: 'awaiting-input' | 'activity' | null @@ -86,8 +86,6 @@ export function useNativeChatTranscriptSlots({ ] ) const liveReasoningId = liveLine?.reasoning?.message.id ?? null - // A boolean, so the line's changing words never rebuild the slots. - const tailRowBelow = liveLine !== null || tailRow === 'awaiting-input' const { slots, forkPoint } = useMemo( () => buildNativeChatTranscript({ @@ -107,7 +105,6 @@ export function useNativeChatTranscriptSlots({ subagentSections, subagentChoices, liveReasoningId, - tailRowBelow, forkOffer }), [ @@ -123,7 +120,6 @@ export function useNativeChatTranscriptSlots({ receipts, subagentChoices, subagentSections, - tailRowBelow, turnDiffs, turnKeys, turnStatuses, diff --git a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx index edc7937b816..8724de50fb1 100644 --- a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx @@ -27,7 +27,7 @@ import type { NativeChatVisualOwner } from './native-chat-visual-owner' export function NativeChatVisualUnavailable(): React.JSX.Element { const t = useTranslate() return ( -

+

{t('components.native-chat.visualUnavailable', 'Visualization unavailable')}

) @@ -117,7 +117,7 @@ export function NativeChatInlineVisual({ const openLabel = t('components.native-chat.visualOpenInNewTab', 'Open in new tab') return ( -
+
{state.status === 'ready' && near ? ( <> {/* Above the frame, not over it: the page owns every pixel of its box. */} diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatReplyGap.fixture.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatReplyGap.fixture.tsx new file mode 100644 index 00000000000..a5876181b12 --- /dev/null +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatReplyGap.fixture.tsx @@ -0,0 +1,94 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { NativeChatMessageList } from '../../NativeChatMessageList' +import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { NativeChatVisualOwnerContext } from '../../media/visuals/native-chat-visual-owner' +import { + NATIVE_CHAT_APPEARANCE_ROOT_CLASS, + nativeChatAppearanceStyle +} from '../../appearance/native-chat-appearance-style' + +const owner = { + target: { kind: 'local' as const }, + sessionId: 'reply-gap', + worktreeId: 'reply-gap' +} + +function message(id: string, role: NativeChatMessage['role'], text: string): NativeChatMessage { + return { + id, + role, + timestamp: + 1_800_000_000_000 + ['earlier-ask', 'earlier-reply', 'ask', 'reply'].indexOf(id) * 60_000, + source: 'transcript', + blocks: [{ type: 'text', text }] + } +} + +function ReplyGap({ visual }: { visual: boolean }): React.JSX.Element { + const session: NativeChatLiveSession = { + agent: 'codex', + sessionId: 'reply-gap', + status: 'ready', + readPhase: 'ready', + hasMore: false, + loadingEarlier: false, + olderHistoryGeneration: 0, + loadEarlier: async () => 'applied', + messages: [ + message('earlier-ask', 'user', 'Review the earlier result.'), + message( + 'earlier-reply', + 'assistant', + 'The earlier result is ready.\n\nThe inputs have been checked.\n\nThe comparison is complete.\n\nThe earlier trend was steady.\n\nThe summary is recorded.\n\nThe next result follows below.' + ), + message('ask', 'user', 'Summarize the result.'), + message( + 'reply', + 'assistant', + visual + ? 'The trend is increasing.\n\n::orca-visual{file="trend.html"}' + : 'The trend is increasing.' + ) + ] + } + const theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light' + return ( + +
+ +
+ Composer boundary +
+
+
+ ) +} + +function visualSetup(): void { + const call = window.api.runtime.call + window.api.runtime.call = async (request) => + request.method === 'agentSession.readVisual' + ? { + id: 'reply-gap', + ok: true, + _meta: { runtimeId: 'fixture' }, + result: { + ok: true, + revision: '1', + path: '/workspace/trend.html', + html: '
Trend: 12 → 18 → 25
' + } + } + : call(request) +} + +export const textEnding = defineFixture({ width: 560, render: () => }) +export const visualEnding = defineFixture({ + width: 560, + setup: visualSetup, + render: () => +}) From cab3a673827fb3baf7af13feb66603daccd21fe9 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:54:51 -0800 Subject: [PATCH 15/44] refactor(orcad): organize runtime, launch, and host lifecycle owners (#41659) --- .github/workflows/node-server-tests.yml | 2 +- .github/workflows/ssh-hostile-hosts.yml | 4 +- .github/workflows/ssh-windows-hosts.yml | 6 +- config/build-plugins/cli-main-entry-names.ts | 4 +- config/daemon-blocking-call-baseline.txt | 2 +- config/electron-builder.config.cjs | 4 +- config/flaky-test-pattern-baseline.txt | 23 +- config/main-sync-fs-baseline.txt | 66 ++-- config/main-sync-spawn-baseline.txt | 4 +- config/recurring-timer-baseline.txt | 8 +- config/reliability-gates.jsonc | 29 +- .../scripts/ci/sharding/ci-shard-timings.json | 74 ++-- ...heck-runtime-launcher-protocol-ratchet.mjs | 2 +- .../node-server-qualification.mjs | 4 +- .../qualification/node-server-test-paths.mjs | 25 +- .../compact-packaged-orcad-ripgrep.test.mjs | 67 +--- .../template/packaged-orcad-browser.test.mjs | 69 ---- .../source-routing/pr-code-change-scope.mjs | 8 +- .../runtime/cli-lifecycle-handlers.test.ts | 2 +- src/cli/runtime/cli-lifecycle-handlers.ts | 2 +- src/cli/server/serve-reset-identity.test.ts | 2 +- src/cli/server/serve-reset-identity.ts | 2 +- .../__mocks__/worktree-create-preparation.ts | 4 +- .../presence/server-hook-root-replay.test.ts | 315 ------------------ .../session-search-host-registration.test.ts | 3 +- .../backend-desktop/backend-supervisor.ts | 2 +- src/main/backend/backend-entry.ts | 6 +- src/main/backend/service-composition.ts | 2 +- ...daemon-appimage-copy-host.electron.test.ts | 6 +- .../macos/macos-daemon-launchd.ts | 2 +- ...electron-to-node-adoption.electron.test.ts | 6 +- .../testing/daemon-launcher-driver-fixture.ts | 2 +- ...-pty-adapter-input-closed.node-pty.test.ts | 2 +- ...mon-pty-adapter-sleep-cwd.node-pty.test.ts | 2 +- ...pty-input-closed-delivery.node-pty.test.ts | 2 +- .../pty-subprocess-io-failure-native.test.ts | 103 ------ .../ssh/ssh-host-server-on-connect-wiring.ts | 4 +- .../wsl-host-handlers-user-actions.test.ts | 4 +- src/main/ipc/wsl/wsl-host-handlers.ts | 2 +- .../orcad-initial-activation-admission.ts | 2 +- .../activation/orcad-installed-activation.ts | 2 +- .../orcad-windows-host-state-ops.ts | 2 +- .../install/orcad-remote-context.ts | 2 +- .../install/orcad-remote-deploy.ts | 2 +- .../install/orcad-remote-launch-windows.ts | 2 +- .../orcad-remote-node-runtime-report.ts | 2 +- .../install/orcad-remote-windows-node.ts | 2 +- .../lifecycle/orcad-bash-stdio-bridge.test.ts | 2 +- .../lifecycle/orcad-managed-auto-update.ts | 4 +- .../lifecycle/orcad-managed-crash-loop.ts | 6 +- .../lifecycle/orcad-managed-remote-stop.ts | 3 +- .../orcad-managed-stale-lock-reclaim.ts | 2 +- .../lifecycle/orcad-runtime-deployment.ts | 2 +- .../orcad-runtime-maintenance.test.ts | 35 +- .../lifecycle/orcad-runtime-maintenance.ts | 2 +- .../lifecycle/orcad-runtime-target.ts | 2 +- .../lifecycle/orcad-stdio-bridge-provider.ts | 2 +- .../lifecycle/orcad-stdio-bridge.test.ts | 2 +- .../lifecycle/orcad-stdio-bridge.ts | 2 +- ...gration-catalog-client-source-kind.test.ts | 91 ----- .../orcad-migration-catalog-client.test.ts | 2 +- .../orcad-migration-cutover-fixture.ts | 2 +- .../orcad-migration-destination-fake.ts | 4 +- .../orcad-account-services.ts | 30 +- .../orcad-codex-account-homes.ts | 18 +- .../orcad-host-account-launch-env-store.ts | 6 +- .../orcad-wsl-host-claude-profile-refresh.ts | 10 +- .../orcad-artifact-cache-retention.test.ts | 2 +- .../orcad-artifact-cache-retention.ts | 9 +- .../orcad-artifact-identity.ts | 6 +- .../orcad-artifact-materializer.test.ts | 6 +- .../orcad-artifact-materializer.ts | 17 +- .../orcad-artifact-slot-name.ts | 0 .../orcad-artifact-source-verification.ts | 4 +- .../orcad-artifact-verification-record.ts | 0 .../orcad-daemon-slot-pins.ts | 11 +- .../orcad-template-manifest.ts | 0 .../external-chromium-browser-process.ts | 16 +- .../external-chromium-browser-session.test.ts | 11 +- .../external-chromium-browser-session.ts | 10 +- .../external-chromium-command-arguments.ts | 6 +- .../chromium}/external-chromium-page-input.ts | 8 +- .../external-chromium-profile-path.test.ts | 0 .../external-chromium-profile-path.ts | 0 .../external-chromium-tab-projection.ts | 0 .../external-chromium-tab-registry.ts | 6 +- .../electron-serve-browser-environment.ts | 0 .../electron-serve-browser-process.ts | 32 +- .../electron-sidecar-method-routing.ts | 0 .../electron}/electron-sidecar-profile.ts | 12 +- .../electron-sidecar-tab-registry.test.ts | 0 .../electron-sidecar-tab-registry.ts | 2 +- .../electron}/loopback-port-reservation.ts | 0 .../orcad-agent-browser-binary.ts | 4 +- .../orcad-browser-install-park.ts | 4 +- .../orcad-browser-provider.test.ts | 4 +- .../orcad-browser-provider.ts | 10 +- .../orcad-browser-startup.ts | 8 +- .../orcad-client-page-commands.ts | 20 +- .../orcad-sidecar-runtime-client.ts | 8 +- .../orcad-legacy-keyring-key.ts | 0 ...cad-plaintext-credential-migration.test.ts | 6 +- .../orcad-plaintext-credential-migration.ts | 32 +- .../orcad-secret-key-record.ts | 11 +- .../orcad-secret-key-resolution.ts | 4 +- .../orcad-secret-protection-gap.ts | 0 .../{ => credentials}/orcad-secret-sealing.ts | 0 .../orcad-secret-store-startup.ts | 6 +- .../orcad-secret-store.test.ts | 2 +- .../{ => credentials}/orcad-secret-store.ts | 2 +- .../{ => daemon}/orcad-daemon-retirement.ts | 10 +- .../orcad-daemon-supervision.test.ts | 8 +- .../{ => daemon}/orcad-daemon-supervision.ts | 13 +- .../orcad-idle-stop-daemon-recovery.ts | 4 +- .../orcad-event-loop-watchdog.ts | 2 +- .../orcad/{ => diagnostics}/orcad-health.ts | 20 +- .../orcad-host-unavailable.ts | 0 .../orcad-observability.test.ts | 35 +- .../{ => diagnostics}/orcad-observability.ts | 4 +- .../{ => diagnostics}/orcad-startup-timing.ts | 0 .../orcad-terminal-census.ts | 6 +- .../electron-serve-provider-selection.test.ts | 113 ------- .../orcad-idle-exit-monitor.test.ts | 28 -- .../idle-exit}/orcad-idle-exit-monitor.ts | 0 .../idle-exit}/orcad-idle-stop-record.ts | 8 +- .../orcad-managed-idle-exit-host.ts | 24 +- .../orcad-managed-idle-exit.test.ts | 0 .../idle-exit}/orcad-managed-idle-exit.ts | 10 +- .../orcad-completed-stop-receipt.ts | 8 +- .../orcad-managed-stop-admission.ts | 8 +- .../orcad-managed-stop-cancel-race.test.ts | 2 +- .../orcad-managed-stop-cancellation.test.ts | 8 +- .../orcad-managed-stop-cancellation.ts | 2 +- .../orcad-managed-stop-command.ts | 2 +- .../orcad-managed-stop-completion.ts | 8 +- .../orcad-managed-stop-decision.ts | 6 +- .../orcad-managed-stop-identity.test.ts | 6 +- .../orcad-managed-stop-request.ts | 9 +- .../managed-stop}/orcad-managed-stop.test.ts | 9 +- .../managed-stop}/orcad-stop-deadlines.ts | 0 .../orcad-stop-request-listener.ts | 4 +- ...-stop-request-shutdown.integration.test.ts | 13 +- .../orcad-stop-terminal-admission.ts | 0 .../orcad-fatal-stop-lock.test.ts | 4 +- .../orcad-lifecycle-host.test.ts | 4 +- .../{ => host-lifecycle}/orcad-lifecycle.ts | 43 +-- .../orcad-lock-yield.test.ts | 13 +- .../orcad-process-error-guards.ts | 4 +- .../orcad-unexpected-exit.test.ts | 2 +- .../orcad-unexpected-exit.ts | 4 +- .../orcad-app-paths.test.ts | 0 .../{ => host-runtime}/orcad-app-paths.ts | 2 +- .../{ => host-runtime}/orcad-automations.ts | 8 +- .../orcad-emulator-bridge.ts | 10 +- .../orcad/{ => host-runtime}/orcad-entry.ts | 104 +++--- .../{ => host-runtime}/orcad-host-adapters.ts | 14 +- .../orcad-managed-agent-hooks.ts | 26 +- .../orcad-paired-environment-options.ts | 6 +- .../orcad-restored-terminal-authority.ts | 10 +- .../orcad-session-scanner-idle.ts | 4 +- .../orcad-session-search.ts | 10 +- .../host-runtime/orcad-speech-services.ts | 19 ++ .../orcad/{ => host-runtime}/orcad-stats.ts | 8 +- .../orcad-wsl-host-login-environment.ts | 6 +- .../orcad-data-root-locality.ts | 0 .../orcad-data-root-privacy.ts | 2 +- .../orcad-instance-lock-hold.ts | 2 +- .../orcad-instance-lock-reclaim.ts | 4 +- .../orcad-instance-lock-record.ts | 0 .../orcad-instance-lock.test.ts | 5 +- .../orcad-instance-lock.ts | 20 +- .../orcad-lock-clone-machine.ts | 4 +- .../orcad-lock-holder-locality.ts | 4 +- .../orcad-process-start-time.test.ts | 6 +- .../orcad-process-start-time.ts | 6 +- .../orcad-stale-lock-reclaim.test.ts | 7 +- .../orcad-stale-lock-reclaim.ts | 23 +- .../orcad-wsl-holder-release.ts | 8 +- src/main/orcad/launcher.ts | 9 +- src/main/orcad/main.ts | 26 +- ...rcad-migration-destination-capabilities.ts | 4 +- .../orcad-migration-manifest-digest.ts | 2 +- .../orcad-migration-wsl-destination.ts | 10 +- .../build-toolchain-diagnosis.ts | 0 .../{ => native-runtime}/native-host-abi.ts | 0 .../node-pty-loader-diagnosis.ts | 2 +- .../node-pty-prebuilt-slot.test.ts | 0 .../node-pty-prebuilt-slot.ts | 4 +- .../node-pty-precondition.test.ts | 0 .../node-pty-precondition.ts | 4 +- .../orcad-bundle-native-load-order.test.ts | 2 +- .../orcad-native-preflight.ts | 6 +- ...rcad-packaged-node-pty.integration.test.ts | 11 +- .../orcad-runtime-native-preflight.ts | 12 +- .../orcad-structured-provider-smoke.ts | 2 +- ...ndows-conpty-breakaway.integration.test.ts | 6 +- .../orcad-agent-session-claim-signer.test.ts | 55 --- .../orcad/orcad-browser-install-park.test.ts | 140 -------- .../orcad/orcad-chat-restart-offer.test.ts | 83 ----- .../orcad/orcad-event-loop-watchdog.test.ts | 83 ----- .../orcad/orcad-forked-child-paths.test.ts | 46 --- .../orcad-local-serve-selection-entry.ts | 4 +- ...ad-managed-idle-exit-chat-provider.test.ts | 123 ------- src/main/orcad/orcad-runtime-lifetime.ts | 4 - src/main/orcad/orcad-speech-services.ts | 19 -- .../orcad-host-identity-reset.ts | 6 +- .../orcad-profile-state-startup.ts | 14 +- .../orcad-profile-state-telemetry.ts | 2 +- .../serve-profile-ssh-targets.ts | 10 +- .../orcad-bundled-runtime.ts | 8 +- .../orcad-compile-cache.ts | 2 +- ...cad-launcher-isolation.integration.test.ts | 24 +- .../orcad-profile-preflight.ts | 23 +- .../orcad-startup-qualification.test.ts | 13 +- .../orcad-startup-qualification.ts | 10 +- .../orcad-cli-launcher.integration.test.ts | 12 +- .../orcad-cli-launcher.test.ts | 4 +- .../{ => serve-startup}/orcad-cli-launcher.ts | 10 +- .../orcad-command-arguments.ts | 8 +- .../orcad-command-startup.ts | 17 +- .../orcad-configuration-exit.ts | 0 .../{ => serve-startup}/orcad-exit-code.ts | 12 +- .../orcad-help.integration.test.ts | 5 +- .../orcad-local-serve-selection.ts | 22 +- .../orcad-serve-readiness.ts | 8 +- .../orcad-serve-supervision.ts | 2 +- .../orcad-start-contract.ts | 4 +- .../orcad-ws-port-policy.ts | 2 +- .../orcad-daemon-session-client-fixture.ts | 0 .../orcad-daemon-teardown-fixture.ts | 20 +- .../native-slots}/orcad-node-slot-fixture.ts | 8 +- ...-serve-cleanup-diagnostics.test-fixture.ts | 26 +- ...ad-serve-cleanup-redaction.test-fixture.ts | 11 + .../orcad-serve-parity.integration.test.ts | 16 +- ...ckaged-structured-chat.integration.test.ts | 32 +- .../orcad-structured-chat-scenario.ts | 0 .../wsl-mover/wsl-move-cutover-fixture.ts | 2 +- .../orcad-migration-blob-installers.ts | 2 +- ...istence-orcad-migration-catalog-fixture.ts | 2 +- .../orcad-migration-manifest-export.ts | 2 +- .../source/catalog/orcad-source-export.ts | 2 +- .../wsl-move-cutover-journal.ts | 2 +- .../wsl-move-manifest-export.ts | 2 +- src/main/runtime/hosts/runtime-status.ts | 4 +- .../rpc/methods/orcad/orcad-migration.test.ts | 68 +--- .../rpc/methods/orcad/orcad-migration.ts | 4 +- .../orcad/orcad-terminal-census.test.ts | 4 +- .../methods/orcad/orcad-terminal-census.ts | 3 +- .../terminal/session-terminal-scrollback.ts | 2 +- .../projection/restored-pane-materialize.ts | 2 +- .../terminal-update-admission-census.test.ts | 84 ----- src/main/server/serve-readiness.ts | 2 +- .../ssh-host-server-connect-events.ts | 2 +- .../ssh-host-server-on-connect.test.ts | 45 +-- .../host-server/ssh-host-server-on-connect.ts | 2 +- .../ssh-host-server-setup-outcome.ts | 2 +- .../ssh-hostile-host-cells.ts | 2 +- .../ssh-hostile-host-managed-orcad.ts | 2 +- .../endpoints/ssh-relay-endpoint-incumbent.ts | 2 +- .../startup/main-process-ready-runtime.ts | 2 +- .../desktop-profile-instance-lock.ts | 6 +- ...rktree-create-preparation-stale-cleanup.ts | 2 +- .../wsl/discovery/wsl-distro-unsupported.ts | 2 +- .../execution/wsl-guest-process-identity.ts | 2 +- .../wsl-host-connect-failure.ts | 2 +- .../host-lifecycle/wsl-host-first-connect.ts | 2 +- .../__tests__/wsl-orcad-chat-scenario.ts | 2 +- .../__tests__/wsl-orcad-lane-host-fixture.ts | 2 +- .../__tests__/wsl-orcad-midturn-stop-lane.ts | 4 +- .../wsl-orcad-structured-chat-contract.ts | 2 +- .../orcad/wsl-orcad-connect-state-snapshot.ts | 2 +- .../orcad/wsl-orcad-deploy-app-update.test.ts | 46 +-- src/main/wsl/orcad/wsl-orcad-deploy.test.ts | 11 +- src/main/wsl/orcad/wsl-orcad-deploy.ts | 2 +- .../wsl/orcad/wsl-orcad-instance-adoption.ts | 6 +- .../wsl-orcad-update-move-hold-driver.test.ts | 2 +- .../daemon-generation-profile-store.ts | 2 +- .../helpers/headless-layout-oracle-hosts.ts | 2 +- tests/e2e/orcad-serve-mode-switch.spec.ts | 46 +-- .../orcad-serve-open-url-on-desktop.spec.ts | 2 +- .../e2e/paired-host-usage-credentials.spec.ts | 2 +- 281 files changed, 942 insertions(+), 2601 deletions(-) delete mode 100644 config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs delete mode 100644 src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts delete mode 100644 src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts delete mode 100644 src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts rename src/main/orcad/{ => account-launch}/orcad-account-services.ts (76%) rename src/main/orcad/{ => account-launch}/orcad-codex-account-homes.ts (62%) rename src/main/orcad/{ => account-launch}/orcad-host-account-launch-env-store.ts (89%) rename src/main/orcad/{ => account-launch}/orcad-wsl-host-claude-profile-refresh.ts (84%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-cache-retention.test.ts (98%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-cache-retention.ts (91%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-identity.ts (88%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-materializer.test.ts (99%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-materializer.ts (95%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-slot-name.ts (100%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-source-verification.ts (97%) rename src/main/orcad/{ => artifact-slots}/orcad-artifact-verification-record.ts (100%) rename src/main/orcad/{ => artifact-slots}/orcad-daemon-slot-pins.ts (87%) rename src/main/orcad/{ => artifact-slots}/orcad-template-manifest.ts (100%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-browser-process.ts (92%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-browser-session.test.ts (85%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-browser-session.ts (96%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-command-arguments.ts (96%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-page-input.ts (96%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-profile-path.test.ts (100%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-profile-path.ts (100%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-tab-projection.ts (100%) rename src/main/orcad/{ => browser-providers/chromium}/external-chromium-tab-registry.ts (97%) rename src/main/orcad/{ => browser-providers/electron}/electron-serve-browser-environment.ts (100%) rename src/main/orcad/{ => browser-providers/electron}/electron-serve-browser-process.ts (88%) rename src/main/orcad/{ => browser-providers/electron}/electron-sidecar-method-routing.ts (100%) rename src/main/orcad/{ => browser-providers/electron}/electron-sidecar-profile.ts (87%) rename src/main/orcad/{ => browser-providers/electron}/electron-sidecar-tab-registry.test.ts (100%) rename src/main/orcad/{ => browser-providers/electron}/electron-sidecar-tab-registry.ts (99%) rename src/main/orcad/{ => browser-providers/electron}/loopback-port-reservation.ts (100%) rename src/main/orcad/{ => browser-providers}/orcad-agent-browser-binary.ts (85%) rename src/main/orcad/{ => browser-providers}/orcad-browser-install-park.ts (98%) rename src/main/orcad/{ => browser-providers}/orcad-browser-provider.test.ts (96%) rename src/main/orcad/{ => browser-providers}/orcad-browser-provider.ts (95%) rename src/main/orcad/{ => browser-providers}/orcad-browser-startup.ts (90%) rename src/main/orcad/{ => browser-providers}/orcad-client-page-commands.ts (89%) rename src/main/orcad/{ => browser-providers}/orcad-sidecar-runtime-client.ts (92%) rename src/main/orcad/{ => credentials}/orcad-legacy-keyring-key.ts (100%) rename src/main/orcad/{ => credentials}/orcad-plaintext-credential-migration.test.ts (96%) rename src/main/orcad/{ => credentials}/orcad-plaintext-credential-migration.ts (79%) rename src/main/orcad/{ => credentials}/orcad-secret-key-record.ts (95%) rename src/main/orcad/{ => credentials}/orcad-secret-key-resolution.ts (97%) rename src/main/orcad/{ => credentials}/orcad-secret-protection-gap.ts (100%) rename src/main/orcad/{ => credentials}/orcad-secret-sealing.ts (100%) rename src/main/orcad/{ => credentials}/orcad-secret-store-startup.ts (68%) rename src/main/orcad/{ => credentials}/orcad-secret-store.test.ts (98%) rename src/main/orcad/{ => credentials}/orcad-secret-store.ts (96%) rename src/main/orcad/{ => daemon}/orcad-daemon-retirement.ts (87%) rename src/main/orcad/{ => daemon}/orcad-daemon-supervision.test.ts (79%) rename src/main/orcad/{ => daemon}/orcad-daemon-supervision.ts (85%) rename src/main/orcad/{ => daemon}/orcad-idle-stop-daemon-recovery.ts (91%) rename src/main/orcad/{ => diagnostics}/orcad-event-loop-watchdog.ts (98%) rename src/main/orcad/{ => diagnostics}/orcad-health.ts (86%) rename src/main/orcad/{ => diagnostics}/orcad-host-unavailable.ts (100%) rename src/main/orcad/{ => diagnostics}/orcad-observability.test.ts (62%) rename src/main/orcad/{ => diagnostics}/orcad-observability.ts (85%) rename src/main/orcad/{ => diagnostics}/orcad-startup-timing.ts (100%) rename src/main/orcad/{ => diagnostics}/orcad-terminal-census.ts (87%) delete mode 100644 src/main/orcad/electron-serve-provider-selection.test.ts rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-idle-exit-monitor.test.ts (80%) rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-idle-exit-monitor.ts (100%) rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-idle-stop-record.ts (84%) rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-managed-idle-exit-host.ts (88%) rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-managed-idle-exit.test.ts (100%) rename src/main/orcad/{ => host-lifecycle/idle-exit}/orcad-managed-idle-exit.ts (90%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-completed-stop-receipt.ts (91%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-admission.ts (80%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-cancel-race.test.ts (95%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-cancellation.test.ts (88%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-cancellation.ts (95%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-command.ts (98%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-completion.ts (95%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-decision.ts (88%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-identity.test.ts (96%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop-request.ts (90%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-managed-stop.test.ts (94%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-stop-deadlines.ts (100%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-stop-request-listener.ts (96%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-stop-request-shutdown.integration.test.ts (86%) rename src/main/orcad/{ => host-lifecycle/managed-stop}/orcad-stop-terminal-admission.ts (100%) rename src/main/orcad/{ => host-lifecycle}/orcad-fatal-stop-lock.test.ts (92%) rename src/main/orcad/{ => host-lifecycle}/orcad-lifecycle-host.test.ts (89%) rename src/main/orcad/{ => host-lifecycle}/orcad-lifecycle.ts (80%) rename src/main/orcad/{ => host-lifecycle}/orcad-lock-yield.test.ts (84%) rename src/main/orcad/{ => host-lifecycle}/orcad-process-error-guards.ts (94%) rename src/main/orcad/{ => host-lifecycle}/orcad-unexpected-exit.test.ts (98%) rename src/main/orcad/{ => host-lifecycle}/orcad-unexpected-exit.ts (89%) rename src/main/orcad/{ => host-runtime}/orcad-app-paths.test.ts (100%) rename src/main/orcad/{ => host-runtime}/orcad-app-paths.ts (97%) rename src/main/orcad/{ => host-runtime}/orcad-automations.ts (74%) rename src/main/orcad/{ => host-runtime}/orcad-emulator-bridge.ts (62%) rename src/main/orcad/{ => host-runtime}/orcad-entry.ts (77%) rename src/main/orcad/{ => host-runtime}/orcad-host-adapters.ts (80%) rename src/main/orcad/{ => host-runtime}/orcad-managed-agent-hooks.ts (65%) rename src/main/orcad/{ => host-runtime}/orcad-paired-environment-options.ts (75%) rename src/main/orcad/{ => host-runtime}/orcad-restored-terminal-authority.ts (62%) rename src/main/orcad/{ => host-runtime}/orcad-session-scanner-idle.ts (82%) rename src/main/orcad/{ => host-runtime}/orcad-session-search.ts (63%) create mode 100644 src/main/orcad/host-runtime/orcad-speech-services.ts rename src/main/orcad/{ => host-runtime}/orcad-stats.ts (63%) rename src/main/orcad/{ => host-runtime}/orcad-wsl-host-login-environment.ts (90%) rename src/main/orcad/{ => instance-lock}/orcad-data-root-locality.ts (100%) rename src/main/orcad/{ => instance-lock}/orcad-data-root-privacy.ts (96%) rename src/main/orcad/{ => instance-lock}/orcad-instance-lock-hold.ts (98%) rename src/main/orcad/{ => instance-lock}/orcad-instance-lock-reclaim.ts (97%) rename src/main/orcad/{ => instance-lock}/orcad-instance-lock-record.ts (100%) rename src/main/orcad/{ => instance-lock}/orcad-instance-lock.test.ts (99%) rename src/main/orcad/{ => instance-lock}/orcad-instance-lock.ts (94%) rename src/main/orcad/{ => instance-lock}/orcad-lock-clone-machine.ts (94%) rename src/main/orcad/{ => instance-lock}/orcad-lock-holder-locality.ts (94%) rename src/main/orcad/{ => instance-lock}/orcad-process-start-time.test.ts (94%) rename src/main/orcad/{ => instance-lock}/orcad-process-start-time.ts (94%) rename src/main/orcad/{ => instance-lock}/orcad-stale-lock-reclaim.test.ts (97%) rename src/main/orcad/{ => instance-lock}/orcad-stale-lock-reclaim.ts (93%) rename src/main/orcad/{ => instance-lock}/orcad-wsl-holder-release.ts (82%) rename src/main/orcad/{ => migration}/orcad-migration-destination-capabilities.ts (85%) rename src/main/orcad/{ => migration}/orcad-migration-manifest-digest.ts (94%) rename src/main/orcad/{ => migration}/orcad-migration-wsl-destination.ts (81%) rename src/main/orcad/{ => native-runtime}/build-toolchain-diagnosis.ts (100%) rename src/main/orcad/{ => native-runtime}/native-host-abi.ts (100%) rename src/main/orcad/{ => native-runtime}/node-pty-loader-diagnosis.ts (95%) rename src/main/orcad/{ => native-runtime}/node-pty-prebuilt-slot.test.ts (100%) rename src/main/orcad/{ => native-runtime}/node-pty-prebuilt-slot.ts (98%) rename src/main/orcad/{ => native-runtime}/node-pty-precondition.test.ts (100%) rename src/main/orcad/{ => native-runtime}/node-pty-precondition.ts (98%) rename src/main/orcad/{ => native-runtime}/orcad-bundle-native-load-order.test.ts (97%) rename src/main/orcad/{ => native-runtime}/orcad-native-preflight.ts (90%) rename src/main/orcad/{ => native-runtime}/orcad-packaged-node-pty.integration.test.ts (93%) rename src/main/orcad/{ => native-runtime}/orcad-runtime-native-preflight.ts (88%) rename src/main/orcad/{ => native-runtime}/orcad-structured-provider-smoke.ts (84%) rename src/main/orcad/{ => native-runtime}/orcad-windows-conpty-breakaway.integration.test.ts (95%) delete mode 100644 src/main/orcad/orcad-agent-session-claim-signer.test.ts delete mode 100644 src/main/orcad/orcad-browser-install-park.test.ts delete mode 100644 src/main/orcad/orcad-chat-restart-offer.test.ts delete mode 100644 src/main/orcad/orcad-event-loop-watchdog.test.ts delete mode 100644 src/main/orcad/orcad-forked-child-paths.test.ts delete mode 100644 src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts delete mode 100644 src/main/orcad/orcad-runtime-lifetime.ts delete mode 100644 src/main/orcad/orcad-speech-services.ts rename src/main/orcad/{ => profile-state}/orcad-host-identity-reset.ts (90%) rename src/main/orcad/{ => profile-state}/orcad-profile-state-startup.ts (75%) rename src/main/orcad/{ => profile-state}/orcad-profile-state-telemetry.ts (89%) rename src/main/orcad/{ => profile-state}/serve-profile-ssh-targets.ts (72%) rename src/main/orcad/{ => runtime-launch}/orcad-bundled-runtime.ts (94%) rename src/main/orcad/{ => runtime-launch}/orcad-compile-cache.ts (93%) rename src/main/orcad/{ => runtime-launch}/orcad-launcher-isolation.integration.test.ts (88%) rename src/main/orcad/{ => runtime-launch}/orcad-profile-preflight.ts (88%) rename src/main/orcad/{ => runtime-launch}/orcad-startup-qualification.test.ts (63%) rename src/main/orcad/{ => runtime-launch}/orcad-startup-qualification.ts (90%) rename src/main/orcad/{ => serve-startup}/orcad-cli-launcher.integration.test.ts (89%) rename src/main/orcad/{ => serve-startup}/orcad-cli-launcher.test.ts (96%) rename src/main/orcad/{ => serve-startup}/orcad-cli-launcher.ts (90%) rename src/main/orcad/{ => serve-startup}/orcad-command-arguments.ts (94%) rename src/main/orcad/{ => serve-startup}/orcad-command-startup.ts (60%) rename src/main/orcad/{ => serve-startup}/orcad-configuration-exit.ts (100%) rename src/main/orcad/{ => serve-startup}/orcad-exit-code.ts (65%) rename src/main/orcad/{ => serve-startup}/orcad-help.integration.test.ts (94%) rename src/main/orcad/{ => serve-startup}/orcad-local-serve-selection.ts (87%) rename src/main/orcad/{ => serve-startup}/orcad-serve-readiness.ts (70%) rename src/main/orcad/{ => serve-startup}/orcad-serve-supervision.ts (90%) rename src/main/orcad/{ => serve-startup}/orcad-start-contract.ts (84%) rename src/main/orcad/{ => serve-startup}/orcad-ws-port-policy.ts (85%) rename src/main/orcad/{ => testing/daemon-processes}/orcad-daemon-session-client-fixture.ts (100%) rename src/main/orcad/{ => testing/daemon-processes}/orcad-daemon-teardown-fixture.ts (91%) rename src/main/orcad/{ => testing/native-slots}/orcad-node-slot-fixture.ts (95%) rename src/main/orcad/{ => testing/serve-lifecycle}/orcad-serve-cleanup-diagnostics.test-fixture.ts (91%) create mode 100644 src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts rename src/main/orcad/{ => testing/serve-lifecycle}/orcad-serve-parity.integration.test.ts (93%) rename src/main/orcad/{ => testing/structured-chat}/orcad-packaged-structured-chat.integration.test.ts (88%) rename src/main/orcad/{ => testing/structured-chat}/orcad-structured-chat-scenario.ts (100%) delete mode 100644 src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts diff --git a/.github/workflows/node-server-tests.yml b/.github/workflows/node-server-tests.yml index 18334d1e587..bf9d65525a1 100644 --- a/.github/workflows/node-server-tests.yml +++ b/.github/workflows/node-server-tests.yml @@ -247,7 +247,7 @@ jobs: run: node "$(if [ -f config/scripts/orcad-distribution/template/build-orcad-template.mjs ]; then printf %s config/scripts/orcad-distribution/template/build-orcad-template.mjs; else printf %s config/scripts/build-orcad-template.mjs; fi)" --targets linux-${{ runner.arch == 'ARM64' && 'arm64' || 'x64' }}-glibc - name: Verify a structured chat from the desktop server template if: runner.os == 'Linux' - run: pnpm test:node-server --artifact src/main/orcad/orcad-packaged-structured-chat.integration.test.ts --maxWorkers=2 + run: pnpm test:node-server --artifact src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts --maxWorkers=2 # Only a Windows runner compiles it; arm64 cross-compiles here. # Before the Node 18 check below: the build script imports TypeScript, which Node 18 cannot load. # orcad's instance lock and stop proof read a PID's creation time through it; the x64 binary this diff --git a/.github/workflows/ssh-hostile-hosts.yml b/.github/workflows/ssh-hostile-hosts.yml index 00c23a1b9de..fa45eff64b3 100644 --- a/.github/workflows/ssh-hostile-hosts.yml +++ b/.github/workflows/ssh-hostile-hosts.yml @@ -15,8 +15,8 @@ on: - 'src/main/managed-server/**' - 'src/main/ssh/migration-source/**' - 'src/main/persistence/migrating-orcad-catalog/**' - - 'src/main/orcad/orcad-artifact-materializer.ts' - - 'src/main/orcad/orcad-host-unavailable.ts' + - 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' + - 'src/main/orcad/diagnostics/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - 'src/main/ssh/remote-exec/**' - 'src/main/ssh/remote-host/**' diff --git a/.github/workflows/ssh-windows-hosts.yml b/.github/workflows/ssh-windows-hosts.yml index 9f7a2496700..f2a0ca584dd 100644 --- a/.github/workflows/ssh-windows-hosts.yml +++ b/.github/workflows/ssh-windows-hosts.yml @@ -12,8 +12,8 @@ on: - 'src/main/managed-server/**' - 'src/main/ssh/migration-source/**' - 'src/main/persistence/migrating-orcad-catalog/**' - - 'src/main/orcad/orcad-artifact-materializer.ts' - - 'src/main/orcad/orcad-host-unavailable.ts' + - 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' + - 'src/main/orcad/diagnostics/orcad-host-unavailable.ts' - 'src/main/node-runtime/**' - 'src/main/ssh/remote-exec/**' - 'src/main/ssh/remote-host/**' @@ -38,7 +38,7 @@ on: - 'config/scripts/native-build/windows/build-windows-cli-launcher.mjs' - 'config/scripts/native-build/windows/windows-rust-executable-build.mjs' - 'native/windows-cli-launcher/**' - - 'src/main/orcad/orcad-cli-launcher.ts' + - 'src/main/orcad/serve-startup/orcad-cli-launcher.ts' - '.github/actions/prepare-windows-cli-launcher/**' - 'config/patches/node-pty*' - 'config/patches/@vscode__windows-process-tree*' diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index 4285cbae0d9..791768ff519 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -9,8 +9,8 @@ export const CLI_MAIN_ENTRY_NAMES = [ 'skills/bundled-skill-install/bundled-skill-local-host', 'skills/bundled-skill-install/bundled-skill-installation', 'filesystem/macos-tree-clone', - 'orcad/orcad-stale-lock-reclaim', - 'orcad/orcad-host-identity-reset', + 'orcad/instance-lock/orcad-stale-lock-reclaim', + 'orcad/profile-state/orcad-host-identity-reset', 'plugins/plugin-artifact-validation', 'plugins/plugin-content-hash', 'plugins/plugin-catalog-release-entry', diff --git a/config/daemon-blocking-call-baseline.txt b/config/daemon-blocking-call-baseline.txt index 66d82518654..bdd5065bf0b 100644 --- a/config/daemon-blocking-call-baseline.txt +++ b/config/daemon-blocking-call-baseline.txt @@ -8,7 +8,7 @@ 2 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts 1 src/main/daemon/process-scopes/daemon-user-manager-lifetime.ts 1 src/main/daemon/process-scopes/terminal-scopes.ts -2 src/main/orcad/node-pty-precondition.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts 1 src/main/pty/process-retirement/posix-pty-process-table.ts 1 src/main/pty/shell-startup/pwsh.ts 2 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 1c5b06c5ed3..c174dfc36da 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -368,8 +368,8 @@ module.exports = { 'out/main/computer-sidecar.js', 'out/main/parcel-watcher-process-entry.js', 'out/main/orcad/orcad-local-serve-selection-entry.js', - 'out/main/orcad/orcad-stale-lock-reclaim.js', - 'out/main/orcad/orcad-host-identity-reset.js', + 'out/main/orcad/instance-lock/orcad-stale-lock-reclaim.js', + 'out/main/orcad/profile-state/orcad-host-identity-reset.js', 'out/main/chunks/**', 'out/renderer/**', 'out/mobile-web/**', diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 9280abe04c4..c52479b5387 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -13,7 +13,6 @@ 1 test-no-in-test-import-actual:src/main/linear/issues/linear-description-images.test.ts 1 test-no-in-test-import-actual:src/main/managed-server/host-state/orcad-snapshot-room.test.ts 1 test-no-in-test-import-actual:src/main/omp/omp-session-cwd-lookup.test.ts -1 test-no-in-test-import-actual:src/main/orcad/electron-serve-provider-selection.test.ts 1 test-no-in-test-import-actual:src/main/pty/scrollback/overlay-mirror.test.ts 1 test-no-in-test-import-actual:src/main/runtime/rpc/server/pairing/mobile-pairing-userdata-path.test.ts 1 test-no-in-test-import-actual:src/main/runtime/terminal/artifacts/orca-runtime-files-terminal-artifact-swap-detection.test.ts @@ -452,11 +451,11 @@ 1 test-no-wall-clock:src/main/opencode/status-hooks/overlay-dir-gc.test.ts 2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts 2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts -2 test-no-wall-clock:src/main/orcad/orcad-artifact-cache-retention.test.ts -1 test-no-wall-clock:src/main/orcad/orcad-artifact-materializer.test.ts -6 test-no-wall-clock:src/main/orcad/orcad-serve-parity.integration.test.ts -1 test-no-wall-clock:src/main/orcad/orcad-stale-lock-reclaim.test.ts -3 test-no-wall-clock:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts +2 test-no-wall-clock:src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts +1 test-no-wall-clock:src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts +6 test-no-wall-clock:src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts +1 test-no-wall-clock:src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts +3 test-no-wall-clock:src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts 1 test-no-wall-clock:src/main/persistence/closed-terminal-tab-write-fence.test.ts 1 test-no-wall-clock:src/main/persistence/profile-state/backup/profile-state-backup-rotation.test.ts 1 test-no-wall-clock:src/main/persistence/profile-state/recovery/profile-state-section-repair.test.ts @@ -604,12 +603,12 @@ 4 test-timeout-needs-reason:src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts 3 test-timeout-needs-reason:src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts 1 test-timeout-needs-reason:src/main/notebook/notebook-kernel.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-bundle-native-load-order.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-packaged-node-pty.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-packaged-structured-chat.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-serve-parity.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts -1 test-timeout-needs-reason:src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts +1 test-timeout-needs-reason:src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts 1 test-timeout-needs-reason:src/main/persistence/applying-settings/persistence-source-control-ai-migration.test.ts 2 test-timeout-needs-reason:src/main/providers/agent-foreground-process-git-bash.win32.test.ts 1 test-timeout-needs-reason:src/main/providers/local-pty/local-pty-child-process-verdict.test.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index baf5e8317ec..fb2c4649dd9 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -342,39 +342,39 @@ 2 src/main/orca-profiles/storage/new-profile-state.ts 5 src/main/orca-profiles/storage/profile-legacy-state-import.ts 2 src/main/orcad/launcher.ts -7 src/main/orcad/node-pty-prebuilt-slot.ts -2 src/main/orcad/node-pty-precondition.ts -2 src/main/orcad/orcad-agent-browser-binary.ts -1 src/main/orcad/orcad-app-paths.ts -1 src/main/orcad/orcad-artifact-identity.ts -2 src/main/orcad/orcad-artifact-materializer.ts -12 src/main/orcad/orcad-bundled-runtime.ts -2 src/main/orcad/orcad-cli-launcher.ts -1 src/main/orcad/orcad-command-arguments.ts -1 src/main/orcad/orcad-completed-stop-receipt.ts -2 src/main/orcad/orcad-daemon-slot-pins.ts -2 src/main/orcad/orcad-data-root-locality.ts -3 src/main/orcad/orcad-data-root-privacy.ts -4 src/main/orcad/orcad-host-account-launch-env-store.ts -1 src/main/orcad/orcad-host-adapters.ts -1 src/main/orcad/orcad-host-identity-reset.ts -2 src/main/orcad/orcad-idle-stop-record.ts -3 src/main/orcad/orcad-instance-lock-hold.ts -16 src/main/orcad/orcad-instance-lock-reclaim.ts -4 src/main/orcad/orcad-instance-lock.ts -7 src/main/orcad/orcad-local-serve-selection.ts -1 src/main/orcad/orcad-lock-clone-machine.ts -1 src/main/orcad/orcad-managed-stop-cancellation.ts -3 src/main/orcad/orcad-managed-stop-decision.ts -2 src/main/orcad/orcad-managed-stop-request.ts -4 src/main/orcad/orcad-plaintext-credential-migration.ts -5 src/main/orcad/orcad-process-start-time.ts -11 src/main/orcad/orcad-secret-key-record.ts -3 src/main/orcad/orcad-stale-lock-reclaim.ts -1 src/main/orcad/orcad-stop-request-listener.ts -1 src/main/orcad/orcad-wsl-holder-release.ts -2 src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts -1 src/main/orcad/serve-profile-ssh-targets.ts +7 src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts +2 src/main/orcad/browser-providers/orcad-agent-browser-binary.ts +1 src/main/orcad/host-runtime/orcad-app-paths.ts +1 src/main/orcad/artifact-slots/orcad-artifact-identity.ts +2 src/main/orcad/artifact-slots/orcad-artifact-materializer.ts +12 src/main/orcad/runtime-launch/orcad-bundled-runtime.ts +2 src/main/orcad/serve-startup/orcad-cli-launcher.ts +1 src/main/orcad/serve-startup/orcad-command-arguments.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts +2 src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts +2 src/main/orcad/instance-lock/orcad-data-root-locality.ts +3 src/main/orcad/instance-lock/orcad-data-root-privacy.ts +4 src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts +1 src/main/orcad/host-runtime/orcad-host-adapters.ts +1 src/main/orcad/profile-state/orcad-host-identity-reset.ts +2 src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts +3 src/main/orcad/instance-lock/orcad-instance-lock-hold.ts +16 src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts +4 src/main/orcad/instance-lock/orcad-instance-lock.ts +7 src/main/orcad/serve-startup/orcad-local-serve-selection.ts +1 src/main/orcad/instance-lock/orcad-lock-clone-machine.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts +3 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts +2 src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts +4 src/main/orcad/credentials/orcad-plaintext-credential-migration.ts +5 src/main/orcad/instance-lock/orcad-process-start-time.ts +11 src/main/orcad/credentials/orcad-secret-key-record.ts +3 src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts +1 src/main/orcad/instance-lock/orcad-wsl-holder-release.ts +2 src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts +1 src/main/orcad/profile-state/serve-profile-ssh-targets.ts 6 src/main/persistence/atomic-snapshot-writer.ts 5 src/main/persistence/loading-store/user-data-path.ts 4 src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index 94bb779f5fe..34df7fd2668 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -27,8 +27,8 @@ 1 src/main/ipc/worktree-logic.ts 1 src/main/network/macos-tailscale-dns-diagnostic.ts 1 src/main/opencode/status-hooks/legacy-plugin-acl-retry.ts -2 src/main/orcad/node-pty-precondition.ts -1 src/main/orcad/orcad-data-root-privacy.ts +2 src/main/orcad/native-runtime/node-pty-precondition.ts +1 src/main/orcad/instance-lock/orcad-data-root-privacy.ts 2 src/main/persistence/profile-state/access/profile-state-access-identity.ts 1 src/main/persistence/profile-state/recovery/profile-state-recovery-copy.ts 1 src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt index f6061f98094..b7c69278284 100644 --- a/config/recurring-timer-baseline.txt +++ b/config/recurring-timer-baseline.txt @@ -38,10 +38,10 @@ 1 src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts 1 src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts 1 src/main/notifications/desktop-presence-reporter.ts -1 src/main/orcad/orcad-browser-install-park.ts -1 src/main/orcad/orcad-event-loop-watchdog.ts -1 src/main/orcad/orcad-lock-clone-machine.ts -1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/orcad/browser-providers/orcad-browser-install-park.ts +1 src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts +1 src/main/orcad/instance-lock/orcad-lock-clone-machine.ts +1 src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts 1 src/main/plugins/catalog/plugin-auto-updater.ts 1 src/main/plugins/catalog/plugin-kill-list-service.ts 1 src/main/plugins/installation/plugin-git-repository.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 1ee9c681616..ff55eff77a0 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2182,21 +2182,19 @@ "providers": ["local-daemon", "ssh-daemon", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local-daemon"], - "coverageNotes": "Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real TerminalHost, Session, and subprocess wrapper with injected native I/O failures and mocked OS signals. Local non-daemon and SSH-relay implementations are unaffected; daemon consumers on SSH, WSL, paired runtimes, and mobile retain host-owned semantics. Live Linux/Windows/WSL and remote runs remain gaps. No git or folder-workspace assumptions. The fault-injection suite also runs with simulated darwin/linux/win32 platform branches; these do not constitute native OS coverage. Native macOS coverage now proves shell exit and PTY master-fd closure, input/output round trips, and teardown of a paused producer for both graceful and immediate cleanup. Windows single-close/job escalation and pre-listener output/status are fault-injected contracts. Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", + "coverageNotes": "Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real TerminalHost, Session, and subprocess wrapper with injected native I/O failures and mocked OS signals. Local non-daemon and SSH-relay implementations are unaffected; daemon consumers on SSH, WSL, paired runtimes, and mobile retain host-owned semantics. Live Linux/Windows/WSL and remote runs remain gaps. No git or folder-workspace assumptions. The fault-injection suite also runs with simulated darwin/linux/win32 platform branches; these do not constitute native OS coverage. Archived native macOS results previously exercised shell exit and PTY master-fd closure, input/output round trips, and teardown of a paused producer; that suite is now retired without replacement. Windows single-close/job escalation and pre-listener output/status are fault-injected contracts. Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.\nOrcad folder cleanup intentionally retires the Cartesian native failed-I/O test under repository test policy, without equivalent replacement. Remaining selectors retain their narrower scope. Dated evidenceRuns remain historical and do not validate this changed selector.", "motivatingLinks": ["docs/terminal-daemon-session-leak-investigation.md"], "invariant": "I/O errors must not establish physical exit or disable termination of an owned PTY. Session and native handle disposal require the exit event.", - "oracle": "Inject write and resize failures, require graceful and forced signals to reach the native owner, keep producer resume available, suppress repeated failed I/O, deliver output and exit, and suppress signals after exit. Across 32 create/close cycles per failure, retain each session before exit and release its native handle and emulator exactly once afterwards. Mark physical exit before notifying listeners; reentrant kill/forceKill/signal from those listeners must never signal the retired PID. A native POSIX test performs input/output and resize, pauses the producer, injects each I/O failure, then gracefully or immediately closes 16 real shells; require ESRCH for each child PID and EBADF for each PTY master fd.", + "oracle": "Inject write and resize failures, require graceful and forced signals to reach the native owner, keep producer resume available, suppress repeated failed I/O, deliver output and exit, and suppress signals after exit. Across 32 create/close cycles per failure, retain each session before exit and release its native handle and emulator exactly once afterwards. Mark physical exit before notifying listeners; reentrant kill/forceKill/signal from those listeners must never signal the retired PID. The former native POSIX shell/PID/fd oracle is retired without replacement.", "commands": [ "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts", - "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts", - "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" + "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts" ], "testFiles": [ "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts", "src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts", "src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts", - "src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts", - "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" + "src/main/daemon/terminal-host/testing/terminal-session-teardown.test.ts" ], "assertionRefs": [ { @@ -2207,10 +2205,6 @@ "suppresses repeated native I/O failures while still delivering output and exit", "blocks reentrant termination from an exit listener after I/O failure" ] - }, - { - "file": "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts", - "assertions": ["reaps real shells and master fds after %s failure (immediate=%s)"] } ], "evidenceRuns": [ @@ -2223,16 +2217,6 @@ "durationSeconds": 3.71, "summary": "32 tests passed with 4 Windows-only cases skipped; simulated macOS/Linux/Windows branches include 192 failed-I/O create/close cycles and exit-listener reentrancy.", "currentCommand": "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts" - }, - { - "date": "2026-09-07", - "runner": "local", - "platform": "macos", - "command": "pnpm test src/main/daemon/pty-subprocess-io-failure-native.test.ts", - "result": "passed", - "durationSeconds": 2.52, - "summary": "Four native cases pass across 16 real shells, including input/output, pause before teardown, confirmed PID absence, and closed PTY master fds.", - "currentCommand": "pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts" } ], "runtimeBudget": { @@ -2257,10 +2241,11 @@ "knownGaps": [ "Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "Fault injection proves a leak mechanism, not causality for the historical 427-session incident.", - "Real Linux/Windows/WSL, remote, startup-close, login-wrapper descendants, and multi-day load evidence remain outstanding. Native tests inject synchronous I/O errors; they do not model every asynchronous node-pty pipe failure.", + "Real Linux/Windows/WSL, remote, startup-close, login-wrapper descendants, and multi-day load evidence remain outstanding. The archived native tests injected synchronous I/O errors; they did not model every asynchronous node-pty pipe failure. No active native-shell coverage remains after their retirement.", "No output throughput change or interactive latency benchmark is included.", "Audit1302: src/main/daemon/terminal-host-teardown-recreate.test.ts: Fake subprocess handles synthesize exits via real40ms/30s timers or manual exit callback, with descendant retirement mocked away; assertions inspect isNew/refusal/spawn counts. No real subprocess/PTY teardown/recreation or owned-tree retention boundary. Lose artificial teardown/attach/shutdown/cancellation scheduling alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", - "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host-teardown-recreate.test.ts src/main/daemon/terminal-session-teardown.test.ts src/main/daemon/session.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.617,\n \"summary\": \"136 tests passed across six files; failed-I/O cycle tests cover 64 closures.\"\n }" + "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-cleanup.test.ts src/main/daemon/pty-subprocess-handle-lifecycle.test.ts src/main/daemon/terminal-host-session-reaping-leak.test.ts src/main/daemon/terminal-host-teardown-recreate.test.ts src/main/daemon/terminal-session-teardown.test.ts src/main/daemon/session.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.617,\n \"summary\": \"136 tests passed across six files; failed-I/O cycle tests cover 64 closures.\"\n }", + "Orcad owner layout retires this native test receipt without replacement. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm test src/main/daemon/pty-subprocess-io-failure-native.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 2.52,\n \"summary\": \"Four native cases pass across 16 real shells, including input/output, pause before teardown, confirmed PID absence, and closed PTY master fds.\",\n \"currentCommand\": \"pnpm test src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts\"\n }" ], "demotionRule": "Keep experimental; investigate any lost cleanup signal, premature exit, or unexplained flake." }, diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index ae84f5be7f6..8dc28274407 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -180,7 +180,6 @@ "config/scripts/desktop-distribution/linux/package-linux-formats-appimage.test.mjs": 624, "config/scripts/desktop-distribution/linux/package-linux-formats.test.mjs": 282, "config/scripts/desktop-distribution/runtime-verification/packaged-node-pty-prebuild-prune.test.mjs": 74, - "config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs": 407, "config/scripts/desktop-distribution/runtime-verification/packaged-process-host.test.mjs": 537, "config/scripts/desktop-distribution/runtime-verification/packaged-repository-input-exclusion.test.mjs": 222, "config/scripts/desktop-distribution/runtime-verification/packaged-source-map-prune.test.mjs": 73, @@ -1553,7 +1552,6 @@ "src/main/daemon/pty-subprocess/testing/pty-subprocess-foreground-identity.test.ts": 818, "src/main/daemon/pty-subprocess/testing/pty-subprocess-handle-lifecycle.test.ts": 449, "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-cleanup.test.ts": 1127, - "src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts": 3285, "src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts": 528, "src/main/daemon/pty-subprocess/testing/pty-subprocess-windows-shell-launch.test.ts": 459, "src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts": 431, @@ -2460,46 +2458,40 @@ "src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts": 1642, "src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts": 1456, "src/main/orca-profiles/profile-telemetry-consent-seed.test.ts": 536, - "src/main/orcad/electron-serve-provider-selection.test.ts": 554, - "src/main/orcad/electron-sidecar-tab-registry.test.ts": 105, - "src/main/orcad/external-chromium-browser-session.test.ts": 152, - "src/main/orcad/node-pty-prebuilt-slot.test.ts": 185, - "src/main/orcad/node-pty-precondition.test.ts": 477, - "src/main/orcad/orcad-agent-session-claim-signer.test.ts": 64, - "src/main/orcad/orcad-app-paths.test.ts": 45, - "src/main/orcad/orcad-artifact-cache-retention.test.ts": 301, - "src/main/orcad/orcad-artifact-materializer.test.ts": 1129, + "src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts": 105, + "src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts": 152, + "src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts": 185, + "src/main/orcad/native-runtime/node-pty-precondition.test.ts": 477, + "src/main/orcad/host-runtime/orcad-app-paths.test.ts": 45, + "src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts": 301, + "src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts": 1129, "src/main/orcad/orcad-bind-address.test.ts": 41, - "src/main/orcad/orcad-browser-install-park.test.ts": 131, - "src/main/orcad/orcad-browser-provider.test.ts": 479, - "src/main/orcad/orcad-bundle-native-load-order.test.ts": 3555, - "src/main/orcad/orcad-chat-restart-offer.test.ts": 3691, - "src/main/orcad/orcad-cli-launcher.integration.test.ts": 390, - "src/main/orcad/orcad-cli-launcher.test.ts": 232, + "src/main/orcad/browser-providers/orcad-browser-provider.test.ts": 479, + "src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts": 3555, + "src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts": 390, + "src/main/orcad/serve-startup/orcad-cli-launcher.test.ts": 232, "src/main/orcad/orcad-cli-orchestration.integration.test.ts": 214, - "src/main/orcad/orcad-forked-child-paths.test.ts": 337, - "src/main/orcad/orcad-help.integration.test.ts": 5016, - "src/main/orcad/orcad-idle-exit-monitor.test.ts": 106, - "src/main/orcad/orcad-instance-lock.test.ts": 315, - "src/main/orcad/orcad-launcher-isolation.integration.test.ts": 617, - "src/main/orcad/orcad-lifecycle-host.test.ts": 407, - "src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts": 2062, - "src/main/orcad/orcad-managed-idle-exit.test.ts": 180, - "src/main/orcad/orcad-managed-stop-cancel-race.test.ts": 218, - "src/main/orcad/orcad-managed-stop-cancellation.test.ts": 285, - "src/main/orcad/orcad-managed-stop-identity.test.ts": 270, - "src/main/orcad/orcad-managed-stop.test.ts": 1726, - "src/main/orcad/orcad-observability.test.ts": 187, - "src/main/orcad/orcad-packaged-node-pty.integration.test.ts": 78, - "src/main/orcad/orcad-packaged-structured-chat.integration.test.ts": 448, - "src/main/orcad/orcad-plaintext-credential-migration.test.ts": 223, - "src/main/orcad/orcad-process-start-time.test.ts": 77, - "src/main/orcad/orcad-secret-store.test.ts": 2281, - "src/main/orcad/orcad-serve-parity.integration.test.ts": 280, - "src/main/orcad/orcad-stale-lock-reclaim.test.ts": 258, - "src/main/orcad/orcad-startup-qualification.test.ts": 102, - "src/main/orcad/orcad-stop-request-shutdown.integration.test.ts": 293, - "src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts": 79, + "src/main/orcad/serve-startup/orcad-help.integration.test.ts": 5016, + "src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts": 106, + "src/main/orcad/instance-lock/orcad-instance-lock.test.ts": 315, + "src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts": 617, + "src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts": 407, + "src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts": 180, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts": 218, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts": 285, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts": 270, + "src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts": 1726, + "src/main/orcad/diagnostics/orcad-observability.test.ts": 187, + "src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts": 78, + "src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts": 448, + "src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts": 223, + "src/main/orcad/instance-lock/orcad-process-start-time.test.ts": 77, + "src/main/orcad/credentials/orcad-secret-store.test.ts": 2281, + "src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts": 280, + "src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts": 258, + "src/main/orcad/runtime-launch/orcad-startup-qualification.test.ts": 102, + "src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts": 293, + "src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts": 79, "src/main/persistence/preferences/persistence-onboarding-language-cohort.test.ts": 1760, "src/main/persistence/applying-settings/persistence-automation-extra-agent-args.test.ts": 2268, "src/main/persistence/applying-settings/persistence-automation-mode-precondition.test.ts": 1595, @@ -3640,7 +3632,6 @@ "src/main/runtime/terminal/output/tail/terminal-tail-redraw-spans.test.ts": 166, "src/main/runtime/terminal-tail-redraw-wall-time.test.ts": 43418, "src/main/runtime/terminal/output/tail/terminal-tail-sentinel-index.test.ts": 3649, - "src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts": 4182, "src/main/runtime/terminal/output/terminal-vertical-control-scan.test.ts": 168, "src/main/runtime/terminal/wait/terminal-wait-detection.test.ts": 220, "src/main/runtime/terminal/wait/terminal-wait-name-only-idle.test.ts": 5018, @@ -3796,7 +3787,6 @@ "src/main/managed-server/install/orcad-launch-ssh-session.test.ts": 689, "src/main/managed-server/migration/transfers/orcad-migration-blob-coordinator.test.ts": 1464, "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-frame-budget.test.ts": 405, - "src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts": 400, "src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts": 400, "src/main/managed-server/migration/cutover/orcad-migration-cutover-coordinator.test.ts": 2408, "src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts": 3812, diff --git a/config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.mjs b/config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.mjs index 24bb8a96093..096afb70520 100644 --- a/config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.mjs +++ b/config/scripts/daemon-protocol/admission/check-runtime-launcher-protocol-ratchet.mjs @@ -13,7 +13,7 @@ import { /** Files that decide which runtime executable launches orcad or the terminal daemon. */ export const RUNTIME_LAUNCHER_PATHS = [ // orcad handoff to its bundled runtime, and the pinned runtimes it can hand off to. - 'src/main/orcad/orcad-bundled-runtime.ts', + 'src/main/orcad/runtime-launch/orcad-bundled-runtime.ts', 'src/main/orcad/launcher.ts', 'config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs', 'src/shared/node-runtime-pin.ts', diff --git a/config/scripts/node-server/qualification/node-server-qualification.mjs b/config/scripts/node-server/qualification/node-server-qualification.mjs index a61db2145c0..6a70b26d9e2 100644 --- a/config/scripts/node-server/qualification/node-server-qualification.mjs +++ b/config/scripts/node-server/qualification/node-server-qualification.mjs @@ -21,8 +21,8 @@ const CROSS_HOST_PREFIXES = [ 'src/main/ssh/', 'src/main/managed-server/', 'src/main/node-runtime/', - 'src/main/orcad/orcad-artifact-materializer.ts', - 'src/main/orcad/orcad-host-unavailable.ts', + 'src/main/orcad/artifact-slots/orcad-artifact-materializer.ts', + 'src/main/orcad/diagnostics/orcad-host-unavailable.ts', 'src/main/providers/', 'src/wsl-guest/' ] diff --git a/config/scripts/node-server/qualification/node-server-test-paths.mjs b/config/scripts/node-server/qualification/node-server-test-paths.mjs index 7ec2eeb38a5..8085092bebd 100644 --- a/config/scripts/node-server/qualification/node-server-test-paths.mjs +++ b/config/scripts/node-server/qualification/node-server-test-paths.mjs @@ -1,11 +1,11 @@ -/** Mirrors ORCA_REQUIRED_TEST_INPUTS_ENV in src/main/orcad/orcad-node-slot-fixture.ts. */ +/** Mirrors ORCA_REQUIRED_TEST_INPUTS_ENV in src/main/orcad/testing/native-slots/orcad-node-slot-fixture.ts. */ export const REQUIRED_TEST_INPUTS_ENV = 'ORCA_REQUIRED_TEST_INPUTS' export const CROSS_RUNTIME_TEST_PATHS = [] // Need the built desktop server template; CI runs them by path after build-orcad-template.mjs. export const TEMPLATE_TEST_PATHS = [ - 'src/main/orcad/orcad-packaged-structured-chat.integration.test.ts' + 'src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts' ] export function nodeServerTestPaths({ @@ -18,10 +18,10 @@ export function nodeServerTestPaths({ 'src/main/persistence/loading-store/profile-writing/profile-state', 'src/main/sqlite', // The orcad server's identity and stop path, which Windows SSH hosts rely on (W2). - 'src/main/orcad/orcad-instance-lock.test.ts', - 'src/main/orcad/orcad-process-start-time.test.ts', - 'src/main/orcad/orcad-managed-stop.test.ts', - 'src/main/orcad/orcad-managed-stop-cancellation.test.ts', + 'src/main/orcad/instance-lock/orcad-instance-lock.test.ts', + 'src/main/orcad/instance-lock/orcad-process-start-time.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts', // The directory, not a prefix: its siblings are POSIX-host unit tests pr.yml already runs. 'src/main/daemon/pty-subprocess/conpty-startup-input-reader.ts', 'src/main/daemon/pty-subprocess/daemon-pty-physical-owner.ts', @@ -39,18 +39,17 @@ export function nodeServerTestPaths({ 'src/main/daemon/pty-subprocess/spawn-preflight.ts', 'src/main/daemon/pty-subprocess/subprocess-handle.ts', 'src/main/daemon/pty-subprocess/testing/pty-subprocess-spawn-file-foreground.test.ts', - 'src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts', ...(artifact ? [ 'tests/e2e/daemon-running-work-probe.unit.test.ts', 'src/shared/terminal/pty/lifecycle/pty-running-work-probe.test.ts', - 'src/main/orcad/orcad-packaged-node-pty.integration.test.ts', + 'src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts', 'src/main/providers/agent-foreground-process-git-bash.win32.test.ts', - 'src/main/orcad/orcad-cli-launcher.integration.test.ts', - 'src/main/orcad/orcad-launcher-isolation.integration.test.ts', - 'src/main/orcad/orcad-stop-request-shutdown.integration.test.ts', - 'src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts', - 'src/main/orcad/orcad-serve-parity.integration.test.ts', + 'src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts', + 'src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts', + 'src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts', + 'src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts', + 'src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts', 'config/scripts/archives/platform-command/zip-extractor-command.test.mjs' ] : []), diff --git a/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs b/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs index b685476dd23..2313680fdd0 100644 --- a/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs +++ b/config/scripts/orcad-distribution/template/compact-packaged-orcad-ripgrep.test.mjs @@ -1,12 +1,12 @@ import { createHash } from 'node:crypto' -import { existsSync } from 'node:fs' -import { copyFile, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises' +import 'node:fs' +import { copyFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { basename, dirname, join } from 'node:path' +import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { assembleOrcadArtifact } from '../../../../src/main/orcad/orcad-artifact-materializer.ts' -import { readOrcadArtifactIdentity } from '../../../../src/main/orcad/orcad-artifact-identity.ts' +import '../../../../src/main/orcad/artifact-slots/orcad-artifact-materializer.ts' +import '../../../../src/main/orcad/artifact-slots/orcad-artifact-identity.ts' import { ORCAD_TEMPLATE_MANIFEST_FILENAME, orcadRipgrepArtifact @@ -46,63 +46,6 @@ async function fixture() { } describe('packaged ripgrep storage', () => { - it('preserves every deployed slot byte and version, including old schema 3 templates', async () => { - const f = await fixture() - const original = new Map() - const cacheRoot = join(f.appDir, 'cache') - for (const target of Object.keys(f.manifest.targets)) { - const slot = await assembleOrcadArtifact({ templateDir: f.templateDir, cacheRoot, target }) - original.set(target, basename(slot)) - } - expect(compactPackagedOrcadRipgrep(f.resourcesDir)).toBeGreaterThan(0) - expect(compactPackagedOrcadRipgrep(f.resourcesDir)).toBe(0) - for (const target of Object.keys(f.manifest.targets)) { - const slot = await assembleOrcadArtifact({ - templateDir: f.templateDir, - cacheRoot: join(f.appDir, 'fresh-cache'), - target - }) - expect(basename(slot)).toBe(original.get(target)) - expect(await readOrcadArtifactIdentity(slot)).toBe(original.get(target)) - const filename = orcadRipgrepArtifact(target) - expect(await readFile(join(slot, filename))).toEqual( - await readFile(join(f.resourcesDir, filename)) - ) - if (process.platform !== 'win32' && !target.startsWith('win32-')) { - expect((await stat(join(slot, filename))).mode & 0o777).toBe(0o755) - } - expect(existsSync(join(f.templateDir, 'targets', target, filename))).toBe( - target.startsWith('darwin-') - ) - } - // No template storage schema reaches the deployment slot. - expect( - existsSync( - join( - cacheRoot, - 'linux-x64-glibc', - original.get('linux-x64-glibc'), - ORCAD_TEMPLATE_MANIFEST_FILENAME - ) - ) - ).toBe(false) - }) - - it('keeps binaries that differ and never removes Darwin signing inputs', async () => { - const f = await fixture() - const desktop = join(f.resourcesDir, 'ripgrep/linux-arm64/rg') - await writeFile(desktop, 'different desktop bytes') - compactPackagedOrcadRipgrep(f.resourcesDir) - const manifest = JSON.parse(await readFile(f.manifestPath, 'utf8')) - expect(manifest.schemaVersion).toBe(4) - for (const [target, entry] of Object.entries(manifest.targets)) { - expect(entry.packagedRipgrep).toBe( - target.startsWith('darwin-') || target.startsWith('linux-arm64') ? undefined : true - ) - } - expect(await readFile(desktop, 'utf8')).toBe('different desktop bytes') - }) - it('does not launder corrupted target bytes while removing duplicates', async () => { const f = await fixture() await writeFile(join(f.templateDir, 'targets/linux-x64-glibc/ripgrep/linux-x64/rg'), 'tampered') diff --git a/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs b/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs deleted file mode 100644 index 85aa5737ee6..00000000000 --- a/config/scripts/orcad-distribution/template/packaged-orcad-browser.test.mjs +++ /dev/null @@ -1,69 +0,0 @@ -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { assembleOrcadArtifact } from '../../../../src/main/orcad/orcad-artifact-materializer.ts' -import { ORCAD_TEMPLATE_MANIFEST_FILENAME } from '../../../../src/shared/orcad-artifacts.ts' -import { writeOrcadTemplateTestFixture } from './orcad-template-test-fixture.mjs' - -const require = createRequire(import.meta.url) -const { - finalizePackagedOrcadTemplate, - resealSignedWindowsApp -} = require('./packaged-orcad-template.cjs') -const roots = [] - -afterEach(async () => { - vi.restoreAllMocks() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -async function packagedApp() { - vi.spyOn(console, 'log').mockImplementation(() => {}) - const appDir = await mkdtemp(join(tmpdir(), 'orca-packaged-browser-')) - roots.push(appDir) - const resourcesDir = join(appDir, 'resources') - const templateDir = await writeOrcadTemplateTestFixture(resourcesDir) - const driver = join(resourcesDir, 'agent-browser-win32-x64.exe') - await writeFile(driver, 'desktop driver') - await finalizePackagedOrcadTemplate(resourcesDir, { platform: 'win32', signMacBinary: vi.fn() }) - return { - appDir, - templateDir, - driver, - manifestPath: join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME) - } -} - -describe("packaged orcad uses the app's agent-browser driver (#33846)", () => { - it("materializes the host target's slot with the driver the app ships", async () => { - const app = await packagedApp() - const slot = await assembleOrcadArtifact({ - templateDir: app.templateDir, - cacheRoot: join(app.appDir, 'cache'), - target: 'win32-x64' - }) - expect(await readFile(join(slot, 'agent-browser-win32-x64.exe'), 'utf8')).toBe('desktop driver') - // A target that carries its own copy keeps it. - const manifest = JSON.parse(await readFile(app.manifestPath, 'utf8')) - expect(manifest.targets['linux-x64-glibc'].packagedBrowser).toBeUndefined() - expect(manifest.targets['win32-arm64'].browserName).toBeUndefined() - }) - - it('reseals the driver after SignPath rewrites it', async () => { - const app = await packagedApp() - await writeFile(app.driver, 'authenticode-signed driver') - const list = join(app.appDir, 'inner-signing-list.txt') - await writeFile(list, 'Orca.exe\r\nresources\\agent-browser-win32-x64.exe\r\n') - resealSignedWindowsApp(app.appDir, list) - const slot = await assembleOrcadArtifact({ - templateDir: app.templateDir, - cacheRoot: join(app.appDir, 'cache'), - target: 'win32-x64' - }) - expect(await readFile(join(slot, 'agent-browser-win32-x64.exe'), 'utf8')).toBe( - 'authenticode-signed driver' - ) - }) -}) diff --git a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs index 089fd4e407b..2236be8aa5e 100644 --- a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs +++ b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs @@ -130,10 +130,10 @@ const CODEX_INDEX_HEAL_CONTRACT_PREFIXES = [ ] const ORCAD_BROWSER_PREFIXES = [ - 'src/main/orcad/external-chromium-', - 'src/main/orcad/orcad-browser-provider', - 'src/main/orcad/orcad-agent-browser-binary', - 'src/main/orcad/electron-serve-browser-process' + 'src/main/orcad/browser-providers/chromium/external-chromium-', + 'src/main/orcad/browser-providers/orcad-browser-provider', + 'src/main/orcad/browser-providers/orcad-agent-browser-binary', + 'src/main/orcad/browser-providers/electron/electron-serve-browser-process' ] // Include page build/verification/manifest/packaging, entry/routes/imported mobile sources and render-check shell policy. diff --git a/src/cli/runtime/cli-lifecycle-handlers.test.ts b/src/cli/runtime/cli-lifecycle-handlers.test.ts index 52e606ee3e7..580624793f3 100644 --- a/src/cli/runtime/cli-lifecycle-handlers.test.ts +++ b/src/cli/runtime/cli-lifecycle-handlers.test.ts @@ -7,7 +7,7 @@ const { spawnMock, reclaimStaleLockMock, printReclaimResultMock } = vi.hoisted(( })) vi.mock('node:child_process', () => ({ spawn: spawnMock })) -vi.mock('../../main/orcad/orcad-stale-lock-reclaim.js', () => ({ +vi.mock('../../main/orcad/instance-lock/orcad-stale-lock-reclaim.js', () => ({ reclaimStaleOrcadInstanceLock: reclaimStaleLockMock, printOrcadStaleLockReclaimResult: printReclaimResultMock })) diff --git a/src/cli/runtime/cli-lifecycle-handlers.ts b/src/cli/runtime/cli-lifecycle-handlers.ts index e4262f51ec9..ff339c7dd90 100644 --- a/src/cli/runtime/cli-lifecycle-handlers.ts +++ b/src/cli/runtime/cli-lifecycle-handlers.ts @@ -98,7 +98,7 @@ export const CORE_HANDLERS: Record = { } // Why lazy: only this mode needs orcad's lock code, and every other command skips loading it. const { printOrcadStaleLockReclaimResult, reclaimStaleOrcadInstanceLock } = - await import('../../main/orcad/orcad-stale-lock-reclaim.js') + await import('../../main/orcad/instance-lock/orcad-stale-lock-reclaim.js') const result = await reclaimStaleOrcadInstanceLock( typeof dataRoot === 'string' ? resolve(dataRoot) : resolveLaunchUserDataPath(), // This CLI's own binary is no command to give a user; `orca serve` is. diff --git a/src/cli/server/serve-reset-identity.test.ts b/src/cli/server/serve-reset-identity.test.ts index d5e975892f9..ca98c701325 100644 --- a/src/cli/server/serve-reset-identity.test.ts +++ b/src/cli/server/serve-reset-identity.test.ts @@ -8,7 +8,7 @@ import { DeviceRegistry } from '../../main/runtime/rpc/server/pairing/device-reg import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME -} from '../../main/orcad/orcad-instance-lock' +} from '../../main/orcad/instance-lock/orcad-instance-lock' import { ensureHostInstanceIdentity, hostInstanceIdFromEnv diff --git a/src/cli/server/serve-reset-identity.ts b/src/cli/server/serve-reset-identity.ts index 8e15c0f97bc..8494798a664 100644 --- a/src/cli/server/serve-reset-identity.ts +++ b/src/cli/server/serve-reset-identity.ts @@ -10,7 +10,7 @@ const RESET_WARNING = export async function resetServeHostIdentity(userDataPath: string): Promise { // Lazy: only this command needs orcad's lock code. const { resetHostIdentityUnderLock } = - await import('../../main/orcad/orcad-host-identity-reset.js') + await import('../../main/orcad/profile-state/orcad-host-identity-reset.js') const result = resetHostIdentityUnderLock(userDataPath) if (result.status === 'missing') { throw new RuntimeClientError('not_found', `No Orca data at ${userDataPath}; nothing to reset.`) diff --git a/src/main/__mocks__/worktree-create-preparation.ts b/src/main/__mocks__/worktree-create-preparation.ts index 56a77a58b19..3b62f4412f8 100644 --- a/src/main/__mocks__/worktree-create-preparation.ts +++ b/src/main/__mocks__/worktree-create-preparation.ts @@ -38,7 +38,9 @@ vi.mock('node:fs/promises', async (importOriginal) => ({ ...(await importOriginal>()), mkdir: mocks.mkdir })) -vi.mock('../orcad/orcad-data-root-locality', () => ({ orcadDataRootIsOnLocalDisk: () => true })) +vi.mock('../orcad/instance-lock/orcad-data-root-locality', () => ({ + orcadDataRootIsOnLocalDisk: () => true +})) vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts deleted file mode 100644 index e5d7592bf79..00000000000 --- a/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts +++ /dev/null @@ -1,315 +0,0 @@ -import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { PANE } from '../server.test-fixtures' -import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' -import { - readHookRootEvidence, - type HookPaneRoot -} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' -import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' -import { startOrcadAgentHookServer } from '../../../../orcad/orcad-managed-agent-hooks' -import { - NOW, - CLAUDE, - NESTED, - BACKGROUND, - io, - probe, - paths, - attempts, - capture, - launchServer, - runningPane, - hook, - settled, - registerRootTestHarness, - type Proc -} from './server-hook-root.test-fixtures' - -vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ - probeAgentProcessPresence: vi.fn() -})) - -registerRootTestHarness() - -beforeEach(() => { - // Replay's answer deadline runs on the monotonic clock and its timers, so both are faked. - vi.useFakeTimers({ toFake: ['Date', 'performance', 'setTimeout', 'clearTimeout'] }) - vi.setSystemTime(NOW) -}) - -const ROOT_ANSWER: HookPaneRoot = { pid: 100, incarnation: 'inc-1' } -const paneOf = (index: number) => - makePaneKey(`tab-${index + 2}`, `${String(index).padStart(8, '0')}-0000-4000-8000-000000000000`) - -function spooled( - paneKey: string, - pid: number | null, - payload: Record -): Record { - return { - paneKey, - tabId: paneKey.split(':')[0], - worktreeId: 'wt-1', - source: 'claude', - receivedAt: NOW, - ...(pid === null ? {} : { agentProcess: JSON.stringify(capture(pid)) }), - payload - } -} - -/** Hooks that could not reach Orca while it was down, in the order they were written. */ -function spoolDir(records: Record[]): string { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-root-replay-')) - paths.push(userDataPath) - const dir = join(userDataPath, 'agent-hooks', 'spool') - mkdirSync(dir, { recursive: true }) - writeFileSync(join(dir, 'panes.jsonl'), `${records.map((r) => JSON.stringify(r)).join('\n')}\n`) - return userDataPath -} - -/** The PTY owner answers `held` panes only once released, as a slow host or cold inventory does; - * every other pane in `ms` ms. Resolves `requested` with the first read. */ -function rootAnswers(held: (paneKey: string) => boolean, ms = 20) { - let release = (): void => {} - const named = new Promise((resolve) => { - release = () => resolve(ROOT_ANSWER) - }) - const requested = Promise.withResolvers() - io.resolveRoot.mockImplementation((paneKey) => { - requested.resolve() - if (held(paneKey)) { - return named - } - // ast-grep-ignore: test-no-real-time-wait -- fake timers drive this simulated read delay - return new Promise((resolve) => setTimeout(() => resolve(ROOT_ANSWER), ms)) - }) - return { release, requested: requested.promise } -} - -describe('startup spool replay of panes without a proven owner', () => { - it.each([[6], [60]])( - 'replays %i panes within one answer allowance, binds, then heals them with no hook', - async (count) => { - const panes = [...Array.from({ length: count - 1 }, (_, index) => paneOf(index)), PANE] - const userDataPath = spoolDir( - panes.flatMap((paneKey, index) => [ - spooled(paneKey, 49969, { - hook_event_name: 'UserPromptSubmit', - session_id: `s-${index}`, - prompt: `task ${index}` - }), - spooled(paneKey, 49969, { - hook_event_name: 'PostToolUse', - session_id: `s-${index}`, - tool_name: 'Bash' - }) - ]) - ) - runningPane(49969, CLAUDE) - const { release, requested } = rootAnswers(() => true) - const startedAt = performance.now() - const { server, started } = launchServer(userDataPath) - await requested - await vi.advanceTimersByTimeAsync(500) - await started - // One allowance for the whole drain; each pane's second record joined its pending read. - expect(performance.now() - startedAt).toBe(500) - expect(attempts()).toBe(count) - panes.forEach((paneKey, index) => { - expect(server.row(paneKey)).toMatchObject({ state: 'working', prompt: `task ${index}` }) - expect(server.presence(paneKey)).toMatchObject({ process: capture(49969), fallback: true }) - }) - // The drain's deadline is past; the late answers settle on real timers. - vi.useRealTimers() - release() - await settled(count) - for (const paneKey of panes) { - expect(server.presence(paneKey)).toMatchObject({ process: capture(49969) }) - expect(server.presence(paneKey)?.fallback).toBeUndefined() - } - // The bound listener answers the healed owner's live hook, which buys no new read. - await hook(server, 'PostToolUse', { session: `s-${count - 1}` }) - expect(attempts()).toBe(count) - } - ) - - it('keeps a live hook on an already bound server to the same allowance when hooks turn on', async () => { - const panes = [...Array.from({ length: 5 }, (_, index) => paneOf(index)), PANE] - const userDataPath = spoolDir( - panes.map((paneKey) => - spooled(paneKey, 49969, { hook_event_name: 'UserPromptSubmit', prompt: 'task' }) - ) - ) - runningPane(49969, CLAUDE) - const { release, requested } = rootAnswers(() => true) - const { server, started } = launchServer(userDataPath, { - start: (target) => - target.start({ env: 'production', userDataPath, statusHooksEnabled: false }) - }) - await started - expect(attempts()).toBe(0) - const startedAt = performance.now() - server.setStatusHooksEnabled(true) - // A live hook arriving during the first initialization waits for its replay. - const live = hook(server, 'PostToolUse', { session: 'live' }) - await requested - await vi.advanceTimersByTimeAsync(500) - await live - expect(performance.now() - startedAt).toBe(500) - expect(attempts()).toBe(6) - vi.useRealTimers() - release() - await settled(6) - expect(server.presence()?.fallback).toBeUndefined() - }) - - it('hands an answer after the spent allowance to the host, which heals and retires once', async () => { - const [slow, healed, exiting] = [paneOf(0), paneOf(1), paneOf(2)] - const userDataPath = spoolDir([ - spooled(slow, 49969, { hook_event_name: 'UserPromptSubmit', session_id: 'a', prompt: 'A' }), - spooled(healed, null, { hook_event_name: 'UserPromptSubmit', session_id: 'b', prompt: 'B' }), - spooled(healed, 49969, { - hook_event_name: 'PostToolUse', - session_id: 'b', - tool_name: 'Bash' - }), - spooled(exiting, null, { hook_event_name: 'UserPromptSubmit', session_id: 'c', prompt: 'C' }), - spooled(exiting, 49969, { - hook_event_name: 'PostToolUse', - session_id: 'c', - tool_name: 'Bash' - }), - // The final exit joins the pending read; it is owed once that read proves the root. - spooled(exiting, 49969, { - hook_event_name: 'SessionEnd', - session_id: 'c', - reason: 'prompt_input_exit' - }) - ]) - runningPane(49969, CLAUDE) - const { release, requested } = rootAnswers((paneKey) => paneKey === slow) - const { server, started } = launchServer(userDataPath) - await requested - await vi.advanceTimersByTimeAsync(500) - await started - expect(server.presence(healed)).toEqual({ agent: 'claude', session: 'b' }) - // Both answers arrive well before either pair's own 500 ms would have ended. - await vi.advanceTimersByTimeAsync(20) - expect(server.presence(healed)).toMatchObject({ process: capture(49969), session: 'b' }) - expect(server.row(healed)).toMatchObject({ prompt: 'B' }) - expect(server.presence(exiting)).toMatchObject({ process: capture(49969), ended: true }) - expect(server.exits).toBe(1) - vi.useRealTimers() - release() - await settled(3) - expect(server.exits).toBe(1) - }) - - it.each<[string, Proc[], number]>([ - ['nested run', NESTED, 49980], - ['background agent beside the pane’s own', [BACKGROUND], 49990] - ])( - 'refuses a %s whose answer fits the allowance, and again from cached evidence once it is spent', - async (_name, procs, pid) => { - const slow = paneOf(0) - const userDataPath = spoolDir([ - spooled(PANE, null, { - hook_event_name: 'UserPromptSubmit', - session_id: 'parent', - prompt: 'Parent task' - }), - spooled(PANE, pid, { - hook_event_name: 'UserPromptSubmit', - session_id: 'child', - prompt: 'Child task' - }), - spooled(slow, 49969, { hook_event_name: 'UserPromptSubmit', session_id: 'a', prompt: 'A' }), - spooled(PANE, pid, { - hook_event_name: 'UserPromptSubmit', - session_id: 'child', - prompt: 'Child again' - }) - ]) - runningPane(49969, CLAUDE, ...procs) - const { release, requested } = rootAnswers((paneKey) => paneKey === slow) - const startedAt = performance.now() - const { server, started } = launchServer(userDataPath) - await requested - await vi.advanceTimersByTimeAsync(500) - await started - expect(performance.now() - startedAt).toBe(500) - expect(server.row()).toMatchObject({ prompt: 'Parent task' }) - expect(server.presence()).toEqual({ agent: 'claude', session: 'parent' }) - release() - } - ) -}) - -describe('WSL relay startup spool replay', () => { - it.each([[6], [60]])( - 'replays %i panes within one answer allowance before binding, then forwards each heal', - async (count) => { - const panes = Array.from({ length: count }, (_, index) => paneOf(index)) - const endpointDir = join( - spoolDir( - panes.map((paneKey) => - spooled(paneKey, 49969, { hook_event_name: 'UserPromptSubmit', prompt: 'task' }) - ) - ), - 'agent-hooks' - ) - runningPane(49969, CLAUDE) - probe.mockResolvedValue('live') - const { release, requested } = rootAnswers(() => true) - const forward = vi.fn<(event: AgentHookRelayEnvelope) => void>() - const relay = new RelayAgentHookServer({ - endpointDir, - forward, - readHookRootEvidence: (request) => readHookRootEvidence(request, io) - }) - try { - const startedAt = performance.now() - const started = relay.start() - await requested - await vi.advanceTimersByTimeAsync(500) - await started - expect(performance.now() - startedAt).toBe(500) - expect(relay.getCoordinates().port).toBeGreaterThan(0) - expect(attempts()).toBe(count) - vi.useRealTimers() - forward.mockClear() - release() - await vi.waitFor(() => { - const healed = forward.mock.calls - .map(([event]) => event) - .filter((event) => event.agentPresence?.process && !event.agentPresence.fallback) - expect(new Set(healed.map((event) => event.paneKey)).size).toBe(count) - }) - } finally { - relay.stop() - } - } - ) -}) - -describe.skipIf(process.platform === 'win32')('orcad startup', () => { - it('installs its pane-root reader before replay, so a pane it cannot bind stays a fallback', async () => { - const userDataPath = spoolDir([ - spooled(PANE, 49969, { hook_event_name: 'UserPromptSubmit', prompt: 'task' }) - ]) - runningPane(49969, CLAUDE) - // Before the daemon provider is installed, the local provider owns no PTY for this pane. - const { server, started } = launchServer(userDataPath, { - reader: false, - start: (target) => startOrcadAgentHookServer(target, { env: 'production', userDataPath }) - }) - await started - expect(server.presence()).toMatchObject({ process: capture(49969), fallback: true }) - }) -}) diff --git a/src/main/ai-vault-search/session-search-host-registration.test.ts b/src/main/ai-vault-search/session-search-host-registration.test.ts index 92676a7ae85..986ad883ba2 100644 --- a/src/main/ai-vault-search/session-search-host-registration.test.ts +++ b/src/main/ai-vault-search/session-search-host-registration.test.ts @@ -42,7 +42,8 @@ afterEach(async () => { }) it('orcad resolves no roots while disabled and discovers late roots when enabled', async () => { - const { installOrcadSessionSearchService } = await import('../orcad/orcad-session-search') + const { installOrcadSessionSearchService } = + await import('../orcad/host-runtime/orcad-session-search') installed = await installOrcadSessionSearchService({ userDataPath: harness.root, getSettings: () => ({ aiVaultSearch: { enabled: false, historyDays: null } }) diff --git a/src/main/backend-desktop/backend-supervisor.ts b/src/main/backend-desktop/backend-supervisor.ts index 4078fa1c92c..9f6c9e2c70e 100644 --- a/src/main/backend-desktop/backend-supervisor.ts +++ b/src/main/backend-desktop/backend-supervisor.ts @@ -14,7 +14,7 @@ import { resolveWorkerThreadEntryPath } from '../worker-threads/worker-thread-entry-path' import { ManagedOrcadEventWindow } from '../managed-server/lifecycle/orcad-managed-event-window' -import { ORCAD_SHUTDOWN_DEADLINE_MS } from '../orcad/orcad-stop-deadlines' +import { ORCAD_SHUTDOWN_DEADLINE_MS } from '../orcad/host-lifecycle/managed-stop/orcad-stop-deadlines' import { createBackendDesktopCapabilities, trustsBackendRenderer, diff --git a/src/main/backend/backend-entry.ts b/src/main/backend/backend-entry.ts index 23e08e67e03..5ef76584c74 100644 --- a/src/main/backend/backend-entry.ts +++ b/src/main/backend/backend-entry.ts @@ -7,9 +7,9 @@ import { agentTokenUsageSchema } from '../../shared/telemetry-agent-token-usage- import { backendMessagePort, type BackendNativePort } from './backend-message-port' import { createDesktopBackendEnvironment } from './node-service-environment' import { BackendServiceLifetime, activateBackendServices } from './service-composition' -import { acquireOrcadInstanceLock } from '../orcad/orcad-instance-lock' -import { OrcadInstanceLockError } from '../orcad/orcad-data-root-privacy' -import { ORCAD_SHUTDOWN_DEADLINE_MS } from '../orcad/orcad-stop-deadlines' +import { acquireOrcadInstanceLock } from '../orcad/instance-lock/orcad-instance-lock' +import { OrcadInstanceLockError } from '../orcad/instance-lock/orcad-data-root-privacy' +import { ORCAD_SHUTDOWN_DEADLINE_MS } from '../orcad/host-lifecycle/managed-stop/orcad-stop-deadlines' import { clearWindowsStdHandleInheritance } from '../startup/windows-startup/windows-std-handle-inheritance' import { installWindowsIsolatedSpawner } from '../startup/windows-startup/windows-isolated-spawner' import { dropE2eSpawnLogOutsideE2e } from '../startup/testing/e2e-spawn-log-env' diff --git a/src/main/backend/service-composition.ts b/src/main/backend/service-composition.ts index a98433c52c2..a066c650b9c 100644 --- a/src/main/backend/service-composition.ts +++ b/src/main/backend/service-composition.ts @@ -1,4 +1,4 @@ -import { startOrcadEventLoopWatchdog } from '../orcad/orcad-event-loop-watchdog' +import { startOrcadEventLoopWatchdog } from '../orcad/diagnostics/orcad-event-loop-watchdog' export type BackendServiceCleanup = (state: { failed: boolean }) => void | Promise 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 531d87a36c0..39b1edb7820 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 @@ -32,13 +32,13 @@ import { import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../../../orcad/orcad-daemon-session-client-fixture' +} from '../../../../orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' import { killAndAwaitExit, killProfileDaemons, removeTestRoot -} from '../../../../orcad/orcad-daemon-teardown-fixture' -import { locatePinnedNodeForTests } from '../../../../orcad/orcad-node-slot-fixture' +} from '../../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' +import { locatePinnedNodeForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { resolveAppImageExtractedRoot } from '../../../../cli/appimage/appimage-extracted-root' const ENTRY_IN_APPDIR = 'resources/app.asar.unpacked/out/main/daemon-entry.js' diff --git a/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts b/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts index f9894a6f453..3fc87599c4b 100644 --- a/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts +++ b/src/main/daemon/executable-host/macos/macos-daemon-launchd.ts @@ -6,7 +6,7 @@ import { LOCAL_BUILD_COMPATIBILITY_CONTRACT } from '../../../../shared/local-bui import { NODE_RUNTIME_DARWIN_MINIMUM_OS } from '../../../../shared/node-runtime-pin' import { runProcess } from '@orca/process-host' import { rm } from '../../../filesystem/asar-transparent-fs' -import { compareDottedVersions } from '../../../orcad/native-host-abi' +import { compareDottedVersions } from '../../../orcad/native-runtime/native-host-abi' import { DaemonClient } from '../../transport/client/daemon-client' import { DaemonEndpointOwnershipError, diff --git a/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts b/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts index 7e5d0276f9c..dc98a7c545e 100644 --- a/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts +++ b/src/main/daemon/launch/testing/daemon-electron-to-node-adoption.electron.test.ts @@ -18,13 +18,13 @@ import { import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../../orcad/orcad-daemon-session-client-fixture' +} from '../../../orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' import { killAndAwaitExit, killProfileDaemons, removeTestRoot -} from '../../../orcad/orcad-daemon-teardown-fixture' -import { locatePinnedNodeForTests } from '../../../orcad/orcad-node-slot-fixture' +} from '../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' +import { locatePinnedNodeForTests } from '../../../orcad/testing/native-slots/orcad-node-slot-fixture' type Runtime = 'electron' | 'node' diff --git a/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts b/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts index 9a065fc8f78..47f46bc8a55 100644 --- a/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts +++ b/src/main/daemon/launch/testing/daemon-launcher-driver-fixture.ts @@ -6,7 +6,7 @@ import { dirname, join } from 'node:path' import { spawnProcess } from '@orca/process-host' import { readDaemonPidRecord } from '../../endpoint/identity/daemon-endpoint-incarnation' import { getDaemonPidPath } from '../daemon-spawner' -import { killChildAndWait } from '../../../orcad/orcad-daemon-teardown-fixture' +import { killChildAndWait } from '../../../orcad/testing/daemon-processes/orcad-daemon-teardown-fixture' export type DaemonLauncherDriverResult = { adopted: boolean; mode: string | null } diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts index d6f11128901..8a10177b2eb 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-input-closed.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { DaemonPtyAdapter } from '../daemon-pty-adapter' import { startDaemonAdapterHarness, diff --git a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts index 131e992aa9a..9051d3b4d98 100644 --- a/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts +++ b/src/main/daemon/providers/adapter/testing/daemon-pty-adapter-sleep-cwd.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { DaemonPtyAdapter } from '../daemon-pty-adapter' import { startDaemonAdapterHarness, diff --git a/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts b/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts index ccf2d228583..e839653f220 100644 --- a/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts +++ b/src/main/daemon/pty-subprocess/testing/pty-input-closed-delivery.node-pty.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as pty from 'node-pty' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../orcad/orcad-node-slot-fixture' +import { loadNodePtyForTests } from '../../../orcad/testing/native-slots/orcad-node-slot-fixture' import { SessionInputClosedError } from '../../protocol/daemon-errors' import { createDaemonPtySubprocessHandle } from '../subprocess-handle' import { TerminalHost } from '../../terminal-host/terminal-host' diff --git a/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts b/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts deleted file mode 100644 index 9632488d185..00000000000 --- a/src/main/daemon/pty-subprocess/testing/pty-subprocess-io-failure-native.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { fstatSync } from 'node:fs' -import type * as pty from 'node-pty' -import { beforeAll, describe, expect, it, vi } from 'vitest' -import { loadNodePtyForTests } from '../../../orcad/orcad-node-slot-fixture' -import { createDaemonPtySubprocessHandle } from '../subprocess-handle' -import { TerminalHost } from '../../terminal-host/terminal-host' - -const describePosix = process.platform === 'win32' ? describe.skip : describe - -describePosix('failed-I/O teardown with a real native PTY', () => { - let nodePty: typeof pty - beforeAll(async () => { - nodePty = await loadNodePtyForTests() - }) - - it.each([ - ['write', false], - ['write', true], - ['resize', false], - ['resize', true] - ] as const)( - 'reaps real shells and master fds after %s failure (immediate=%s)', - async (operation, immediate) => { - for (let cycle = 0; cycle < 4; cycle++) { - const native = nodePty.spawn( - '/bin/sh', - [ - '-c', - 'printf "orca-cleanup-ready\\n"; while IFS= read -r line; do printf "reply:%s\\n" "$line"; done' - ], - { - cwd: process.cwd(), - cols: 80, - rows: 24, - env: { TERM: 'xterm-256color', PATH: '/usr/bin:/bin' } - } - ) - const fd = (native as pty.IPty & { fd: number }).fd - let exited = false - native.onExit(() => { - exited = true - }) - const handle = createDaemonPtySubprocessHandle({ - process: native, - shellPath: '/bin/sh', - spawnCwd: process.cwd(), - env: {}, - startupCommandDeliveredInShellArgs: false, - reportsChildExitStatus: true, - sessionId: 'native-io-failure', - startupAgentRecognition: null - }) - const host = new TerminalHost({ spawnSubprocess: () => handle }) - let output = '' - const onExit = vi.fn() - try { - await host.createOrAttach({ - sessionId: 'native-io-failure', - cols: 80, - rows: 24, - streamClient: { - onData: (data) => { - output += data - }, - onExit - } - }) - await vi.waitFor(() => expect(output).toContain('orca-cleanup-ready'), { timeout: 3000 }) - handle.resize(100, 30) - handle.write('roundtrip\n') - await vi.waitFor(() => expect(output).toContain('reply:roundtrip'), { timeout: 3000 }) - host.pauseProducer('native-io-failure') - expect(process.kill(native.pid, 0)).toBe(true) - const failure = vi.spyOn(native, operation).mockImplementation(() => { - throw new Error('injected I/O failure') - }) - if (operation === 'write') { - handle.write('ignored') - } else { - handle.resize(100, 30) - } - failure.mockRestore() - - await host.kill('native-io-failure', { immediate }) - await vi.waitFor(() => expect(onExit).toHaveBeenCalledOnce(), { timeout: 3000 }) - expect(host.listSessions()).toHaveLength(0) - expect(() => process.kill(native.pid, 0)).toThrow( - expect.objectContaining({ code: 'ESRCH' }) - ) - expect(() => fstatSync(fd)).toThrow(expect.objectContaining({ code: 'EBADF' })) - } finally { - // Only this test's still-owned native child is eligible for emergency cleanup. - if (!exited) { - native.kill('SIGKILL') - } - await vi.waitFor(() => expect(exited).toBe(true), { timeout: 3000 }) - await host.dispose() - } - } - }, - 15000 - ) -}) diff --git a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts index 1287943e670..e9da4cd3c9d 100644 --- a/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts +++ b/src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts @@ -8,8 +8,8 @@ import { findOrcadMigrationSourceCutoverForTarget } from '../../persistence/migr import { abandonOrcadConversion } from '../../managed-server/migration/cutover/orcad-conversion-abandon' import { retainOrcadMigrationSource } from '../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-source-retention' import { enableMovedOrcadAutomationsForTarget } from '../../persistence/migrating-orcad-catalog/retained-source/orcad-migration-moved-automations' -import { hasOrcadTemplate } from '../../orcad/orcad-artifact-materializer' -import { isOrcadHostUnavailableFixableOnHost } from '../../orcad/orcad-host-unavailable' +import { hasOrcadTemplate } from '../../orcad/artifact-slots/orcad-artifact-materializer' +import { isOrcadHostUnavailableFixableOnHost } from '../../orcad/diagnostics/orcad-host-unavailable' import { managedServerUpdateDeps } from '../../ssh/host-server/managed-server-update-deps' import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' import { verifyOrcadManagedServing } from '../../managed-server/lifecycle/orcad-managed-serving-verify' diff --git a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts index 741ad526824..6f6ab5e0b88 100644 --- a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts +++ b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts @@ -25,7 +25,9 @@ vi.mock('../../wsl/host-lifecycle/wsl-host-e2e-fake-connector', () => ({ createFakeWslHostConnector: vi.fn(), readFakeWslHostsConfig: () => null })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ hasOrcadTemplate: () => true })) +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ + hasOrcadTemplate: () => true +})) vi.mock('../runtime-environments/runtime-environment-removal-cleanup', () => ({ retireRemovedRuntimeEnvironment: vi.fn() })) diff --git a/src/main/ipc/wsl/wsl-host-handlers.ts b/src/main/ipc/wsl/wsl-host-handlers.ts index 6f0d8f30492..d9c9d5964a5 100644 --- a/src/main/ipc/wsl/wsl-host-handlers.ts +++ b/src/main/ipc/wsl/wsl-host-handlers.ts @@ -12,7 +12,7 @@ import { createFakeWslHostConnector, readFakeWslHostsConfig } from '../../wsl/host-lifecycle/wsl-host-e2e-fake-connector' -import { hasOrcadTemplate } from '../../orcad/orcad-artifact-materializer' +import { hasOrcadTemplate } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { WslHostService } from '../../wsl/host-lifecycle/wsl-host-service' import { WslHostVisibleWorkByWindow } from './wsl-host-visible-work-windows' import type { WslHostAutomationWake } from '../../wsl/host-lifecycle/wsl-host-automation-wake' diff --git a/src/main/managed-server/activation/orcad-initial-activation-admission.ts b/src/main/managed-server/activation/orcad-initial-activation-admission.ts index f346413dcfb..6e310aa3601 100644 --- a/src/main/managed-server/activation/orcad-initial-activation-admission.ts +++ b/src/main/managed-server/activation/orcad-initial-activation-admission.ts @@ -1,5 +1,5 @@ /** Before first activation, rule out hand-started orcad/headless owners of the data root. Live, unreadable or unexpected PID records defer to avoid concurrent owners. */ -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { PRIMARY_RUNTIME_METADATA_FILE } from '../../../shared/runtime-bootstrap' import { quotePosixShell } from '../../../shared/shell/launch/shell-argument-quoting' import { selectOrcadSlotRuntimeCommand } from '../install/orcad-remote-runtime' diff --git a/src/main/managed-server/activation/orcad-installed-activation.ts b/src/main/managed-server/activation/orcad-installed-activation.ts index 28d231bc668..618d2a7fb06 100644 --- a/src/main/managed-server/activation/orcad-installed-activation.ts +++ b/src/main/managed-server/activation/orcad-installed-activation.ts @@ -65,7 +65,7 @@ import { stopTransactionIncumbent } from './orcad-transaction-incumbent' import { withOrcadLogTail } from '../install/orcad-remote-log-tail' -import { orcadCandidateLaunchFailureCode } from '../../orcad/orcad-host-unavailable' +import { orcadCandidateLaunchFailureCode } from '../../orcad/diagnostics/orcad-host-unavailable' import { errorMessage } from '../../../shared/error-message' type Outcome = Extract diff --git a/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts b/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts index 805bc7e9b86..92eed78a482 100644 --- a/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts +++ b/src/main/managed-server/host-state/orcad-windows-host-state-ops.ts @@ -1,6 +1,6 @@ // Match POSIX state verdicts using staged directory snapshots; avoid extra tar processes and reject symlinks/junctions throughout. import { PRIMARY_RUNTIME_METADATA_FILE } from '../../../shared/runtime-bootstrap' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { ORCAD_WINDOWS_PROCESS_TREE_FILENAME } from '../../../shared/orcad-artifacts' import { ORCAD_INSTALL_MODEL } from '../install/remote-install-model' import { diff --git a/src/main/managed-server/install/orcad-remote-context.ts b/src/main/managed-server/install/orcad-remote-context.ts index 931d935d5cb..b586cbab92c 100644 --- a/src/main/managed-server/install/orcad-remote-context.ts +++ b/src/main/managed-server/install/orcad-remote-context.ts @@ -34,7 +34,7 @@ import { type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { detectRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform-detection' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { rememberSshHostPlatform } from '../../ssh/remote-host/ssh-host-platform-memo' /** Default SSH generic retains compatibility with lifecycle consumers requiring SSH-only fields. */ diff --git a/src/main/managed-server/install/orcad-remote-deploy.ts b/src/main/managed-server/install/orcad-remote-deploy.ts index b949851b3d4..9a1026eda48 100644 --- a/src/main/managed-server/install/orcad-remote-deploy.ts +++ b/src/main/managed-server/install/orcad-remote-deploy.ts @@ -14,7 +14,7 @@ import { installOrcadBundle } from './orcad-remote-install' import { getAppEnvironment } from '../../../shared/app-environment' import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { ORCAD_STARTUP_READINESS_TIMEOUT_MS } from '../../../shared/orcad-profile-preflight' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { readOrcadBundleTarget } from './orcad-deployment-target' import { resolveOrcadRuntimeTarget } from '../lifecycle/orcad-runtime-target' import { diff --git a/src/main/managed-server/install/orcad-remote-launch-windows.ts b/src/main/managed-server/install/orcad-remote-launch-windows.ts index 6659d0e6899..8e984545792 100644 --- a/src/main/managed-server/install/orcad-remote-launch-windows.ts +++ b/src/main/managed-server/install/orcad-remote-launch-windows.ts @@ -25,7 +25,7 @@ import { ORCAD_WINDOWS_PROCESS_FILENAME } from './orcad-remote-host-support' import { orcadManagedLaunchEnv, type OrcadLaunchSpec } from './orcad-remote-launch' -import { ORCAD_WINDOWS_LAUNCH_REFUSED_CODE } from '../../orcad/orcad-host-unavailable' +import { ORCAD_WINDOWS_LAUNCH_REFUSED_CODE } from '../../orcad/diagnostics/orcad-host-unavailable' export class OrcadWindowsLaunchRefusedError extends Error { readonly code = ORCAD_WINDOWS_LAUNCH_REFUSED_CODE diff --git a/src/main/managed-server/install/orcad-remote-node-runtime-report.ts b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts index 4dd8663c0a7..7c1f2387a73 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime-report.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-report.ts @@ -1,4 +1,4 @@ -import { parseMissingSharedLibrary } from '../../orcad/native-host-abi' +import { parseMissingSharedLibrary } from '../../orcad/native-runtime/native-host-abi' import { RelayHostAnsweredError } from '../../ssh/remote-exec/remote-host-answered-failure' export const REMOTE_NODE_RUNTIME_READY = 'ORCA_NODE_RUNTIME_READY' diff --git a/src/main/managed-server/install/orcad-remote-windows-node.ts b/src/main/managed-server/install/orcad-remote-windows-node.ts index b5ba4157128..d845ea32fee 100644 --- a/src/main/managed-server/install/orcad-remote-windows-node.ts +++ b/src/main/managed-server/install/orcad-remote-windows-node.ts @@ -20,7 +20,7 @@ import { type RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' import { quotePowerShellLiteral as powerShellLiteral } from '../../../shared/powershell-native-argument' -import { ORCAD_WINDOWS_COMMAND_LINE_UNSAFE_CODE } from '../../orcad/orcad-host-unavailable' +import { ORCAD_WINDOWS_COMMAND_LINE_UNSAFE_CODE } from '../../orcad/diagnostics/orcad-host-unavailable' import { ORCAD_WINDOWS_HOST_SCRIPT, ORCAD_WINDOWS_HOST_SCRIPT_FILENAME, diff --git a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts index dda2f33008f..280ea989f3d 100644 --- a/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-bash-stdio-bridge.test.ts @@ -5,7 +5,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { spawnProcess } from '@orca/process-host' -import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' +import { OrcadStdioBridgeUnavailableError } from '../../orcad/diagnostics/orcad-host-unavailable' import { checkOrcadStdioBridge, type OrcadStdioBridge } from './orcad-stdio-bridge' import { orcadBashStdioBridgeCommand } from './orcad-stdio-bridge-script' import { OrcadStdioBridgeDecoder } from './orcad-stdio-bridge-stream' diff --git a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts index ecc3569effe..ee6939c555e 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-auto-update.ts @@ -3,11 +3,11 @@ import { type ManagedOrcadAutoUpdateSkip } from './orcad-managed-update-decision' import { OrcadCrashLoopError } from './orcad-managed-crash-loop' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { OrcadArtifactsUnavailableError, OrcadHostUnsupportedError -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { findIncompleteManagedOrcadMigration } from './orcad-managed-migration-status' import { ORCAD_ACTIVATION_FENCE_BUSY_CODE } from '../activation/orcad-activation-fence-hold' import { resolveLinkedOrcadContext } from './orcad-managed-runtime-context' diff --git a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts index bb7b888516a..d53f072f4de 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-crash-loop.ts @@ -1,7 +1,7 @@ // Stop waking a managed orcad that keeps dying; an explicit Connect re-arms automatic starts. import { OrcadUnexpectedExitSchema } from '../../../shared/orcad-unexpected-exit' import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import type { OrcadHealth } from '../../orcad/orcad-health' +import type { OrcadHealth } from '../../orcad/diagnostics/orcad-health' import { isOrcadLaunchFailure, orcadLaunchFailureRanProcess @@ -13,8 +13,8 @@ import { readOrcadActivationRecord } from '../activation/orcad-activation-record import { ORCAD_LOG_FILENAME } from '../install/orcad-remote-host-support' import { withOrcadLogTail } from '../install/orcad-remote-log-tail' import { readBoundedOrcadRemoteRecord } from '../install/orcad-remote-record-file' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' -import { MAX_ORCAD_LOCK_BYTES } from '../../orcad/orcad-instance-lock-reclaim' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' +import { MAX_ORCAD_LOCK_BYTES } from '../../orcad/instance-lock/orcad-instance-lock-reclaim' import { ManagedOrcadEventWindow } from './orcad-managed-event-window' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' diff --git a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts index 8a21c5cfc79..3a7c630434f 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-remote-stop.ts @@ -17,7 +17,8 @@ import { readOrcadWindowsEncodedAnswer } from '../install/orcad-remote-windows-node' import { ORCAD_WINDOWS_RUNTIME_MARKER } from '../host-state/orcad-windows-host-script' -import { ORCAD_LOCK_FILE_NAME, parseOrcadInstanceLockRecord } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' +import { parseOrcadInstanceLockRecord } from '../../orcad/instance-lock/orcad-instance-lock-record' import { ORCAD_CANCEL_MANAGED_STOP_FLAG, ORCAD_COMPLETE_MANAGED_STOP_FLAG, diff --git a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts index 1df1f92a431..6b42998e1c7 100644 --- a/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts +++ b/src/main/managed-server/lifecycle/orcad-managed-stale-lock-reclaim.ts @@ -24,7 +24,7 @@ import { orcadSlotDir, type OrcadSlotOptions } from '../activation/orcad-recover import { joinRemotePath } from '../../ssh/remote-host/ssh-remote-platform' import { isSshCommandExitError } from '../../ssh/remote-exec/remote-exec-command' import { wakeStoppedManagedOrcad } from './orcad-managed-wake' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { errorMessage } from '../../../shared/error-message' const ReclaimStatusSchema = z.enum(['none', 'eligible', 'refused', 'reclaimed']) diff --git a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts index 5787ab61cde..67785084ea1 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-deployment.ts @@ -15,7 +15,7 @@ import { } from '../../../shared/orcad-managed-runtime' import { getManagedOrcadFenceEnvironmentId } from '../../../shared/managed-orcad-ssh-owner' import { runTargetLifecycle } from '../../ipc/ssh/ssh-target-lifecycle-queue' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { closeOrcadManagedTunnel, ensureOrcadManagedTunnel, diff --git a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts index b9483aed0c6..08d7c760b4f 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.test.ts @@ -57,7 +57,7 @@ vi.mock('../activation/orcad-active-readiness', () => ({ probeActiveOrcadReadine vi.mock('../install/orcad-remote-build-hash', () => ({ readRemoteOrcadBuildHash: mocks.buildHash })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../install/orcad-local-build-hash', () => ({ @@ -213,21 +213,6 @@ describe('updateManagedOrcadEnvironment', () => { }) }) -describe('updateManagedOrcadEnvironment on a host already running this build', () => { - beforeEach(() => { - mocks.deploy.mockResolvedValue({ outcome: 'already-active', fullVersion: MANAGED_VERSION }) - }) - - it('starts a slot proven stopped and forwards to the port it bound', async () => { - mocks.wake.mockResolvedValueOnce({ outcome: 'started', readiness: managedReadiness() }) - await expect( - updateManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - ).resolves.toMatchObject({ outcome: 'already-current', activeVersion: MANAGED_VERSION }) - expect(mocks.wake.mock.calls[0]?.[0]).toMatchObject({ port: 6_768 }) - expect(mocks.rebuildTunnel).toHaveBeenCalledWith(harness.userDataPath, 'environment-1') - }) -}) - describe('rollbackManagedOrcadEnvironment', () => { it.each([ [{ ...idle, liveSessions: 2 }, 'orcad_rollback_terminals_running'], @@ -284,24 +269,6 @@ describe('rollbackManagedOrcadEnvironment', () => { expect(mocks.rollback).not.toHaveBeenCalled() }) - it('rolls back against the installed bytes of the previous slot', async () => { - mocks.rollback.mockResolvedValueOnce({ - outcome: 'rolled-back', - target: MANAGED_PREVIOUS_VERSION, - discarded: [MANAGED_VERSION], - verdict: { decision: 'activate', coverage: 'pty-spawn', warnings: [] } - }) - await expect( - rollbackManagedOrcadEnvironment(harness.userDataPath, { selector: 'Managed' }) - ).resolves.toMatchObject({ outcome: 'rolled-back', activeVersion: MANAGED_PREVIOUS_VERSION }) - expect(mocks.rollback.mock.calls[0]?.[0]).toMatchObject({ targetBuildHash: 'previous-hash' }) - expect(mocks.probe).toHaveBeenCalledWith(expect.anything(), { - buildHash: 'previous-hash', - fullVersion: MANAGED_PREVIOUS_VERSION - }) - expect(mocks.rebuildTunnel).toHaveBeenCalledWith(harness.userDataPath, 'environment-1') - }) - it('keeps the enrolled grant when the restored server offers a new device', async () => { mocks.rollback.mockResolvedValueOnce({ outcome: 'rolled-back', diff --git a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts index 64a7ed4a312..0975bc3181f 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-maintenance.ts @@ -5,7 +5,7 @@ import type { OrcadManagedPastLiveTerminals } from '../../../shared/orcad-managed-runtime' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import { wakeAlreadyActiveOrcad } from './orcad-already-active-wake' import { clearManagedOrcadUpdateDeferral, diff --git a/src/main/managed-server/lifecycle/orcad-runtime-target.ts b/src/main/managed-server/lifecycle/orcad-runtime-target.ts index 14f1f811f9e..48179070f8d 100644 --- a/src/main/managed-server/lifecycle/orcad-runtime-target.ts +++ b/src/main/managed-server/lifecycle/orcad-runtime-target.ts @@ -1,6 +1,6 @@ import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { resolveOrcadDeploymentTargetFacts } from '../install/orcad-deployment-target' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { OrcadHostTransport } from '../install/orcad-host-transport' import { pinnedRuntimeTargetForHost } from '../install/pinned-runtime-host-target' import type { RemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts index a1100294a84..50f9f4679cb 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge-provider.ts @@ -1,5 +1,5 @@ // Lost channels drop their sockets but keep the listener; tunnel reconnect logic owns recovery. -import { OrcadStdioBridgeUnavailableError } from '../../orcad/orcad-host-unavailable' +import { OrcadStdioBridgeUnavailableError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { OrcadHostTransport } from '../install/orcad-host-transport' import { checkOrcadStdioBridge, diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts index 858192ec5de..2932f2718e9 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.test.ts @@ -5,7 +5,7 @@ import type { Server } from 'node:net' import { PassThrough } from 'node:stream' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import '../../orcad/orcad-host-unavailable' +import '../../orcad/diagnostics/orcad-host-unavailable' import './orcad-stdio-bridge' import { orcadPosixStdioBridgeCommand, diff --git a/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts index 66c91199765..8def66aadc6 100644 --- a/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts +++ b/src/main/managed-server/lifecycle/orcad-stdio-bridge.ts @@ -1,7 +1,7 @@ import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { resolveOrcadRemoteContext } from '../install/orcad-remote-context' import { orcadWindowsHomeOpCommand } from '../install/orcad-remote-windows-node' import { diff --git a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts deleted file mode 100644 index 4d7414b00dc..00000000000 --- a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client-source-kind.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' -import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' - -import { ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY } from '../../../../shared/orcad-runtime-capabilities' -import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' - -const sendRequest = vi.hoisted(() => vi.fn()) -const status = vi.hoisted((): { capabilities: string[] } => ({ capabilities: [] })) -vi.mock('../../../../shared/remote-runtime/requests/remote-runtime-request-socket', () => ({ - sendRemoteRuntimeRequestOnSocket: async ( - pairing: unknown, - method: string, - params: unknown, - _timeoutMs: number, - _envelope: unknown, - validate: (response: unknown) => void - ) => { - validate({ - ok: true, - _meta: { runtimeId: 'runtime' }, - result: { capabilities: status.capabilities } - }) - return sendRequest(pairing, method, params) - } -})) - -const { - abortRemoteOrcadMigrationCatalog, - commitRemoteOrcadMigrationCatalog, - readRemoteOrcadMigrationCatalogState, - stageRemoteOrcadMigrationCatalog -} = await import('./orcad-migration-catalog-client') -const { ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED } = - await import('./orcad-migration-request') - -const OPERATIONS = [ - stageRemoteOrcadMigrationCatalog, - commitRemoteOrcadMigrationCatalog, - readRemoteOrcadMigrationCatalogState, - abortRemoteOrcadMigrationCatalog -] - -function sshManifest(): OrcadMigrationManifest { - const unsigned = { - version: ORCAD_MIGRATION_MANIFEST_VERSION, - migrationId: 'migration-kind', - createdAt: '2026-10-01T00:00:00.000Z', - source: { sshTargetId: 'ssh-prod', sshTargetGeneration: 7, targetLabel: 'Production' }, - payload: { repositories: [], projectGroups: [], folderWorkspaces: [] } - } - return { ...unsigned, manifestSha256: computeOrcadMigrationManifestSha256(unsigned) } -} - -/** Include unknown wire kinds from newer or malformed peers. */ -function manifestOfKind(kind: string): OrcadMigrationManifest { - const source: OrcadMigrationManifest['source'] = { - kind: 'local-wsl', - distro: 'Ubuntu', - scopeRepoIds: [], - scopeFolderWorkspaceIds: [], - generation: 1 - } - Object.assign(source, { kind }) - return { ...sshManifest(), source } -} - -const pairingCode = encodePairingOffer({ - v: PAIRING_OFFER_VERSION, - endpoint: 'ws://127.0.0.1:46768/runtime', - deviceToken: 'device-token', - publicKeyB64: 'public-key', - pairedDeviceId: 'paired-desktop' -}) - -beforeEach(() => { - vi.clearAllMocks() - sendRequest.mockResolvedValue({ ok: false, error: { code: 'x', message: 'sent' } }) - status.capabilities = [ORCAD_MIGRATION_CATALOG_RUNTIME_CAPABILITY] -}) - -describe('orcad migration source-kind capability gate', () => { - it.each(OPERATIONS)('never sends a WSL manifest to an older destination', async (op) => { - await expect(op(pairingCode, manifestOfKind('local-wsl'))).rejects.toThrow( - ORCAD_MIGRATION_DESTINATION_SOURCE_KIND_UNSUPPORTED - ) - expect(sendRequest).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts index 82969e80fdd..a5539c049b7 100644 --- a/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts +++ b/src/main/managed-server/migration/catalog/orcad-migration-catalog-client.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationManifest } from '../../../../shared/orcad-migration/orcad-migration-manifest' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' import { encodePairingOffer } from '../../../../shared/remote-runtime/pairing/pairing' import { PAIRING_OFFER_VERSION } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' diff --git a/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts index a52afb6e458..fd8878d6c11 100644 --- a/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-cutover-fixture.ts @@ -1,6 +1,6 @@ import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationSourceCutover } from '../../../../../shared/orcad-migration/orcad-migration-source-cutover' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' export function orcadMigrationCutoverFixture( migrationId = 'migration-1', diff --git a/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts index f039e5abfbb..a28a2dbc602 100644 --- a/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts +++ b/src/main/managed-server/migration/cutover/testing/orcad-migration-destination-fake.ts @@ -4,8 +4,8 @@ import type { OrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest' import { parseOrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' -import { advertisedOrcadMigrationDestinationCapabilities } from '../../../../orcad/orcad-migration-destination-capabilities' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' +import { advertisedOrcadMigrationDestinationCapabilities } from '../../../../orcad/migration/orcad-migration-destination-capabilities' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { Store } from '../../../../persistence/loading-store/store' import type { OrcadMigrationDestinationCatalog } from '../orcad-migration-cutover-coordinator' diff --git a/src/main/orcad/orcad-account-services.ts b/src/main/orcad/account-launch/orcad-account-services.ts similarity index 76% rename from src/main/orcad/orcad-account-services.ts rename to src/main/orcad/account-launch/orcad-account-services.ts index ae8767016d3..65a2d7daf8e 100644 --- a/src/main/orcad/orcad-account-services.ts +++ b/src/main/orcad/account-launch/orcad-account-services.ts @@ -1,24 +1,24 @@ -import type { Store } from '../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { GetSelectedCodexHomePath, PrepareClaudeAuth, PrepareCodexSessionResume -} from '../ipc/pty/host-env/types' +} from '../../ipc/pty/host-env/types' import type { AiVaultPrepareSessionResumeArgs, AiVaultPrepareSessionResumeResult -} from '../../shared/ai-vault/resume/ai-vault-resume-preparation' -import type { ClaudeStatusLineRateLimits } from '../../shared/claude-statusline-rate-limits' -import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' -import { createProviderAccountServices } from '../providers/accounts/provider-account-services' -import { createCodexRuntimeHomeLaunchPreparation } from '../codex/configuration/homes/codex-runtime-home-launch-preparation' -import { createCodexSessionResumeLaunchPreparation } from '../codex/history/resume/codex-session-resume-launch-preparation' -import { prepareCodexAiVaultSessionResume } from '../codex/history/resume/codex-ai-vault-session-resume' -import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { resolveHostAgentBaseEnvironment } from '../runtime/agent-session/environment/structured-agent-shell-environment' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' +} from '../../../shared/ai-vault/resume/ai-vault-resume-preparation' +import type { ClaudeStatusLineRateLimits } from '../../../shared/claude-statusline-rate-limits' +import { resolveTuiAgentLaunchEnv } from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { createProviderAccountServices } from '../../providers/accounts/provider-account-services' +import { createCodexRuntimeHomeLaunchPreparation } from '../../codex/configuration/homes/codex-runtime-home-launch-preparation' +import { createCodexSessionResumeLaunchPreparation } from '../../codex/history/resume/codex-session-resume-launch-preparation' +import { prepareCodexAiVaultSessionResume } from '../../codex/history/resume/codex-ai-vault-session-resume' +import { resolveHostCodexSessionSourceHome } from '../../codex/history/rollouts/codex-session-source-home' +import { resolveHostAgentBaseEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import type { BackendServiceCleanup } from '../../backend/service-composition' type StructuredLaunchInput = { launchEnv: NodeJS.ProcessEnv } @@ -50,7 +50,7 @@ export function createOrcadAccountServices(args: { setClaudeStatusLineListener: ( listener: ((event: ClaudeStatusLineRateLimits) => void) | null ) => void - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void /** Client-provided account homes override host selection, as for PTYs. */ clientCodexHomes: { selectLaunchHome: GetSelectedCodexHomePath diff --git a/src/main/orcad/orcad-codex-account-homes.ts b/src/main/orcad/account-launch/orcad-codex-account-homes.ts similarity index 62% rename from src/main/orcad/orcad-codex-account-homes.ts rename to src/main/orcad/account-launch/orcad-codex-account-homes.ts index bc2c277c35c..4ddecf9c34e 100644 --- a/src/main/orcad/orcad-codex-account-homes.ts +++ b/src/main/orcad/account-launch/orcad-codex-account-homes.ts @@ -1,19 +1,19 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { isAgentStatusHooksEnabledForAgent } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { listGuestCodexAccountHomes, resolveGuestCodexAccountHome -} from '../codex-accounts/managed-homes/guest-codex-account-homes' -import { reconcileCodexAccountHomeHook } from '../codex/hooks/reconciliation/codex-account-home-hook' -import { stopCodexStateDbBackfillRecoveries } from '../codex/history/index/codex-state-db-backfill-recovery' -import type { GetSelectedCodexHomePath } from '../ipc/pty/host-env/types' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' +} from '../../codex-accounts/managed-homes/guest-codex-account-homes' +import { reconcileCodexAccountHomeHook } from '../../codex/hooks/reconciliation/codex-account-home-hook' +import { stopCodexStateDbBackfillRecoveries } from '../../codex/history/index/codex-state-db-backfill-recovery' +import type { GetSelectedCodexHomePath } from '../../ipc/pty/host-env/types' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import type { BackendServiceCleanup } from '../../backend/service-composition' /** Keep host status hooks and session discovery in client-selected managed CODEX_HOME paths. */ export function orcadCodexAccountHomes( getSettings: () => GlobalSettings, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void ) { registerCleanup(() => stopCodexStateDbBackfillRecoveries()) const selectLaunchHome: GetSelectedCodexHomePath = async (_target, launchEnv, context) => { diff --git a/src/main/orcad/orcad-host-account-launch-env-store.ts b/src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts similarity index 89% rename from src/main/orcad/orcad-host-account-launch-env-store.ts rename to src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts index dad560a016d..c533c91cfc2 100644 --- a/src/main/orcad/orcad-host-account-launch-env-store.ts +++ b/src/main/orcad/account-launch/orcad-host-account-launch-env-store.ts @@ -5,9 +5,9 @@ import { join } from 'node:path' import { HostAccountLaunchEnvParams, type HostAccountLaunchEnv -} from '../../shared/agent-launch/startup/host-account-launch-env' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +} from '../../../shared/agent-launch/startup/host-account-launch-env' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' import { createWslHostClaudeProfileRefresh } from './orcad-wsl-host-claude-profile-refresh' const FILE_NAME = 'host-account-launch-env.json' diff --git a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts b/src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts similarity index 84% rename from src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts rename to src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts index 008e92264da..f91a4b31a7a 100644 --- a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts +++ b/src/main/orcad/account-launch/orcad-wsl-host-claude-profile-refresh.ts @@ -6,11 +6,11 @@ import { existsSync } from 'node:fs' import { homedir } from 'node:os' import { posix } from 'node:path' -import type { HostAccountLaunchEnv } from '../../shared/agent-launch/startup/host-account-launch-env' -import { claudeProfileMarkerPath } from '../claude-accounts/profiles/claude-profile-paths' -import type { ClaudeProfileSetupReport } from '../claude-accounts/profiles/setup/claude-profile-setup' -import { wslClaudeProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-paths' -import { provisionWslClaudeAccountProfile } from '../claude-accounts/profiles/wsl/claude-profile-wsl-provision' +import type { HostAccountLaunchEnv } from '../../../shared/agent-launch/startup/host-account-launch-env' +import { claudeProfileMarkerPath } from '../../claude-accounts/profiles/claude-profile-paths' +import type { ClaudeProfileSetupReport } from '../../claude-accounts/profiles/setup/claude-profile-setup' +import { wslClaudeProfile } from '../../claude-accounts/profiles/wsl/claude-profile-wsl-paths' +import { provisionWslClaudeAccountProfile } from '../../claude-accounts/profiles/wsl/claude-profile-wsl-provision' /** The desktop router's cap: a slow refresh delays a launch this long, then runs alongside it. */ const REFRESH_WAIT_MS = 5_000 diff --git a/src/main/orcad/orcad-artifact-cache-retention.test.ts b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts similarity index 98% rename from src/main/orcad/orcad-artifact-cache-retention.test.ts rename to src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts index faa07750cee..083c3ad1f8f 100644 --- a/src/main/orcad/orcad-artifact-cache-retention.test.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.test.ts @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { pruneDesktopOrcadArtifactCache, pruneOrcadArtifactCache diff --git a/src/main/orcad/orcad-artifact-cache-retention.ts b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts similarity index 91% rename from src/main/orcad/orcad-artifact-cache-retention.ts rename to src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts index d50ff03fe6c..a2e75edc634 100644 --- a/src/main/orcad/orcad-artifact-cache-retention.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-cache-retention.ts @@ -2,12 +2,13 @@ // Unknown machine/boot ownership must preserve slots too. import { readdir, rm, stat } from 'node:fs/promises' import { join } from 'node:path' -import { nodeRuntimeAsset } from '../../shared/node-runtime-pin' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' -import { orcadPeerPidIsJudgeableHere } from './orcad-lock-holder-locality' +import { nodeRuntimeAsset } from '../../../shared/node-runtime-pin' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../instance-lock/orcad-instance-lock-record' +import { orcadPeerPidIsJudgeableHere } from '../instance-lock/orcad-lock-holder-locality' import { materializedOrcadArtifactVersions } from './orcad-artifact-materializer' import { orcadArtifactSlotVersion } from './orcad-artifact-slot-name' -import { isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' +import { isProcessAlive } from '../../daemon/endpoint/identity/daemon-process-inspection' import { defaultOrcadSlotPeerJudge, liveDaemonOrcadSlots, diff --git a/src/main/orcad/orcad-artifact-identity.ts b/src/main/orcad/artifact-slots/orcad-artifact-identity.ts similarity index 88% rename from src/main/orcad/orcad-artifact-identity.ts rename to src/main/orcad/artifact-slots/orcad-artifact-identity.ts index 7c916c8b671..cb7cdf90d72 100644 --- a/src/main/orcad/orcad-artifact-identity.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-identity.ts @@ -9,9 +9,9 @@ import { ORCAD_VERSION, orcadArtifactFilenames, orcadMobileWebAssetFilenames -} from '../../shared/orcad-artifacts' -import { COMPAT_SERVER_TARGETS, SERVER_TARGETS } from '../../shared/node-runtime-pin' -import { orcadAgentBrowserNativeName } from '../../shared/orcad-agent-browser-name' +} from '../../../shared/orcad-artifacts' +import { COMPAT_SERVER_TARGETS, SERVER_TARGETS } from '../../../shared/node-runtime-pin' +import { orcadAgentBrowserNativeName } from '../../../shared/orcad-agent-browser-name' /** Hash installed bytes in the build's order; a version marker is not proof of delivery. */ export async function readOrcadArtifactIdentity(directory: string): Promise { diff --git a/src/main/orcad/orcad-artifact-materializer.test.ts b/src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts similarity index 99% rename from src/main/orcad/orcad-artifact-materializer.test.ts rename to src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts index 7c676992b3b..c121fa928f5 100644 --- a/src/main/orcad/orcad-artifact-materializer.test.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-materializer.test.ts @@ -14,7 +14,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../shared/node-runtime-pin' +import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' import { ORCAD_MOBILE_WEB_MANIFEST, ORCAD_NODE_RUNTIME_MARKER_FILENAME, @@ -24,13 +24,13 @@ import { orcadRipgrepArtifact, orcadTemplateCommonFilenames, orcadTemplateTargetFilenames -} from '../../shared/orcad-artifacts' +} from '../../../shared/orcad-artifacts' import { getAppEnvironment, hasAppEnvironment, setAppEnvironment, type AppEnvironment -} from '../../shared/app-environment' +} from '../../../shared/app-environment' import { assembleOrcadArtifact, getOrcadTemplateCandidates, diff --git a/src/main/orcad/orcad-artifact-materializer.ts b/src/main/orcad/artifact-slots/orcad-artifact-materializer.ts similarity index 95% rename from src/main/orcad/orcad-artifact-materializer.ts rename to src/main/orcad/artifact-slots/orcad-artifact-materializer.ts index c04585a07a5..5301e22abc6 100644 --- a/src/main/orcad/orcad-artifact-materializer.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-materializer.ts @@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto' import { existsSync } from 'node:fs' import { chmod, copyFile, mkdir, readFile, rename, rm, utimes, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { getAppEnvironment } from '../../shared/app-environment' -import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason' +import { getAppEnvironment } from '../../../shared/app-environment' +import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { ORCAD_MOBILE_WEB_DIR, ORCAD_MOBILE_WEB_MANIFEST, @@ -18,10 +18,10 @@ import { orcadTemplateCommonFilenames, orcadTemplatePackagedRipgrep, orcadTemplateTargetFilenames -} from '../../shared/orcad-artifacts' -import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../shared/node-runtime-pin' -import { findOrcadCachePath } from '../node-runtime/orcad-cache-path' -import type { PinnedRuntimeMaterializeOptions } from '../node-runtime/pinned-runtime-materializer' +} from '../../../shared/orcad-artifacts' +import { pinnedNodeRuntimeAsset, type NodeRuntimeTarget } from '../../../shared/node-runtime-pin' +import { findOrcadCachePath } from '../../node-runtime/orcad-cache-path' +import type { PinnedRuntimeMaterializeOptions } from '../../node-runtime/pinned-runtime-materializer' import { readOrcadArtifactVerificationRecord } from './orcad-artifact-verification-record' import { orcadArtifactSlotName } from './orcad-artifact-slot-name' import { @@ -35,7 +35,10 @@ import { type ExpectedSha256 } from './orcad-artifact-source-verification' import { OrcadTemplateManifestSchema, type OrcadTemplateManifest } from './orcad-template-manifest' -import { OrcadArtifactsUnavailableError, OrcadHostUnsupportedError } from './orcad-host-unavailable' +import { + OrcadArtifactsUnavailableError, + OrcadHostUnsupportedError +} from '../diagnostics/orcad-host-unavailable' type MaterializeOptions = PinnedRuntimeMaterializeOptions & { templateDir?: string diff --git a/src/main/orcad/orcad-artifact-slot-name.ts b/src/main/orcad/artifact-slots/orcad-artifact-slot-name.ts similarity index 100% rename from src/main/orcad/orcad-artifact-slot-name.ts rename to src/main/orcad/artifact-slots/orcad-artifact-slot-name.ts diff --git a/src/main/orcad/orcad-artifact-source-verification.ts b/src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts similarity index 97% rename from src/main/orcad/orcad-artifact-source-verification.ts rename to src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts index 3e509060559..1995a3c29f1 100644 --- a/src/main/orcad/orcad-artifact-source-verification.ts +++ b/src/main/orcad/artifact-slots/orcad-artifact-source-verification.ts @@ -2,13 +2,13 @@ import { createHash, type Hash } from 'node:crypto' import { createReadStream } from 'node:fs' import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { ORCAD_VERSION, ORCAD_VERSION_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_VERSION, ORCAD_VERSION_FILENAME } from '../../../shared/orcad-artifacts' import { fileSignature, writeOrcadArtifactVerificationRecord, type OrcadArtifactVerificationRecord } from './orcad-artifact-verification-record' -import { fileSha256 } from '../node-runtime/pinned-runtime-materializer' +import { fileSha256 } from '../../node-runtime/pinned-runtime-materializer' export type ArtifactSource = { filename: string; path: string; executable?: boolean } export type ExpectedSha256 = { sha256: string; label: string } diff --git a/src/main/orcad/orcad-artifact-verification-record.ts b/src/main/orcad/artifact-slots/orcad-artifact-verification-record.ts similarity index 100% rename from src/main/orcad/orcad-artifact-verification-record.ts rename to src/main/orcad/artifact-slots/orcad-artifact-verification-record.ts diff --git a/src/main/orcad/orcad-daemon-slot-pins.ts b/src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts similarity index 87% rename from src/main/orcad/orcad-daemon-slot-pins.ts rename to src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts index 5ffcc927b0c..d000b610462 100644 --- a/src/main/orcad/orcad-daemon-slot-pins.ts +++ b/src/main/orcad/artifact-slots/orcad-daemon-slot-pins.ts @@ -1,14 +1,17 @@ // Daemons outlive instance locks; pin their entry/runtime slots separately. import { readdirSync, readFileSync } from 'node:fs' import { isAbsolute, join, relative, resolve, sep } from 'node:path' -import { parseDaemonPidFile } from '../daemon/endpoint/identity/daemon-pid-file-parse' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' +import { parseDaemonPidFile } from '../../daemon/endpoint/identity/daemon-pid-file-parse' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' import { currentOrcadPeerMachine, orcadPeerPidIsJudgeableHere, type OrcadPeerMachine -} from './orcad-lock-holder-locality' -import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' +} from '../instance-lock/orcad-lock-holder-locality' +import { orcadDataRootIsOnLocalDisk } from '../instance-lock/orcad-data-root-locality' export type OrcadSlotPeerJudge = { self: OrcadPeerMachine diff --git a/src/main/orcad/orcad-template-manifest.ts b/src/main/orcad/artifact-slots/orcad-template-manifest.ts similarity index 100% rename from src/main/orcad/orcad-template-manifest.ts rename to src/main/orcad/artifact-slots/orcad-template-manifest.ts diff --git a/src/main/orcad/external-chromium-browser-process.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts similarity index 92% rename from src/main/orcad/external-chromium-browser-process.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts index e170c0e50b4..5a9cf9fdeaa 100644 --- a/src/main/orcad/external-chromium-browser-process.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-process.ts @@ -1,14 +1,14 @@ import { z } from 'zod' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import { BrowserError } from '../browser/browser-error' -import { assertUploadFilesExist } from '../browser/cdp/input/browser-upload-files' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import type { RuntimeBrowserCommands } from '../../../runtime/browser/commands/browser-commands' +import { BrowserError } from '../../../browser/browser-error' +import { assertUploadFilesExist } from '../../../browser/cdp/input/browser-upload-files' import { agentBrowserEvalCommand, ExternalChromiumBrowserSession, type ExternalChromiumLaunch } from './external-chromium-browser-session' -import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import { externalChromiumCommandArguments, externalChromiumWaitCommand, @@ -20,9 +20,9 @@ import { } from './external-chromium-tab-projection' import { ExternalChromiumTabRegistry } from './external-chromium-tab-registry' import { runExternalChromiumPageInput, type PageInputSession } from './external-chromium-page-input' -import { agentBrowserSnapshotArgs } from '../browser/agent-browser/protocol/agent-browser-snapshot-arguments' -import { Snapshot } from '../../shared/rpc-contract/browser-observation-params' -import { ExpectedPageUrlGuard } from '../browser/cdp/input/browser-expected-page-url' +import { agentBrowserSnapshotArgs } from '../../../browser/agent-browser/protocol/agent-browser-snapshot-arguments' +import { Snapshot } from '../../../../shared/rpc-contract/browser-observation-params' +import { ExpectedPageUrlGuard } from '../../../browser/cdp/input/browser-expected-page-url' const AgentBrowserCurrentUrl = z.object({ url: z.string() }) diff --git a/src/main/orcad/external-chromium-browser-session.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts similarity index 85% rename from src/main/orcad/external-chromium-browser-session.test.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts index 1dd8d8a3459..144fd9edec3 100644 --- a/src/main/orcad/external-chromium-browser-session.test.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.test.ts @@ -16,7 +16,7 @@ vi.mock('node:fs/promises', () => ({ })) import { ExternalChromiumBrowserSession } from './external-chromium-browser-session' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../../../browser/agent-browser/testing/agent-browser-bridge-test-harness' const BASE = { executablePath: '/opt/orca/chromium', @@ -100,13 +100,4 @@ describe('orcad external-chromium agent-browser environment', () => { message: expect.stringContaining('--no-sandbox') }) }) - - it("keeps Chromium's own explanation when another process holds the profile", async () => { - const inUse = - 'The profile appears to be in use by another Chromium process (4242) on another computer (build-box).\n' + - 'Failed to create a ProcessSingleton for your profile directory.' - await expect(startFailingOpen(inUse)).rejects.toMatchObject({ - message: expect.stringContaining('in use by another Chromium process (4242)') - }) - }) }) diff --git a/src/main/orcad/external-chromium-browser-session.ts b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts similarity index 96% rename from src/main/orcad/external-chromium-browser-session.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts index 364a6edad00..b338ca55440 100644 --- a/src/main/orcad/external-chromium-browser-session.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-browser-session.ts @@ -2,19 +2,19 @@ import { createHash, randomUUID } from 'node:crypto' import { chmod, mkdir, readFile, rm } from 'node:fs/promises' import { join } from 'node:path' import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' +import { BrowserError } from '../../../browser/browser-error' import { AGENT_BROWSER_BATCH_ARGS, agentBrowserBatchInput, isAgentBrowserStaleRefError, parseAgentBrowserJsonOutput -} from '../browser/agent-browser/protocol/agent-browser-batch-command' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { Screenshot } from '../../shared/rpc-contract/browser-observation-params' +} from '../../../browser/agent-browser/protocol/agent-browser-batch-command' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-session-contracts' +import { Screenshot } from '../../../../shared/rpc-contract/browser-observation-params' import { agentBrowserScreenshotArgs, readAgentBrowserScreenshot -} from '../browser/agent-browser/observation/agent-browser-screenshot-arguments' +} from '../../../browser/agent-browser/observation/agent-browser-screenshot-arguments' import { runProcess } from '@orca/process-host' import { resolveExternalChromiumProfilePath } from './external-chromium-profile-path' diff --git a/src/main/orcad/external-chromium-command-arguments.ts b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts similarity index 96% rename from src/main/orcad/external-chromium-command-arguments.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts index e3ff45e5a45..8f7fa05b8d7 100644 --- a/src/main/orcad/external-chromium-command-arguments.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-command-arguments.ts @@ -1,6 +1,6 @@ -import { BrowserError } from '../browser/browser-error' -import { agentBrowserSetMediaArguments } from '../browser/agent-browser/protocol/agent-browser-set-media-arguments' -import { agentBrowserWaitArguments } from '../browser/agent-browser/protocol/agent-browser-wait-arguments' +import { BrowserError } from '../../../browser/browser-error' +import { agentBrowserSetMediaArguments } from '../../../browser/agent-browser/protocol/agent-browser-set-media-arguments' +import { agentBrowserWaitArguments } from '../../../browser/agent-browser/protocol/agent-browser-wait-arguments' const TARGET_OVERRIDE_FLAGS: Record = { '--args': true, '--cdp': true, diff --git a/src/main/orcad/external-chromium-page-input.ts b/src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts similarity index 96% rename from src/main/orcad/external-chromium-page-input.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts index 2485783a6fc..849fe21a5e9 100644 --- a/src/main/orcad/external-chromium-page-input.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-page-input.ts @@ -1,13 +1,13 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import { assertClipboardTextWriteWithinLimitWithYield } from '../../shared/clipboard-text' -import { BrowserError } from '../browser/browser-error' +import { assertClipboardTextWriteWithinLimitWithYield } from '../../../../shared/clipboard-text' +import { BrowserError } from '../../../browser/browser-error' import { FILL_ELEMENT_FUNCTION, SELECT_ALL_ELEMENT_FUNCTION, SELECT_OPTION_TARGET_FUNCTION -} from '../browser/cdp/input/browser-element-functions' -import { typedInputSteps } from '../browser/cdp/input/cdp-keyboard-us-layout' +} from '../../../browser/cdp/input/browser-element-functions' +import { typedInputSteps } from '../../../browser/cdp/input/cdp-keyboard-us-layout' import { agentBrowserError, agentBrowserEvalCommand, diff --git a/src/main/orcad/external-chromium-profile-path.test.ts b/src/main/orcad/browser-providers/chromium/external-chromium-profile-path.test.ts similarity index 100% rename from src/main/orcad/external-chromium-profile-path.test.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-profile-path.test.ts diff --git a/src/main/orcad/external-chromium-profile-path.ts b/src/main/orcad/browser-providers/chromium/external-chromium-profile-path.ts similarity index 100% rename from src/main/orcad/external-chromium-profile-path.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-profile-path.ts diff --git a/src/main/orcad/external-chromium-tab-projection.ts b/src/main/orcad/browser-providers/chromium/external-chromium-tab-projection.ts similarity index 100% rename from src/main/orcad/external-chromium-tab-projection.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-tab-projection.ts diff --git a/src/main/orcad/external-chromium-tab-registry.ts b/src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts similarity index 97% rename from src/main/orcad/external-chromium-tab-registry.ts rename to src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts index 35ae649067a..00f542b8ef2 100644 --- a/src/main/orcad/external-chromium-tab-registry.ts +++ b/src/main/orcad/browser-providers/chromium/external-chromium-tab-registry.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { z } from 'zod' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import { BrowserError } from '../browser/browser-error' -import { normalizeBrowserNavigationUrl } from '../../shared/browser-url' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import { BrowserError } from '../../../browser/browser-error' +import { normalizeBrowserNavigationUrl } from '../../../../shared/browser-url' import type { ExternalChromiumBrowserSession } from './external-chromium-browser-session' import { externalChromiumTabInfo, diff --git a/src/main/orcad/electron-serve-browser-environment.ts b/src/main/orcad/browser-providers/electron/electron-serve-browser-environment.ts similarity index 100% rename from src/main/orcad/electron-serve-browser-environment.ts rename to src/main/orcad/browser-providers/electron/electron-serve-browser-environment.ts diff --git a/src/main/orcad/electron-serve-browser-process.ts b/src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts similarity index 88% rename from src/main/orcad/electron-serve-browser-process.ts rename to src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts index c54a8b0f929..f295d87085b 100644 --- a/src/main/orcad/electron-serve-browser-process.ts +++ b/src/main/orcad/browser-providers/electron/electron-serve-browser-process.ts @@ -1,28 +1,28 @@ import { BROWSER_EXPECT_URL_RUNTIME_CAPABILITY, BROWSER_GOOGLE_COOKIE_CLEAR_CAPABILITY -} from '../../shared/browser/runtime/browser-runtime-capabilities' +} from '../../../../shared/browser/runtime/browser-runtime-capabilities' import { BROWSER_EXPECT_URL_UNSUPPORTED_CODE, BrowserExpectedUrlMismatch -} from '../../shared/browser/client-hosting/browser-expected-url' -import { browserExpectedUrlMismatchError } from '../browser/cdp/input/browser-expected-page-url' +} from '../../../../shared/browser/client-hosting/browser-expected-url' +import { browserExpectedUrlMismatchError } from '../../../browser/cdp/input/browser-expected-page-url' import { setTimeout as delay } from 'node:timers/promises' import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import type { RuntimeMetadata } from '../../shared/runtime-bootstrap' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { readRuntimeMetadata } from '../runtime/rpc/server/runtime-metadata' +import { BrowserError } from '../../../browser/browser-error' +import type { RuntimeBrowserCommandHost } from '../../../runtime/browser/commands/browser-command-contracts' +import type { RuntimeBrowserCommands } from '../../../runtime/browser/commands/browser-commands' +import type { RuntimeMetadata } from '../../../../shared/runtime-bootstrap' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-session-contracts' +import { readRuntimeMetadata } from '../../../runtime/rpc/server/runtime-metadata' import { spawnProcess } from '@orca/process-host' -import { isProcessAlive } from '../../shared/serve-bundle-coordination' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { BROWSER_SIDECAR_OWNER_ENV } from '../../shared/browser-sidecar-lifetime' -import { electronIsolatedProfileSwitches } from '../../shared/electron-isolated-profile-switches' -import { headlessServeOzonePlatformSwitches } from '../../shared/headless-serve-ozone-platform' -import { sendOrcadSidecarRequest } from './orcad-sidecar-runtime-client' -import { browserWaitRequestTimeoutMs } from '../../shared/browser-wait-timeout' +import { isProcessAlive } from '../../../../shared/serve-bundle-coordination' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { BROWSER_SIDECAR_OWNER_ENV } from '../../../../shared/browser-sidecar-lifetime' +import { electronIsolatedProfileSwitches } from '../../../../shared/electron-isolated-profile-switches' +import { headlessServeOzonePlatformSwitches } from '../../../../shared/headless-serve-ozone-platform' +import { sendOrcadSidecarRequest } from '../orcad-sidecar-runtime-client' +import { browserWaitRequestTimeoutMs } from '../../../../shared/browser-wait-timeout' import { electronServeEnvironment } from './electron-serve-browser-environment' import { reserveLoopbackPort } from './loopback-port-reservation' import { diff --git a/src/main/orcad/electron-sidecar-method-routing.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-method-routing.ts similarity index 100% rename from src/main/orcad/electron-sidecar-method-routing.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-method-routing.ts diff --git a/src/main/orcad/electron-sidecar-profile.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts similarity index 87% rename from src/main/orcad/electron-sidecar-profile.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts index 234d1d55dd1..53fe86bbc35 100644 --- a/src/main/orcad/electron-sidecar-profile.ts +++ b/src/main/orcad/browser-providers/electron/electron-sidecar-profile.ts @@ -3,12 +3,12 @@ import { tmpdir } from 'node:os' import { basename, join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { z } from 'zod' -import { isSafeOwnedDirectory } from '../../shared/owned-private-directory' -import { isProcessAlive } from '../../shared/serve-bundle-coordination' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { isDirectChild } from '../filesystem/owned-temp-staging-root' -import { readRuntimeMetadataAsync } from '../runtime/rpc/server/runtime-metadata' -import { sendOrcadSidecarRequest } from './orcad-sidecar-runtime-client' +import { isSafeOwnedDirectory } from '../../../../shared/owned-private-directory' +import { isProcessAlive } from '../../../../shared/serve-bundle-coordination' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { isDirectChild } from '../../../filesystem/owned-temp-staging-root' +import { readRuntimeMetadataAsync } from '../../../runtime/rpc/server/runtime-metadata' +import { sendOrcadSidecarRequest } from '../orcad-sidecar-runtime-client' const STOP_TIMEOUT_MS = 5_000 const ORPHAN_PROBE_TIMEOUT_MS = 2_000 diff --git a/src/main/orcad/electron-sidecar-tab-registry.test.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts similarity index 100% rename from src/main/orcad/electron-sidecar-tab-registry.test.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.test.ts diff --git a/src/main/orcad/electron-sidecar-tab-registry.ts b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts similarity index 99% rename from src/main/orcad/electron-sidecar-tab-registry.ts rename to src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts index 02b8dbf048e..f10deaf9cf9 100644 --- a/src/main/orcad/electron-sidecar-tab-registry.ts +++ b/src/main/orcad/browser-providers/electron/electron-sidecar-tab-registry.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { BrowserError } from '../browser/browser-error' +import { BrowserError } from '../../../browser/browser-error' const CertificateFailure = z .object({ browserPageId: z.string() }) diff --git a/src/main/orcad/loopback-port-reservation.ts b/src/main/orcad/browser-providers/electron/loopback-port-reservation.ts similarity index 100% rename from src/main/orcad/loopback-port-reservation.ts rename to src/main/orcad/browser-providers/electron/loopback-port-reservation.ts diff --git a/src/main/orcad/orcad-agent-browser-binary.ts b/src/main/orcad/browser-providers/orcad-agent-browser-binary.ts similarity index 85% rename from src/main/orcad/orcad-agent-browser-binary.ts rename to src/main/orcad/browser-providers/orcad-agent-browser-binary.ts index c8e8e7261fe..abe55a5e455 100644 --- a/src/main/orcad/orcad-agent-browser-binary.ts +++ b/src/main/orcad/browser-providers/orcad-agent-browser-binary.ts @@ -1,8 +1,8 @@ import { accessSync, constants, existsSync } from 'node:fs' import { arch, platform } from 'node:os' import { dirname, join } from 'node:path' -import { orcadAgentBrowserNativeName } from '../../shared/orcad-agent-browser-name' -import { ensureDependencyBinaryExecutable } from '../browser/agent-browser/helper-process/agent-browser-dependency-binary' +import { orcadAgentBrowserNativeName } from '../../../shared/orcad-agent-browser-name' +import { ensureDependencyBinaryExecutable } from '../../browser/agent-browser/helper-process/agent-browser-dependency-binary' /** A slot carries only its own target's driver, so trying both libc names needs no libc probe. */ function hostDriverNames(): string[] { diff --git a/src/main/orcad/orcad-browser-install-park.ts b/src/main/orcad/browser-providers/orcad-browser-install-park.ts similarity index 98% rename from src/main/orcad/orcad-browser-install-park.ts rename to src/main/orcad/browser-providers/orcad-browser-install-park.ts index 32c66dca1d6..7b31c97b744 100644 --- a/src/main/orcad/orcad-browser-install-park.ts +++ b/src/main/orcad/browser-providers/orcad-browser-install-park.ts @@ -1,8 +1,8 @@ import { ORCAD_BROWSER_PARK_LABEL, SERVE_SUPERVISOR_HEARTBEAT_MS -} from '../../shared/serve-bundle-coordination' -import { openServeBundlePark, type ServeBundlePark } from '../../shared/serve-bundle-park' +} from '../../../shared/serve-bundle-coordination' +import { openServeBundlePark, type ServeBundlePark } from '../../../shared/serve-bundle-park' const PARK_POLL_MS = 1_000 const RESTART_RETRY_MIN_MS = 5_000 diff --git a/src/main/orcad/orcad-browser-provider.test.ts b/src/main/orcad/browser-providers/orcad-browser-provider.test.ts similarity index 96% rename from src/main/orcad/orcad-browser-provider.test.ts rename to src/main/orcad/browser-providers/orcad-browser-provider.test.ts index a24452e201c..7a503fd5ef6 100644 --- a/src/main/orcad/orcad-browser-provider.test.ts +++ b/src/main/orcad/browser-providers/orcad-browser-provider.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' +import { agentBrowserCommandOf } from '../../browser/agent-browser/testing/agent-browser-bridge-test-harness' import { resolveInstalledElectronExecutable, resolveOrcadBrowserProvider @@ -11,7 +11,7 @@ import { import { runtimeBrowserUnavailableCause, setRuntimeBrowserUnavailableCause -} from '../runtime/browser/installation/runtime-browser-commands-factory' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' vi.mock('@orca/process-host', () => ({ runProcess: vi.fn(), diff --git a/src/main/orcad/orcad-browser-provider.ts b/src/main/orcad/browser-providers/orcad-browser-provider.ts similarity index 95% rename from src/main/orcad/orcad-browser-provider.ts rename to src/main/orcad/browser-providers/orcad-browser-provider.ts index cf03c41c2e5..5f0723d7b72 100644 --- a/src/main/orcad/orcad-browser-provider.ts +++ b/src/main/orcad/browser-providers/orcad-browser-provider.ts @@ -6,13 +6,13 @@ import { setRuntimeBrowserUnavailableCause, type RuntimeBrowserCommandsFactory, type RuntimeBrowserUnavailableCause -} from '../runtime/browser/installation/runtime-browser-commands-factory' -import { ExternalChromiumBrowserProcess } from './external-chromium-browser-process' -import type { ExternalChromiumLaunch } from './external-chromium-browser-session' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { ExternalChromiumBrowserProcess } from './chromium/external-chromium-browser-process' +import type { ExternalChromiumLaunch } from './chromium/external-chromium-browser-session' import { resolveOrcadAgentBrowserBinary } from './orcad-agent-browser-binary' -import { ElectronServeBrowserProcess } from './electron-serve-browser-process' +import { ElectronServeBrowserProcess } from './electron/electron-serve-browser-process' import { openOrcadBrowserInstallPark } from './orcad-browser-install-park' -import { errorMessage } from '../../shared/error-message' +import { errorMessage } from '../../../shared/error-message' export type OrcadBrowserProvider = { kind: 'electron' | 'chromium' diff --git a/src/main/orcad/orcad-browser-startup.ts b/src/main/orcad/browser-providers/orcad-browser-startup.ts similarity index 90% rename from src/main/orcad/orcad-browser-startup.ts rename to src/main/orcad/browser-providers/orcad-browser-startup.ts index a0aef4d2d57..0542e657420 100644 --- a/src/main/orcad/orcad-browser-startup.ts +++ b/src/main/orcad/browser-providers/orcad-browser-startup.ts @@ -1,10 +1,10 @@ -import { BrowserError } from '../browser/browser-error' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' +import { BrowserError } from '../../browser/browser-error' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../shared/runtime-session-contracts' +import type { RuntimeBrowserCommands } from '../../runtime/browser/commands/browser-commands' import { browserUnavailableError, setRuntimeBrowserCommandsFactory -} from '../runtime/browser/installation/runtime-browser-commands-factory' +} from '../../runtime/browser/installation/runtime-browser-commands-factory' import { resolveOrcadBrowserProvider, type OrcadBrowserProvider, diff --git a/src/main/orcad/orcad-client-page-commands.ts b/src/main/orcad/browser-providers/orcad-client-page-commands.ts similarity index 89% rename from src/main/orcad/orcad-client-page-commands.ts rename to src/main/orcad/browser-providers/orcad-client-page-commands.ts index 11e8e8e4a1e..762c22f5fff 100644 --- a/src/main/orcad/orcad-client-page-commands.ts +++ b/src/main/orcad/browser-providers/orcad-client-page-commands.ts @@ -1,19 +1,19 @@ // Paired desktops can host pages without a local engine; present engine and desktop pages as one tab list. -import { BrowserError } from '../browser/browser-error' -import type { RuntimeBrowserCommands } from '../runtime/browser/commands/browser-commands' -import type { RuntimeBrowserCommandHost } from '../runtime/browser/commands/browser-command-contracts' +import { BrowserError } from '../../browser/browser-error' +import type { RuntimeBrowserCommands } from '../../runtime/browser/commands/browser-commands' +import type { RuntimeBrowserCommandHost } from '../../runtime/browser/commands/browser-command-contracts' import type { BrowserTabListResult, BrowserTabShowResult, BrowserTabSwitchResult -} from '../../shared/browser/runtime/runtime-browser-contracts' -import { browserUnavailableError } from '../runtime/browser/installation/runtime-browser-commands-factory' -import { browserTabCreateClientPageStartsActive } from '../runtime/browser/tabs/browser-tab-create-publication' +} from '../../../shared/browser/runtime/runtime-browser-contracts' +import { browserUnavailableError } from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { browserTabCreateClientPageStartsActive } from '../../runtime/browser/tabs/browser-tab-create-publication' import { closeBrowserPageWithoutEngine, resolveClientPageToClose, retireRuntimeBrowserClientPage -} from '../runtime/browser/client-pages/browser-client-page-close' +} from '../../runtime/browser/client-pages/browser-client-page-close' import { canPlacePairedPage, createBrowserClientPage, @@ -21,17 +21,17 @@ import { DEFAULT_BROWSER_PROFILE_ID, hasPairedPageHost, openBrowserUrlOnClient -} from '../runtime/browser/client-pages/browser-client-page-opening' +} from '../../runtime/browser/client-pages/browser-client-page-opening' import { BrowserClientPageQueries, yieldClientPageSelection, type BrowserEngineTabs -} from '../runtime/browser/client-pages/browser-client-page-queries' +} from '../../runtime/browser/client-pages/browser-client-page-queries' import { findListedBrowserTab, readBrowserTabAnnotations -} from '../runtime/browser/tabs/browser-tab-annotations' +} from '../../runtime/browser/tabs/browser-tab-annotations' type Forward = (args: unknown[], name?: string) => unknown diff --git a/src/main/orcad/orcad-sidecar-runtime-client.ts b/src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts similarity index 92% rename from src/main/orcad/orcad-sidecar-runtime-client.ts rename to src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts index 9e8b832f590..8cb6a02084d 100644 --- a/src/main/orcad/orcad-sidecar-runtime-client.ts +++ b/src/main/orcad/browser-providers/orcad-sidecar-runtime-client.ts @@ -1,10 +1,10 @@ import { randomUUID } from 'node:crypto' import { createConnection } from 'node:net' import { z } from 'zod' -import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap' -import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../shared/runtime-types' -import { BrowserError } from '../browser/browser-error' -import { daemonSocketDirIsTrusted } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' +import { findTransport, type RuntimeMetadata } from '../../../shared/runtime-bootstrap' +import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../shared/runtime-session-contracts' +import { BrowserError } from '../../browser/browser-error' +import { daemonSocketDirIsTrusted } from '../../daemon/endpoint/publication/daemon-socket-endpoint-path' const SIDECAR_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 const RuntimeResponse = z.discriminatedUnion('ok', [ diff --git a/src/main/orcad/orcad-legacy-keyring-key.ts b/src/main/orcad/credentials/orcad-legacy-keyring-key.ts similarity index 100% rename from src/main/orcad/orcad-legacy-keyring-key.ts rename to src/main/orcad/credentials/orcad-legacy-keyring-key.ts diff --git a/src/main/orcad/orcad-plaintext-credential-migration.test.ts b/src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts similarity index 96% rename from src/main/orcad/orcad-plaintext-credential-migration.test.ts rename to src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts index 658dec396bb..d47691a4db1 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.test.ts +++ b/src/main/orcad/credentials/orcad-plaintext-credential-migration.test.ts @@ -2,9 +2,9 @@ import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { SecretStore } from '../../shared/secret-store' -import { _resetSecretStoreForTests, setSecretStore } from '../../shared/secret-store' -import { readStoredCredentialToken } from '../credentials/integration-credential-file' +import type { SecretStore } from '../../../shared/secret-store' +import { _resetSecretStoreForTests, setSecretStore } from '../../../shared/secret-store' +import { readStoredCredentialToken } from '../../credentials/integration-credential-file' import { migratePlaintextCredentials } from './orcad-plaintext-credential-migration' import { orcadSecretStateFileName } from './orcad-secret-key-record' import { createOrcadSecretStore } from './orcad-secret-store' diff --git a/src/main/orcad/orcad-plaintext-credential-migration.ts b/src/main/orcad/credentials/orcad-plaintext-credential-migration.ts similarity index 79% rename from src/main/orcad/orcad-plaintext-credential-migration.ts rename to src/main/orcad/credentials/orcad-plaintext-credential-migration.ts index cd4e990fc52..aab696fa158 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.ts +++ b/src/main/orcad/credentials/orcad-plaintext-credential-migration.ts @@ -2,23 +2,29 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' -import type { SecretStore } from '../../shared/secret-store' -import { classifyUnenvelopedCredential } from '../../shared/secret-at-rest-protection' -import { hardenExistingSecureFile, writeSecureFile } from '../../shared/secure-storage/secure-file' -import { writeCredentialFileAtomic } from '../credentials/integration-credential-file' +import type { SecretStore } from '../../../shared/secret-store' +import { classifyUnenvelopedCredential } from '../../../shared/secret-at-rest-protection' +import { + hardenExistingSecureFile, + writeSecureFile +} from '../../../shared/secure-storage/secure-file' +import { writeCredentialFileAtomic } from '../../credentials/integration-credential-file' import { getWorkspaceTokenDir, getWorkspaceTokenPath, LEGACY_WORKSPACE_ID -} from '../linear/accounts/linear-credential-paths' -import { getTokenDir as getJiraTokenDir } from '../jira/site-credential-store' -import { getSecretPath as getBitbucketSecretPath } from '../bitbucket/credential-store' -import { getOpenAiKeyPath } from '../speech/openai-api-key-store' -import { API_KEY_ENVELOPE_PREFIX, getZcodePlanApiKeyPath } from '../zcode/zcode-plan-api-key-store' -import { COOKIE_ENVELOPE_PREFIX, getMiniMaxCookiePath } from '../minimax/minimax-cookie-store' -import { miniMaxApiKeyEnvelopeFile } from '../minimax/minimax-api-key-store' -import { openCodeGoApiKeyEnvelopeFile } from '../opencode/accounts/opencode-go-api-key-store' -import { openAiCompatibleSpeechProviderEnvelopeFile } from '../speech/openai-compatible-speech-provider-store' +} from '../../linear/accounts/linear-credential-paths' +import { getTokenDir as getJiraTokenDir } from '../../jira/site-credential-store' +import { getSecretPath as getBitbucketSecretPath } from '../../bitbucket/credential-store' +import { getOpenAiKeyPath } from '../../speech/openai-api-key-store' +import { + API_KEY_ENVELOPE_PREFIX, + getZcodePlanApiKeyPath +} from '../../zcode/zcode-plan-api-key-store' +import { COOKIE_ENVELOPE_PREFIX, getMiniMaxCookiePath } from '../../minimax/minimax-cookie-store' +import { miniMaxApiKeyEnvelopeFile } from '../../minimax/minimax-api-key-store' +import { openCodeGoApiKeyEnvelopeFile } from '../../opencode/accounts/opencode-go-api-key-store' +import { openAiCompatibleSpeechProviderEnvelopeFile } from '../../speech/openai-compatible-speech-provider-store' type PlaintextCredentialTarget = { path: string diff --git a/src/main/orcad/orcad-secret-key-record.ts b/src/main/orcad/credentials/orcad-secret-key-record.ts similarity index 95% rename from src/main/orcad/orcad-secret-key-record.ts rename to src/main/orcad/credentials/orcad-secret-key-record.ts index 680d1384fe0..4b35018b2aa 100644 --- a/src/main/orcad/orcad-secret-key-record.ts +++ b/src/main/orcad/credentials/orcad-secret-key-record.ts @@ -16,11 +16,14 @@ import { bestEffortFsyncDirectorySync, hardenExistingSecureFile, writeSecureFile -} from '../../shared/secure-storage/secure-file' -import { restrictWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl' +} from '../../../shared/secure-storage/secure-file' +import { restrictWindowsFile } from '../../../shared/secure-storage/secure-path-windows-acl' import { ORCAD_MASTER_KEY_BYTES } from './orcad-secret-sealing' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' -import { errorMessage } from '../../shared/error-message' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' +import { errorMessage } from '../../../shared/error-message' // Read legacy keyring records only for migration. export type StoredKeyState = diff --git a/src/main/orcad/orcad-secret-key-resolution.ts b/src/main/orcad/credentials/orcad-secret-key-resolution.ts similarity index 97% rename from src/main/orcad/orcad-secret-key-resolution.ts rename to src/main/orcad/credentials/orcad-secret-key-resolution.ts index 16945c2e50b..314386381ad 100644 --- a/src/main/orcad/orcad-secret-key-resolution.ts +++ b/src/main/orcad/credentials/orcad-secret-key-resolution.ts @@ -1,8 +1,8 @@ import { randomBytes } from 'node:crypto' import { join } from 'node:path' import process from 'node:process' -import { withFileTransactionLock } from '../filesystem/file-transaction-lock' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { withFileTransactionLock } from '../../filesystem/file-transaction-lock' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { resolveOrcadLegacyKeyringReader, type OrcadLegacyKeyringReader diff --git a/src/main/orcad/orcad-secret-protection-gap.ts b/src/main/orcad/credentials/orcad-secret-protection-gap.ts similarity index 100% rename from src/main/orcad/orcad-secret-protection-gap.ts rename to src/main/orcad/credentials/orcad-secret-protection-gap.ts diff --git a/src/main/orcad/orcad-secret-sealing.ts b/src/main/orcad/credentials/orcad-secret-sealing.ts similarity index 100% rename from src/main/orcad/orcad-secret-sealing.ts rename to src/main/orcad/credentials/orcad-secret-sealing.ts diff --git a/src/main/orcad/orcad-secret-store-startup.ts b/src/main/orcad/credentials/orcad-secret-store-startup.ts similarity index 68% rename from src/main/orcad/orcad-secret-store-startup.ts rename to src/main/orcad/credentials/orcad-secret-store-startup.ts index d8247da1754..83d0b77b8b6 100644 --- a/src/main/orcad/orcad-secret-store-startup.ts +++ b/src/main/orcad/credentials/orcad-secret-store-startup.ts @@ -1,9 +1,9 @@ import { join } from 'node:path' -import { prepareOrcadSecretStore } from './orcad-host-adapters' +import { prepareOrcadSecretStore } from '../host-runtime/orcad-host-adapters' export async function prepareOrcadSecretStoreAndMigrate(userDataPath: string): Promise { - const { getSecretStore } = await import('../../shared/secret-store') - const { reportSecretProtectionGap } = await import('../host/secret-protection-report') + const { getSecretStore } = await import('../../../shared/secret-store') + const { reportSecretProtectionGap } = await import('../../host/secret-protection-report') const { migratePlaintextCredentials, orcadCredentialRoot } = await import('./orcad-plaintext-credential-migration') // Keep sealing keys outside disposable ORCA_USER_DATA roots. diff --git a/src/main/orcad/orcad-secret-store.test.ts b/src/main/orcad/credentials/orcad-secret-store.test.ts similarity index 98% rename from src/main/orcad/orcad-secret-store.test.ts rename to src/main/orcad/credentials/orcad-secret-store.test.ts index c37a8f5d6ba..5f773aa4294 100644 --- a/src/main/orcad/orcad-secret-store.test.ts +++ b/src/main/orcad/credentials/orcad-secret-store.test.ts @@ -10,7 +10,7 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _resetSecretStoreForTests } from '../../shared/secret-store' +import { _resetSecretStoreForTests } from '../../../shared/secret-store' import type { OrcadLegacyKeyringReader } from './orcad-legacy-keyring-key' import { orcadSecretStateFileName } from './orcad-secret-key-record' import { createOrcadSecretStore } from './orcad-secret-store' diff --git a/src/main/orcad/orcad-secret-store.ts b/src/main/orcad/credentials/orcad-secret-store.ts similarity index 96% rename from src/main/orcad/orcad-secret-store.ts rename to src/main/orcad/credentials/orcad-secret-store.ts index 9a63a7a01c9..0e62a7b30e9 100644 --- a/src/main/orcad/orcad-secret-store.ts +++ b/src/main/orcad/credentials/orcad-secret-store.ts @@ -1,5 +1,5 @@ // Always report available to prevent plaintext fallback; throw on seal/unseal when the key is unavailable. -import type { SecretStore } from '../../shared/secret-store' +import type { SecretStore } from '../../../shared/secret-store' import { sweepStaleRecordStaging } from './orcad-secret-key-record' import { orcadSecretStatePath, diff --git a/src/main/orcad/orcad-daemon-retirement.ts b/src/main/orcad/daemon/orcad-daemon-retirement.ts similarity index 87% rename from src/main/orcad/orcad-daemon-retirement.ts rename to src/main/orcad/daemon/orcad-daemon-retirement.ts index d68b9648766..633619ec675 100644 --- a/src/main/orcad/orcad-daemon-retirement.ts +++ b/src/main/orcad/daemon/orcad-daemon-retirement.ts @@ -4,11 +4,11 @@ import { listLiveDaemonSessions, releaseDaemonRetirementFence, requestIdleDaemonRetirement -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { DaemonIdleRetirementResult } from '../daemon/providers/adapter/daemon-pty-runtime-state' -import type { OrcadDaemonRetirementVerdict } from '../../shared/orcad-stop-request' -import { withTimeout } from '../../shared/promise-timeout-fallback' -import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from './orcad-stop-deadlines' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { DaemonIdleRetirementResult } from '../../daemon/providers/adapter/daemon-pty-runtime-state' +import type { OrcadDaemonRetirementVerdict } from '../../../shared/orcad-stop-request' +import { withTimeout } from '../../../shared/promise-timeout-fallback' +import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from '../host-lifecycle/managed-stop/orcad-stop-deadlines' export type OrcadDaemonRetirement = { retirement: OrcadDaemonRetirementVerdict diff --git a/src/main/orcad/orcad-daemon-supervision.test.ts b/src/main/orcad/daemon/orcad-daemon-supervision.test.ts similarity index 79% rename from src/main/orcad/orcad-daemon-supervision.test.ts rename to src/main/orcad/daemon/orcad-daemon-supervision.test.ts index cf455e9623d..ed866214056 100644 --- a/src/main/orcad/orcad-daemon-supervision.test.ts +++ b/src/main/orcad/daemon/orcad-daemon-supervision.test.ts @@ -1,15 +1,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const initDaemonPtyProvider = vi.hoisted(() => vi.fn()) -vi.mock('../daemon/providers/lifecycle/daemon-provider-init', () => ({ initDaemonPtyProvider })) +vi.mock('../../daemon/providers/lifecycle/daemon-provider-init', () => ({ initDaemonPtyProvider })) import { startOrcadDaemon } from './orcad-daemon-supervision' -import { OrcadTerminalsNotDurableError } from './orcad-serve-supervision' -import { resolveOrcadExitCode } from './orcad-exit-code' +import { OrcadTerminalsNotDurableError } from '../serve-startup/orcad-serve-supervision' +import { resolveOrcadExitCode } from '../serve-startup/orcad-exit-code' import { ORCA_SERVE_SUPERVISED_ENV, ORCAD_EXIT_TERMINALS_NOT_DURABLE -} from '../../shared/serve-supervised-terminal-durability' +} from '../../../shared/serve-supervised-terminal-durability' afterEach(() => { vi.restoreAllMocks() diff --git a/src/main/orcad/orcad-daemon-supervision.ts b/src/main/orcad/daemon/orcad-daemon-supervision.ts similarity index 85% rename from src/main/orcad/orcad-daemon-supervision.ts rename to src/main/orcad/daemon/orcad-daemon-supervision.ts index 4c1e48f78cd..a3cd51dba92 100644 --- a/src/main/orcad/orcad-daemon-supervision.ts +++ b/src/main/orcad/daemon/orcad-daemon-supervision.ts @@ -3,11 +3,14 @@ import { disconnectDaemon, daemonOwnsFreshPersistentPtys, readDaemonPidRecord -} from '../daemon/providers/lifecycle/daemon-provider-state' -import { initDaemonPtyProvider } from '../daemon/providers/lifecycle/daemon-provider-init' -import { resolveTerminalSpawnAdmissionMode } from '../daemon/admission/terminal-spawn-admission-mode' -import { errorMessage } from '../../shared/error-message' -import { OrcadTerminalsNotDurableError, takeOrcadServeSupervision } from './orcad-serve-supervision' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import { initDaemonPtyProvider } from '../../daemon/providers/lifecycle/daemon-provider-init' +import { resolveTerminalSpawnAdmissionMode } from '../../daemon/admission/terminal-spawn-admission-mode' +import { errorMessage } from '../../../shared/error-message' +import { + OrcadTerminalsNotDurableError, + takeOrcadServeSupervision +} from '../serve-startup/orcad-serve-supervision' const WINDOWS_DAEMON_STARTUP_TIMEOUT_MS = 30_000 diff --git a/src/main/orcad/orcad-idle-stop-daemon-recovery.ts b/src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts similarity index 91% rename from src/main/orcad/orcad-idle-stop-daemon-recovery.ts rename to src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts index c535e4facb2..b8ac12f850e 100644 --- a/src/main/orcad/orcad-idle-stop-daemon-recovery.ts +++ b/src/main/orcad/daemon/orcad-idle-stop-daemon-recovery.ts @@ -1,8 +1,8 @@ // Cancelled idle stops may leave daemon admission closed. Replace only after atomic retirement // agreement: replacement could otherwise kill the old daemon’s live sessions. -import { withTimeout } from '../../shared/promise-timeout-fallback' +import { withTimeout } from '../../../shared/promise-timeout-fallback' import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from './orcad-stop-deadlines' +import { ORCAD_DAEMON_RETIREMENT_TIMEOUT_MS } from '../host-lifecycle/managed-stop/orcad-stop-deadlines' type RetirementOutcome = Pick diff --git a/src/main/orcad/orcad-event-loop-watchdog.ts b/src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts similarity index 98% rename from src/main/orcad/orcad-event-loop-watchdog.ts rename to src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts index e2e87cb5690..6bc31064af3 100644 --- a/src/main/orcad/orcad-event-loop-watchdog.ts +++ b/src/main/orcad/diagnostics/orcad-event-loop-watchdog.ts @@ -2,7 +2,7 @@ // The check runs on a worker thread, which a blocked main thread cannot starve. import inspector from 'node:inspector' import type { Worker } from 'node:worker_threads' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' export const ORCAD_EVENT_LOOP_WATCHDOG_ENV = 'ORCA_ORCAD_EVENT_LOOP_WATCHDOG' const BEAT_INTERVAL_MS = 1_000 diff --git a/src/main/orcad/orcad-health.ts b/src/main/orcad/diagnostics/orcad-health.ts similarity index 86% rename from src/main/orcad/orcad-health.ts rename to src/main/orcad/diagnostics/orcad-health.ts index 9d3cc4920c2..bad23db05c8 100644 --- a/src/main/orcad/orcad-health.ts +++ b/src/main/orcad/diagnostics/orcad-health.ts @@ -1,22 +1,22 @@ // RPC readiness cannot prove terminal health; cross the daemon socket boundary for its own self-test. -import { hashOrcadLauncher } from '../../shared/orcad-build-identity' +import { hashOrcadLauncher } from '../../../shared/orcad-build-identity' import { confirmPtyProcessCeiling, type PtyProcessCeilingState -} from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' +} from '../../../shared/terminal/pty/native-process/pty-process-ceiling-state' import process from 'node:process' -import { checkDaemonHealthWithCoverage, type DaemonHealth } from '../daemon/health/daemon-health' -import { ptySpawnHealthPlatformCoverage } from '../daemon/health/daemon-health-identity' +import { checkDaemonHealthWithCoverage, type DaemonHealth } from '../../daemon/health/daemon-health' +import { ptySpawnHealthPlatformCoverage } from '../../daemon/health/daemon-health-identity' import { daemonOwnsFreshPersistentPtys, getDaemonEndpointFacts, readDaemonPidRecord -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { OrcadProfileStateAuthoritySelection } from './orcad-profile-state-telemetry' -import { ORCAD_STOP_REQUESTS_CAPABILITY } from '../../shared/orcad-stop-request' -import type { OrcadIdleStopRecord } from '../../shared/orcad-idle-exit' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' -import { orcadPreviousUnexpectedExit } from './orcad-unexpected-exit' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { OrcadProfileStateAuthoritySelection } from '../profile-state/orcad-profile-state-telemetry' +import { ORCAD_STOP_REQUESTS_CAPABILITY } from '../../../shared/orcad-stop-request' +import type { OrcadIdleStopRecord } from '../../../shared/orcad-idle-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' +import { orcadPreviousUnexpectedExit } from '../host-lifecycle/orcad-unexpected-exit' /** Distinguish real PTY spawn coverage from handshake-only platform probes. */ type PtySelfTestCoverage = 'pty-spawn' | 'handshake' diff --git a/src/main/orcad/orcad-host-unavailable.ts b/src/main/orcad/diagnostics/orcad-host-unavailable.ts similarity index 100% rename from src/main/orcad/orcad-host-unavailable.ts rename to src/main/orcad/diagnostics/orcad-host-unavailable.ts diff --git a/src/main/orcad/orcad-observability.test.ts b/src/main/orcad/diagnostics/orcad-observability.test.ts similarity index 62% rename from src/main/orcad/orcad-observability.test.ts rename to src/main/orcad/diagnostics/orcad-observability.test.ts index 1e46b71d084..bca26152fbb 100644 --- a/src/main/orcad/orcad-observability.test.ts +++ b/src/main/orcad/diagnostics/orcad-observability.test.ts @@ -1,9 +1,9 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { setAppEnvironment } from '../../shared/app-environment' -import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { setAppEnvironment } from '../../../shared/app-environment' +import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { installOrcadObservability } from './orcad-observability' const CI_ENV = [ @@ -77,33 +77,4 @@ describe('orcad trace file', () => { ) expect(existsSync(join(dataRoot, 'logs', 'main.trace.ndjson'))).toBe(false) }) - - it('flushes what is buffered when the process exits with no cleanup', async () => { - const before = new Set(process.listeners('exit')) - const close = installOrcadObservability() - const onExit = process.listeners('exit').filter((listener) => !before.has(listener)) - expect(onExit).toHaveLength(1) - - reportLateSettlement() - onExit[0]?.call(process, 1) - - expect(traceRecords().map((record) => record.name)).toContain('agentSession.late-settlement') - await close() - expect(process.listeners('exit')).toHaveLength(before.size) - }) - - it('still starts when the logs folder cannot be opened, with tracing off', async () => { - writeFileSync(join(dataRoot, 'logs'), 'not a folder') - const warn = vi.mocked(console.warn) - - const close = installOrcadObservability() - reportLateSettlement() - await close() - - expect(warn).toHaveBeenCalledWith( - expect.stringContaining('[observability] tracing is off'), - expect.any(Error) - ) - expect(readFileSync(join(dataRoot, 'logs'), 'utf8')).toBe('not a folder') - }) }) diff --git a/src/main/orcad/orcad-observability.ts b/src/main/orcad/diagnostics/orcad-observability.ts similarity index 85% rename from src/main/orcad/orcad-observability.ts rename to src/main/orcad/diagnostics/orcad-observability.ts index 84ac75ae558..ac44e15c08d 100644 --- a/src/main/orcad/orcad-observability.ts +++ b/src/main/orcad/diagnostics/orcad-observability.ts @@ -3,8 +3,8 @@ import { closeObservabilityOnExit, initObservability, shutdownObservability -} from '../observability' -import { getOrcadTraceFilePath } from '../observability/logs-directory' +} from '../../observability/index' +import { getOrcadTraceFilePath } from '../../observability/logs-directory' /** Install before runtime startup; close after quit handlers so their spans reach disk. */ export function installOrcadObservability(): () => Promise { diff --git a/src/main/orcad/orcad-startup-timing.ts b/src/main/orcad/diagnostics/orcad-startup-timing.ts similarity index 100% rename from src/main/orcad/orcad-startup-timing.ts rename to src/main/orcad/diagnostics/orcad-startup-timing.ts diff --git a/src/main/orcad/orcad-terminal-census.ts b/src/main/orcad/diagnostics/orcad-terminal-census.ts similarity index 87% rename from src/main/orcad/orcad-terminal-census.ts rename to src/main/orcad/diagnostics/orcad-terminal-census.ts index d55ff3f7c92..8003644f210 100644 --- a/src/main/orcad/orcad-terminal-census.ts +++ b/src/main/orcad/diagnostics/orcad-terminal-census.ts @@ -1,9 +1,9 @@ import { countInProcessFallbackTerminals, listLiveDaemonSessionsWithProtocol -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { DaemonSessionInfo } from '../daemon/protocol/daemon-session-info' -import type { OrcadTerminalCensus } from '../../shared/orcad-terminal-census' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { DaemonSessionInfo } from '../../daemon/protocol/daemon-session-info' +import type { OrcadTerminalCensus } from '../../../shared/orcad-terminal-census' const UNVERIFIABLE: OrcadTerminalCensus = { liveSessions: null, diff --git a/src/main/orcad/electron-serve-provider-selection.test.ts b/src/main/orcad/electron-serve-provider-selection.test.ts deleted file mode 100644 index f201d43aebf..00000000000 --- a/src/main/orcad/electron-serve-provider-selection.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { ProcessSpec } from '@orca/process-host/process-spec' -import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RunProcessModule from '@orca/process-host' - -const { runProcessMock, spawnProcessMock } = vi.hoisted(() => ({ - runProcessMock: vi.fn(), - spawnProcessMock: vi.fn() -})) - -vi.mock('@orca/process-host', async (importOriginal) => ({ - ...(await importOriginal()), - runProcess: runProcessMock, - spawnProcess: spawnProcessMock -})) - -// Real macOS installs would register a park in the developer’s home. -vi.mock('./orcad-browser-install-park', () => ({ openOrcadBrowserInstallPark: () => null })) - -import { resolveOrcadBrowserProvider, type OrcadBrowserProvider } from './orcad-browser-provider' -import { agentBrowserCommandOf } from '../browser/agent-browser/testing/agent-browser-bridge-test-harness' - -const FAKE_SIDECAR = join(import.meta.dirname, '__fixtures__', 'fake-orcad-electron-sidecar.cjs') -const INSTALLED_EXECUTABLE = join('/Applications', 'Orca.app', 'Contents', 'MacOS', 'Orca') - -let harnessRoot: string -let controlPath: string -let chromiumExecutable: string -let sidecarMode: string | undefined -let provider: OrcadBrowserProvider | null - -function agentBrowserSuccess(data: unknown) { - return Promise.resolve({ - code: 0, - signal: null, - stdout: JSON.stringify({ success: true, data, error: null }), - stderr: '', - timedOut: false - }) -} - -beforeEach(async () => { - harnessRoot = await mkdtemp(join(tmpdir(), 'orcad-provider-selection-')) - controlPath = join(harnessRoot, 'control.json') - chromiumExecutable = join(harnessRoot, process.platform === 'win32' ? 'chromium.exe' : 'chromium') - sidecarMode = undefined - provider = null - await writeFile(controlPath, '{}') - await writeFile(chromiumExecutable, '') - if (process.platform !== 'win32') { - await chmod(chromiumExecutable, 0o755) - } - - const actual = await vi.importActual('@orca/process-host') - spawnProcessMock.mockReset() - spawnProcessMock.mockImplementation((spec: ProcessSpec) => - actual.spawnProcess({ - ...spec, - program: process.execPath, - args: [FAKE_SIDECAR, ...(spec.args ?? [])], - env: { - ...spec.env, - ORCA_FAKE_SIDECAR_CONTROL: controlPath, - ...(sidecarMode ? { ORCA_FAKE_SIDECAR_MODE: sidecarMode } : {}) - } - }) - ) - runProcessMock.mockReset() - runProcessMock.mockImplementation(async (spec: ProcessSpec) => { - const command = agentBrowserCommandOf(spec.args ?? [], spec.input) - if (command[0] === 'open') { - return agentBrowserSuccess({ url: 'about:blank', title: '' }) - } - if (command[0] === 'tab') { - return agentBrowserSuccess({ - tabs: [{ active: true, tabId: 't1', title: '', url: 'about:blank' }] - }) - } - if (command[0] === 'close') { - return agentBrowserSuccess({ closed: true }) - } - throw new Error(`Unexpected agent-browser command: ${command.join(' ')}`) - }) -}) - -afterEach(async () => { - await provider?.stop() - vi.restoreAllMocks() - await rm(harnessRoot, { recursive: true, force: true }) -}) - -describe('resolveOrcadBrowserProvider Electron preference', () => { - it('falls back to the operator Chromium when the installed Electron app cannot start', async () => { - sidecarMode = 'exit-before-ready' - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - - provider = await resolveOrcadBrowserProvider({ - userDataPath: join(harnessRoot, 'state'), - environment: { ORCA_BROWSER_EXECUTABLE: chromiumExecutable }, - resolveInstalledElectronExecutable: async () => INSTALLED_EXECUTABLE, - resolveAgentBrowserBinary: () => '/agent-browser' - }) - - expect(spawnProcessMock).toHaveBeenCalled() - expect(provider?.kind).toBe('chromium') - expect(warn).toHaveBeenCalledWith( - '[orcad] Installed Electron browser provider unavailable:', - expect.anything() - ) - }) -}) diff --git a/src/main/orcad/orcad-idle-exit-monitor.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts similarity index 80% rename from src/main/orcad/orcad-idle-exit-monitor.test.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts index 87ea58eefcf..0e30fcf132e 100644 --- a/src/main/orcad/orcad-idle-exit-monitor.test.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { OrcadIdleExitMonitor, - resolveOrcadIdlePollMs, type OrcadIdleProbe, type OrcadIdleVerdict } from './orcad-idle-exit-monitor' @@ -115,31 +114,4 @@ describe('OrcadIdleExitMonitor', () => { h.advance(100) expect(await h.monitor.check()).toBe(true) }) - - it('polls often enough for a short test timeout and at most once a minute', () => { - expect(resolveOrcadIdlePollMs(15 * 60_000)).toBe(60_000) - expect(resolveOrcadIdlePollMs(2_000)).toBe(400) - expect(resolveOrcadIdlePollMs(10)).toBe(250) - }) - - it('stops itself on a timer once idle', async () => { - vi.useFakeTimers() - try { - const onIdle = vi.fn() - const monitor = new OrcadIdleExitMonitor({ - timeoutMs: 1_000, - probes: [{ name: 'clients', read: () => 'idle' }], - lastClientActivityAt: () => 0, - onIdle, - log: () => {} - }) - monitor.start() - await vi.advanceTimersByTimeAsync(1_600) - expect(onIdle).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(5_000) - expect(onIdle).toHaveBeenCalledTimes(1) - } finally { - vi.useRealTimers() - } - }) }) diff --git a/src/main/orcad/orcad-idle-exit-monitor.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.ts similarity index 100% rename from src/main/orcad/orcad-idle-exit-monitor.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-exit-monitor.ts diff --git a/src/main/orcad/orcad-idle-stop-record.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts similarity index 84% rename from src/main/orcad/orcad-idle-stop-record.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts index 30c8d3fd7e8..d6c98b8fc35 100644 --- a/src/main/orcad/orcad-idle-stop-record.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-idle-stop-record.ts @@ -1,15 +1,15 @@ // Consume clean idle-stop evidence once; discard failed stops so later crashes cannot inherit it. import { rmSync } from 'node:fs' import { join } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { ORCAD_IDLE_STOP_RECORD_FILENAME, OrcadIdleStopRecordSchema, type OrcadIdleStopRecord -} from '../../shared/orcad-idle-exit' +} from '../../../../shared/orcad-idle-exit' import type { OrcadIdleExitEvidence } from './orcad-idle-exit-monitor' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' const RECORD_MAX_BYTES = 16 * 1024 diff --git a/src/main/orcad/orcad-managed-idle-exit-host.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts similarity index 88% rename from src/main/orcad/orcad-managed-idle-exit-host.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts index cf8c9eb7608..c1fb1afb454 100644 --- a/src/main/orcad/orcad-managed-idle-exit-host.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit-host.ts @@ -1,5 +1,5 @@ -import { getAppEnvironment } from '../../shared/app-environment' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' +import { getAppEnvironment } from '../../../../shared/app-environment' +import type { RuntimeRpcClientActivity } from '../../../runtime/rpc/server/runtime-rpc' import type { OrcadIdleExitEvidence } from './orcad-idle-exit-monitor' import { activationFenceExists, @@ -9,21 +9,21 @@ import { type OrcadManagedIdleExitConfig, type OrcadManagedIdleExitPorts } from './orcad-managed-idle-exit' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { recoverDaemonAfterCancelledIdleStop } from './orcad-idle-stop-daemon-recovery' +import type { OrcadDaemonRetirement } from '../../daemon/orcad-daemon-retirement' +import { recoverDaemonAfterCancelledIdleStop } from '../../daemon/orcad-idle-stop-daemon-recovery' import { consumeOrcadIdleStopRecord, discardOrcadIdleStopRecord, writeOrcadIdleStopRecord } from './orcad-idle-stop-record' -import type { OrcadShutdownTrigger } from './orcad-lifecycle' +import type { OrcadShutdownTrigger } from '../orcad-lifecycle' import { idleStopMayReleaseWslHolder, requestOrcadWslHolderRelease, withdrawOrcadWslHolderRelease -} from './orcad-wsl-holder-release' -import type { OrcadIdleStopRecord } from '../../shared/orcad-idle-exit' -import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' +} from '../../instance-lock/orcad-wsl-holder-release' +import type { OrcadIdleStopRecord } from '../../../../shared/orcad-idle-exit' +import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-registry' let requestIdleShutdown: OrcadShutdownTrigger | null = null @@ -70,11 +70,11 @@ async function startOrcadManagedIdleExit( version: string } ): Promise { - const { getLocalPtyProvider } = await import('../ipc/pty/provider/registry') + const { getLocalPtyProvider } = await import('../../../ipc/pty/provider/registry') const { getCurrentDaemonPid, getDaemonEndpointFacts, isDaemonTerminalAdmissionClosed } = - await import('../daemon/providers/lifecycle/daemon-provider-state') + await import('../../../daemon/providers/lifecycle/daemon-provider-state') const { countLiveOrcadDaemonSessions, retireOrcadDaemonIfIdle } = - await import('./orcad-daemon-retirement') + await import('../../daemon/orcad-daemon-retirement') const idleRecord = createIdleStopRecordOwnership(input.userDataPath) const hasChatProviders = (): boolean => getStructuredAgentSessionHost()?.hasLoadedProviders() ?? false @@ -130,7 +130,7 @@ async function startOrcadManagedIdleExit( throw new Error('the retiring daemon never identified itself') } const { restartDaemon } = - await import('../daemon/providers/lifecycle/daemon-provider-restart') + await import('../../../daemon/providers/lifecycle/daemon-provider-restart') await restartDaemon({ expectedDaemonPid: retiringPid, endpointMayBeGone: true }) } }) diff --git a/src/main/orcad/orcad-managed-idle-exit.test.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts similarity index 100% rename from src/main/orcad/orcad-managed-idle-exit.test.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.test.ts diff --git a/src/main/orcad/orcad-managed-idle-exit.ts b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts similarity index 90% rename from src/main/orcad/orcad-managed-idle-exit.ts rename to src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts index cc77791741b..2064eb6a575 100644 --- a/src/main/orcad/orcad-managed-idle-exit.ts +++ b/src/main/orcad/host-lifecycle/idle-exit/orcad-managed-idle-exit.ts @@ -1,15 +1,15 @@ // Live terminals block idle exit; ordinary shutdown disconnects without killing their daemon. import { stat } from 'node:fs/promises' import { join } from 'node:path' -import { RELAY_INSTALL_LOCK_NAME } from '../../shared/relay-install-lock-name' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' -import type { RuntimeRpcClientActivity } from '../runtime/rpc/server/runtime-rpc' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { RELAY_INSTALL_LOCK_NAME } from '../../../../shared/relay-install-lock-name' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' +import type { RuntimeRpcClientActivity } from '../../../runtime/rpc/server/runtime-rpc' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../../shared/orcad-managed-launch-env' import { ORCAD_IDLE_EXIT_TIMEOUT_MS, readOrcadE2EIdleTimeoutMs, readOrcadIdleTimeoutMs -} from '../../shared/orcad-idle-exit' +} from '../../../../shared/orcad-idle-exit' import { OrcadIdleExitMonitor, type OrcadIdleExitEvidence, diff --git a/src/main/orcad/orcad-completed-stop-receipt.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts similarity index 91% rename from src/main/orcad/orcad-completed-stop-receipt.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts index 8114ddddcbe..58f0defc7b5 100644 --- a/src/main/orcad/orcad-completed-stop-receipt.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-completed-stop-receipt.ts @@ -1,9 +1,9 @@ import { lstatSync } from 'node:fs' import { dirname, join } from 'node:path' import type { z } from 'zod' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' import { ORCAD_STOP_RECEIPTS_DIRNAME, OrcadCompletedStopReceiptSchema, @@ -13,7 +13,7 @@ import { type OrcadCompletedStopReceipt, type OrcadDaemonRetirementRecord, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' const RECEIPT_MAX_BYTES = 64 * 1024 diff --git a/src/main/orcad/orcad-managed-stop-admission.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts similarity index 80% rename from src/main/orcad/orcad-managed-stop-admission.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts index 5a3ae86da7d..c7018dc145f 100644 --- a/src/main/orcad/orcad-managed-stop-admission.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-admission.ts @@ -1,12 +1,12 @@ -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' import { persistOrcadDaemonRetirementRecord } from './orcad-completed-stop-receipt' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' -import { stopOrcadAutomationScheduler } from './orcad-automations' +import type { OrcadDaemonRetirement } from '../../daemon/orcad-daemon-retirement' +import { stopOrcadAutomationScheduler } from '../../host-runtime/orcad-automations' import { holdOrcadTerminalAdmissionUntilExit } from './orcad-stop-terminal-admission' // Keep daemon imports lazy so entry loading cannot initialize native code. async function retireLazily(): Promise { - const { retireOrcadDaemonIfIdle } = await import('./orcad-daemon-retirement') + const { retireOrcadDaemonIfIdle } = await import('../../daemon/orcad-daemon-retirement') return retireOrcadDaemonIfIdle() } diff --git a/src/main/orcad/orcad-managed-stop-cancel-race.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-cancel-race.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts index 4fe4c5414c5..77d718a4480 100644 --- a/src/main/orcad/orcad-managed-stop-cancel-race.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancel-race.test.ts @@ -10,7 +10,7 @@ vi.mock('./orcad-managed-stop-decision', async (importOriginal) => ({ readOrcadManagedStopDecision: decisions.read })) -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { completeOrcadManagedStop } from './orcad-managed-stop-completion' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' diff --git a/src/main/orcad/orcad-managed-stop-cancellation.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts similarity index 88% rename from src/main/orcad/orcad-managed-stop-cancellation.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts index 5e8a906c7a1..0a34a78a4aa 100644 --- a/src/main/orcad/orcad-managed-stop-cancellation.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.test.ts @@ -3,17 +3,17 @@ import { rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' +import type * as WindowsAcl from '../../../../shared/secure-storage/secure-path-windows-acl' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' import { cancelOrcadManagedStop } from './orcad-managed-stop-cancellation' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-managed-stop-cancellation.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-cancellation.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts index db8556765c0..f820a69f57e 100644 --- a/src/main/orcad/orcad-managed-stop-cancellation.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-cancellation.ts @@ -2,7 +2,7 @@ import { rmSync } from 'node:fs' import type { OrcadManagedStopCancellation, OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { orcadManagedStopRequestPath, diff --git a/src/main/orcad/orcad-managed-stop-command.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts similarity index 98% rename from src/main/orcad/orcad-managed-stop-command.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts index e5375e1fc7a..0a26dcea1aa 100644 --- a/src/main/orcad/orcad-managed-stop-command.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-command.ts @@ -7,7 +7,7 @@ import { type OrcadManagedStopCancellation, type OrcadManagedStopCompletion, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { cancelOrcadManagedStop } from './orcad-managed-stop-cancellation' import { readOrcadCompletedStopReceipt } from './orcad-completed-stop-receipt' import { readOrcadManagedStopRequest } from './orcad-managed-stop-request' diff --git a/src/main/orcad/orcad-managed-stop-completion.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts similarity index 95% rename from src/main/orcad/orcad-managed-stop-completion.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts index 839372a972c..edc8155adef 100644 --- a/src/main/orcad/orcad-managed-stop-completion.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-completion.ts @@ -1,23 +1,23 @@ // Request shutdown without signaling; only kernel identity, owner change or PID absence proves exit. import { setTimeout as delay } from 'node:timers/promises' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { OrcadManagedStopRequestSchema, orcadManagedStopRequestKey, type OrcadManagedStopInstance, type OrcadManagedStopRequest, type OrcadManagedStopVerdict -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { compareOrcadProcessIdentity, recordedOrcadProcessIncarnation, type OrcadProcessIdentityReaders, type OrcadRecordedIdentity -} from './orcad-process-start-time' +} from '../../instance-lock/orcad-process-start-time' import { hasErrorCode, inspectProcessSignal -} from '../daemon/endpoint/identity/daemon-process-inspection' +} from '../../../daemon/endpoint/identity/daemon-process-inspection' import { persistOrcadCompletedStopReceipt } from './orcad-completed-stop-receipt' import { readOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { withdrawOrcadManagedStopRequest } from './orcad-managed-stop-cancellation' diff --git a/src/main/orcad/orcad-managed-stop-decision.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts similarity index 88% rename from src/main/orcad/orcad-managed-stop-decision.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts index 8684361d2ed..bdbf1db5f05 100644 --- a/src/main/orcad/orcad-managed-stop-decision.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-decision.ts @@ -1,15 +1,15 @@ // Exclusive hard links arbitrate stop versus cancel; cancel cannot succeed once dispatch wins. import { linkSync, rmSync } from 'node:fs' import { randomUUID } from 'node:crypto' -import { writeDurableSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { writeDurableSecureJsonFile } from '../../../../shared/secure-storage/secure-file' import { OrcadManagedStopDecisionSchema, OrcadManagedStopRequestSchema, type OrcadManagedStopDecision, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { orcadStopReceiptPath, readOrcadStopReceipt } from './orcad-completed-stop-receipt' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' type OrcadManagedStopDecisionValue = OrcadManagedStopDecision['decision'] diff --git a/src/main/orcad/orcad-managed-stop-identity.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts similarity index 96% rename from src/main/orcad/orcad-managed-stop-identity.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts index 37a285670e5..af67beb5b4f 100644 --- a/src/main/orcad/orcad-managed-stop-identity.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-identity.test.ts @@ -6,15 +6,15 @@ import { z } from 'zod' import { OrcadManagedStopRequestSchema, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +} from '../../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' import { orcadManagedStopRequestPath } from './orcad-managed-stop-request' import { completeOrcadManagedStop, type OrcadManagedStopCompletionOptions } from './orcad-managed-stop-completion' import { orcadStopReceiptPath } from './orcad-completed-stop-receipt' -import type { OrcadProcessIncarnation } from './orcad-process-start-time' +import type { OrcadProcessIncarnation } from '../../instance-lock/orcad-process-start-time' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-managed-stop-request.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts similarity index 90% rename from src/main/orcad/orcad-managed-stop-request.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts index 4a75f130bf7..d782428b528 100644 --- a/src/main/orcad/orcad-managed-stop-request.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop-request.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { lstatSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' +import { readNodeFileSyncWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader' import { ORCAD_MANAGED_STOP_REQUEST_MAX_BYTES, ORCAD_MANAGED_STOP_REQUEST_PREFIX, @@ -9,8 +9,11 @@ import { type OrcadManagedStopContext, type OrcadManagedStopInstance, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' -import { readOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock' +} from '../../../../shared/orcad-stop-request' +import { + readOrcadInstanceLockRecord, + type OrcadLockRecord +} from '../../instance-lock/orcad-instance-lock-record' /** Nonce-scoped paths prevent requests from addressing a previous instance. */ export function orcadManagedStopRequestPath(instance: OrcadManagedStopInstance): string { diff --git a/src/main/orcad/orcad-managed-stop.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts similarity index 94% rename from src/main/orcad/orcad-managed-stop.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts index 51a2ed944f1..5924bf79a04 100644 --- a/src/main/orcad/orcad-managed-stop.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-managed-stop.test.ts @@ -2,9 +2,10 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'no import { tmpdir } from 'node:os' import { basename, dirname, join, sep } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl' -import type { OrcadManagedStopRequest } from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock, type OrcadInstanceLock } from './orcad-instance-lock' +import type * as WindowsAcl from '../../../../shared/secure-storage/secure-path-windows-acl' +import type { OrcadManagedStopRequest } from '../../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../../instance-lock/orcad-instance-lock' +import type { OrcadInstanceLock } from '../../instance-lock/orcad-instance-lock-hold' import { orcadManagedStopRequestPath, validateOrcadManagedStopRequest @@ -18,7 +19,7 @@ import { runOrcadManagedStopCommand } from './orcad-managed-stop-command' const hardening = vi.hoisted(() => ({ pending: new Set>() })) -vi.mock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { +vi.mock('../../../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => { const acl = await importOriginal() return { ...acl, diff --git a/src/main/orcad/orcad-stop-deadlines.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-deadlines.ts similarity index 100% rename from src/main/orcad/orcad-stop-deadlines.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-deadlines.ts diff --git a/src/main/orcad/orcad-stop-request-listener.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts similarity index 96% rename from src/main/orcad/orcad-stop-request-listener.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts index 4e237e65aba..5e9c765fda9 100644 --- a/src/main/orcad/orcad-stop-request-listener.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-listener.ts @@ -5,14 +5,14 @@ import { ORCAD_STOP_REQUEST_FILENAME, type OrcadManagedStopContext, type OrcadManagedStopRequest -} from '../../shared/orcad-stop-request' +} from '../../../../shared/orcad-stop-request' import { orcadManagedStopRequestPath, validateOrcadManagedStopRequest } from './orcad-managed-stop-request' import { claimOrcadManagedStopDecision } from './orcad-managed-stop-decision' import { withdrawOrcadManagedStopRequest } from './orcad-managed-stop-cancellation' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { hasErrorCode } from '../../../daemon/endpoint/identity/daemon-process-inspection' export type OrcadStopRequestListener = { close(): void } diff --git a/src/main/orcad/orcad-stop-request-shutdown.integration.test.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts similarity index 86% rename from src/main/orcad/orcad-stop-request-shutdown.integration.test.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts index 89b14cc4a6e..70a5a5b327d 100644 --- a/src/main/orcad/orcad-stop-request-shutdown.integration.test.ts +++ b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-request-shutdown.integration.test.ts @@ -4,22 +4,23 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { spawnProcess } from '@orca/process-host' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' -import { ORCAD_STOP_REQUEST_FILENAME } from '../../shared/orcad-stop-request' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../../shared/orcad-artifacts' +import { ORCAD_STOP_REQUEST_FILENAME } from '../../../../shared/orcad-stop-request' import { killChildAndWait, killProfileDaemons, recordProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' -import { parseOrcadReadinessOutput } from '../managed-server/install/orcad-remote-launch' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' +} from '../../testing/daemon-processes/orcad-daemon-teardown-fixture' +import { parseOrcadReadinessOutput } from '../../../managed-server/install/orcad-remote-launch' +import { ORCAD_LOCK_FILE_NAME } from '../../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../../instance-lock/orcad-instance-lock-record' import { ORCAD_SHUTDOWN_DEADLINE_MS } from './orcad-stop-deadlines' import { installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const skip = skipForMissingInputs('artifact', [ diff --git a/src/main/orcad/orcad-stop-terminal-admission.ts b/src/main/orcad/host-lifecycle/managed-stop/orcad-stop-terminal-admission.ts similarity index 100% rename from src/main/orcad/orcad-stop-terminal-admission.ts rename to src/main/orcad/host-lifecycle/managed-stop/orcad-stop-terminal-admission.ts diff --git a/src/main/orcad/orcad-fatal-stop-lock.test.ts b/src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts similarity index 92% rename from src/main/orcad/orcad-fatal-stop-lock.test.ts rename to src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts index 1c65da9a49a..6ffa86f14ff 100644 --- a/src/main/orcad/orcad-fatal-stop-lock.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-fatal-stop-lock.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { installOrcadShutdownSignals, startOrcadWithHost } from './orcad-lifecycle' const roots: string[] = [] diff --git a/src/main/orcad/orcad-lifecycle-host.test.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts similarity index 89% rename from src/main/orcad/orcad-lifecycle-host.test.ts rename to src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts index dc1c1e9da1d..b28c26c5697 100644 --- a/src/main/orcad/orcad-lifecycle-host.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-lifecycle-host.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../instance-lock/orcad-instance-lock' import { startOrcadWithHost } from './orcad-lifecycle' const roots: string[] = [] diff --git a/src/main/orcad/orcad-lifecycle.ts b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts similarity index 80% rename from src/main/orcad/orcad-lifecycle.ts rename to src/main/orcad/host-lifecycle/orcad-lifecycle.ts index cc534a847bc..884cab84148 100644 --- a/src/main/orcad/orcad-lifecycle.ts +++ b/src/main/orcad/host-lifecycle/orcad-lifecycle.ts @@ -1,26 +1,29 @@ -import { setRuntimeBrowserCommandsFactory } from '../runtime/browser/installation/runtime-browser-commands-factory' -import { markHostShuttingDown } from '../startup/quit/host-shutdown-state' -import { setDesktopBrowserBridgeHostEnabled } from '../runtime/desktop-browser-bridge/desktop-browser-bridge-registry' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' -import { startOrcadBrowserProvider } from './orcad-browser-startup' -import { OrcadRuntimeLifetime, type OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { OrcadManagedStopInstance } from '../../shared/orcad-stop-request' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' +import { setRuntimeBrowserCommandsFactory } from '../../runtime/browser/installation/runtime-browser-commands-factory' +import { markHostShuttingDown } from '../../startup/quit/host-shutdown-state' +import { setDesktopBrowserBridgeHostEnabled } from '../../runtime/desktop-browser-bridge/desktop-browser-bridge-registry' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' +import { startOrcadBrowserProvider } from '../browser-providers/orcad-browser-startup' +import { + BackendServiceLifetime, + type BackendServiceCleanup +} from '../../backend/service-composition' +import type { OrcadManagedStopInstance } from '../../../shared/orcad-stop-request' +import { acquireOrcadInstanceLock } from '../instance-lock/orcad-instance-lock' import { markOrcadRunFailed, orcadRunFailed, recordOrcadPreviousUnexpectedExit } from './orcad-unexpected-exit' -import { ORCAD_BUNDLED_LAUNCHER_ENV } from './orcad-bundled-runtime' -import { resolveOrcadExitCode } from './orcad-exit-code' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' -import { recordAgentSessionRuntimeEnd } from '../runtime/agent-session/records/agent-session-runtime-end-record' -import { ORCAD_SHUTDOWN_DEADLINE_MS } from './orcad-stop-deadlines' -import { holdOrcadTerminalAdmissionUntilExit } from './orcad-stop-terminal-admission' +import { ORCAD_BUNDLED_LAUNCHER_ENV } from '../runtime-launch/orcad-bundled-runtime' +import { resolveOrcadExitCode } from '../serve-startup/orcad-exit-code' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' +import { recordAgentSessionRuntimeEnd } from '../../runtime/agent-session/records/agent-session-runtime-end-record' +import { ORCAD_SHUTDOWN_DEADLINE_MS } from './managed-stop/orcad-stop-deadlines' +import { holdOrcadTerminalAdmissionUntilExit } from './managed-stop/orcad-stop-terminal-admission' import { acquireProfileStateRuntimeAdmission, type ProfileStateRuntimeAdmission -} from '../persistence/profile-state/access/profile-state-access' +} from '../../persistence/profile-state/access/profile-state-access' const bundledLauncherChannel = process.env[ORCAD_BUNDLED_LAUNCHER_ENV] === '1' delete process.env[ORCAD_BUNDLED_LAUNCHER_ENV] @@ -108,15 +111,15 @@ export function installOrcadShutdownSignals( export async function stopOrcadStructuredAgentSessions(): Promise { const { stopStructuredAgentSessionRuntime } = - await import('../runtime/agent-session/structured-agent-session-runtime') + await import('../../runtime/agent-session/structured-agent-session-runtime') await stopStructuredAgentSessionRuntime({ trigger: 'quit' }) } export async function startOrcadWithLifecycle( - start: (registerRuntimeCleanup: (cleanup: OrcadRuntimeCleanup) => void) => Promise, + start: (registerRuntimeCleanup: (cleanup: BackendServiceCleanup) => void) => Promise, cleanupHost: (runtimeCleanupSucceeded: boolean) => Promise ): Promise }> { - const runtime = new OrcadRuntimeLifetime() + const runtime = new BackendServiceLifetime() const cleanup = createIdempotentOrcadCleanup(async () => { // Stamp quit before awaiting teardown so dying chat agents read as restart rather than crash. recordAgentSessionRuntimeEnd('quit') @@ -147,7 +150,7 @@ export async function startOrcadWithLifecycle( /** Keep profile admission/lock until all runtime writers stop. */ export async function startOrcadWithHost( userDataPath: string, - start: (registerCleanup: (cleanup: OrcadRuntimeCleanup) => void) => Promise, + start: (registerCleanup: (cleanup: BackendServiceCleanup) => void) => Promise, runQuitHandlers: () => void | Promise ): Promise; instance: OrcadManagedStopInstance }> { const instanceLock = acquireOrcadInstanceLock(userDataPath, { @@ -183,7 +186,7 @@ export async function startOrcadWithHost( }, async (runtimeCleanupSucceeded) => { // Failed cleanup retains both ownership fences until process exit. - const host = new OrcadRuntimeLifetime(() => { + const host = new BackendServiceLifetime(() => { if (runtimeCleanupSucceeded && !orcadRunFailed()) { instanceLock.release() } diff --git a/src/main/orcad/orcad-lock-yield.test.ts b/src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts similarity index 84% rename from src/main/orcad/orcad-lock-yield.test.ts rename to src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts index 6051f615f05..ac51d380859 100644 --- a/src/main/orcad/orcad-lock-yield.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-lock-yield.test.ts @@ -3,16 +3,19 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -vi.mock('./orcad-browser-startup', () => ({ +vi.mock('../browser-providers/orcad-browser-startup', () => ({ startOrcadBrowserProvider: () => ({ ready: Promise.resolve(), stop: async () => {} }) })) -import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' -import { readOrcadInstanceLockRecord } from './orcad-instance-lock-record' +import { + acquireOrcadInstanceLock, + ORCAD_LOCK_FILE_NAME +} from '../instance-lock/orcad-instance-lock' +import { readOrcadInstanceLockRecord } from '../instance-lock/orcad-instance-lock-record' import { installOrcadShutdownSignals, startOrcadWithHost } from './orcad-lifecycle' -import { ORCAD_LOCK_HEARTBEAT_MS } from './orcad-lock-clone-machine' +import { ORCAD_LOCK_HEARTBEAT_MS } from '../instance-lock/orcad-lock-clone-machine' import { orcadRunFailed } from './orcad-unexpected-exit' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-process-error-guards.ts b/src/main/orcad/host-lifecycle/orcad-process-error-guards.ts similarity index 94% rename from src/main/orcad/orcad-process-error-guards.ts rename to src/main/orcad/host-lifecycle/orcad-process-error-guards.ts index 8032cc4178f..41c364d22b2 100644 --- a/src/main/orcad/orcad-process-error-guards.ts +++ b/src/main/orcad/host-lifecycle/orcad-process-error-guards.ts @@ -1,7 +1,7 @@ // Survive rejected tasks and known-benign exceptions; unknown exceptions require bounded shutdown. import process from 'node:process' -import { isNativePtyException } from '../daemon/pty-subprocess/daemon-native-pty-exception' -import { ORCAD_EXIT_FAILED } from './orcad-exit-code' +import { isNativePtyException } from '../../daemon/pty-subprocess/daemon-native-pty-exception' +import { ORCAD_EXIT_FAILED } from '../serve-startup/orcad-exit-code' import type { OrcadShutdownTrigger } from './orcad-lifecycle' // Cap rejection storms so logging cannot stall the server. diff --git a/src/main/orcad/orcad-unexpected-exit.test.ts b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts similarity index 98% rename from src/main/orcad/orcad-unexpected-exit.test.ts rename to src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts index b43300a56f1..6e8bd46ffe1 100644 --- a/src/main/orcad/orcad-unexpected-exit.test.ts +++ b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.test.ts @@ -6,7 +6,7 @@ import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, type OrcadInstanceLockHooks -} from './orcad-instance-lock' +} from '../instance-lock/orcad-instance-lock' const roots: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-unexpected-exit.ts b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts similarity index 89% rename from src/main/orcad/orcad-unexpected-exit.ts rename to src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts index 96b55416aa8..bf721df1e2e 100644 --- a/src/main/orcad/orcad-unexpected-exit.ts +++ b/src/main/orcad/host-lifecycle/orcad-unexpected-exit.ts @@ -1,6 +1,6 @@ import { uptime } from 'node:os' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' -import type { OrcadLockRecord } from './orcad-instance-lock' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' +import type { OrcadLockRecord } from '../instance-lock/orcad-instance-lock-record' /** A reclaimed orcad lock from this boot means that run died; without boot evidence a reboot cannot be ruled out. */ export function reclaimedUnexpectedExit( diff --git a/src/main/orcad/orcad-app-paths.test.ts b/src/main/orcad/host-runtime/orcad-app-paths.test.ts similarity index 100% rename from src/main/orcad/orcad-app-paths.test.ts rename to src/main/orcad/host-runtime/orcad-app-paths.test.ts diff --git a/src/main/orcad/orcad-app-paths.ts b/src/main/orcad/host-runtime/orcad-app-paths.ts similarity index 97% rename from src/main/orcad/orcad-app-paths.ts rename to src/main/orcad/host-runtime/orcad-app-paths.ts index 2839cbbd3ba..12ae8f27342 100644 --- a/src/main/orcad/orcad-app-paths.ts +++ b/src/main/orcad/host-runtime/orcad-app-paths.ts @@ -3,7 +3,7 @@ import { realpathSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import process from 'node:process' -import type { AppPathName } from '../../shared/app-environment' +import type { AppPathName } from '../../../shared/app-environment' // Empty exported paths remain unset. function env(name: string): string | null { diff --git a/src/main/orcad/orcad-automations.ts b/src/main/orcad/host-runtime/orcad-automations.ts similarity index 74% rename from src/main/orcad/orcad-automations.ts rename to src/main/orcad/host-runtime/orcad-automations.ts index bac55aea8dc..c825e9f034b 100644 --- a/src/main/orcad/orcad-automations.ts +++ b/src/main/orcad/host-runtime/orcad-automations.ts @@ -1,7 +1,7 @@ -import type { Store } from '../persistence/loading-store/store' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { createRuntimeAutomationService } from '../automations/runtime-automation-service' -import { isFinalAutomationRunStatus } from '../../shared/automations/history/automation-run' +import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { createRuntimeAutomationService } from '../../automations/runtime-automation-service' +import { isFinalAutomationRunStatus } from '../../../shared/automations/history/automation-run' type AutomationStore = Pick diff --git a/src/main/orcad/orcad-emulator-bridge.ts b/src/main/orcad/host-runtime/orcad-emulator-bridge.ts similarity index 62% rename from src/main/orcad/orcad-emulator-bridge.ts rename to src/main/orcad/host-runtime/orcad-emulator-bridge.ts index 96575d47b68..a4371a2c7d8 100644 --- a/src/main/orcad/orcad-emulator-bridge.ts +++ b/src/main/orcad/host-runtime/orcad-emulator-bridge.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import { EmulatorBridge } from '../emulator/emulator-bridge' -import { withTimeout } from '../../shared/promise-timeout-fallback' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import { EmulatorBridge } from '../../emulator/emulator-bridge' +import { withTimeout } from '../../../shared/promise-timeout-fallback' // A stalled adb must not hold the final profile flush past orcad's shutdown deadline. const EMULATOR_TEARDOWN_BUDGET_MS = 3_000 @@ -9,7 +9,7 @@ const EMULATOR_TEARDOWN_BUDGET_MS = 3_000 /** Android drives adb/emulator on any host; iOS backends report their own host-support errors. */ export function installOrcadEmulatorBridge( runtime: OrcaRuntimeService, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void ): void { const bridge = new EmulatorBridge() runtime.setEmulatorBridge(bridge) diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/host-runtime/orcad-entry.ts similarity index 77% rename from src/main/orcad/orcad-entry.ts rename to src/main/orcad/host-runtime/orcad-entry.ts index f1aeccad01e..43b466b4c2f 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/host-runtime/orcad-entry.ts @@ -1,36 +1,36 @@ // Compose the Node-host runtime; paired desktop pages work even without a local browser engine. import process from 'node:process' -import { getAppEnvironment } from '../../shared/app-environment' +import { getAppEnvironment } from '../../../shared/app-environment' import { resolveUserDataPath } from './orcad-app-paths' -import { prepareOrcadCliLauncher } from './orcad-cli-launcher' +import { prepareOrcadCliLauncher } from '../serve-startup/orcad-cli-launcher' import { installOrcadHostAdapters, runOrcadQuitHandlers } from './orcad-host-adapters' -import { prepareOrcadSecretStoreAndMigrate } from './orcad-secret-store-startup' -import { describeOrcadBindExposure, resolveOrcadBindHost } from '../../shared/orcad-bind-address' +import { prepareOrcadSecretStoreAndMigrate } from '../credentials/orcad-secret-store-startup' +import { describeOrcadBindExposure, resolveOrcadBindHost } from '../../../shared/orcad-bind-address' import { flushOrcadProfileStoreForShutdown, startOrcadWithHost, stopOrcadStructuredAgentSessions -} from './orcad-lifecycle' -import { resolveOrcadWebClientRoot } from './orcad-command-arguments' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import { bindOrcadStopTerminalAdmission } from './orcad-stop-terminal-admission' -import type { OrcadHandle, OrcadOptions } from './orcad-start-contract' -import { beginOrcadIdleExit } from './orcad-managed-idle-exit-host' +} from '../host-lifecycle/orcad-lifecycle' +import { resolveOrcadWebClientRoot } from '../serve-startup/orcad-command-arguments' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import { bindOrcadStopTerminalAdmission } from '../host-lifecycle/managed-stop/orcad-stop-terminal-admission' +import type { OrcadHandle, OrcadOptions } from '../serve-startup/orcad-start-contract' +import { beginOrcadIdleExit } from '../host-lifecycle/idle-exit/orcad-managed-idle-exit-host' import { orcadAutomationsKeepHostBusy, startOrcadAutomations } from './orcad-automations' import { changedAiVaultSearchSettings, type AiVaultSearchSettings -} from '../../shared/ai-vault/search/ai-vault-search-settings' -import { stampRuntimeSourceEnv } from '../../shared/runtime-source-env' +} from '../../../shared/ai-vault/search/ai-vault-search-settings' +import { stampRuntimeSourceEnv } from '../../../shared/runtime-source-env' import { adoptWslHostLoginEnvironmentLogged } from './orcad-wsl-host-login-environment' -import { orcadWsPortOptions } from './orcad-ws-port-policy' -import { createOrcadStartupTiming } from './orcad-startup-timing' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' +import { orcadWsPortOptions } from '../serve-startup/orcad-ws-port-policy' +import { createOrcadStartupTiming } from '../diagnostics/orcad-startup-timing' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { restoreOrcadTerminalAuthority } from './orcad-restored-terminal-authority' -import { installOrcadFeatureReadiness } from '../runtime/rpc/startup/orcad-readiness' -import { ORCA_SERVE_SUPERVISED_ENV } from '../../shared/serve-supervised-terminal-durability' -import { activateBackendServices } from '../backend/service-composition' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { installOrcadFeatureReadiness } from '../../runtime/rpc/startup/orcad-readiness' +import { ORCA_SERVE_SUPERVISED_ENV } from '../../../shared/serve-supervised-terminal-durability' +import { activateBackendServices } from '../../backend/service-composition' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' let closeOrcadObservability = (): Promise => Promise.resolve() @@ -67,12 +67,12 @@ export async function startOrcad(options: OrcadOptions = {}): Promise void + registerCleanup: (cleanup: BackendServiceCleanup) => void ): Promise> { const { time: timed, report: reportStartupTiming } = createOrcadStartupTiming() // Overlap login-shell probing with imports and store startup. const loginEnvironment = adoptWslHostLoginEnvironmentLogged() - const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision') + const { startOrcadDaemon, stopOrcadDaemon } = await import('../daemon/orcad-daemon-supervision') // The daemon and its PTYs inherit the adopted login env and nothing later startup writes, so it // spawns as soon as that lands, alongside imports, stores and hooks. Rejects only when supervised. const daemonStartup = loginEnvironment.then(() => timed('daemon', () => startOrcadDaemon())) @@ -82,33 +82,34 @@ async function activateOrcadRuntime( // mid-spawn. It disconnects without killing daemon PTYs that must survive restart, after an // in-flight spawn settles; a failed one leaves only the disconnect to do. registerCleanup(() => daemonStartup.catch(() => {}).then(() => stopOrcadDaemon())) - const { OrcaRuntimeService } = await import('../runtime/orca-runtime') - const { OrcaRuntimeRpcServer } = await import('../runtime/rpc/server/runtime-rpc') - const { registerHeadlessPtyRuntime } = await import('../ipc/pty/register-headless-runtime') - const { getLocalPtyProvider } = await import('../ipc/pty/provider/registry') - const { installOrcadObservability } = await import('./orcad-observability') + const { OrcaRuntimeService } = await import('../../runtime/orca-runtime') + const { OrcaRuntimeRpcServer } = await import('../../runtime/rpc/server/runtime-rpc') + const { registerHeadlessPtyRuntime } = await import('../../ipc/pty/register-headless-runtime') + const { getLocalPtyProvider } = await import('../../ipc/pty/provider/registry') + const { installOrcadObservability } = await import('../diagnostics/orcad-observability') closeOrcadObservability = installOrcadObservability() - const { ServeReadinessPublisher } = await import('../server/serve-readiness') - const { servePublishMode } = await import('../server/serve-pairing-readiness') - const { buildOrcadServeReadiness } = await import('./orcad-serve-readiness') - const { createOrcadProfileStateStartup } = await import('./orcad-profile-state-startup') + const { ServeReadinessPublisher } = await import('../../server/serve-readiness') + const { servePublishMode } = await import('../../server/serve-pairing-readiness') + const { buildOrcadServeReadiness } = await import('../serve-startup/orcad-serve-readiness') + const { createOrcadProfileStateStartup } = + await import('../profile-state/orcad-profile-state-startup') const { daemonOwnsFreshPersistentPtys } = - await import('../daemon/providers/lifecycle/daemon-provider-state') + await import('../../daemon/providers/lifecycle/daemon-provider-state') const { resolveDaemonSessionScrollbackRows } = - await import('../daemon/sessions/daemon-session-scrollback-window') - const { collectOrcadHealth } = await import('./orcad-health') - const { agentHookServer } = await import('../agent-hooks/server/agent-hook-server') - await import('../agent-hooks/installation/managed-agent-hook-controls') - const { agentHookRuntimeDeps } = await import('../agent-hooks/runtime/agent-hook-runtime-deps') + await import('../../daemon/sessions/daemon-session-scrollback-window') + const { collectOrcadHealth } = await import('../diagnostics/orcad-health') + const { agentHookServer } = await import('../../agent-hooks/server/agent-hook-server') + await import('../../agent-hooks/installation/managed-agent-hook-controls') + const { agentHookRuntimeDeps } = await import('../../agent-hooks/runtime/agent-hook-runtime-deps') const { installHookStatusSessionTabsRepublish } = - await import('../agent-hooks/runtime/hook-status-session-tabs-republish') + await import('../../agent-hooks/runtime/hook-status-session-tabs-republish') const { startOrcadAgentHookServer, startOrcadManagedAgentHooks } = await import('./orcad-managed-agent-hooks') const { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } = - await import('../runtime/terminal/identity/agent-status-observed-pane-identity') + await import('../../runtime/terminal/identity/agent-status-observed-pane-identity') const { disposeWatcherProcessAndWait } = - await import('../ipc/filesystem/watcher-process/parcel-watcher-process') + await import('../../ipc/filesystem/watcher-process/parcel-watcher-process') let paneGridsForShutdown: { flushPaneGrids(): Promise | null } | null = null let profileStoreForShutdown: Parameters[0] | undefined @@ -127,11 +128,11 @@ async function activateOrcadRuntime( }) registerCleanup(stopOrcadStructuredAgentSessions) registerCleanup(() => disposeWatcherProcessAndWait()) - const { DesktopPushService } = await import('../runtime/push/desktop-push-service') - const { resolvePushGatewayOrigin } = await import('../runtime/push/push-gateway-origin') + const { DesktopPushService } = await import('../../runtime/push/desktop-push-service') + const { resolvePushGatewayOrigin } = await import('../../runtime/push/push-gateway-origin') const runtimeUserDataPath = getAppEnvironment().getPath('userData') - const { startEventLoopDelayProbe } = await import('../diagnostics/event-loop-delay-probe') + const { startEventLoopDelayProbe } = await import('../../diagnostics/event-loop-delay-probe') startEventLoopDelayProbe('orcad', runtimeUserDataPath) await timed('cli-launcher', () => prepareOrcadCliLauncher()).catch((error: unknown) => { console.warn('[orcad] Could not prepare the profile CLI launcher', error) @@ -173,7 +174,7 @@ async function activateOrcadRuntime( // Runtime constructor callbacks use this index only after it is installed. let sessionSearch: { apply(settings: AiVaultSearchSettings): void; dispose(): void } | null = null - const { orcadCodexAccountHomes } = await import('./orcad-codex-account-homes') + const { orcadCodexAccountHomes } = await import('../account-launch/orcad-codex-account-homes') const codexAccountHomes = orcadCodexAccountHomes( () => profileStore.getSettings(), registerCleanup @@ -181,7 +182,7 @@ async function activateOrcadRuntime( // Gates open where each phase finishes today; RPC starts after all of them (no behavior change). const featureReadiness = installOrcadFeatureReadiness() - const { createOrcadAccountServices } = await import('./orcad-account-services') + const { createOrcadAccountServices } = await import('../account-launch/orcad-account-services') const accountLaunch = createOrcadAccountServices({ store: profileStore, setClaudeStatusLineListener: (listener) => @@ -191,7 +192,7 @@ async function activateOrcadRuntime( }) const { loadAgentSessionClaimSigner } = - await import('../runtime/agent-session/ownership/agent-session-claim-identity') + await import('../../runtime/agent-session/ownership/agent-session-claim-identity') const { createOrcadPairedEnvironmentOptions } = await import('./orcad-paired-environment-options') const pairedEnvironments = createOrcadPairedEnvironmentOptions() const runtime = new OrcaRuntimeService(profileStore, stats, { @@ -227,13 +228,14 @@ async function activateOrcadRuntime( accountLaunch?.attachToRuntime(runtime) const { wireGitHubIssueLinkTitleFill } = - await import('../github/workspace-links/github-issue-link-title-wiring') + await import('../../github/workspace-links/github-issue-link-title-wiring') registerCleanup(wireGitHubIssueLinkTitleFill(profileStore, runtime)) const { installOrcadEmulatorBridge } = await import('./orcad-emulator-bridge') installOrcadEmulatorBridge(runtime, registerCleanup) // Restore prior desktop-pushed account selection before automations or CLI launches. - const { restoreOrcadHostAccountLaunchEnv } = await import('./orcad-host-account-launch-env-store') + const { restoreOrcadHostAccountLaunchEnv } = + await import('../account-launch/orcad-host-account-launch-env-store') restoreOrcadHostAccountLaunchEnv(runtime, runtimeUserDataPath) featureReadiness.open('accounts') @@ -246,16 +248,16 @@ async function activateOrcadRuntime( featureReadiness.open('sessionSearch') const { startAgentStateRulesLiveUpdates } = - await import('../runtime/agent-state-rules/agent-state-rules-live-update') + await import('../../runtime/agent-state-rules/agent-state-rules-live-update') startAgentStateRulesLiveUpdates(profileStore, (rules) => console.info(`[orcad] agent state rules ${rules.version} (${rules.source})`) ) // Paired phones dictate through this host; keep its model loaded the same way the desktop does. - const { startSpeechModelWarmup } = await import('../speech/speech-model-warmup') + const { startSpeechModelWarmup } = await import('../../speech/speech-model-warmup') startSpeechModelWarmup(profileStore) if (ORCA_LAYOUT_OWNER_IS_MAIN) { const { repairDuplicatePtyPanesOnStart } = - await import('../runtime/terminal/identity/moved-pane-owner-rekey') + await import('../../runtime/terminal/identity/moved-pane-owner-rekey') // Wait behind earlier writes and persist repair before reconciliation/RPC admission. await repairDuplicatePtyPanesOnStart(profileStore, runtime) } @@ -298,7 +300,7 @@ async function activateOrcadRuntime( agentHookServer.setClaudePermissionHolds(runtime.terminalWorkerApprovals) // First RPC clients must see a fully published graph. const { publishHeadlessRuntimeGraph } = - await import('../runtime/session-graph/headless-runtime-graph') + await import('../../runtime/session-graph/headless-runtime-graph') publishHeadlessRuntimeGraph(runtime) // Only the runtime can identify running shells and install deferred migrated history. void runtime.installPendingOrcadMigrationShellHistory().catch((error: unknown) => { diff --git a/src/main/orcad/orcad-host-adapters.ts b/src/main/orcad/host-runtime/orcad-host-adapters.ts similarity index 80% rename from src/main/orcad/orcad-host-adapters.ts rename to src/main/orcad/host-runtime/orcad-host-adapters.ts index 63ce0b05d38..9049e511e82 100644 --- a/src/main/orcad/orcad-host-adapters.ts +++ b/src/main/orcad/host-runtime/orcad-host-adapters.ts @@ -1,14 +1,14 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import process from 'node:process' -import { ORCAD_CLI_PACKAGE_FILENAME } from '../../shared/orcad-artifacts' -import { setAppEnvironment, type AppEnvironment } from '../../shared/app-environment' -import { createNodeServiceEnvironment } from '../backend/node-service-environment' -import { setSecretStore } from '../../shared/secret-store' +import { ORCAD_CLI_PACKAGE_FILENAME } from '../../../shared/orcad-artifacts' +import { setAppEnvironment, type AppEnvironment } from '../../../shared/app-environment' +import { createNodeServiceEnvironment } from '../../backend/node-service-environment' +import { setSecretStore } from '../../../shared/secret-store' import { resolveOrcadInstallRoot, resolveOrcadPath } from './orcad-app-paths' -import { getOrcadCliLauncherPath } from './orcad-cli-launcher' -import { createOrcadSecretStore, type OrcadSecretStore } from './orcad-secret-store' -import { setSpeechServiceFactories } from '../speech/speech-runtime-service' +import { getOrcadCliLauncherPath } from '../serve-startup/orcad-cli-launcher' +import { createOrcadSecretStore, type OrcadSecretStore } from '../credentials/orcad-secret-store' +import { setSpeechServiceFactories } from '../../speech/speech-runtime-service' import { orcadSpeechServiceFactories } from './orcad-speech-services' let quitRegisteredHandlers = (): void => {} diff --git a/src/main/orcad/orcad-managed-agent-hooks.ts b/src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts similarity index 65% rename from src/main/orcad/orcad-managed-agent-hooks.ts rename to src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts index 1e3bdc4ebb7..efbe72ef3df 100644 --- a/src/main/orcad/orcad-managed-agent-hooks.ts +++ b/src/main/orcad/host-runtime/orcad-managed-agent-hooks.ts @@ -1,18 +1,18 @@ -import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service' -import { getAppEnvironment } from '../../shared/app-environment' -import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { adoptLoginShellAgentHomes } from '../agent-hooks/installation/agent-home-login-shell' -import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' +import { getClaudeAgentViewService } from '../../claude/agent-view/agent-view-service' +import { getAppEnvironment } from '../../../shared/app-environment' +import { startCodexHooks } from '../../codex/hooks/reconciliation/codex-hook-reconcile' +import { adoptLoginShellAgentHomes } from '../../agent-hooks/installation/agent-home-login-shell' +import { hydrateAgentCliShellPath } from '../../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' -import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/status-hooks/opencode-status-plugin-startup-refresh' -import type { ProfilePreferences } from '../persistence/loading-store/profile-preferences/profile-preferences' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' -import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { reconcileStartupManagedAgentHooks } from '../../agent-hooks/installation/managed-agent-hook-startup' +import { refreshInstalledOpenCodeStatusPlugins } from '../../opencode/status-hooks/opencode-status-plugin-startup-refresh' +import type { ProfilePreferences } from '../../persistence/loading-store/profile-preferences/profile-preferences' +import type { BackendServiceCleanup } from '../../backend/service-composition' +import type { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { installLocalHookRootEvidence } from '../../agent-hooks/observations/local-hook-root-evidence' /** SSH and WSL-host panes run beside this host, so it proves which agent owns each pane, from the * first record its startup replay reads. */ @@ -31,7 +31,7 @@ export function startOrcadAgentHookServer( export function startOrcadManagedAgentHooks( store: Pick, setStatusHooksEnabled: (enabled: boolean) => void, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void ): { readinessPublished: () => void } { const published = Promise.withResolvers() let stopping = false diff --git a/src/main/orcad/orcad-paired-environment-options.ts b/src/main/orcad/host-runtime/orcad-paired-environment-options.ts similarity index 75% rename from src/main/orcad/orcad-paired-environment-options.ts rename to src/main/orcad/host-runtime/orcad-paired-environment-options.ts index 4430d41babc..29b2800e162 100644 --- a/src/main/orcad/orcad-paired-environment-options.ts +++ b/src/main/orcad/host-runtime/orcad-paired-environment-options.ts @@ -1,6 +1,6 @@ -import { createOrchestrationEnvironmentTransport } from '../ipc/runtime-environments/orchestration-environment-transport' -import type { RuntimeConstructionDependencies } from '../runtime/construction/runtime-construction-dependencies' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' +import { createOrchestrationEnvironmentTransport } from '../../ipc/runtime-environments/orchestration-environment-transport' +import type { RuntimeConstructionDependencies } from '../../runtime/construction/runtime-construction-dependencies' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' type PairedEnvironmentRuntimeOptions = Required< Pick diff --git a/src/main/orcad/orcad-restored-terminal-authority.ts b/src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts similarity index 62% rename from src/main/orcad/orcad-restored-terminal-authority.ts rename to src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts index 86e8dc4d3aa..3141ccebd51 100644 --- a/src/main/orcad/orcad-restored-terminal-authority.ts +++ b/src/main/orcad/host-runtime/orcad-restored-terminal-authority.ts @@ -1,8 +1,8 @@ -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { OrcadFeatureReadiness } from '../runtime/rpc/startup/orcad-readiness' -import { placeUnshownLiveTerminalsBestEffort } from '../runtime/terminal/adoption/unshown-live-terminal-placement' -import type { createOrcadStartupTiming } from './orcad-startup-timing' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { OrcadFeatureReadiness } from '../../runtime/rpc/startup/orcad-readiness' +import { placeUnshownLiveTerminalsBestEffort } from '../../runtime/terminal/adoption/unshown-live-terminal-placement' +import type { createOrcadStartupTiming } from '../diagnostics/orcad-startup-timing' /** Restored orchestration authority, the legacy terminal reconcile and unshown placement, in order. */ export async function restoreOrcadTerminalAuthority( diff --git a/src/main/orcad/orcad-session-scanner-idle.ts b/src/main/orcad/host-runtime/orcad-session-scanner-idle.ts similarity index 82% rename from src/main/orcad/orcad-session-scanner-idle.ts rename to src/main/orcad/host-runtime/orcad-session-scanner-idle.ts index f7e83c9a354..961913db36d 100644 --- a/src/main/orcad/orcad-session-scanner-idle.ts +++ b/src/main/orcad/host-runtime/orcad-session-scanner-idle.ts @@ -1,4 +1,4 @@ -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' /** WSL hosts hold a per-distro memory budget; a retire there costs the next scan ~1.5x on a big history. */ export const WSL_HOST_SESSION_SCANNER_IDLE_TIMEOUT_MS = 3 * 60_000 @@ -14,7 +14,7 @@ export async function applyOrcadSessionScannerIdleTimeout(): Promise { const timeoutMs = orcadSessionScannerIdleTimeoutMs() if (timeoutMs !== null) { const { setAiVaultServiceIdleTimeoutMs } = - await import('../ai-vault/scan-service/session-scanner-service-spawn') + await import('../../ai-vault/scan-service/session-scanner-service-spawn') setAiVaultServiceIdleTimeoutMs(timeoutMs) } } diff --git a/src/main/orcad/orcad-session-search.ts b/src/main/orcad/host-runtime/orcad-session-search.ts similarity index 63% rename from src/main/orcad/orcad-session-search.ts rename to src/main/orcad/host-runtime/orcad-session-search.ts index 78ae307b122..f463806ca0b 100644 --- a/src/main/orcad/orcad-session-search.ts +++ b/src/main/orcad/host-runtime/orcad-session-search.ts @@ -1,12 +1,12 @@ -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { type AiVaultSearchSettings, resolveAiVaultSearchSettings -} from '../../shared/ai-vault/search/ai-vault-search-settings' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { localAiVaultScanRoots } from '../ai-vault/discovery/ai-vault-scan-roots' -import { installInProcessSessionSearchService } from '../ai-vault-search/session-search-in-process-service' +} from '../../../shared/ai-vault/search/ai-vault-search-settings' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { localAiVaultScanRoots } from '../../ai-vault/discovery/ai-vault-scan-roots' +import { installInProcessSessionSearchService } from '../../ai-vault-search/session-search-in-process-service' /** Index in-process as sole writer; the scanner child has no installed search data root. */ export async function installOrcadSessionSearchService(args: { diff --git a/src/main/orcad/host-runtime/orcad-speech-services.ts b/src/main/orcad/host-runtime/orcad-speech-services.ts new file mode 100644 index 00000000000..e51a29710d2 --- /dev/null +++ b/src/main/orcad/host-runtime/orcad-speech-services.ts @@ -0,0 +1,19 @@ +import { ModelManager } from '../../speech/model-manager' +import { openNodeSpeechDownloadRequest } from '../../speech/node-speech-download-request' +import { canReadCloudSpeechCredentials } from '../../speech/cloud-transcription-target' +import type { SpeechServiceFactories } from '../../speech/speech-runtime-service' +import { SttService } from '../../speech/stt-service' +import { createSttGpuPolicy } from '../../speech/stt-gpu-failure-marker' +import { spawnSttWorkerWithCpuFallback } from '../../speech/stt-worker-cpu-fallback' +import { spawnSttForkedProcess } from '../../speech/stt-worker-forked-process' + +// Local speech needs the installed app recognizer supplied by orca serve. +export const orcadSpeechServiceFactories: SpeechServiceFactories = { + createModelManager: (customModelsDir) => + // Headless key reads cannot open keychain prompts, so readiness may verify decryption. + new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadCloudSpeechCredentials), + createSttService: (models, gpuEnabled) => { + const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) + return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu)) + } +} diff --git a/src/main/orcad/orcad-stats.ts b/src/main/orcad/host-runtime/orcad-stats.ts similarity index 63% rename from src/main/orcad/orcad-stats.ts rename to src/main/orcad/host-runtime/orcad-stats.ts index 260054832da..c1938f98391 100644 --- a/src/main/orcad/orcad-stats.ts +++ b/src/main/orcad/host-runtime/orcad-stats.ts @@ -1,11 +1,11 @@ -import { feedAgentSessionStats, type AgentStatusSource } from '../stats/agent-session-stats-feed' -import { initStatsPath, StatsCollector } from '../stats/collector' -import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' +import { feedAgentSessionStats, type AgentStatusSource } from '../../stats/agent-session-stats-feed' +import { initStatsPath, StatsCollector } from '../../stats/collector' +import type { BackendServiceCleanup } from '../../backend/service-composition' export function startOrcadStats( userDataPath: string, hooks: AgentStatusSource, - registerCleanup: (cleanup: OrcadRuntimeCleanup) => void + registerCleanup: (cleanup: BackendServiceCleanup) => void ): StatsCollector { initStatsPath(userDataPath) const stats = new StatsCollector() diff --git a/src/main/orcad/orcad-wsl-host-login-environment.ts b/src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts similarity index 90% rename from src/main/orcad/orcad-wsl-host-login-environment.ts rename to src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts index 943ad23dee1..9ca2e61c729 100644 --- a/src/main/orcad/orcad-wsl-host-login-environment.ts +++ b/src/main/orcad/host-runtime/orcad-wsl-host-login-environment.ts @@ -1,7 +1,7 @@ // WSL exec skips shell setup; hydrate login-shell credentials/proxies before git and daemon startup. -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import { PROBE_MARKER_ENV_VAR } from '../startup/shell-environment/hydrate-shell-path' -import { resolveLoginShellEnvironment } from '../startup/shell-environment/login-shell-environment' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import { PROBE_MARKER_ENV_VAR } from '../../startup/shell-environment/hydrate-shell-path' +import { resolveLoginShellEnvironment } from '../../startup/shell-environment/login-shell-environment' // Allowlist excludes GUI askpass (which could block) and PATH (which has separate drive filtering). const WSL_HOST_LOGIN_ENV_NAMES: readonly string[] = [ diff --git a/src/main/orcad/orcad-data-root-locality.ts b/src/main/orcad/instance-lock/orcad-data-root-locality.ts similarity index 100% rename from src/main/orcad/orcad-data-root-locality.ts rename to src/main/orcad/instance-lock/orcad-data-root-locality.ts diff --git a/src/main/orcad/orcad-data-root-privacy.ts b/src/main/orcad/instance-lock/orcad-data-root-privacy.ts similarity index 96% rename from src/main/orcad/orcad-data-root-privacy.ts rename to src/main/orcad/instance-lock/orcad-data-root-privacy.ts index f32688b0a59..412ad8544f1 100644 --- a/src/main/orcad/orcad-data-root-privacy.ts +++ b/src/main/orcad/instance-lock/orcad-data-root-privacy.ts @@ -1,6 +1,6 @@ import { chmodSync, statSync } from 'node:fs' import process from 'node:process' -import { restrictWindowsPathSync } from '../../shared/secure-storage/secure-path-windows-acl' +import { restrictWindowsPathSync } from '../../../shared/secure-storage/secure-path-windows-acl' type OrcadInstanceLockCode = | 'orcad_data_root_unusable' diff --git a/src/main/orcad/orcad-instance-lock-hold.ts b/src/main/orcad/instance-lock/orcad-instance-lock-hold.ts similarity index 98% rename from src/main/orcad/orcad-instance-lock-hold.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-hold.ts index 31542c1703a..97574747cb5 100644 --- a/src/main/orcad/orcad-instance-lock-hold.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock-hold.ts @@ -7,7 +7,7 @@ import { parseOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' export type OrcadInstanceLock = { readonly path: string diff --git a/src/main/orcad/orcad-instance-lock-reclaim.ts b/src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts similarity index 97% rename from src/main/orcad/orcad-instance-lock-reclaim.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts index e8444b6804a..0518327c2a1 100644 --- a/src/main/orcad/orcad-instance-lock-reclaim.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock-reclaim.ts @@ -13,8 +13,8 @@ import { import { basename, dirname, join } from 'node:path' import process from 'node:process' import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { readNodeFileSyncWithinLimit } from '../../shared/file-content/node-bounded-file-reader' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' +import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader' +import { hasErrorCode } from '../../daemon/endpoint/identity/daemon-process-inspection' export const MAX_ORCAD_LOCK_BYTES = 64 * 1024 // Serialize recovery so reclaimers cannot displace newly published live locks. diff --git a/src/main/orcad/orcad-instance-lock-record.ts b/src/main/orcad/instance-lock/orcad-instance-lock-record.ts similarity index 100% rename from src/main/orcad/orcad-instance-lock-record.ts rename to src/main/orcad/instance-lock/orcad-instance-lock-record.ts diff --git a/src/main/orcad/orcad-instance-lock.test.ts b/src/main/orcad/instance-lock/orcad-instance-lock.test.ts similarity index 99% rename from src/main/orcad/orcad-instance-lock.test.ts rename to src/main/orcad/instance-lock/orcad-instance-lock.test.ts index 4c3419d48b3..2991dde3c2f 100644 --- a/src/main/orcad/orcad-instance-lock.test.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock.test.ts @@ -16,10 +16,9 @@ import type * as NodeFs from 'node:fs' import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, - readOrcadInstanceLockRecord, - type OrcadInstanceLockHooks, - type OrcadLockRecord + type OrcadInstanceLockHooks } from './orcad-instance-lock' +import { readOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' import { OrcadInstanceLockError } from './orcad-data-root-privacy' // Inject a contender immediately after canonical-lock rename. diff --git a/src/main/orcad/orcad-instance-lock.ts b/src/main/orcad/instance-lock/orcad-instance-lock.ts similarity index 94% rename from src/main/orcad/orcad-instance-lock.ts rename to src/main/orcad/instance-lock/orcad-instance-lock.ts index 95ad6fbc0bc..fe56fc3dab6 100644 --- a/src/main/orcad/orcad-instance-lock.ts +++ b/src/main/orcad/instance-lock/orcad-instance-lock.ts @@ -18,12 +18,15 @@ import { OrcadInstanceLockError, type OrcadDataRootPrivacyHooks } from './orcad-data-root-privacy' -import { hasErrorCode, isProcessAlive } from '../daemon/endpoint/identity/daemon-process-inspection' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { + hasErrorCode, + isProcessAlive +} from '../../daemon/endpoint/identity/daemon-process-inspection' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' -import type { OrcadReclaimHintRuntime } from '../../shared/orcad-stale-lock-reclaim' -import { reclaimedUnexpectedExit } from './orcad-unexpected-exit' -import type { OrcadUnexpectedExit } from '../../shared/orcad-unexpected-exit' +import type { OrcadReclaimHintRuntime } from '../../../shared/orcad-stale-lock-reclaim' +import { reclaimedUnexpectedExit } from '../host-lifecycle/orcad-unexpected-exit' +import type { OrcadUnexpectedExit } from '../../../shared/orcad-unexpected-exit' import { orcadLockHolderLocality, orcadLockHolderUnverifiableError @@ -47,13 +50,6 @@ import { } from './orcad-instance-lock-record' import { holdOrcadInstanceLock, type OrcadInstanceLock } from './orcad-instance-lock-hold' -export { - parseOrcadInstanceLockRecord, - readOrcadInstanceLockRecord, - type OrcadLockRecord -} from './orcad-instance-lock-record' -export type { OrcadInstanceLock } from './orcad-instance-lock-hold' - export const ORCAD_LOCK_FILE_NAME = 'orcad.lock' // Allow old torn writes time to complete before treating garbled records as abandoned. const GARBLED_LOCK_GRACE_MS = 10_000 diff --git a/src/main/orcad/orcad-lock-clone-machine.ts b/src/main/orcad/instance-lock/orcad-lock-clone-machine.ts similarity index 94% rename from src/main/orcad/orcad-lock-clone-machine.ts rename to src/main/orcad/instance-lock/orcad-lock-clone-machine.ts index 7926733665f..78951edcb93 100644 --- a/src/main/orcad/orcad-lock-clone-machine.ts +++ b/src/main/orcad/instance-lock/orcad-lock-clone-machine.ts @@ -1,9 +1,9 @@ // Images cloned with one /etc/machine-id look like one machine to every PID check (#32918). import { statSync } from 'node:fs' import process from 'node:process' -import { ORCA_MACHINE_NAME_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCA_MACHINE_NAME_ENV } from '../../../shared/orcad-managed-launch-env' import type { OrcadPeerMachine } from './orcad-lock-holder-locality' -import { currentLinuxBootStartedAtMs } from '../persistence/profile-state/access/profile-state-access-identity' +import { currentLinuxBootStartedAtMs } from '../../persistence/profile-state/access/profile-state-access-identity' const CLONE_MACHINE_ID_HINT = 'Machines cloned from one image share /etc/machine-id, so Orca cannot tell them apart. If the Orca ' + diff --git a/src/main/orcad/orcad-lock-holder-locality.ts b/src/main/orcad/instance-lock/orcad-lock-holder-locality.ts similarity index 94% rename from src/main/orcad/orcad-lock-holder-locality.ts rename to src/main/orcad/instance-lock/orcad-lock-holder-locality.ts index dc5489b27be..33dcb62b2cd 100644 --- a/src/main/orcad/orcad-lock-holder-locality.ts +++ b/src/main/orcad/instance-lock/orcad-lock-holder-locality.ts @@ -1,12 +1,12 @@ import process from 'node:process' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' import { readOrcadProcessIncarnation } from './orcad-process-start-time' import { OrcadInstanceLockError } from './orcad-data-root-privacy' import { orcadCloneMachineHint, orcadPeerIsLiveCloneMachine } from './orcad-lock-clone-machine' import { orcadStaleLockReclaimCommand, type OrcadReclaimHintRuntime -} from '../../shared/orcad-stale-lock-reclaim' +} from '../../../shared/orcad-stale-lock-reclaim' /** Match machine identity, then legacy boot identity; identity-less records require local-only storage. */ export function orcadLockHolderLocality( diff --git a/src/main/orcad/orcad-process-start-time.test.ts b/src/main/orcad/instance-lock/orcad-process-start-time.test.ts similarity index 94% rename from src/main/orcad/orcad-process-start-time.test.ts rename to src/main/orcad/instance-lock/orcad-process-start-time.test.ts index 4eb2b6442e5..527b55de466 100644 --- a/src/main/orcad/orcad-process-start-time.test.ts +++ b/src/main/orcad/instance-lock/orcad-process-start-time.test.ts @@ -3,16 +3,16 @@ import { mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as DaemonProcessStartTime from '../daemon/endpoint/identity/daemon-process-start-time' +import type * as DaemonProcessStartTime from '../../daemon/endpoint/identity/daemon-process-start-time' const { readWindowsProcessCreationTime, getProcessStartedAtMs } = vi.hoisted(() => ({ readWindowsProcessCreationTime: vi.fn<(pid: number) => number | null>(), getProcessStartedAtMs: vi.fn<(pid: number) => number | null>() })) -vi.mock('../windows/windows-process-table', () => ({ +vi.mock('../../windows/windows-process-table', () => ({ readWindowsProcessCreationTime })) -vi.mock('../daemon/endpoint/identity/daemon-process-start-time', async (importOriginal) => ({ +vi.mock('../../daemon/endpoint/identity/daemon-process-start-time', async (importOriginal) => ({ ...(await importOriginal()), getProcessStartedAtMs })) diff --git a/src/main/orcad/orcad-process-start-time.ts b/src/main/orcad/instance-lock/orcad-process-start-time.ts similarity index 94% rename from src/main/orcad/orcad-process-start-time.ts rename to src/main/orcad/instance-lock/orcad-process-start-time.ts index 555ace95778..7b5159cd01f 100644 --- a/src/main/orcad/orcad-process-start-time.ts +++ b/src/main/orcad/instance-lock/orcad-process-start-time.ts @@ -1,12 +1,12 @@ // Linux ticks/boot ID avoid drifting wall time; Windows uses kernel creation time. Unknown never proves exit. import { readFileSync, statSync } from 'node:fs' -import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../agent-hooks/installation/locking/managed-hook-owner-identity' import { getProcessStartedAtMs, START_TIME_TOLERANCE_MS, startTimesWithinTolerance -} from '../daemon/endpoint/identity/daemon-process-start-time' -import { readWindowsProcessCreationTime } from '../windows/windows-process-table' +} from '../../daemon/endpoint/identity/daemon-process-start-time' +import { readWindowsProcessCreationTime } from '../../windows/windows-process-table' export type OrcadProcessIncarnation = { linuxStartTicks: string; bootId: string } diff --git a/src/main/orcad/orcad-stale-lock-reclaim.test.ts b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts similarity index 97% rename from src/main/orcad/orcad-stale-lock-reclaim.test.ts rename to src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts index 060740df8e5..15aa04e2a9e 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.test.ts +++ b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.test.ts @@ -10,9 +10,10 @@ import { import { createServer, type Server } from 'node:net' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { ORCAD_LOCK_FILE_NAME, readOrcadInstanceLockRecord } from './orcad-instance-lock' -import type { OrcadLockRecord } from './orcad-instance-lock' -import { shortDaemonSocketDir } from '../daemon/endpoint/publication/daemon-socket-endpoint-path' +import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' +import { readOrcadInstanceLockRecord } from './orcad-instance-lock-record' +import type { OrcadLockRecord } from './orcad-instance-lock-record' +import { shortDaemonSocketDir } from '../../daemon/endpoint/publication/daemon-socket-endpoint-path' import { probeOrcadEndpoint, reclaimStaleOrcadInstanceLock, diff --git a/src/main/orcad/orcad-stale-lock-reclaim.ts b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts similarity index 93% rename from src/main/orcad/orcad-stale-lock-reclaim.ts rename to src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts index 4ba94080ccb..2ed93b481f6 100644 --- a/src/main/orcad/orcad-stale-lock-reclaim.ts +++ b/src/main/orcad/instance-lock/orcad-stale-lock-reclaim.ts @@ -8,23 +8,22 @@ import process from 'node:process' import { acquireOrcadInstanceLock, ORCAD_LOCK_FILE_NAME, - parseOrcadInstanceLockRecord, - type OrcadInstanceLockHooks, - type OrcadLockRecord + type OrcadInstanceLockHooks } from './orcad-instance-lock' +import { parseOrcadInstanceLockRecord, type OrcadLockRecord } from './orcad-instance-lock-record' import { readBoundedLockFile } from './orcad-instance-lock-reclaim' import { orcadLockHolderLocality } from './orcad-lock-holder-locality' import { ORCAD_LOCK_FRESH_MS, orcadLockPeer, orcadLockSelf } from './orcad-lock-clone-machine' import { orcadDataRootIsOnLocalDisk } from './orcad-data-root-locality' import { readOrcadProcessIncarnation } from './orcad-process-start-time' -import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' -import { resolveUserDataPath } from './orcad-app-paths' -import { profileStateAccessMachineIdentity } from '../persistence/profile-state/access/profile-state-access-identity' -import { readRuntimeMetadata } from '../runtime/rpc/server/runtime-metadata' +import { hasErrorCode } from '../../daemon/endpoint/identity/daemon-process-inspection' +import { resolveUserDataPath } from '../host-runtime/orcad-app-paths' +import { profileStateAccessMachineIdentity } from '../../persistence/profile-state/access/profile-state-access-identity' +import { readRuntimeMetadata } from '../../runtime/rpc/server/runtime-metadata' import { RUNTIME_SOCKET_NAME_REGEX, runtimeSocketDirs -} from '../runtime/rpc/server/runtime-rpc-socket-metadata' +} from '../../runtime/rpc/server/runtime-rpc-socket-metadata' import { ORCAD_RECLAIM_STALE_LOCK_FLAG, ORCAD_STALE_LOCK_DATA_ROOT_FLAG, @@ -33,10 +32,8 @@ import { type OrcadReclaimHintRuntime, type OrcadStaleLockEvidence, type OrcadStaleLockReclaimStatus -} from '../../shared/orcad-stale-lock-reclaim' +} from '../../../shared/orcad-stale-lock-reclaim' -// A new holder may not listen yet, and NFS attribute caching can age a live heartbeat this much. -export const ORCAD_STALE_LOCK_MIN_AGE_MS = ORCAD_LOCK_FRESH_MS const ENDPOINT_PROBE_TIMEOUT_MS = 1_500 /** Silent requires OS-confirmed absence of a listener; errors leave ownership unknown. */ @@ -177,8 +174,8 @@ async function checkStaleLock( } const now = (hooks.now ?? Date.now)() const writtenMs = Math.max(Date.parse(holder.acquiredAt), statOrNull(lockPath)?.mtimeMs ?? now) - if (!(now - writtenMs >= ORCAD_STALE_LOCK_MIN_AGE_MS)) { - return { refusal: `The lock is less than ${ORCAD_STALE_LOCK_MIN_AGE_MS / 60_000} minutes old.` } + if (!(now - writtenMs >= ORCAD_LOCK_FRESH_MS)) { + return { refusal: `The lock is less than ${ORCAD_LOCK_FRESH_MS / 60_000} minutes old.` } } const endpoints = await holderEndpoints(dataRoot, holder.pid) if (!endpoints) { diff --git a/src/main/orcad/orcad-wsl-holder-release.ts b/src/main/orcad/instance-lock/orcad-wsl-holder-release.ts similarity index 82% rename from src/main/orcad/orcad-wsl-holder-release.ts rename to src/main/orcad/instance-lock/orcad-wsl-holder-release.ts index 942c21abf82..2a348888168 100644 --- a/src/main/orcad/orcad-wsl-holder-release.ts +++ b/src/main/orcad/instance-lock/orcad-wsl-holder-release.ts @@ -4,10 +4,10 @@ */ import { rmSync } from 'node:fs' import { join } from 'node:path' -import { ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../shared/orcad-idle-exit' -import { writeSecureFile } from '../../shared/secure-storage/secure-file' -import { ORCAD_WSL_HOST_ENV } from '../ipc/wsl-guest-windows-drive-path' -import type { OrcadDaemonRetirement } from './orcad-daemon-retirement' +import { ORCAD_WSL_HOLDER_RELEASE_FILENAME } from '../../../shared/orcad-idle-exit' +import { writeSecureFile } from '../../../shared/secure-storage/secure-file' +import { ORCAD_WSL_HOST_ENV } from '../../../shared/orcad-server-launch-env' +import type { OrcadDaemonRetirement } from '../daemon/orcad-daemon-retirement' export function orcadWslHolderReleasePath(userDataPath: string): string { return join(userDataPath, ORCAD_WSL_HOLDER_RELEASE_FILENAME) diff --git a/src/main/orcad/launcher.ts b/src/main/orcad/launcher.ts index bb956c00737..031142e16db 100644 --- a/src/main/orcad/launcher.ts +++ b/src/main/orcad/launcher.ts @@ -3,9 +3,12 @@ import { readFileSync, realpathSync } from 'node:fs' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' import { ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' -import { assertOrcadServerRuntime, handoffToBundledOrcad } from './orcad-bundled-runtime' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { enableManagedOrcadCompileCache } from './orcad-compile-cache' +import { + assertOrcadServerRuntime, + handoffToBundledOrcad +} from './runtime-launch/orcad-bundled-runtime' +import { ORCAD_EXIT_CONFIGURATION } from './serve-startup/orcad-configuration-exit' +import { enableManagedOrcadCompileCache } from './runtime-launch/orcad-compile-cache' declare const ORCAD_SERVER_SHA256: string diff --git a/src/main/orcad/main.ts b/src/main/orcad/main.ts index 4f64317bcb7..c3eed2168d5 100644 --- a/src/main/orcad/main.ts +++ b/src/main/orcad/main.ts @@ -1,9 +1,9 @@ import '../memory/host-malloc-tunables-claim' import process from 'node:process' -import { main } from './orcad-command-startup' -import { resolveOrcadExitCode } from './orcad-exit-code' +import { main } from './serve-startup/orcad-command-startup' +import { resolveOrcadExitCode } from './serve-startup/orcad-exit-code' import { reserveServeStdoutForReadiness } from '../server/serve-stdout-boundary' -import { runOrcadNativePreflightVerdict } from './orcad-native-preflight' +import { runOrcadNativePreflightVerdict } from './native-runtime/orcad-native-preflight' import { ORCAD_PROFILE_PREFLIGHT_FLAG, ORCAD_STARTUP_PREFLIGHT_FLAG @@ -15,8 +15,8 @@ import { forgetBundledOrcadStartupQualification, preflightBundledOrcadStartup, runOrcadProfilePreflight -} from './orcad-profile-preflight' -import { assertOrcadServerRuntime } from './orcad-bundled-runtime' +} from './runtime-launch/orcad-profile-preflight' +import { assertOrcadServerRuntime } from './runtime-launch/orcad-bundled-runtime' import { formatOrcadNativePreflightReport, ORCAD_NATIVE_PREFLIGHT_FLAG @@ -30,7 +30,7 @@ import { WINDOWS_BREAKAWAY_LAUNCH_FLAG } from '../../shared/windows-breakaway-launch' import { runWindowsBreakawayLaunchIfRequested } from '../../shared/windows-breakaway-launcher' -import { parseArgs } from './orcad-command-arguments' +import { parseArgs } from './serve-startup/orcad-command-arguments' import { ORCAD_RECLAIM_STALE_LOCK_FLAG } from '../../shared/orcad-stale-lock-reclaim' // A resolved plain-Node module graph proves the build guard; skip probes, ports and data-root locks. @@ -46,7 +46,7 @@ function failStartup(error: unknown): void { // One-shot launch and stop commands must skip server startup and preflights. if (process.argv[2] === '--orcad-structured-provider-load-check') { - void import('./orcad-structured-provider-smoke') + void import('./native-runtime/orcad-structured-provider-smoke') .then(({ smokeLoadOrcadStructuredProviders }) => smokeLoadOrcadStructuredProviders()) .then(() => process.exit(0)) .catch(failStartup) @@ -56,12 +56,14 @@ if (process.argv[2] === '--orcad-structured-provider-load-check') { process.argv[2] === ORCAD_COMPLETE_MANAGED_STOP_FLAG || process.argv[2] === ORCAD_CANCEL_MANAGED_STOP_FLAG ) { - void import('./orcad-managed-stop-command').then(({ runOrcadManagedStopCommandAndExit }) => - runOrcadManagedStopCommandAndExit(process.argv.slice(2)) + void import('./host-lifecycle/managed-stop/orcad-managed-stop-command').then( + ({ runOrcadManagedStopCommandAndExit }) => + runOrcadManagedStopCommandAndExit(process.argv.slice(2)) ) } else if (process.argv[2] === ORCAD_RECLAIM_STALE_LOCK_FLAG) { - void import('./orcad-stale-lock-reclaim').then(({ runOrcadStaleLockReclaimCommandAndExit }) => - runOrcadStaleLockReclaimCommandAndExit(process.argv.slice(2)) + void import('./instance-lock/orcad-stale-lock-reclaim').then( + ({ runOrcadStaleLockReclaimCommandAndExit }) => + runOrcadStaleLockReclaimCommandAndExit(process.argv.slice(2)) ) } else { startOrcadProcess() @@ -77,7 +79,7 @@ function startOrcadProcess(): void { assertOrcadServerRuntime() const flag = process.argv[2] if (flag === ORCAD_NATIVE_PREFLIGHT_FLAG && process.argv.length === 3) { - void import('./node-pty-precondition').then(({ checkNodePtyPrecondition }) => { + void import('./native-runtime/node-pty-precondition').then(({ checkNodePtyPrecondition }) => { const verdict = checkNodePtyPrecondition() const report = formatOrcadNativePreflightReport(verdict.status, verdict.reason ?? null) process.stdout.write(`${report}\n`, () => process.exit(0)) diff --git a/src/main/orcad/orcad-migration-destination-capabilities.ts b/src/main/orcad/migration/orcad-migration-destination-capabilities.ts similarity index 85% rename from src/main/orcad/orcad-migration-destination-capabilities.ts rename to src/main/orcad/migration/orcad-migration-destination-capabilities.ts index dd10fd3a2ef..0ab1583679d 100644 --- a/src/main/orcad/orcad-migration-destination-capabilities.ts +++ b/src/main/orcad/migration/orcad-migration-destination-capabilities.ts @@ -1,5 +1,5 @@ -import { advertisedOrcadMigrationBlobCapabilities } from '../../shared/orcad-migration/orcad-migration-blob-transfer' -import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../shared/session-tabs-runtime-capabilities' +import { advertisedOrcadMigrationBlobCapabilities } from '../../../shared/orcad-migration/orcad-migration-blob-transfer' +import { SESSION_TERMINAL_SCROLLBACK_READ_RUNTIME_CAPABILITY } from '../../../shared/session-tabs-runtime-capabilities' import { servesWslMovedPaneHistory } from './orcad-migration-wsl-destination' /** diff --git a/src/main/orcad/orcad-migration-manifest-digest.ts b/src/main/orcad/migration/orcad-migration-manifest-digest.ts similarity index 94% rename from src/main/orcad/orcad-migration-manifest-digest.ts rename to src/main/orcad/migration/orcad-migration-manifest-digest.ts index 810dc4aa8f3..410dcd0fc6e 100644 --- a/src/main/orcad/orcad-migration-manifest-digest.ts +++ b/src/main/orcad/migration/orcad-migration-manifest-digest.ts @@ -3,7 +3,7 @@ import { orcadMigrationManifestHashInput, serializeOrcadMigrationValue, type OrcadMigrationManifest -} from '../../shared/orcad-migration/orcad-migration-manifest' +} from '../../../shared/orcad-migration/orcad-migration-manifest' export function computeOrcadMigrationManifestSha256( manifest: Omit diff --git a/src/main/orcad/orcad-migration-wsl-destination.ts b/src/main/orcad/migration/orcad-migration-wsl-destination.ts similarity index 81% rename from src/main/orcad/orcad-migration-wsl-destination.ts rename to src/main/orcad/migration/orcad-migration-wsl-destination.ts index 1982c6392e4..16faa2b9f91 100644 --- a/src/main/orcad/orcad-migration-wsl-destination.ts +++ b/src/main/orcad/migration/orcad-migration-wsl-destination.ts @@ -1,13 +1,11 @@ // In-place WSL moves require the desktop-launched orcad in the source distro to own the unchanged paths. -import type { OrcadMigrationManifestSource } from '../../shared/orcad-migration/orcad-migration-manifest' -import { isOrcadMigrationLocalWslSource } from '../../shared/orcad-migration/orcad-migration-source-kind' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' -import { ORCAD_WSL_DISTRO_GUID_ENV } from '../../shared/orcad-server-launch-env' +import type { OrcadMigrationManifestSource } from '../../../shared/orcad-migration/orcad-migration-manifest' +import { isOrcadMigrationLocalWslSource } from '../../../shared/orcad-migration/orcad-migration-source-kind' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' +import { ORCAD_WSL_DISTRO_GUID_ENV } from '../../../shared/orcad-server-launch-env' export const ORCAD_MIGRATION_SOURCE_NOT_THIS_HOST = 'orcad_migration_source_not_this_host' -export { ORCAD_WSL_DISTRO_GUID_ENV } - export function servesLocalWslMigrationSource( env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform diff --git a/src/main/orcad/build-toolchain-diagnosis.ts b/src/main/orcad/native-runtime/build-toolchain-diagnosis.ts similarity index 100% rename from src/main/orcad/build-toolchain-diagnosis.ts rename to src/main/orcad/native-runtime/build-toolchain-diagnosis.ts diff --git a/src/main/orcad/native-host-abi.ts b/src/main/orcad/native-runtime/native-host-abi.ts similarity index 100% rename from src/main/orcad/native-host-abi.ts rename to src/main/orcad/native-runtime/native-host-abi.ts diff --git a/src/main/orcad/node-pty-loader-diagnosis.ts b/src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts similarity index 95% rename from src/main/orcad/node-pty-loader-diagnosis.ts rename to src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts index 3d48db58b9e..982fbf3bad8 100644 --- a/src/main/orcad/node-pty-loader-diagnosis.ts +++ b/src/main/orcad/native-runtime/node-pty-loader-diagnosis.ts @@ -1,4 +1,4 @@ -import type { RuntimeTerminalUnavailableReason } from '../../shared/runtime-types' +import type { RuntimeTerminalUnavailableReason } from '../../../shared/runtime-capability-degradation' import { parseIncompatibleArchitecture, parseMissingSharedLibrary, diff --git a/src/main/orcad/node-pty-prebuilt-slot.test.ts b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts similarity index 100% rename from src/main/orcad/node-pty-prebuilt-slot.test.ts rename to src/main/orcad/native-runtime/node-pty-prebuilt-slot.test.ts diff --git a/src/main/orcad/node-pty-prebuilt-slot.ts b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts similarity index 98% rename from src/main/orcad/node-pty-prebuilt-slot.ts rename to src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts index 44a3ee55744..d5059bbea5a 100644 --- a/src/main/orcad/node-pty-prebuilt-slot.ts +++ b/src/main/orcad/native-runtime/node-pty-prebuilt-slot.ts @@ -5,8 +5,8 @@ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync } from 'no import { dirname, join } from 'node:path' import process from 'node:process' import { z } from 'zod' -import { usesNodePtySpawnHelper } from '../../shared/node-pty-spawn-helper' -import { COMPAT_SERVER_TARGET_BASES, COMPAT_SERVER_TARGETS } from '../../shared/node-runtime-pin' +import { usesNodePtySpawnHelper } from '../../../shared/node-pty-spawn-helper' +import { COMPAT_SERVER_TARGET_BASES, COMPAT_SERVER_TARGETS } from '../../../shared/node-runtime-pin' import { compareDottedVersions, hostNodeApiVersion, diff --git a/src/main/orcad/node-pty-precondition.test.ts b/src/main/orcad/native-runtime/node-pty-precondition.test.ts similarity index 100% rename from src/main/orcad/node-pty-precondition.test.ts rename to src/main/orcad/native-runtime/node-pty-precondition.test.ts diff --git a/src/main/orcad/node-pty-precondition.ts b/src/main/orcad/native-runtime/node-pty-precondition.ts similarity index 98% rename from src/main/orcad/node-pty-precondition.ts rename to src/main/orcad/native-runtime/node-pty-precondition.ts index 8dda5bdaba0..6c85c88e4a5 100644 --- a/src/main/orcad/node-pty-precondition.ts +++ b/src/main/orcad/native-runtime/node-pty-precondition.ts @@ -4,8 +4,8 @@ import { dirname, join } from 'node:path' import process from 'node:process' import { runProcessSync } from '@orca/process-host' import type { ProcessResult } from '@orca/process-host/process-spec' -import { usesNodePtySpawnHelper } from '../../shared/node-pty-spawn-helper' -import type { RuntimeTerminalUnavailableReason } from '../../shared/runtime-types' +import { usesNodePtySpawnHelper } from '../../../shared/node-pty-spawn-helper' +import type { RuntimeTerminalUnavailableReason } from '../../../shared/runtime-capability-degradation' import { buildToolchainProbeCommand, parseBuildToolchainProbe, diff --git a/src/main/orcad/orcad-bundle-native-load-order.test.ts b/src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts similarity index 97% rename from src/main/orcad/orcad-bundle-native-load-order.test.ts rename to src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts index 985a8e5dd0e..8705205a2d3 100644 --- a/src/main/orcad/orcad-bundle-native-load-order.test.ts +++ b/src/main/orcad/native-runtime/orcad-bundle-native-load-order.test.ts @@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url' import { afterEach, expect, it } from 'vitest' import { runProcessSync } from '@orca/process-host' -const REPO_ROOT = join(__dirname, '..', '..', '..') +const REPO_ROOT = join(__dirname, '..', '..', '..', '..') const directories: string[] = [] afterEach(() => { diff --git a/src/main/orcad/orcad-native-preflight.ts b/src/main/orcad/native-runtime/orcad-native-preflight.ts similarity index 90% rename from src/main/orcad/orcad-native-preflight.ts rename to src/main/orcad/native-runtime/orcad-native-preflight.ts index fb991b1a5de..495fbef62c7 100644 --- a/src/main/orcad/orcad-native-preflight.ts +++ b/src/main/orcad/native-runtime/orcad-native-preflight.ts @@ -1,13 +1,13 @@ import process from 'node:process' -import { setRuntimeTerminalUnavailableCause } from '../runtime/terminal/launch/native-terminal-availability' -import { terminalUnavailableMessage } from '../../shared/runtime-types' +import { setRuntimeTerminalUnavailableCause } from '../../runtime/terminal/launch/native-terminal-availability' +import { terminalUnavailableMessage } from '../../../shared/runtime-capability-degradation' import { checkNodePtyPrecondition, formatNodePtyPreconditionReport, probeLocalBuildToolchainHints, type NodePtyPreconditionVerdict } from './node-pty-precondition' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' type NativePreflightHooks = { /** The slot's last launch on this unchanged host passed this probe (startup qualification). */ diff --git a/src/main/orcad/orcad-packaged-node-pty.integration.test.ts b/src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts similarity index 93% rename from src/main/orcad/orcad-packaged-node-pty.integration.test.ts rename to src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts index c0c33c9f032..386d7ea0e79 100644 --- a/src/main/orcad/orcad-packaged-node-pty.integration.test.ts +++ b/src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts @@ -5,10 +5,13 @@ import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { NODE_RUNTIME_PIN } from '../../shared/node-runtime-pin' -import { ORCAD_NODE_PTY_DIR } from '../../shared/orcad-artifacts' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { locatePinnedNodeForTests, skipForMissingInputs } from './orcad-node-slot-fixture' +import { NODE_RUNTIME_PIN } from '../../../shared/node-runtime-pin' +import { ORCAD_NODE_PTY_DIR } from '../../../shared/orcad-artifacts' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' +import { + locatePinnedNodeForTests, + skipForMissingInputs +} from '../testing/native-slots/orcad-node-slot-fixture' const packageDir = resolve('out/orcad') const pinnedNode = locatePinnedNodeForTests() diff --git a/src/main/orcad/orcad-runtime-native-preflight.ts b/src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts similarity index 88% rename from src/main/orcad/orcad-runtime-native-preflight.ts rename to src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts index 7e2c972c4c0..5b99f08f50a 100644 --- a/src/main/orcad/orcad-runtime-native-preflight.ts +++ b/src/main/orcad/native-runtime/orcad-runtime-native-preflight.ts @@ -5,17 +5,17 @@ import { PtySpawnHealthTimeoutError, PTY_SPAWN_HEALTH_TIMEOUT_MS, runPtySpawnHealthProbe -} from '../daemon/pty-subprocess/spawn-preflight' -import { WatcherProcessSupervisor } from '../ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor' -import { resolveWatcherProcessEntryPath } from '../ipc/filesystem/watcher-process/parcel-watcher-entry-path' -import { resolveOrcadInstallRoot } from './orcad-app-paths' +} from '../../daemon/pty-subprocess/spawn-preflight' +import { WatcherProcessSupervisor } from '../../ipc/filesystem/watcher-process/supervision/parcel-watcher-process-supervisor' +import { resolveWatcherProcessEntryPath } from '../../ipc/filesystem/watcher-process/parcel-watcher-entry-path' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' import { isWindowsProcessTableAvailable, isWindowsProcessStartTimeAvailable, readWindowsProcessCreationTime, readWindowsProcessIdentityTableFresh -} from '../windows/windows-process-table' -import { WindowsProcessTableTimeoutError } from '../windows/windows-process-table-timeout-error' +} from '../../windows/windows-process-table' +import { WindowsProcessTableTimeoutError } from '../../windows/windows-process-table-timeout-error' // Antivirus and cold arm64 conpty startup can exceed the steady-state budget. const WINDOWS_FIRST_PTY_PROBE_TIMEOUT_MS = 15_000 diff --git a/src/main/orcad/orcad-structured-provider-smoke.ts b/src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts similarity index 84% rename from src/main/orcad/orcad-structured-provider-smoke.ts rename to src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts index ac4177e2363..95166d7b835 100644 --- a/src/main/orcad/orcad-structured-provider-smoke.ts +++ b/src/main/orcad/native-runtime/orcad-structured-provider-smoke.ts @@ -1,4 +1,4 @@ -import { openClaudeStreamJsonConnection } from '../claude/claude-stream-json-connection' +import { openClaudeStreamJsonConnection } from '../../claude/claude-stream-json-connection' export async function smokeLoadOrcadStructuredProviders(): Promise { const loaded = new Error('structured provider module loaded') diff --git a/src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts b/src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts similarity index 95% rename from src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts rename to src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts index 4c0791ea20d..26fee48dff1 100644 --- a/src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts +++ b/src/main/orcad/native-runtime/orcad-windows-conpty-breakaway.integration.test.ts @@ -8,13 +8,13 @@ import { quoteWindowsArgument } from '@orca/process-host/windows-command-line' import { ORCAD_NODE_PTY_DIR, ORCAD_WINDOWS_PROCESS_TREE_FILENAME -} from '../../shared/orcad-artifacts' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +} from '../../../shared/orcad-artifacts' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' import { installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const windows = process.platform === 'win32' diff --git a/src/main/orcad/orcad-agent-session-claim-signer.test.ts b/src/main/orcad/orcad-agent-session-claim-signer.test.ts deleted file mode 100644 index dc88854333f..00000000000 --- a/src/main/orcad/orcad-agent-session-claim-signer.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { ClaimedAgentPtyOwnerRegistry } from '../../shared/claimed-agent-pty-owner' -import { - canonicalizeAgentSessionIdentity, - loadAgentSessionClaimSigner, - type AgentSessionClaimSigner -} from '../runtime/agent-session/ownership/agent-session-claim-identity' - -const namespace = { machine: 'm', principal: 'u', container: 'native', providerRoot: 'default' } -const identity = canonicalizeAgentSessionIdentity('claude', { key: 'session_id', id: 'conv-1' }) -const surface = { - worktreeId: 'worktree', - tabId: 'tab', - leafId: '12345678-1234-4234-8234-123456789abc', - terminalHandle: 'term_handle' -} - -async function ensureFrom( - daemonOwners: ClaimedAgentPtyOwnerRegistry, - signer: AgentSessionClaimSigner, - ptyId: string -) { - return await daemonOwners.ensure({ - claim: signer.createClaim({ namespace, identity, canonicalWorktreeId: 'worktree' }), - surface, - spawn: async () => ({ ptyId }), - isLive: () => true - }) -} - -describe('orcad agent-session claim signer', () => { - it('adopts the live PTY after an orcad restart instead of starting a second writer', async () => { - const userData = mkdtempSync(join(tmpdir(), 'orcad-claim-signer-')) - try { - const daemonOwners = new ClaimedAgentPtyOwnerRegistry() - const first = await ensureFrom( - daemonOwners, - loadAgentSessionClaimSigner(userData, userData), - 'pty-1' - ) - const restarted = await ensureFrom( - daemonOwners, - loadAgentSessionClaimSigner(userData, userData), - 'pty-2' - ) - expect(first.disposition).toBe('created') - expect(restarted).toMatchObject({ disposition: 'adopted', owner: { ptyId: 'pty-1' } }) - } finally { - rmSync(userData, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/orcad/orcad-browser-install-park.test.ts b/src/main/orcad/orcad-browser-install-park.test.ts deleted file mode 100644 index c7c7aad0c94..00000000000 --- a/src/main/orcad/orcad-browser-install-park.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { setImmediate as flush } from 'node:timers/promises' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { ORCAD_BROWSER_PARK_LABEL } from '../../shared/serve-bundle-coordination' -import { openServeBundlePark } from '../../shared/serve-bundle-park' -import { - commitServeSupervisorPark, - parkServeSupervisorsForInstall, - releaseServeSupervisorPark -} from '../updater/lifecycle/serve-supervisor-install-park' -import { watchOrcadBrowserInstallPark } from './orcad-browser-install-park' - -const HELPER = 424242 - -describe('orcad browser helper in the desktop install park', () => { - let root: string - let bundle: string - let executable: string - let tick: () => void - let running: boolean - let starts: AbortSignal[] - let failStarts: number - let hangStarts: boolean - let clock: number - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orcad-browser-park-')) - bundle = join(root, 'Orca.app') - executable = join(bundle, 'Contents', 'MacOS', 'Orca') - await mkdir(join(bundle, 'Contents', 'MacOS'), { recursive: true }) - await writeFile(executable, '') - await writeFile(join(bundle, 'Contents', 'Info.plist'), 'v1') - tick = () => undefined - running = true - starts = [] - failStarts = 0 - hangStarts = false - clock = 1_000 - }) - - afterEach(async () => { - await releaseServeSupervisorPark() - await rm(root, { recursive: true, force: true }) - }) - - function watch() { - const park = openServeBundlePark({ - executable, - label: ORCAD_BROWSER_PARK_LABEL, - platform: 'darwin', - env: {}, - userDataRoot: join(root, 'data') - }) - expect(park).not.toBeNull() - return watchOrcadBrowserInstallPark( - { - pid: () => (running ? HELPER : null), - stop: async () => { - running = false - }, - start: async (signal) => { - starts.push(signal) - if (hangStarts) { - running = true - await new Promise((_resolve, reject) => - signal.addEventListener('abort', () => reject(new Error('aborted'))) - ) - } - if (failStarts > 0) { - failStarts-- - throw new Error('helper did not become ready') - } - running = true - } - }, - { - park: park!, - now: () => clock, - log: () => undefined, - setRepeating: (callback) => { - tick = callback - return () => { - tick = () => undefined - } - } - } - ) - } - - async function step(): Promise { - tick() - await flush() - await flush() - } - - const installerDeps = () => ({ - macUserDataRoot: join(root, 'data'), - listBlockers: async () => (running ? [HELPER] : []), - sleep: step - }) - - it('stops the helper for an install and starts it again from the replaced bundle', async () => { - const parkWatch = watch() - await expect( - parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - ).resolves.toEqual({ kind: 'parked' }) - expect(running).toBe(false) - - await commitServeSupervisorPark(async () => (running ? [HELPER] : [])) - await step() - expect(running).toBe(false) - - await rm(join(bundle, 'Contents', 'Info.plist')) - await step() - expect(starts).toHaveLength(0) - - await writeFile(join(bundle, 'Contents', 'Info.plist'), 'v2-new-bundle') - await step() - expect(running).toBe(true) - expect(starts).toHaveLength(1) - await parkWatch.close() - }) - - it('gives up a slow restart so a new install can still park the helper', async () => { - const parkWatch = watch() - await parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - await releaseServeSupervisorPark() - hangStarts = true - await step() - await step() - expect(starts).toHaveLength(1) - await expect( - parkServeSupervisorsForInstall(executable, [HELPER], installerDeps()) - ).resolves.toEqual({ kind: 'parked' }) - expect(starts[0]?.aborted).toBe(true) - await parkWatch.close() - }) -}) diff --git a/src/main/orcad/orcad-chat-restart-offer.test.ts b/src/main/orcad/orcad-chat-restart-offer.test.ts deleted file mode 100644 index 724bdf310f6..00000000000 --- a/src/main/orcad/orcad-chat-restart-offer.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import { - CALLER, - hostTestState -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' -import { - HOST_TEST_THREAD as THREAD, - HOST_TEST_NOW as NOW, - hostTestAttachParams, - hostTestOperationId -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import { AgentSessionRecoveryCapsule } from '../runtime/agent-session/records/agent-session-recovery-capsule' -import { startOrcadWithLifecycle, stopOrcadStructuredAgentSessions } from './orcad-lifecycle' - -vi.mock('../runtime/agent-session/structured-agent-session-runtime', () => ({ - stopStructuredAgentSessionRuntime: async (options: { trigger: 'quit' }) => { - await hostTestState().host.flushAllStreamedEvents(options) - } -})) - -afterEach(() => vi.restoreAllMocks()) - -it.each([10, 100])( - 'batches %i working chats into durable offers before the profile closes', - async (size) => { - const { host, acquire, root } = hostTestState() - const ids = Array.from({ length: size }, (_, i) => `session-${i}`) - for (const sessionId of ids) { - const params = hostTestAttachParams(null, { - envelope: { - sessionId, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: null, - payloadFingerprint: '' - } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - const events = acquire.mock.calls.at(-1)?.[0].events - if (!events) { - throw new Error('missing provider event sink') - } - events.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'working', ordinal: 1 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(sessionId) - } - const close = vi.fn(async () => true) - host.deps.adapter.closeSession = close - const record = vi.spyOn(AgentSessionRecoveryCapsule.prototype, 'record') - const getRecord = vi.spyOn(host.deps.store, 'getRecord') - const server = await startOrcadWithLifecycle( - async (register) => { - register(async () => { - expect(close.mock.calls).toEqual(ids.map((id) => [id, undefined])) - expect(record).toHaveBeenCalledTimes(1) - expect(record.mock.calls[0]?.[0]).toHaveLength(size) - expect( - (await new AgentSessionRecoveryCapsule(root).list(NOW)).map((row) => row.sessionId) - ).toEqual(ids) - }) - register(stopOrcadStructuredAgentSessions) - return {} - }, - async () => {} - ) - await server.stop() - // Witness, lease and status passes are per session; no inventory scan for each child. - expect(getRecord.mock.calls.length).toBeLessThanOrEqual(32 * size) - const reads = getRecord.mock.calls.length - await server.stop() - expect(getRecord).toHaveBeenCalledTimes(reads) - expect(close).toHaveBeenCalledTimes(size) - expect(record).toHaveBeenCalledTimes(1) - record.mockRestore() - getRecord.mockRestore() - expect(await host.restartResume.list()).toMatchObject( - ids.map((sessionId) => ({ sessionId, trigger: 'quit' })) - ) - } -) diff --git a/src/main/orcad/orcad-event-loop-watchdog.test.ts b/src/main/orcad/orcad-event-loop-watchdog.test.ts deleted file mode 100644 index 837e200033e..00000000000 --- a/src/main/orcad/orcad-event-loop-watchdog.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { spawn } from 'node:child_process' -import { afterEach, expect, it } from 'vitest' -import { - ORCAD_EVENT_LOOP_WATCHDOG_ENV, - ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE, - startOrcadEventLoopWatchdog, - type OrcadEventLoopWatchdog, - type OrcadEventLoopWatchdogMessage -} from './orcad-event-loop-watchdog' - -const watchdogs: OrcadEventLoopWatchdog[] = [] -afterEach(() => watchdogs.splice(0).forEach((watchdog) => watchdog.stop())) - -/** Models a synchronous call that never yields the event loop; the worker's clock cannot be faked. */ -function blockMainThread(ms: number): void { - // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread - const until = Date.now() + ms - // ast-grep-ignore: test-no-wall-clock -- a busy-wait must read the real clock to block the real thread - while (Date.now() < until) { - // Busy-wait. - } -} - -it('reports a blocked event loop from a thread the block cannot starve, then its recovery (#34410)', async () => { - const watchdog = startOrcadEventLoopWatchdog({ - supervised: false, - env: {}, - timings: { beatIntervalMs: 20, checkIntervalMs: 50, warnAfterMs: 300 } - }) - expect(watchdog).not.toBeNull() - watchdogs.push(watchdog!) - const messages: OrcadEventLoopWatchdogMessage[] = [] - watchdog!.worker.on('message', (message: OrcadEventLoopWatchdogMessage) => messages.push(message)) - await expect.poll(() => messages.map((message) => message.type)).toEqual(['started']) - - blockMainThread(900) - - await expect - .poll(() => messages.map((message) => message.type), { timeout: 2000 }) - .toEqual(['started', 'stalled', 'recovered']) - const stalled = messages[1] - expect(stalled.type === 'stalled' && stalled.blockedMs >= 300).toBe(true) -}) - -it('can be turned off', () => { - expect( - startOrcadEventLoopWatchdog({ supervised: true, env: { [ORCAD_EVENT_LOOP_WATCHDOG_ENV]: '0' } }) - ).toBeNull() -}) - -// Why the longer timeout: the child must boot a runtime and a worker before its loop blocks. -it('ends a supervised process whose event loop stays blocked past the exit bound', async () => { - // A child process stands in for orcad so the test runner survives the kill. - const script = ` - const { Worker } = require('node:worker_threads') - const worker = new Worker(process.env.WATCHDOG_SOURCE, { - eval: true, - workerData: { - beat: new SharedArrayBuffer(4), - checkIntervalMs: 50, - warnAfterMs: 100, - exitAfterMs: 300 - } - }) - worker.once('message', () => { - const until = Date.now() + 10000 - while (Date.now() < until) {} - process.exit(0) - }) - ` - const child = spawn(process.execPath, ['-e', script], { - env: { ...process.env, WATCHDOG_SOURCE: ORCAD_EVENT_LOOP_WATCHDOG_WORKER_SOURCE }, - stdio: ['ignore', 'ignore', 'pipe'] - }) - let stderr = '' - child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString())) - const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>( - // close, not exit: stderr may still hold the worker's last line when exit fires. - (resolve) => child.once('close', (code, signal) => resolve({ code, signal })) - ) - expect(exit.code === 0 && exit.signal === null).toBe(false) - expect(stderr).toContain('exiting so the service manager restarts it') -}, 20_000) diff --git a/src/main/orcad/orcad-forked-child-paths.test.ts b/src/main/orcad/orcad-forked-child-paths.test.ts deleted file mode 100644 index 177ed5a1671..00000000000 --- a/src/main/orcad/orcad-forked-child-paths.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { getWatcherProcessEntryPath } from '../ipc/filesystem/watcher-process/parcel-watcher-entry-path' -import { AI_VAULT_SERVICE_ENTRY_FILENAME } from '../ai-vault/scan-service/session-scanner-service-entry-path' -import { FOREIGN_SQLITE_READER_ENTRY_FILENAME } from '../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' -import { installOrcadHostAdapters } from './orcad-host-adapters' - -// Compose real adapters and deployment paths: isolated resolver tests missed nonexistent fork targets. -describe('orcad forked-child paths', () => { - let deployRoot: string - let originalArgv: string[] - - beforeEach(() => { - deployRoot = mkdtempSync(join(tmpdir(), 'orcad-deploy-')) - writeFileSync(join(deployRoot, 'orcad.js'), '') - writeFileSync(join(deployRoot, 'parcel-watcher-process-entry.js'), '') - writeFileSync(join(deployRoot, FOREIGN_SQLITE_READER_ENTRY_FILENAME), '') - writeFileSync(join(deployRoot, AI_VAULT_SERVICE_ENTRY_FILENAME), '') - originalArgv = process.argv - process.argv = [process.execPath, join(deployRoot, 'orcad.js')] - installOrcadHostAdapters() - }) - - afterEach(() => { - process.argv = originalArgv - rmSync(deployRoot, { recursive: true, force: true }) - }) - - it('ignores a decoy child under the working directory', () => { - // Cwd may hold an unrelated build; only the install root establishes shipped children. - const elsewhere = mkdtempSync(join(tmpdir(), 'orcad-cwd-')) - mkdirSync(join(elsewhere, 'out', 'main'), { recursive: true }) - writeFileSync(join(elsewhere, 'out', 'main', 'parcel-watcher-process-entry.js'), '') - writeFileSync(join(elsewhere, 'parcel-watcher-process-entry.js'), '') - const originalCwd = process.cwd() - process.chdir(elsewhere) - try { - expect(getWatcherProcessEntryPath()).toBe(join(deployRoot, 'parcel-watcher-process-entry.js')) - } finally { - process.chdir(originalCwd) - rmSync(elsewhere, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/orcad/orcad-local-serve-selection-entry.ts b/src/main/orcad/orcad-local-serve-selection-entry.ts index 86dab58700e..944f01379c1 100644 --- a/src/main/orcad/orcad-local-serve-selection-entry.ts +++ b/src/main/orcad/orcad-local-serve-selection-entry.ts @@ -5,8 +5,8 @@ import { formatServeRuntimeSelection, ORCAD_LOCAL_SERVE_SELECTION_FLAGS as FLAGS } from '../../shared/orcad-local-serve-selection' -import { selectServeRuntime } from './orcad-local-serve-selection' -import { pruneDesktopOrcadArtifactCache } from './orcad-artifact-cache-retention' +import { selectServeRuntime } from './serve-startup/orcad-local-serve-selection' +import { pruneDesktopOrcadArtifactCache } from './artifact-slots/orcad-artifact-cache-retention' import { findAppImageNodeRuntime } from '../node-runtime/appimage-bundled-node-runtime' function flagValue(argv: readonly string[], flag: string): string | null { diff --git a/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts b/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts deleted file mode 100644 index bfd76d38c7c..00000000000 --- a/src/main/orcad/orcad-managed-idle-exit-chat-provider.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' -import { - createRestTestRig, - foundRestTestChat, - sweepOnce -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' - -import { STRUCTURED_AGENT_SESSION_IDLE_MS as IDLE_MS } from '../native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep' -import { - HOST_TEST_SESSION as REST_TEST_SESSION, - HOST_TEST_THREAD as REST_TEST_THREAD -} from '../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' -import type { RestTestRig } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' -import { OrcadIdleExitMonitor } from './orcad-idle-exit-monitor' -import { createOrcadIdleProbes } from './orcad-managed-idle-exit' - -let rig: RestTestRig -const SERVER_IDLE_MS = 15 * 60_000 - -beforeEach(async () => { - rig = await createRestTestRig() - rig.host.collaboratorsForTests().lifetime.idleSweep.dispose() - await foundRestTestChat(rig) -}) - -afterEach(async () => { - await rig.dispose() -}) - -function idleMonitor() { - const onIdle = vi.fn() - const monitor = new OrcadIdleExitMonitor({ - timeoutMs: SERVER_IDLE_MS, - now: () => rig.clock.now, - log: () => {}, - lastClientActivityAt: () => 0, - onIdle, - probes: createOrcadIdleProbes( - { timeoutMs: SERVER_IDLE_MS, activationRoot: 'test-fence' }, - { - readClientActivity: () => ({ openConnections: 0, requestsInFlight: 0, lastRequestAt: 0 }), - listTerminals: async () => [], - countDaemonSessions: async () => 0, - hasDaemon: () => true, - hasChatProviders: () => rig.host.hasLoadedProviders(), - agentStates: () => [{ state: 'blocked' }], - hasStagedMigration: () => false, - automationsBusy: () => false, - emulatorsBusy: async () => false, - activationFenceExists: async () => false - } - ) - }) - return { monitor, onIdle } -} - -function providerEvents() { - const events = rig.adapter.acquire.mock.calls.at(-1)?.[0].events - if (!events) { - throw new Error('no provider was started') - } - return events -} - -it('U2: keeps the provider and disconnected server alive while an approval is unanswered', async () => { - providerEvents().appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'approval-turn', ordinal: 70 }, - { - kind: 'approval', - title: 'Run the command?', - detail: null, - options: [{ id: 'allow', label: 'Allow' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(REST_TEST_SESSION) - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - rig.clock.now += 7 * 24 * 60 * 60_000 - await sweepOnce(rig.host) - - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(await monitor.check()).toBe(false) - expect(onIdle).not.toHaveBeenCalled() -}) - -it('releases an idle provider after the existing window, then lets the disconnected server exit', async () => { - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - rig.clock.now += IDLE_MS - 1 - await sweepOnce(rig.host) - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(await monitor.check()).toBe(false) - - rig.clock.now += 2 - await sweepOnce(rig.host) - expect(rig.adapter.closeSession).toHaveBeenCalledWith(REST_TEST_SESSION, undefined) - expect(rig.host.hasLoadedProviders()).toBe(false) - expect(await monitor.check()).toBe(false) - rig.clock.now += SERVER_IDLE_MS - expect(await monitor.check()).toBe(true) - expect(onIdle).toHaveBeenCalledOnce() -}) - -it('never releases a quiet running turn or idle-exits its server', async () => { - providerEvents().appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 71 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(REST_TEST_SESSION) - const { monitor, onIdle } = idleMonitor() - expect(await monitor.check()).toBe(false) - for (let pass = 0; pass < 3; pass += 1) { - rig.clock.now += 7 * 24 * 60 * 60_000 - await sweepOnce(rig.host) - expect(await monitor.check()).toBe(false) - } - expect(rig.adapter.closeSession).not.toHaveBeenCalled() - expect(onIdle).not.toHaveBeenCalled() -}) diff --git a/src/main/orcad/orcad-runtime-lifetime.ts b/src/main/orcad/orcad-runtime-lifetime.ts deleted file mode 100644 index 283adac3bb5..00000000000 --- a/src/main/orcad/orcad-runtime-lifetime.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - BackendServiceLifetime as OrcadRuntimeLifetime, - type BackendServiceCleanup as OrcadRuntimeCleanup -} from '../backend/service-composition' diff --git a/src/main/orcad/orcad-speech-services.ts b/src/main/orcad/orcad-speech-services.ts deleted file mode 100644 index d9c0c661c90..00000000000 --- a/src/main/orcad/orcad-speech-services.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ModelManager } from '../speech/model-manager' -import { openNodeSpeechDownloadRequest } from '../speech/node-speech-download-request' -import { canReadCloudSpeechCredentials } from '../speech/cloud-transcription-target' -import type { SpeechServiceFactories } from '../speech/speech-runtime-service' -import { SttService } from '../speech/stt-service' -import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker' -import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback' -import { spawnSttForkedProcess } from '../speech/stt-worker-forked-process' - -// Local speech needs the installed app recognizer supplied by orca serve. -export const orcadSpeechServiceFactories: SpeechServiceFactories = { - createModelManager: (customModelsDir) => - // Headless key reads cannot open keychain prompts, so readiness may verify decryption. - new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadCloudSpeechCredentials), - createSttService: (models, gpuEnabled) => { - const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) - return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu)) - } -} diff --git a/src/main/orcad/orcad-host-identity-reset.ts b/src/main/orcad/profile-state/orcad-host-identity-reset.ts similarity index 90% rename from src/main/orcad/orcad-host-identity-reset.ts rename to src/main/orcad/profile-state/orcad-host-identity-reset.ts index c0f21f9a70d..5cb0ac954e3 100644 --- a/src/main/orcad/orcad-host-identity-reset.ts +++ b/src/main/orcad/profile-state/orcad-host-identity-reset.ts @@ -1,11 +1,11 @@ // CLI entry for `orca serve reset-identity`; plain Node, loaded from the packaged CLI. import { existsSync } from 'node:fs' -import { acquireOrcadInstanceLock } from './orcad-instance-lock' -import { OrcadInstanceLockError } from './orcad-data-root-privacy' +import { acquireOrcadInstanceLock } from '../instance-lock/orcad-instance-lock' +import { OrcadInstanceLockError } from '../instance-lock/orcad-data-root-privacy' import { HostIdentityRotationNotStartedError, rotateHostIdentity -} from '../runtime/host-instance-identity' +} from '../../runtime/host-instance-identity' export type HostIdentityResetResult = | { status: 'reset' } diff --git a/src/main/orcad/orcad-profile-state-startup.ts b/src/main/orcad/profile-state/orcad-profile-state-startup.ts similarity index 75% rename from src/main/orcad/orcad-profile-state-startup.ts rename to src/main/orcad/profile-state/orcad-profile-state-startup.ts index 711a019e981..ef8262ab4db 100644 --- a/src/main/orcad/orcad-profile-state-startup.ts +++ b/src/main/orcad/profile-state/orcad-profile-state-startup.ts @@ -1,11 +1,11 @@ -import { createProfileStateStoreForStartup } from '../persistence/profile-state/startup/profile-state-startup-authority' -import type { ProfileStateStoreFactoryResult } from '../persistence/profile-state/startup/profile-state-store-factory' -import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' -import { initOrcaProfilePaths } from '../orca-profiles/profile-storage-paths' -import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' -import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' +import { createProfileStateStoreForStartup } from '../../persistence/profile-state/startup/profile-state-startup-authority' +import type { ProfileStateStoreFactoryResult } from '../../persistence/profile-state/startup/profile-state-store-factory' +import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' +import { initOrcaProfilePaths } from '../../orca-profiles/profile-storage-paths' +import { initSshHostKeyStoreFile } from '../../ssh/host-keys/ssh-host-key-store' +import { initOrcadHeldFenceTokenFile } from '../../managed-server/activation/orcad-held-fence-tokens' import { emitOrcadProfileStateAuthoritySelected } from './orcad-profile-state-telemetry' -import { isWslHostOrcadProcess } from '../ipc/wsl-guest-windows-drive-path' +import { isWslHostOrcadProcess } from '../../ipc/wsl-guest-windows-drive-path' /** WSL hosts are held to a per-distro memory budget; the idle writer thread costs ~13-15 MB. */ export const WSL_HOST_PROFILE_WRITER_IDLE_STOP_MS = 60_000 diff --git a/src/main/orcad/orcad-profile-state-telemetry.ts b/src/main/orcad/profile-state/orcad-profile-state-telemetry.ts similarity index 89% rename from src/main/orcad/orcad-profile-state-telemetry.ts rename to src/main/orcad/profile-state/orcad-profile-state-telemetry.ts index 4e04fd10412..efc796cbc6d 100644 --- a/src/main/orcad/orcad-profile-state-telemetry.ts +++ b/src/main/orcad/profile-state/orcad-profile-state-telemetry.ts @@ -1,4 +1,4 @@ -import type { ProfileStateStorageClassification } from '../persistence/profile-state/database/profile-state-storage-classification' +import type { ProfileStateStorageClassification } from '../../persistence/profile-state/database/profile-state-storage-classification' /** Exclude paths, profile IDs and serialized state from fleet telemetry. */ export type OrcadProfileStateAuthoritySelection = { diff --git a/src/main/orcad/serve-profile-ssh-targets.ts b/src/main/orcad/profile-state/serve-profile-ssh-targets.ts similarity index 72% rename from src/main/orcad/serve-profile-ssh-targets.ts rename to src/main/orcad/profile-state/serve-profile-ssh-targets.ts index 6698e81e2ca..8db9b6ef718 100644 --- a/src/main/orcad/serve-profile-ssh-targets.ts +++ b/src/main/orcad/profile-state/serve-profile-ssh-targets.ts @@ -1,10 +1,10 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../shared/orca-profiles' -import { PROFILE_STATE_DATABASE_FILE_NAME } from '../../shared/profile-state-storage-paths' -import { getActiveProfileStateLocation } from '../persistence/profile-state/offline-access/profile-state-active-location' -import { readProfileStateDomain } from '../persistence/profile-state/documents/profile-state-domain-reader' -import { classifyProfileStateStorage } from '../persistence/profile-state/database/profile-state-storage-classification' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../shared/orca-profiles' +import { PROFILE_STATE_DATABASE_FILE_NAME } from '../../../shared/profile-state-storage-paths' +import { getActiveProfileStateLocation } from '../../persistence/profile-state/offline-access/profile-state-active-location' +import { readProfileStateDomain } from '../../persistence/profile-state/documents/profile-state-domain-reader' +import { classifyProfileStateStorage } from '../../persistence/profile-state/database/profile-state-storage-classification' /** Inspect SSH targets without creating, locking or migrating state owned by the next serve host. */ export function serveProfileHasSshTargets(userDataPath: string): boolean { diff --git a/src/main/orcad/orcad-bundled-runtime.ts b/src/main/orcad/runtime-launch/orcad-bundled-runtime.ts similarity index 94% rename from src/main/orcad/orcad-bundled-runtime.ts rename to src/main/orcad/runtime-launch/orcad-bundled-runtime.ts index 59785312057..547f686ea4e 100644 --- a/src/main/orcad/orcad-bundled-runtime.ts +++ b/src/main/orcad/runtime-launch/orcad-bundled-runtime.ts @@ -2,15 +2,15 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs' import { dirname, join } from 'node:path' import { constants } from 'node:os' import { spawnProcess } from '@orca/process-host' -import { resolveOrcadInstallRoot } from './orcad-app-paths' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' import { ORCAD_NODE_RUNTIME_MARKER_FILENAME, ORCAD_SERVER_TARGET_FILENAME, ORCAD_VERSION_FILENAME, orcadNodeRuntimeRelativePath -} from '../../shared/orcad-artifacts' -import { NODE_RUNTIME_PIN, nodeRuntimeAsset } from '../../shared/node-runtime-pin' +} from '../../../shared/orcad-artifacts' +import { NODE_RUNTIME_PIN, nodeRuntimeAsset } from '../../../shared/node-runtime-pin' export class OrcadBundledRuntimeError extends Error {} export const ORCAD_BUNDLED_LAUNCHER_ENV = 'ORCA_BUNDLED_LAUNCHER_CHANNEL' diff --git a/src/main/orcad/orcad-compile-cache.ts b/src/main/orcad/runtime-launch/orcad-compile-cache.ts similarity index 93% rename from src/main/orcad/orcad-compile-cache.ts rename to src/main/orcad/runtime-launch/orcad-compile-cache.ts index 7e7f3db8052..e5db79bff7f 100644 --- a/src/main/orcad/orcad-compile-cache.ts +++ b/src/main/orcad/runtime-launch/orcad-compile-cache.ts @@ -1,6 +1,6 @@ import module from 'node:module' import { join } from 'node:path' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' export const ORCAD_COMPILE_CACHE_DIRNAME = '.orcad-compile-cache' diff --git a/src/main/orcad/orcad-launcher-isolation.integration.test.ts b/src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts similarity index 88% rename from src/main/orcad/orcad-launcher-isolation.integration.test.ts rename to src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts index 4cfc10f784c..896058d75c2 100644 --- a/src/main/orcad/orcad-launcher-isolation.integration.test.ts +++ b/src/main/orcad/runtime-launch/orcad-launcher-isolation.integration.test.ts @@ -4,14 +4,17 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_LAUNCHER_FILENAME, ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' -import { NODE_RUNTIME_PIN } from '../../shared/node-runtime-pin' -import { hashOrcadLauncher } from '../../shared/orcad-build-identity' +import { + ORCAD_LAUNCHER_FILENAME, + ORCAD_SERVER_ENTRY_FILENAME +} from '../../../shared/orcad-artifacts' +import { NODE_RUNTIME_PIN } from '../../../shared/node-runtime-pin' +import '../../../shared/orcad-build-identity' import { locatePinnedNodeForTests, skipForMissingInputs, writeNodeSlotFixture -} from './orcad-node-slot-fixture' +} from '../testing/native-slots/orcad-node-slot-fixture' const pinnedNode = locatePinnedNodeForTests() const launcherNode = @@ -51,19 +54,6 @@ beforeAll(async () => { await buildLauncher(launcher) }) -it('changes the launcher identity when the server is rebuilt', async () => { - const directory = join(root, 'rebuilt') - await mkdir(directory) - const entry = join(directory, ORCAD_LAUNCHER_FILENAME) - const server = join(directory, ORCAD_SERVER_ENTRY_FILENAME) - await writeFile(server, SERVER_FIXTURE) - await buildLauncher(entry) - const first = hashOrcadLauncher(entry) - await writeFile(server, 'console.log("rebuilt server")') - await buildLauncher(entry) - expect(hashOrcadLauncher(entry)).not.toBe(first) -}) - afterAll(async () => { // Windows can hold an exited node.exe image open briefly (EBUSY). await rm(root, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 }) diff --git a/src/main/orcad/orcad-profile-preflight.ts b/src/main/orcad/runtime-launch/orcad-profile-preflight.ts similarity index 88% rename from src/main/orcad/orcad-profile-preflight.ts rename to src/main/orcad/runtime-launch/orcad-profile-preflight.ts index 39acd0eaf3d..f8576c65e42 100644 --- a/src/main/orcad/orcad-profile-preflight.ts +++ b/src/main/orcad/runtime-launch/orcad-profile-preflight.ts @@ -2,20 +2,23 @@ import { z } from 'zod' import { randomUUID } from 'node:crypto' import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { preflightProfileStateRuntime } from '../persistence/profile-state/startup/profile-state-runtime-preflight' +import { preflightProfileStateRuntime } from '../../persistence/profile-state/startup/profile-state-runtime-preflight' import { ORCAD_STARTUP_PREFLIGHT_FLAG, ORCAD_PROFILE_PREFLIGHT_TIMEOUT_MS, parseOrcadProfilePreflight, orcadProfilePreflightResponseSchema, type OrcadProfilePreflightResponse -} from '../../shared/orcad-profile-preflight' -import { readOrcadArtifactIdentity } from './orcad-artifact-identity' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { ORCAD_SERVER_ENTRY_FILENAME, ORCAD_VERSION_FILENAME } from '../../shared/orcad-artifacts' -import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../shared/orcad-node-runtime-identity' +} from '../../../shared/orcad-profile-preflight' +import { readOrcadArtifactIdentity } from '../artifact-slots/orcad-artifact-identity' +import { ORCAD_EXIT_CONFIGURATION } from '../serve-startup/orcad-configuration-exit' +import { + ORCAD_SERVER_ENTRY_FILENAME, + ORCAD_VERSION_FILENAME +} from '../../../shared/orcad-artifacts' +import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../../shared/orcad-node-runtime-identity' import { runProcess } from '@orca/process-host' -import { preflightOrcadNativeRuntime } from './orcad-runtime-native-preflight' +import { preflightOrcadNativeRuntime } from '../native-runtime/orcad-runtime-native-preflight' import { orcadCompileCacheEnv } from './orcad-compile-cache' import { consumeOrcadStartupQualification, @@ -152,9 +155,9 @@ async function readServedDaemonProtocols(servedUserDataPath: string): Promise ({ files: ['orcad-server.js', 'daemon-entry.js'] })) -vi.mock('./orcad-artifact-identity', () => ({ +vi.mock('../artifact-slots/orcad-artifact-identity', () => ({ listOrcadArtifactFilenames: async () => artifacts.files })) import { consumeOrcadStartupQualification, - orcadStartupQualificationKey, recordOrcadStartupQualification } from './orcad-startup-qualification' @@ -28,16 +27,6 @@ afterEach(() => { }) describe('orcad startup qualification', () => { - it('keys on the artifact version and on every installed file staying the same file', async () => { - const key = await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa') - - expect(await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa')).toBe(key) - expect(await orcadStartupQualificationKey(slot, '0.2.0+aaaaaaaaaaaa')).not.toBe(key) - rmSync(join(slot, 'daemon-entry.js')) - writeFileSync(join(slot, 'daemon-entry.js'), 'replaced') - expect(await orcadStartupQualificationKey(slot, '0.1.0+aaaaaaaaaaaa')).not.toBe(key) - }) - it('consumes a matching marker once, so a launch that dies before readiness re-qualifies', async () => { await recordOrcadStartupQualification(slot, 'key-1') diff --git a/src/main/orcad/orcad-startup-qualification.ts b/src/main/orcad/runtime-launch/orcad-startup-qualification.ts similarity index 90% rename from src/main/orcad/orcad-startup-qualification.ts rename to src/main/orcad/runtime-launch/orcad-startup-qualification.ts index 8236f357a99..911feaa677f 100644 --- a/src/main/orcad/orcad-startup-qualification.ts +++ b/src/main/orcad/runtime-launch/orcad-startup-qualification.ts @@ -4,11 +4,11 @@ import { readFile, rename, stat, unlink, writeFile } from 'node:fs/promises' import { release } from 'node:os' import { isAbsolute, join, relative } from 'node:path' import process from 'node:process' -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' -import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../shared/orcad-node-runtime-identity' -import { mapWithConcurrency } from '../../shared/map-with-concurrency' -import { listOrcadArtifactFilenames } from './orcad-artifact-identity' -import { detectNativeHostAbi } from './native-host-abi' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' +import { ORCAD_NODE_RUNTIME_IDENTITY } from '../../../shared/orcad-node-runtime-identity' +import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import { listOrcadArtifactFilenames } from '../artifact-slots/orcad-artifact-identity' +import { detectNativeHostAbi } from '../native-runtime/native-host-abi' export const ORCAD_STARTUP_QUALIFIED_FILENAME = '.orcad-startup-qualified' const ARTIFACT_STAT_CONCURRENCY = 16 diff --git a/src/main/orcad/orcad-cli-launcher.integration.test.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts similarity index 89% rename from src/main/orcad/orcad-cli-launcher.integration.test.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts index 572c7b1f72f..b94833cdaad 100644 --- a/src/main/orcad/orcad-cli-launcher.integration.test.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.integration.test.ts @@ -2,18 +2,18 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { expect, it } 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' import { runProcess, spawnProcess } from '@orca/process-host' -import { sealedChildEnv } from '../runtime/agent-session/environment/structured-session-child-env.test-support' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' -import { skipForMissingInputs } from './orcad-node-slot-fixture' +import { sealedChildEnv } from '../../runtime/agent-session/environment/structured-session-child-env.test-support' +import { resolveBundledOrcadRuntime } from '../runtime-launch/orcad-bundled-runtime' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../shared/orcad-artifacts' +import { skipForMissingInputs } from '../testing/native-slots/orcad-node-slot-fixture' import { killChildAndWait, killProfileDaemons, recordProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' +} from '../testing/daemon-processes/orcad-daemon-teardown-fixture' const slotDir = resolve('out/orcad') const runtime = existsSync(join(slotDir, ORCAD_NODE_RUNTIME_MARKER_FILENAME)) diff --git a/src/main/orcad/orcad-cli-launcher.test.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.test.ts similarity index 96% rename from src/main/orcad/orcad-cli-launcher.test.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.test.ts index 6d3b4560541..8defbce327b 100644 --- a/src/main/orcad/orcad-cli-launcher.test.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.test.ts @@ -3,11 +3,11 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_CLI_ENTRY_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_CLI_ENTRY_FILENAME } from '../../../shared/orcad-artifacts' import { getOrcadCliLauncherPath, prepareOrcadCliLauncher } from './orcad-cli-launcher' const roots = vi.hoisted(() => ({ install: '', profile: '' })) -vi.mock('./orcad-app-paths', () => ({ +vi.mock('../host-runtime/orcad-app-paths', () => ({ resolveOrcadInstallRoot: () => roots.install, resolveUserDataPath: () => roots.profile })) diff --git a/src/main/orcad/orcad-cli-launcher.ts b/src/main/orcad/serve-startup/orcad-cli-launcher.ts similarity index 90% rename from src/main/orcad/orcad-cli-launcher.ts rename to src/main/orcad/serve-startup/orcad-cli-launcher.ts index ed39f5c49bb..01ef8b0d60d 100644 --- a/src/main/orcad/orcad-cli-launcher.ts +++ b/src/main/orcad/serve-startup/orcad-cli-launcher.ts @@ -5,11 +5,11 @@ import { join } from 'node:path' import { ORCAD_CLI_ENTRY_FILENAME, ORCAD_WINDOWS_CLI_LAUNCHER_FILENAME -} from '../../shared/orcad-artifacts' -import { nodeFileContentsEqual } from '../../shared/file-content/node-file-content-equality' -import { buildUnixCliLauncher } from '../cli/launchers/cli-dev-launcher' -import { writeFileAtomically } from '../filesystem/atomic-file-publication' -import { resolveOrcadInstallRoot, resolveUserDataPath } from './orcad-app-paths' +} from '../../../shared/orcad-artifacts' +import { nodeFileContentsEqual } from '../../../shared/file-content/node-file-content-equality' +import { buildUnixCliLauncher } from '../../cli/launchers/cli-dev-launcher' +import { writeFileAtomically } from '../../filesystem/atomic-file-publication' +import { resolveOrcadInstallRoot, resolveUserDataPath } from '../host-runtime/orcad-app-paths' // The native Windows launcher selects server mode when this sibling config exists. export const ORCAD_WINDOWS_CLI_LAUNCHER_CONFIG_FILENAME = 'orca-launcher.cfg' diff --git a/src/main/orcad/orcad-command-arguments.ts b/src/main/orcad/serve-startup/orcad-command-arguments.ts similarity index 94% rename from src/main/orcad/orcad-command-arguments.ts rename to src/main/orcad/serve-startup/orcad-command-arguments.ts index 1a1b5da57b7..6db33d64835 100644 --- a/src/main/orcad/orcad-command-arguments.ts +++ b/src/main/orcad/serve-startup/orcad-command-arguments.ts @@ -1,10 +1,10 @@ import type { OrcadOptions } from './orcad-start-contract' -import { DEFAULT_WS_PORT } from '../runtime/rpc/server/runtime-rpc-pairing-types' -import { ORCAD_LOOPBACK_BIND_HOST } from '../../shared/orcad-bind-address' -import { getServeOptionValidationError } from '../../shared/serve-option-validation' +import { DEFAULT_WS_PORT } from '../../runtime/rpc/server/runtime-rpc-pairing-types' +import { ORCAD_LOOPBACK_BIND_HOST } from '../../../shared/orcad-bind-address' +import { getServeOptionValidationError } from '../../../shared/serve-option-validation' import { existsSync } from 'node:fs' import { join, resolve } from 'node:path' -import { WEB_CLIENT_INDEX_FILENAME } from '../../shared/bundled-web-client-root' +import { WEB_CLIENT_INDEX_FILENAME } from '../../../shared/bundled-web-client-root' export const ORCAD_USAGE = `orcad — the Orca runtime served without Electron. diff --git a/src/main/orcad/orcad-command-startup.ts b/src/main/orcad/serve-startup/orcad-command-startup.ts similarity index 60% rename from src/main/orcad/orcad-command-startup.ts rename to src/main/orcad/serve-startup/orcad-command-startup.ts index a0dd47d055b..2dbbe27103a 100644 --- a/src/main/orcad/orcad-command-startup.ts +++ b/src/main/orcad/serve-startup/orcad-command-startup.ts @@ -1,12 +1,15 @@ -import { startOrcad } from './orcad-entry' +import { startOrcad } from '../host-runtime/orcad-entry' import process from 'node:process' -import { resolveOrcadInstallRoot } from './orcad-app-paths' +import { resolveOrcadInstallRoot } from '../host-runtime/orcad-app-paths' import { ORCAD_USAGE, parseArgs } from './orcad-command-arguments' -import { installOrcadShutdownSignals, type OrcadShutdownTrigger } from './orcad-lifecycle' -import { installOrcadProcessErrorGuards } from './orcad-process-error-guards' -import { installOrcadStopRequestListeners } from './orcad-stop-request-listener' -import { prepareOrcadManagedStop } from './orcad-managed-stop-admission' -import { bindOrcadIdleShutdown } from './orcad-managed-idle-exit-host' +import { + installOrcadShutdownSignals, + type OrcadShutdownTrigger +} from '../host-lifecycle/orcad-lifecycle' +import { installOrcadProcessErrorGuards } from '../host-lifecycle/orcad-process-error-guards' +import { installOrcadStopRequestListeners } from '../host-lifecycle/managed-stop/orcad-stop-request-listener' +import { prepareOrcadManagedStop } from '../host-lifecycle/managed-stop/orcad-managed-stop-admission' +import { bindOrcadIdleShutdown } from '../host-lifecycle/idle-exit/orcad-managed-idle-exit-host' export async function main(argv: string[] = process.argv.slice(2)): Promise { const options = parseArgs(argv) diff --git a/src/main/orcad/orcad-configuration-exit.ts b/src/main/orcad/serve-startup/orcad-configuration-exit.ts similarity index 100% rename from src/main/orcad/orcad-configuration-exit.ts rename to src/main/orcad/serve-startup/orcad-configuration-exit.ts diff --git a/src/main/orcad/orcad-exit-code.ts b/src/main/orcad/serve-startup/orcad-exit-code.ts similarity index 65% rename from src/main/orcad/orcad-exit-code.ts rename to src/main/orcad/serve-startup/orcad-exit-code.ts index 17cbec53673..846e949f3cf 100644 --- a/src/main/orcad/orcad-exit-code.ts +++ b/src/main/orcad/serve-startup/orcad-exit-code.ts @@ -1,10 +1,10 @@ -import { OrcadBindAddressError } from '../../shared/orcad-bind-address' -import { OrcadBundledRuntimeError } from './orcad-bundled-runtime' -import { OrcadInstanceLockError } from './orcad-data-root-privacy' -import { ProfileStateAccessError } from '../persistence/profile-state/access/profile-state-access-error' +import { OrcadBindAddressError } from '../../../shared/orcad-bind-address' +import { OrcadBundledRuntimeError } from '../runtime-launch/orcad-bundled-runtime' +import { OrcadInstanceLockError } from '../instance-lock/orcad-data-root-privacy' +import { ProfileStateAccessError } from '../../persistence/profile-state/access/profile-state-access-error' import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../shared/single-instance-exit-code' -import { ORCAD_EXIT_TERMINALS_NOT_DURABLE } from '../../shared/serve-supervised-terminal-durability' +import { SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE } from '../../../shared/single-instance-exit-code' +import { ORCAD_EXIT_TERMINALS_NOT_DURABLE } from '../../../shared/serve-supervised-terminal-durability' import { OrcadTerminalsNotDurableError } from './orcad-serve-supervision' export const ORCAD_EXIT_FAILED = 1 diff --git a/src/main/orcad/orcad-help.integration.test.ts b/src/main/orcad/serve-startup/orcad-help.integration.test.ts similarity index 94% rename from src/main/orcad/orcad-help.integration.test.ts rename to src/main/orcad/serve-startup/orcad-help.integration.test.ts index c1157a9a1f8..50be505dd13 100644 --- a/src/main/orcad/orcad-help.integration.test.ts +++ b/src/main/orcad/serve-startup/orcad-help.integration.test.ts @@ -4,7 +4,10 @@ import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { ORCAD_LAUNCHER_FILENAME, ORCAD_SERVER_ENTRY_FILENAME } from '../../shared/orcad-artifacts' +import { + ORCAD_LAUNCHER_FILENAME, + ORCAD_SERVER_ENTRY_FILENAME +} from '../../../shared/orcad-artifacts' let directory = '' let launcher = '' diff --git a/src/main/orcad/orcad-local-serve-selection.ts b/src/main/orcad/serve-startup/orcad-local-serve-selection.ts similarity index 87% rename from src/main/orcad/orcad-local-serve-selection.ts rename to src/main/orcad/serve-startup/orcad-local-serve-selection.ts index 0bf91a2228f..bc5d364db4f 100644 --- a/src/main/orcad/orcad-local-serve-selection.ts +++ b/src/main/orcad/serve-startup/orcad-local-serve-selection.ts @@ -3,31 +3,31 @@ import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, readFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { runProcess } from '@orca/process-host' -import { NODE_RUNTIME_ASSETS, type ServerTarget } from '../../shared/node-runtime-pin' +import { NODE_RUNTIME_ASSETS, type ServerTarget } from '../../../shared/node-runtime-pin' import { ORCAD_SERVER_ENTRY_FILENAME, ORCAD_VERSION_FILENAME, orcadNodeRuntimeRelativePath -} from '../../shared/orcad-artifacts' +} from '../../../shared/orcad-artifacts' import { ORCAD_NATIVE_PREFLIGHT_FLAG, parseOrcadNativePreflightReport -} from '../../shared/orcad-native-preflight-report' +} from '../../../shared/orcad-native-preflight-report' import { SERVE_RUNTIME_ELECTRON, SERVE_RUNTIME_ENV, type ServeRuntimeSelection -} from '../../shared/orcad-local-serve-selection' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { detectNativeHostAbi, nativeSlotName } from './native-host-abi' -import { materializeOrcadArtifact } from './orcad-artifact-materializer' -import { materializeCachedNodeRuntime } from '../node-runtime/pinned-runtime-materializer' +} from '../../../shared/orcad-local-serve-selection' +import { resolveBundledOrcadRuntime } from '../runtime-launch/orcad-bundled-runtime' +import { detectNativeHostAbi, nativeSlotName } from '../native-runtime/native-host-abi' +import { materializeOrcadArtifact } from '../artifact-slots/orcad-artifact-materializer' +import { materializeCachedNodeRuntime } from '../../node-runtime/pinned-runtime-materializer' import { copyVerifiedAppImageNodeRuntime, type AppImageNodeRuntime -} from '../node-runtime/appimage-bundled-node-runtime' -import { serveProfileHasSshTargets } from './serve-profile-ssh-targets' -import { errorMessage } from '../../shared/error-message' +} from '../../node-runtime/appimage-bundled-node-runtime' +import { serveProfileHasSshTargets } from '../profile-state/serve-profile-ssh-targets' +import { errorMessage } from '../../../shared/error-message' const NATIVE_PREFLIGHT_TIMEOUT_MS = 30_000 diff --git a/src/main/orcad/orcad-serve-readiness.ts b/src/main/orcad/serve-startup/orcad-serve-readiness.ts similarity index 70% rename from src/main/orcad/orcad-serve-readiness.ts rename to src/main/orcad/serve-startup/orcad-serve-readiness.ts index 2e94738f536..4e4159e0d66 100644 --- a/src/main/orcad/orcad-serve-readiness.ts +++ b/src/main/orcad/serve-startup/orcad-serve-readiness.ts @@ -1,7 +1,7 @@ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcaRuntimeRpcServer } from '../runtime/rpc/server/runtime-rpc' -import { buildServePairingReadiness } from '../server/serve-pairing-readiness' -import type { OrcadHealth } from './orcad-health' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcaRuntimeRpcServer } from '../../runtime/rpc/server/runtime-rpc' +import { buildServePairingReadiness } from '../../server/serve-pairing-readiness' +import type { OrcadHealth } from '../diagnostics/orcad-health' import type { OrcadOptions } from './orcad-start-contract' export async function buildOrcadServeReadiness(input: { diff --git a/src/main/orcad/orcad-serve-supervision.ts b/src/main/orcad/serve-startup/orcad-serve-supervision.ts similarity index 90% rename from src/main/orcad/orcad-serve-supervision.ts rename to src/main/orcad/serve-startup/orcad-serve-supervision.ts index e45e076d85e..061f31fa140 100644 --- a/src/main/orcad/orcad-serve-supervision.ts +++ b/src/main/orcad/serve-startup/orcad-serve-supervision.ts @@ -1,6 +1,6 @@ // `orca serve --supervise` runs orcad under a service manager, which restarts it routinely. import process from 'node:process' -import { ORCA_SERVE_SUPERVISED_ENV } from '../../shared/serve-supervised-terminal-durability' +import { ORCA_SERVE_SUPERVISED_ENV } from '../../../shared/serve-supervised-terminal-durability' /** A supervised service must not hand out terminals that its next restart would kill. */ export class OrcadTerminalsNotDurableError extends Error { diff --git a/src/main/orcad/orcad-start-contract.ts b/src/main/orcad/serve-startup/orcad-start-contract.ts similarity index 84% rename from src/main/orcad/orcad-start-contract.ts rename to src/main/orcad/serve-startup/orcad-start-contract.ts index e30420addb6..f61e4f16cc4 100644 --- a/src/main/orcad/orcad-start-contract.ts +++ b/src/main/orcad/serve-startup/orcad-start-contract.ts @@ -1,5 +1,5 @@ -import type { ServeReadiness } from '../server/serve-readiness' -import type { OrcadManagedStopContext } from '../../shared/orcad-stop-request' +import type { ServeReadiness } from '../../server/serve-readiness' +import type { OrcadManagedStopContext } from '../../../shared/orcad-stop-request' export type OrcadOptions = { port?: number diff --git a/src/main/orcad/orcad-ws-port-policy.ts b/src/main/orcad/serve-startup/orcad-ws-port-policy.ts similarity index 85% rename from src/main/orcad/orcad-ws-port-policy.ts rename to src/main/orcad/serve-startup/orcad-ws-port-policy.ts index 37445ae3eb9..7103e9e32ca 100644 --- a/src/main/orcad/orcad-ws-port-policy.ts +++ b/src/main/orcad/serve-startup/orcad-ws-port-policy.ts @@ -1,4 +1,4 @@ -import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../shared/orcad-managed-launch-env' +import { ORCAD_MANAGED_ACTIVATION_ROOT_ENV } from '../../../shared/orcad-managed-launch-env' type OrcadWsPortOptions = { wsPort?: number diff --git a/src/main/orcad/orcad-daemon-session-client-fixture.ts b/src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture.ts similarity index 100% rename from src/main/orcad/orcad-daemon-session-client-fixture.ts rename to src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture.ts diff --git a/src/main/orcad/orcad-daemon-teardown-fixture.ts b/src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts similarity index 91% rename from src/main/orcad/orcad-daemon-teardown-fixture.ts rename to src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts index bbd400bf7dc..133372497c2 100644 --- a/src/main/orcad/orcad-daemon-teardown-fixture.ts +++ b/src/main/orcad/testing/daemon-processes/orcad-daemon-teardown-fixture.ts @@ -7,15 +7,15 @@ import { buildProcessTableIndex, collectDescendantsFromIndex, type ProcessTableIndexOf -} from '../../shared/process-table-index' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' -import { DaemonEndpointOwnershipError } from '../daemon/launch/daemon-endpoint-adoption' -import { parseLinuxProcessState } from '../daemon/endpoint/identity/daemon-incarnation-evidence' -import { readDaemonPidRecord } from '../daemon/endpoint/identity/daemon-endpoint-incarnation' -import { readLinuxStat } from '../daemon/endpoint/identity/daemon-process-inspection' -import { cleanupDaemonForProtocol } from '../daemon/launch/daemon-protocol-cleanup' -import type { WindowsProcessIdentityRow } from '../windows/windows-process-table' +} from '../../../../shared/process-table-index' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { parseLinuxStartTicks } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' +import { DaemonEndpointOwnershipError } from '../../../daemon/launch/daemon-endpoint-adoption' +import { parseLinuxProcessState } from '../../../daemon/endpoint/identity/daemon-incarnation-evidence' +import { readDaemonPidRecord } from '../../../daemon/endpoint/identity/daemon-endpoint-incarnation' +import { readLinuxStat } from '../../../daemon/endpoint/identity/daemon-process-inspection' +import { cleanupDaemonForProtocol } from '../../../daemon/launch/daemon-protocol-cleanup' +import type { WindowsProcessIdentityRow } from '../../../windows/windows-process-table' import type { spawnProcess } from '@orca/process-host' const EXIT_WAIT_MS = 10_000 @@ -126,7 +126,7 @@ async function readWindowsProcessTable(): Promise limit - ? value.slice(-limit).replace(/^[^\r\n]*(?:\r?\n|$)/u, '[truncated]\n') - : value - return tail - .replace(/\b(?:https?|wss?):\/\/\S+/giu, '[url]') - .replace(/\bBearer\s+\S+/giu, 'Bearer [redacted]') - .replace(/((?:token|pairingCode|authToken)["'=:\s]+)\S+/giu, '$1[redacted]') - .slice(-limit) -} - function errorDetails(error: unknown): Record { if (!(error instanceof Error)) { return { message: boundedText(String(error)) } @@ -139,7 +129,7 @@ export class ServeCleanupDiagnostics { snapshot.processEvidence = 'unverifiable: Windows native capture only' return } - const table = await import('../windows/windows-process-table') + const table = await import('../../../windows/windows-process-table') // Refuse fallback evidence: the public reader can use CIM without the native binding. if (!table.isWindowsProcessTableAvailable()) { snapshot.processEvidence = 'unverifiable: native process table unavailable' diff --git a/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts b/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts new file mode 100644 index 00000000000..343332b4fae --- /dev/null +++ b/src/main/orcad/testing/serve-lifecycle/orcad-serve-cleanup-redaction.test-fixture.ts @@ -0,0 +1,11 @@ +export function boundedText(value: string, limit = 2_048): string { + const tail = + value.length > limit + ? value.slice(-limit).replace(/^[^\r\n]*(?:\r?\n|$)/u, '[truncated]\n') + : value + return tail + .replace(/\b(?:https?|wss?):\/\/\S+/giu, '[url]') + .replace(/\bBearer\s+\S+/giu, 'Bearer [redacted]') + .replace(/((?:token|pairingCode|authToken)["'=:\s]+)\S+/giu, '$1[redacted]') + .slice(-limit) +} diff --git a/src/main/orcad/orcad-serve-parity.integration.test.ts b/src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts similarity index 93% rename from src/main/orcad/orcad-serve-parity.integration.test.ts rename to src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts index 4965f8aefc5..7b936dde3eb 100644 --- a/src/main/orcad/orcad-serve-parity.integration.test.ts +++ b/src/main/orcad/testing/serve-lifecycle/orcad-serve-parity.integration.test.ts @@ -3,16 +3,16 @@ import { tmpdir, userInfo } from 'node:os' import { join, resolve } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { runProcess, spawnProcess } from '@orca/process-host' -import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../shared/orcad-artifacts' +import { ORCAD_NODE_RUNTIME_MARKER_FILENAME } from '../../../../shared/orcad-artifacts' import { findBundledWebClientRoot, WEB_CLIENT_INDEX_FILENAME -} from '../../shared/bundled-web-client-root' -import { orcadServeArgs } from '../../shared/orcad-serve-argv' -import { ORCAD_LOCK_FILE_NAME } from './orcad-instance-lock' -import { resolveBundledOrcadRuntime } from './orcad-bundled-runtime' -import { skipForMissingInputs } from './orcad-node-slot-fixture' -import { buildDaemonSessionClient } from './orcad-daemon-session-client-fixture' +} from '../../../../shared/bundled-web-client-root' +import { orcadServeArgs } from '../../../../shared/orcad-serve-argv' +import { ORCAD_LOCK_FILE_NAME } from '../../instance-lock/orcad-instance-lock' +import { resolveBundledOrcadRuntime } from '../../runtime-launch/orcad-bundled-runtime' +import { skipForMissingInputs } from '../native-slots/orcad-node-slot-fixture' +import { buildDaemonSessionClient } from '../daemon-processes/orcad-daemon-session-client-fixture' import type { ServeCleanupDiagnostics } from './orcad-serve-cleanup-diagnostics.test-fixture' import { killAndAwaitExit, @@ -20,7 +20,7 @@ import { recordProfileDaemons, removeTestRoot, waitForProcessExit -} from './orcad-daemon-teardown-fixture' +} from '../daemon-processes/orcad-daemon-teardown-fixture' const slotDir = resolve('out/orcad') const runtime = existsSync(join(slotDir, ORCAD_NODE_RUNTIME_MARKER_FILENAME)) diff --git a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts b/src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts similarity index 88% rename from src/main/orcad/orcad-packaged-structured-chat.integration.test.ts rename to src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts index 09dfd71eb7c..5f22fa3cd04 100644 --- a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts +++ b/src/main/orcad/testing/structured-chat/orcad-packaged-structured-chat.integration.test.ts @@ -12,40 +12,40 @@ import { tmpdir } from 'node:os' import { delimiter, dirname, join, resolve } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { z } from 'zod' -import { getDefaultPersistedState } from '../../shared/constants' -import { folderWorkspaceKey } from '../../shared/workspace-scope' +import { getDefaultPersistedState } from '../../../../shared/constants' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { spawnProcess } from '@orca/process-host' -import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session/lifecycle/agent-session-mutation-envelope' -import type { AgentSessionSubscribeEvent } from '../../shared/agent-session/agent-session-wire' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import { parsePairingCode } from '../../shared/remote-runtime/pairing/pairing' +import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' +import type { AgentSessionSubscribeEvent } from '../../../../shared/agent-session/agent-session-wire' +import type { AgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { parsePairingCode } from '../../../../shared/remote-runtime/pairing/pairing' import { pairedRuntimeConnectionFromOffer, type PairedRuntimeConnection -} from '../../shared/remote-runtime/pairing/paired-runtime-connection' +} from '../../../../shared/remote-runtime/pairing/paired-runtime-connection' import { AGENT_SESSION_TURN_ITEM_CAPABILITY, CLAUDE_STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, STRUCTURED_AGENT_SESSION_CLIENT_LAUNCH_MODE_CAPABILITY, STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY -} from '../../shared/agent-session/agent-session-runtime-capabilities' -import { sendRemoteRuntimeRequestOnSocket } from '../../shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RemoteRuntimeTransportSubscription } from '../../shared/remote-runtime/requests/remote-runtime-subscription-contract' -import { claudeSessionIdForOrcaSession } from '../claude/structured/claude-structured-session-id' -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { materializeOrcadArtifact } from './orcad-artifact-materializer' +} from '../../../../shared/agent-session/agent-session-runtime-capabilities' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { materializeOrcadArtifact } from '../../artifact-slots/orcad-artifact-materializer' import { hostServerTarget, installPackagedOrcadSlotForTests, locatePinnedNodeForTests, skipForMissingInputs -} from './orcad-node-slot-fixture' +} from '../native-slots/orcad-node-slot-fixture' import { killChildAndWait, killProfileDaemons, removeTestRoot -} from './orcad-daemon-teardown-fixture' +} from '../daemon-processes/orcad-daemon-teardown-fixture' import { packagedClaudeChatScenario } from './orcad-structured-chat-scenario' const pinnedNode = locatePinnedNodeForTests() diff --git a/src/main/orcad/orcad-structured-chat-scenario.ts b/src/main/orcad/testing/structured-chat/orcad-structured-chat-scenario.ts similarity index 100% rename from src/main/orcad/orcad-structured-chat-scenario.ts rename to src/main/orcad/testing/structured-chat/orcad-structured-chat-scenario.ts diff --git a/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts b/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts index 19462e0987f..398cc20e6a2 100644 --- a/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts +++ b/src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture.ts @@ -5,7 +5,7 @@ import { type WslMoveCutover, type WslMoveCutoverPhase } from '../../../../shared/wsl-move/wsl-move-cutover' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' export function wslMoveCutoverFixture( migrationId = 'move-1', diff --git a/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts b/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts index 6cf08858025..3aef7f43e57 100644 --- a/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts +++ b/src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts @@ -1,5 +1,5 @@ // Validate blob contents before commit; install only advertised kinds after durable commit. -import { servesWslMovedPaneHistory } from '../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../orcad/migration/orcad-migration-wsl-destination' import { readFileSync, rmSync } from 'node:fs' import { dirname } from 'node:path' import type { OrcadMigrationBlobKind } from '../../../../shared/orcad-migration/orcad-migration-blob-transfer' diff --git a/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts b/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts index 23659cc7b2d..02220b07db8 100644 --- a/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts +++ b/src/main/persistence/migrating-orcad-catalog/catalog-commit/persistence-orcad-migration-catalog-fixture.ts @@ -10,7 +10,7 @@ import type { ProjectGroup } from '../../../../shared/project-group-types' import type { Repo } from '../../../../shared/repo-types' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { worktreeWorkspaceKey } from '../../../../shared/workspace-scope' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' export const PROJECT_GROUP: ProjectGroup = { id: 'group-1', diff --git a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts index 99b85207721..583b31a74c6 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-migration-manifest-export.ts @@ -24,7 +24,7 @@ import { import type { SshTarget } from '../../../../../shared/ssh-types' import type { Store } from '../../../loading-store/store' import { collectOrcadMigrationSourceCatalog } from './orcad-source-catalog' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' import { IDENTITY_ORCAD_MIGRATION_PATH_REWRITER, rewriteOrcadMigrationPayloadPaths, diff --git a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts index d0631ca7efa..305a73dfa01 100644 --- a/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts +++ b/src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-export.ts @@ -9,7 +9,7 @@ import type { OrcadMigrationManifest, OrcadMigrationManifestSource } from '../../../../../shared/orcad-migration/orcad-migration-manifest' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { StoreRuntimeState } from '../../../loading-store/store-runtime-state' import { collectOrcadMigrationUntransferredDependencyCensus, diff --git a/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts b/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts index f2fe0a7ecc5..209d0580a1a 100644 --- a/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts +++ b/src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal.ts @@ -6,7 +6,7 @@ import { type WslMoveCutover } from '../../../../shared/wsl-move/wsl-move-cutover' import { isRecord } from '../../../../shared/orcad-migration/orcad-migration-manifest-fields' -import { assertOrcadMigrationManifestDigest } from '../../../orcad/orcad-migration-manifest-digest' +import { assertOrcadMigrationManifestDigest } from '../../../orcad/migration/orcad-migration-manifest-digest' import { createMigrationJournalDirectory, orderMigrationJournalChain diff --git a/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts b/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts index f8a96420334..d5aaacd7700 100644 --- a/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts +++ b/src/main/persistence/moving-wsl-projects/manifest-scope/wsl-move-manifest-export.ts @@ -23,7 +23,7 @@ import type { ProjectGroup } from '../../../../shared/project-group-types' import type { Repo } from '../../../../shared/repo-types' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { getRepoIdFromWorktreeId, getRepoMainWorktreeId } from '../../../../shared/worktree/id' -import { computeOrcadMigrationManifestSha256 } from '../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../orcad/migration/orcad-migration-manifest-digest' import { hasDormantState } from '../../migrating-orcad-catalog/source/dormancy/orcad-migration-dormant-state' import { rewriteOrcadMigrationPayloadPaths, diff --git a/src/main/runtime/hosts/runtime-status.ts b/src/main/runtime/hosts/runtime-status.ts index 73dc3dea758..7452fa18c76 100644 --- a/src/main/runtime/hosts/runtime-status.ts +++ b/src/main/runtime/hosts/runtime-status.ts @@ -13,9 +13,9 @@ import { runtimeBrowserUnavailableCause } from '../browser/installation/runtime-browser-commands-factory' import { isBrowserIdentityModeStoreInitialized } from '../../browser/identity/mode/browser-identity-mode-store' -import { servesLocalWslMigrationSource } from '../../orcad/orcad-migration-wsl-destination' +import { servesLocalWslMigrationSource } from '../../orcad/migration/orcad-migration-wsl-destination' import { ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY } from '../../../shared/orcad-runtime-capabilities' -import { advertisedOrcadMigrationDestinationCapabilities } from '../../orcad/orcad-migration-destination-capabilities' +import { advertisedOrcadMigrationDestinationCapabilities } from '../../orcad/migration/orcad-migration-destination-capabilities' import { USAGE_CREDENTIALS_RUNTIME_CAPABILITY } from '../../../shared/account-runtime-capabilities' import { MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION, diff --git a/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts b/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts index 1f570dab21a..ba0d755f1c8 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-migration.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import type { OrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest' -import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/orcad-migration-manifest-digest' +import { computeOrcadMigrationManifestSha256 } from '../../../../orcad/migration/orcad-migration-manifest-digest' import type { OrcaRuntimeService } from '../../../orca-runtime' import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../../core' import '../rpc-method-registry' @@ -62,39 +62,6 @@ function context( } describe('orcad migration RPC', () => { - it.each([ - ['mobile client', { clientKind: 'mobile', pairedDeviceId: 'paired-phone' }], - ['unpaired runtime client', { clientKind: 'runtime', pairedDeviceId: undefined }], - ['local caller', { clientKind: undefined, pairedDeviceId: undefined }] - ] as const)('rejects a %s before any migration mutation', async (_label, caller) => { - for (const name of MIGRATION_METHOD_NAMES) { - const invoke = vi.fn() - const method = migrationMethod(name) - const runtimeMethod = - name === 'orcad.migration.stageCatalog' - ? 'stageOrcadMigrationCatalog' - : name === 'orcad.migration.commitCatalog' - ? 'commitStagedOrcadMigrationCatalog' - : name === 'orcad.migration.stageSnapshotChunk' - ? 'stageOrcadMigrationSnapshotChunk' - : name === 'orcad.migration.stageBlobChunk' - ? 'stageOrcadMigrationBlobChunk' - : name === 'orcad.migration.abortCatalog' - ? 'abortStagedOrcadMigrationCatalog' - : name === 'orcad.migration.abortCatalogByReference' - ? 'abortStagedOrcadMigrationCatalogByReference' - : 'getOrcadMigrationCatalogState' - - await expect( - method.handler( - method.params?.parse(migrationMethodInput(name)), - context(invoke, caller, { [runtimeMethod]: invoke }) - ) - ).rejects.toThrow('orcad_migration_runtime_client_required') - expect(invoke).not.toHaveBeenCalled() - } - }) - it('rejects malformed and tampered manifests before staging', async () => { const stageCatalog = vi.fn() const method = migrationMethod() @@ -150,36 +117,3 @@ describe('orcad migration RPC', () => { expect(stageCatalog).toHaveBeenCalledTimes(1) }) }) - -function migrationSnapshotRequest(input: OrcadMigrationManifest) { - return { - migrationId: input.migrationId, - manifestSha256: input.manifestSha256, - ref: `v1-${'1'.repeat(32)}`, - offset: 0, - bytesBase64: 'YQ==' - } -} - -function migrationMethodInput(name: (typeof MIGRATION_METHOD_NAMES)[number]) { - const input = manifest() - if (name === 'orcad.migration.stageBlobChunk') { - return migrationBlobRequest(input) - } - if (name === 'orcad.migration.abortCatalogByReference') { - return { migrationId: input.migrationId, manifestSha256: input.manifestSha256 } - } - return name === 'orcad.migration.stageSnapshotChunk' - ? migrationSnapshotRequest(input) - : { manifest: input } -} - -function migrationBlobRequest(input: OrcadMigrationManifest, key = `${'a'.repeat(16)}-zsh`) { - return { - migrationId: input.migrationId, - manifestSha256: input.manifestSha256, - blob: { blobKind: 'shell-history', key, sha256: 'b'.repeat(64), byteLength: 1 }, - offset: 0, - bytesBase64: 'YQ==' - } -} diff --git a/src/main/runtime/rpc/methods/orcad/orcad-migration.ts b/src/main/runtime/rpc/methods/orcad/orcad-migration.ts index 0ff85c6b71c..6c92980a40e 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-migration.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-migration.ts @@ -7,8 +7,8 @@ import { import { parseOrcadMigrationManifest } from '../../../../../shared/orcad-migration/orcad-migration-manifest-validation' import { OrcadMigrationSnapshotChunkRequestSchema } from '../../../../../shared/orcad-migration/orcad-migration-scrollback' import { OrcadMigrationBlobChunkRequestSchema } from '../../../../../shared/orcad-migration/orcad-migration-blob-transfer' -import { assertOrcadMigrationManifestDigest } from '../../../../orcad/orcad-migration-manifest-digest' -import { assertOrcadMigrationSourceServedHere } from '../../../../orcad/orcad-migration-wsl-destination' +import { assertOrcadMigrationManifestDigest } from '../../../../orcad/migration/orcad-migration-manifest-digest' +import { assertOrcadMigrationSourceServedHere } from '../../../../orcad/migration/orcad-migration-wsl-destination' import { defineMethod, type RpcContext } from '../../core' export const ORCAD_MIGRATION_METHODS = [ diff --git a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts index 953c6b65120..bcfb8bb819c 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.test.ts @@ -1,7 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const collect = vi.hoisted(() => vi.fn()) -vi.mock('../../../../orcad/orcad-terminal-census', () => ({ collectOrcadTerminalCensus: collect })) +vi.mock('../../../../orcad/diagnostics/orcad-terminal-census', () => ({ + collectOrcadTerminalCensus: collect +})) import { ORCAD_TERMINAL_CENSUS_METHODS } from './orcad-terminal-census' import { TerminalUpdateAdmission } from '../../../terminal/stop/terminal-update-admission' diff --git a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts index 701ea5b00fd..5358e113543 100644 --- a/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts +++ b/src/main/runtime/rpc/methods/orcad/orcad-terminal-census.ts @@ -40,7 +40,8 @@ async function countTerminals( runtime: Pick ): Promise { // Import lazily: daemon modules install xterm's global window and must not contaminate every dispatcher process. - const { collectOrcadTerminalCensus } = await import('../../../../orcad/orcad-terminal-census') + const { collectOrcadTerminalCensus } = + await import('../../../../orcad/diagnostics/orcad-terminal-census') if (!params.releaseFinishedAutomationTerminals) { return collectOrcadTerminalCensus(params.activatedAt) } diff --git a/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts b/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts index 05d5db25a7e..e2c4f23a734 100644 --- a/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts +++ b/src/main/runtime/rpc/methods/terminal/session-terminal-scrollback.ts @@ -1,6 +1,6 @@ import { SessionReadTerminalScrollbackParams } from '../../../../../shared/rpc-contract/session-terminal-scrollback-params' import { defineMethod } from '../../core' -import { servesWslMovedPaneHistory } from '../../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../../orcad/migration/orcad-migration-wsl-destination' // Defined statically so the params catalog types it; registration is gated per host below. export const SESSION_TERMINAL_SCROLLBACK_METHODS = [ diff --git a/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts b/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts index 24b4762a578..40dee62d413 100644 --- a/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts +++ b/src/main/runtime/session-lifecycle/projection/restored-pane-materialize.ts @@ -29,7 +29,7 @@ import type { NewerDaemonReopenResult } from '../../../../shared/newer-daemon-ho import type { WorkspaceLayoutStream } from '../../terminal/surface/workspace-layout-stream' import { getDaemonHistoryDir } from '../../../daemon/launch/daemon-launch-paths' import { HistoryReader } from '../../../daemon/history/restoration/history-reader' -import { servesWslMovedPaneHistory } from '../../../orcad/orcad-migration-wsl-destination' +import { servesWslMovedPaneHistory } from '../../../orcad/migration/orcad-migration-wsl-destination' import { movedPaneHistorySessionId } from '../../../persistence/migrating-orcad-catalog/terminal-history/orcad-terminal-history-installer' import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { agentProviderSessionsEqual } from '../../../../shared/agent-session/lifecycle/agent-session-resume' diff --git a/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts b/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts deleted file mode 100644 index fd8618e5025..00000000000 --- a/src/main/runtime/terminal/stop/terminal-update-admission-census.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -// An update counts the server's terminals, then stops it: a terminal started between the two -// would die with the stop, uncounted. The last census closes admission so none can start. -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { z } from 'zod' -import { - ORCAD_UPDATE_ADMISSION_FENCE_MS, - OrcadTerminalCensusParamsSchema -} from '../../../../shared/orcad-terminal-census' -import { spawnWorktreeTarget } from '../../../../shared/worktree/host-qualified-identity' -import { ORCAD_TERMINAL_CENSUS_METHODS } from '../../rpc/methods/orcad/orcad-terminal-census' -import { TERMINAL_UPDATE_ADMISSION_CLOSED_MESSAGE } from './terminal-update-admission' - -const { collect, listLiveDaemonPtyIds } = vi.hoisted(() => ({ - collect: vi.fn(), - listLiveDaemonPtyIds: vi.fn<() => Promise>() -})) -vi.mock('../../../orcad/orcad-terminal-census', () => ({ collectOrcadTerminalCensus: collect })) -vi.mock('../../../daemon/providers/lifecycle/daemon-provider-state', () => ({ - listLiveDaemonPtyIds -})) - -// Fragments stay side-effect ordered: mocks, then lifecycle, then fixtures. -await import('../../orca-runtime-tests/runtime-test-module-registration.spec') -const { OrcaRuntimeService } = await import('../../orca-runtime') -await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec') -const { TEST_WORKTREE_ID, store } = - await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const idle = { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 7 } -const target = spawnWorktreeTarget(TEST_WORKTREE_ID, null) - -type CensusRequest = Omit, 'activatedAt'> - -function census(runtime: InstanceType, params: CensusRequest) { - // Parsed as the server parses it, so a field the server does not know is dropped here too. - const parsed = OrcadTerminalCensusParamsSchema.parse({ activatedAt: 1, ...params }) - return ORCAD_TERMINAL_CENSUS_METHODS[0]!.handler(parsed, { runtime }) -} - -// What the SSH and WSL updates send as the last count before the stop. -const updateRecount: CensusRequest = { - releaseFinishedAutomationTerminals: true, - closeAdmissionForMs: ORCAD_UPDATE_ADMISSION_FENCE_MS -} - -afterEach(() => { - collect.mockReset() - listLiveDaemonPtyIds.mockReset() -}) - -describe("an update's last terminal census", () => { - it('counts only after a spawn admitted before it has finished starting', async () => { - collect.mockResolvedValue({ ...idle, liveSessions: 1 }) - const runtime = new OrcaRuntimeService(store) - const releaseSpawn = await runtime.acquireWorktreeTerminalSpawn(target) - - const counted = census(runtime, updateRecount) - await vi.waitFor(() => expect(runtime.terminalUpdateAdmission.isClosed()).toBe(true)) - expect(collect).not.toHaveBeenCalled() - releaseSpawn() - - await expect(counted).resolves.toMatchObject({ liveSessions: 1 }) - }) - - it('still lets a client reattach a session the daemon runs, but not one it cannot vouch for', async () => { - collect.mockResolvedValue({ ...idle, liveSessions: 1 }) - const runtime = new OrcaRuntimeService(store) - await census(runtime, updateRecount) - - listLiveDaemonPtyIds.mockResolvedValue(['pty-live']) - const requireAttachOnly = vi.fn() - const release = await runtime.acquireWorktreeTerminalSpawn(target, { - reattachSessionId: 'pty-live', - requireAttachOnly - }) - release() - // Should the session exit before the attach lands, the spawn fails instead of starting one. - expect(requireAttachOnly).toHaveBeenCalledTimes(1) - listLiveDaemonPtyIds.mockResolvedValue(null) - await expect( - runtime.acquireWorktreeTerminalSpawn(target, { reattachSessionId: 'pty-live' }) - ).rejects.toThrow(TERMINAL_UPDATE_ADMISSION_CLOSED_MESSAGE) - }) -}) diff --git a/src/main/server/serve-readiness.ts b/src/main/server/serve-readiness.ts index ec1efd1134e..1f05b2987c2 100644 --- a/src/main/server/serve-readiness.ts +++ b/src/main/server/serve-readiness.ts @@ -1,5 +1,5 @@ import type { PairingOfferUnavailableReason } from '../runtime/rpc/server/runtime-rpc-pairing-types' -import type { OrcadHealth } from '../orcad/orcad-health' +import type { OrcadHealth } from '../orcad/diagnostics/orcad-health' import { describePtyProcessCeiling } from '../../shared/terminal/pty/native-process/pty-process-ceiling-state' export type ServePairingUnavailableReason = PairingOfferUnavailableReason | 'disabled_by_operator' diff --git a/src/main/ssh/host-server/ssh-host-server-connect-events.ts b/src/main/ssh/host-server/ssh-host-server-connect-events.ts index cb46e501da6..899f97ab0ef 100644 --- a/src/main/ssh/host-server/ssh-host-server-connect-events.ts +++ b/src/main/ssh/host-server/ssh-host-server-connect-events.ts @@ -5,7 +5,7 @@ import type { } from '../../../shared/orcad-managed-runtime' import type { SshTarget } from '../../../shared/ssh-types' import type { HostServerOnConnectResult } from './ssh-host-server-on-connect' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' export type HostServerConnectEvent = | { diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts index d10c4eed181..ede657e8357 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts @@ -3,11 +3,8 @@ import type { SshTarget } from '../../../shared/ssh-types' import { OrcadHostUnsupportedError, OrcadStdioBridgeUnavailableError -} from '../../orcad/orcad-host-unavailable' -import { - resolveHostServerOnConnect, - type HostServerOnConnectDeps -} from './ssh-host-server-on-connect' +} from '../../orcad/diagnostics/orcad-host-unavailable' +import { resolveHostServerOnConnect } from './ssh-host-server-on-connect' import { hostServerDepsStub } from './testing/ssh-host-server-on-connect-test-deps' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } @@ -180,18 +177,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.recordUnavailable).toHaveBeenCalledWith(target, 'ssh_tunnel_unavailable') }) - it('keeps a staged or converted host fenced when its tunnel fails', async () => { - const failure = new OrcadStdioBridgeUnavailableError('exit 127') - const d = deps({ - managedEnvironmentId: () => 'env-9', - ensureTunnel: vi.fn(async () => { - throw failure - }) - }) - await expect(resolveHostServerOnConnect(target, d)).rejects.toBe(failure) - expect(d.releaseUnreachableSetup).not.toHaveBeenCalled() - }) - it('backs an uncommitted conversion out to the relay when its commit fails', async () => { const d = deps({ managedEnvironmentId: () => 'env-9', @@ -207,30 +192,4 @@ describe('which server an SSH host runs on connect', () => { }) expect(d.abandonConversion).toHaveBeenCalledWith(target) }) - - describe('updating a managed host on connect', () => { - const managed = (overrides: Partial) => - deps({ managedEnvironmentId: () => 'env-9', ...overrides }) - - it('starts a stopped server before the update counts its terminals, as after a reboot', async () => { - const order: string[] = [] - const d = managed({ - ensureServing: vi.fn(async () => { - order.push('start') - return { state: 'started' as const, boundPort: null } - }), - // Wake first so the restarted daemon can supply authoritative idle census. - autoUpdate: vi.fn(async (_id, options) => { - order.push('update') - options.onUpdating() - return { outcome: 'updated' as const, activeVersion: '0.1.0+b' } - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9' - }) - expect(order).toEqual(['start', 'update']) - }) - }) }) diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.ts index e0214aaabba..bda0ee93396 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.ts @@ -22,7 +22,7 @@ import { deferred, setupFailed } from './ssh-host-server-setup-outcome' import { classifyOrcadHostUnavailable, ORCAD_TUNNEL_UNAVAILABLE_REASON -} from '../../orcad/orcad-host-unavailable' +} from '../../orcad/diagnostics/orcad-host-unavailable' import { decidedEvent, reportHostServerConversion, diff --git a/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts index bb1f592b654..89d00a123ec 100644 --- a/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts +++ b/src/main/ssh/host-server/ssh-host-server-setup-outcome.ts @@ -7,7 +7,7 @@ import type { import { orcadMigrationConflictGuidance } from '../../managed-server/migration/cutover/orcad-migration-conflict-guidance' import { boundedDetail, setupFailure, type SetupFailure } from './ssh-host-server-setup-failure' import { isSshSessionStartFailure } from '../connection/ssh-session-start-failure' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' import { reportHostServerSetupError, type HostServerDecisionTrace diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts index 99ecc4a210c..9136c2eb5f6 100644 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-cells.ts @@ -1,6 +1,6 @@ /** Run real managed-orcad deployment against container/loopback host constraints in ssh-hostile-hosts.yml. */ import type { NodeRuntimeTarget } from '../../../shared/node-runtime-pin' -import type { OrcadHostUnavailableReason } from '../../orcad/orcad-host-unavailable' +import type { OrcadHostUnavailableReason } from '../../orcad/diagnostics/orcad-host-unavailable' /** Every shimmed toolchain command appends its name here; a managed deploy must leave it empty. */ export const FORBIDDEN_TOOL_LOG = '/tmp/orca-forbidden-tool-calls.log' diff --git a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts index 7429b761518..dd605c5aa31 100644 --- a/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts +++ b/src/main/ssh/hostile-host-test-support/ssh-hostile-host-managed-orcad.ts @@ -8,7 +8,7 @@ import { ORCAD_MANAGED_REMOTE_PORT } from '../../../shared/orcad-managed-runtime import { ORCAD_RUNTIMES_DIRNAME } from '../../../shared/orcad-artifacts' import type { SshTarget } from '../../../shared/ssh-types' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' -import { classifyOrcadHostUnavailable } from '../../orcad/orcad-host-unavailable' +import { classifyOrcadHostUnavailable } from '../../orcad/diagnostics/orcad-host-unavailable' import { managedOrcadSlot } from '../../managed-server/lifecycle/orcad-managed-runtime-context' import { orcadSlotDir, diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts index 3e29de8f0ac..89305c729be 100644 --- a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-incumbent.ts @@ -12,7 +12,7 @@ import { isUnconfirmedSshCommandTermination } from '../../remote-exec/remote-exec-command' import { isWindowsRemoteHost, type RemoteHostPlatform } from '../../remote-host/ssh-remote-platform' -import { filesystemTypeIsLocalDisk } from '../../../orcad/orcad-data-root-locality' +import { filesystemTypeIsLocalDisk } from '../../../orcad/instance-lock/orcad-data-root-locality' type RelayEndpointVerdict = 'live' | 'unverifiable' | 'exited' diff --git a/src/main/startup/main-process-ready-runtime.ts b/src/main/startup/main-process-ready-runtime.ts index 397c78792ce..36a426219af 100644 --- a/src/main/startup/main-process-ready-runtime.ts +++ b/src/main/startup/main-process-ready-runtime.ts @@ -42,7 +42,7 @@ import { runAfterFirstWindowShown } from './main-window/first-window-deferral' import { startSpeechModelWarmup } from '../speech/speech-model-warmup' import { logStartupMilestone } from './diagnostics/startup-diagnostics' import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/status-hooks/opencode-status-plugin-startup-refresh' -import { pruneDesktopOrcadArtifactCache } from '../orcad/orcad-artifact-cache-retention' +import { pruneDesktopOrcadArtifactCache } from '../orcad/artifact-slots/orcad-artifact-cache-retention' import { runGatedWslMoveDesktopRewritePass } from '../persistence/moving-wsl-projects/desktop-state/wsl-move-desktop-rewrite' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch' import { repairDuplicatePtyPanesOnStart } from '../runtime/terminal/identity/moved-pane-owner-rekey' diff --git a/src/main/startup/profile-startup/desktop-profile-instance-lock.ts b/src/main/startup/profile-startup/desktop-profile-instance-lock.ts index 24255078740..257da781ab1 100644 --- a/src/main/startup/profile-startup/desktop-profile-instance-lock.ts +++ b/src/main/startup/profile-startup/desktop-profile-instance-lock.ts @@ -1,7 +1,7 @@ /** Share orcad's profile lock to prevent concurrent desktop/serve writers; Electron's own instance lock cannot fence plain Node. */ -import { acquireOrcadInstanceLock } from '../../orcad/orcad-instance-lock' -import type { OrcadInstanceLock } from '../../orcad/orcad-instance-lock-hold' -import { OrcadInstanceLockError } from '../../orcad/orcad-data-root-privacy' +import { acquireOrcadInstanceLock } from '../../orcad/instance-lock/orcad-instance-lock' +import type { OrcadInstanceLock } from '../../orcad/instance-lock/orcad-instance-lock-hold' +import { OrcadInstanceLockError } from '../../orcad/instance-lock/orcad-data-root-privacy' import { writeStartupDiagnosticLine, type StartupDiagnosticSink diff --git a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts index 1be232e1463..49a3a1e5898 100644 --- a/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts +++ b/src/main/workspaces/creation/preparation/worktree-create-preparation-stale-cleanup.ts @@ -4,7 +4,7 @@ import { parseWorktreePreparationOwnerPid, parseWorktreePreparationPathOwnerPid } from '../../../../shared/worktree/create-preparation' -import { orcadDataRootIsOnLocalDisk } from '../../../orcad/orcad-data-root-locality' +import { orcadDataRootIsOnLocalDisk } from '../../../orcad/instance-lock/orcad-data-root-locality' import { profileStateAccessMachineIdentity } from '../../../persistence/profile-state/access/profile-state-access-identity' import type { AddWorktreeOptions } from '../../../git/worktrees/worktree-operation-options' import { listWorktreeGraph } from '../../../git/worktrees/catalog/worktree-scan-cache' diff --git a/src/main/wsl/discovery/wsl-distro-unsupported.ts b/src/main/wsl/discovery/wsl-distro-unsupported.ts index 2d25769addc..bccb05fd3c6 100644 --- a/src/main/wsl/discovery/wsl-distro-unsupported.ts +++ b/src/main/wsl/discovery/wsl-distro-unsupported.ts @@ -2,7 +2,7 @@ * Distros that can't host Orca's server, each refused with the step that fixes it. There is no * fallback once the WSL bridge is gone, so a refusal must say what to run, not only what failed. */ -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { OrcadHostGlibcUnsupportedError } from '../../managed-server/lifecycle/orcad-runtime-target' import { RemoteNodeRuntimeSelfTestError } from '../../managed-server/install/orcad-remote-node-runtime-report' import { wslHostAddRefusalText } from '../../../shared/wsl-host-failure-copy' diff --git a/src/main/wsl/execution/wsl-guest-process-identity.ts b/src/main/wsl/execution/wsl-guest-process-identity.ts index 4ee30b043e2..cfd98d870a1 100644 --- a/src/main/wsl/execution/wsl-guest-process-identity.ts +++ b/src/main/wsl/execution/wsl-guest-process-identity.ts @@ -1,5 +1,5 @@ /** Use kernel boot ID and /proc start ticks for distro/process identity; wall-clock jumps after host sleep can misidentify live processes (microsoft/WSL#4179/#10006). */ -import type { OrcadProcessIncarnation } from '../../orcad/orcad-process-start-time' +import type { OrcadProcessIncarnation } from '../../orcad/instance-lock/orcad-process-start-time' import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { execCommand } from '../../ssh/remote-exec/remote-exec-command' diff --git a/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts b/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts index 0bef7c7b592..d28d17346ea 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-connect-failure.ts @@ -1,6 +1,6 @@ import { errorMessage } from '../../../shared/error-message' import { RemoteRuntimeClientError } from '../../../shared/remote-runtime/remote-runtime-client-error' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import { WslDistroNotRunningError, WslOrcadLaunchDeferredError diff --git a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts index 05b54127ddf..1bc383a74f6 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-first-connect.ts @@ -1,7 +1,7 @@ /** Before Add persists its record, removal/disable/startup cannot find the connection or detached holder. Every unsuccessful Add must release both here. */ import { errorMessage } from '../../../shared/error-message' import type { WslHostAddResult } from '../../../shared/wsl-host-types' -import { OrcadHostUnsupportedError } from '../../orcad/orcad-host-unavailable' +import { OrcadHostUnsupportedError } from '../../orcad/diagnostics/orcad-host-unavailable' import type { WslHostConnector } from './wsl-host-connector-contract' import { WslOrcadLaunchDeferredError } from '../orcad/wsl-orcad-connection-errors' import { diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts index cabb9eded94..47b8f8a55dc 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-chat-scenario.ts @@ -1,4 +1,4 @@ -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' /** The normal streamed reply stays open for an approval and the user's Stop. */ export function wslClaudeChatScenario(providerSessionId: string, partialReplyAckPath: string) { diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts index 76073103fc8..83f9aec0c30 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-lane-host-fixture.ts @@ -1,5 +1,5 @@ import type { WslHostStatus } from '../../../../shared/wsl-host-types' -import { hasOrcadTemplate } from '../../../orcad/orcad-artifact-materializer' +import { hasOrcadTemplate } from '../../../orcad/artifact-slots/orcad-artifact-materializer' import { createWslHostConnector } from '../../host-lifecycle/wsl-host-connector' import type { WslHostConnector } from '../../host-lifecycle/wsl-host-connector-contract' import { WslHostService } from '../../host-lifecycle/wsl-host-service' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts index 74ffab31b6d..e99dfddfb14 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-midturn-stop-lane.ts @@ -18,8 +18,8 @@ import { latestNativeChatOrcaStopCut } from '../../../../shared/native-chat/nati import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import type { WslHostStatus } from '../../../../shared/wsl-host-types' import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' -import '../../../orcad/orcad-artifact-materializer' -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import '../../../orcad/artifact-slots/orcad-artifact-materializer' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { wslDistroHolderKey } from '../../discovery/wsl-distro-holder-record' import { wslHostStoppedMessage } from '../../../../shared/wsl-host-stopped-message' import { wslHostConnectOptions } from '../../host-lifecycle/wsl-host-connect-request' diff --git a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts index bac2b644fd2..2aebf199ad0 100644 --- a/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts +++ b/src/main/wsl/orcad/__tests__/wsl-orcad-structured-chat-contract.ts @@ -13,7 +13,7 @@ import '../../../../shared/remote-runtime/requests/remote-runtime-request-socket import { subscribeRemoteRuntimeTransport } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' import type { RemoteRuntimeTransportSubscription } from '../../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' import { claudeSessionIdForOrcaSession } from '../../../claude/structured/claude-structured-session-id' -import { packagedClaudeChatScenario } from '../../../orcad/orcad-structured-chat-scenario' +import { packagedClaudeChatScenario } from '../../../orcad/testing/structured-chat/orcad-structured-chat-scenario' import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { wslClaudeChatScenario } from './wsl-orcad-chat-scenario' import { envelope } from './wsl-orcad-chat-envelope' diff --git a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts index a534753826a..50b5a2f3ae7 100644 --- a/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts +++ b/src/main/wsl/orcad/wsl-orcad-connect-state-snapshot.ts @@ -21,7 +21,7 @@ import { } from '../../managed-server/activation/orcad-activation-transaction' import { execOrcadRemote } from '../../managed-server/install/orcad-remote-runtime-control' import { probeInstallLockExistsCommand } from '../../managed-server/install/remote-install-lock-commands' -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { parseWslGuestIdentity, wslGuestIdentityShellCommand, diff --git a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts index b577859aeea..06252bebd44 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy-app-update.test.ts @@ -54,7 +54,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: mocks.recover })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) @@ -413,50 +413,6 @@ describe('deployAndLaunchWslOrcad across an app update (E1)', () => { expect(mocks.deploy).toHaveBeenCalledTimes(2) }) - it('keeps retrying an update that only waited, or that a newer host refused', async () => { - mocks.deploy.mockResolvedValue({ - outcome: 'installed-not-activated', - fullVersion: '1.5.0+ab', - code: 'orcad_update_terminals_running', - reason: 'busy' - }) - await launch() - await launch() - mocks.deploy.mockResolvedValue(policyRefused) - await launch() - await launch() - expect(mocks.deploy).toHaveBeenCalledTimes(4) - expect(mocks.adoptRunning).not.toHaveBeenCalled() - }) - - it('lets the next connect try again once an explicit Force went through', async () => { - mocks.deploy.mockResolvedValueOnce(rejected) - await launch() - mocks.deploy.mockResolvedValueOnce({ - outcome: 'installed-and-activated', - fullVersion: '1.5.0+ab', - verdict: {} - }) - await launch(undefined, { intent: 'force' }) - mocks.deploy.mockResolvedValueOnce(rejected) - await launch() - expect(mocks.deploy).toHaveBeenCalledTimes(3) - }) - - it('deploys on the record the wake read when the skipped build stopped meanwhile', async () => { - withRecord(newer) - const stopped = { ...newer, active: null, activatedAt: null } - mocks.adoptRunning.mockResolvedValueOnce(null) - mocks.readRecord.mockResolvedValueOnce(stopped) - mocks.deploy.mockResolvedValueOnce(policyRefused) - await launch() - expect(mocks.incumbent).not.toHaveBeenCalled() - expect(mocks.deploy.mock.calls[0][0]).toMatchObject({ - censusRecord: stopped, - census: { liveSessions: 0 } - }) - }) - it('leaves a host stopped after a rollback for Force, not the build it rolled back from', async () => { // Desktop lacks the previous bundle and cannot restart it. const stopped = { diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts index 323ca16f7d2..682a54a6756 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.test.ts @@ -56,7 +56,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: mocks.recover })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: mocks.deploy })) @@ -198,13 +198,4 @@ describe('deployAndLaunchWslOrcad', () => { await expect(launch()).rejects.toBe(refused) expect(mocks.wake).toHaveBeenCalledTimes(3) }) - - it('refuses to deploy or launch when an unrecorded orcad cannot be proven', async () => { - mocks.adopt.mockRejectedValueOnce( - Object.assign(new Error('cannot be identified'), { name: 'WslOrcadUnrecordedInstanceError' }) - ) - await expect(launch()).rejects.toMatchObject({ name: 'WslOrcadUnrecordedInstanceError' }) - expect(mocks.deploy).not.toHaveBeenCalled() - expect(mocks.wake).not.toHaveBeenCalled() - }) }) diff --git a/src/main/wsl/orcad/wsl-orcad-deploy.ts b/src/main/wsl/orcad/wsl-orcad-deploy.ts index 8901944fd21..db72186bc98 100644 --- a/src/main/wsl/orcad/wsl-orcad-deploy.ts +++ b/src/main/wsl/orcad/wsl-orcad-deploy.ts @@ -8,7 +8,7 @@ import type { ServeReadiness } from '../../server/serve-readiness' import { recoverInterruptedOrcadActivation } from '../../managed-server/activation/orcad-activation-recovery' import { readOrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record-store' -import { materializeOrcadArtifact } from '../../orcad/orcad-artifact-materializer' +import { materializeOrcadArtifact } from '../../orcad/artifact-slots/orcad-artifact-materializer' import type { OrcadHostTransport } from '../../managed-server/install/orcad-host-transport' import { ORCAD_ACTIVATION_POLICY_REFUSED_CODE } from '../../managed-server/activation/orcad-installed-activation' import { orcadBoundPort } from '../../managed-server/lifecycle/orcad-managed-bound-port' diff --git a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts index f861a356a7d..97d94c036d5 100644 --- a/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts +++ b/src/main/wsl/orcad/wsl-orcad-instance-adoption.ts @@ -1,10 +1,10 @@ /** Adopt serving unrecorded orcad under the activation fence only when lock, readiness and installed build identify the same process. Never kill it without census; launching another loses the instance lock. Normal update admission handles version changes. */ -import { ORCAD_LOCK_FILE_NAME } from '../../orcad/orcad-instance-lock' +import { ORCAD_LOCK_FILE_NAME } from '../../orcad/instance-lock/orcad-instance-lock' import { parseOrcadInstanceLockRecord, type OrcadLockRecord -} from '../../orcad/orcad-instance-lock-record' -import { compareOrcadProcessIdentity } from '../../orcad/orcad-process-start-time' +} from '../../orcad/instance-lock/orcad-instance-lock-record' +import { compareOrcadProcessIdentity } from '../../orcad/instance-lock/orcad-process-start-time' import type { OrcadActivationRecord } from '../../managed-server/activation/orcad-activation-record' import { readOrcadActivationRecord, diff --git a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts index ff310707c17..1b6c3e8640c 100644 --- a/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts +++ b/src/main/wsl/orcad/wsl-orcad-update-move-hold-driver.test.ts @@ -83,7 +83,7 @@ vi.mock('../../managed-server/install/orcad-remote-context', () => ({ vi.mock('../../managed-server/activation/orcad-activation-recovery', () => ({ recoverInterruptedOrcadActivation: async () => ({ outcome: 'none' }) })) -vi.mock('../../orcad/orcad-artifact-materializer', () => ({ +vi.mock('../../orcad/artifact-slots/orcad-artifact-materializer', () => ({ materializeOrcadArtifact: async () => '/local/orcad' })) vi.mock('../../managed-server/install/orcad-remote-deploy', () => ({ deployOrcad: host.deploy })) diff --git a/tests/e2e/fixtures/daemon-generation-profile-store.ts b/tests/e2e/fixtures/daemon-generation-profile-store.ts index 61c0a2e68c5..0bc39c2e470 100644 --- a/tests/e2e/fixtures/daemon-generation-profile-store.ts +++ b/tests/e2e/fixtures/daemon-generation-profile-store.ts @@ -1,5 +1,5 @@ import path from 'node:path' -import { installOrcadHostAdapters } from '../../../src/main/orcad/orcad-host-adapters' +import { installOrcadHostAdapters } from '../../../src/main/orcad/host-runtime/orcad-host-adapters' import type { Store } from '../../../src/main/persistence/loading-store/store' import { createProfileStateStore } from '../../../src/main/persistence/profile-state/startup/profile-state-store-factory' diff --git a/tests/e2e/helpers/headless-layout-oracle-hosts.ts b/tests/e2e/helpers/headless-layout-oracle-hosts.ts index 1a69e45ab85..3a6a2fe87a9 100644 --- a/tests/e2e/helpers/headless-layout-oracle-hosts.ts +++ b/tests/e2e/helpers/headless-layout-oracle-hosts.ts @@ -5,7 +5,7 @@ import { createServer, type AddressInfo } from 'node:net' import os from 'node:os' import path from 'node:path' import { RuntimeClient } from '../../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../../src/main/orcad/orcad-bundled-runtime' +import { resolveBundledOrcadRuntime } from '../../../src/main/orcad/runtime-launch/orcad-bundled-runtime' import { runProcess } from '@orca/process-host' import { NODE_RUNTIME_PIN } from '../../../src/shared/node-runtime-pin' import { cleanupE2EDaemons } from './electron-process-shutdown' diff --git a/tests/e2e/orcad-serve-mode-switch.spec.ts b/tests/e2e/orcad-serve-mode-switch.spec.ts index 7276ffa694c..6b293d727cf 100644 --- a/tests/e2e/orcad-serve-mode-switch.spec.ts +++ b/tests/e2e/orcad-serve-mode-switch.spec.ts @@ -1,17 +1,17 @@ // D7: switch Electron serve ↔ orcad serve on one profile without replacing surviving daemon terminals; each host must refuse the other’s profile lock. // Build pnpm build:orcad, then run electron-headless with ORCA_E2E_ORCAD_SERVE=1 ORCA_BACKGROUND_LAUNCH=1. -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { runProcess } from '@orca/process-host' import { getDaemonPidPath } from '../../src/main/daemon/launch/daemon-spawner' import { readDaemonPidRecord } from '../../src/main/daemon/endpoint/identity/daemon-endpoint-incarnation' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/orcad-bundled-runtime' -import { ORCAD_EXIT_CONFIGURATION } from '../../src/main/orcad/orcad-configuration-exit' +import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' +import { ORCAD_EXIT_CONFIGURATION } from '../../src/main/orcad/serve-startup/orcad-configuration-exit' import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../src/main/orcad/orcad-daemon-session-client-fixture' +} from '../../src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' import { expect, test } from './helpers/orca-app' import { resolveElectronExecutable } from './helpers/daemon-generation-runtime-fixture' import { @@ -19,12 +19,7 @@ import { type HeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { - cliServeProfile, - isPidAlive, - spawnUntilReady, - startCliServe -} from './helpers/orca-serve-cli-host' +import { cliServeProfile, isPidAlive, spawnUntilReady } from './helpers/orca-serve-cli-host' const RUN = process.env.ORCA_E2E_ORCAD_SERVE === '1' const slotDir = path.resolve('out/orcad') @@ -237,34 +232,3 @@ test('each serve host refuses a profile the other holds', async () => { await host.dispose() } }) - -/** Which host holds the profile: both take `orcad.lock`, each under its own role. */ -function profileLockRole(userDataDir: string): unknown { - return JSON.parse(readFileSync(path.join(userDataDir, 'orcad.lock'), 'utf8')).role -} - -// Needs out/orcad-template for this runner's target, as a packaged install carries. -test('`orca serve` runs on orcad by default and on Electron with ORCA_SERVE_RUNTIME=electron', async () => { - const profile = cliServeProfile(scratch) - try { - const byDefault = await startCliServe(profile) - try { - expect(byDefault.stderr()).toContain('[serve] running on orcad') - expect(byDefault.readiness.health).toBeDefined() - expect(profileLockRole(profile.userDataDir)).toBe('orcad') - } finally { - await byDefault.stop() - } - - // Electron serve publishes no build-health block yet, which is what tells the two apart. - const electron = await startCliServe(profile, { ORCA_SERVE_RUNTIME: 'electron' }) - try { - expect(electron.stderr()).not.toContain('[serve] running on orcad') - expect(electron.readiness.health).toBeUndefined() - } finally { - await electron.stop() - } - } finally { - await cleanupE2EDaemons(profile.userDataDir) - } -}) diff --git a/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts b/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts index 64fdceff665..163a508e11c 100644 --- a/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts +++ b/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts @@ -8,7 +8,7 @@ import path from 'node:path' import type { ElectronApplication } from '@stablyai/playwright-test' import { runProcess } from '@orca/process-host' import { RuntimeClient } from '../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/orcad-bundled-runtime' +import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' import { expect, test } from './helpers/orca-app' import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' import { cliServeProfile, spawnUntilReady } from './helpers/orca-serve-cli-host' diff --git a/tests/e2e/paired-host-usage-credentials.spec.ts b/tests/e2e/paired-host-usage-credentials.spec.ts index 6d4a8d3103d..807ce6a5113 100644 --- a/tests/e2e/paired-host-usage-credentials.spec.ts +++ b/tests/e2e/paired-host-usage-credentials.spec.ts @@ -5,7 +5,7 @@ import os from 'node:os' import path from 'node:path' import type { Page, TestInfo } from '@stablyai/playwright-test' import { RuntimeClient } from '../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/orcad-bundled-runtime' +import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' import { expect, test } from './helpers/orca-app' import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' import { cliServeProfile, spawnUntilReady } from './helpers/orca-serve-cli-host' From 3265616c56882358cb09c911cac29bbc719151b2 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 12 Nov 2026 13:55:06 -0800 Subject: [PATCH 16/44] test: prune low-value plugin artifact and contribution tests (#41663) * test: prune low-value theme and icon artifact samples * test: remove plugin syntax limits and contribution inventories --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 1 - .../plugin-icon-theme-artifact.test.ts | 49 ------------- .../artifacts/plugin-syntax-artifact.test.ts | 12 ---- .../artifacts/plugin-theme-artifact.test.ts | 54 -------------- .../plugin-content-pack-contributions.test.ts | 71 +------------------ ...lugin-status-bar-item-contribution.test.ts | 48 ------------- 6 files changed, 1 insertion(+), 234 deletions(-) delete mode 100644 src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 8dc28274407..4acdd0f4344 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6593,7 +6593,6 @@ "src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227, "src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238, "src/shared/plugins/contributions/plugin-panel-contribution.test.ts": 240, - "src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts": 232, "src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147, "src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198, "src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168, diff --git a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts index c51cab98b5a..62cae24915e 100644 --- a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { - isPlausiblePluginIconSvg, isPluginIconThemeRegistration, parsePluginIconThemeArtifact } from './plugin-icon-theme-artifact' @@ -16,28 +15,6 @@ describe('plugin icon theme artifacts', () => { parse({ schemaVersion: 1, folderNames, folderNamesExpanded: folderNames }) ).toThrow(/mappings/) }) - - it.each([ - ['a case-only duplicate', { schemaVersion: 1, fileExtensions: { ts: 'a.svg', TS: 'b.svg' } }], - ['an unknown slot', { schemaVersion: 1, icons: { 'sidebar.search': 'a.svg' } }], - ['a path in a file name', { schemaVersion: 1, fileNames: { 'a/b': 'a.svg' } }], - ['a path in a folder name', { schemaVersion: 1, folderNames: { 'a\\b': 'a.svg' } }], - [ - 'a case-only duplicate folder', - { schemaVersion: 1, folderNamesExpanded: { src: 'a.svg', Src: 'b.svg' } } - ], - ['an escaping icon path', { schemaVersion: 1, icons: { file: '../a.svg' } }] - ])('rejects %s', (_label, value) => { - expect(() => parse(value)).toThrow() - }) - - it('skips unknown slots at runtime', () => { - expect( - parsePluginIconThemeArtifact( - JSON.stringify({ schemaVersion: 1, icons: { file: 'f.svg', 'sidebar.search': 'a.svg' } }) - ).icons - ).toEqual({ file: 'f.svg' }) - }) }) describe('plugin icon theme artifact prototype keys', () => { @@ -81,14 +58,6 @@ describe('isPluginIconThemeRegistration', () => { folderNamesExpanded: {} } - it.each([ - ['an index past the SVG list', { constructor: 1 }], - ['a negative index', { constructor: -1 }], - ['a fractional index', { constructor: 0.5 }] - ])('rejects %s', (_label, fileNames) => { - expect(isPluginIconThemeRegistration({ ...base, fileNames })).toBe(false) - }) - it('checks the range of an own __proto__ index too', () => { const fileNames = JSON.parse('{"__proto__":5}') expect(isPluginIconThemeRegistration({ ...base, fileNames })).toBe(false) @@ -96,22 +65,4 @@ describe('isPluginIconThemeRegistration', () => { isPluginIconThemeRegistration({ ...base, fileNames: JSON.parse('{"__proto__":0}') }) ).toBe(true) }) - - it('checks folder indexes too', () => { - expect( - isPluginIconThemeRegistration({ ...base, fileNames: {}, folderNamesExpanded: { src: 1 } }) - ).toBe(false) - }) -}) - -describe('isPlausiblePluginIconSvg', () => { - it.each([ - ['an SVG', '', true], - ['an XML declaration and comment first', '', true], - ['a DOCTYPE', '', false], - ['an entity declaration', '', false], - ['HTML', '', false] - ])('accepts %s: %s', (_label, svg, expected) => { - expect(isPlausiblePluginIconSvg(svg)).toBe(expected) - }) }) diff --git a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts index a9c3c0e398c..315f42a7dc2 100644 --- a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts @@ -11,18 +11,6 @@ function grammar(scopeName: string, body: Record = {}): string } describe('plugin syntax artifacts', () => { - it('refuses oversized and deeply nested grammars', () => { - const huge = grammar('source.demo', { comment: 'x'.repeat(1024 * 1024) }) - expect(() => parsePluginGrammarArtifact(huge, 'source.demo')).toThrow('exceeds') - let nested: Record = { match: 'a' } - for (let depth = 0; depth < 80; depth += 1) { - nested = { patterns: [nested] } - } - expect(() => - parsePluginGrammarArtifact(grammar('source.demo', { patterns: [nested] }), 'source.demo') - ).toThrow('nested too deeply') - }) - it('requires includes inside the plugin to resolve and lets outside scopes degrade', () => { const main = parsePluginGrammarArtifact( grammar('source.demo', { diff --git a/src/shared/plugins/artifacts/plugin-theme-artifact.test.ts b/src/shared/plugins/artifacts/plugin-theme-artifact.test.ts index 2f3c0531b6c..e9363925381 100644 --- a/src/shared/plugins/artifacts/plugin-theme-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-theme-artifact.test.ts @@ -1,39 +1,10 @@ import { describe, expect, it } from 'vitest' import { parsePluginAppThemeArtifact } from './plugin-theme-artifact' -import { parsePluginTerminalThemeArtifact } from './plugin-terminal-theme-artifact' const parseApp = (value: unknown) => () => parsePluginAppThemeArtifact(JSON.stringify(value), 'strict') describe('plugin app theme artifacts', () => { - it.each([ - ['a private token', { base: 'dark', tokens: { '--internal-gap': '#000' } }], - ['a URL', { base: 'dark', tokens: { '--background': 'url(x)' } }], - ['a var() chain', { base: 'dark', tokens: { '--background': 'var(--a)' } }], - ['declaration syntax', { base: 'dark', tokens: { '--background': '#000; color: red' } }], - ['no tokens', { base: 'dark', tokens: {} }], - [ - 'transparent', - { base: 'dark', tokens: { '--background': 'transparent', '--foreground': '#fff' } } - ], - ['an unknown key', { base: 'dark', tokens: { '--border': '#000' }, extra: 1 }] - ])('rejects %s', (_label, value) => { - expect(parseApp(value)).toThrow() - }) - - it('skips unknown tokens and keys at runtime so newer themes still load', () => { - const theme = parsePluginAppThemeArtifact( - JSON.stringify({ - schemaVersion: 1, - base: 'dark', - tokens: { '--background': '#000', '--foreground': '#fff', '--future': '#123' }, - future: true - }) - ) - expect(theme.tokens).not.toHaveProperty('--future') - expect(parseApp({ schemaVersion: 2, base: 'dark', tokens: {} })).toThrow() - }) - it('reads a background image, strict for authors and never fatal at runtime', () => { const base = { base: 'dark', tokens: { '--background': '#000', '--foreground': '#fff' } } const background = { path: 'images/dusk.webp', opacity: 0.35, size: 'tile' } @@ -73,28 +44,3 @@ describe('plugin app theme artifacts', () => { ).toEqual([{ scope: ['keyword'], settings: { foreground: '#ff79c6' } }]) }) }) - -describe('plugin terminal theme artifacts', () => { - const terminal = { background: '#000000', foreground: '#ffffff', green: '#00ff00' } - - it('skips unknown slots at runtime', () => { - expect( - parsePluginTerminalThemeArtifact( - JSON.stringify({ schemaVersion: 1, terminal: { ...terminal, glow: '#000000' } }) - ) - ).toEqual({ mode: 'unknown', terminal }) - }) - - it.each([ - ['an unknown slot', { ...terminal, glow: '#000000' }], - ['an invalid color', { ...terminal, red: 'red; x' }], - ['no ANSI color', { background: '#000000', foreground: '#ffffff' }] - ])('rejects %s', (_label, colors) => { - expect(() => - parsePluginTerminalThemeArtifact( - JSON.stringify({ schemaVersion: 1, terminal: colors }), - 'strict' - ) - ).toThrow() - }) -}) diff --git a/src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts b/src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts index c972e4b38a1..25641d2f847 100644 --- a/src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts +++ b/src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parsePluginManifest, pluginManifestSchema } from '../manifest/plugin-manifest' +import { pluginManifestSchema } from '../manifest/plugin-manifest' function manifest(contributes: Record): Record { return { @@ -16,75 +16,6 @@ function manifest(contributes: Record): Record } describe('content-pack manifest contributions', () => { - it('still requires a worker entry for non-alias commands', () => { - expect( - parsePluginManifest( - manifest({ commands: [{ id: 'content-pack.run', title: 'Run content pack' }] }) - ) - ).toMatchObject({ ok: false, error: expect.stringContaining('worker command') }) - }) - - it.each([ - [ - 'unknown alias target', - { - commands: [{ id: 'open', title: 'Open', action: 'missing.action' }] - }, - 'unknown built-in action' - ], - [ - 'unknown command reference', - { keybindings: [{ command: 'missing', key: 'Mod+K' }] }, - 'unknown contributed command' - ], - [ - 'invalid chord', - { - commands: [{ id: 'open', title: 'Open', action: 'view.tasks' }], - keybindings: [{ command: 'open', key: 'Mod+NotAKey' }] - }, - 'key' - ], - [ - 'global binding for a worktree command', - { - commands: [{ id: 'open', title: 'Open', context: 'workspace', action: 'view.tasks' }], - keybindings: [{ command: 'open', key: 'Mod+K', when: 'global' }] - }, - "command's when" - ], - [ - 'platform-equivalent duplicate chords', - { - commands: [ - { id: 'first', title: 'First', action: 'view.tasks' }, - { id: 'second', title: 'Second', action: 'sidebar.left.toggle' } - ], - keybindings: [ - { command: 'first', key: 'Mod+K' }, - { command: 'second', key: 'Ctrl+K' } - ] - }, - 'duplicate keybinding' - ] - ])('rejects %s', (_label, contributes, error) => { - expect(parsePluginManifest(manifest(contributes))).toMatchObject({ - ok: false, - error: expect.stringContaining(error) - }) - }) - - it.each([ - ['language pack', { languagePacks: [{ locale: 'en_US', path: 'locale.json' }] }], - // Shape-legal but ill-formed: the regex alone let these load with dates falling back to English. - ['duplicate region', { languagePacks: [{ locale: 'en-US-US', path: 'locale.json' }] }], - ['unknown subtag', { languagePacks: [{ locale: 'en-aaa', path: 'locale.json' }] }], - ['language pack path', { languagePacks: [{ locale: 'pt-BR', path: '../outside.json' }] }], - ['VM recipe', { vmRecipes: [{ path: '\\\\server\\recipe.json' }] }] - ])('rejects unsafe or malformed %s contributions', (_label, contributes) => { - expect(parsePluginManifest(manifest(contributes)).ok).toBe(false) - }) - it('rejects duplicate ids, locales, paths, and bindings', () => { const parsed = pluginManifestSchema.safeParse( manifest({ diff --git a/src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts b/src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts deleted file mode 100644 index 46d8e49d6f3..00000000000 --- a/src/shared/plugins/contributions/plugin-status-bar-item-contribution.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parsePluginManifest } from '../manifest/plugin-manifest' -import { - buildPluginApprovalRequest, - formatPluginApprovalMessage -} from '../approval/plugin-cli-approval' - -function manifest(statusBarItems: unknown[], engines = '>=1.4.248') { - return { - manifestVersion: 2, - execution: 'declarative', - id: 'status-demo', - name: 'Status demo', - version: '1.0.0', - engines: { orca: engines }, - contributes: { - commands: [{ id: 'demo.tasks', title: 'Open tasks', action: 'view.tasks' }], - statusBarItems - } - } -} - -describe('contributes.statusBarItems', () => { - it('lists items in the dev-load and inspect approval, and binds the fingerprint to them', () => { - const subject = (items: unknown[]) => { - const parsed = parsePluginManifest(manifest(items)) - if (!parsed.ok) { - throw new Error(parsed.error) - } - return { - pluginKey: 'dev:status-demo', - manifest: parsed.manifest, - consentFingerprint: 'c', - contentIdentity: 'h', - isDev: true - } - } - const request = buildPluginApprovalRequest( - subject([{ id: 'tasks', text: '3 open' }]), - 'dev-load' - ) - expect(formatPluginApprovalMessage(request)).toContain('statusBarItems "3 open"') - expect( - buildPluginApprovalRequest(subject([{ id: 'tasks', text: '4 open' }]), 'dev-load') - .approvalFingerprint - ).not.toBe(request.approvalFingerprint) - }) -}) From e388a69394fad7af3b46bb13326328d9409f2de0 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Thu, 12 Nov 2026 14:07:58 -0800 Subject: [PATCH 17/44] test: remove low-value plugin policy and graph GC suites (#41675) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../scripts/ci/sharding/ci-shard-timings.json | 2 - .../git-graph/git-graph-rendering.test.tsx | 214 ------------------ .../catalog/plugin-repository-link.test.ts | 23 +- .../plugin-panel-contribution.test.ts | 29 --- .../images/plugin-image-format.test.ts | 10 - .../installation/plugin-path-safety.test.ts | 30 --- .../manifest/plugin-display-text.test.ts | 14 +- .../plugins/media/plugin-video-format.test.ts | 15 -- 8 files changed, 2 insertions(+), 335 deletions(-) delete mode 100644 src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx delete mode 100644 src/shared/plugins/contributions/plugin-panel-contribution.test.ts delete mode 100644 src/shared/plugins/installation/plugin-path-safety.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 4acdd0f4344..0595cbe5a2a 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6592,7 +6592,6 @@ "src/shared/plugins/contributions/plugin-command-replaces.test.ts": 230, "src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227, "src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238, - "src/shared/plugins/contributions/plugin-panel-contribution.test.ts": 240, "src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147, "src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198, "src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168, @@ -6616,7 +6615,6 @@ "src/shared/plugins/images/plugin-image-format.test.ts": 104, "src/shared/plugins/images/plugin-image-url.test.ts": 42, "src/shared/plugins/installation/plugin-file-validation.test.ts": 363, - "src/shared/plugins/installation/plugin-path-safety.test.ts": 221, "src/shared/plugins/manifest/plugin-display-text.test.ts": 285, "src/shared/plugins/manifest/plugin-manifest-source-module-floor.test.ts": 212, "src/shared/plugins/manifest/plugin-manifest-v2-rules.test.ts": 239, diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx deleted file mode 100644 index e37dc484d94..00000000000 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ /dev/null @@ -1,214 +0,0 @@ -import { workspaceId, local, repo } from './git-graph-workspace.test-fixtures' -// @vitest-environment happy-dom -import { useAppStore } from '@/store' -import { gitGraphHistoryForTab, disposeGitGraphHistory } from './git-graph-tab-controllers' - -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { GitGraphTab } from './git-graph-tab' -import * as graphSvg from '@/components/right-sidebar/source-control/sync/git-history-graph-svg' -import type { GitHistoryResult } from '../../../../../shared/git/history/git-history-types' - -const { getHistory, getRefs, viewport } = vi.hoisted(() => ({ - getHistory: vi.fn(), - getRefs: vi.fn(), - viewport: { rows: 20 } -})) -vi.mock('@/runtime/source-control/git/runtime-git-status-client', async (original) => ({ - ...(await original()), - getRuntimeGitHistory: getHistory, - getRuntimeGitRefs: getRefs -})) -vi.mock('@/runtime/source-control/git/runtime-git-diff-client', async (original) => ({ - ...(await original()), - getRuntimeGitCommitCompare: vi.fn(async () => ({ summary: { status: 'ready' }, entries: [] })) -})) -const container = document.createElement('div') -document.body.appendChild(container) -let root = createRoot(container) -let resize: (() => void) | undefined -const initialState = useAppStore.getState() -beforeEach(() => { - vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation( - () => viewport.rows * 24 - ) - vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(function ( - this: HTMLElement - ) { - return ( - Number.parseFloat( - this.firstElementChild?.getAttribute('style')?.match(/height: ([\d.]+)px/)?.[1] ?? '0' - ) + 48 - ) - }) - vi.stubGlobal( - 'ResizeObserver', - class { - constructor(private readonly callback: () => void) { - resize = callback - } - observe() {} - disconnect() { - if (resize === this.callback) { - resize = undefined - } - } - unobserve() {} - } - ) - useAppStore.setState({ - repos: [repo], - worktreesByRepo: { r: [local] }, - activeWorktreeId: workspaceId, - activeWorkspaceExecutionHostId: 'local', - gitGraphFiltersByWorktree: {} - }) -}) -afterEach(async () => { - await act(async () => root.unmount()) - root = createRoot(container) - viewport.rows = 20 - disposeGitGraphHistory(`${workspaceId}::git-graph`) - useAppStore.setState(initialState, true) - vi.restoreAllMocks() -}) -const result: GitHistoryResult = { - items: [{ id: 'a', subject: 'subject', message: 'subject', parentIds: [] }], - hasMore: false, - hasIncomingChanges: false, - hasOutgoingChanges: false, - limit: 50 -} - -const renderTab = () => - act(async () => - root.render( - - - - ) - ) -const loadedCount = () => gitGraphHistoryForTab(workspaceId).view.getState().result?.items.length - -it('releases replaced history while the pane stays mounted', async () => { - const count = 500_000 - viewport.rows = 40 - const renderedGraph = vi.spyOn(graphSvg, 'GitHistoryGraphSvg') - getHistory - .mockReset() - .mockImplementationOnce(async () => ({ - ...result, - refs: 'all', - hasMore: true, - items: Array.from({ length: count }, (_, index) => ({ - id: `old-${index}`, - subject: `Old ${index}`, - message: `Old ${index}`, - parentIds: [] - })) - })) - .mockRejectedValueOnce(new Error('network down')) - .mockResolvedValue({ ...result, refs: 'head' }) - await renderTab() - await act(async () => { - const scroll = container.querySelector('div.overflow-y-auto')! - scroll.scrollTop = (count - 40) * 24 - scroll.dispatchEvent(new Event('scroll')) - }) - expect(getHistory).toHaveBeenCalledTimes(2) - expect(container.textContent).toContain('network down') - const replaced = (() => { - const loaded = gitGraphHistoryForTab(workspaceId).view.getState().result! - expect(loaded.items).toHaveLength(count) - return [ - new WeakRef(renderedGraph.mock.calls[0]![0].viewModel), - new WeakRef(loaded), - new WeakRef(loaded.items), - new WeakRef(loaded.items[count - 1]!) - ] - })() - await act(async () => - useAppStore.setState({ gitGraphFiltersByWorktree: { [workspaceId]: 'head' } }) - ) - await act(async () => { - await gitGraphHistoryForTab(workspaceId).settledResult() - }) - expect(loadedCount()).toBe(1) - getHistory.mockReset() - renderedGraph.mockClear() - await expectReleased(replaced) - let controller = gitGraphHistoryForTab(workspaceId) - const loadDisposable = async () => { - getHistory.mockImplementationOnce(async () => ({ - ...result, - items: [{ id: 'disposable', subject: 'Disposable', message: 'Body', parentIds: [] }] - })) - await act(async () => { - await controller.refresh() - }) - const payload = controller.view.getState().result!.items[0]! - const row = renderedGraph.mock.calls.find( - ([props]) => props.viewModel.historyItem.id === 'disposable' - )![0].viewModel - const weak = [new WeakRef(payload), new WeakRef(row)] - getHistory.mockReset() - renderedGraph.mockClear() - return weak - } - const empty = await loadDisposable() - getHistory.mockResolvedValueOnce({ ...result, items: [] }) - await act(async () => { - await controller.refresh() - }) - // A normal refresh commits past React's previous-render snapshot. - getHistory.mockRejectedValueOnce(new Error('Empty refresh failed')) - await act(async () => { - await controller.refresh() - }) - expect(container.textContent).toContain('Empty refresh failed') - expect(loadedCount()).toBe(0) - getHistory.mockReset() - renderedGraph.mockClear() - await expectReleased(empty) - const missing = await loadDisposable() - getHistory.mockRejectedValueOnce(new Error('failed filter')) - await act(async () => - useAppStore.setState({ gitGraphFiltersByWorktree: { [workspaceId]: 'all' } }) - ) - await act(async () => { - await controller.settledResult() - }) - expect(loadedCount()).toBeUndefined() - getHistory.mockRejectedValueOnce(new Error('Missing refresh failed')) - await act(async () => { - await controller.refresh() - }) - expect(container.textContent).toContain('Missing refresh failed') - expect(loadedCount()).toBeUndefined() - getHistory.mockReset() - renderedGraph.mockClear() - await expectReleased(missing) - const unmounted = await loadDisposable() - await act(async () => { - disposeGitGraphHistory(`${workspaceId}::git-graph`) - root.unmount() - }) - root = createRoot(container) - controller = gitGraphHistoryForTab(workspaceId) - await expectReleased(unmounted) -}) - -async function expectReleased(obsolete: WeakRef[]) { - if (typeof globalThis.gc !== 'function') { - throw new Error('Run with the repository Vitest --expose-gc config') - } - for (let round = 0; round < 3; round++) { - await new Promise((resolve) => setImmediate(resolve)) - globalThis.gc() - } - for (const value of obsolete) { - expect(value.deref()).toBeUndefined() - } -} diff --git a/src/shared/plugins/catalog/plugin-repository-link.test.ts b/src/shared/plugins/catalog/plugin-repository-link.test.ts index de8d6d9259a..5e80cc0e849 100644 --- a/src/shared/plugins/catalog/plugin-repository-link.test.ts +++ b/src/shared/plugins/catalog/plugin-repository-link.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { pluginListingRepositoryUrl, pluginRepositoryPageUrl } from './plugin-repository-link' +import { pluginRepositoryPageUrl } from './plugin-repository-link' describe('pluginRepositoryPageUrl', () => { it('drops credentials, ports, queries and fragments from the URL it was given', () => { @@ -8,24 +8,3 @@ describe('pluginRepositoryPageUrl', () => { ) }) }) - -describe('pluginListingRepositoryUrl', () => { - const mirror = { url: 'https://github.com/stablyai/orca-community-mirror.git' } - - it("never links a recorded repository outside the publisher's namespace or linkable hosts", () => { - for (const repository of [ - 'https://github.com/someone-else/notes', - 'https://evil.example/acme/notes', - 'https://github.com/acme/%2e%2e' - ]) { - expect( - pluginListingRepositoryUrl({ - pluginKey: 'acme.notes', - source: mirror, - release: { repository } - }) - ).toBe(mirror.url) - } - expect(pluginListingRepositoryUrl({ pluginKey: 'acme.notes', source: mirror })).toBe(mirror.url) - }) -}) diff --git a/src/shared/plugins/contributions/plugin-panel-contribution.test.ts b/src/shared/plugins/contributions/plugin-panel-contribution.test.ts deleted file mode 100644 index bedaace271b..00000000000 --- a/src/shared/plugins/contributions/plugin-panel-contribution.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parsePluginManifest } from '../manifest/plugin-manifest' - -const panel = { id: 'board', title: 'Board' } - -function manifest(engine: string, panelFields: Record) { - return { - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'board', - publisher: 'acme', - name: 'Board', - version: '1.0.0', - engines: { orca: engine }, - pluginApi: 1, - contributes: { panels: [{ ...panel, entry: 'panel.js', ...panelFields }] } - } -} - -describe('panel ui', () => { - it('makes authors declare the release that reads ui and the newer icons', () => { - expect(parsePluginManifest(manifest('>=1.4.245', { ui: 'components' })).ok).toBe(false) - expect(parsePluginManifest(manifest('>=1.4.245', { icon: 'add' })).ok).toBe(false) - expect(parsePluginManifest(manifest('>=1.4.245', { icon: 'rocket' })).ok).toBe(true) - expect(parsePluginManifest(manifest('>=1.4.246', { ui: 'components', icon: 'add' })).ok).toBe( - true - ) - }) -}) diff --git a/src/shared/plugins/images/plugin-image-format.test.ts b/src/shared/plugins/images/plugin-image-format.test.ts index d93dfe96b98..a5245ae2d1e 100644 --- a/src/shared/plugins/images/plugin-image-format.test.ts +++ b/src/shared/plugins/images/plugin-image-format.test.ts @@ -107,14 +107,4 @@ describe('readPluginImageHeader', () => { height: 800 }) }) - - it('refuses animation, other formats and oversized frames', () => { - expect(readPluginImageHeader(pngBytes(512, 512, true))).toBe('animated images are not allowed') - expect(readPluginImageHeader(webpVp8x(512, 512, 0x02))).toBe('animated images are not allowed') - expect(readPluginImageHeader(Buffer.from(''))).toBe( - 'must be a PNG, JPEG or WebP image' - ) - expect(readPluginImageHeader(Buffer.from('GIF89a'))).toBe('must be a PNG, JPEG or WebP image') - expect(readPluginImageHeader(pngBytes(5000, 100))).toBe('image is larger than 4096×4096') - }) }) diff --git a/src/shared/plugins/installation/plugin-path-safety.test.ts b/src/shared/plugins/installation/plugin-path-safety.test.ts deleted file mode 100644 index ad104c4ef73..00000000000 --- a/src/shared/plugins/installation/plugin-path-safety.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parsePluginManifest } from '../manifest/plugin-manifest' - -describe('plugin path portability', () => { - it('applies portable path validation to every declared artifact kind', () => { - const base = { - manifestVersion: 1, - id: 'demo', - publisher: 'samples', - name: 'Demo', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: { panels: [], commands: [], events: [] }, - capabilities: [] - } - - expect(parsePluginManifest({ ...base, icon: 'assets/NUL.svg' }).ok).toBe(false) - expect(parsePluginManifest({ ...base, main: 'dist/worker.js.' }).ok).toBe(false) - expect( - parsePluginManifest({ - ...base, - contributes: { - ...base.contributes, - panels: [{ id: 'panel', title: 'Panel', entry: 'dist/panel.html:ads' }] - } - }).ok - ).toBe(false) - }) -}) diff --git a/src/shared/plugins/manifest/plugin-display-text.test.ts b/src/shared/plugins/manifest/plugin-display-text.test.ts index bd52635c6f3..81c595075a0 100644 --- a/src/shared/plugins/manifest/plugin-display-text.test.ts +++ b/src/shared/plugins/manifest/plugin-display-text.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { validatePluginFile } from '../installation/plugin-file-validation' import { pluginCatalogEntrySchema } from '../catalog/plugin-catalog' -import { parseHostPluginManifest, parsePluginManifest } from './plugin-manifest' +import { parseHostPluginManifest } from './plugin-manifest' import { catalogEntryFixture, catalogFixture, @@ -27,18 +27,6 @@ describe('plugin display text', () => { }) }) - it('refuses unsafe characters in validate:plugin instead of stripping them', () => { - expect(parsePluginManifest(themed(SPOOFED_NAME, 'Dusk'))).toEqual({ - ok: false, - error: expect.stringContaining( - 'name: must be one line without control, bidirectional or zero-width characters;' - ) - }) - expect(validatePluginFile('orca-plugin.json', themed('Dusk', 'Dusk\u2066'))).toEqual([ - 'description: must be one line without control, bidirectional or zero-width characters; contributes.themes[0].title: must be one line without control, bidirectional or zero-width characters' - ]) - }) - it('strips catalog listing text at runtime and refuses it in catalog CI', () => { const entry = catalogEntryFixture({ description: 'Gleam\u202e' }, { name: 'Gleam\u200b' }) expect(pluginCatalogEntrySchema.parse(entry)).toMatchObject({ diff --git a/src/shared/plugins/media/plugin-video-format.test.ts b/src/shared/plugins/media/plugin-video-format.test.ts index 004d8750be2..dc91ecdec19 100644 --- a/src/shared/plugins/media/plugin-video-format.test.ts +++ b/src/shared/plugins/media/plugin-video-format.test.ts @@ -99,21 +99,6 @@ describe('readPluginVideoHeader', () => { }) }) - it('refuses images, audio, extra tracks and missing or negative lengths', () => { - const oneTrack = 'video must have exactly one track, a video track with no audio' - expect(readPluginVideoHeader(Buffer.from('\x89PNG\r\n\x1a\n'))).toBe( - 'must be an MP4 or WebM video' - ) - const video = mp4Track('vide', 'avc1', 960, 540) - const audio = mp4Track('soun', 'mp4a', 0, 0) - expect(readPluginVideoHeader(mp4([audio]))).toBe(oneTrack) - expect(readPluginVideoHeader(mp4([audio, video]))).toBe(oneTrack) - expect(readPluginVideoHeader(mp4([video, video]))).toBe(oneTrack) - expect(readPluginVideoHeader(webm('V_VP9', 960, 540, 1000, true))).toBe(oneTrack) - expect(readPluginVideoHeader(webm('V_VP9', 960, 540))).toBe('video has no duration') - expect(readPluginVideoHeader(webm('V_VP9', 960, 540, -5000))).toBe('video has no duration') - }) - it('stops on hostile structure instead of recursing or reading past the end', () => { let nested = box('mdia') for (let depth = 0; depth < 5000; depth++) { From f543fcd0b7a47cd4a21c992833167ed3efd68923 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:12:06 -0800 Subject: [PATCH 18/44] perf(renderer): drop the mobile-driver overlay's backdrop blur (#41557) * perf(renderer): paint modal backdrops, sticky headers and pane overlays solid instead of blurring Dialogs, palettes and sheets blurred the whole workspace, and sticky headers, pinned bars, the mobile-driver scrim and markdown table controls re-blurred whatever scrolled or changed beneath them. The workspace now stays sharp under the existing dim with a solid dialog panel at today's color, and each sticky or pinned bar paints the opaque equivalent of its tint over the surface it sits on. Reduce Visual Effects keeps its behavior; the CSS-value-only blur e2e spec is removed and its onboarding recovery test moves to the onboarding spec. Co-Authored-By: Claude Opus 5.5 (1M context) * test(fixtures): describe the sheet fixture's dimmed, unblurred workspace Co-Authored-By: Claude Opus 5.5 (1M context) * perf(renderer): narrow to the mobile-driver overlay; keep every other blur as on main Brennan 11-12 kept modal blur, and only the mobile-driver overlay met its measurement rule. Restore every other surface, the e2e blur spec and the fixture copy to the synced base. Co-Authored-By: Claude Opus 5.5 (1M context) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- .../browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx index b6c7dc55355..e2d1aa9d056 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserMobileDriverOverlay.tsx @@ -59,7 +59,7 @@ export function BrowserMobileDriverOverlay({ driver, onTakeBack }: Props): React aria-labelledby={OVERLAY_TITLE_ID} aria-live="assertive" className={cn( - 'pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-background/80 p-6 backdrop-blur-sm', + 'pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-background/80 p-6', 'mobile-browser-driver-banner' )} > From 3586fdc055830ffc8b897866ee313af0588c18df Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:18:24 -0800 Subject: [PATCH 19/44] fix(terminal): capture replay snapshots at one output position (#41247) Capture the terminal screen, output position and unfinished parser state together on the existing output queue so restored output continues at the correct byte. Retire reconstructed partial escape state on Reset. Tracked in #34435 and STA-12466. Co-authored-by: liaoxingyu <3114147163@qq.com> --- .../output/headless-buffer-snapshot.ts | 81 ++++++++++------- .../headless-snapshot-stream-position.test.ts | 86 +++++++++++++++++++ .../output/headless-terminal-state.ts | 1 + 3 files changed, 136 insertions(+), 32 deletions(-) create mode 100644 src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts diff --git a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts index df00b995cb2..6f49d1bc0ea 100644 --- a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts +++ b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts @@ -50,38 +50,55 @@ export abstract class OrcaRuntimeWithSerializeHeadlessTerminalBuffer extends Orc } await state.writeChain await state.ownership.settle() - // Why: normal history is separated from an active alternate frame, so the - // caller's scrollback policy can be honored without painting it into alt. - const scrollbackRows = opts.scrollbackRows ?? 0 - const snapshot = state.emulator.getSnapshot({ scrollbackRows }) - const terminalOwner = state.ownership.owner - const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi - return data.length > 0 || opts.includeEmpty === true - ? this.preferTrackedLastTitle(ptyId, { - data, - frameRestoreAnsi: snapshot.frameRestoreAnsi, - cols: snapshot.cols, - rows: snapshot.rows, - cwd: snapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), - lastTitle: snapshot.lastTitle, - seq: state.outputSequence, - source: 'headless' as const, - oscLinks: snapshot.oscLinks, - scrollbackAnsi: snapshot.scrollbackAnsi, - // Capture flags at the image's stream position to prevent duplicate/out-of-order replay pushes and pops. - ...(parseTerminalKittyKeyboardFlags(snapshot.modes?.kittyKeyboardFlags) !== undefined - ? { kittyKeyboardFlags: snapshot.modes.kittyKeyboardFlags } - : {}), - ...(snapshot.pendingEscapeTailAnsi - ? { pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi } - : {}), - ...(terminalOwner ? { terminalOwner } : {}), - // Alt snapshots must preserve xterm history used for TUI scroll-up after tab return. - alternateScreen: snapshot.modes?.alternateScreen ?? state.emulator.isAlternateScreen, - // Do not fold into data: the restorer's later reset would abort this partial escape. - pendingEscapeTailAnsi: snapshot.pendingEscapeTailAnsi - }) - : null + // Capture image and applied progress in the same ordered operation as parsing. + const completion = state.writeChain.then(() => { + const current = + this.headlessTerminals.get(ptyId) ?? + (this.ptysById.get(ptyId)?.connected === true + ? undefined + : this.headlessExitHolds.get(ptyId)?.exited) + if (current !== state) { + return null + } + // Why: normal history is separated from an active alternate frame, so the + // caller's scrollback policy can be honored without painting it into alt. + const scrollbackRows = opts.scrollbackRows ?? 0 + const snapshot = state.emulator.getSnapshot({ scrollbackRows }) + const terminalOwner = state.ownership.owner + const pendingEscapeTailAnsi = + state.rendererSeedSeq !== undefined + ? state.rendererSeedEscapeTail + : snapshot.pendingEscapeTailAnsi + const data = snapshot.rehydrateSequences + snapshot.snapshotAnsi + return data.length > 0 || opts.includeEmpty === true + ? this.preferTrackedLastTitle(ptyId, { + data, + frameRestoreAnsi: snapshot.frameRestoreAnsi, + cols: snapshot.cols, + rows: snapshot.rows, + cwd: snapshot.cwd ?? this.terminalCwdByPtyId.get(ptyId), + lastTitle: snapshot.lastTitle, + seq: state.outputSequence, + source: 'headless' as const, + oscLinks: snapshot.oscLinks, + scrollbackAnsi: snapshot.scrollbackAnsi, + // Capture flags at the image's stream position to prevent duplicate/out-of-order replay pushes and pops. + ...(parseTerminalKittyKeyboardFlags(snapshot.modes?.kittyKeyboardFlags) !== undefined + ? { kittyKeyboardFlags: snapshot.modes.kittyKeyboardFlags } + : {}), + ...(terminalOwner ? { terminalOwner } : {}), + // Alt snapshots must preserve xterm history used for TUI scroll-up after tab return. + alternateScreen: snapshot.modes?.alternateScreen ?? state.emulator.isAlternateScreen, + // Do not fold into data: the restorer's later reset would abort this partial escape. + pendingEscapeTailAnsi + }) + : null + }) + state.writeChain = completion.then( + () => {}, + () => {} + ) + return completion } /** Keeps the PTY's model readable through its exit until released, so a stream mid-publication can still serialize it. */ diff --git a/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts b/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts new file mode 100644 index 00000000000..1b3f757e453 --- /dev/null +++ b/src/main/runtime/terminal/output/headless-snapshot-stream-position.test.ts @@ -0,0 +1,86 @@ +import { assert, expect, it } from 'vitest' +import { OrcaRuntimeService } from '../../orca-runtime' +import { HeadlessEmulator } from '../../../daemon/emulation/headless-emulator' + +const grid = { cols: 80, rows: 24 } +const partial = 'prompt\r\n> \x1b[?' + +function createRuntime() { + const runtime = new OrcaRuntimeService() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => grid + }) + return runtime +} + +async function replay( + snapshot: { data: string; pendingEscapeTailAnsi?: string } | null, + suffix: string +) { + assert(snapshot) + const restored = new HeadlessEmulator(grid) + try { + await restored.write(snapshot.data) + await restored.write(snapshot.pendingEscapeTailAnsi ?? '') + await restored.write(suffix) + return restored + .getVisibleLines() + .map((line) => line.trimEnd()) + .filter(Boolean) + } finally { + restored.dispose() + } +} + +it('restores a screen and live suffix without repainting a consumed escape continuation', async () => { + const runtime = createRuntime() + const continuation = '1002h\x1b[>4;2m' + try { + runtime.onPtyData('pty-snapshot', partial, 1) + const pending = runtime.serializeHiddenOutputRecoveryBuffer('pty-snapshot') + queueMicrotask(() => runtime.onPtyData('pty-snapshot', continuation, 2)) + const snapshot = await pending + expect(await replay(snapshot, (partial + continuation).slice(snapshot?.seq))).toEqual([ + 'prompt', + '>' + ]) + } finally { + await runtime.onPtyExit('pty-snapshot', 0) + } +}) + +it.each([false, true])( + 'preserves seeded parser state through replay and live output (reset=%s)', + async (reset) => { + const runtime = createRuntime() + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + getSize: () => grid, + hasRendererSerializer: () => true, + serializeBuffer: async () => ({ data: 'prompt\r\n> ', ...grid, seq: 13 }) + }) + try { + runtime.onPtyData('pty-seed', partial, 1) + let snapshot = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + expect(snapshot?.seq).toBe(13) + if (reset) { + await runtime.resetHeadlessTerminalInputModes('pty-seed') + snapshot = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + } + const continuation = reset ? 'hello' : '1002h' + const expected = reset ? ['prompt', '> hello'] : ['prompt', '>'] + expect(await replay(snapshot, continuation)).toEqual(expected) + + runtime.onPtyData('pty-seed', continuation, 2) + const live = await runtime.serializeHiddenOutputRecoveryBuffer('pty-seed') + expect(await replay(live, '')).toEqual(expected) + } finally { + await runtime.onPtyExit('pty-seed', 0) + } + } +) diff --git a/src/main/runtime/terminal/output/headless-terminal-state.ts b/src/main/runtime/terminal/output/headless-terminal-state.ts index 6df5db366d7..9ea360a80a1 100644 --- a/src/main/runtime/terminal/output/headless-terminal-state.ts +++ b/src/main/runtime/terminal/output/headless-terminal-state.ts @@ -269,6 +269,7 @@ export abstract class OrcaRuntimeWithCreatePtyHeadlessTerminalState extends Orca // Why on the chain: the ground must land after every PTY chunk already queued. const completion = state.writeChain.then(async () => { await state.emulator.write(state.ownership.groundInputModes()) + state.rendererSeedEscapeTail = undefined }) state.writeChain = completion.catch(() => {}) await completion From 8ed0d047db5fadd33b75540a605333b40105a136 Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:22:18 +0000 Subject: [PATCH 20/44] feat(computer): show where snapshots were cut and read one element's subtree (#41482) * feat(computer): show where snapshots were cut and read one element's subtree * fix(computer): validate subtree targets against the fresh walk and keep scope for focused input * fix(computer): return whole-window action results after subtree reads * fix(computer): count kept records toward the macOS limit and index subtree reads against the latest cache * fix(computer): index Linux/Windows subtree reads against the snapshot they started from --- docs/site/content/docs/cli/computer-use.mdx | 2 +- native/computer-use-linux/runtime.py | 35 ++- .../computer-use-linux/runtime_render_test.py | 20 ++ .../Sources/OrcaComputerUseMacOS/main.swift | 213 ++++++++++++------ native/computer-use-windows/runtime.ps1 | 39 ++-- skill-guides/orca-computer-use.md | 6 + src/cli/computer/computer-format.ts | 2 +- src/cli/computer/computer.ts | 15 +- src/cli/discovery/command-scoped-flag-help.ts | 2 + src/cli/skills/bundled-skill-guides.ts | 6 + src/cli/specs/computer.ts | 4 +- .../desktop-script-provider-client.ts | 9 + .../desktop-script-provider-types.ts | 4 + .../desktop-script-snapshot-rendering.ts | 6 + .../desktop-script-subtree-snapshot.test.ts | 72 ++++++ .../desktop-script-subtree-snapshot.ts | 103 +++++++++ src/shared/computer-use-runtime-types.ts | 2 + src/shared/computer-use-tree-text.ts | 10 + .../rpc-contract/computer-schemas-params.ts | 5 +- 19 files changed, 455 insertions(+), 100 deletions(-) create mode 100644 src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts create mode 100644 src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts diff --git a/docs/site/content/docs/cli/computer-use.mdx b/docs/site/content/docs/cli/computer-use.mdx index 4f6b8f31ae7..776ac5a21a2 100644 --- a/docs/site/content/docs/cli/computer-use.mdx +++ b/docs/site/content/docs/cli/computer-use.mdx @@ -37,7 +37,7 @@ orca computer click --app com.spotify.client --element-index 42 --json Element indexes are scoped to the latest `get-app-state` result and may be **sparse**. In `--json` output, read the tree from `result.snapshot.treeText`. Do not invent indexes from `elementCount`. Refresh state after navigation, focus changes, scrolling, or any app re-render before reusing an index. -Action results return only the accessibility-tree lines that changed since the last state for that window (`~` changed, `+` added, `-` removed), marked by `snapshot.treeDiff`; pass `--full-tree` to get the whole tree. To find one control in a large window, `get-app-state --query ` prints only matching elements and their ancestors, and `--max-elements ` caps the output. +Action results return only the accessibility-tree lines that changed since the last state for that window (`~` changed, `+` added, `-` removed), marked by `snapshot.treeDiff`; pass `--full-tree` to get the whole tree. To find one control in a large window, `get-app-state --query ` prints only matching elements and their ancestors, and `--max-elements ` caps the output. A window larger than the snapshot limit shows `... N more not shown (snapshot limit)` where the tree was cut; `get-app-state --element-index ` reads only that element's subtree, so pass the cut-off children's parent to see them. ## Waiting for the app diff --git a/native/computer-use-linux/runtime.py b/native/computer-use-linux/runtime.py index c81e3812534..5e5fa614185 100644 --- a/native/computer-use-linux/runtime.py +++ b/native/computer-use-linux/runtime.py @@ -487,13 +487,19 @@ def render_accessibility_tree(root, root_path, compact_browser_tabs=False, geome has_text = bool(item["name"] or item["automationId"] or item["value"]) return role in {"panel", "filler", "unknown", "section"} and not has_text and not meaningful_actions(item["actions"]) and summary is None and child_count <= 1 + def walk_children(child_items, depth, path): + for position, (child_index, child) in enumerate(child_items): + if len(records) >= MAX_NODES or depth > MAX_DEPTH: + truncation["truncated"] = True + if depth > MAX_DEPTH: + truncation["maxDepthReached"] = True + # Marks where the walk stopped, so the agent can read that parent's subtree by index. + lines.append(("\t" * depth) + f"... {len(child_items) - position} more not shown (snapshot limit)") + return + walk(child, depth, path + [child_index]) + def walk(node, depth, path): nonlocal next_index - if len(records) >= MAX_NODES or depth > MAX_DEPTH: - truncation["truncated"] = True - if depth > MAX_DEPTH: - truncation["maxDepthReached"] = True - return item = record(node, next_index, path) role_key = (item["controlType"] or "").lower() title = item["name"] or item["automationId"] or "" @@ -505,8 +511,7 @@ def render_accessibility_tree(root, root_path, compact_browser_tabs=False, geome if len(summary_values) >= 2 and is_plain_text_subtree(node): generic_summary = " ".join(summary_values) if should_elide(item, len(child_items), generic_summary): - for child_index, child in child_items: - walk(child, depth, path + [child_index]) + walk_children(child_items, depth, path) return records.append(item) next_index += 1 @@ -529,8 +534,7 @@ def render_accessibility_tree(root, root_path, compact_browser_tabs=False, geome if generic_summary or suppressed: return child_line_start = len(lines) - for child_index, child in child_items: - walk(child, depth + 1, path + [child_index]) + walk_children(child_items, depth + 1, path) if compact_browser_tabs: compact_rendered_browser_tabs(records, lines, child_line_start, depth + 1) @@ -1203,17 +1207,23 @@ def window_json(app, index, window): } -def make_snapshot(query, include_screenshot, window_id=None, window_index=None, restore=False): +def make_snapshot(query, include_screenshot, window_id=None, window_index=None, restore=False, root=None): app = find_app(query) window_index, window = choose_window(app, window_id, window_index) if restore: restore_window(app, window) window_index, window = choose_window(app, window_id, window_index) bounds = screen_rect(window) + tree_root, root_path = window, [window_index] + if root is not None: + tree_root = find_element(app, root) + if tree_root is None: + raise RuntimeError(f"stale element: element {root.get('index')} is gone; run get-app-state again and use a fresh element index") + root_path = list(root.get("runtimeId") or []) geometry_nodes = {} records, lines, truncation = render_accessibility_tree( - window, - [window_index], + tree_root, + root_path, compact_browser_tabs=is_browser_app(query, app), geometry_nodes=geometry_nodes, ) @@ -1875,6 +1885,7 @@ def run_operation(operation): operation.get("windowId"), operation.get("windowIndex"), bool(operation.get("restoreWindow")), + operation.get("root"), ), } diff --git a/native/computer-use-linux/runtime_render_test.py b/native/computer-use-linux/runtime_render_test.py index 6e997611596..207d2de3410 100644 --- a/native/computer-use-linux/runtime_render_test.py +++ b/native/computer-use-linux/runtime_render_test.py @@ -699,6 +699,26 @@ class RuntimeRenderTest(unittest.TestCase): indexes = [item["index"] for item in snapshot["elements"]] self.assertEqual(len(indexes), len(set(indexes))) + def test_cut_tree_marks_hidden_children_and_root_reads_them(self): + items = [FakeAccessible("button", f"A{i}") for i in range(3)] + root = FakeAccessible("frame", "Main", children=[ + FakeAccessible("list", "Items", children=items), FakeAccessible("button", "After"), + ]) + with SnapshotFixture(root), patch.object(runtime, "MAX_NODES", 4): + snapshot = runtime.make_snapshot("Fixture", False) + self.assertEqual(snapshot["treeLines"], [ + "0 frame Main", + "\t1 list Items", + "\t\t2 button A0", + "\t\t3 button A1", + "\t\t... 1 more not shown (snapshot limit)", + "\t... 1 more not shown (snapshot limit)", + ]) + items_record = next(item for item in snapshot["elements"] if item["name"] == "Items") + subtree = runtime.run_operation({"tool": "get_app_state", "app": "Fixture", "noScreenshot": True, "root": items_record})["snapshot"] + self.assertEqual(subtree["treeLines"], ["0 list Items", "\t1 button A0", "\t2 button A1", "\t3 button A2"]) + self.assertEqual(subtree["elements"][-1]["runtimeId"], [0, 0, 2]) + diff --git a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift index 9a43b296403..0027bea1f5a 100644 --- a/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOS/main.swift @@ -143,6 +143,12 @@ final class ElementRecord { } } +/// A snapshot that read one element's subtree; its elements also keep the window's earlier ones. +struct SnapshotScope { + let rootIndex: Int + let walkedIndexes: Set +} + struct Snapshot { let id: String let app: AppDescriptor @@ -161,6 +167,7 @@ struct Snapshot { let nextFreshElementIndex: Int let truncated: Bool let maxDepthReached: Bool + let scope: SnapshotScope? /// On-screen windows of the app (menus and sheets included), so a new or closed window counts as a change. let appWindowIds: [CGWindowID] @@ -187,6 +194,7 @@ struct Snapshot { nextFreshElementIndex: nextFreshElementIndex, truncated: truncated, maxDepthReached: maxDepthReached, + scope: scope, appWindowIds: appWindowIds ) } @@ -262,9 +270,10 @@ final class Provider { var action = try runAction() // Why: only --restore-window activates the app or posts to the HID tap; every other route leaves the user's desktop alone. action["delivery"] = isForegroundRequest(params) ? "foreground" : "background" - // Why: the action's currentSnapshot just cached this target's tree from before the action. + // Why: the action's currentSnapshot just cached this target's tree from before the action; + // a subtree read can't be compared with the whole-window read that follows. let before = action["path"] as? String == "accessibility" && action["verification"] == nil - ? try? cachedSnapshot(params: params) + ? (try? cachedSnapshot(params: params)).flatMap { $0.scope == nil ? $0 : nil } : nil do { let after = try observe(params: params) @@ -315,12 +324,14 @@ final class Provider { } let namespace = snapshotNamespace(params) pruneSnapshotCache() + let subtree = try requestedSubtree(params: params, app: app) let snapshot = try buildSnapshot( app: app, includeScreenshot: params["noScreenshot"]?.bool != true, - windowId: windowId, - windowIndex: windowIndex, + windowId: subtree.map(\.base.windowId) ?? windowId, + windowIndex: subtree == nil ? windowIndex : nil, restoreWindow: params["restoreWindow"]?.bool == true, + subtree: subtree, previousSnapshot: { [snapshots] resolvedWindowId in // Why: indexes carry over from this caller's own last view of exactly this window. snapshots[namespacedSnapshotKey(namespace, snapshotCanonicalWindowIdKey(resolvedWindowId))] @@ -339,6 +350,15 @@ final class Provider { return snapshot } + /// Resolves `rootElementIndex` against this caller's last snapshot of the window, whose indexes it extends. + private func requestedSubtree(params: [String: JSONValue], app: AppDescriptor) throws -> (root: ElementRecord, base: Snapshot)? { + guard let rootIndex = try optionalInteger(params, "rootElementIndex") else { return nil } + guard let base = try cachedSnapshot(params: params), base.app.pid == app.pid else { + throw ProviderError.coded("element_not_found", "--element-index needs a get-app-state snapshot of this app/window first") + } + return (try element(base, rootIndex), base) + } + private func rememberSnapshot( query: String, app: AppDescriptor, @@ -416,19 +436,30 @@ final class Provider { } } - private func currentSnapshot(params: [String: JSONValue]) throws -> Snapshot { + private func currentSnapshot(params: [String: JSONValue], needsFocus: Bool = false) throws -> Snapshot { pruneSnapshotCache() let cached = try cachedSnapshot(params: params) + let requestedIndexes = try requestedElementIndexes(params) + let observeParams = params.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement } + // Why: elements read with --element-index, focused ones included, may lie past the whole-window node limit, + // so only their subtree can re-find them. + if let scope = cached?.scope, + requestedIndexes.isEmpty ? needsFocus : requestedIndexes.allSatisfy(scope.walkedIndexes.contains), + let scoped = try? observe(params: observeParams.merging(["rootElementIndex": .number(Double(scope.rootIndex))]) { _, replacement in replacement }), + !requestedIndexes.isEmpty || scoped.focusedElementId != nil { + try validateRequestedElements(cached: cached, current: scoped, requestedIndexes: requestedIndexes) + return scoped + } // Why: cached AX frames can be stale after a window move or resize, and // stale geometry can turn an intended action into a misclick. - let snapshot = try observe(params: params.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement }) - try validateRequestedElements(cached: cached, current: snapshot, params: params) + let snapshot = try observe(params: observeParams) + try validateRequestedElements(cached: cached, current: snapshot, requestedIndexes: requestedIndexes) return snapshot } private func currentKeyboardSnapshot(params: [String: JSONValue]) throws -> Snapshot { // Why: keyboard actions need fresh focused-element state, never pixels. - try currentSnapshot(params: params.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement }) + try currentSnapshot(params: params.merging(["noScreenshot": .bool(true)]) { _, replacement in replacement }, needsFocus: true) } private func cachedSnapshot(params: [String: JSONValue]) throws -> Snapshot? { @@ -473,17 +504,24 @@ final class Provider { (isExplicitSnapshotNamespace(namespace) ? nil : snapshots[key]) } - private func validateRequestedElements(cached: Snapshot?, current: Snapshot, params: [String: JSONValue]) throws { - let requestedIndexes = try ["elementIndex", "fromElementIndex", "toElementIndex"].compactMap { key -> Int? in + private func requestedElementIndexes(_ params: [String: JSONValue]) throws -> [Int] { + try ["elementIndex", "fromElementIndex", "toElementIndex"].compactMap { key -> Int? in guard params[key]?.number != nil else { return nil } return try optionalInteger(params, key) } + } + + private func validateRequestedElements(cached: Snapshot?, current: Snapshot, requestedIndexes: [Int]) throws { guard !requestedIndexes.isEmpty else { return } guard let cached else { throw ProviderError.coded("element_not_found", "element indexes require a fresh get-app-state snapshot for this app/window") } for index in requestedIndexes { - guard let expected = cached.elements[index], let actual = current.elements[index] else { + // Why: a subtree read also carries the window's earlier records, which prove nothing about the element now. + guard let expected = cached.elements[index], + let actual = current.elements[index], + current.scope?.walkedIndexes.contains(index) ?? true + else { throw ProviderError.coded("element_not_found", "element \(index) is stale; run get-app-state again and use a fresh element index") } guard expected.signature == actual.signature else { @@ -658,6 +696,7 @@ final class Provider { windowId: CGWindowID?, windowIndex: Int?, restoreWindow: Bool, + subtree: (root: ElementRecord, base: Snapshot)?, previousSnapshot: (CGWindowID) -> Snapshot? ) throws -> Snapshot { guard accessibilityTrustedSettled() else { @@ -703,11 +742,29 @@ final class Provider { focused: focusedElement(appElement: appElement), compactBrowserTabs: app.isKnownBrowser ) - renderer.render(window) + if let subtree { + guard let ancestors = ancestorChain(of: subtree.root.element, in: window) else { + throw ProviderError.coded("element_not_found", "element \(subtree.root.index) is no longer in this window; run get-app-state again and use a fresh element index") + } + renderer.render(subtree.root.element, ancestors: ancestors) + } else { + renderer.render(window) + } if renderer.appStoppedResponding { throw AccessibilityMessaging.appNotResponding(app.name) } - let indexes = renderer.carryOverIndexes(from: previousSnapshot(capture.windowId)) + let previous = subtree?.base ?? previousSnapshot(capture.windowId) + let indexes = renderer.carryOverIndexes(from: previous) + var elements = renderer.records + var elementOrder = indexes.order + if let subtree { + // Why: elements outside the subtree keep resolving, so the agent can still act on what the whole-window read showed. + // Re-reading the same subtree replaces its last walk, so rows scrolled away don't pile up. + let replaced = subtree.base.scope.flatMap { $0.rootIndex == subtree.root.index ? $0.walkedIndexes : nil } ?? [] + let kept = subtree.base.elements.filter { !replaced.contains($0.key) && renderer.records[$0.key] == nil } + elements = kept.merging(renderer.records) { _, walked in walked } + elementOrder = subtree.base.elementOrder.filter { kept[$0] != nil } + indexes.order + } let screenshot = includeScreenshot ? capture.screenshotPayload() : nil let screenshotStatus: ScreenshotStatus = if screenshot != nil { .captured @@ -725,17 +782,18 @@ final class Provider { windowBounds: capture.bounds, windowId: capture.windowId, windowLayer: capture.layer, - treeText: renderTreeText(app: app, title: title, bounds: capture.bounds, lines: renderer.lines, focused: renderer.focusedSummary), + treeText: renderTreeText(app: app, title: title, rootIndex: subtree?.root.index, lines: renderer.lines, focused: renderer.focusedSummary), focusedElementId: renderer.focusedElementId, screenshot: screenshot, screenshotStatus: screenshotStatus, screenshotScale: screenshotScale(screenshot: screenshot, bounds: capture.bounds), screenshotEngine: capture.image?.engine, - elements: renderer.records, - elementOrder: indexes.order, + elements: elements, + elementOrder: elementOrder, nextFreshElementIndex: indexes.nextFreshIndex, truncated: renderer.truncated, maxDepthReached: renderer.maxDepthReached, + scope: subtree.map { SnapshotScope(rootIndex: $0.root.index, walkedIndexes: Set(indexes.order)) }, appWindowIds: windowCandidates.map(\.windowId).sorted() ) } @@ -751,39 +809,43 @@ final class Provider { "scale": payload.scale, ] } - return [ - "snapshot": [ - "id": snapshot.id, - "app": [ - "name": snapshot.app.name, - "bundleId": jsonNullable(snapshot.app.bundleId), - "pid": Int(snapshot.app.pid), - ], - "window": [ - "id": Int(snapshot.windowId), - "title": snapshot.windowTitle, - "x": Int(snapshot.windowBounds.origin.x.rounded()), - "y": Int(snapshot.windowBounds.origin.y.rounded()), - "width": Int(snapshot.windowBounds.width.rounded()), - "height": Int(snapshot.windowBounds.height.rounded()), - "isMinimized": false, - "isOffscreen": false, - "screenIndex": jsonNullable(screenIndex(for: snapshot.windowBounds)), - "platform": [ - "layer": snapshot.windowLayer, - ], - ], - "coordinateSpace": "window", - "treeText": snapshot.treeText, - "elementCount": snapshot.elements.count, - "focusedElementId": snapshot.focusedElementId as Any, - "truncation": [ - "truncated": snapshot.truncated, - "maxNodes": TreeRenderer.maxNodes, - "maxDepth": TreeRenderer.maxDepth, - "maxDepthReached": snapshot.maxDepthReached, + var snapshotPayload: [String: Any] = [ + "id": snapshot.id, + "app": [ + "name": snapshot.app.name, + "bundleId": jsonNullable(snapshot.app.bundleId), + "pid": Int(snapshot.app.pid), + ], + "window": [ + "id": Int(snapshot.windowId), + "title": snapshot.windowTitle, + "x": Int(snapshot.windowBounds.origin.x.rounded()), + "y": Int(snapshot.windowBounds.origin.y.rounded()), + "width": Int(snapshot.windowBounds.width.rounded()), + "height": Int(snapshot.windowBounds.height.rounded()), + "isMinimized": false, + "isOffscreen": false, + "screenIndex": jsonNullable(screenIndex(for: snapshot.windowBounds)), + "platform": [ + "layer": snapshot.windowLayer, ], ], + "coordinateSpace": "window", + "treeText": snapshot.treeText, + "elementCount": snapshot.scope?.walkedIndexes.count ?? snapshot.elements.count, + "focusedElementId": snapshot.focusedElementId as Any, + "truncation": [ + "truncated": snapshot.truncated, + "maxNodes": TreeRenderer.maxNodes, + "maxDepth": TreeRenderer.maxDepth, + "maxDepthReached": snapshot.maxDepthReached, + ], + ] + if let scope = snapshot.scope { + snapshotPayload["rootElementIndex"] = scope.rootIndex + } + return [ + "snapshot": snapshotPayload, "screenshot": screenshot, "screenshotStatus": renderScreenshotStatus(snapshot.screenshotStatus, snapshot: snapshot), ] @@ -1462,6 +1524,18 @@ private func pointerRecipient( return .focused(syntheticClickRecipient(pid: ownerPID, windowId: candidate.windowId)) } +/// The element's parents from `window` down, or nil when it is no longer inside `window`. +private func ancestorChain(of element: AXUIElement, in window: AXUIElement) -> [AXUIElement]? { + var chain: [AXUIElement] = [] + var current = element + while !CFEqual(current, window) { + guard chain.count < 256, let parent = copyElement(current, kAXParentAttribute as String) else { return nil } + chain.append(parent) + current = parent + } + return chain.reversed() +} + private func containingWindow(_ element: AXUIElement) -> AXUIElement? { var current = element for _ in 0..<64 { @@ -2179,15 +2253,18 @@ private func mouseButton(_ raw: String?) throws -> MouseButtonSelection { } } -private func renderTreeText(app: AppDescriptor, title: String, bounds: CGRect, lines: [String], focused: String?) -> String { +private func renderTreeText(app: AppDescriptor, title: String, rootIndex: Int?, lines: [String], focused: String?) -> String { var output = [ "App=\(app.bundleId ?? app.name.replacingOccurrences(of: " ", with: "_")) (pid \(app.pid))", "Window: \"\(sanitize(title))\", App: \(sanitize(app.name)).", - "", ] + if let rootIndex { + output.append("Showing element \(rootIndex) and its descendants.") + } + output.append("") output.append(contentsOf: lines) output.append("") - output.append(focused.map { "The focused UI element is \($0)." } ?? "No UI element is currently focused.") + output.append(focused.map { "The focused UI element is \($0)." } ?? (rootIndex == nil ? "No UI element is currently focused." : "No UI element inside this one is focused.")) return output.joined(separator: "\n") } @@ -2231,15 +2308,6 @@ private final class TreeRenderer { func render(_ element: AXUIElement, depth: Int = 0, ancestors: [AXUIElement] = []) { guard !reader.appStoppedResponding else { return } - guard nextIndex < Self.maxNodes else { - truncated = true - return - } - guard depth < Self.maxDepth else { - truncated = true - maxDepthReached = true - return - } guard !ancestors.contains(where: { CFEqual($0, element) }) else { return } let role = reader.stringAttribute(element, kAXRoleAttribute as String) ?? "AXUnknown" @@ -2290,9 +2358,7 @@ private final class TreeRenderer { webAreaDepth: webAreaDepth ) if SnapshotRenderHeuristics.shouldElide(node) { - for child in children { - render(child, depth: depth, ancestors: ancestors + [element]) - } + renderChildren(children, depth: depth, ancestors: ancestors + [element]) return } @@ -2315,9 +2381,8 @@ private final class TreeRenderer { return } if compactBrowserTabs, let tabStripCompaction = tabStripCompaction(parent: node, children: children) { - for (childIndex, child) in children.enumerated() where tabStripCompaction.retainedIndexes.contains(childIndex) { - render(child, depth: depth + 1, ancestors: ancestors + [element]) - } + let retained = children.enumerated().filter { tabStripCompaction.retainedIndexes.contains($0.offset) }.map(\.element) + renderChildren(retained, depth: depth + 1, ancestors: ancestors + [element]) lines.append( String(repeating: "\t", count: depth + 1) + "... \(tabStripCompaction.omittedCount) inactive browser tabs omitted" @@ -2325,14 +2390,26 @@ private final class TreeRenderer { return } let childLineStart = lines.count - for child in children { - render(child, depth: depth + 1, ancestors: ancestors + [element]) - } + renderChildren(children, depth: depth + 1, ancestors: ancestors + [element]) if compactBrowserTabs { compactRenderedBrowserTabs(parent: node, startLine: childLineStart, depth: depth + 1) } } + /// Stops at the node or depth limit with a note of how many children were left, so the agent can read that subtree. + private func renderChildren(_ children: [AXUIElement], depth: Int, ancestors: [AXUIElement]) { + for (position, child) in children.enumerated() { + // Why: browser-tab compaction drops records, so the limit counts what is kept, as on Linux and Windows. + guard records.count < Self.maxNodes, depth < Self.maxDepth else { + truncated = true + maxDepthReached = maxDepthReached || depth >= Self.maxDepth + lines.append(String(repeating: "\t", count: depth) + "... \(children.count - position) more not shown (snapshot limit)") + return + } + render(child, depth: depth, ancestors: ancestors) + } + } + private func tabStripCompaction(parent: SnapshotRenderNode, children: [AXUIElement]) -> SnapshotTabStripCompaction? { let childNodes = children.map { child in let role = reader.stringAttribute(child, kAXRoleAttribute as String) ?? "AXUnknown" diff --git a/native/computer-use-windows/runtime.ps1 b/native/computer-use-windows/runtime.ps1 index b8d86341d86..f4e5d1fc62e 100644 --- a/native/computer-use-windows/runtime.ps1 +++ b/native/computer-use-windows/runtime.ps1 @@ -794,12 +794,20 @@ function Render-OrcaTree($RootElement, $WindowFrame, [bool]$CompactBrowserTabs = # Tab compaction shrinks records mid-walk, so $records.Count would reuse retained indexes. $nextIndex = [ref]0 - function Visit-OrcaNode($Node, [int]$Depth) { - if ($records.Count -ge $MaxNodes -or $Depth -gt $MaxDepth) { - $truncation.truncated = $true - if ($Depth -gt $MaxDepth) { $truncation.maxDepthReached = $true } - return + function Visit-OrcaChildren($Children, [int]$Depth) { + for ($i = 0; $i -lt $Children.Count; $i++) { + if ($records.Count -ge $MaxNodes -or $Depth -gt $MaxDepth) { + $truncation.truncated = $true + if ($Depth -gt $MaxDepth) { $truncation.maxDepthReached = $true } + # Marks where the walk stopped, so the agent can read that parent's subtree by index. + $lines.Add(("`t" * $Depth) + "... $($Children.Count - $i) more not shown (snapshot limit)") + return + } + Visit-OrcaNode $Children.Item($i) $Depth } + } + + function Visit-OrcaNode($Node, [int]$Depth) { $identity = try { (@($Node.GetRuntimeId()) -join ".") } catch { [Guid]::NewGuid().ToString() } if (-not $seen.Add($identity)) { return } @@ -820,9 +828,7 @@ function Render-OrcaTree($RootElement, $WindowFrame, [bool]$CompactBrowserTabs = } } if (($roleKey -in @("pane", "group", "custom", "unknown")) -and [string]::IsNullOrWhiteSpace($title) -and [string]::IsNullOrWhiteSpace($record.value) -and $meaningfulActions.Count -eq 0 -and $null -eq $genericSummary -and $children.Count -le 1) { - for ($i = 0; $i -lt $children.Count; $i++) { - Visit-OrcaNode $children.Item($i) $Depth - } + Visit-OrcaChildren $children $Depth return } @@ -847,9 +853,7 @@ function Render-OrcaTree($RootElement, $WindowFrame, [bool]$CompactBrowserTabs = if (-not [string]::IsNullOrWhiteSpace($genericSummary) -or (Test-OrcaSuppressChildren $roleKey $title $record.value $genericSummary)) { return } $childLineStart = $lines.Count - for ($i = 0; $i -lt $children.Count; $i++) { - Visit-OrcaNode $children.Item($i) ($Depth + 1) - } + Visit-OrcaChildren $children ($Depth + 1) if ($CompactBrowserTabs) { Compress-OrcaRenderedBrowserTabs $records $lines $childLineStart ($Depth + 1) } @@ -1025,14 +1029,21 @@ function Get-OrcaScreenshot([bool]$IncludeScreenshot, $WindowFrame, [IntPtr]$Win } } -function New-OrcaSnapshot([string]$Query, [bool]$IncludeScreenshot, $WindowId = $null, $WindowIndex = $null, [bool]$RestoreWindow = $false) { +function New-OrcaSnapshot([string]$Query, [bool]$IncludeScreenshot, $WindowId = $null, $WindowIndex = $null, [bool]$RestoreWindow = $false, $TreeRoot = $null) { $process = Find-OrcaProcess $Query Assert-OrcaWindowTarget $process $WindowId $WindowIndex # Root first: its hang probe must run before ShowWindow, which blocks on a hung window. $root = Get-OrcaRootElement $process if ($RestoreWindow) { Restore-OrcaWindow $process } $windowFrame = Get-OrcaWindowFrame $process $root - $tree = Render-OrcaTree $root $windowFrame (Test-OrcaBrowserProcess $process) + $walkRoot = $root + if ($null -ne $TreeRoot) { + $walkRoot = Find-OrcaElement $root $TreeRoot + if ($null -eq $walkRoot) { + throw "stale element: element $($TreeRoot.index) is gone; run get-app-state again and use a fresh element index" + } + } + $tree = Render-OrcaTree $walkRoot $windowFrame (Test-OrcaBrowserProcess $process) $screenshot = Get-OrcaScreenshot $IncludeScreenshot $windowFrame ([IntPtr]$process.MainWindowHandle) [pscustomobject]@{ @@ -1452,7 +1463,7 @@ function Invoke-OrcaOperation($Operation) { return [pscustomobject]@{ ok = $true; app = $list.app; windows = @($list.windows) } } if ($Operation.tool -eq "get_app_state") { - return [pscustomobject]@{ ok = $true; snapshot = New-OrcaSnapshot $Operation.app $includeScreenshot $Operation.windowId $Operation.windowIndex ([bool]$Operation.restoreWindow) } + return [pscustomobject]@{ ok = $true; snapshot = New-OrcaSnapshot $Operation.app $includeScreenshot $Operation.windowId $Operation.windowIndex ([bool]$Operation.restoreWindow) $Operation.root } } $process = Find-OrcaProcess $Operation.app diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 4e1506d0e88..28ab7323b87 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -46,6 +46,12 @@ In a large window, look for one control with `get-app-state --query `: it ORCA computer get-app-state --app com.apple.finder --query Downloads --json ``` +A snapshot reads at most `truncation.maxNodes` elements and `maxDepth` levels. When it stops early, `truncation.truncated` is true and each cut-off place shows a `... N more not shown (snapshot limit)` line, indented like the children it stands for. To read them, pass the parent element's index (the nearest line above with less indentation) as `get-app-state --element-index `: it reads only that element and its descendants, with the full limit. Elements already shown keep their indexes and hidden ones get new ones, and you can act on them. Action results show the whole window again, so read the subtree again before acting on another hidden element. + +```text +ORCA computer get-app-state --app com.apple.Safari --element-index 312 --json +``` + ## Waiting Never `sleep` between actions. When the UI changes on its own after an action (a save finishes, a dialog opens, a button becomes clickable), wait for the change with `wait`. It returns as soon as the condition holds and prints the matching elements or windows; it fails with `wait_timeout` if the condition does not hold in time (default 10 s, `--timeout ` up to 120000). diff --git a/src/cli/computer/computer-format.ts b/src/cli/computer/computer-format.ts index a00f42f2ce7..f13b05919d8 100644 --- a/src/cli/computer/computer-format.ts +++ b/src/cli/computer/computer-format.ts @@ -31,7 +31,7 @@ export function formatGetAppState(result: ComputerSnapshotResult): string { ? '' : ` @ ${result.snapshot.window.x},${result.snapshot.window.y}` const truncation = result.snapshot.truncation?.truncated - ? ` Truncated: yes (max nodes ${result.snapshot.truncation.maxNodes ?? 'unknown'}, max depth ${result.snapshot.truncation.maxDepth ?? 'unknown'})` + ? ` Truncated: yes (max nodes ${result.snapshot.truncation.maxNodes ?? 'unknown'}, max depth ${result.snapshot.truncation.maxDepth ?? 'unknown'}); read cut-off children with --element-index ` : ' Truncated: no' return [ `${app.name} (pid ${app.pid}${bundle})`, diff --git a/src/cli/computer/computer.ts b/src/cli/computer/computer.ts index 7a5745c5ec1..cdd3082dfd0 100644 --- a/src/cli/computer/computer.ts +++ b/src/cli/computer/computer.ts @@ -7,6 +7,7 @@ import type { } from '../../shared/computer-use-runtime-types' import type { CommandHandler } from '../dispatch/dispatch' import { + getOptionalNonNegativeIntegerFlag, getOptionalPositiveIntegerFlag, getOptionalStringFlag, getRequiredStringFlag @@ -85,11 +86,23 @@ export const COMPUTER_HANDLERS: Record = { const observeFlags = getComputerObserveFlags(flags) const query = getOptionalStringFlag(flags, 'query') const maxElements = getOptionalPositiveIntegerFlag(flags, 'max-elements') + const rootElementIndex = getOptionalNonNegativeIntegerFlag(flags, 'element-index') const target = await getComputerCommandTarget(flags, cwd, client) const result = await client.call('computer.getAppState', { ...target, - ...observeFlags + ...observeFlags, + ...(rootElementIndex === undefined ? {} : { rootElementIndex }) }) + // Why: older runtimes drop the param and return the whole window, which would look like the subtree. + if ( + rootElementIndex !== undefined && + result.result.snapshot.rootElementIndex !== rootElementIndex + ) { + throw new RuntimeClientError( + 'unsupported_capability', + 'This Orca runtime cannot read one element subtree; update Orca, or run get-app-state without --element-index' + ) + } if (query !== undefined || maxElements !== undefined) { const { snapshot } = result.result snapshot.treeText = queryComputerTreeText(snapshot.treeText, { query, maxElements }) diff --git a/src/cli/discovery/command-scoped-flag-help.ts b/src/cli/discovery/command-scoped-flag-help.ts index b23764dd9f4..ba18dc9b3c3 100644 --- a/src/cli/discovery/command-scoped-flag-help.ts +++ b/src/cli/discovery/command-scoped-flag-help.ts @@ -19,6 +19,8 @@ const COMMAND_SCOPED_FLAG_HELP: Record> = { key: '--key Opaque key from reference list; repeat for several' }, 'computer get-app-state': { + 'element-index': + '--element-index Read only this element and its descendants, including any the window snapshot cut off', query: '--query Show only elements whose line contains this text, with their ancestors' }, diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 33aeaf25c71..6cb5a77d842 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1065,6 +1065,12 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "ORCA computer get-app-state --app com.apple.finder --query Downloads --json", "```", "", + "A snapshot reads at most `truncation.maxNodes` elements and `maxDepth` levels. When it stops early, `truncation.truncated` is true and each cut-off place shows a `... N more not shown (snapshot limit)` line, indented like the children it stands for. To read them, pass the parent element's index (the nearest line above with less indentation) as `get-app-state --element-index `: it reads only that element and its descendants, with the full limit. Elements already shown keep their indexes and hidden ones get new ones, and you can act on them. Action results show the whole window again, so read the subtree again before acting on another hidden element.", + "", + "```text", + "ORCA computer get-app-state --app com.apple.Safari --element-index 312 --json", + "```", + "", "## Waiting", "", "Never `sleep` between actions. When the UI changes on its own after an action (a save finishes, a dialog opens, a button becomes clickable), wait for the change with `wait`. It returns as soon as the condition holds and prints the matching elements or windows; it fails with `wait_timeout` if the condition does not hold in time (default 10 s, `--timeout ` up to 120000).", diff --git a/src/cli/specs/computer.ts b/src/cli/specs/computer.ts index bd4ea9d5c8d..af216111fc6 100644 --- a/src/cli/specs/computer.ts +++ b/src/cli/specs/computer.ts @@ -44,8 +44,8 @@ export const COMPUTER_COMMAND_SPECS: CommandSpec[] = [ path: ['computer', 'get-app-state'], summary: 'Capture a compact accessibility snapshot of an app', usage: - 'orca computer get-app-state --app [--window-id | --window-index ] [--worktree | --session ] [--query ] [--max-elements ] [--restore-window] [--no-screenshot] [--json]', - allowedFlags: [...COMPUTER_OBSERVE_FLAGS, 'query', 'max-elements'] + 'orca computer get-app-state --app [--window-id | --window-index ] [--worktree | --session ] [--element-index ] [--query ] [--max-elements ] [--restore-window] [--no-screenshot] [--json]', + allowedFlags: [...COMPUTER_OBSERVE_FLAGS, 'element-index', 'query', 'max-elements'] }, { path: ['computer', 'wait'], diff --git a/src/main/computer/desktop-script/desktop-script-provider-client.ts b/src/main/computer/desktop-script/desktop-script-provider-client.ts index 1e00ec6f6aa..cb64132de77 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-client.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-client.ts @@ -40,6 +40,7 @@ import { isRuntimeHostUnavailable } from './runtime-host/desktop-script-runtime-host' import { DesktopScriptSnapshotStore } from './snapshots/desktop-script-snapshot-store' +import { readSubtreeSnapshot } from './snapshots/desktop-script-subtree-snapshot' import { normalizeBridgeApp, renderSnapshot } from './snapshots/desktop-script-snapshot-rendering' import { normalizeComputerActionResult } from '../action-contracts/computer-action-verification-normalization' import { RuntimeClientError } from '../runtime-client-error' @@ -119,6 +120,14 @@ export class DesktopScriptProviderClient { async snapshot(params: Record): Promise { const app = stringParam(params, 'app') + const rootElementIndex = optionalNumberParam(params, 'rootElementIndex') + if (rootElementIndex !== undefined) { + return await readSubtreeSnapshot(this.snapshotStore, (request) => this.callBridge(request), { + app, + rootElementIndex, + params + }) + } const response = await this.callBridge({ tool: 'get_app_state', app, diff --git a/src/main/computer/desktop-script/desktop-script-provider-types.ts b/src/main/computer/desktop-script/desktop-script-provider-types.ts index adcdb816766..662d9230323 100644 --- a/src/main/computer/desktop-script/desktop-script-provider-types.ts +++ b/src/main/computer/desktop-script/desktop-script-provider-types.ts @@ -77,6 +77,8 @@ export type BridgeSnapshot = { focusedElementId?: number | null selectedText?: string | null elements?: BridgeElement[] + /** Set by the client when treeLines show only this element's subtree. */ + rootElementIndex?: number } export type BridgeWindow = { @@ -128,6 +130,8 @@ export type BridgeRequest = { requestId?: number app?: string element?: BridgeElement + /** get_app_state renders only this element's subtree. */ + root?: BridgeElement fromElement?: BridgeElement toElement?: BridgeElement x?: number diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts b/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts index f16500f2fbe..7b32866b033 100644 --- a/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts +++ b/src/main/computer/desktop-script/snapshots/desktop-script-snapshot-rendering.ts @@ -49,6 +49,9 @@ export function renderSnapshot( treeText, elementCount: snapshot.elements?.length ?? 0, focusedElementId, + ...(snapshot.rootElementIndex === undefined + ? {} + : { rootElementIndex: snapshot.rootElementIndex }), truncation: { truncated: snapshot.truncation?.truncated === true, maxNodes: snapshot.truncation?.maxNodes, @@ -125,6 +128,9 @@ function renderTreeText(snapshot: BridgeSnapshot): string { const lines = [ `App=${appRef} (pid ${snapshot.app.pid})`, `Window: "${sanitize(snapshot.windowTitle ?? snapshot.app.name)}", App: ${sanitize(snapshot.app.name)}.`, + ...(snapshot.rootElementIndex === undefined + ? [] + : [`Showing element ${snapshot.rootElementIndex} and its descendants.`]), '', ...(snapshot.treeLines ?? []) ] diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts new file mode 100644 index 00000000000..319685e8c91 --- /dev/null +++ b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.test.ts @@ -0,0 +1,72 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { + createDesktopScriptProviderClient, + mockBridgeResponse, + resetDesktopScriptProviderTestHarness, + sampleBridgeSnapshot, + sampleCapabilities +} from '../desktop-script-provider-test-harness' + +function bridgeSnapshot(treeLines: string[], elements: { index: number; runtimeId: number[] }[]) { + return { ...sampleBridgeSnapshot('Mail', ''), windowIndex: 0, treeLines, elements } +} + +describe('DesktopScriptProviderClient subtree reads', () => { + afterEach(resetDesktopScriptProviderTestHarness) + + it('keeps shown indexes, numbers hidden children after them, and resolves them for actions', async () => { + const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') + mockBridgeResponse({ + ok: true, + snapshot: bridgeSnapshot( + ['0 frame Mail', '\t1 list Inbox', '\t\t2 button A', '\t\t... 1 more not shown'], + [ + { index: 0, runtimeId: [0] }, + { index: 1, runtimeId: [0, 0] }, + { index: 2, runtimeId: [0, 0, 0] } + ] + ) + }) + await client.snapshot({ app: 'Mail' }) + + let sentRoot: unknown + mockBridgeResponse( + { + ok: true, + snapshot: bridgeSnapshot( + ['0 list Inbox', '\t1 button A', '\t2 button B'], + [ + { index: 0, runtimeId: [0, 0] }, + { index: 1, runtimeId: [0, 0, 0] }, + { index: 2, runtimeId: [0, 0, 1] } + ] + ) + }, + (operation) => { + sentRoot = operation.root + } + ) + const subtree = await client.snapshot({ app: 'Mail', rootElementIndex: 1 }) + + expect(sentRoot).toMatchObject({ index: 1, runtimeId: [0, 0] }) + expect(subtree.snapshot.rootElementIndex).toBe(1) + expect(subtree.snapshot.treeText.split('\n').slice(2, 7)).toEqual([ + 'Showing element 1 and its descendants.', + '', + '1 list Inbox', + '\t2 button A', + '\t3 button B' + ]) + + let clicked: unknown + mockBridgeResponse({ ok: true, capabilities: sampleCapabilities() }) + mockBridgeResponse( + { ok: true, snapshot: bridgeSnapshot(['0 frame Mail'], [{ index: 0, runtimeId: [0] }]) }, + (operation) => { + clicked = operation.element + } + ) + await client.action('click', { app: 'Mail', elementIndex: 3 }) + expect(clicked).toMatchObject({ runtimeId: [0, 0, 1] }) + }) +}) diff --git a/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts new file mode 100644 index 00000000000..4a569d6d26b --- /dev/null +++ b/src/main/computer/desktop-script/snapshots/desktop-script-subtree-snapshot.ts @@ -0,0 +1,103 @@ +import type { ComputerSnapshotResult } from '../../../../shared/computer-use-runtime-types' +import { renumberComputerTreeLine } from '../../../../shared/computer-use-tree-text' +import { RuntimeClientError } from '../../runtime-client-error' +import { elementParam } from '../actions/desktop-script-action' +import { optionalNumberParam } from '../desktop-script-provider-params' +import type { + BridgeElement, + BridgeRequest, + BridgeResponse, + BridgeSnapshot +} from '../desktop-script-provider-types' +import type { DesktopScriptSnapshotStore } from './desktop-script-snapshot-store' +import { renderSnapshot } from './desktop-script-snapshot-rendering' + +/** Reads one element's subtree of the window the store last saw, the target of --element-index. */ +export async function readSubtreeSnapshot( + store: DesktopScriptSnapshotStore, + callBridge: (request: BridgeRequest) => Promise, + { + app, + rootElementIndex, + params + }: { app: string; rootElementIndex: number; params: Record } +): Promise { + const base = store.current(app, optionalNumberParam(params, 'windowId'), params) + if (!base) { + throw new RuntimeClientError( + 'element_not_found', + '--element-index needs a get-app-state snapshot of this app/window first' + ) + } + const response = await callBridge({ + tool: 'get_app_state', + app, + root: elementParam(base, rootElementIndex), + windowId: base.windowId ?? undefined, + windowIndex: base.windowIndex ?? undefined, + noScreenshot: params.noScreenshot === true, + restoreWindow: params.restoreWindow === true + }) + if (!response.snapshot) { + throw new RuntimeClientError('accessibility_error', 'desktop provider returned no snapshot') + } + const { shown, cached } = indexSubtreeSnapshot(base, response.snapshot, rootElementIndex) + store.remember(app, cached, params) + return renderSnapshot(shown, params.noScreenshot === true) +} + +/** + * Gives a subtree read the indexes the window's cached snapshot already uses: elements it showed + * keep theirs, new ones get unused indexes. Returns what to show and what to cache, where the + * cache keeps the earlier elements so their indexes still resolve for actions. + */ +function indexSubtreeSnapshot( + base: BridgeSnapshot, + subtree: BridgeSnapshot, + rootElementIndex: number +): { shown: BridgeSnapshot; cached: BridgeSnapshot } { + const baseElements = base.elements ?? [] + const baseIndexByRuntimeId = new Map() + for (const element of baseElements) { + const key = runtimeIdKey(element) + if (key !== null && !baseIndexByRuntimeId.has(key)) { + baseIndexByRuntimeId.set(key, element.index) + } + } + let nextIndex = baseElements.reduce((max, element) => Math.max(max, element.index), -1) + 1 + const indexes = new Map() + const claimed = new Set() + for (const element of subtree.elements ?? []) { + const key = runtimeIdKey(element) + const known = key === null ? undefined : baseIndexByRuntimeId.get(key) + const index = known !== undefined && !claimed.has(known) ? known : nextIndex++ + claimed.add(index) + indexes.set(element.index, index) + } + const walked = (subtree.elements ?? []).map((element) => ({ + ...element, + index: indexes.get(element.index) ?? element.index + })) + const focusedElementId = + subtree.focusedElementId === null || subtree.focusedElementId === undefined + ? subtree.focusedElementId + : (indexes.get(subtree.focusedElementId) ?? null) + const shown: BridgeSnapshot = { + ...subtree, + treeLines: subtree.treeLines?.map((line) => renumberComputerTreeLine(line, indexes)), + focusedElementId, + elements: walked, + rootElementIndex + } + const cached: BridgeSnapshot = { + ...shown, + elements: [...baseElements.filter((element) => !claimed.has(element.index)), ...walked] + } + return { shown, cached } +} + +function runtimeIdKey(element: BridgeElement): string | null { + return Array.isArray(element.runtimeId) && element.runtimeId.length > 0 + ? JSON.stringify(element.runtimeId) + : null +} diff --git a/src/shared/computer-use-runtime-types.ts b/src/shared/computer-use-runtime-types.ts index 42de55e7b3c..7ae199c70e8 100644 --- a/src/shared/computer-use-runtime-types.ts +++ b/src/shared/computer-use-runtime-types.ts @@ -52,6 +52,8 @@ export type ComputerSnapshotData = { treeText: string elementCount: number focusedElementId: number | null + // Present only when treeText is the subtree of this element, read with rootElementIndex. + rootElementIndex?: number // Present only when treeText is a diff against the previous snapshot of the same window. treeDiff?: { baseSnapshotId: string diff --git a/src/shared/computer-use-tree-text.ts b/src/shared/computer-use-tree-text.ts index 44edee2de03..2e73c73e6b0 100644 --- a/src/shared/computer-use-tree-text.ts +++ b/src/shared/computer-use-tree-text.ts @@ -37,6 +37,16 @@ export function parseComputerTreeText(treeText: string): ComputerTreeText { return { header: lines.slice(0, first), elements, footer: lines.slice(footerStart) } } +/** Rewrites the index of an element line; other lines pass through. */ +export function renumberComputerTreeLine( + line: string, + indexes: ReadonlyMap +): string { + const match = ELEMENT_LINE.exec(line) + const index = match ? indexes.get(Number(match[2])) : undefined + return match && index !== undefined ? `${match[1]}${index}${line.slice(match[0].length)}` : line +} + export function joinComputerTreeText(header: string[], body: string[], footer: string[]): string { return [...trimTrailingBlank(header), '', ...body, ...footer].join('\n') } diff --git a/src/shared/rpc-contract/computer-schemas-params.ts b/src/shared/rpc-contract/computer-schemas-params.ts index 0f0a0f1fc00..6fb6d0bf2ac 100644 --- a/src/shared/rpc-contract/computer-schemas-params.ts +++ b/src/shared/rpc-contract/computer-schemas-params.ts @@ -56,7 +56,10 @@ export function validateComputerTarget( validateWindowTarget(value, ctx) } -export const ComputerObserveTarget = ComputerObserveTargetBase.superRefine(validateComputerTarget) +export const ComputerObserveTarget = ComputerObserveTargetBase.extend({ + // Reads one element's subtree. Older runtimes strip it, and their result has no rootElementIndex. + rootElementIndex: OptionalNonNegativeInt +}).superRefine(validateComputerTarget) export const ListApps = z.object({}).strict() From 8b2caa497cd1aded03b6206d46c70b94a246df42 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:24:53 -0800 Subject: [PATCH 21/44] test(terminal): isolate live zsh hook command lookup (#41678) --- ...-idle-zsh-preexec-hook-order.live-shell.test.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts b/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts index 4fe65b9232d..b5b756c4cbf 100644 --- a/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts +++ b/src/main/runtime/terminal/wait/tui-idle-zsh-preexec-hook-order.live-shell.test.ts @@ -6,6 +6,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import * as pty from 'node-pty' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' import { getShellLaunchConfig } from '../../../providers/local-pty/local-pty-shell-ready' import { selectShellStartupFeatures } from '../../../pty/shell-startup/shell-startup-features' import { hasZsh, ZSH_PATH } from '../../../pty/shell-startup/zsh-startup-hook-pty-harness' @@ -102,9 +103,14 @@ async function captureLaunch(hookCase: HookCase): Promise { const root = mkdtempSync(join(tmpdir(), 'orca-preexec-order-')) const home = join(root, 'home') const bin = join(root, 'bin') + const fixturePath = `${bin}:/usr/bin:/bin` mkdirSync(home) mkdirSync(bin) - writeFileSync(join(home, '.zshrc'), hookCase.zshrc) + // Login profiles can reorder PATH, so restore the stand-in before the startup command runs. + writeFileSync( + join(home, '.zshrc'), + `export PATH=${quotePosixShell(fixturePath)}\n${hookCase.zshrc}` + ) const standIn = join(bin, 'claude') writeFileSync(standIn, standInClaude(hookCase.agentSetsRestTitle)) chmodSync(standIn, 0o755) @@ -129,12 +135,12 @@ async function captureLaunch(hookCase: HookCase): Promise { rows: 30, cwd: home, env: { - PATH: `${bin}:/usr/bin:/bin`, + ...launchEnv, + PATH: fixturePath, HOME: home, TERM: 'xterm-256color', LANG: 'en_US.UTF-8', - ORCA_TEST_HOOK_ORDER: hookOrderPath, - ...launchEnv + ORCA_TEST_HOOK_ORDER: hookOrderPath } }) const chunks: Chunk[] = [] From 8bb57668ed7dc033ce7a7af0021274fdd52a5bab Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:25:10 +0000 Subject: [PATCH 22/44] fix(computer): refuse quit, log out and lock shortcuts unless explicitly allowed (#41412) * fix(computer): refuse quit, log out and lock shortcuts unless explicitly allowed * fix(computer): close Linux keysym bypasses in the system shortcut guard * fix(computer): refuse Linux keycode, L1/L2 and VT-switch keysym bypasses * fix(computer): catch control characters in Linux keycode tokens and point recovery at the stated effect --- docs/site/content/docs/cli/computer-use.mdx | 2 + skill-guides/orca-computer-use.md | 2 + src/cli/computer/computer-action-flags.ts | 12 +- src/cli/discovery/flag-help-text.ts | 2 + src/cli/skills/bundled-skill-guides.ts | 2 + src/cli/specs/computer.ts | 8 +- .../computer-blocked-key-combos.test.ts | 77 ++++++++ .../computer-blocked-key-combos.ts | 177 ++++++++++++++++++ .../computer-provider-action-validation.ts | 14 +- src/shared/cli-argument-boundary.ts | 1 + src/shared/computer-use-error-recovery.ts | 5 + src/shared/computer-use-runtime-types.ts | 1 + .../rpc-contract/computer-schemas-params.ts | 6 +- 13 files changed, 296 insertions(+), 13 deletions(-) create mode 100644 src/main/computer/action-contracts/computer-blocked-key-combos.test.ts create mode 100644 src/main/computer/action-contracts/computer-blocked-key-combos.ts diff --git a/docs/site/content/docs/cli/computer-use.mdx b/docs/site/content/docs/cli/computer-use.mdx index 776ac5a21a2..5f39edea8e5 100644 --- a/docs/site/content/docs/cli/computer-use.mdx +++ b/docs/site/content/docs/cli/computer-use.mdx @@ -87,6 +87,8 @@ orca computer perform-secondary-action --app --element-index --action Prefer semantic actions (`click`, `set-value`, `perform-secondary-action`) over raw `type-text` or `press-key` — they target accessibility elements directly and survive focus changes that keyboard input doesn't. +`hotkey` and `press-key` refuse shortcuts that quit or close the app, log out, lock the screen, force-quit or end the session, such as `Cmd+Q`, `Shift+Cmd+Q`, `Ctrl+Cmd+Q` and `Option+Cmd+Esc` on macOS, `Alt+F4` and `Win+L` on Windows, and `Ctrl+Q`, `Alt+F4`, `Super+L` and `Ctrl+Alt+Delete` on Linux. The error code is `system_shortcut_blocked`. Pass `--allow-system-shortcut` to send one anyway. + On macOS, actions run in the background: the target app isn't brought forward, your frontmost app and key window stay put, and the pointer doesn't move, so you can keep working while an agent drives another window. Each action result reports `action.delivery` (`background` or `foreground`). Pass `--restore-window` only when an app ignores background input, such as drags in Chromium or Electron apps or games; it brings the app forward and uses the real pointer and keyboard. Popup menus and web ``, use `set-value` on it; otherwise retry once with `--restore-window` after telling the user it will take over their screen. - `window_not_focused`: retry once with `--restore-window`; if the message says restore was already requested, stop retrying restore and bring the app forward manually or check permissions. For editable fields prefer `set-value`, then inspect before assuming keyboard input worked. diff --git a/src/cli/computer/computer-action-flags.ts b/src/cli/computer/computer-action-flags.ts index 3d5134617c9..bb80a69845d 100644 --- a/src/cli/computer/computer-action-flags.ts +++ b/src/cli/computer/computer-action-flags.ts @@ -145,24 +145,32 @@ export async function getComputerTextActionFlags(flags: Map): { key: string + allowSystemShortcut?: boolean } { const key = getRequiredStringFlag(flags, 'key') const message = computerUsePressKeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } - return { key } + return { + key, + ...(flags.get('allow-system-shortcut') === true ? { allowSystemShortcut: true } : {}) + } } export function getComputerHotkeyActionFlags(flags: Map): { key: string + allowSystemShortcut?: boolean } { const key = getRequiredStringFlag(flags, 'key') const message = computerUseHotkeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } - return { key } + return { + key, + ...(flags.get('allow-system-shortcut') === true ? { allowSystemShortcut: true } : {}) + } } export async function getComputerSetValueActionFlags( diff --git a/src/cli/discovery/flag-help-text.ts b/src/cli/discovery/flag-help-text.ts index 108cf43bf8f..de9456cb499 100644 --- a/src/cli/discovery/flag-help-text.ts +++ b/src/cli/discovery/flag-help-text.ts @@ -10,6 +10,8 @@ export const FLAG_HELP_TEXT: Record = { action: '--action Secondary accessibility action name', activate: '--activate Reveal the new worktree in the Orca app', app: '--app App name, bundle ID, or pid:N', + 'allow-system-shortcut': + '--allow-system-shortcut Send a quit, log out or lock shortcut that is refused by default', direction: '--direction Direction: up|down|left|right for scroll, horizontal|vertical for split', 'display-name': '--display-name Override the Orca display name', diff --git a/src/cli/skills/bundled-skill-guides.ts b/src/cli/skills/bundled-skill-guides.ts index 6cb5a77d842..0bc7a527040 100644 --- a/src/cli/skills/bundled-skill-guides.ts +++ b/src/cli/skills/bundled-skill-guides.ts @@ -1147,6 +1147,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "- After any UI-changing action, use the returned state or rerun `get-app-state` before choosing the next element index.", "- Use `type-text` only after focusing a field and confirming the app has a focused text receiver; synthetic keyboard delivery is reported as unverified, so inspect the returned state before assuming text landed.", "- Use `press-key` for single/navigation keys such as Return, Escape, Tab, and arrows. Use `hotkey` only for one modifier chord plus one key, such as `CmdOrCtrl+A` or `CmdOrCtrl+Shift+P`; prefer `CmdOrCtrl+...` for cross-platform combos.", + "- Shortcuts that quit or close the app, log out, lock the screen, force-quit or end the session (such as `Cmd+Q` on macOS, `Alt+F4` on Windows and Linux, `Ctrl+Q` on Linux) are refused with `system_shortcut_blocked`. The error says what the shortcut would do; reach that goal another way, such as the window's own close button or menu item. Add `--allow-system-shortcut` only when the user asked for that exact shortcut.", "- Use `click --modifiers ` for modifier-clicks. Never synthesize separate modifier-down and modifier-up commands around a click; interruption can leave a modifier logically held.", "- Coordinates are window-local; use coordinates from the latest screenshot/state for the same target window.", "", @@ -1207,6 +1208,7 @@ const ORCA_COMPUTER_USE_MARKDOWN = [ "", "- `app_not_found`: run `list-apps` and retry with the bundle ID. If the target is a web app such as Gmail, choose the desktop browser app/window that contains it; do not retry `ORCA computer ... --app Gmail` unchanged because `orca computer` app selectors refer to desktop apps, not website names.", "- `app_blocked`: stop; the target is intentionally blocked from computer-use.", + "- `system_shortcut_blocked`: the error message says what the shortcut would do. Reach the same goal with a semantic action, such as a button or menu item, or ask the user; retry with `--allow-system-shortcut` only when the user asked for that exact shortcut.", "- `window_not_found` / `window_stale`: run `list-windows`, choose a current selector, then rerun `get-app-state`.", "- `background_unavailable`: for a popup or `