diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 51ec40e85fe..d0abf40cae2 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -54,6 +54,8 @@ on: - 'tests/e2e/computer-linux.e2e.ts' - 'tests/e2e/computer-windows.e2e.ts' - 'tests/e2e/computer-windows-store.e2e.ts' + - 'tests/e2e/computer-windows-background.e2e.ts' + - 'tests/e2e/helpers/windows-semantic-controls-fixture.*' - 'tests/e2e/helpers/computer-cli-driver.ts' - 'tests/e2e/helpers/computer-driver.ts' - 'tests/e2e/vitest.config.ts' @@ -151,4 +153,4 @@ jobs: - run: pnpm verify:computer-native - run: pnpm build:cli - run: pnpm run build:electron-vite:parallel - - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts + - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-store.e2e.ts tests/e2e/computer-windows-background.e2e.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/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 0473b42de3b..598db059065 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -221,8 +221,8 @@ jobs: pnpm-lock.yaml cloud/pnpm-lock.yaml - # These two tests import the cloud relay workspace directly. Keeping them in one job - # avoids installing and building the same workspace once per unit-test shard. + # This test imports the cloud relay workspace directly. Its dedicated job avoids + # installing and building the same workspace once per unit-test shard. - name: Install relay integration dependencies id: relay_dependencies if: ${{ !cancelled() && steps.root_dependencies.outcome == 'success' }} @@ -237,5 +237,4 @@ jobs: ORCA_BACKGROUND_LAUNCH: '1' run: >- pnpm exec vitest run --config config/vitest.config.ts - tests/e2e/relay-region-compatibility.unit.test.ts tests/e2e/relay-region-correction.unit.test.ts diff --git a/cloud/apps/relay-edge/spike/lib.ts b/cloud/apps/relay-edge/spike/lib.ts index 4c226454227..4ea68543ac0 100644 --- a/cloud/apps/relay-edge/spike/lib.ts +++ b/cloud/apps/relay-edge/spike/lib.ts @@ -5,7 +5,7 @@ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs import { SignJWT, exportJWK, generateKeyPair, importJWK, type JWK } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) diff --git a/cloud/apps/relay-edge/spike/run-all-harness.ts b/cloud/apps/relay-edge/spike/run-all-harness.ts index d4928f8784c..050c9a81be2 100644 --- a/cloud/apps/relay-edge/spike/run-all-harness.ts +++ b/cloud/apps/relay-edge/spike/run-all-harness.ts @@ -2,7 +2,7 @@ // client wrapper, the echo service, phone sockets and workerd memory sampling. import { execSync } from 'node:child_process' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const PORT = 8787 diff --git a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts index a4e00c9fc29..8c7814db282 100644 --- a/cloud/apps/relay-edge/spike/run-all-lifecycle.ts +++ b/cloud/apps/relay-edge/spike/run-all-lifecycle.ts @@ -39,7 +39,7 @@ export async function runLifecycleChecks(ctx: Ctx, main: Control, mainAck: Ack): mute.on('close', (c) => (muteClose = c)) await new Promise((res) => mute.on('open', res)) // Complete the handshake by hand with the shipped proof answerer, then never pong. - const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/relay-host-proof') + const { answerRelayHostChallenge } = await import('../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof') mute.send(JSON.stringify({ type: 'host-hello', v: 1, relayHostId: ctx.relayHostId, assignmentEpoch: 7, hostPublicKeyB64: ctx.keypair.publicKeyB64, appVersion: 'spike' })) mute.on('message', (raw) => { diff --git a/cloud/apps/relay-edge/test/harness-mvp-object.ts b/cloud/apps/relay-edge/test/harness-mvp-object.ts index c47386b9be5..579814d0b42 100644 --- a/cloud/apps/relay-edge/test/harness-mvp-object.ts +++ b/cloud/apps/relay-edge/test/harness-mvp-object.ts @@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs' import { SignJWT, type KeyLike } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' export const PORT = 8789 diff --git a/cloud/apps/relay-edge/test/harness-roundtrip.ts b/cloud/apps/relay-edge/test/harness-roundtrip.ts index 04b44f2ab85..a9fd304e8d4 100644 --- a/cloud/apps/relay-edge/test/harness-roundtrip.ts +++ b/cloud/apps/relay-edge/test/harness-roundtrip.ts @@ -8,7 +8,7 @@ import { join } from 'node:path' import { SignJWT, type KeyLike } from 'jose' import nacl from 'tweetnacl' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol' diff --git a/cloud/apps/relay-edge/test/mvp.ts b/cloud/apps/relay-edge/test/mvp.ts index 8b1b66b858e..0fd34352f55 100644 --- a/cloud/apps/relay-edge/test/mvp.ts +++ b/cloud/apps/relay-edge/test/mvp.ts @@ -15,7 +15,7 @@ import { SignJWT, exportJWK, generateKeyPair, type KeyLike } from 'jose' import nacl from 'tweetnacl' import pg from 'pg' import WebSocket from 'ws' -import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/relay-control-client' +import { RelayControlClient } from '../../../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client' import { CloudRelayTransport } from '../../../../src/main/runtime/rpc/transports/relay-transport' import { RelayPhoneHelloSchema } from '../../../../src/shared/remote-runtime/relay/mobile-relay-phone-protocol' diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md deleted file mode 100644 index 2ac4ad78391..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md +++ /dev/null @@ -1,8 +0,0 @@ -Exact relay contract snapshots from `027acb4efa2e6b226d40df266b86367423946d62`, `cloud/packages/relay-contract/src/`. Used to exercise the pre-correction strict wire parsers. Do not format or edit these baseline sources. - -```text -aba94e108a5cd0f1af8b38875429ad8636d24c43a728273e3df60d9a1a1d1b6d director-messages.ts -bd13b5a694a5d683a5b680c14e46ab33f4ef4a5bfedf040d046b09d540cb4c17 wire-scalars.ts -bc89116f884a2f20a6588f9b91219aa596bc2410d28b499a93a78350def109d5 relay-regions.ts -8fcae470a5fc72f2fcdde9d2f09cd20289c256356dd490484ac1cfa53839fbe4 control-messages.ts -``` diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts deleted file mode 100644 index 0daf21e7c28..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { z } from 'zod' -import { - Base6432ByteSchema, - Base64Raw24ByteSchema, - Base64Url32ByteSchema, - EpochMsSchema, - GenerationSchema, - OpaqueIdSchema, - PositiveDurationMsSchema, - RelayHostIdSchema -} from './wire-scalars.js' - -const AppVersionSchema = z.string().min(1).max(128) -const BoundedCiphertextSchema = z - .string() - .min(1) - .max(16 * 1024) - .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/) -const ConnectionKindSchema = z.enum(['invite', 'resume']) - -export const HostHelloSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - assignmentEpoch: GenerationSchema, - hostPublicKeyB64: Base6432ByteSchema, - appVersion: AppVersionSchema, - previousGeneration: GenerationSchema.optional(), - controlResumeSecret: Base64Url32ByteSchema.optional() - }) - .strict() - -export const HostChallengeSchema = z - .object({ - challengeId: OpaqueIdSchema, - relayEphemeralPublicKeyB64: Base6432ByteSchema, - nonceB64: Base64Raw24ByteSchema, - ciphertextB64: BoundedCiphertextSchema, - expiresAt: EpochMsSchema - }) - .strict() - -export const HostChallengeAckSchema = z - .object({ challengeId: OpaqueIdSchema, proofB64: Base6432ByteSchema }) - .strict() - -// Advertised on the control upgrade rather than in host-hello: HostHelloSchema -// is strict, so a new hello key is refused by every already-deployed cell. -export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities' -// The host accepts kind/relayDeviceId on a pendingConns entry. A host that does -// not advertise this parses those entries strictly and would drop the whole ack. -export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' - -export function parseRelayHostCapabilities( - header: string | string[] | undefined -): ReadonlySet { - const raw = Array.isArray(header) ? header.join(',') : (header ?? '') - return new Set( - raw - .split(',') - .map((token) => token.trim()) - .filter((token) => token.length > 0 && token.length <= 64) - .slice(0, 16) - ) -} - -// kind/relayDeviceId are optional so an entry stays readable by a host that -// predates them; the cell only emits them to a host that advertised support. -const PendingConnectionSchema = z - .object({ - connId: OpaqueIdSchema, - connTicket: Base64Url32ByteSchema, - kind: ConnectionKindSchema.optional(), - relayDeviceId: OpaqueIdSchema.optional() - }) - .strict() - -export const HostHelloAckSchema = z - .object({ - v: z.literal(1), - generation: GenerationSchema, - controlResumeSecret: Base64Url32ByteSchema, - leaseExpiresAt: EpochMsSchema, - activeConnIds: z.array(OpaqueIdSchema).max(8), - pendingConns: z.array(PendingConnectionSchema).max(8) - }) - .strict() - -export const ConnectionOpenSchema = z - .object({ - connId: OpaqueIdSchema, - connTicket: Base64Url32ByteSchema, - kind: ConnectionKindSchema, - relayDeviceId: OpaqueIdSchema, - attachDeadlineMs: PositiveDurationMsSchema - }) - .strict() - -export const HostDataAuthSchema = z - .object({ - v: z.literal(1), - connTicket: Base64Url32ByteSchema, - generation: GenerationSchema - }) - .strict() - -export const InviteCreateSchema = z - .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) - .strict() - -export const InviteCreatedSchema = z - .object({ - reqId: OpaqueIdSchema, - inviteToken: Base64Url32ByteSchema, - expiresAt: EpochMsSchema, - maxAttempts: z.number().int().positive().max(16) - }) - .strict() - -export const DeviceRevokeSchema = z - .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) - .strict() - -export const AuthRefreshSchema = z.object({ relayJwt: z.string().min(1).max(8 * 1024) }).strict() - -export const DrainSchema = z - .object({ - graceMs: z.number().int().nonnegative().max(60 * 60 * 1000), - recovery: z.literal('resolve-director') - }) - .strict() - -export const HeartbeatSchema = z.object({ t: EpochMsSchema }).strict() - -export type HostHello = z.infer -export type HostChallenge = z.infer -export type HostChallengeAck = z.infer -export type HostHelloAck = z.infer -export type ConnectionOpen = z.infer -export type HostDataAuth = z.infer -export type InviteCreate = z.infer -export type InviteCreated = z.infer -export type DeviceRevoke = z.infer -export type AuthRefresh = z.infer -export type Drain = z.infer -export type Heartbeat = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts deleted file mode 100644 index e697135b68e..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { z } from 'zod' -import { - Base64Url32ByteSchema, - CanonicalHttpsOriginSchema, - EpochMsSchema, - GenerationSchema, - RelayHostIdSchema -} from './wire-scalars.js' -import { RelayRegionSchema } from './relay-regions.js' - -const SignedAssignmentLeaseSchema = z.string().min(1).max(8 * 1024) - -export const AssignmentRequestSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - // Client-declared reconnection; the director verifies it against the - // durable assignment before granting fast-lane admission. - reconnect: z.boolean().optional(), - preferredRegion: RelayRegionSchema.optional() - }) - .strict() - -export const AssignmentResponseSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema, - lease: SignedAssignmentLeaseSchema - }) - .strict() - -export const ResolveRequestSchema = z - .object({ - v: z.literal(1), - relayHostId: RelayHostIdSchema, - resumeToken: Base64Url32ByteSchema - }) - .strict() - -export const ResolveResponseSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema, - leaseExpiresAt: EpochMsSchema - }) - .strict() - -export const RelayMovedSchema = z - .object({ - v: z.literal(1), - cellUrl: CanonicalHttpsOriginSchema, - assignmentEpoch: GenerationSchema - }) - .strict() - -export function isTrustedNewerMove(input: { - sourceOrigin: string - configuredDirectorOrigin: string - currentAssignmentEpoch: number - move: z.infer -}): boolean { - // Why: cells and stale director responses must never redirect a credential-bearing client. - return ( - input.sourceOrigin === input.configuredDirectorOrigin && - input.move.assignmentEpoch > input.currentAssignmentEpoch - ) -} - -export type AssignmentRequest = z.infer -export type AssignmentResponse = z.infer -export type ResolveRequest = z.infer -export type ResolveResponse = z.infer -export type RelayMoved = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts deleted file mode 100644 index 6b8837829df..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { z } from 'zod' - -export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const - -export const RelayRegionSchema = z.enum(RELAY_REGIONS) - -export type RelayRegion = z.infer - -export const RELAY_DEFAULT_REGION: RelayRegion = 'us-central1' - -// Field-name segment for the flat per-region runtime counters, spelled out rather than derived so -// the Terraform side can hold the same literal and a test can compare the two. `satisfies` makes a -// new region a compile error here, which is the point: a region with no segment would silently -// drop out of the region-skew alert's denominators. -export const RELAY_REGION_METRIC_SEGMENTS = { - 'us-central1': 'UsCentral1', - 'asia-east2': 'AsiaEast2' -} as const satisfies Record - -const RelayProbeOriginSchema = z.string().url().max(2_048).refine(isCanonicalHttpsOrigin) - -export const RelayRegionCatalogResponseSchema = z - .object({ - v: z.literal(1), - regions: z - .array( - z - .object({ - region: RelayRegionSchema, - probeOrigins: z.array(RelayProbeOriginSchema).min(1).max(2) - }) - .strict() - ) - .max(RELAY_REGIONS.length) - }) - .strict() - .superRefine((catalog, context) => { - const regions = new Set() - const origins = new Set() - for (const [regionIndex, entry] of catalog.regions.entries()) { - if (regions.has(entry.region)) { - context.addIssue({ - code: 'custom', - message: 'duplicate relay region', - path: ['regions', regionIndex, 'region'] - }) - } - regions.add(entry.region) - for (const [originIndex, origin] of entry.probeOrigins.entries()) { - if (origins.has(origin)) { - context.addIssue({ - code: 'custom', - message: 'duplicate relay probe origin', - path: ['regions', regionIndex, 'probeOrigins', originIndex] - }) - } - origins.add(origin) - } - } - }) - -export type RelayRegionCatalogResponse = z.infer - -function isCanonicalHttpsOrigin(value: string): boolean { - try { - const url = new URL(value) - return url.protocol === 'https:' && url.origin === value - } catch { - return false - } -} diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts deleted file mode 100644 index 27dd3a8b30f..00000000000 --- a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { z } from 'zod' - -export const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) -export const Base64Url24ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/) -export const Base6432ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){10}[A-Za-z0-9+/]{3}=$/) -export const Base64Raw24ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){8}$/) -export const RelayHostIdSchema = z.string().regex(/^[A-Za-z0-9_-]{16}$/) -export const OpaqueIdSchema = z.string().min(1).max(128) -export const EpochMsSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) -export const GenerationSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) -export const PositiveDurationMsSchema = z.number().int().positive().max(24 * 60 * 60 * 1000) - -export const CanonicalHttpsOriginSchema = z.string().max(2048).refine((value) => { - try { - const url = new URL(value) - return url.protocol === 'https:' && url.origin === value && url.pathname === '/' - } catch { - return false - } -}, 'must be a canonical HTTPS origin') 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..1c04bc751a0 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 @@ -476,7 +475,7 @@ 1 test-no-wall-clock:src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts 2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts 1 test-no-wall-clock:src/main/runtime/agent-session/structured-child-records-switch.test.ts -1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts 2 test-no-wall-clock:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-device-registration-persistence.test.ts 1 test-no-wall-clock:src/main/runtime/push/push-registration-rpc.test.ts @@ -604,18 +603,18 @@ 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 2 test-timeout-needs-reason:src/main/providers/startup-line-typed-length.live-shell.test.ts 5 test-timeout-needs-reason:src/main/pty/process-retirement/node-pty-master-fd-retirement.test.ts -1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +1 test-timeout-needs-reason:src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts 1 test-timeout-needs-reason:src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts 2 test-timeout-needs-reason:src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts 1 test-timeout-needs-reason:src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 1dec6b9a0d4..17a971600e9 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -47,7 +47,7 @@ 5 src/main/persistence/restoring-sessions/session-owner-fields.ts 12 src/main/persistence/restoring-sessions/session-owner-removal.ts 2 src/main/persistence/restoring-sessions/workspace-pane-normalization.ts -4 src/main/persistence/terminal-topology/terminal-topology-membership.ts +4 src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts 1 src/main/persistence/tracking-repos/project-group-operations.ts 4 src/main/persistence/tracking-repos/repo-worktree-pruning.ts 3 src/main/persistence/tracking-repos/worktree-identity-migration.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index f68be042103..15c501db745 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 @@ -475,8 +475,8 @@ 1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts 9 src/main/runtime/host-instance-identity.ts 4 src/main/runtime/hosts/platform-probe/host-descriptor.ts -5 src/main/runtime/mobile-cloud-relay/relay-region-preference.ts -2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +5 src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts +2 src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts 1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts 2 src/main/runtime/push/push-unregister-outbox.ts 1 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.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..e48c4c98f18 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 @@ -49,7 +49,7 @@ 1 src/main/rate-limits/service/service-polling.ts 1 src/main/runtime/agent-state-rules/agent-state-rules-live-update.ts 1 src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts -3 src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +3 src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts 1 src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts 1 src/main/runtime/rpc/mobile/mobile-socket-wiring.ts 1 src/main/runtime/rpc/transports/websocket/remote-runtime-server-heartbeat.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 1ee9c681616..6bc8969b944 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." }, @@ -6193,7 +6178,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", @@ -6207,8 +6192,8 @@ "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts", "src/main/ipc/agent-hooks.test.ts", "src/main/ipc/agent-pane-authority-ownership.test.ts", - "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts", - "src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts", + "src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts", + "src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts", "src/main/pty/process-retirement/pty-descendant-termination.test.ts", "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts", diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2892db33f7b..525576adfe7 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, @@ -2526,7 +2518,6 @@ "src/main/persistence/loading-store/terminal-bindings/reused-terminal-id-unbind.test.ts": 312, "src/main/persistence/loading-store/profile-writing/state-write-round-trip.test.ts": 1983, "src/main/persistence/loading-store/workspace-sessions/store-host-partition-before-unload.test.ts": 1670, - "src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts": 5719, "src/main/persistence/loading-store/workspace-sessions/workspace-session-terminal-binding-replay.test.ts": 95, "src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization.test.ts": 127, "src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-staging.test.ts": 466, @@ -2595,43 +2586,39 @@ "src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts": 466, "src/main/persistence/runtime-authored-workspace-session-fields.test.ts": 64, "src/main/persistence/scheduling-automations/automation-run-operations.test.ts": 151, - "src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts": 289, - "src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts": 2087, - "src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts": 526, - "src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts": 1943, - "src/main/persistence/terminal-topology/pane-last-grid.test.ts": 5642, - "src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts": 1926, - "src/main/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts": 1744, - "src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts": 1841, - "src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts": 1835, - "src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts": 1961, - "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts": 5772, - "src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts": 1996, - "src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts": 1898, - "src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts": 2143, - "src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts": 1790, - "src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts": 1776, - "src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts": 1738, - "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts": 1853, - "src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts": 2079, - "src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts": 1795, - "src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts": 2870, - "src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts": 2027, + "src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts": 2087, + "src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts": 526, + "src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts": 1943, + "src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts": 5642, + "src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts": 1926, + "src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts": 1744, + "src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts": 1841, + "src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts": 1835, + "src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts": 5772, + "src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts": 1996, + "src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts": 1898, + "src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts": 2143, + "src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts": 1790, + "src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts": 1776, + "src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts": 1853, + "src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts": 2079, + "src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts": 1795, + "src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts": 2870, + "src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts": 2027, "src/main/persistence/terminal-topology/terminal-layout-apply.test.ts": 2005, - "src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts": 1773, - "src/main/persistence/terminal-topology/terminal-layout-create.test.ts": 2107, - "src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts": 1753, - "src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts": 1977, - "src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts": 2198, - "src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts": 1847, - "src/main/persistence/terminal-topology/terminal-leaf-move.test.ts": 2197, - "src/main/persistence/terminal-topology/terminal-owner-invariants.test.ts": 285, - "src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts": 1796, - "src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts": 1766, - "src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts": 1941, - "src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts": 2114, - "src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts": 1872, - "src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts": 1626, + "src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts": 1773, + "src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts": 2107, + "src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts": 1753, + "src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts": 1977, + "src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts": 2198, + "src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts": 1847, + "src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts": 2197, + "src/shared/workspace-layout/terminal-topology/terminal-owner-invariants.test.ts": 285, + "src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts": 1796, + "src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts": 1766, + "src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts": 1941, + "src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts": 2114, + "src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts": 1626, "src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.test.ts": 544, "src/main/persistence/tracking-repos/missing-local-worktree-metadata-pruning.test.ts": 619, "src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts": 2374, @@ -2992,7 +2979,6 @@ "src/main/runtime/terminal/output/headless-terminal-dispose-write-ordering.test.ts": 4309, "src/main/runtime/terminal/recovery/held-pane-reopen-layout-owner.test.ts": 5093, "src/main/runtime/terminal/wait/hermes-slash-readiness-transcript.test.ts": 4931, - "src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts": 9614, "src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts": 68, "src/main/runtime/hosts/platform-probe/host-descriptor.test.ts": 207, "src/main/runtime/terminal/surface/host-pane-remount-terminal-handle.test.ts": 5293, @@ -3008,19 +2994,17 @@ "src/main/runtime/workspaces/creation/managed-worktree-create-registry.test.ts": 4143, "src/main/runtime/workspaces/creation/managed-worktree-create-telemetry.test.ts": 4152, "src/main/runtime/workspaces/removal/missing-worktree-terminal-reconciliation.test.ts": 432, - "src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts": 48, - "src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts": 408, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts": 580, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts": 161, - "src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts": 1013, - "src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts": 701, + "src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts": 48, + "src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts": 408, + "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts": 580, + "src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts": 1013, + "src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts": 701, "src/main/runtime/mobile-cloud-relay/relay-control-origin.test.ts": 147, - "src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts": 122, - "src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts": 175, - "src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts": 196, - "src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts": 253, - "src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts": 127, - "src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts": 73, + "src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts": 122, + "src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts": 175, + "src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts": 196, + "src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts": 253, + "src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts": 73, "src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts": 804, "src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.integration.test.ts": 11377, "src/main/runtime/mobile-desktop-relay/mobile-desktop-relay.test.ts": 1185, @@ -3050,8 +3034,6 @@ "src/main/runtime/browser/screencast/orca-runtime-browser-screencast-fanout.test.ts": 607, "src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts": 682, "src/main/runtime/terminal/query/orca-runtime-codex-idle-title-chat-address.test.ts": 5781, - "src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts": 4130, - "src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts": 3716, "src/main/runtime/terminal/wait/orca-runtime-exact-worker-provider-session.test.ts": 3617, "src/main/runtime/terminal/lifecycle/orca-runtime-exited-split-pane-close.test.ts": 4235, "src/main/runtime/files/orca-runtime-files-preview-budget.test.ts": 672, @@ -3517,7 +3499,6 @@ "src/main/runtime/rpc/server/runtime-rpc-browser-host-admission.test.ts": 4402, "src/main/runtime/rpc/server/runtime-rpc-delegated-device-sync.test.ts": 4986, "src/main/runtime/rpc/server/runtime-rpc-device-key-dispatch.test.ts": 3597, - "src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts": 5350, "src/main/runtime/rpc/server/runtime-rpc-local-disconnect-forwarding.test.ts": 5138, "src/main/runtime/rpc/server/runtime-rpc-long-poll-transport.test.ts": 30838, "src/main/runtime/rpc/server/runtime-rpc-metadata-lifecycle.test.ts": 4652, @@ -3550,8 +3531,6 @@ "src/main/runtime/workspaces/lineage/runtime-worktree-lineage-controller.test.ts": 1027, "src/main/runtime/workspaces/startup/runtime-worktree-startup-readiness.test.ts": 289, "src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts": 1412, - "src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts": 321, - "src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts": 5010, "src/main/runtime/session-lifecycle/close/close-mobile-row-in-main-layout.test.ts": 4514, "src/main/runtime/session-lifecycle/projection/pane-sleeping-record.test.ts": 76, "src/main/runtime/session-lifecycle/projection/sleep-record-pane-claim.test.ts": 48, @@ -3640,7 +3619,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, @@ -3661,7 +3639,6 @@ "src/main/runtime/terminal/stop/exact-terminal-stop-liveness.test.ts": 4321, "src/main/runtime/terminal/stop/terminal-update-admission.test.ts": 48, "src/main/runtime/terminal/surface/closed-pane-exit-cleanup-main.test.ts": 4281, - "src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts": 4330, "src/main/runtime/terminal/surface/terminal-surface-replies-main.test.ts": 4324, "src/main/runtime/terminal/wait/tui-idle-codex-plan-menu.test.ts": 4441, "src/main/runtime/terminal/wait/tui-idle-command-paint.test.ts": 4148, @@ -3676,8 +3653,6 @@ "src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts": 2136, "src/main/runtime/terminal/surface/workspace-layout-stream.test.ts": 427, "src/main/runtime/terminal/surface/workspace-session-membership-scaling.test.ts": 72, - "src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts": 6111, - "src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts": 12352, "src/main/runtime/workspaces/lifecycle/workspace-lifecycle-queue.test.ts": 116, "src/main/runtime/workspaces/sleep/workspace-sleep-execution.test.ts": 110, "src/main/runtime/workspaces/startup/worktree-agent-first-surface.test.ts": 5816, @@ -3796,7 +3771,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, @@ -4223,7 +4197,6 @@ "src/preload/renderer-heap-statistics-reader.test.ts": 50, "src/preload/renderer-process-memory-reader.test.ts": 66, "src/preload/renderer-restart-wiring.test.ts": 96, - "src/preload/runtime-environment-subscriptions.test.ts": 71, "src/preload/ssh-authority-forwarding.test.ts": 1111, "src/preload/updater-package-recovery.test.ts": 1102, "src/preload/usage-provider-api.test.ts": 46, @@ -6368,7 +6341,6 @@ "src/shared/git/worktrees/git-worktree-admin.test.ts": 161, "src/shared/github/account-binding.test.ts": 48, "src/shared/github/api-availability.test.ts": 47, - "src/shared/source-control/review-comments/pr-comments-resolution-prompt.test.ts": 49, "src/shared/github/project-board-columns.test.ts": 64, "src/shared/github/project-identity.test.ts": 33, "src/shared/github/project-ref-input.test.ts": 40, @@ -6596,16 +6568,12 @@ "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, "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, "src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198, "src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168, @@ -6617,21 +6585,14 @@ "src/shared/plugins/declarative/runtime/declarative-storage-sync.test.ts": 190, "src/shared/plugins/declarative/testing/orca-testing-hooks.test.ts": 506, "src/shared/plugins/declarative/testing/orca-testing-worker.test.ts": 480, - "src/shared/plugins/declarative/testing/orca-testing.test.ts": 489, "src/shared/plugins/declarative/testing/testing-editor-host.test.ts": 197, "src/shared/plugins/frames/plugin-frame-document-session.test.ts": 404, "src/shared/plugins/frames/plugin-frame-document.test.ts": 426, - "src/shared/plugins/frames/plugin-frame-facades.test.ts": 383, - "src/shared/plugins/frames/plugin-frame-guest.test.ts": 50, "src/shared/plugins/frames/plugin-panel-call-admission.test.ts": 89, - "src/shared/plugins/frames/plugin-panel-message-budget.test.ts": 99, "src/shared/plugins/frames/plugin-panel-shell.test.ts": 376, "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, "src/shared/plugins/manifest/plugin-manifest.test.ts": 234, "src/shared/plugins/view/plugin-editor-shot-acts.test.ts": 112, diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs index 8613ec9468f..587377b53fc 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs @@ -45,7 +45,6 @@ export const UNIT_EXCLUDE = [ 'src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts', 'src/shared/startup-shell-portability.live-shell.test.ts', 'src/shared/posix-command-path-lookup.test.ts', - 'tests/e2e/relay-region-compatibility.unit.test.ts', 'tests/e2e/relay-region-correction.unit.test.ts', 'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts', // Electron probes with in-process deadlines; the package job runs them serially. 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/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index 8b639caf0d7..669928bd511 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -141,7 +141,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts', 'src/main/runtime/agent-session/records/structured-agent-session-startup-tab-restore.test.ts', 'src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts', - 'src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts', + 'src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts', 'src/main/ipc/filesystem/watchers/filesystem-watcher-ignore-real.test.ts', 'src/main/ipc/runtime-environments/runtime-environment-preference.test.ts', 'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx', 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/docs/site/content/docs/cli/computer-use.mdx b/docs/site/content/docs/cli/computer-use.mdx index be075f766f0..44ad60afec2 100644 --- a/docs/site/content/docs/cli/computer-use.mdx +++ b/docs/site/content/docs/cli/computer-use.mdx @@ -37,7 +37,19 @@ 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 + +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 @@ -75,7 +87,9 @@ 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. -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 `` controls are set with `set-value` instead of a click. On Linux, clicks, scrolling, drags and keyboard input still bring the window forward. On Windows, element clicks, `set-value` (including sliders), element scrolls and secondary actions (`Invoke`, `Toggle`, `Select`, `Expand`, `Collapse`, `ScrollToVisible`) go through UI Automation when the control supports them, without moving the pointer or sending keys. Some apps still bring their own window forward when driven this way (WPF apps do for most of these), so `action.delivery` reports `foreground` whenever the target window came forward. Anything else brings the window forward. When accessibility targeting fails, fall back carefully to coordinates: diff --git a/mobile/src/components/SmartWorkspaceSourceRow.test.tsx b/mobile/src/components/SmartWorkspaceSourceRow.test.tsx new file mode 100644 index 00000000000..c3f37566639 --- /dev/null +++ b/mobile/src/components/SmartWorkspaceSourceRow.test.tsx @@ -0,0 +1,45 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { SmartWorkspaceSourceRow } from './SmartWorkspaceSourceRow' + +vi.mock('react-native', () => ({ Text: 'Text', View: 'View' })) +vi.mock('lucide-react-native', () => ({ GitBranch: 'Icon', Sparkles: 'Icon' })) +vi.mock('../theme/mobile-theme', () => ({ colors: {}, radii: {}, spacing: {} })) +vi.mock('../theme/themed-styles', () => ({ themedStyleSheet: (make: () => unknown) => make() })) +vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'dark' })) +vi.mock('../i18n/use-mobile-translation', () => ({ + useMobileTranslation: () => (_key: string, fallback: string) => fallback +})) +vi.mock('./TaskProviderLogo', () => ({ TaskProviderLogo: () => null })) +vi.mock('./list/ListGroup', () => ({ ListRow: 'ListRow' })) +let renderer: ReactTestRenderer + +afterEach(() => { + act(() => renderer?.unmount()) +}) + +it('renders a natural remote label without a namespace subtitle and keeps collision qualification', async () => { + const onPress = vi.fn() + const row = { + kind: 'branch' as const, + value: 'branch-refs/remotes/origin/topic', + refName: 'refs/remotes/origin/topic', + localBranchName: 'topic' + } + await act(async () => { + renderer = create(createElement(SmartWorkspaceSourceRow, { row, onPress })) + }) + expect(renderer.toJSON()).toMatchObject({ props: { title: 'origin/topic', subtitle: 'topic' } }) + await act(async () => { + renderer.update( + createElement(SmartWorkspaceSourceRow, { + row: { ...row, label: 'refs/remotes/origin/topic' }, + onPress + }) + ) + }) + expect(renderer.toJSON()).toMatchObject({ + props: { title: 'refs/remotes/origin/topic', subtitle: 'topic' } + }) +}) diff --git a/mobile/src/components/SmartWorkspaceSourceRow.tsx b/mobile/src/components/SmartWorkspaceSourceRow.tsx index b97379e6128..3af8c135f86 100644 --- a/mobile/src/components/SmartWorkspaceSourceRow.tsx +++ b/mobile/src/components/SmartWorkspaceSourceRow.tsx @@ -1,3 +1,4 @@ +import { branchRefLabel } from '../../../src/shared/git/refs/branch-ref-label' import { Text, View } from 'react-native' import { GitBranch, Sparkles } from 'lucide-react-native' import type { SmartWorkspaceSourceRow as SourceRow } from '../../../src/shared/new-workspace/smart-workspace-source-results' @@ -70,8 +71,9 @@ function resolveRowContent(row: SourceRow, t: Translate): RowContent { case 'branch': return { icon: , - title: row.localBranchName || row.refName, - subtitle: row.refName + title: row.label ?? branchRefLabel(row.refName), + subtitle: + row.localBranchName !== branchRefLabel(row.refName) ? row.localBranchName : undefined } case 'linear': return { diff --git a/mobile/src/files/session-documents/mobile-file-tap-open.test.ts b/mobile/src/files/session-documents/mobile-file-tap-open.test.ts index c436160748c..778676c0d8e 100644 --- a/mobile/src/files/session-documents/mobile-file-tap-open.test.ts +++ b/mobile/src/files/session-documents/mobile-file-tap-open.test.ts @@ -9,21 +9,6 @@ function ok(result: unknown): RpcResponse { return { id: 'rpc', ok: true, result, _meta: { runtimeId: 'runtime-1' } } } -function createClient(responses: (RpcResponse | Error)[]) { - return { - sendRequest: vi.fn(async (method) => { - const response = responses.shift() - if (!response) { - throw new Error(`no scripted response for ${method}`) - } - if (response instanceof Error) { - throw response - } - return response - }) - } -} - function activeTerminalState(activated: boolean) { return { activated, @@ -92,14 +77,6 @@ describe('openMobileFileTap', () => { .map(([, params]) => params) } - it('opens the longest terminal reading that exists, as desktop does', async () => { - const opened = await openTerminalReadings( - ['src/index.ts', 'src/index.ts.map', 'src/index.ts.map.bak'], - new Set(['src/index.ts', 'src/index.ts.map']) - ) - expect(opened).toEqual([{ worktree: 'id:wt-1', relativePath: 'src/index.ts.map' }]) - }) - it('still checks the real path behind hundreds of hard-wrap guesses', async () => { const guesses = Array.from({ length: 210 }, (_, index) => `src/file${index}.tssrc/next.ts`) const opened = await openTerminalReadings( @@ -108,94 +85,4 @@ describe('openMobileFileTap', () => { ) expect(opened).toEqual([{ worktree: 'id:wt-1', relativePath: 'src/file19.ts' }]) }) - - it('does not navigate an absolute artifact after the user leaves the source terminal', async () => { - let resolveRequest: (value: RpcResponse) => void = () => {} - const client = { - sendRequest: vi.fn( - () => - new Promise((resolve) => { - resolveRequest = resolve - }) - ) - } - let activeTerminalHandle: string | null = 'terminal-1' - const pushPreviewRoute = vi.fn() - - openMobileFileTap({ - client, - hostId: 'host-1', - worktreeId: 'wt-1', - candidates: [{ pathText: '/tmp/result.json', line: null, column: null }], - terminalHandle: 'terminal-1', - pushPreviewRoute, - openBrowser: vi.fn(), - triggerOpenFeedback: vi.fn(), - fetchSessionTabs: vi.fn(), - getSessionTabs: () => [], - getActiveSessionTabId: () => null, - getActivationState: (activated) => ({ - ...activeTerminalState(activated), - activeTerminalHandle - }), - switchSessionTab: vi.fn(), - scheduleDelayedAction: vi.fn() - }) - - activeTerminalHandle = 'terminal-2' - resolveRequest( - ok({ - worktree: 'wt-1', - relativePath: null, - absolutePath: '/tmp/result.json', - exists: true, - isDirectory: false, - openTarget: { - kind: 'absolute-file', - provider: 'local', - absolutePath: '/tmp/result.json', - grantId: 'grant-1' - } - }) - ) - await vi.advanceTimersByTimeAsync(0) - - expect(pushPreviewRoute).not.toHaveBeenCalled() - }) - - it('does not report a stale failure after a newer tap supersedes it', async () => { - const client = createClient([ - ok({ - worktree: 'wt-1', - relativePath: null, - absolutePath: null, - exists: false, - isDirectory: false - }) - ]) - const onOpenFailed = vi.fn() - - openMobileFileTap({ - client, - hostId: 'host-1', - worktreeId: 'wt-1', - candidates: [{ pathText: 'gone/missing.ts', line: null, column: null }], - pushPreviewRoute: vi.fn(), - openBrowser: vi.fn(), - triggerOpenFeedback: vi.fn(), - fetchSessionTabs: vi.fn(), - getSessionTabs: () => [], - getActiveSessionTabId: () => null, - getActivationState: (activated) => ({ - ...activeTerminalState(activated), - latestActivationSeq: 2 - }), - switchSessionTab: vi.fn(), - scheduleDelayedAction: vi.fn(), - onOpenFailed - }) - await vi.advanceTimersByTimeAsync(0) - - expect(onOpenFailed).not.toHaveBeenCalled() - }) }) diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 4147e76f1cc..ee677e5aca6 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -3936,7 +3936,10 @@ "planAgentUnsupported": "Agent \"{{agent}}\" does not support AI commit messages.", "planModelUnavailable": "Model \"{{model}}\" is not available for {{label}}.", "planModelWithoutThinking": "Model \"{{model}}\" does not support a thinking effort level.", - "planThinkingLevelInvalid": "Thinking level \"{{level}}\" is not valid for {{model}}." + "planThinkingLevelInvalid": "Thinking level \"{{level}}\" is not valid for {{model}}.", + "commandTemplateEmptyDictationCleanup": "Command template is empty for dictation cleanup.", + "dictationCleanupAgentUnsupported": "Choose a supported agent for AI cleanup in Settings -> Voice -> Cleanup. Supported agents: {{agents}}, or Custom command.", + "agentCannotGenerateDictationCleanup": "Agent \"{{agent}}\" does not support dictation cleanup. Supported agents: {{agents}}, or Custom command." }, "conflictActions": { "resolveFile": "{{action}}: {{path}}", diff --git a/mobile/src/navigation/host-stack-navigation.test.ts b/mobile/src/navigation/host-stack-navigation.test.ts index 64f99b4b3cc..dc0cf52af11 100644 --- a/mobile/src/navigation/host-stack-navigation.test.ts +++ b/mobile/src/navigation/host-stack-navigation.test.ts @@ -1,17 +1,9 @@ import { describe, expect, it, vi } from 'vitest' import { coordinateHostStackNavigation, - navigateToHostStackRoute, type HostStackNavigationState } from './host-stack-navigation' -const TARGET = { name: '[hostId]/tasks', params: { hostId: 'host/one' } } as const -const OTHER_TARGET = { - name: '[hostId]/session/[worktreeId]', - params: { hostId: 'host/one', worktreeId: 'repo::/tmp/wt' } -} as const - -// Remove listeners for real so teardown is tested instead of merely the active guard. function navigationHarness(initialState: HostStackNavigationState | undefined) { const stateListeners = new Set<() => void>() let state = initialState @@ -57,58 +49,6 @@ function committedHostState(hostIdParam: string): HostStackNavigationState { } describe('host stack navigation', () => { - it('stops listening and never replaces once canceled', () => { - const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) - - const controller = navigateToHostStackRoute( - harness.navigation, - { push: vi.fn(), replace: vi.fn() }, - 'host/one', - TARGET - ) - expect(harness.listenerCount()).toBe(1) - controller.cancel() - - expect(harness.unsubscribe).toHaveBeenCalledTimes(1) - expect(harness.listenerCount()).toBe(0) - expect(controller.isActive()).toBe(false) - - harness.setState(committedHostState('host/one')) - expect(harness.navigation.dispatch).not.toHaveBeenCalled() - }) - - it('retargets a still-pending transition to the same host instead of pushing twice', () => { - const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) - const push = vi.fn() - const router = { push, replace: vi.fn() } - - const pending = coordinateHostStackNavigation( - null, - harness.navigation, - router, - 'host/one', - TARGET - ) - const retargeted = coordinateHostStackNavigation( - pending, - harness.navigation, - router, - 'host/one', - OTHER_TARGET - ) - - expect(retargeted).toBe(pending) - expect(push).toHaveBeenCalledTimes(1) - expect(harness.listenerCount()).toBe(1) - - harness.setState(committedHostState('host/one')) - - expect(harness.navigation.dispatch).toHaveBeenCalledTimes(1) - expect(harness.navigation.dispatch).toHaveBeenCalledWith( - expect.objectContaining({ payload: OTHER_TARGET }) - ) - }) - describe('a session opened inside its host document', () => { const SESSION = { name: '[hostId]/session/[worktreeId]', @@ -155,27 +95,5 @@ describe('host stack navigation', () => { ] ]) }) - - it('lets another screen tapped while the push commits take the list place', () => { - const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] }) - const push = vi.fn() - const router = { push, replace: vi.fn() } - - const pending = coordinateHostStackNavigation( - null, - harness.navigation, - router, - 'host/one', - SESSION, - true - ) - coordinateHostStackNavigation(pending, harness.navigation, router, 'host/one', TARGET) - harness.setState(committedHostState('host/one')) - - expect(push).toHaveBeenCalledTimes(1) - expect(harness.navigation.dispatch.mock.calls).toEqual([ - [{ type: 'REPLACE', target: '/h', source: 'host-index', payload: TARGET }] - ]) - }) }) }) diff --git a/mobile/src/new-workspace/source-selection/smart-source-search-requests.ts b/mobile/src/new-workspace/source-selection/smart-source-search-requests.ts index a422f5b8692..ea998a34180 100644 --- a/mobile/src/new-workspace/source-selection/smart-source-search-requests.ts +++ b/mobile/src/new-workspace/source-selection/smart-source-search-requests.ts @@ -1,3 +1,4 @@ +import { legacyBaseRefSearchResult } from '../../../../src/shared/base-ref-search-result' import type { GitHubWorkItem } from '../../../../src/shared/github/work-items/work-item-types' import type { GitLabWorkItem } from '../../../../src/shared/gitlab-types' import type { LinearIssue } from '../../../../src/shared/linear/issue-types' @@ -124,8 +125,5 @@ export async function searchBranches( { timeoutMs: 30_000 } ) const result = repoBaseRefSearchRead.interpret(reply) - return ( - result.refDetails ?? - (result.refs ?? []).map((refName) => ({ refName, localBranchName: refName })) - ) + return result.refDetails ?? (result.refs ?? []).map(legacyBaseRefSearchResult) } diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx index bdca6cc312b..6d586d03903 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatUsageLimitStatus.tsx @@ -43,14 +43,19 @@ export function MobileNativeChatUsageLimitStatus({ const { usageLimit, openAccounts } = useContext(MobileNativeChatNoticeContext) const failure = readWholeAgentSessionFailureFact(notice.failure) const resetsAt = failure?.kind === 'usageLimitReached' ? failure.usageLimit?.resetsAt : undefined - const resetPassed = useResetPassed(resetsAt) const actions = failure?.kind === 'usageLimitReached' && notice.usageLimitTurnItemId !== undefined && usageLimit?.turnItemId === notice.usageLimitTurnItemId ? usageLimit : null - // The line names the reset Orca waits for; Continue still keys off the cut's own reset. + // Continue applies at the cut's own reset, or earlier once the host says the chat moved accounts. + const resetPassed = useResetPassed( + resetsAt !== undefined && actions?.continueAt !== undefined + ? Math.min(resetsAt, actions.continueAt) + : resetsAt + ) + // The line names the reset Orca waits for. const shownAt = actions?.autoContinue ? (actions.continueAt ?? resetsAt) : resetsAt const shownPassed = useResetPassed(shownAt) if (failure?.kind !== 'usageLimitReached') { diff --git a/mobile/src/source-control/dictation-cleanup-failure-copy.ts b/mobile/src/source-control/dictation-cleanup-failure-copy.ts new file mode 100644 index 00000000000..b343d74f474 --- /dev/null +++ b/mobile/src/source-control/dictation-cleanup-failure-copy.ts @@ -0,0 +1,25 @@ +import type { TextGenerationFailureCode } from '../../../src/shared/text-generation-failure-copy' +import { translate } from '../i18n/mobile-i18n' + +export const DICTATION_CLEANUP_FAILURE_COPY = { + commandTemplateEmptyDictationCleanup: (values) => + translate( + 'sourceControl.textGenerationFailure.commandTemplateEmptyDictationCleanup', + 'Command template is empty for dictation cleanup.', + values + ), + dictationCleanupAgentUnsupported: (values) => + translate( + 'sourceControl.textGenerationFailure.dictationCleanupAgentUnsupported', + 'Choose a supported agent for AI cleanup in Settings -> Voice -> Cleanup. Supported agents: {{agents}}, or Custom command.', + values + ), + agentCannotGenerateDictationCleanup: (values) => + translate( + 'sourceControl.textGenerationFailure.agentCannotGenerateDictationCleanup', + 'Agent "{{agent}}" does not support dictation cleanup. Supported agents: {{agents}}, or Custom command.', + values + ) +} satisfies Partial< + Record) => string> +> diff --git a/mobile/src/source-control/mobile-pr-create-draft.ts b/mobile/src/source-control/mobile-pr-create-draft.ts index d2431ffabde..ae5f965dc7e 100644 --- a/mobile/src/source-control/mobile-pr-create-draft.ts +++ b/mobile/src/source-control/mobile-pr-create-draft.ts @@ -1,3 +1,4 @@ +import { legacyBaseRefSearchResult } from '../../../src/shared/base-ref-search-result' import { translate } from '../i18n/mobile-i18n' import { refusedRpcMessageOrFallback } from '../transport/rpc/rpc-refusal-message' import type { UnvalidatedRpcRequestPort } from '../transport/rpc/unvalidated-rpc-request-port' @@ -137,7 +138,7 @@ export async function searchMobilePrBaseRefs( ) const result = repoBaseRefSearchRead.interpret(reply) return normalizeCreateReviewBaseSearchResults( - result.refDetails ?? (result.refs ?? []).map((refName) => ({ refName, localBranchName: '' })) + result.refDetails ?? (result.refs ?? []).map(legacyBaseRefSearchResult) ) } diff --git a/mobile/src/source-control/text-generation-failure-copy.test.ts b/mobile/src/source-control/text-generation-failure-copy.test.ts deleted file mode 100644 index 379714e3ad3..00000000000 --- a/mobile/src/source-control/text-generation-failure-copy.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { activateMobileUiLocale, mobileI18n } from '../i18n/mobile-i18n' -import { textGenerationErrorText } from './text-generation-failure-copy' - -beforeEach(async () => { - mobileI18n.addResourceBundle('de', 'translation', { - 'sourceControl.textGenerationFailure.cliFailedWithDetail': - '{{label}} fehlgeschlagen ({{exitCode}}): {{detail}}', - 'sourceControl.textGenerationFailure.noStagedChanges': 'Keine Änderungen vorgemerkt.', - 'sourceControl.textGenerationFailure.planModelUnavailable': - 'Modell {{model}} für {{label}} nicht verfügbar.', - 'sourceControl.textGenerationFailure.kimiConflictingOptions': - 'Kimi: {{option}} und {{otherOption}} widersprechen sich.' - }) - await activateMobileUiLocale('de') -}) - -afterEach(async () => { - await activateMobileUiLocale('en') - mobileI18n.removeResourceBundle('de', 'translation') -}) - -describe('textGenerationErrorText', () => { - it('translates coded failures and preserves agent output verbatim', () => { - expect( - textGenerationErrorText({ - error: 'host error', - errorCode: 'cliFailedWithDetail', - errorParams: { label: 'Codex', exitCode: 0, detail: 'ignored' }, - errorDetail: '{{label}}: $t(secret) ' - }) - ).toBe('Codex fehlgeschlagen (0): {{label}}: $t(secret) ') - expect(textGenerationErrorText({ error: 'host error', errorCode: 'noStagedChanges' })).toBe( - 'Keine Änderungen vorgemerkt.' - ) - }) - - it.each([ - {}, - { errorCode: 'newerHostCode' }, - { errorCode: 'toString' }, - { errorCode: 42 }, - { errorCode: 'cliFailedWithDetail', errorParams: { label: 'Codex', exitCode: 1 } }, - { - errorCode: 'cliFailedWithDetail', - errorParams: { label: 'Codex', exitCode: null }, - errorDetail: 'detail' - }, - { - errorCode: 'cliFailedWithDetail', - errorParams: { label: 'Codex', exitCode: 1, detail: 'not errorDetail' } - }, - { errorCode: 'agentCouldNotStart', errorParams: 'Codex' } - ])('keeps the host error when the code or required values are unavailable: %j', (fields) => { - expect(textGenerationErrorText({ error: 'Host English', ...fields })).toBe('Host English') - }) -}) diff --git a/mobile/src/source-control/text-generation-failure-copy.ts b/mobile/src/source-control/text-generation-failure-copy.ts index be32494f6e6..c50f7eada9e 100644 --- a/mobile/src/source-control/text-generation-failure-copy.ts +++ b/mobile/src/source-control/text-generation-failure-copy.ts @@ -5,6 +5,7 @@ import { import { translate } from '../i18n/mobile-i18n' import { AGENT_OUTPUT_FAILURE_COPY } from './agent-output-failure-copy' import { TEXT_GENERATION_PLAN_FAILURE_COPY } from './text-generation-plan-failure-copy' +import { DICTATION_CLEANUP_FAILURE_COPY } from './dictation-cleanup-failure-copy' type CopyValues = Record @@ -256,7 +257,8 @@ const COPY: Record string> = values ), ...TEXT_GENERATION_PLAN_FAILURE_COPY, - ...AGENT_OUTPUT_FAILURE_COPY + ...AGENT_OUTPUT_FAILURE_COPY, + ...DICTATION_CLEANUP_FAILURE_COPY } function isTextGenerationFailureCode(code: unknown): code is TextGenerationFailureCode { diff --git a/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-create-drawer.tsx b/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-create-drawer.tsx index 83fb92aa837..dcbc1333ac3 100644 --- a/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-create-drawer.tsx +++ b/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-create-drawer.tsx @@ -1,3 +1,4 @@ +import { branchRefLabel } from '../../../../src/shared/git/refs/branch-ref-label' import type { ConnectionPresentationModel } from '../screen-state/use-mobile-tasks-connection-presentation' import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer' import { View, Text } from 'react-native' @@ -146,12 +147,14 @@ export function renderMobileTasksWorkspaceCreateDrawer(model: ConnectionPresenta key="startFrom" title={translate('tasks.workspaceCreateDrawer.startFrom', 'Start from')} value={ - workspaceBaseBranch?.refName ?? + (workspaceBaseBranch ? branchRefLabel(workspaceBaseBranch.refName) : null) ?? translate('tasks.workspaceCreateDrawer.defaultBranch', 'Default branch') } navigates onPress={() => { - setWorkspaceBaseBranchQuery(workspaceBaseBranch?.refName ?? '') + setWorkspaceBaseBranchQuery( + workspaceBaseBranch ? branchRefLabel(workspaceBaseBranch.refName) : '' + ) setShowWorkspaceBaseBranchPicker(true) }} /> diff --git a/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-option-pickers.tsx b/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-option-pickers.tsx index 768d0cce684..04a5632b933 100644 --- a/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-option-pickers.tsx +++ b/mobile/src/tasks/workspace-creation/mobile-tasks-workspace-option-pickers.tsx @@ -1,3 +1,4 @@ +import { branchRefLabels, branchRefLabel } from '../../../../src/shared/git/refs/branch-ref-label' import type { ConnectionPresentationModel } from '../screen-state/use-mobile-tasks-connection-presentation' import { BottomDrawer } from '../../components/bottom-drawer/BottomDrawer' import { View, Text, Pressable, ActivityIndicator } from 'react-native' @@ -24,6 +25,7 @@ export function renderMobileTasksWorkspaceBaseBranchPicker(model: ConnectionPres workspaceBaseBranchResults, workspaceCreateDraft } = model + const labels = branchRefLabels(workspaceBaseBranchResults.map((branch) => branch.refName)) return ( ( ({ refName, localBranchName: refName })) + result.refDetails ?? (result.refs ?? []).map(legacyBaseRefSearchResult) ) }) .catch((err) => { diff --git a/mobile/src/terminal/terminal-accessory-keys.test.ts b/mobile/src/terminal/terminal-accessory-keys.test.ts deleted file mode 100644 index ddf5d586082..00000000000 --- a/mobile/src/terminal/terminal-accessory-keys.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { buildTerminalShortcutKey } from './terminal-accessory-keys' - -describe('TERMINAL_ACCESSORY_KEYS', () => { - it('builds Ctrl, Alt, and Shift printable shortcut bytes', () => { - expect(buildTerminalShortcutKey({ key: 'c', modifiers: ['ctrl'] })).toEqual({ - label: 'Ctrl+C', - bytes: '\x03', - accessibilityLabel: 'Ctrl C' - }) - expect(buildTerminalShortcutKey({ key: 'k', modifiers: ['ctrl', 'alt'] })).toEqual({ - label: 'Ctrl+Alt+K', - bytes: '\x1b\x0b', - accessibilityLabel: 'Ctrl Alt K' - }) - expect(buildTerminalShortcutKey({ key: '1', modifiers: ['alt', 'shift'] })).toEqual({ - label: 'Alt+Shift+1', - bytes: '\x1b!', - accessibilityLabel: 'Alt Shift 1' - }) - }) - - it('builds custom Space shortcut bytes with terminal modifiers', () => { - expect(buildTerminalShortcutKey({ key: 'space', modifiers: [] })).toEqual({ - label: 'Space', - bytes: ' ', - accessibilityLabel: 'Space' - }) - expect(buildTerminalShortcutKey({ key: 'space', modifiers: ['ctrl'] })).toEqual({ - label: 'Ctrl+Space', - bytes: '\x00', - accessibilityLabel: 'Ctrl Space' - }) - expect(buildTerminalShortcutKey({ key: 'space', modifiers: ['alt'] })).toEqual({ - label: 'Alt+Space', - bytes: '\x1b ', - accessibilityLabel: 'Alt Space' - }) - }) - - it('builds modified special-key terminal sequences', () => { - expect(buildTerminalShortcutKey({ key: 'tab', modifiers: ['shift'] })).toEqual({ - label: 'Shift+Tab', - bytes: '\x1b[Z', - accessibilityLabel: 'Shift Tab' - }) - expect(buildTerminalShortcutKey({ key: 'enter', modifiers: [] })).toEqual({ - label: 'Enter', - bytes: '\r', - accessibilityLabel: 'Enter' - }) - expect(buildTerminalShortcutKey({ key: 'arrowRight', modifiers: ['ctrl', 'shift'] })).toEqual({ - label: 'Ctrl+Shift+→', - bytes: '\x1b[1;6C', - accessibilityLabel: 'Ctrl Shift →' - }) - expect(buildTerminalShortcutKey({ key: 'delete', modifiers: ['alt'] })).toEqual({ - label: 'Alt+Del', - bytes: '\x1b[3;3~', - accessibilityLabel: 'Alt Del' - }) - }) - - it('builds function-key terminal sequences', () => { - expect(buildTerminalShortcutKey({ key: 'f1', modifiers: [] })).toEqual({ - label: 'F1', - bytes: '\x1bOP', - accessibilityLabel: 'F1' - }) - expect(buildTerminalShortcutKey({ key: 'f5', modifiers: ['shift'] })).toEqual({ - label: 'Shift+F5', - bytes: '\x1b[15;2~', - accessibilityLabel: 'Shift F5' - }) - }) - - it('rejects control combinations that terminals cannot encode as control bytes', () => { - expect(buildTerminalShortcutKey({ key: '1', modifiers: ['ctrl'] })).toBeNull() - }) -}) diff --git a/native/computer-use-linux/runtime.py b/native/computer-use-linux/runtime.py index b276ecd05dc..5e5fa614185 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), @@ -474,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 "" @@ -492,15 +511,15 @@ 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 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) @@ -515,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) @@ -1189,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, ) @@ -1264,7 +1288,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, @@ -1861,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 5c31d6126f4..207d2de3410 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)] @@ -684,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 4ca1844479e..5e26673b3c6 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 { @@ -553,6 +591,7 @@ final class Provider { "annotatedScreenshot": false, "elementFrames": true, "ocr": false, + "disabledState": true, ], "actions": [ "click": true, @@ -657,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 { @@ -702,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 @@ -724,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() ) } @@ -750,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), ] @@ -813,6 +876,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 +896,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 +935,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 +987,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 +1001,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") } @@ -948,14 +1047,16 @@ final class Provider { private func typeText(params: [String: JSONValue]) throws -> [String: Any] { let snapshot = try currentKeyboardSnapshot(params: params) let text = try requiredString(params, "text") - if let focused = focusedRecord(snapshot), let verification = try TextInput.replaceSelection(focused.element, with: text) { + let focused = focusedRecord(snapshot)?.element + if let focused, let verification = try TextInput.replaceSelection(focused, with: text) { return actionMetadata(path: "accessibility", actionName: "AXReplaceSelection", verification: verification) } + let insertion = TextInput.Insertion(into: focused, text: text) try deliverKeys(try withTransportErrors { try BackgroundInputTransport.textEvents(text) }, snapshot: snapshot, params: params) return actionMetadata( path: "synthetic", actionName: "typeText", - verification: unverifiedAction(reason: "synthetic_input") + verification: insertion?.verification() ?? unverifiedAction(reason: "synthetic_input") ) } @@ -990,17 +1091,19 @@ final class Provider { private func pasteText(params: [String: JSONValue]) throws -> [String: Any] { let snapshot = try currentKeyboardSnapshot(params: params) let text = try requiredString(params, "text") - if let focused = focusedRecord(snapshot), let verification = try TextInput.replaceSelection(focused.element, with: text) { + let focused = focusedRecord(snapshot)?.element + if let focused, let verification = try TextInput.replaceSelection(focused, with: text) { return actionMetadata(path: "accessibility", actionName: "AXReplaceSelection", verification: verification) } let pasteKeys = try Input.keyEvents("cmd+v") + let insertion = TextInput.Insertion(into: focused, text: text) try Input.withPasteboardText(text) { try deliverKeys(pasteKeys, snapshot: snapshot, params: params) } return actionMetadata( path: "clipboard", actionName: "paste", - verification: unverifiedAction(reason: "clipboard_paste") + verification: insertion?.verification() ?? unverifiedAction(reason: "clipboard_paste") ) } @@ -1425,6 +1528,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 { @@ -1980,6 +2095,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? @@ -2054,15 +2257,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") } @@ -2106,15 +2312,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" @@ -2165,9 +2362,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 } @@ -2190,9 +2385,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" @@ -2200,14 +2394,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" @@ -3094,6 +3300,49 @@ private enum TextInput { return verifiedAction(property: "focusedText") } + /// Text sent as keys or a paste: what the focused field should read once it lands. + struct Insertion { + let element: AXUIElement + let expected: String + + /// Nil when the field can't prove the result: none focused, a secure field, no readable value and selection, or text a readback can't confirm. + init?(into element: AXUIElement?, text: String) { + guard let element, + !AXSnapshotReader().isSecureTextElement(element), + let current = rawStringAttribute(element, kAXValueAttribute as String), + // Why: settle re-reads the whole value every 25 ms; a terminal's scrollback or a long document is too costly. + current.utf16.count <= 64 * 1024 + else { + return nil + } + let selection = TextInput.selectedTextRange(element).flatMap { range -> Range? in + range.location >= 0 && range.length >= 0 && range.length <= Int.max - range.location + ? range.location..<(range.location + range.length) : nil + } + guard let expected = TextInsertionReadback.expectedValue(current: current, selection: selection, inserting: text) else { + return nil + } + self.element = element + self.expected = expected + } + + /// Nil when the readback can't tell: the field stopped answering or was still changing at the cap. + func verification() -> [String: Any]? { + let outcome = TextInsertionReadback.settle(expected: expected) { + rawStringAttribute(element, kAXValueAttribute as String) + } + switch outcome { + case .landed: + return verifiedAction(property: "focusedText") + case .mismatch: + // Why: the field may hold part of the text, so the result never shows what it reads. + return unverifiedAction(reason: "text_mismatch") + case .undetermined: + return nil + } + } + } + static func selectAll(_ element: AXUIElement) -> Bool { guard let current = rawStringAttribute(element, kAXValueAttribute as String) else { return false 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/Sources/OrcaComputerUseMacOSCore/TextInsertionReadback.swift b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/TextInsertionReadback.swift new file mode 100644 index 00000000000..8a27da80932 --- /dev/null +++ b/native/computer-use-macos/Sources/OrcaComputerUseMacOSCore/TextInsertionReadback.swift @@ -0,0 +1,81 @@ +import Foundation + +/// Checks that text sent as keys or a paste landed: predict the field's value, then read it back. +public enum TextInsertionReadback { + public enum Outcome: Equatable { + case landed + case mismatch + /// The field stopped answering, or was still changing when the wait ran out. + case undetermined + } + + /// The value a field should hold once `text` replaces its selection. `selection` is in UTF-16 offsets, as + /// AXSelectedTextRange reports it. Nil means a readback can't prove the result: a non-empty field with no + /// selection, a range outside the value or inside a character, text with control characters (Return or Tab + /// can submit, end editing or move focus instead of being stored), or a value the field already holds. + public static func expectedValue(current: String, selection: Range?, inserting text: String) -> String? { + guard !text.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) else { + return nil + } + let units = Array(current.utf16) + let range: Range + if let selection { + guard selection.lowerBound >= 0, selection.upperBound <= units.count else { + return nil + } + range = selection + } else if units.isEmpty { + range = 0..<0 + } else { + return nil + } + let prefix = Array(units[.. Double = CFAbsoluteTimeGetCurrent, + sleep: (Double) -> Void = { Thread.sleep(forTimeInterval: $0) }, + read: () -> String? + ) -> Outcome { + let start = now() + var readback = read() + // Why: an AX read can block for seconds; the quiet window counts from the answer, not the ask. + var quietDeadline = now() + quietSeconds + while let current = readback, !sameText(current, expected) { + let time = now() + // Why: past the cap a field may still be filling or a read may have blocked through the quiet window; calling it a mismatch invites typing the rest twice. + guard time < start + capSeconds else { + return .undetermined + } + guard time < quietDeadline else { + return .mismatch + } + sleep(intervalSeconds) + readback = read() + if readback != current { + quietDeadline = now() + quietSeconds + } + } + return readback == nil ? .undetermined : .landed + } + + // Why: Chromium contenteditables store typed trailing or repeated spaces as no-break spaces. + private static func sameText(_ lhs: String, _ rhs: String) -> Bool { + lhs.replacingOccurrences(of: "\u{00A0}", with: " ") == rhs.replacingOccurrences(of: "\u{00A0}", with: " ") + } +} 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/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/TextInsertionReadbackTests.swift b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/TextInsertionReadbackTests.swift new file mode 100644 index 00000000000..88ce1fd7932 --- /dev/null +++ b/native/computer-use-macos/Tests/OrcaComputerUseMacOSTests/TextInsertionReadbackTests.swift @@ -0,0 +1,86 @@ +import XCTest +@testable import OrcaComputerUseMacOSCore + +final class TextInsertionReadbackTests: XCTestCase { + + func testInsertionReplacesTheSelectionInUTF16Offsets() { + XCTAssertEqual( + TextInsertionReadback.expectedValue(current: "a😀bcd", selection: 3..<5, inserting: "XY"), + "a😀XYd" + ) + XCTAssertEqual(TextInsertionReadback.expectedValue(current: "", selection: nil, inserting: "hi"), "hi") + } + + func testUnpredictableInsertionsReturnNil() { + XCTAssertNil(TextInsertionReadback.expectedValue(current: "abc", selection: nil, inserting: "d")) + XCTAssertNil(TextInsertionReadback.expectedValue(current: "abc", selection: 2..<4, inserting: "d")) + XCTAssertNil(TextInsertionReadback.expectedValue(current: "a😀", selection: 2..<2, inserting: "d")) + XCTAssertNil(TextInsertionReadback.expectedValue(current: "", selection: 0..<0, inserting: "send\n")) + XCTAssertNil(TextInsertionReadback.expectedValue(current: "", selection: 0..<0, inserting: "a\tb")) + XCTAssertNil(TextInsertionReadback.expectedValue(current: "hello", selection: 0..<5, inserting: "hello")) + } + + func testFieldStillFillingPastTheQuietWindowLands() { + // One character every 0.4 s: each read is past the first 0.5 s window, but each change restarts it. + let reads = ["", "h", "he", "hel", "hell", "hello"] + XCTAssertEqual(settle(expected: "hello", reads: reads, secondsPerRead: 0.4), .landed) + } + + func testSlowFirstReadStillGetsAQuietWindow() { + var clock = 0.0 + var reads = ["h", "hello"][...] + let outcome = TextInsertionReadback.settle( + expected: "hello", + now: { clock }, + sleep: { clock += $0 }, + read: { + if reads.count == 2 { clock += 0.6 } + return reads.popFirst() + } + ) + XCTAssertEqual(outcome, .landed) + } + + func testReadBlockedPastTheCapIsUndetermined() { + var clock = 0.0 + var reads = ["h", "h"][...] + let outcome = TextInsertionReadback.settle( + expected: "hello", + now: { clock }, + sleep: { clock += $0 }, + read: { + if reads.count == 1 { clock = 2.2 } + return reads.popFirst() + } + ) + XCTAssertEqual(outcome, .undetermined) + } + + func testContentEditableNoBreakSpacesLand() { + XCTAssertEqual(settle(expected: "a b ", reads: ["a \u{00A0}b\u{00A0}"], secondsPerRead: 0.025), .landed) + } + + func testFieldThatDropsTheTextIsAMismatch() { + XCTAssertEqual(settle(expected: "hello", reads: Array(repeating: "", count: 100), secondsPerRead: 0.025), .mismatch) + } + + func testFieldThatStopsAnsweringIsUndetermined() { + XCTAssertEqual(settle(expected: "hello", reads: ["", "h"], secondsPerRead: 0.025), .undetermined) + } + + func testFieldStillFillingAtTheCapIsUndetermined() { + let reads = (0..<100).map { String(repeating: "a", count: $0) } + XCTAssertEqual(settle(expected: String(repeating: "a", count: 200), reads: reads, secondsPerRead: 0.1), .undetermined) + } + + private func settle(expected: String, reads: [String], secondsPerRead: Double) -> TextInsertionReadback.Outcome { + var clock = 0.0 + var remaining = reads[...] + return TextInsertionReadback.settle( + expected: expected, + now: { clock }, + sleep: { _ in clock += secondsPerRead }, + read: { remaining.popFirst() } + ) + } +} diff --git a/native/computer-use-windows/runtime-pointer.test.ps1 b/native/computer-use-windows/runtime-pointer.test.ps1 index 78bc1ba9fd9..e25dc2effe3 100644 --- a/native/computer-use-windows/runtime-pointer.test.ps1 +++ b/native/computer-use-windows/runtime-pointer.test.ps1 @@ -51,6 +51,10 @@ public static class OrcaDesktopWin32 { } return Foreground; } + public static uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId) { + processId = hwnd == new IntPtr(101) ? 4242u : 1u; + return 1; + } public static bool SetCursorPos(int x, int y) { Calls.Add("move:" + x + "," + y); return true; @@ -74,7 +78,7 @@ $functions = @( "Get-OrcaRequiredNumber", "Get-OrcaPositiveInteger", "Get-OrcaPositiveNumber", "Get-OrcaScreenPoint", "Get-OrcaElementScreenPoint", "Get-OrcaModifierVirtualKey", "Get-OrcaClickModifierVirtualKeys", "Send-OrcaMouseClick", "Send-OrcaDrag", "Invoke-OrcaOperation", - "Assert-OrcaInputAllowed" + "Assert-OrcaInputAllowed", "Test-OrcaTargetTookForeground" ) foreach ($definition in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $false)) { if ($definition.Name -in $functions) { . ([scriptblock]::Create($definition.Extent.Text)) } @@ -87,6 +91,7 @@ function Get-OrcaRootElement { $null } function Get-OrcaWindowFrame { @{ x = [OrcaDesktopWin32]::WindowX; y = 200 } } function Find-OrcaElement($RootElement, $Record) { $Record } function Invoke-OrcaPrimaryAction($Element) { $null -ne $Element } +function Invoke-OrcaScrollPattern($Element, $RootElement, $Direction, $Pages) { $null -ne $Element } function New-OrcaSnapshot { [pscustomobject]@{} } foreach ($case in @( @@ -112,6 +117,7 @@ foreach ($case in @( if ($inputCalls.Count -eq 0) { throw "$($case.tool) did not send pointer input after activation" } if ([OrcaDesktopWin32]::FocusReads -lt 2) { throw "$($case.tool) did not wait for activation" } Assert-TestEqual $inputCalls[0] "move:505,206" "$($case.tool) geometry after delayed activation" + Assert-TestEqual $result.action.delivery "foreground" "$($case.tool) pointer delivery" } else { Assert-TestEqual $denied $true "$($case.tool) denied activation" Assert-TestEqual $inputCalls.Count 0 "$($case.tool) denied activation sends no pointer or modifier input" @@ -119,10 +125,18 @@ foreach ($case in @( } } -[OrcaDesktopWin32]::Reset($false) -$result = Invoke-OrcaOperation ([pscustomobject]@{ tool = "click"; app = "Fixture"; element = [pscustomobject]@{ index = 1 } }) -Assert-TestEqual $result.action.path "accessibility" "pattern click path" -Assert-TestEqual ([OrcaDesktopWin32]::Calls.Count) 0 "pattern click bypasses activation and global input" +foreach ($case in @( + @{ tool = "click" }, + @{ tool = "scroll"; direction = "down"; pages = 1 } +)) { + [OrcaDesktopWin32]::Reset($false) + $operation = [pscustomobject]@{ app = "Fixture"; element = [pscustomobject]@{ index = 1 } } + foreach ($key in $case.Keys) { $operation | Add-Member -NotePropertyName $key -NotePropertyValue $case[$key] } + $result = Invoke-OrcaOperation $operation + Assert-TestEqual $result.action.path "accessibility" "pattern $($case.tool) path" + Assert-TestEqual $result.action.delivery "background" "pattern $($case.tool) delivery" + Assert-TestEqual ([OrcaDesktopWin32]::Calls.Count) 0 "pattern $($case.tool) bypasses activation and global input" +} foreach ($case in @( @{ tool = "click"; element = [pscustomobject]@{ index = 1 } }, @{ tool = "click"; x = 5; y = 6; restoreWindow = $true }, @@ -137,4 +151,10 @@ foreach ($case in @( if ($message -notlike "target_elevated:*") { throw "$($case.tool) elevated target expected target_elevated, received '$message'" } Assert-TestEqual ([OrcaDesktopWin32]::Calls.Count) 0 "$($case.tool) elevated target sends no activation or input" } +# Why: WPF activates its own window for most patterns; the result must say so rather than claim background. +[OrcaDesktopWin32]::Reset($false) +function Invoke-OrcaPrimaryAction($Element) { [OrcaDesktopWin32]::Foreground = [IntPtr]101; $true } +$result = Invoke-OrcaOperation ([pscustomobject]@{ tool = "click"; app = "Fixture"; element = [pscustomobject]@{ index = 1 } }) +Assert-TestEqual $result.action.path "accessibility" "self-activating pattern click path" +Assert-TestEqual $result.action.delivery "foreground" "self-activating pattern click delivery" Write-Output "windows-pointer-tests-ok" diff --git a/native/computer-use-windows/runtime.ps1 b/native/computer-use-windows/runtime.ps1 index 6ac335bbe97..afbdfe2ee44 100644 --- a/native/computer-use-windows/runtime.ps1 +++ b/native/computer-use-windows/runtime.ps1 @@ -104,6 +104,9 @@ public static class OrcaDesktopWin32 { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] + public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId); + [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); @@ -561,6 +564,14 @@ function Restore-OrcaWindow($Process) { [void][OrcaDesktopWin32]::SetForegroundWindow([IntPtr]$Process.MainWindowHandle) } +function Test-OrcaTargetTookForeground([IntPtr]$Before, $Process) { + $after = [OrcaDesktopWin32]::GetForegroundWindow() + if ($after -eq $Before) { return $false } + $owner = [uint32]0 + [void][OrcaDesktopWin32]::GetWindowThreadProcessId($after, [ref]$owner) + $owner -eq $Process.Id +} + function Test-OrcaWindowFocused([IntPtr]$WindowHandle) { [OrcaDesktopWin32]::GetForegroundWindow() -eq $WindowHandle } @@ -647,15 +658,50 @@ function Get-OrcaValueText($Element) { } } -function Get-OrcaActions($Element) { +function Get-OrcaRangeValueText($Element) { + try { + $pattern = $Element.GetCurrentPattern([Windows.Automation.RangeValuePattern]::Pattern) + ([double]$pattern.Current.Value).ToString([Globalization.CultureInfo]::InvariantCulture) + } catch { + "" + } +} + +function Test-OrcaRangeValueWritable($Element) { + try { + -not $Element.GetCurrentPattern([Windows.Automation.RangeValuePattern]::Pattern).Current.IsReadOnly + } catch { + $false + } +} + +function Get-OrcaExpandCollapseActions($Element) { + try { + $state = $Element.GetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern).Current.ExpandCollapseState + } catch { + return @() + } + switch ($state) { + ([Windows.Automation.ExpandCollapseState]::Collapsed) { return @("Expand") } + ([Windows.Automation.ExpandCollapseState]::Expanded) { return @("Collapse") } + ([Windows.Automation.ExpandCollapseState]::PartiallyExpanded) { return @("Expand", "Collapse") } + } + @() +} + +function Get-OrcaActions($Element, $Patterns = $null) { + if ($null -eq $Patterns) { $Patterns = @($Element.GetSupportedPatterns()) } $actions = New-Object System.Collections.Generic.List[string] - foreach ($pattern in $Element.GetSupportedPatterns()) { + foreach ($pattern in $Patterns) { $name = [string]$pattern.ProgrammaticName if ($name -like "InvokePatternIdentifiers.Pattern") { $actions.Add("Invoke") } elseif ($name -like "TogglePatternIdentifiers.Pattern") { $actions.Add("Toggle") } elseif ($name -like "SelectionItemPatternIdentifiers.Pattern") { $actions.Add("Select") } elseif ($name -like "ScrollPatternIdentifiers.Pattern") { $actions.Add("Scroll") } elseif ($name -like "ValuePatternIdentifiers.Pattern") { $actions.Add("SetValue") } + elseif ($name -like "RangeValuePatternIdentifiers.Pattern") { if (Test-OrcaRangeValueWritable $Element) { $actions.Add("SetValue") } } + elseif ($name -like "ExpandCollapsePatternIdentifiers.Pattern") { foreach ($action in @(Get-OrcaExpandCollapseActions $Element)) { $actions.Add($action) } } + elseif ($name -like "ScrollItemPatternIdentifiers.Pattern") { $actions.Add("ScrollToVisible") } } @($actions | Select-Object -Unique) } @@ -751,6 +797,11 @@ function Test-OrcaPlainTextSubtree($Element, [int]$MaxDepth = 4) { function New-OrcaElementRecord($Element, [int]$Index, $WindowFrame) { $controlType = try { [string]$Element.Current.ControlType.ProgrammaticName } catch { "" } $nativeWindowHandle = try { [int64]$Element.Current.NativeWindowHandle } catch { 0 } + $patterns = @($Element.GetSupportedPatterns()) + $value = Get-OrcaValueText $Element + if ([string]::IsNullOrEmpty($value) -and $patterns -contains [Windows.Automation.RangeValuePattern]::Pattern) { + $value = Get-OrcaRangeValueText $Element + } [pscustomobject]@{ index = $Index runtimeId = @(Get-OrcaRuntimeId $Element) @@ -759,14 +810,19 @@ function New-OrcaElementRecord($Element, [int]$Index, $WindowFrame) { controlType = $controlType localizedControlType = Get-OrcaProperty $Element "LocalizedControlType" className = Get-OrcaProperty $Element "ClassName" - value = Get-OrcaValueText $Element + value = $value isSelected = Test-OrcaElementSelected $Element + isDisabled = Test-OrcaElementDisabled $Element nativeWindowHandle = $nativeWindowHandle frame = Get-OrcaElementFrame $Element $WindowFrame - actions = @(Get-OrcaActions $Element) + actions = @(Get-OrcaActions $Element $patterns) } } +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) @@ -789,12 +845,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 } @@ -815,16 +879,15 @@ 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 } $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) @@ -841,9 +904,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) } @@ -1019,14 +1080,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]@{ @@ -1099,7 +1167,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 @@ -1158,7 +1226,8 @@ function Invoke-OrcaPrimaryAction($Element) { function Invoke-OrcaNamedAction($Element, [string]$Action) { $wanted = "" - if ($null -ne $Action) { $wanted = $Action.Trim().ToLowerInvariant() } + # Why: accept the rendered name ("ScrollToVisible") and macOS's spaced form ("scroll to visible"). + if ($null -ne $Action) { $wanted = ($Action -replace "\s+", "").ToLowerInvariant() } switch ($wanted) { "invoke" { $pattern = $Element.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern) @@ -1175,21 +1244,128 @@ function Invoke-OrcaNamedAction($Element, [string]$Action) { $pattern.Toggle() return $true } + "expand" { + $pattern = $Element.GetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern) + $pattern.Expand() + return $true + } + "collapse" { + $pattern = $Element.GetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern) + $pattern.Collapse() + return $true + } + "scrolltovisible" { + $pattern = $Element.GetCurrentPattern([Windows.Automation.ScrollItemPattern]::Pattern) + $pattern.ScrollIntoView() + return $true + } default { return $false } } } +function Test-OrcaRangeValueMatches([string]$Actual, [double]$Expected) { + # Why: allow float32 rounding (0.1 reads back 0.100000001), but cap it so a snapped neighbour never verifies at any size. + $actualNumber = 0.0 + [double]::TryParse($Actual, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$actualNumber) -and + [Math]::Abs($actualNumber - $Expected) -le [Math]::Min(1e-6 * [Math]::Max(1.0, [Math]::Abs($Expected)), 1e-3) +} + function Set-OrcaElementValue($Element, [string]$Value) { try { $pattern = $Element.GetCurrentPattern([Windows.Automation.ValuePattern]::Pattern) if (-not $pattern.Current.IsReadOnly) { $pattern.SetValue($Value) - return $true + return [pscustomobject]@{ verification = $null } } } catch {} - $false + if (-not (Test-OrcaRangeValueWritable $Element)) { return $null } + $range = $Element.GetCurrentPattern([Windows.Automation.RangeValuePattern]::Pattern) + $culture = [Globalization.CultureInfo]::InvariantCulture + $number = 0.0 + if (-not [double]::TryParse($Value, [Globalization.NumberStyles]::Float, $culture, [ref]$number) -or [double]::IsNaN($number)) { + throw "value must be a number for this range control" + } + $minimum = [double]$range.Current.Minimum + $maximum = [double]$range.Current.Maximum + if ($number -lt $minimum -or $number -gt $maximum) { + throw "value $Value is outside this range control's $($minimum.ToString($culture))..$($maximum.ToString($culture))" + } + $range.SetValue($number) + # Why: Chromium applies the write asynchronously, so poll briefly like macOS's settled readback. + $stopwatch = [Diagnostics.Stopwatch]::StartNew() + while ($true) { + $actual = Get-OrcaRangeValueText $Element + $matched = Test-OrcaRangeValueMatches $actual $number + if ($matched -or $stopwatch.ElapsedMilliseconds -ge 500) { break } + Start-Sleep -Milliseconds 25 + } + $verification = if ($matched) { + [pscustomobject]@{ state = "verified"; property = "value"; expected = $Value; actualPreview = $actual } + } elseif ([string]::IsNullOrEmpty($actual)) { + # Why: a failed read is not evidence the write failed; only a read-back number can contradict it. + [pscustomobject]@{ state = "unverified"; reason = "readback_unsupported"; expected = $Value } + } else { + [pscustomobject]@{ state = "unverified"; reason = "value_mismatch"; expected = $Value; actualPreview = $actual } + } + [pscustomobject]@{ verification = $verification } +} + +function Get-OrcaScrollPattern($Element, $RootElement, [bool]$Vertical) { + $rootId = Get-OrcaRuntimeId $RootElement + $current = $Element + # Why: an item's ScrollPattern lives on its list or viewport, the same container a wheel at its center would scroll. + while ($null -ne $current) { + try { + $pattern = $current.GetCurrentPattern([Windows.Automation.ScrollPattern]::Pattern) + $scrollable = if ($Vertical) { $pattern.Current.VerticallyScrollable } else { $pattern.Current.HorizontallyScrollable } + if ($scrollable) { return $pattern } + } catch {} + if (Test-OrcaSameRuntimeId (Get-OrcaRuntimeId $current) $rootId) { break } + $current = try { [Windows.Automation.TreeWalker]::RawViewWalker.GetParent($current) } catch { $null } + } + $null +} + +function Get-OrcaScrollPercent($Pattern, [bool]$Vertical) { + try { + if ($Vertical) { return [double]$Pattern.Current.VerticalScrollPercent } + [double]$Pattern.Current.HorizontalScrollPercent + } catch { + $null + } +} + +function Invoke-OrcaScrollPattern($Element, $RootElement, [string]$Direction, [double]$Pages) { + # Why: ScrollPattern moves in whole pages; fractional pages keep the wheel, as on macOS. + if ($null -eq $Element -or $Pages -ne [Math]::Floor($Pages)) { return $false } + $vertical = $Direction -in @("up", "down") + $pattern = Get-OrcaScrollPattern $Element $RootElement $vertical + if ($null -eq $pattern) { return $false } + $amount = if ($Direction -in @("down", "right")) { [Windows.Automation.ScrollAmount]::LargeIncrement } else { [Windows.Automation.ScrollAmount]::LargeDecrement } + $none = [Windows.Automation.ScrollAmount]::NoAmount + # Why: without a readable position the loop can't tell the end of the content, so the wheel handles it. + $before = Get-OrcaScrollPercent $pattern $vertical + if ($null -eq $before) { return $false } + for ($page = 0; $page -lt $Pages; $page++) { + try { + if ($vertical) { $pattern.Scroll($none, $amount) } else { $pattern.Scroll($amount, $none) } + } catch { + # Why: a refusal before any page moved falls back to the wheel; after that it is the end of the content. + return $page -gt 0 + } + # Why: WPF and Chromium move the viewport after Scroll returns; an unmoved or unreadable percent after the wait is the end. + $stopwatch = [Diagnostics.Stopwatch]::StartNew() + while ($true) { + $after = Get-OrcaScrollPercent $pattern $vertical + if ($after -ne $before -or $stopwatch.ElapsedMilliseconds -ge 500) { break } + Start-Sleep -Milliseconds 25 + } + if ($null -eq $after -or $after -eq $before) { break } + $before = $after + } + $true } function Get-OrcaRequiredNumber($Value, [string]$Name) { @@ -1446,7 +1622,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 @@ -1462,6 +1638,8 @@ function Invoke-OrcaOperation($Operation) { if ($Operation.tool -in @("type_text", "press_key", "hotkey", "paste_text")) { Assert-OrcaKeyboardFocus $handle $Operation } + # Why: pattern paths need an element; reading the foreground only then keeps coordinate input untouched. + $foregroundBefore = if ($null -ne $element) { [OrcaDesktopWin32]::GetForegroundWindow() } else { [IntPtr]::Zero } $action = $null switch ($Operation.tool) { @@ -1491,7 +1669,8 @@ function Invoke-OrcaOperation($Operation) { $action = [pscustomobject]@{ path = "accessibility"; actionName = $Operation.action; fallbackReason = $null } } "scroll" { - $delta = 120 * [int][Math]::Ceiling((Get-OrcaPositiveNumber $Operation.pages "pages")) + $pages = Get-OrcaPositiveNumber $Operation.pages "pages" + $delta = 120 * [int][Math]::Ceiling($pages) $mouseEvent = $MouseEvents.Wheel if ($Operation.direction -eq "down") { $delta = -1 * $delta @@ -1503,12 +1682,18 @@ function Invoke-OrcaOperation($Operation) { } elseif ($Operation.direction -ne "up") { throw "unsupported scroll direction: $($Operation.direction)" } - $windowFrame = Restore-OrcaPointerWindow $process $root - $point = Get-OrcaElementScreenPoint $element - if ($null -eq $point) { $point = Get-OrcaScreenPoint $Operation $windowFrame } - [void][OrcaDesktopWin32]::SetCursorPos([int]$point.x, [int]$point.y) - [OrcaDesktopWin32]::mouse_event($mouseEvent, 0, 0, $delta, [UIntPtr]::Zero) - $action = [pscustomobject]@{ path = "synthetic"; actionName = "scroll"; fallbackReason = $null } + if (Invoke-OrcaScrollPattern $element $root $Operation.direction $pages) { + $action = [pscustomobject]@{ path = "accessibility"; actionName = "scroll"; fallbackReason = $null } + } else { + # Why: the wheel scrolls whatever is under the pointer, so the window must be on top. + $windowFrame = Restore-OrcaPointerWindow $process $root + $point = Get-OrcaElementScreenPoint $element + if ($null -eq $point) { $point = Get-OrcaScreenPoint $Operation $windowFrame } + [void][OrcaDesktopWin32]::SetCursorPos([int]$point.x, [int]$point.y) + [OrcaDesktopWin32]::mouse_event($mouseEvent, 0, 0, $delta, [UIntPtr]::Zero) + $fallbackReason = if ($null -ne $element) { "actionUnsupported" } else { $null } + $action = [pscustomobject]@{ path = "synthetic"; actionName = "scroll"; fallbackReason = $fallbackReason } + } } "drag" { $windowFrame = Restore-OrcaPointerWindow $process $root @@ -1548,15 +1733,25 @@ function Invoke-OrcaOperation($Operation) { $action = [pscustomobject]@{ path = "clipboard"; actionName = "paste"; fallbackReason = $null; verification = [pscustomobject]@{ state = "unverified"; reason = "clipboard_paste" } } } "set_value" { - if ($null -eq $element -or -not (Set-OrcaElementValue $element ([string]$Operation.value))) { + $written = if ($null -ne $element) { Set-OrcaElementValue $element ([string]$Operation.value) } else { $null } + if ($null -eq $written) { throw "element value is not settable" } $action = [pscustomobject]@{ path = "accessibility"; actionName = "setValue"; fallbackReason = $null } + if ($null -ne $written.verification) { + $action | Add-Member -NotePropertyName verification -NotePropertyValue $written.verification + } } default { throw "unsupported tool: $($Operation.tool)" } } + # Why: input paths raise the target; WPF also activates its own window for most patterns, so those are measured. + $delivery = "foreground" + if ($action.path -eq "accessibility" -and -not [bool]$Operation.restoreWindow -and -not (Test-OrcaTargetTookForeground $foregroundBefore $process)) { + $delivery = "background" + } + $action | Add-Member -NotePropertyName delivery -NotePropertyValue $delivery try { try { diff --git a/skill-guides/orca-computer-use.md b/skill-guides/orca-computer-use.md index 62718ae0921..2e84d6b6076 100644 --- a/skill-guides/orca-computer-use.md +++ b/skill-guides/orca-computer-use.md @@ -46,6 +46,28 @@ 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). + +```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 +89,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 @@ -99,12 +122,14 @@ printf '%s' "$TEXT" | ORCA computer set-value --app --element-index ` 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. @@ -123,7 +148,7 @@ Do not pass `--restore-window` by default. Use it only when foreground input is Popup menus and web `` controls: set the option with `set-value` on the popup element. Background clicks on them are refused because they open the menu off screen or wedge the app's input.", "", - "On Linux and Windows, clicks, scrolling, drags and keyboard input still bring the target window forward.", + "On Linux, clicks, scrolling, drags and keyboard input still bring the target window forward. On Windows, these go through UI Automation when the control supports them, without moving the pointer or sending keys: element clicks, `set-value` (including sliders), element scrolls by whole `--pages`, and secondary actions such as `Invoke`, `Toggle`, `Select`, `Expand`, `Collapse` and `ScrollToVisible` (the last brings a list or tree item into view). Some apps bring their own window forward when driven this way (WPF apps do for most of these), so read `action.delivery`: `background` means the user's foreground window stayed put, `foreground` means the target came forward. Everything else brings the window forward and reports `foreground`.", "", "## Screenshots", "", @@ -1176,7 +1201,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.", "", @@ -1184,6 +1209,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 `' : + '') + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const win = new BrowserWindow({ show: false, width: 960, height: 640, + webPreferences: { offscreen: true, webviewTag: true } }) + const attached = new Promise(resolve => win.webContents.once('did-attach-webview', (_event, guest) => resolve(guest))) + await win.loadURL('data:text/html,' + encodeURIComponent('' + + '')) + const guest = await attached + if (guest.isLoading()) await new Promise(resolve => guest.once('did-finish-load', resolve)) + let crashed = false + guest.on('render-process-gone', () => { crashed = true }) + guest.debugger.attach('1.3') + const send = (method, params, sessionId) => guest.debugger.sendCommand(method, params, sessionId) + const insert = async text => (await routePageTextInsertion(guest, send)).deliver({ text }) + await guest.executeJavaScript('field.focus()') + if (scenario.startsWith('child-')) { + const childServer = createServer((_req,res) => { + res.setHeader('Content-Type','text/html') + res.end('') + }) + await new Promise(resolve => childServer.listen(0,'127.0.0.1',resolve)) + const loaded = new Promise(resolve => guest.once('did-frame-finish-load',resolve)) + await guest.executeJavaScript('document.querySelector("iframe").src="http://127.0.0.1:' + childServer.address().port + '/";void 0') + await loaded + const { frameTree } = await send('Page.getFrameTree',{}) + const frameId = frameTree.childFrames[0].frame.id + const { executionContextId } = await send('Page.createIsolatedWorld',{frameId,worldName:'fixture-child'}) + const child = expression => send('Runtime.evaluate',{expression,contextId:executionContextId,returnByValue:true}) + const { targetInfos } = await send('Target.getTargets',{}) + if (targetInfos.some(target => target.type === 'iframe' && target.targetId === frameId)) throw Error('Fixture child must share the root renderer') + await child('field.focus()') + if (scenario === 'child-focus-race') await child("document.designMode='on';document.body.innerHTML='';document.body.focus()") + await win.webContents.executeJavaScript('draft.focus()') + const route = await routePageTextInsertion(guest,send) + if (scenario === 'child-focus-race') await guest.executeJavaScript('field.focus()') + if (scenario === 'child-detached') await guest.executeJavaScript('document.querySelector("iframe").remove()') + if (scenario === 'child-navigation') { + const reloaded = new Promise(resolve => guest.once('did-frame-finish-load',resolve)) + await guest.executeJavaScript('document.querySelector("iframe").src+="?new";void 0') + await reloaded + } + if (scenario === 'child-expired') { + const busy = new Promise(resolve => guest.once('console-message',resolve)) + void child("console.log('busy');{const end=performance.now()+11000;while(performance.now(){inputText=field.value})") + await insert('First\nSecond 🙏') + const selection = await guest.executeJavaScript('field.value') + const inputText = await guest.executeJavaScript('inputText') + await guest.executeJavaScript("document.execCommand('undo')") + const undo = await guest.executeJavaScript('field.value') + await guest.executeJavaScript("field.addEventListener('beforeinput', e => e.preventDefault(), {once:true})") + await insert('Cancelled') + const cancelled = await guest.executeJavaScript('field.value') + await guest.executeJavaScript("const rich=document.createElement('div');rich.id='rich';rich.contentEditable='true';document.body.append(rich);rich.focus()") + await insert('Rich 🙏') + const rich = await guest.executeJavaScript('rich.textContent') + await guest.executeJavaScript("const host=document.createElement('div');host.id='shadow';document.body.append(host);host.attachShadow({mode:'open'}).innerHTML='';host.shadowRoot.firstChild.focus()") + await insert('Shadow') + const shadow = await guest.executeJavaScript('shadow.shadowRoot.firstChild.value') + await guest.executeJavaScript("const frame=document.createElement('iframe');frame.id='local';document.body.append(frame);frame.contentDocument.body.innerHTML='';frame.contentDocument.querySelector('textarea').focus();Date.now=()=>0;Document.prototype.execCommand=()=>{throw Error('page hook ran')};frame.contentWindow.Document.prototype.execCommand=()=>{throw Error('child hook ran')};void 0") + await insert('Local 🙏') + const local = await guest.executeJavaScript('local.contentDocument.querySelector("textarea").value') + await guest.executeJavaScript("local.contentDocument.designMode='on';local.contentDocument.body.innerHTML='';local.contentWindow.focus()") + await insert('Design') + const design = await guest.executeJavaScript('local.contentDocument.body.textContent') + await guest.executeJavaScript("field.focus();field.addEventListener('beforeinput',()=>shadow.shadowRoot.firstChild.focus(),{once:true})") + let moved = 'ok' + try { await insert('Wrong target') } catch(error) { moved=error.code } + await guest.executeJavaScript("document.body.innerHTML='';document.body.contentEditable='true';document.body.focus()") + await insert('Body 🙏') + const body = await guest.executeJavaScript('document.body.textContent') + answer({ selection, inputText, undo, cancelled, rich, shadow, local, design, moved, body, + host: await win.webContents.executeJavaScript('draft.value') }) + return + } + if (scenario === 'detached') { + await guest.executeJavaScript("const frame=document.createElement('iframe');frame.id='local';document.body.append(frame);frame.contentDocument.body.innerHTML='';frame.contentDocument.querySelector('textarea').focus()") + } + const route = await routePageTextInsertion(guest, send) + if (scenario === 'focus-race') { + const { targetInfos } = await send('Target.getTargets', {}) + const target = targetInfos.find(info => info.type === 'iframe') + if (!target) throw new Error('Cross-site frame target missing') + const { sessionId } = await send('Target.attachToTarget', { targetId: target.targetId, flatten: true }) + const { root } = await send('DOM.getDocument', {}, sessionId) + const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector: '#field' }, sessionId) + await send('DOM.focus', { nodeId }, sessionId) + } else if (scenario === 'navigation') { + await guest.loadURL('http://127.0.0.1:' + server.address().port + '/') + await guest.executeJavaScript('field.focus()') + } else if (scenario === 'detached') { + await guest.executeJavaScript('local.remove()') + } else if (scenario === 'handler-expired') { + await guest.executeJavaScript("field.addEventListener('beforeinput',()=>{const end=performance.now()+11000;while(performance.now() guest.once('console-message', resolve)) + void guest.executeJavaScript("Date.now=()=>0;console.log('busy');{const end=performance.now()+11000;while(performance.now() {}) + await busy + } + let outcome = 'ok' + const delivered = route.deliver({ text: 'LATE' }) + if (scenario === 'renderer-dies') guest.forcefullyCrashRenderer() + try { await delivered } catch (error) { outcome = error.code } + if (scenario === 'renderer-dies') { + answer({ outcome, host: await win.webContents.executeJavaScript('draft.value') }) + return + } + if (crashed) { answer({ crashed, outcome }); return } + const after = await guest.executeJavaScript('field.value') + await guest.executeJavaScript('field.focus()') + const next = await routePageTextInsertion(guest, send) + await next.deliver({ text: 'Next 🙏' }) + answer({ crashed, outcome, after, next: await guest.executeJavaScript('field.value'), + host: await win.webContents.executeJavaScript('draft.value') }) +}).catch(error => answer({ error: String(error.stack || error) })) +` + +it.each([ + 'focus-race', + 'expired', + 'navigation', + 'detached', + 'editing', + 'handler-expired', + 'renderer-dies', + 'child-insert', + 'child-focus-race', + 'child-expired', + 'child-navigation', + 'child-detached' +])( + 'handles %s input without leaking or replaying abandoned text', + async (scenario) => { + const root = mkdtempSync(join(tmpdir(), 'orca-guest-text-')) + try { + const mainPath = join(root, 'main.cjs') + await build({ + stdin: { contents: MAIN, resolveDir: process.cwd(), loader: 'ts' }, + outfile: mainPath, + bundle: true, + platform: 'node', + format: 'cjs', + external: ['electron', '*.node'] + }) + writeFileSync( + join(root, 'config.json'), + JSON.stringify({ resultPath: join(root, 'result.json'), scenario }) + ) + const result = await runBrowserRouteEgressElectron(root, mainPath) + if (scenario.startsWith('child-')) { + expect(result).toEqual({ + outcome: + scenario === 'child-insert' + ? 'ok' + : scenario === 'child-expired' + ? 'browser_timeout' + : 'browser_input_target_unavailable', + after: + scenario === 'child-insert' ? 'Child 🙏' : scenario === 'child-detached' ? null : '', + root: 'Next 🙏', + host: 'Unsent draft', + hostFocus: 'draft' + }) + return + } + if (scenario === 'editing') { + expect(result).toEqual({ + selection: 'First\nSecond 🙏', + inputText: 'First\nSecond 🙏', + undo: 'Replace me', + cancelled: 'Replace me', + rich: 'Rich 🙏', + shadow: 'Shadow', + local: 'Local 🙏', + design: 'Design', + moved: 'browser_input_target_unavailable', + body: 'Body 🙏', + host: 'Unsent draft' + }) + return + } + if (scenario === 'renderer-dies') { + expect(result).toEqual({ outcome: 'browser_error', host: 'Unsent draft' }) + return + } + expect(result).toEqual({ + crashed: false, + outcome: scenario.endsWith('expired') + ? 'browser_timeout' + : 'browser_input_target_unavailable', + after: '', + next: 'Next 🙏', + host: 'Unsent draft' + }) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }, + 45_000 +) diff --git a/src/main/claude-accounts/claude-account-service.test.ts b/src/main/claude-accounts/claude-account-service.test.ts index 944c48015d8..defc0da2de8 100644 --- a/src/main/claude-accounts/claude-account-service.test.ts +++ b/src/main/claude-accounts/claude-account-service.test.ts @@ -11,6 +11,12 @@ import type { ClaudeCommandConfig, ClaudeCommandOptions } from './sign-in/claude import type { ClaudeAccountSelectionTarget } from './selection/runtime-selection' import { ClaudeAccountService } from './service' +// Selection checks must never reach the real Keychain. +vi.mock('../macos-keychain/generic-password', async (importOriginal) => ({ + ...(await importOriginal()), + readKeychainPassword: async () => null +})) + const roots: string[] = [] afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))) @@ -190,4 +196,19 @@ describe('ClaudeAccountService', () => { expect(f.runtimeAuth.removeAccountFolder).not.toHaveBeenCalled() expect(f.settings().claudeManagedAccounts.map((entry) => entry.id)).toEqual(['a', 'b']) }) + + it('refuses to select an account that has its identity but no login to start Claude with', async () => { + const f = fixture() + f.signIn('b', 'b@example.test') + await expect(f.service.selectAccount('b')).rejects.toThrow( + 'Sign in to this Claude account again before selecting it.' + ) + expect(f.settings().activeClaudeManagedAccountId).toBe('a') + + writeFileSync( + join(f.home('b'), '.credentials.json'), + JSON.stringify({ claudeAiOauth: { refreshToken: 'refresh' } }) + ) + await expect(f.service.selectAccount('b')).resolves.toMatchObject({ activeAccountId: 'b' }) + }) }) diff --git a/src/main/claude-accounts/selection/claude-account-selection.ts b/src/main/claude-accounts/selection/claude-account-selection.ts index f1867ab0005..7fb0f91260e 100644 --- a/src/main/claude-accounts/selection/claude-account-selection.ts +++ b/src/main/claude-accounts/selection/claude-account-selection.ts @@ -6,6 +6,8 @@ import type { import type { GlobalSettings } from '../../../shared/global-settings-types' import type { RateLimitService } from '../../rate-limits/service/rate-limit-service' import { claudeStateFile, readClaudeFolderLogin } from '../sign-in/claude-account-folder' +import { readClaudeOAuthCredentials } from '../../rate-limits/providers/claude/claude-oauth-credentials' +import { resolveLoginShellEnvironment } from '../../startup/shell-environment/login-shell-environment' import { savedWslClaudeAccountHome } from '../profiles/wsl/claude-profile-wsl-paths' import type { ClaudeRuntimeAuthService } from '../runtime-auth-service' import { @@ -193,8 +195,13 @@ export class ClaudeAccountSelection { ) { throw new Error('That Claude account belongs to a different runtime.') } - // CLI and paired clients bypass the renderer's sign-in check. - if (this.summarize(account).needsSignIn) { + // CLI and paired clients bypass the renderer's sign-in check. An identity file alone can't + // start Claude, and chats follow the selection on their next start. + const summary = this.summarize(account) + if ( + summary.needsSignIn || + (summary.home && !summary.runsOnSystemDefault && (await accountHoldsNoLogin(summary.home))) + ) { throw new Error(CLAUDE_ACCOUNT_NEEDS_SIGN_IN_MESSAGE) } effectiveTarget = accountTarget @@ -271,3 +278,16 @@ export class ClaudeAccountSelection { } } } + +/** The read usage already makes for this account; an unreadable store is no answer. */ +async function accountHoldsNoLogin(home: string): Promise { + // Claude then keeps every login elsewhere, so an empty account folder proves nothing. + if ((await resolveLoginShellEnvironment()).CLAUDE_SECURESTORAGE_CONFIG_DIR !== undefined) { + return false + } + const login = await readClaudeOAuthCredentials({ + credentialsFileConfigDir: home, + keychainConfigDir: home + }) + return !login.token && !login.hasRefreshableCredentials && !login.unavailable +} diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts index 54f6f9c7e86..42ca17db6ad 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-adapter.ts @@ -161,6 +161,7 @@ export class CodexStructuredSessionAdapter implements SessionAdapter { return admission } if (event.type === 'notification') { + turnEnd.publishCodexTurnOpened(session, event, this.sessions) // Only an admitted turn end settles; a refused one settles on the retry that lands. turnEnd.settleCodexSendsInEndedTurn(session, event) // Child records observe refused frames only after a retry reaches the journal. @@ -340,7 +341,6 @@ export class CodexStructuredSessionAdapter implements SessionAdapter { hasOwnedAcquisition = (sessionId: string): boolean => this.acquisitions.get(sessionId) !== undefined || this.sessions.has(sessionId) - private session(sessionId: string): CodexSession { - return requireLiveCodexSession(this.sessions, sessionId) - } + private session = (sessionId: string): CodexSession => + requireLiveCodexSession(this.sessions, sessionId) } diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts index af6652bbb46..1b65ead9f71 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-start.ts @@ -27,6 +27,7 @@ import { reportedCodexSessionOptions } from '../catalog/codex-structured-session-options' import { CodexSkillReport } from '../catalog/codex-structured-skill-report' +import { codexMessageInputOptions } from '../turns/codex-structured-message-options' import { codexAcquireCatalogAccess } from '../catalog/codex-structured-acquire-catalog' import { CODEX_DEFAULT_SERVICE_TIER, @@ -183,6 +184,10 @@ export async function openCodexStructuredSession( ...(opened.effort ? { effort: opened.effort } : {}), ...(serviceTier ? { serviceTier } : {}) }, + appliedTurnInputOptions: codexMessageInputOptions(input.options ?? {}, { + serviceTier: CODEX_DEFAULT_SERVICE_TIER, + interactionMode: 'default' + }), appliedSettings: attempt.window.appliedSettings, ...(catalogAccess ? { catalogAccess } : {}), dispatchEchoes: start.dispatchEchoes, diff --git a/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts b/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts index e247973e02d..24fb8378af3 100644 --- a/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts +++ b/src/main/codex/structured/session-lifecycle/codex-structured-session-state.ts @@ -179,6 +179,8 @@ export type CodexSession = { nativeDefaults?: { personality?: string; serviceTier?: string } /** Acquisition facts overlaid by controls actually sent, independently of reports or saved picks. */ appliedTurnOptions?: Readonly> + /** Saved/start input choices before protocol shaping; later catalogs cannot change eligibility. */ + appliedTurnInputOptions?: Readonly> appliedSettings?: CodexAppliedSettings /** Optional for adapters without a host catalog store. */ catalogAccess?: CodexSessionCatalogAccess diff --git a/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts b/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts index 8881f19b90b..895a8ac0b96 100644 --- a/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts +++ b/src/main/codex/structured/threads/codex-structured-thread-goal.test.ts @@ -4,7 +4,10 @@ import { CodexAppliedSettings } from '../catalog/codex-structured-applied-settin import { CodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' import { changeCodexThreadGoal } from './codex-structured-thread-goal' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' -import { waitsForCodexTurnOptions } from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' +import { + codexTurnOptionsDiffer, + waitsForCodexTurnOptions +} from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' const THREAD = 'thread-1' @@ -89,31 +92,16 @@ describe('direct goal settings application', () => { threadId: 'thread-abc', threadSettings: { model, effort } }) - const goal = (model = 'gpt-live', effort?: string) => + const goal = (model = 'gpt-live', effort?: string, signal?: AbortSignal) => adapter.changeThreadGoal({ sessionId: 'session-1', fence: 7, change: { kind: 'status', status: 'active' }, replacesGoal: false, - executionOptions: { model, ...(effort ? { effort } : {}) } + executionOptions: { model, ...(effort ? { effort } : {}) }, + signal }) - const state = acquiredSettingsTestSeam(adapter) - return { codex, adapter, apply, goal, settings: state.settings, state, acquisition } - } - - it('keeps literal goal settings separate from exact applied turn proof and recovers on a successful turn', async () => { - const { codex, adapter, apply, goal, acquisition } = await fixture() - const choices = { model: 'unlisted-model-a', effort: 'high' } - const turnProof = { model: 'unlisted-model-a', effort: 'high', interactionMode: 'default' } - const dispatch = () => - adapter.dispatch({ - sessionId: 'session-1', - fence: 7, - clientMessageId: `message-${codex.connections[0].calls.length}`, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, - executionOptions: choices - }) - const held = (options = choices) => + const held = (options: Record) => waitsForCodexTurnOptions( { provider: 'codex', sessionId: 'session-1' }, { @@ -138,16 +126,37 @@ describe('direct goal settings application', () => { { fence: 7, generation: acquisition.acquisitionGeneration, phase: 'ready' }, adapter ) - const proof = () => - adapter.readAppliedInputOptions({ + return { + codex, + adapter, + apply, + goal, + held, + get settings() { + return acquiredSettingsTestSeam(adapter).settings + }, + get state() { + return acquiredSettingsTestSeam(adapter) + }, + acquisition + } + } + + it('preserves goal choice eligibility through readback, refusal and successful-turn recovery', async () => { + const { codex, adapter, apply, goal, held: heldOptions } = await fixture() + const choices = { model: 'unlisted-model-a', effort: 'high' } + const dispatch = () => + adapter.dispatch({ sessionId: 'session-1', fence: 7, - acquisitionGeneration: acquisition.acquisitionGeneration, - next: choices + clientMessageId: `message-${codex.connections[0].calls.length}`, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: choices }) + const held = (options = choices) => heldOptions(options) try { expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()?.active).toEqual(turnProof) + expect(held()).toBe(false) codex.routes['thread/settings/update'] = (params) => { apply(String(params?.model), String(params?.effort)) return {} @@ -161,15 +170,18 @@ describe('direct goal settings application', () => { params: { threadId: 'thread-abc', model: 'unlisted-model-b', effort: 'low' } } ]) - const appliedGoal = { model: 'unlisted-model-b', effort: 'low', interactionMode: 'default' } - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + const goalChoices = { model: 'unlisted-model-b', effort: 'low' } + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) apply('observation-only', 'medium') - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) codex.routes['thread/settings/update'] = () => { throw new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') } expect(await goal('refused-model', 'high')).toMatchObject({ ok: false }) - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) + expect(held(goalChoices)).toBe(false) + expect(held()).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/goal/set') ).toHaveLength(1) @@ -178,8 +190,8 @@ describe('direct goal settings application', () => { (call) => call.method === 'thread/settings/update' ).length expect(await goal('observation-only-c', 'medium')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: appliedGoal, next: turnProof }) - expect(held(appliedGoal)).toBe(false) + expect(held()).toBe(true) + expect(held(goalChoices)).toBe(false) expect(held({ model: 'observation-only-c', effort: 'medium' })).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/settings/update') @@ -188,35 +200,150 @@ describe('direct goal settings application', () => { throw new Error('reply lost after settings enqueue') } expect(await goal('uncertain-model', 'low')).toMatchObject({ ok: false }) - expect(proof()).toEqual({ - active: { effort: 'low', interactionMode: 'default' }, - next: turnProof - }) expect(held()).toBe(true) expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) codex.routes['thread/settings/update'] = () => { throw new CodexAppServerRequestError('thread/settings/update', -32601, 'method not found') } expect(await goal('unlisted-model-b', 'low')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) const callsBeforeCached = codex.connections[0].calls.filter( (call) => call.method === 'thread/settings/update' ).length expect(await goal('unlisted-model-b', 'low')).toEqual({ ok: true }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) expect(held()).toBe(false) - expect(held(appliedGoal)).toBe(true) + expect(held(goalChoices)).toBe(true) expect( codex.connections[0].calls.filter((call) => call.method === 'thread/settings/update') ).toHaveLength(callsBeforeCached) expect(await dispatch()).toMatchObject({ state: 'admitted' }) - expect(proof()).toEqual({ active: turnProof, next: turnProof }) + expect(held()).toBe(false) } finally { await adapter.closeAll() } }) + it.each([ + ['success', false], + ['refusal', false], + ['success', true], + ['refusal', true] + ] as const)( + 'preserves a newer start after late goal %s (replaced acquisition: %s)', + async (outcome, replaceAcquisition) => { + const { codex, adapter, goal, acquisition } = await fixture() + let generation = acquisition.acquisitionGeneration + const dispatch = (model: string) => + adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: model, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: { model, effort: 'high' } + }) + const answer = Promise.withResolvers() + const authority = new AbortController() + try { + expect(await dispatch('model-a')).toMatchObject({ state: 'admitted' }) + const request = vi.spyOn(codex.connections[0], 'request') + codex.routes['thread/settings/update'] = () => answer.promise + const pending = goal('model-b', 'high', authority.signal) + const rpc = request.mock.results.at(-1)?.value + expect(rpc).toBeInstanceOf(Promise) + authority.abort(new Error('stopped')) + expect(await pending).toMatchObject({ ok: false }) + if (replaceAcquisition) { + await adapter.closeSession('session-1') + const { acquireReadyCodexForTest, identityFor } = + await import('../session-lifecycle/codex-structured-session-adapter-fixture') + const replacement = await acquireReadyCodexForTest(adapter, { + identity: identityFor('session-1'), + fence: 7, + spawnToken: 'replacement' + }) + generation = replacement.acquisitionGeneration + expect( + adapter.readAppliedInputOptions({ + sessionId: 'session-1', + fence: 7, + acquisitionGeneration: acquisition.acquisitionGeneration, + next: {} + }) + ).toBeNull() + } + expect(await dispatch('model-c')).toMatchObject({ state: 'admitted' }) + if (outcome === 'success') { + answer.resolve({}) + } else { + answer.reject( + new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') + ) + } + await Promise.allSettled([rpc]) + const differs = (model: string) => + codexTurnOptionsDiffer( + { provider: 'codex', sessionId: 'session-1' }, + { model, effort: 'high' }, + { fence: 7, generation, phase: 'ready' }, + adapter + ) + expect(differs('model-c')).toBe(false) + expect(differs('model-a')).toBe(true) + expect(differs('model-b')).toBe(true) + expect( + codex.connections + .flatMap((connection) => connection.calls) + .some((call) => call.method.startsWith('thread/goal/')) + ).toBe(false) + } finally { + await adapter.closeAll() + } + } + ) + + it.each(['success', 'refusal'] as const)( + 'settles an owned late %s after abort without resuming the goal', + async (outcome) => { + const { codex, adapter, goal, held } = await fixture() + const answer = Promise.withResolvers() + const authority = new AbortController() + try { + await adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: 'prior', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Continue' }] }, + executionOptions: { model: 'model-a', effort: 'high' } + }) + const request = vi.spyOn(codex.connections[0], 'request') + codex.routes['thread/settings/update'] = () => answer.promise + const pending = goal('model-b', 'high', authority.signal) + const rpc = request.mock.results.at(-1)?.value + expect(rpc).toBeInstanceOf(Promise) + authority.abort(new Error('stopped')) + expect(await pending).toMatchObject({ ok: false }) + if (outcome === 'success') { + answer.resolve({}) + } else { + answer.reject( + new CodexAppServerRequestError('thread/settings/update', -32602, 'invalid model') + ) + } + await Promise.allSettled([rpc]) + expect(held({ model: 'model-b', effort: 'high' })).toBe(outcome !== 'success') + expect(held({ model: 'model-a', effort: 'high' })).toBe(outcome === 'success') + expect( + codex.connections + .flatMap((connection) => connection.calls) + .some((call) => call.method.startsWith('thread/goal/')) + ).toBe(false) + } finally { + await adapter.closeAll() + } + } + ) + it.each(['success', 'rejection', 'stale'] as const)( 'rechecks current application after its RPC reply, preserving pre-reply evidence (%s)', async (mode) => { diff --git a/src/main/codex/structured/threads/codex-structured-thread-goal.ts b/src/main/codex/structured/threads/codex-structured-thread-goal.ts index be5a3123528..48b65d0642e 100644 --- a/src/main/codex/structured/threads/codex-structured-thread-goal.ts +++ b/src/main/codex/structured/threads/codex-structured-thread-goal.ts @@ -120,7 +120,16 @@ export async function changeCodexThreadGoalWithSettings( try { if (startsWork) { const requested = resolvedCodexGoalSettings(session, input.executionOptions) - const previousApplied = session.appliedTurnOptions + let previousApplied = session.appliedTurnOptions + let previousInput = session.appliedTurnInputOptions + let invalidatedApplied: CodexSession['appliedTurnOptions'] + let invalidatedInput: CodexSession['appliedTurnInputOptions'] + const ownsAcquisition = () => + current() && + !session.ended && + !session.connection.closed && + session.fence === input.fence && + session.acquisitionGeneration === generation const installed = await session.appliedSettings?.install( session.connection, session.threadId, @@ -128,19 +137,44 @@ export async function changeCodexThreadGoalWithSettings( timeoutMs, input.signal, () => { - session.appliedTurnOptions = { ...session.appliedTurnOptions, ...requested } + if (!ownsAcquisition()) { + return + } + if (session.appliedTurnOptions === invalidatedApplied) { + session.appliedTurnOptions = { ...invalidatedApplied, ...requested } + } + if (session.appliedTurnInputOptions === invalidatedInput) { + session.appliedTurnInputOptions = { ...invalidatedInput, ...requested } + } }, () => { - session.appliedTurnOptions = previousApplied + if (!ownsAcquisition()) { + return + } + if (session.appliedTurnOptions === invalidatedApplied) { + session.appliedTurnOptions = previousApplied + } + if (session.appliedTurnInputOptions === invalidatedInput) { + session.appliedTurnInputOptions = previousInput + } }, () => { + previousApplied = session.appliedTurnOptions + previousInput = session.appliedTurnInputOptions const known = { ...previousApplied } + const knownInput = { ...previousInput } for (const key of ['model', 'effort'] as const) { if (requested[key] !== undefined && requested[key] !== known[key]) { delete known[key] } + if (requested[key] !== undefined && requested[key] !== knownInput[key]) { + delete knownInput[key] + } } - session.appliedTurnOptions = known + invalidatedApplied = known + invalidatedInput = knownInput + session.appliedTurnOptions = invalidatedApplied + session.appliedTurnInputOptions = invalidatedInput } ) if (installed && !installed.ok) { diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts b/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts index f9cf8c3b058..23e9fd67015 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-admission.test.ts @@ -1,7 +1,13 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' import { agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionEventSink +} from '../../../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createFixture } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-store-contract-test-fixture' +import { testEventSinkLogging } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { StructuredAgentSessionCurrentWork } from '../../../native-chat/agent-session-wire/observations/structured-agent-session-current-work' import { MAX_CODEX_PENDING_DISPATCH_ECHOES } from './codex-structured-dispatch-echo' import { acquiredCodexAdapter, @@ -43,6 +49,26 @@ function lifecycleRecorder(): { } describe('codex dispatch admission', () => { + it('releases acknowledged steers without an echo and retains each late receipt', async () => { + const codex = fakeCodexAppServer({ 'turn/steer': () => ({ turnId: 'turn-1' }) }) + const settlements: LateSettlement[] = [] + const adapter = await acquiredCodexAdapter({ codex, settlements }) + const connection = codex.connections[0]! + startTurn(connection, 'turn-1') + expect(await send(adapter, 'client-1')).toMatchObject({ state: 'admitted' }) + expect(adapter.heldSends('session-1')).toEqual(new Set()) + expect(await send(adapter, 'client-2')).toMatchObject({ state: 'admitted' }) + expect(adapter.heldSends('session-1')).toEqual(new Set()) + echoUserMessage(connection, { turnId: 'turn-1', itemId: 'late-1', clientId: 'client-1' }) + echoUserMessage(connection, { turnId: 'turn-1', itemId: 'late-2', clientId: 'client-2' }) + expect(settlements.map(({ clientMessageId }) => clientMessageId)).toEqual([ + 'client-1', + 'client-2' + ]) + expect(connection.calls.filter(({ method }) => method === 'turn/steer')).toHaveLength(2) + await adapter.closeSession('session-1') + }) + it('correlates each send by client message id, not queue order', async () => { const codex = fakeCodexAppServer({ 'turn/steer': () => ({ turnId: 'turn-1' }) }) const settlements: LateSettlement[] = [] @@ -190,3 +216,73 @@ describe('codex dispatch admission', () => { expect(settlements).toEqual([]) }) }) + +describe('ordered Codex admission publication', () => { + const fixture = createFixture() + + it('holds a replied start through refused and delayed journal writes, then releases without an echo', async () => { + const journal = await fixture.open() + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + deferred.bind({ journal, fence: 7, publish: () => {} }) + let refuse = true + const revise = deferred.sink.tryReviseResolvedItem! + deferred.sink.tryReviseResolvedItem = (...args) => + refuse ? { accepted: false, reason: 'backpressure' } : revise(...args) + const write = journal.appendResolvedItem.bind(journal) + const delay = Promise.withResolvers() + let delayed = false + vi.spyOn(journal, 'appendResolvedItem').mockImplementation(async (...args) => { + delayed = true + await delay.promise + return write(...args) + }) + const codex = fakeCodexAppServer({ 'turn/start': () => ({ turn: { id: 'ordered-turn' } }) }) + let work: StructuredAgentSessionCurrentWork | undefined + const observed: { active: string | null; working: boolean }[] = [] + const adapter = await acquiredCodexAdapter({ + codex, + settlements: [], + sink: deferred.sink, + onHeldSendsChanged: () => { + if (work) { + observed.push({ active: work.activeTurnId(), working: work.working() }) + } + } + }) + work = new StructuredAgentSessionCurrentWork(journal, 7, 0, undefined, undefined, false, () => + adapter.heldSends('session-1') + ) + await journal.appendSubmission({ + clientMessageId: 'ordered', + payloadFingerprint: 'ordered-input', + body: CODEX_TEST_USER_MESSAGE, + fence: 7 + }) + await send(adapter, 'ordered') + const submission = journal.submission('ordered')! + expect(work.publishedSubmission(submission)).toMatchObject({ dispatchState: 'pending' }) + expect(work.working()).toBe(true) + + startTurn(codex.connections[0]!, 'ordered-turn') + expect(work.activeTurnId()).toBeNull() + expect(work.working()).toBe(true) + refuse = false + await vi.waitFor(() => expect(delayed).toBe(true)) + expect(work.activeTurnId()).toBeNull() + expect(work.publishedSubmission(submission)).toMatchObject({ dispatchState: 'pending' }) + delay.resolve() + await deferred.sink.written!() + await vi.waitFor(() => + expect(work!.publishedSubmission(submission)).toMatchObject({ + dispatchState: 'unknown', + recovered: true, + reason: 'provider_write_outcome_unknown' + }) + ) + expect(work.activeTurnId()).toBe('ordered-turn') + expect(work.working()).toBe(true) + expect(observed).toEqual([{ active: 'ordered-turn', working: true }]) + await adapter.closeSession('session-1') + deferred.close() + }) +}) diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts b/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts index 447179d8496..1b5842ca410 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-echo.test.ts @@ -73,7 +73,7 @@ it.each(['start', 'steer'] as const)( describe('the sends Codex holds', () => { const held = (echoes: ReturnType) => [...echoes.heldSends()] - it('holds a send from its write until the turn it was answered into ends, echo or not', () => { + it('holds a replied start until its turn is published without consuming its echo', () => { const changes: string[] = [] const echoes = createCodexDispatchEchoes(() => changes.push(held(echoes).join(','))) echoes.arm('sent') @@ -82,12 +82,34 @@ describe('the sends Codex holds', () => { echoes.bindTurn('sent', 'thread-1', 'turn-1', 'start', echoes.tick()) expect(held(echoes)).toEqual(['sent']) - // A hook can refuse input and complete the turn without echoing it. - echoes.endTurn('thread-1', 'turn-1', { status: 'completed' }) + echoes.opened('thread-1', 'turn-1') + expect(held(echoes)).toEqual(['sent']) + echoes.published('thread-1', 'turn-1') expect(held(echoes)).toEqual([]) expect(changes).toEqual(['']) }) + it('releases a replied steer into a published turn while retaining exact late correlation', () => { + const echoes = createCodexDispatchEchoes() + echoes.published('thread-1', 'turn-1') + echoes.arm('steered') + echoes.expect('steered', 'thread-1', 'steer', [], 'turn-1') + expect(held(echoes)).toEqual(['steered']) + echoes.bindTurn('steered', 'thread-1', 'turn-1', 'steer', echoes.tick()) + expect(held(echoes)).toEqual([]) + expect( + readCodexDispatchEcho( + { + type: 'userMessage', + id: 'late-user', + clientId: 'steered' + }, + CODEX_IDENTITY, + echoes + )?.clientMessageId + ).toBe('steered') + }) + it('holds a send answered into no turn only while a status read after its answer says running', () => { const echoes = createCodexDispatchEchoes() echoes.arm('timed-out') diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts b/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts index aa6bb41e05d..c469ba6a9d8 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-echo.ts @@ -8,10 +8,7 @@ import type { ProviderDiagnostic } from '../../../../shared/agent-session/failur import type { AgentJournalItemIdentity } from '../../../../shared/agent-session/journal/agent-session-journal-identity' import type { AgentJournalTurnJoin } from '../../../../shared/agent-session/journal/agent-session-journal-types' -export { - MAX_CODEX_PENDING_DISPATCH_ECHOES, - MAX_CODEX_RECORDED_TURN_ENDS -} from './codex-dispatch-receipt-correlation' +export { MAX_CODEX_PENDING_DISPATCH_ECHOES, MAX_CODEX_RECORDED_TURN_ENDS } export type CodexTurnEnd = | { status: 'completed' } @@ -31,7 +28,7 @@ export type CodexDispatchEchoes = { answered: (clientMessageId: string, at: number) => void /** Only status received after a no-turn answer determines whether that send is held. */ observeStatus: (active: boolean) => void - /** Sends still executing; ended turns release them even without an echo. */ + /** Sends awaiting admission to a published turn; exact echoes remain independently armed. */ heldSends: () => ReadonlySet /** False at capacity preserves older pending sends. */ arm: (clientMessageId: string, requestedAt?: number) => boolean @@ -63,6 +60,8 @@ export type CodexDispatchEchoes = { /** Mark a timed-out open wait so later sends do not wait again. */ leftUnopened: (threadId: string, turnId: string) => void opened: (threadId: string, turnId: string) => void + /** The turn's admitted journal writes landed; receipt observation alone cannot release work. */ + published: (threadId: string, turnId: string) => void /** An error naming a never-opened turn counts as its end. */ hasOpened: (threadId: string, turnId: string) => boolean /** Latest answered turn still unopened after its wait was exhausted. */ @@ -105,12 +104,14 @@ export function createCodexDispatchEchoes( >() let clock = 0 let status: { active: boolean; at: number } | null = null + const publishedTurns = new Set() const heldSends = (): Set => new Set( [...armed].flatMap(([clientMessageId, entry]) => entry.answeredAt === undefined || (entry.turn - ? entry.turnEnded !== true + ? entry.turnEnded !== true && + !publishedTurns.has(turnKey(entry.turn.threadId, entry.turn.turnId)) : status?.active === true && status.at > entry.answeredAt) ? [clientMessageId] : [] @@ -224,6 +225,16 @@ export function createCodexDispatchEchoes( openedTurns.delete(oldest) } }, + published: (threadId, turnId) => + reporting(() => { + publishedTurns.add(turnKey(threadId, turnId)) + for (const oldest of publishedTurns) { + if (publishedTurns.size <= MAX_CODEX_RECORDED_TURN_ENDS) { + break + } + publishedTurns.delete(oldest) + } + }), hasOpened: (threadId, turnId) => openedTurns.has(turnKey(threadId, turnId)), endTurn: (threadId, turnId, end) => reporting(() => { @@ -286,6 +297,7 @@ export function createCodexDispatchEchoes( receiptCorrelation.clear() unopenedTurns.clear() openedTurns.clear() + publishedTurns.clear() nextSequence = 0 }, get size() { diff --git a/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts b/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts index dc301fe56da..6c232e59d13 100644 --- a/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts +++ b/src/main/codex/structured/turns/codex-structured-dispatch-test-support.ts @@ -99,6 +99,7 @@ export async function acquiredCodexAdapter(input: { sink?: StructuredAgentSessionEventSink requestTimeoutMs?: number permissionMode?: AgentChatPermissionChoice + onHeldSendsChanged?: CodexStructuredSessionAdapterDeps['onHeldSendsChanged'] }): Promise { const adapter = new CodexStructuredSessionAdapter({ resolveLaunch: async () => ({ @@ -114,6 +115,7 @@ export async function acquiredCodexAdapter(input: { onDispatchSettledLate: (settlement) => { input.settlements.push(settlement) }, + ...(input.onHeldSendsChanged ? { onHeldSendsChanged: input.onHeldSendsChanged } : {}), ...(input.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: input.requestTimeoutMs }) }) const identity: AgentSessionJournalIdentity = { diff --git a/src/main/codex/structured/turns/codex-structured-message-options.test.ts b/src/main/codex/structured/turns/codex-structured-message-options.test.ts index 907fbc4b505..77ac386d2e3 100644 --- a/src/main/codex/structured/turns/codex-structured-message-options.test.ts +++ b/src/main/codex/structured/turns/codex-structured-message-options.test.ts @@ -9,11 +9,28 @@ import { claudeAndCodexAgents } from '../../../native-chat/agent-session-wire/pr import { describe, expect, it, vi } from 'vitest' import { AgentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store' import { optionSession } from '../catalog/codex-structured-option-session.test-fixture' -import { resolvedCodexMessageOptions } from './codex-structured-message-options' +import { + readCodexAppliedInputOptions, + resolvedCodexMessageOptions +} from './codex-structured-message-options' +import { + codexTurnOptionsDiffer, + waitsForCodexTurnOptions +} from '../../../native-chat/agent-session-wire/options/structured-agent-session-message-options' import { startCodexTurn } from './codex-structured-turn-start' import { CodexAppServerRequestError } from '../../app-server/codex-app-server-request-error' +import { CodexAppliedSettings } from '../catalog/codex-structured-applied-settings' +import { changeCodexThreadGoalWithSettings } from '../threads/codex-structured-thread-goal' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' -import { USER_MESSAGE } from '../session-lifecycle/codex-structured-session-adapter-fixture' +import { + USER_MESSAGE, + fakeCodex, + adapterFor, + acquireReadyCodexForTest, + identityFor, + answerWithOpenedTurn +} from '../session-lifecycle/codex-structured-session-adapter-fixture' +import type { AgentJournalItemBody } from '../../../../shared/agent-session/journal/agent-session-journal-types' function seedMessageDefaults(session: CodexSession): void { const store = new AgentModelCatalogStore() @@ -29,7 +46,7 @@ function seedMessageDefaults(session: CodexSession): void { label: 'Model A', isDefault: false, defaultEffort: 'low', - serviceTiers: [{ value: 'priority', label: 'Priority' }], + serviceTiers: [{ value: 'priority', label: 'Fast' }], efforts: [ { value: 'low', label: 'Low' }, { value: 'high', label: 'High' } @@ -211,3 +228,237 @@ it('sends native Plan and Build on fresh turns while a steer keeps its running m expect(request.mock.calls.at(-1)?.[0]).toBe('turn/steer') expect(request.mock.calls.at(-1)?.[1]).not.toHaveProperty('collaborationMode') }) + +it.each(['priority', 'default'])( + 'keeps the same priority input eligible after an actual %s start and catalog change', + async (initialTier) => { + const request = vi.fn(async () => ({ turn: { id: 'tier-turn' } })) + const session = optionSession(request) + const store = new AgentModelCatalogStore() + const catalog = (priority: boolean) => + store.recordSuccess( + 'input-intent', + 'codex', + { + origin: 'probe', + models: [ + { + id: 'gpt-live', + label: 'GPT', + isDefault: true, + efforts: [{ value: 'high', label: 'High' }], + serviceTiers: priority ? [{ value: 'priority', label: 'Fast' }] : [] + } + ] + }, + 'discovery' + ) + session.catalogAccess = { store, fingerprint: 'input-intent', accountHomePath: '/test-account' } + session.reportedOptions = { model: 'gpt-live', effort: 'high', serviceTier: 'default' } + catalog(initialTier === 'priority') + const choices = { model: 'gpt-live', effort: 'high', serviceTier: 'priority' } + await startCodexTurn(session, { + clientMessageId: 'priority-input', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect(request).toHaveBeenCalledWith( + 'turn/start', + expect.objectContaining({ + serviceTier: initialTier + }), + expect.anything() + ) + catalog(false) + const differs = (next: Record) => + codexTurnOptionsDiffer( + { provider: 'codex', sessionId: 'session-1' }, + next, + { fence: 1, generation: 'generation-1', phase: 'ready' }, + { readAppliedInputOptions: (input) => readCodexAppliedInputOptions(session, input) } + ) + expect(differs(choices)).toBe(false) + expect(differs({ ...choices, serviceTier: 'default' })).toBe(true) + } +) + +it('holds Plan behind a successful sparse Default start, then starts Plan after completion', async () => { + const codex = fakeCodex() + const adapter = adapterFor(codex) + const bodies: AgentJournalItemBody[] = [] + const acquisition = await acquireReadyCodexForTest(adapter, { + identity: identityFor('session-1'), + fence: 7, + spawnToken: 'spawn', + events: { + appendItem: (_identity, body) => bodies.push(body), + appendTombstone: () => {}, + publish: () => {} + } + }) + const dispatch = (id: string, options: Record) => + adapter.dispatch({ + sessionId: 'session-1', + fence: 7, + clientMessageId: id, + body: USER_MESSAGE, + executionOptions: options + }) + const complete = (turnId: string) => + codex.connections[0].handlers.onNotification?.('turn/completed', { + threadId: 'thread-abc', + turn: { id: turnId, status: 'completed' } + }) + const held = (interactionMode: 'default' | 'plan') => + waitsForCodexTurnOptions( + { provider: 'codex', sessionId: 'session-1' }, + { + newestTurn: () => bodies.findLast((body) => body.kind === 'turn') ?? null, + itemBody: () => USER_MESSAGE + }, + { + clientMessageId: 'next-plan', + fence: 7, + payloadFingerprint: 'fingerprint', + dispatchState: 'pending', + providerItemId: null, + reason: null, + submittedAt: 1, + resolvedAt: null, + options: { interactionMode } + }, + { fence: 7, generation: acquisition.acquisitionGeneration, phase: 'ready' }, + adapter + ) + try { + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'plan-first') + expect(await dispatch('first', { interactionMode: 'plan' })).toMatchObject({ + state: 'admitted' + }) + complete('plan-first') + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'default-second') + expect(await dispatch('second', {})).toMatchObject({ state: 'admitted' }) + expect( + codex.connections[0].calls.findLast((call) => call.method === 'turn/start')?.params + ).toMatchObject({ collaborationMode: { mode: 'default' } }) + expect(held('plan')).toBe(true) + expect(held('default')).toBe(false) + complete('default-second') + expect(held('plan')).toBe(false) + codex.routes['turn/start'] = answerWithOpenedTurn(codex, 'plan-third') + expect(await dispatch('third', { interactionMode: 'plan' })).toMatchObject({ + state: 'admitted' + }) + expect( + codex.connections[0].calls.findLast((call) => call.method === 'turn/start')?.params + ).toMatchObject({ collaborationMode: { mode: 'plan' } }) + } finally { + await adapter.closeAll() + } +}) + +it('uses exact successful start controls when the first message omits model and effort', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'first-turn' } }))) + await startCodexTurn(session, { + clientMessageId: 'first', + body: USER_MESSAGE, + executionOptions: {}, + turnOptions: {} + }) + const read = (next: Record) => + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next + }) + expect(read({ effort: 'high' })).toMatchObject({ + active: { model: 'gpt-live', effort: 'high' }, + next: { model: 'gpt-live', effort: 'high' } + }) + expect(read({ effort: 'low' })).toMatchObject({ + active: { effort: 'high' }, + next: { effort: 'low' } + }) +}) + +it('inherits retained sparse intent ahead of canonical execution controls', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'sparse-turn' } }))) + session.appliedTurnOptions = { model: 'gpt-canonical', effort: 'high' } + session.appliedTurnInputOptions = { model: 'gpt-alias', effort: 'low' } + const choices = { model: 'gpt-alias' } + await startCodexTurn(session, { + clientMessageId: 'sparse', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: { model: 'gpt-alias', effort: 'low' } + }) + ).toMatchObject({ + active: { model: 'gpt-alias', effort: 'low' }, + next: { model: 'gpt-alias', effort: 'low' } + }) +}) + +it('retains legacy fast intent as the successful native tier after a standard turn', async () => { + const session = optionSession(vi.fn(async () => ({ turn: { id: 'fast-turn' } }))) + seedMessageDefaults(session) + session.appliedTurnInputOptions = { model: 'model-a', serviceTier: 'default' } + const choices = { model: 'model-a', fastMode: 'true' as const } + await startCodexTurn(session, { + clientMessageId: 'legacy-fast', + body: USER_MESSAGE, + executionOptions: choices, + turnOptions: await resolvedCodexMessageOptions(session, choices) + }) + expect(Object.fromEntries(session.options)).toEqual({ model: 'model-a', serviceTier: 'priority' }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: { serviceTier: 'priority' } + }) + ).toMatchObject({ active: { serviceTier: 'priority' }, next: { serviceTier: 'priority' } }) +}) + +it('invalidates uncertain goal choices independently from shaped execution evidence', async () => { + const session = optionSession( + vi.fn(async () => { + throw new Error('lost after write') + }) + ) + session.appliedSettings = new CodexAppliedSettings() + session.appliedSettings.observe({ model: 'gpt-canonical', effort: 'high' }) + session.appliedTurnOptions = { model: 'gpt-canonical', effort: 'high' } + session.appliedTurnInputOptions = { model: 'gpt-alias', effort: 'low', serviceTier: 'default' } + expect( + await changeCodexThreadGoalWithSettings( + session, + { + sessionId: 'session-1', + fence: 1, + change: { kind: 'set', objective: 'Ship it' }, + replacesGoal: false, + executionOptions: { model: 'gpt-canonical', effort: 'low' } + }, + 1000, + () => true + ) + ).toMatchObject({ ok: false }) + expect( + readCodexAppliedInputOptions(session, { + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: 'generation-1', + next: {} + })?.active + ).toEqual({ effort: 'low', serviceTier: 'default' }) +}) diff --git a/src/main/codex/structured/turns/codex-structured-message-options.ts b/src/main/codex/structured/turns/codex-structured-message-options.ts index f2d2fa9532b..ed853b25734 100644 --- a/src/main/codex/structured/turns/codex-structured-message-options.ts +++ b/src/main/codex/structured/turns/codex-structured-message-options.ts @@ -37,8 +37,9 @@ export async function resolvedCodexMessageOptions( return compileCodexMessageOptions(session, choices) } -function compileCodexMessageOptions( - session: CodexSession, +export function compileCodexMessageOptions( + session: Pick & + Partial>, choices: Readonly> ): Readonly> { const compiled: Record = {} @@ -57,7 +58,29 @@ function compileCodexMessageOptions( return codexTurnRequestOptions(session, compiled) } -/** The same sparse controls as dispatch, compared under the exact acquisition that took them. */ +/** Compare retained input choices, without reinterpreting them through a later catalog. */ +export function codexMessageInputOptions( + choices: Readonly>, + inherited: Readonly> = {}, + applied: Readonly> = {} +): Readonly> { + const next = { ...inherited } + for (const key of ['model', 'effort', 'personality', 'serviceTier', 'interactionMode'] as const) { + if (choices[key] !== undefined) { + next[key] = choices[key] + } + } + if (choices.serviceTier === undefined && choices.fastMode !== undefined) { + const legacy = codexServiceTierOfFastMode(choices.fastMode, undefined) + const inheritedTier = inherited.serviceTier + const tier = + inheritedTier === 'priority' || inheritedTier === 'fast' ? inheritedTier : applied.serviceTier + next.serviceTier = legacy === 'fast' && (tier === 'priority' || tier === 'fast') ? tier : legacy + } + return next +} + +/** Intent belongs to this exact acquisition; catalog/readback differences are not send barriers. */ export function readCodexAppliedInputOptions( session: CodexSession | undefined, input: Parameters>[0] @@ -68,13 +91,13 @@ export function readCodexAppliedInputOptions( session.connection.closed || session.fence !== input.fence || session.acquisitionGeneration !== input.acquisitionGeneration || - !session.appliedTurnOptions + !session.appliedTurnInputOptions ) { return null } - const active = session.appliedTurnOptions + const active = session.appliedTurnInputOptions const requested = input.next ?? Object.fromEntries(session.options) - return { active, next: { ...active, ...compileCodexMessageOptions(session, requested) } } + return { active, next: codexMessageInputOptions(requested, active, session.appliedTurnOptions) } } /** Check the live binding after options settle and again whenever the provider is about to write. */ diff --git a/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts b/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts index 69513fc5251..a5a420758de 100644 --- a/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts +++ b/src/main/codex/structured/turns/codex-structured-turn-end-settlement.ts @@ -97,6 +97,36 @@ export function noteCodexTurnOpened( } } +export function publishCodexTurnOpened( + session: CodexSession, + frame: { sessionId: string; method: string; params: unknown }, + sessions: ReadonlyMap +): void { + const { method, params } = frame + const turnId = method === 'turn/started' ? readCodexTurnId(params) : null + if (!turnId || (readCodexThreadId(params) ?? session.threadId) !== session.threadId) { + return + } + const publish = (): void => { + if (!session.ended && sessions.get(frame.sessionId) === session) { + session.dispatchEchoes.published(session.threadId, turnId) + } + } + const written = session.events?.written?.() + if (written) { + void written.then( + (result) => { + if (result.ok) { + publish() + } + }, + () => {} + ) + } else { + publish() + } +} + export function settleCodexSendsInEndedTurn( session: Pick, frame: { sessionId: string; method: string; params: unknown } diff --git a/src/main/codex/structured/turns/codex-structured-turn-start.ts b/src/main/codex/structured/turns/codex-structured-turn-start.ts index 75a80fabc52..6da125a55d1 100644 --- a/src/main/codex/structured/turns/codex-structured-turn-start.ts +++ b/src/main/codex/structured/turns/codex-structured-turn-start.ts @@ -4,7 +4,11 @@ import { StructuredAgentSessionInputNotAdmitted, type StructuredAgentSessionAdmitFreshInput } from '../../../native-chat/agent-session-wire/delivery/structured-agent-session-input-admission' -import { turnInputFor } from './codex-structured-message-options' +import { + codexMessageInputOptions, + compileCodexMessageOptions, + turnInputFor +} from './codex-structured-message-options' import { reportedCodexPermissionMode } from '../threads/codex-structured-thread-open' import { admitCodexTurnPermission } from './codex-structured-turn-permission' import type { CodexSkillReport } from '../catalog/codex-structured-skill-report' @@ -23,7 +27,7 @@ import type { CodexAppServerConnection } from '../../app-server/codex-app-server import { isCodexAppServerUnsupportedError } from '../../app-server/codex-app-server-session' import type { CodexDispatchEchoes } from './codex-structured-dispatch-echo' import { readCodexTurnId } from '../../app-server/codex-structured-thread-facts' -import { codexTurnRequestOptions } from '../catalog/codex-structured-service-tier' +import type { AgentSessionExecutionOptions } from '../../../../shared/agent-session/options/agent-session-execution-options' import type { CodexSession } from '../session-lifecycle/codex-structured-session-state' import { codexRunningOrOpeningTurn, @@ -40,6 +44,7 @@ export type CodexTurnHost = { permissions?: CodexSession['permissions'] options: Map appliedTurnOptions?: Readonly> + appliedTurnInputOptions?: Readonly> appliedSettings?: CodexSession['appliedSettings'] reportedOptions?: CodexSession['reportedOptions'] catalogAccess?: CodexSession['catalogAccess'] @@ -50,18 +55,22 @@ export type CodexTurnHost = { turnOpenWaits: Pick } +type CodexTurnInput = { + clientMessageId: string + body: AgentJournalMessageItem + requestedAt?: number + turnOptions?: Readonly> + executionOptions?: AgentSessionExecutionOptions + signal?: AbortSignal + isCurrent?: () => boolean + admitFreshInput?: StructuredAgentSessionAdmitFreshInput +} + /** false means correlation capacity refused the send before writing; null turnId means an unnamed answer. */ export async function startCodexTurn( host: CodexTurnHost, - input: { - clientMessageId: string - body: AgentJournalMessageItem - requestedAt?: number + input: CodexTurnInput & { timeoutMs?: number - turnOptions?: Readonly> - signal?: AbortSignal - isCurrent?: () => boolean - admitFreshInput?: StructuredAgentSessionAdmitFreshInput onReply?: () => void } ): Promise<{ turnId: string | null; via: AgentJournalTurnJoin } | false> { @@ -90,8 +99,11 @@ export async function startCodexTurn( return steered } let previousApplied = host.appliedTurnOptions + let previousInput = host.appliedTurnInputOptions let previousOptions: Map | null | undefined let requested: Readonly> = {} + let inputChoices: Readonly> = {} + let requestControls: Record = {} let enqueued = false let discardSettingsAttempt: (() => void) | undefined const enqueue = ( @@ -110,14 +122,21 @@ export async function startCodexTurn( throw new StructuredAgentSessionInputNotAdmitted(undefined, 'permission') } previousApplied = host.appliedTurnOptions + previousInput = host.appliedTurnInputOptions + inputChoices = input.executionOptions ?? input.turnOptions ?? Object.fromEntries(host.options) previousOptions = input.turnOptions ? new Map(host.options) : null if (input.turnOptions) { host.options.clear() - for (const [key, value] of Object.entries(input.turnOptions)) { + for (const [key, value] of Object.entries( + codexMessageInputOptions(inputChoices, {}, input.turnOptions) + )) { host.options.set(key, value) } } - requested = { interactionMode: 'default', ...codexTurnRequestOptions(host) } + requested = { + interactionMode: 'default', + ...compileCodexMessageOptions(host, input.turnOptions ?? Object.fromEntries(host.options)) + } const { interactionMode, ...nativeOptions } = requested const collaborationMode = { mode: interactionMode, @@ -128,11 +147,21 @@ export async function startCodexTurn( developer_instructions: null } } + requestControls = { + ...requested, + ...(collaborationMode.settings.model ? { model: collaborationMode.settings.model } : {}), + ...(collaborationMode.settings.reasoning_effort + ? { effort: collaborationMode.settings.reasoning_effort } + : {}) + } const known = { ...previousApplied } - for (const key of Object.keys(requested)) { + const knownInput = { ...previousInput } + for (const key of new Set([...Object.keys(requested), ...Object.keys(inputChoices)])) { delete known[key] + delete knownInput[key] } host.appliedTurnOptions = known + host.appliedTurnInputOptions = knownInput discardSettingsAttempt = host.appliedSettings?.attempt(requested) enqueued = true host.dispatchEchoes.expect( @@ -202,9 +231,8 @@ export async function startCodexTurn( } if (isCodexAppServerRequestError(error) || isCodexAppServerUnsupportedError(error)) { discardSettingsAttempt?.() - } - if (isCodexAppServerRequestError(error) || isCodexAppServerUnsupportedError(error)) { host.appliedTurnOptions = previousApplied + host.appliedTurnInputOptions = previousInput if (previousOptions) { host.options.clear() for (const [key, value] of previousOptions) { @@ -215,22 +243,23 @@ export async function startCodexTurn( throw error } host.appliedTurnOptions = { ...previousApplied, ...requested } + host.appliedTurnInputOptions = codexMessageInputOptions( + inputChoices, + { + serviceTier: 'default', + ...requestControls, + ...previousInput, + interactionMode: requestControls.interactionMode + }, + requested + ) return { turnId: readCodexTurnId(answer), via: 'start' } } /** Replies establish admission; exact echoes establish identity. Timeouts cannot disprove delivery. */ export async function dispatchCodexTurn( session: CodexTurnHost, - input: { - sessionId: string - clientMessageId: string - body: AgentJournalMessageItem - requestedAt?: number - turnOptions?: Readonly> - signal?: AbortSignal - isCurrent?: () => boolean - admitFreshInput?: StructuredAgentSessionAdmitFreshInput - }, + input: CodexTurnInput & { sessionId: string }, timeoutMs: number | undefined ): Promise { let answer: { turnId: string | null; via: AgentJournalTurnJoin } | false @@ -270,12 +299,6 @@ export async function dispatchCodexTurn( return { state: 'rejected', ...codexDispatchRejection(agentSessionFailureFact('queueFull')) } } // An answer read after the turn it names already ended is settled by that end. - if (!answer.turnId) { - session.dispatchEchoes.answered( - input.clientMessageId, - answeredAt ?? session.dispatchEchoes.tick() - ) - } if (answer.turnId) { session.dispatchEchoes.bindTurn( input.clientMessageId, @@ -284,6 +307,11 @@ export async function dispatchCodexTurn( answer.via, answeredAt ) + } else { + session.dispatchEchoes.answered( + input.clientMessageId, + answeredAt ?? session.dispatchEchoes.tick() + ) } return { state: 'admitted', ranOptions: { ...session.appliedTurnOptions } } } diff --git a/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts b/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts new file mode 100644 index 00000000000..9e4974c5e0c --- /dev/null +++ b/src/main/computer/action-contracts/computer-blocked-key-combos.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { validateComputerProviderActionParams } from './computer-provider-action-validation' + +function sendKey( + method: 'hotkey' | 'pressKey', + key: string, + platform: NodeJS.Platform, + allowSystemShortcut?: boolean +): Promise { + return validateComputerProviderActionParams( + method, + { app: 'Target', key, ...(allowSystemShortcut ? { allowSystemShortcut } : {}) }, + platform + ) +} + +const BLOCKED: [NodeJS.Platform, 'hotkey' | 'pressKey', string][] = [ + ['darwin', 'hotkey', 'Cmd+Q'], + ['darwin', 'hotkey', 'CmdOrCtrl+q'], + ['darwin', 'hotkey', 'Shift+Command+Q'], + ['darwin', 'hotkey', 'Cmd+Option+Shift+Q'], + ['darwin', 'hotkey', 'Ctrl+Meta+Q'], + ['darwin', 'hotkey', 'Cmd+Alt+Esc'], + ['darwin', 'hotkey', 'Cmd+Shift+Delete'], + ['win32', 'hotkey', 'Alt+F4'], + ['win32', 'hotkey', 'Win+L'], + ['win32', 'hotkey', 'Ctrl+Shift+Escape'], + ['linux', 'hotkey', 'Ctrl+Q'], + ['linux', 'hotkey', 'CmdOrCtrl+Shift+Q'], + ['linux', 'hotkey', 'Alt+F4'], + ['linux', 'hotkey', 'Super+L'], + ['linux', 'hotkey', 'ctrl+alt+Delete'], + ['linux', 'hotkey', 'ctrl+alt+BackSpace'], + ['linux', 'hotkey', 'Ctrl+Alt+F2'], + ['linux', 'hotkey', 'Meta+F4'], + ['linux', 'hotkey', 'Ctrl+0x71'], + ['linux', 'hotkey', 'Alt+0xffc1'], + ['linux', 'hotkey', 'Alt+70'], + ['linux', 'hotkey', 'Alt+70suffix'], + ['linux', 'hotkey', 'Alt+70\rsuffix'], + ['linux', 'hotkey', 'Ctrl+Alt+L1'], + ['linux', 'hotkey', 'Ctrl+XF86Switch_VT_1'], + ['linux', 'pressKey', 'XF86_Switch_VT_2'], + ['linux', 'pressKey', 'Terminate_Server'], + ['linux', 'pressKey', 'XF86PowerOff'], + ['linux', 'pressKey', 'XF86_Sleep'], + ['linux', 'pressKey', 'ScreenSaver'], + ['linux', 'pressKey', '0x1008FF2A'] +] + +const ALLOWED: [NodeJS.Platform, 'hotkey' | 'pressKey', string][] = [ + ['darwin', 'hotkey', 'Cmd+A'], + ['darwin', 'hotkey', 'Ctrl+Q'], + ['darwin', 'hotkey', 'Cmd+ForwardDelete'], + ['darwin', 'pressKey', 'q'], + ['win32', 'hotkey', 'Ctrl+Q'], + ['win32', 'hotkey', 'Ctrl+Alt+Delete'], + ['linux', 'hotkey', 'Cmd+Q'], + ['linux', 'hotkey', 'Ctrl+Delete'], + ['linux', 'hotkey', 'Meta+L'], + ['linux', 'hotkey', 'Ctrl+u'], + ['linux', 'hotkey', 'Ctrl+1'], + ['linux', 'pressKey', 'Escape'] +] + +describe('blocked system shortcuts', () => { + it.each(BLOCKED)('refuses %s %s %s unless allowed', async (platform, method, key) => { + await expect(sendKey(method, key, platform)).rejects.toMatchObject({ + code: 'system_shortcut_blocked' + }) + await expect(sendKey(method, key, platform, true)).resolves.toBe('Target') + }) + + it.each(ALLOWED)('sends %s %s %s', async (platform, method, key) => { + await expect(sendKey(method, key, platform)).resolves.toBe('Target') + }) +}) diff --git a/src/main/computer/action-contracts/computer-blocked-key-combos.ts b/src/main/computer/action-contracts/computer-blocked-key-combos.ts new file mode 100644 index 00000000000..581f94a22aa --- /dev/null +++ b/src/main/computer/action-contracts/computer-blocked-key-combos.ts @@ -0,0 +1,177 @@ +import { RuntimeClientError } from '../runtime-client-error' + +// Design ported from vercel-labs/agent-desktop's per-platform blocked_combo lists (Apache-2.0). +type BlockedKeyCombo = { + modifiers: readonly string[] + keys: readonly string[] + effect: string +} + +type PlatformKeyRules = { + modifierAliases: Readonly> + keyAliases: Readonly> + canonicalKey?: (key: string) => string + // Most specific first so the error names what the combo would actually do. + blocked: readonly BlockedKeyCombo[] +} + +const SHARED_KEY_ALIASES = { esc: 'escape' } + +// Aliases mirror how each provider maps modifier names to physical keys. +const MACOS_RULES: PlatformKeyRules = { + modifierAliases: { + cmd: 'cmd', + command: 'cmd', + meta: 'cmd', + super: 'cmd', + win: 'cmd', + cmdorctrl: 'cmd', + commandorcontrol: 'cmd', + ctrl: 'ctrl', + control: 'ctrl', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + // The macOS provider sends both names as the same physical Delete key. + keyAliases: { ...SHARED_KEY_ALIASES, delete: 'backspace' }, + blocked: [ + { modifiers: ['cmd', 'ctrl'], keys: ['q'], effect: 'lock the screen' }, + { modifiers: ['cmd', 'shift'], keys: ['q'], effect: 'log out of macOS' }, + { modifiers: ['cmd', 'alt'], keys: ['escape'], effect: 'open the Force Quit window' }, + { modifiers: ['cmd', 'shift'], keys: ['backspace'], effect: 'empty the Trash' }, + { modifiers: ['cmd'], keys: ['q'], effect: 'quit the app' } + ] +} + +const WINDOWS_RULES: PlatformKeyRules = { + modifierAliases: { + ctrl: 'ctrl', + control: 'ctrl', + cmdorctrl: 'ctrl', + commandorcontrol: 'ctrl', + meta: 'win', + super: 'win', + win: 'win', + cmd: 'win', + command: 'win', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + keyAliases: SHARED_KEY_ALIASES, + // Ctrl+Alt+Delete is absent: Windows never honors a synthesized Secure Attention Sequence. + blocked: [ + { modifiers: ['alt'], keys: ['f4'], effect: 'close the app' }, + { modifiers: ['win'], keys: ['l'], effect: 'lock Windows' }, + { modifiers: ['ctrl', 'shift'], keys: ['escape'], effect: 'open Task Manager' } + ] +} + +const NUMERIC_KEYSYM = 'numeric keysym' + +const LINUX_RULES: PlatformKeyRules = { + modifierAliases: { + ctrl: 'ctrl', + control: 'ctrl', + cmdorctrl: 'ctrl', + commandorcontrol: 'ctrl', + // xdotool sends Meta_L, which default XKB layouts put on the Alt modifier. + meta: 'alt', + super: 'super', + win: 'super', + cmd: 'super', + command: 'super', + alt: 'alt', + option: 'alt', + shift: 'shift' + }, + // X11 names F11 and F12 L1 and L2 too. + keyAliases: { ...SHARED_KEY_ALIASES, l1: 'f11', l2: 'f12' }, + // Xlib and GDK resolve 0x/U hex keysyms and drop an optional XF86 prefix; xdotool reads any + // other token starting with a digit as a raw keycode (atoi ignores trailing text). + canonicalKey: (key) => + /^(\d[\s\S]+|u[0-9a-f]+)$/.test(key) ? NUMERIC_KEYSYM : key.replace(/^xf86_?/, ''), + blocked: [ + { + modifiers: [], + keys: [NUMERIC_KEYSYM], + effect: 'send a numeric keysym or keycode that computer use cannot check' + }, + { + modifiers: [], + keys: ['poweroff', 'powerdown', 'logoff', 'sleep', 'suspend', 'hibernate', 'standby'], + effect: 'power off, suspend or log out of the session' + }, + { modifiers: [], keys: ['screensaver'], effect: 'lock the screen' }, + { + modifiers: [], + keys: Array.from({ length: 12 }, (_, index) => `switch_vt_${index + 1}`), + effect: 'switch to another virtual terminal' + }, + { modifiers: [], keys: ['terminate_server'], effect: 'end the X session' }, + { + modifiers: ['ctrl', 'alt'], + keys: ['delete'], + effect: 'open the log out and power off dialog' + }, + { modifiers: ['ctrl', 'alt'], keys: ['backspace'], effect: 'end the X session' }, + { + modifiers: ['ctrl', 'alt'], + keys: ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12'], + effect: 'switch to another virtual terminal' + }, + { modifiers: ['ctrl', 'alt'], keys: ['l'], effect: 'lock the screen' }, + { modifiers: ['super'], keys: ['l'], effect: 'lock the screen' }, + { modifiers: ['alt'], keys: ['f4'], effect: 'close the window' }, + { modifiers: ['ctrl'], keys: ['q'], effect: 'quit the app' } + ] +} + +function platformKeyRules(platform: NodeJS.Platform): PlatformKeyRules { + if (platform === 'darwin') { + return MACOS_RULES + } + return platform === 'win32' ? WINDOWS_RULES : LINUX_RULES +} + +// Extra modifiers still match: Cmd+Alt+Shift+Q logs out just like Cmd+Shift+Q. +function findBlockedKeyCombo(key: string, platform: NodeJS.Platform): BlockedKeyCombo | null { + const rules = platformKeyRules(platform) + const parts = key === '+' ? ['+'] : key.split('+') + const modifiers = new Set() + let keyName = '' + for (const part of parts) { + const normalized = part.trim().toLowerCase() + const modifier = rules.modifierAliases[normalized.replace(/[\s_-]/g, '')] + if (modifier) { + modifiers.add(modifier) + } else { + const aliased = rules.keyAliases[normalized] ?? normalized + keyName = rules.canonicalKey ? rules.canonicalKey(aliased) : aliased + } + } + return ( + rules.blocked.find( + (combo) => + combo.keys.includes(keyName) && combo.modifiers.every((modifier) => modifiers.has(modifier)) + ) ?? null + ) +} + +export function assertComputerKeyComboAllowed( + params: Record, + key: string, + platform: NodeJS.Platform +): void { + if (params.allowSystemShortcut === true) { + return + } + const blocked = findBlockedKeyCombo(key, platform) + if (blocked) { + throw new RuntimeClientError( + 'system_shortcut_blocked', + `'${key}' would ${blocked.effect}, so computer use refuses it unless the caller passes --allow-system-shortcut` + ) + } +} diff --git a/src/main/computer/action-contracts/computer-provider-action-validation.ts b/src/main/computer/action-contracts/computer-provider-action-validation.ts index d6bc202b0a8..adca833329a 100644 --- a/src/main/computer/action-contracts/computer-provider-action-validation.ts +++ b/src/main/computer/action-contracts/computer-provider-action-validation.ts @@ -3,6 +3,7 @@ import { computerUseHotkeyValidationMessage, computerUsePressKeyValidationMessage } from '../../../shared/computer-use-key-spec' +import { assertComputerKeyComboAllowed } from './computer-blocked-key-combos' import { validateComputerClipboardPasteTextWithBoundedYield } from './computer-clipboard-paste-validation' import { RuntimeClientError } from '../runtime-client-error' @@ -19,7 +20,8 @@ type ComputerProviderActionMethod = export async function validateComputerProviderActionParams( method: ComputerProviderActionMethod, - params: Record + params: Record, + platform: NodeJS.Platform = process.platform ): Promise { const app = requireNonEmptyString(params, 'app') validateWindowTarget(params) @@ -49,10 +51,10 @@ export async function validateComputerProviderActionParams( await validatePasteText(params) return app case 'pressKey': - validatePressKey(params) + validatePressKey(params, platform) return app case 'hotkey': - validateHotkey(params) + validateHotkey(params, platform) return app case 'setValue': requireNonNegativeInteger(params, 'elementIndex') @@ -182,20 +184,22 @@ function validateScrollDirection(params: Record): void { } } -function validatePressKey(params: Record): void { +function validatePressKey(params: Record, platform: NodeJS.Platform): void { const key = requireNonEmptyString(params, 'key') const message = computerUsePressKeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } + assertComputerKeyComboAllowed(params, key, platform) } -function validateHotkey(params: Record): void { +function validateHotkey(params: Record, platform: NodeJS.Platform): void { const key = requireNonEmptyString(params, 'key') const message = computerUseHotkeyValidationMessage(key) if (message) { throw new RuntimeClientError('invalid_argument', message) } + assertComputerKeyComboAllowed(params, key, platform) } function validatePasteText(params: Record): Promise | void { 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/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/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/git/command-runner/git-exec-file.ts b/src/main/git/command-runner/git-exec-file.ts index bdfa4412410..eb7865fac23 100644 --- a/src/main/git/command-runner/git-exec-file.ts +++ b/src/main/git/command-runner/git-exec-file.ts @@ -30,6 +30,7 @@ import { createAbortError } from './process-capture/abort-error' import { readCapturedGitBuffer, readCapturedGitString } from './process-capture/captured-git-output' import { runUnlessGitCwdKnownMissing } from './host-routing/missing-git-spawn-cwd' import { trackGitWorktreeMutation } from './git-worktree-mutation-state' +import { trackGitRefMutation } from './git-ref-mutation-state' import { routeLocalGitOptions, runAdmittedWslGit } from './host-routing/local-git-runtime-route' import { gitRunsIn } from './host-routing/git-runs-in' @@ -190,6 +191,7 @@ export function gitExecFileAsync( ): Promise<{ stdout: string; stderr: string }> { const options = routeLocalGitOptions(callerOptions) const releaseMutation = trackGitWorktreeMutation(args, options) + const releaseRefMutation = trackGitRefMutation(args) const terminationState: { current: Promise | null } = { current: null } const command = resolveGitFetchHeadCommand(args, options.cwd) // Missing folders start no child and must not record a git.exec span. @@ -209,8 +211,10 @@ export function gitExecFileAsync( // A timed-out caller can settle before its child exits. if (terminationState.current) { void terminationState.current.then(releaseMutation) + void terminationState.current.then(releaseRefMutation) } else { releaseMutation() + releaseRefMutation() } }) } diff --git a/src/main/git/command-runner/git-ref-mutation-state.test.ts b/src/main/git/command-runner/git-ref-mutation-state.test.ts new file mode 100644 index 00000000000..ba65218930c --- /dev/null +++ b/src/main/git/command-runner/git-ref-mutation-state.test.ts @@ -0,0 +1,88 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type * as Capture from './process-capture/exec-file-capture' + +const io = vi.hoisted(() => ({ capture: vi.fn() })) +vi.mock('./process-capture/exec-file-capture', async (original) => ({ + ...(await original()), + execFileCapture: io.capture +})) +import { trackGitRefMutation } from './git-ref-mutation-state' +import { gitExecFileAsync } from './git-exec-file' +import { subscribeGitRefChanges } from '../refs/git-ref-change-signal' + +const disposers: (() => void)[] = [] +afterEach(() => { + disposers.splice(0).forEach((dispose) => dispose()) + io.capture.mockReset() +}) + +it('preserves warm refs for reads and proven object/index operations, and fences all for ref writes', () => { + const events: string[] = [] + disposers.push(subscribeGitRefChanges('/a/.git', () => events.push('a'))) + disposers.push(subscribeGitRefChanges('/b/.git', () => events.push('b'))) + for (const args of [ + ['for-each-ref'], + ['remote'], + ['config', '--get', 'remote.origin.url'], + ['worktree', 'list', '--porcelain'], + ['ls-remote'], + ['add', '.'], + ['update-index', '--refresh'], + ['hash-object', '-w', 'file'], + ['restore', '--staged', '.'], + ['apply', '--cached'], + ['merge-tree', '--write-tree'] + ]) { + trackGitRefMutation(args)() + } + expect(events).toEqual([]) + for (const args of [ + ['commit'], + ['push'], + ['pull'], + ['fetch'], + ['branch', 'topic'], + ['config', 'remote.origin.url', 'url'], + ['worktree', 'add', 'path'], + ['custom-alias'] + ]) { + const end = trackGitRefMutation(args) + expect(events.splice(0)).toEqual(['a', 'b']) + end() + end() + expect(events.splice(0)).toEqual(['a', 'b']) + } +}) + +it('keeps the runner completion fence at child termination after a timed-out caller settles', async () => { + const events: string[] = [] + disposers.push(subscribeGitRefChanges('/runner-a/.git', () => events.push('a'))) + disposers.push(subscribeGitRefChanges('/runner-b/.git', () => events.push('b'))) + let started!: () => void + const ready = new Promise((resolve) => { + started = resolve + }) + let terminated!: () => void + let rejectCapture!: (error: Error) => void + io.capture.mockImplementationOnce((_command, _args, options) => { + terminated = options.onChildTerminated + started() + return new Promise((_resolve, reject) => { + rejectCapture = reject + }) + }) + const result = gitExecFileAsync(['branch', 'topic'], { + cwd: process.cwd(), + admissionExempt: true + }) + expect(events.splice(0)).toEqual(['a', 'b']) + await ready + const failure = expect(result).rejects.toThrow('deadline') + rejectCapture(new Error('deadline')) + await failure + expect(events).toEqual([]) + disposers.push(subscribeGitRefChanges('/runner-new/.git', () => events.push('new'))) + terminated() + await new Promise(setImmediate) + expect(events).toEqual(['a', 'b', 'new']) +}) diff --git a/src/main/git/command-runner/git-ref-mutation-state.ts b/src/main/git/command-runner/git-ref-mutation-state.ts new file mode 100644 index 00000000000..06209798328 --- /dev/null +++ b/src/main/git/command-runner/git-ref-mutation-state.ts @@ -0,0 +1,23 @@ +import { + classifyGitCommand, + findGitSubcommandIndex +} from '../../../shared/git/commands/git-command-classification' +import { beginGitRefMutation } from '../refs/git-ref-change-signal' + +export function trackGitRefMutation(args: readonly string[]): () => void { + if (classifyGitCommand(args) === 'read') { + return () => {} + } + const index = findGitSubcommandIndex(args) + const command = args[index] + const flags = args.slice(index + 1) + if ( + ['ls-remote', 'add', 'update-index', 'hash-object'].includes(command) || + (command === 'restore' && flags.includes('--staged')) || + (command === 'apply' && flags.includes('--cached')) || + (command === 'merge-tree' && flags.includes('--write-tree')) + ) { + return () => {} + } + return beginGitRefMutation(null) +} diff --git a/src/main/git/command-runner/git-stream-stdout.ts b/src/main/git/command-runner/git-stream-stdout.ts index d501e1c3eb0..940b5e6371f 100644 --- a/src/main/git/command-runner/git-stream-stdout.ts +++ b/src/main/git/command-runner/git-stream-stdout.ts @@ -41,6 +41,8 @@ export type GitStreamOptions = { signal?: AbortSignal /** Byte backstop; defaults to DEFAULT_GIT_MAX_BUFFER. */ maxBuffer?: number + /** Independent stderr cap for parsers that stream an arbitrarily large population. */ + maxStderrBuffer?: number /** Explicit wall-clock deadline; read commands default to the production backstop. */ timeoutMs?: number /** Overrides only the default read deadline in tests. */ @@ -212,7 +214,7 @@ function streamInSpan( } function onStderrData(chunk: Buffer): void { stderrBytes += chunk.byteLength - if (stderrBytes > maxBuffer) { + if (stderrBytes > (options.maxStderrBuffer ?? maxBuffer)) { void killSpawnedCommandTree(child) finish(new Error('git stderr exceeded maxBuffer.')) return diff --git a/src/main/git/refs/git-ref-change-signal.ts b/src/main/git/refs/git-ref-change-signal.ts new file mode 100644 index 00000000000..9cd7f2c9e28 --- /dev/null +++ b/src/main/git/refs/git-ref-change-signal.ts @@ -0,0 +1,44 @@ +import { gitRepositoryPathKey } from '../../../shared/git/metadata/git-repository-path-key' +type Listener = () => void +const listeners = new Map>() + +export function subscribeGitRefChanges(commonDir: string, listener: Listener): () => void { + commonDir = gitRepositoryPathKey(commonDir) + const subscribers = listeners.get(commonDir) ?? new Set() + subscribers.add(listener) + listeners.set(commonDir, subscribers) + return () => { + subscribers.delete(listener) + if (subscribers.size === 0 && listeners.get(commonDir) === subscribers) { + listeners.delete(commonDir) + } + } +} + +/** Unknown checkout ownership fences every live reader without delaying the mutation for discovery. */ +export function publishGitRefChange(commonDir: string | null): void { + commonDir = commonDir === null ? null : gitRepositoryPathKey(commonDir) + const targets = commonDir === null ? [...listeners.values()] : [listeners.get(commonDir)] + for (const subscribers of targets) { + const callbacks = Array.from(subscribers ?? []) + for (const listener of callbacks) { + try { + listener() + } catch { + // Cache bookkeeping must never refuse a Git action. + } + } + } +} + +export function beginGitRefMutation(commonDir: string | null): () => void { + publishGitRefChange(commonDir) + let ended = false + return () => { + if (ended) { + return + } + ended = true + publishGitRefChange(commonDir) + } +} diff --git a/src/main/git/refs/resolution/base-ref-search-selector.test.ts b/src/main/git/refs/resolution/base-ref-search-selector.test.ts index 86b9adeca68..d5b94a9ae6b 100644 --- a/src/main/git/refs/resolution/base-ref-search-selector.test.ts +++ b/src/main/git/refs/resolution/base-ref-search-selector.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest' -import { parseAndFilterSearchRefDetails } from './repo-base-ref-search' import { resolveBaseRefSearchSelector } from './base-ref-search-selector' describe('base ref search selectors', () => { @@ -39,24 +38,4 @@ describe('base ref search selectors', () => { ])('preserves the identity of %s with short field %s', (full, short, expected) => { expect(resolveBaseRefSearchSelector(full, short)).toBe(expected) }) - - it('filters unsupported selectors before the page limit and deduplicates recovered full refs', () => { - const stdout = [ - 'refs/heads/feature/加\0feature/�', - 'refs/heads/feature/加\0feature/�', - 'refs/remotes/origin/feature/加\0origin/feature/�', - 'refs/heads/safe-one\0safe-one', - 'refs/heads/safe-two\0safe-two', - 'refs/heads/safe-three\0safe-three' - ].join('\n') - expect(parseAndFilterSearchRefDetails(stdout, 2, ['origin'], false)).toEqual([ - { refName: 'safe-one', localBranchName: 'safe-one' }, - { refName: 'safe-two', localBranchName: 'safe-two' } - ]) - expect(parseAndFilterSearchRefDetails(stdout, 3, ['origin'])).toEqual([ - { refName: 'refs/heads/feature/加', localBranchName: 'feature/加' }, - { refName: 'refs/remotes/origin/feature/加', localBranchName: 'feature/加' }, - { refName: 'safe-one', localBranchName: 'safe-one' } - ]) - }) }) diff --git a/src/main/git/refs/resolution/repo-base-ref-search.ts b/src/main/git/refs/resolution/repo-base-ref-search.ts index 4aed3dd18f4..59e17cb9180 100644 --- a/src/main/git/refs/resolution/repo-base-ref-search.ts +++ b/src/main/git/refs/resolution/repo-base-ref-search.ts @@ -5,41 +5,9 @@ import { REPO_SEARCH_REFS_DEFAULT_LIMIT, isRepoSearchRefsRequestLimit } from '../../../../shared/repo-search-limits' -import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' -import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' -import { runSearchBaseRefsGit } from './repo-ref-search-command' - -import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { isQualifiedBaseRef, resolveBaseRefSearchSelector } from './base-ref-search-selector' - -type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot' -function getRefSearchTokens(query: string) { - return query.split('/').filter(Boolean) -} - -export function mergeBaseRefSearchResultGroups( - groups: readonly BaseRefSearchResult[][], - limit: number -): BaseRefSearchResult[] { - const seen = new Set() - const merged: BaseRefSearchResult[] = [] - const maxLength = Math.max(0, ...groups.map((group) => group.length)) - for (let index = 0; index < maxLength && merged.length < limit; index += 1) { - for (const group of groups) { - const entry = group[index] - if (!entry || seen.has(entry.refName)) { - continue - } - seen.add(entry.refName) - merged.push(entry) - if (merged.length >= limit) { - break - } - } - } - return merged -} +import { searchBranchRefSnapshot, snapshotRemoteNames } from '../snapshot/branch-ref-snapshot' +import { searchLegacyBaseRefDetails } from './repo-legacy-ref-search' +import type { LocalGitExecOptions } from './repo-default-base-ref' export async function searchBaseRefs( path: string, @@ -63,42 +31,13 @@ export async function searchBaseRefDetails( if (!isRepoSearchRefsRequestLimit(limit)) { return [] } - const boundedScanLimit = clampRepoSearchRefsScanLimit(limit) - const normalizedQuery = normalizeRefSearchQuery(query) - + if (!includeQualifiedRefs) { + return searchLegacyBaseRefDetails(path, query, limit, git) + } try { - const remotes = await listRemoteNames(path, git) - const search = (patternGroup?: RefSearchPatternGroup): Promise<{ stdout: string }> => - runSearchBaseRefsGit(path, normalizedQuery, boundedScanLimit, { - remoteNames: remotes, - patternGroup, - git - }) - const tokens = getRefSearchTokens(normalizedQuery) - if (tokens.length > 1) { - const results = await Promise.all([search('segmented'), search('branchRoot')]) - return mergeBaseRefSearchResultGroups( - results.map((entry) => - parseAndFilterSearchRefDetails( - entry.stdout, - boundedScanLimit, - remotes, - includeQualifiedRefs - ) - ), - boundedScanLimit - ) - } - - const result = await search() - return parseAndFilterSearchRefDetails( - result.stdout, - boundedScanLimit, - remotes, - includeQualifiedRefs - ) + return await searchBranchRefSnapshot(path, query, clampRepoSearchRefsScanLimit(limit), git) } catch (err) { - console.warn('[searchBaseRefs] for-each-ref failed', { path, err }) + console.warn('[searchBaseRefs] branch snapshot failed', { path, err }) return [] } } @@ -108,91 +47,8 @@ export async function listRemoteNames( options: LocalGitExecOptions = {} ): Promise { try { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - return stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) + return await snapshotRemoteNames(path, options) } catch { return [] } } - -export function parseAndFilterSearchRefDetails( - stdout: string, - limit: number, - remotes: string[] = [], - includeQualifiedRefs = true -): BaseRefSearchResult[] { - const seen = new Set() - const sortedRemotes = [...remotes].sort((a, b) => b.length - a.length) - - return stdout - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.length > 0) - .map((line) => { - const nul = line.indexOf('\0') - if (nul === -1) { - return null - } - const full = line.slice(0, nul) - const gitShort = line.slice(nul + 1) - return { full, short: resolveBaseRefSearchSelector(full, gitShort) } - }) - .filter((entry): entry is { full: string; short: string } => entry !== null) - .filter(({ full }) => isSafeGitRefName(full) && !isRemoteHeadRef(full, sortedRemotes)) - .filter(({ short }) => includeQualifiedRefs || !isQualifiedBaseRef(short)) - .filter(({ short }) => { - if (seen.has(short)) { - return false - } - seen.add(short) - return true - }) - .map(({ full, short }) => ({ - refName: short, - localBranchName: resolveLocalBranchName(full, short, sortedRemotes) - })) - .slice(0, Math.max(0, limit)) -} - -export function resolveConfiguredRemoteBranchName( - fullRef: string, - longestFirstRemoteNames: readonly string[] -): string | null { - const remoteRefPrefix = 'refs/remotes/' - if (!fullRef.startsWith(remoteRefPrefix)) { - return null - } - const remoteAndBranch = fullRef.slice(remoteRefPrefix.length) - const remote = longestFirstRemoteNames.find((candidate) => - remoteAndBranch.startsWith(`${candidate}/`) - ) - return remote ? remoteAndBranch.slice(remote.length + 1) || null : null -} - -export function resolveLocalBranchName( - fullRef: string, - shortRef: string, - remotes: string[] -): string { - const localRefPrefix = 'refs/heads/' - if (fullRef.startsWith(localRefPrefix)) { - return fullRef.slice(localRefPrefix.length) || shortRef - } - const remoteRefPrefix = 'refs/remotes/' - if (!fullRef.startsWith(remoteRefPrefix)) { - return shortRef - } - const configuredBranch = resolveConfiguredRemoteBranchName(fullRef, remotes) - if (configuredBranch) { - return configuredBranch - } - const remoteAndBranch = fullRef.slice(remoteRefPrefix.length) - return remoteAndBranch.split('/').slice(1).join('/') || shortRef -} - -export function normalizeRefSearchQuery(query: string): string { - return query.trim().replace(/[*?[\]\\]/g, '') -} diff --git a/src/main/git/refs/resolution/repo-branch-conflict.ts b/src/main/git/refs/resolution/repo-branch-conflict.ts index 0d6efa0ca93..973e3225ae9 100644 --- a/src/main/git/refs/resolution/repo-branch-conflict.ts +++ b/src/main/git/refs/resolution/repo-branch-conflict.ts @@ -1,4 +1,4 @@ -import { resolveConfiguredRemoteBranchName } from './repo-base-ref-search' +import { resolveConfiguredRemoteBranchName } from '../snapshot/branch-ref-snapshot-data' import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' import { gitExecFileAsync } from '../../command-runner/git-exec-file' import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' diff --git a/src/main/git/refs/resolution/repo-legacy-ref-search.ts b/src/main/git/refs/resolution/repo-legacy-ref-search.ts new file mode 100644 index 00000000000..ca952513b24 --- /dev/null +++ b/src/main/git/refs/resolution/repo-legacy-ref-search.ts @@ -0,0 +1,170 @@ +import { resolveLocalBranchName } from '../snapshot/branch-ref-snapshot-data' +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { + clampRepoSearchRefsScanLimit, + REPO_SEARCH_REFS_DEFAULT_LIMIT, + isRepoSearchRefsRequestLimit +} from '../../../../shared/repo-search-limits' +import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' +import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' +import { runSearchBaseRefsGit } from './repo-ref-search-command' + +import { gitExecOptions, type LocalGitExecOptions } from './repo-default-base-ref' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { isQualifiedBaseRef, resolveBaseRefSearchSelector } from './base-ref-search-selector' + +type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot' +function getRefSearchTokens(query: string) { + return query.split('/').filter(Boolean) +} + +export function mergeBaseRefSearchResultGroups( + groups: readonly BaseRefSearchResult[][], + limit: number +): BaseRefSearchResult[] { + const seen = new Set() + const merged: BaseRefSearchResult[] = [] + const maxLength = Math.max(0, ...groups.map((group) => group.length)) + for (let index = 0; index < maxLength && merged.length < limit; index += 1) { + for (const group of groups) { + const entry = group[index] + if (!entry || seen.has(entry.refName)) { + continue + } + seen.add(entry.refName) + merged.push(entry) + if (merged.length >= limit) { + break + } + } + } + return merged +} + +export async function searchLegacyBaseRefDetails( + path: string, + query: string, + limit = REPO_SEARCH_REFS_DEFAULT_LIMIT, + git: LocalGitExecOptions = {} +): Promise { + if (!isRepoSearchRefsRequestLimit(limit)) { + return [] + } + const boundedScanLimit = clampRepoSearchRefsScanLimit(limit) + const normalizedQuery = normalizeRefSearchQuery(query) + + try { + const remotes = await listRemoteNames(path, git) + const search = (patternGroup?: RefSearchPatternGroup): Promise<{ stdout: string }> => + runSearchBaseRefsGit(path, normalizedQuery, boundedScanLimit, { + remoteNames: remotes, + patternGroup, + git + }) + const tokens = getRefSearchTokens(normalizedQuery) + if (tokens.length > 1) { + const results = await Promise.all([search('segmented'), search('branchRoot')]) + return mergeBaseRefSearchResultGroups( + results.map((entry) => + parseAndFilterSearchRefDetails(entry.stdout, boundedScanLimit, remotes, false) + ), + boundedScanLimit + ) + } + + const result = await search() + return parseAndFilterSearchRefDetails(result.stdout, boundedScanLimit, remotes, false) + } catch (err) { + console.warn('[searchBaseRefs] for-each-ref failed', { path, err }) + return [] + } +} + +export async function listRemoteNames( + path: string, + options: LocalGitExecOptions = {} +): Promise { + try { + const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) + return stdout + .split('\n') + .map((line) => line.trim()) + .filter(Boolean) + } catch { + return [] + } +} + +export function parseAndFilterSearchRefDetails( + stdout: string, + limit: number, + remotes: string[] = [], + includeQualifiedRefs = true +): BaseRefSearchResult[] { + const seen = new Set() + const sortedRemotes = [...remotes].sort((a, b) => b.length - a.length) + + return stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line.length > 0) + .map((line) => { + const nul = line.indexOf('\0') + if (nul === -1) { + return null + } + const full = line.slice(0, nul) + const gitShort = line.slice(nul + 1) + return { full, short: resolveBaseRefSearchSelector(full, gitShort) } + }) + .filter((entry): entry is { full: string; short: string } => entry !== null) + .filter(({ full }) => isSafeGitRefName(full) && !isRemoteHeadRef(full, sortedRemotes)) + .filter(({ short }) => includeQualifiedRefs || !isQualifiedBaseRef(short)) + .filter(({ short }) => { + if (seen.has(short)) { + return false + } + seen.add(short) + return true + }) + .map(({ full, short }) => ({ + refName: short, + localBranchName: resolveLocalBranchName(full, short, sortedRemotes) + })) + .slice(0, Math.max(0, limit)) +} + +export function normalizeRefSearchQuery(query: string): string { + return query.trim().replace(/[*?[\]\\]/g, '') +} + +export async function searchLegacyRemoteRefPage( + path: string, + query: string, + limit: number +): Promise<{ refDetails: BaseRefSearchResult[]; truncated: boolean }> { + const { stdout } = await gitExecFileAsync(['remote'], { cwd: path }) + const remoteNames = stdout.split('\n').filter(Boolean) + const normalized = normalizeRefSearchQuery(query) + const groups: ('segmented' | 'branchRoot' | 'all')[] = + normalized.split('/').filter(Boolean).length > 1 ? ['segmented', 'branchRoot'] : ['all'] + const results = await Promise.all( + groups.map((patternGroup) => + runSearchBaseRefsGit(path, normalized, limit + 1, { + namespace: 'remote', + remoteNames, + patternGroup + }) + ) + ) + const candidates = mergeBaseRefSearchResultGroups( + results.map((result) => parseAndFilterSearchRefDetails(result.stdout, limit + 1, remoteNames)), + limit + 1 + ) + return { + refDetails: candidates.slice(0, limit), + truncated: + candidates.length > limit || + results.some((result) => result.stdout.split('\n').filter(Boolean).length >= (limit + 1) * 4) + } +} diff --git a/src/main/git/refs/resolution/repo-remote-ref-search.ts b/src/main/git/refs/resolution/repo-remote-ref-search.ts index 59cece9edb9..45837f6359f 100644 --- a/src/main/git/refs/resolution/repo-remote-ref-search.ts +++ b/src/main/git/refs/resolution/repo-remote-ref-search.ts @@ -1,39 +1,30 @@ +import { searchLegacyRemoteRefPage } from './repo-legacy-ref-search' import type { BaseRefSearchResult } from '../../../../shared/repo-types' -import { gitExecFileAsync } from '../../command-runner/git-exec-file' -import { runSearchBaseRefsGit } from './repo-ref-search-command' import { - normalizeRefSearchQuery, - parseAndFilterSearchRefDetails, - mergeBaseRefSearchResultGroups -} from './repo-base-ref-search' + clampRepoSearchRefsLimit, + getRepoSearchRefsProbeLimit +} from '../../../../shared/repo-search-limits' +import { searchBranchRefSnapshot } from '../snapshot/branch-ref-snapshot' export async function searchRemoteRefPage( path: string, query: string, - limit: number + limit: number, + includeQualifiedRefs = true ): Promise<{ refDetails: BaseRefSearchResult[]; truncated: boolean }> { - const { stdout } = await gitExecFileAsync(['remote'], { cwd: path }) - const remoteNames = stdout.split('\n').filter(Boolean) - const normalized = normalizeRefSearchQuery(query) - const groups: ('segmented' | 'branchRoot' | 'all')[] = - normalized.split('/').filter(Boolean).length > 1 ? ['segmented', 'branchRoot'] : ['all'] - const results = await Promise.all( - groups.map((patternGroup) => - runSearchBaseRefsGit(path, normalized, limit + 1, { - namespace: 'remote', - remoteNames, - patternGroup - }) - ) - ) - const candidates = mergeBaseRefSearchResultGroups( - results.map((result) => parseAndFilterSearchRefDetails(result.stdout, limit + 1, remoteNames)), - limit + 1 + if (!includeQualifiedRefs) { + return searchLegacyRemoteRefPage(path, query, limit) + } + const bounded = clampRepoSearchRefsLimit(limit) + const candidates = await searchBranchRefSnapshot( + path, + query, + getRepoSearchRefsProbeLimit(bounded), + {}, + true ) return { - refDetails: candidates.slice(0, limit), - truncated: - candidates.length > limit || - results.some((result) => result.stdout.split('\n').filter(Boolean).length >= (limit + 1) * 4) + refDetails: candidates.slice(0, bounded), + truncated: limit > bounded || candidates.length > bounded } } diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts new file mode 100644 index 00000000000..758d8f95613 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-data.ts @@ -0,0 +1,117 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { branchRefLabel } from '../../../../shared/git/refs/branch-ref-label' +import { isSafeGitRefName } from '../../../../shared/git/status/git-status-upstream-ref' +import { isRemoteHeadRef } from '../../../../shared/source-control/hosted-review/hosted-review-refs' + +export type BranchRef = { + refName: string + oid: string + committedAt: number + symref: string + label: string + searchName: string +} + +export const BRANCH_REF_SNAPSHOT_ARGS = [ + 'for-each-ref', + '--sort=refname', + '--sort=-committerdate', + '--format=%(refname)%00%(objectname)%00%(committerdate:unix)%00%(symref)', + 'refs/heads', + 'refs/remotes' +] + +export function parseBranchRef(line: string): BranchRef | null { + const [refName, oid, timestamp, symref = ''] = line.replace(/\r$/, '').split('\0') + if (!refName || !oid || !isSafeGitRefName(refName) || !/^refs\/(heads|remotes)\//.test(refName)) { + return null + } + const label = branchRefLabel(refName) + return { + refName, + oid, + committedAt: Number.isFinite(Number(timestamp)) ? Number(timestamp) * 1000 : 0, + symref, + label, + searchName: label.toLowerCase() + } +} + +export function resolveConfiguredRemoteBranchName( + fullRef: string, + longestFirstRemoteNames: readonly string[] +): string | null { + if (!fullRef.startsWith('refs/remotes/')) { + return null + } + const remoteAndBranch = fullRef.slice('refs/remotes/'.length) + const remote = longestFirstRemoteNames.find((name) => remoteAndBranch.startsWith(`${name}/`)) + return remote ? remoteAndBranch.slice(remote.length + 1) || null : null +} + +export function resolveLocalBranchName( + fullRef: string, + fallback: string, + remotes: string[] +): string { + if (fullRef.startsWith('refs/heads/')) { + return fullRef.slice('refs/heads/'.length) || fallback + } + if (!fullRef.startsWith('refs/remotes/')) { + return fallback + } + return ( + (resolveConfiguredRemoteBranchName(fullRef, remotes) ?? + fullRef.slice('refs/remotes/'.length).split('/').slice(1).join('/')) || + fallback + ) +} + +export function matchesBranchRef(ref: BranchRef, query: string, remoteOnly: boolean): boolean { + return (!remoteOnly || ref.refName.startsWith('refs/remotes/')) && ref.searchName.includes(query) +} + +export function projectBranchRefs( + refs: Iterable, + remotes: string[], + query: string, + limit: number, + remoteOnly = false +): BaseRefSearchResult[] { + const results: BaseRefSearchResult[] = [] + const project = createBranchRefProjection(remotes, query, remoteOnly) + for (const ref of refs) { + const result = project(ref) + if (result) { + results.push(result) + } + if (results.length >= limit) { + break + } + } + return results +} + +export function createBranchRefProjection( + remotes: string[], + query: string, + remoteOnly = false +): (ref: BranchRef) => BaseRefSearchResult | null { + const normalized = query + .trim() + .replace(/[*?[\]\\]/g, '') + .toLowerCase() + const longestFirst = [...remotes].sort((left, right) => right.length - left.length) + return (ref) => { + if ( + !matchesBranchRef(ref, normalized, remoteOnly) || + isRemoteHeadRef(ref.refName, longestFirst) + ) { + return null + } + return { + refName: ref.refName, + localBranchName: resolveLocalBranchName(ref.refName, ref.label, longestFirst) + } + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts new file mode 100644 index 00000000000..b033ab634c9 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-identity.ts @@ -0,0 +1,61 @@ +import { realpath, stat } from 'node:fs/promises' +import { dirname } from 'node:path' +import { resolveGitCommonDirectory } from '../../../../shared/git/metadata/git-common-directory' +import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path' +import { gitRepositoryPathKey } from '../../../../shared/git/metadata/git-repository-path-key' +import { wslDistroForCommand } from '../../../../shared/wsl-paths' +import { routeLocalGitOptions } from '../../command-runner/host-routing/local-git-runtime-route' +import { prepareWslLinkedWorktreeGitRouting } from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' +import { blockedWslDistroForPath } from '../../../wsl/filesystem/wsl-unc-access-gate' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { resolveGitDir } from '../../source-control/resolve-git-dir' + +export type BranchSnapshotIdentity = { + key: string + commonDir: string + gitDir: string + checkoutKey: string + cwd: string + git: LocalGitExecOptions +} + +export async function resolveBranchSnapshotIdentity( + cwd: string, + git: LocalGitExecOptions +): Promise { + const routed = routeLocalGitOptions({ cwd, ...git }) + if (await blockedWslDistroForPath(cwd, routed.wslDistro)) { + throw new Error('The project Git runtime is not running') + } + const distro = (await prepareWslLinkedWorktreeGitRouting(cwd, routed.wslDistro)) + ? null + : wslDistroForCommand(cwd, routed.wslDistro) + const runtime = distro ? `wsl:${distro.toLowerCase()}` : 'host' + let hostRoot = await realpath(resolveWorktreeHostPath(cwd, routed) ?? cwd) + let commonDir = await resolveGitCommonDirectory(hostRoot, routed) + while (!commonDir) { + const parent = dirname(hostRoot) + if (parent === hostRoot) { + return null + } + hostRoot = parent + commonDir = await resolveGitCommonDirectory(hostRoot, routed) + } + const physicalCommonDir = await realpath(commonDir) + const commonStat = await stat(physicalCommonDir, { bigint: true }) + const checkoutGitDir = await resolveGitDir(hostRoot, routed) + const gitDir = await stat(checkoutGitDir).then( + (entry) => (entry.isDirectory() ? checkoutGitDir : commonDir), + () => commonDir + ) + const physicalGitDir = await realpath(gitDir) + const checkoutStat = await stat(physicalGitDir, { bigint: true }) + return { + key: `${runtime}\0${gitRepositoryPathKey(physicalCommonDir)}\0${commonStat.dev}:${commonStat.ino}:${commonStat.birthtimeNs}`, + commonDir: physicalCommonDir, + gitDir: physicalGitDir, + checkoutKey: `${gitRepositoryPathKey(physicalGitDir)}\0${checkoutStat.dev}:${checkoutStat.ino}:${checkoutStat.birthtimeNs}`, + cwd, + git: routed + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts new file mode 100644 index 00000000000..77c393f4bdd --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-metadata.ts @@ -0,0 +1,52 @@ +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import type { BranchSnapshotOwners, Owner, Context } from './branch-ref-snapshot-owners' +import { readBranchRemoteNames } from './branch-ref-snapshot-read' + +const MAX_CONTEXTS = 64 + +export class BranchSnapshotMetadata { + constructor(private readonly cache: BranchSnapshotOwners) {} + + context(owner: Owner, identity: BranchSnapshotIdentity): Context { + const key = identity.checkoutKey + const existing = owner.contexts.get(key) + if (existing) { + return existing + } + if (owner.contexts.size >= MAX_CONTEXTS) { + const oldest = owner.contexts.keys().next().value + if (oldest !== undefined) { + this.cache.retireContext(owner, oldest, owner.contexts.get(oldest)!) + } + } + const context: Context = { + leases: new Set(), + remotes: Promise.resolve([]) + } + const current = () => !owner.disposed && owner.contexts.get(key) === context + const lease = this.cache.lease(owner, current) + owner.contexts.set(key, context) + context.remotes = readBranchRemoteNames(identity.cwd, identity.git) + .then(async (remotes) => { + await this.cache.validate(identity, owner) + if (lease.reserve(256 + remotes.reduce((sum, name) => sum + 48 + name.length * 2, 0))) { + context.leases.add(lease) + } else { + this.cache.retireContext(owner, key, context) + } + return remotes + }) + .catch((error: unknown) => { + this.cache.retireContext(owner, key, context) + throw error + }) + return context + } + + async remoteNames(identity: BranchSnapshotIdentity): Promise { + const owner = this.cache.owner(identity) + return owner + ? this.context(owner, identity).remotes + : readBranchRemoteNames(identity.cwd, identity.git) + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts new file mode 100644 index 00000000000..0d4685e46fd --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-owners.ts @@ -0,0 +1,174 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import { + resolveBranchSnapshotIdentity, + type BranchSnapshotIdentity +} from './branch-ref-snapshot-identity' +import type { BranchRef } from './branch-ref-snapshot-data' +import { + BRANCH_SNAPSHOT_MAX_BYTES, + type BranchRefSnapshot, + type BranchSnapshotRetention +} from './branch-ref-snapshot-read' + +export const BRANCH_SNAPSHOT_TTL_MS = 2 * 60_000 +const MAX_OWNERS = 64 +export class BranchSnapshotIdentityChanged extends Error {} + +export type Lease = BranchSnapshotRetention & { bytes: number } +export type Context = { + remotes: Promise + leases: Set +} +export type Capture = { + snapshot: BranchRefSnapshot | null + request: string + page: BaseRefSearchResult[] + locals: BranchRef[] | null +} +export type Owner = { + key: string + generation: number + expiresAt: number + disposed: boolean + unsubscribe: () => void + snapshot: BranchRefSnapshot | null + snapshotLease?: Lease + oversized: boolean + localRefs?: readonly BranchRef[] + localLease?: Lease + flight?: { generation: number; promise: Promise } + contexts: Map + base?: Lease +} +export type BranchSnapshotSignals = { + subscribe(commonDir: string, listener: () => void): () => void +} + +export class BranchSnapshotOwners { + private readonly owners = new Map() + private allocatedBytes = 0 + constructor(private readonly signals: BranchSnapshotSignals) {} + + lease(owner: Owner, valid = () => true): Lease { + const lease: Lease = { + bytes: 0, + reserve: (bytes) => { + if (owner.disposed || !valid()) { + return false + } + for (const candidate of this.owners.values()) { + if (this.allocatedBytes + bytes <= BRANCH_SNAPSHOT_MAX_BYTES) { + break + } + if (candidate !== owner && !candidate.flight) { + this.retire(candidate) + } + } + if (this.allocatedBytes + bytes > BRANCH_SNAPSHOT_MAX_BYTES) { + return false + } + this.allocatedBytes += bytes + lease.bytes += bytes + return true + }, + release: () => { + this.allocatedBytes -= lease.bytes + lease.bytes = 0 + } + } + return lease + } + + retireContext(owner: Owner, key: string, context: Context): void { + if (owner.contexts.get(key) === context) { + owner.contexts.delete(key) + } + for (const lease of context.leases) { + lease.release() + } + context.leases.clear() + } + + private invalidate(owner: Owner): void { + owner.generation++ + owner.expiresAt = Date.now() + BRANCH_SNAPSHOT_TTL_MS + owner.oversized = false + owner.snapshot = null + owner.localRefs = undefined + owner.snapshotLease?.release() + owner.localLease?.release() + for (const [key, context] of owner.contexts) { + this.retireContext(owner, key, context) + } + owner.contexts.clear() + } + + retire(owner: Owner): void { + if (owner.disposed) { + return + } + owner.disposed = true + if (this.owners.get(owner.key) === owner) { + this.owners.delete(owner.key) + } + owner.unsubscribe() + this.invalidate(owner) + owner.base?.release() + } + + owner(identity: BranchSnapshotIdentity): Owner | null { + const now = Date.now() + for (const candidate of this.owners.values()) { + if (!candidate.flight && candidate.expiresAt <= now) { + this.retire(candidate) + } + } + let owner = this.owners.get(identity.key) + if (owner) { + this.owners.delete(identity.key) + this.owners.set(identity.key, owner) + return owner + } + if (this.owners.size >= MAX_OWNERS) { + const oldest = [...this.owners.values()].find((entry) => !entry.flight) + if (!oldest) { + return null + } + this.retire(oldest) + } + owner = { + key: identity.key, + generation: 0, + expiresAt: now + BRANCH_SNAPSHOT_TTL_MS, + disposed: false, + unsubscribe: () => {}, + snapshot: null, + oversized: false, + contexts: new Map() + } + owner.base = this.lease(owner) + if (!owner.base.reserve(1024 + 2 * (identity.key.length + identity.commonDir.length))) { + return null + } + this.owners.set(identity.key, owner) + const created = owner + created.unsubscribe = this.signals.subscribe(identity.commonDir, () => this.invalidate(created)) + return created + } + + async validate(identity: BranchSnapshotIdentity, owner?: Owner): Promise { + const current = await resolveBranchSnapshotIdentity(identity.cwd, identity.git) + if (!current || current.key !== identity.key || current.checkoutKey !== identity.checkoutKey) { + if (owner) { + this.retire(owner) + } + throw new BranchSnapshotIdentityChanged() + } + } + + reset(): void { + for (const owner of this.owners.values()) { + this.retire(owner) + } + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts new file mode 100644 index 00000000000..419d56412a1 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-read.test.ts @@ -0,0 +1,39 @@ +import { afterEach, expect, it, vi } from 'vitest' +const stream = vi.hoisted(() => vi.fn()) +vi.mock('../../command-runner/git-stream-stdout', () => ({ gitStreamStdout: stream })) +import { readBranchRefSnapshot } from './branch-ref-snapshot-read' + +afterEach(() => stream.mockReset()) + +it('keeps raw output complete under aggregate pressure and distinguishes an intrinsic bound', async () => { + stream.mockImplementation(async (_args, options) => { + for (const name of ['first', 'second']) { + if (options.onStdout(`refs/heads/${name}\0${'a'.repeat(40)}\u00001\0\n`) === true) { + return { stoppedEarly: true } + } + } + return { stoppedEarly: false } + }) + const page: string[] = [] + const pressured = await readBranchRefSnapshot( + '/repo', + {}, + (ref) => { + page.push(ref.refName) + return page.length === 2 + }, + undefined, + { reserve: () => false, release: () => {} } + ) + expect(page).toEqual(['refs/heads/first', 'refs/heads/second']) + expect(pressured).toEqual({ snapshot: null, oversized: false }) + expect(await readBranchRefSnapshot('/repo', {}, () => true, 100)).toEqual({ + snapshot: null, + oversized: true + }) + const recovered = await readBranchRefSnapshot('/repo', {}, () => true) + expect(recovered.snapshot?.refs.map((ref) => ref.refName)).toEqual([ + 'refs/heads/first', + 'refs/heads/second' + ]) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts new file mode 100644 index 00000000000..1ebae032216 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-read.ts @@ -0,0 +1,111 @@ +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { gitStreamStdout } from '../../command-runner/git-stream-stdout' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { gitOptionsForWorktree as gitExecOptions } from '../../command-runner/git-runtime-options' +import { + BRANCH_REF_SNAPSHOT_ARGS, + parseBranchRef, + type BranchRef +} from './branch-ref-snapshot-data' + +export const BRANCH_SNAPSHOT_MAX_BYTES = 64 * 1024 * 1024 + +export type BranchRefSnapshot = { + refs: readonly BranchRef[] +} + +export type BranchSnapshotRetention = { + reserve(bytes: number): boolean + release(): void +} + +export async function readBranchRefSnapshot( + path: string, + git: LocalGitExecOptions, + onRef: (ref: BranchRef) => boolean | void, + maxRetainedBytes = BRANCH_SNAPSHOT_MAX_BYTES, + retention?: BranchSnapshotRetention +): Promise<{ snapshot: BranchRefSnapshot | null; oversized: boolean }> { + let refs: BranchRef[] | null = [] + let estimatedBytes = 256 + let oversized = false + if (retention && !retention.reserve(estimatedBytes)) { + refs = null + } + await readRefLines(BRANCH_REF_SNAPSHOT_ARGS, path, git, (line) => { + const ref = parseBranchRef(line) + if (!ref) { + return + } + const pageComplete = onRef(ref) + if (refs) { + const bytes = + 192 + + 2 * + (ref.refName.length + + ref.oid.length + + ref.symref.length + + ref.label.length + + ref.searchName.length) + estimatedBytes += bytes + if (estimatedBytes > maxRetainedBytes || (retention && !retention.reserve(bytes))) { + oversized = estimatedBytes > maxRetainedBytes && maxRetainedBytes > 0 + refs = null + retention?.release() + } else { + refs.push(ref) + } + } + return !refs && pageComplete === true + }).catch((error: unknown) => { + retention?.release() + throw error + }) + return { snapshot: refs ? { refs } : null, oversized } +} + +export async function readBranchRemoteNames( + path: string, + git: LocalGitExecOptions +): Promise { + const { stdout } = await gitExecFileAsync(['remote'], { + ...gitExecOptions(path, git), + maxBuffer: 1024 * 1024 + }) + return stdout + .split(/\r?\n/) + .map((name) => name.trim()) + .filter(Boolean) +} + +async function readRefLines( + args: string[], + path: string, + git: LocalGitExecOptions, + onLine: (line: string) => boolean | void +): Promise { + let carry = '' + await gitStreamStdout(args, { + ...gitExecOptions(path, git), + // The parser retains a bounded line/page when a population cannot be retained. + maxBuffer: Number.MAX_SAFE_INTEGER, + maxStderrBuffer: 64 * 1024, + onStdout: (chunk) => { + const lines = (carry + chunk).split('\n') + carry = lines.pop() ?? '' + if (carry.length > 64 * 1024) { + throw new Error('Git returned an oversized branch ref record') + } + for (const line of lines) { + if (onLine(line) === true) { + carry = '' + return true + } + } + return false + } + }) + if (carry) { + onLine(carry) + } +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts new file mode 100644 index 00000000000..65969258625 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-real-git.test.ts @@ -0,0 +1,302 @@ +import { mkdtemp, mkdir, realpath, rename, rm, symlink } from 'node:fs/promises' +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { gitExecFileAsync } from '../../command-runner/git-exec-file' +import { listLocalBranches } from '../../worktrees/checkout/checkout' +import { _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { searchBaseRefDetails } from '../resolution/repo-base-ref-search' +import { searchRemoteRefPage } from '../resolution/repo-remote-ref-search' +import { RuntimeRepositoryRefQueries } from '../../../runtime/repositories/runtime-repository-ref-queries' +import { + repoDispatcher, + makeRequest +} from '../../../runtime/rpc/methods/projects/repo-rpc.test-fixture' +import type { Repo } from '../../../../shared/repo-types' +import { drainSubprocessSpawnStats } from '../../../diagnostics/main-thread-churn-probe' +import { beginGitRefMutation, subscribeGitRefChanges } from '../git-ref-change-signal' +import { resolveBranchSnapshotIdentity } from './branch-ref-snapshot-identity' + +const roots: string[] = [] +const git = async (cwd: string, ...args: string[]) => + (await gitExecFileAsync(args, { cwd })).stdout.trim() + +afterEach(async () => { + vi.unstubAllEnvs() + _resetBranchRefSnapshotsForTests() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +it('discovers the physical parent of a symlink to a repository subdirectory', async () => { + const { root } = await fixture() + const parent = await mkdtemp(join(tmpdir(), 'orca-ref-alias-')) + roots.push(parent) + await mkdir(join(root, 'nested')) + await symlink(join(root, 'nested'), join(parent, 'alias'), 'junction') + expect(await searchBaseRefDetails(join(parent, 'alias'), 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) +}) + +it.each([10, 100])( + 'loads one population for %i refs and filters repeated entrypoint searches without children', + async (population) => { + const { root, tagOid } = await fixture() + await gitExecFileAsync(['update-ref', '--stdin'], { + cwd: root, + stdin: Array.from( + { length: population }, + (_, i) => `create refs/heads/scale-${i} ${tagOid}\n` + ).join('') + }) + const repo: Repo = { id: 'scale', path: root, displayName: 'scale', badgeColor: '', addedAt: 0 } + const runtime = new RuntimeRepositoryRefQueries({ resolveRepo: async () => repo }) + vi.stubEnv('ORCA_MAIN_THREAD_DIAGNOSTICS', '1') + drainSubprocessSpawnStats() + expect((await searchBaseRefDetails(root, 'scale-', 30)).length).toBe(Math.min(population, 30)) + expect(drainSubprocessSpawnStats()['git for-each-ref']?.count).toBe(1) + // Queries only need an existing generation; each surface's limit is a bounded projection. + for (let query = 0; query < 10; query++) { + await searchBaseRefDetails(root, `scale-${query}`, 30) + await runtime.search('scale', 'scale-', 20) + await runtime.search('scale', 'absent', 20, true, 'remote') + } + expect(drainSubprocessSpawnStats()).toEqual({}) + const identity = await resolveBranchSnapshotIdentity(root, {}) + const end = beginGitRefMutation(identity!.commonDir) + await searchBaseRefDetails(root, 'scale-', 30) + drainSubprocessSpawnStats() + await runtime.search('scale', 'scale-1', 20) + await searchBaseRefDetails(root, 'absent', 30) + expect(drainSubprocessSpawnStats()).toEqual({}) + end() + } +) + +async function fixture(): Promise<{ root: string; branchOid: string; tagOid: string }> { + const root = await mkdtemp(join(tmpdir(), 'orca-branch-snapshot-')) + roots.push(root) + await git(root, 'init', '-q', '-b', 'main') + const commit = () => + git( + root, + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.test', + 'commit', + '--allow-empty', + '-qm', + 'fixture' + ) + await commit() + const branchOid = await git(root, 'rev-parse', 'HEAD') + await git(root, 'branch', 'collision') + await commit() + const tagOid = await git(root, 'rev-parse', 'HEAD') + await git(root, 'tag', 'collision') + await git(root, 'remote', 'add', 'origin', 'https://example.invalid/repo.git') + await git(root, 'remote', 'add', 'team/fork', 'https://example.invalid/fork.git') + await gitExecFileAsync(['update-ref', '--stdin'], { + cwd: root, + stdin: [ + 'refs/heads/Feature/emoji😀', + 'refs/heads/origin/main', + 'refs/remotes/origin/main', + 'refs/remotes/origin/feature/HEAD', + 'refs/remotes/team/fork/release/topic' + ] + .map((ref) => `create ${ref} ${tagOid}\n`) + .join('') + }) + await git(root, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + return { root, branchOid, tagOid } +} + +it('searches readable branch names while keeping branch actions unambiguous', async () => { + const { root, branchOid, tagOid } = await fixture() + expect(branchOid).not.toBe(tagOid) + expect(await searchBaseRefDetails(root, 'feature/EMOJI', 30)).toEqual([ + { refName: 'refs/heads/Feature/emoji😀', localBranchName: 'Feature/emoji😀' } + ]) + expect(await searchBaseRefDetails(root, 'refs/heads', 30)).toEqual([]) + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + expect(await git(root, 'rev-parse', 'refs/heads/collision')).toBe(branchOid) + expect(await searchBaseRefDetails(root, 'origin/main', 20)).toEqual([ + { refName: 'refs/heads/origin/main', localBranchName: 'origin/main' }, + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ]) + expect(await searchRemoteRefPage(root, '', 2)).toEqual({ + refDetails: [ + { refName: 'refs/remotes/origin/feature/HEAD', localBranchName: 'feature/HEAD' }, + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ], + truncated: true + }) +}) + +it('keeps ordinary branches available to a client without qualified-ref support', async () => { + const { root } = await fixture() + const repo: Repo = { + id: 'snapshot-test', + path: root, + displayName: 'fixture', + badgeColor: '', + addedAt: 0 + } + const queries = new RuntimeRepositoryRefQueries({ resolveRepo: async () => repo }) + const dispatcher = repoDispatcher({ + getRuntimeId: () => 'snapshot-test', + searchRepoRefs: (repo, query, limit, qualified, namespace) => + queries.search(repo, query, limit ?? 25, qualified, namespace) + }) + const response = await dispatcher.dispatch( + makeRequest('repo.searchRefs', { + repo: 'snapshot-test', + query: '', + limit: 20 + }), + { clientCapabilities: [] } + ) + const result = z + .object({ result: z.object({ refs: z.array(z.string()) }) }) + .parse(response).result + expect(result.refs).toContain('main') + expect(result.refs).not.toContain('collision') + expect(result.refs).not.toContain('refs/heads/collision') + expect(result.refs).not.toContain('refs/heads/Feature/emoji😀') + expect(result.refs.some((ref) => ref.startsWith('refs/'))).toBe(false) + await git(root, 'update-ref', 'refs/heads/origin/a', 'HEAD') + await git(root, 'update-ref', 'refs/remotes/origin/a', 'HEAD') + await git(root, 'update-ref', 'refs/remotes/origin/b', 'HEAD') + const remoteResponse = await dispatcher.dispatch( + makeRequest('repo.searchRefs', { + repo: 'snapshot-test', + query: '', + limit: 1, + namespace: 'remote' + }), + { clientCapabilities: [] } + ) + expect( + z + .object({ result: z.object({ refs: z.array(z.string()), truncated: z.boolean() }) }) + .parse(remoteResponse).result + ).toEqual({ refs: [], truncated: true }) +}) + +it('fences prior results even when our mutating command fails', async () => { + const { root } = await fixture() + expect(await searchBaseRefDetails(root, 'external', 20)).toEqual([]) + await promisify(execFile)('git', ['branch', 'external'], { cwd: root }) + await expect(git(root, 'branch', 'main')).rejects.toThrow() + expect(await searchBaseRefDetails(root, 'external', 20)).toEqual([ + { refName: 'refs/heads/external', localBranchName: 'external' } + ]) +}) + +it('shares linked checkout branches while reading current branch and occupancy per request', async () => { + const { root } = await fixture() + const linkedParent = await mkdtemp(join(tmpdir(), 'orca-branch-linked-')) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'other', linked) + const nested = join(linked, 'nested') + await mkdir(nested) + expect(await searchBaseRefDetails(nested, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + const mainBranches = await listLocalBranches(root) + const linkedBranches = await listLocalBranches(nested) + expect(mainBranches.current).toBe('main') + expect(mainBranches.branches[0]).toBe('main') + expect(linkedBranches.current).toBe('other') + expect(linkedBranches.branches[0]).toBe('other') + expect(linkedBranches.worktreePaths?.other).toBe(await realpath(linked)) + await git(root, 'branch', 'fresh') + expect(await searchBaseRefDetails(nested, 'fresh', 20)).toEqual([ + { refName: 'refs/heads/fresh', localBranchName: 'fresh' } + ]) +}) + +it('fences all live repositories for own writes from linked, known and unknown paths', async () => { + const { root } = await fixture() + const { root: other } = await fixture() + const linkedParent = await realpath(await mkdtemp(join(tmpdir(), 'orca-ref-scope-'))) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'linked-scope', linked) + expect((await listLocalBranches(root)).worktreePaths?.['linked-scope']).toBe(linked) + await searchBaseRefDetails(other, '', 20) + const a = await resolveBranchSnapshotIdentity(root, {}) + const b = await resolveBranchSnapshotIdentity(other, {}) + const events: string[] = [] + const offA = subscribeGitRefChanges(a!.commonDir, () => events.push('a')) + const offB = subscribeGitRefChanges(b!.commonDir, () => events.push('b')) + try { + await git(linked, 'branch', 'linked-one') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + await git(linked, 'branch', 'linked-two') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + await git(other, 'branch', 'other-one') + expect(events.splice(0)).toEqual(['a', 'b', 'a', 'b']) + const unknown = await mkdtemp(join(tmpdir(), 'orca-ref-unknown-')) + roots.push(unknown) + await expect(git(unknown, 'branch', 'fails')).rejects.toThrow() + expect(events).toEqual(['a', 'b', 'a', 'b']) + } finally { + offA() + offB() + } +}) + +it('uses each linked checkout effective remote config against the shared raw population', async () => { + const { root, tagOid } = await fixture() + const linkedParent = await mkdtemp(join(tmpdir(), 'orca-ref-config-')) + roots.push(linkedParent) + const linked = join(linkedParent, 'checkout') + await git(root, 'worktree', 'add', '-qb', 'config-context', linked) + await git(root, 'config', 'extensions.worktreeConfig', 'true') + await git( + linked, + 'config', + '--worktree', + 'remote.checkout/fork.url', + 'https://example.invalid/context.git' + ) + await git(root, 'update-ref', 'refs/remotes/checkout/fork/HEAD', tagOid) + expect(await searchBaseRefDetails(root, 'checkout/fork/HEAD', 20)).toEqual([ + { refName: 'refs/remotes/checkout/fork/HEAD', localBranchName: 'fork/HEAD' } + ]) + expect(await searchBaseRefDetails(linked, 'checkout/fork/HEAD', 20)).toEqual([]) +}) + +it('rebinds a repository replaced at the same common-directory path', async () => { + const { root } = await fixture() + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([ + { refName: 'refs/heads/collision', localBranchName: 'collision' } + ]) + await rename(join(root, '.git'), join(root, '.git-old')) + const externalGit = (...args: string[]) => promisify(execFile)('git', args, { cwd: root }) + await externalGit('init', '-q', '-b', 'main') + await externalGit( + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.test', + 'commit', + '--allow-empty', + '-qm', + 'replacement' + ) + await externalGit('branch', 'replacement') + expect(await searchBaseRefDetails(root, 'collision', 20)).toEqual([]) + expect(await searchBaseRefDetails(root, 'replacement', 20)).toEqual([ + { refName: 'refs/heads/replacement', localBranchName: 'replacement' } + ]) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts new file mode 100644 index 00000000000..f4947725675 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-routing.test.ts @@ -0,0 +1,105 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type * as FsPromises from 'node:fs/promises' +import type * as SnapshotReader from './branch-ref-snapshot-read' +import type * as DistroCatalog from '../../../wsl/discovery/distro-catalog' + +const cwd = String.raw`C:\repo-linked` +const commonDir = String.raw`C:\repo-main\.git` +const gitDir = String.raw`C:\repo-main\.git\worktrees\linked` +const io = vi.hoisted(() => ({ remote: vi.fn(), refs: vi.fn() })) +vi.mock('../../../wsl/discovery/distro-catalog', async (original) => ({ + ...(await original()), + listRunningWslDistrosAsync: async () => ['Ubuntu'] +})) +vi.mock('node:fs/promises', async (original) => ({ + ...(await original()), + realpath: async (path: string) => path, + stat: async (path: string) => ({ + isFile: () => path.endsWith('.git'), + isDirectory: () => !path.endsWith('.git'), + dev: 1n, + ino: 2n, + birthtimeNs: 3n + }), + readFile: async () => String.raw`gitdir: C:\repo-main\.git\worktrees\linked` +})) +vi.mock('../../../../shared/git/metadata/git-common-directory', () => ({ + resolveGitCommonDirectory: async () => String.raw`C:\repo-main\.git` +})) +vi.mock('../../source-control/resolve-git-dir', () => ({ + resolveGitDir: async () => String.raw`C:\repo-main\.git\worktrees\linked` +})) +vi.mock('./branch-ref-snapshot-read', async (original) => ({ + ...(await original()), + readBranchRemoteNames: io.remote, + readBranchRefSnapshot: io.refs +})) +import { searchBranchRefSnapshot, _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { + prepareWslLinkedWorktreeGitRouting, + resetWslLinkedWorktreeGitRoutingForTests +} from '../../command-runner/host-routing/wsl-linked-worktree-git-routing' +import { resolveBranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import { trackGitRefMutation } from '../../command-runner/git-ref-mutation-state' +import { subscribeGitRefChanges } from '../git-ref-change-signal' +import { _resetWslBackgroundDistroGateForTests } from '../../../wsl/discovery/wsl-background-distro-gate' + +const platform = process.platform +afterEach(() => { + _resetBranchRefSnapshotsForTests() + resetWslLinkedWorktreeGitRoutingForTests() + _resetWslBackgroundDistroGateForTests() + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + vi.restoreAllMocks() + io.remote.mockReset() + io.refs.mockReset() +}) + +it('keeps a live host snapshot across expiry of the filesystem-only linked-route proof', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const clock = vi.spyOn(Date, 'now').mockReturnValue(10_000) + // The reader boundary models execution's existing route settlement; it is not a real WSL benchmark. + io.remote.mockImplementation(async () => { + await prepareWslLinkedWorktreeGitRouting(cwd, 'Ubuntu') + return [] + }) + io.refs.mockResolvedValue({ + snapshot: { + refs: [ + { + refName: 'refs/heads/topic', + label: 'topic', + searchName: 'topic', + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + ] + }, + oversized: false + }) + expect(await searchBranchRefSnapshot(cwd, 'topic', 20, { wslDistro: 'Ubuntu' })).toEqual([ + { refName: 'refs/heads/topic', localBranchName: 'topic' } + ]) + clock.mockReturnValue(40_001) + expect(await resolveBranchSnapshotIdentity(cwd, { wslDistro: 'Ubuntu' })).toMatchObject({ + commonDir, + gitDir + }) + expect(await searchBranchRefSnapshot(cwd, 'topic', 20, { wslDistro: 'Ubuntu' })).toEqual([ + { refName: 'refs/heads/topic', localBranchName: 'topic' } + ]) + expect(io.remote).toHaveBeenCalledTimes(1) + expect(io.refs).toHaveBeenCalledTimes(1) + clock.mockReturnValue(70_002) + const events: string[] = [] + const offOwner = subscribeGitRefChanges(commonDir, () => events.push('owner')) + const offOther = subscribeGitRefChanges(String.raw`C:\other\.git`, () => events.push('other')) + try { + trackGitRefMutation(['commit'])() + expect(events).toEqual(['owner', 'other', 'owner', 'other']) + } finally { + offOwner() + offOther() + } +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts new file mode 100644 index 00000000000..d0bea0134d6 --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-store.test.ts @@ -0,0 +1,321 @@ +import { afterEach, expect, it, vi } from 'vitest' +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import type { BranchRefSnapshot } from './branch-ref-snapshot-read' +import type { BranchRef } from './branch-ref-snapshot-data' +import type * as SnapshotReader from './branch-ref-snapshot-read' + +const mocks = vi.hoisted(() => ({ + read: vi.fn(), + identity: vi.fn(), + remotes: vi.fn(async (): Promise => []) +})) +vi.mock('./branch-ref-snapshot-read', async (original) => ({ + ...(await original()), + readBranchRefSnapshot: mocks.read, + readBranchRemoteNames: mocks.remotes +})) +vi.mock('./branch-ref-snapshot-identity', () => ({ resolveBranchSnapshotIdentity: mocks.identity })) +import { BranchRefSnapshotStore } from './branch-ref-snapshot-store' +import { searchBaseRefDetails } from '../resolution/repo-base-ref-search' +import { _resetBranchRefSnapshotsForTests } from './branch-ref-snapshot' +import { trackGitRefMutation } from '../../command-runner/git-ref-mutation-state' +import { publishGitRefChange, subscribeGitRefChanges } from '../git-ref-change-signal' + +const identity: BranchSnapshotIdentity = { + key: 'host\0/repo/.git', + commonDir: '/repo/.git', + gitDir: '/repo/.git', + checkoutKey: '/repo/.git', + cwd: '/repo', + git: {} +} +const stores: BranchRefSnapshotStore[] = [] +function store() { + const result = new BranchRefSnapshotStore({ + subscribe: subscribeGitRefChanges + }) + stores.push(result) + mocks.identity.mockResolvedValue(identity) + return result +} +function snapshot(name: string): { snapshot: BranchRefSnapshot; oversized: boolean } { + const ref: BranchRef = { + refName: `refs/heads/${name}`, + label: name, + searchName: name.toLowerCase(), + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + return { snapshot: { refs: [ref] }, oversized: false } +} +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason: unknown) => void + const promise = new Promise((done, fail) => { + resolve = done + reject = fail + }) + return { promise, resolve, reject } +} +afterEach(() => { + for (const value of stores.splice(0)) { + value.reset() + } + _resetBranchRefSnapshotsForTests() + vi.restoreAllMocks() + mocks.read.mockReset() + mocks.identity.mockReset() + mocks.remotes.mockReset().mockResolvedValue([]) +}) + +it('does not publish a capture that finishes after a ref change', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('new')) + const result = value.search(identity, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + old.resolve(snapshot('old')) + expect(await result).toEqual([{ refName: 'refs/heads/old', localBranchName: 'old' }]) + expect(await value.search(identity, 'OLD', 20)).toEqual([]) +}) + +it('serves a post-fence caller from the next physical read without making the earlier caller retry', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockImplementationOnce(() => { + // Another event during the successor read must not prevent its response from settling. + publishGitRefChange(identity.commonDir) + return Promise.resolve(snapshot('fresh')) + }) + const before = value.search(identity, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + const after = value.search(identity, '', 20) + old.resolve(snapshot('old')) + expect(await before).toEqual([{ refName: 'refs/heads/old', localBranchName: 'old' }]) + expect(await after).toEqual([{ refName: 'refs/heads/fresh', localBranchName: 'fresh' }]) +}) + +it('starts the new generation after an obsolete physical read fails', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('fresh')) + const before = expect(value.search(identity, '', 20)).rejects.toThrow('obsolete failure') + await started.promise + publishGitRefChange(identity.commonDir) + const after = value.search(identity, '', 20) + await new Promise(setImmediate) + old.reject(new Error('obsolete failure')) + await before + expect(await after).toEqual([{ refName: 'refs/heads/fresh', localBranchName: 'fresh' }]) +}) + +it('settles public searches across repeated ref publications without restarting the request', async () => { + mocks.identity.mockResolvedValue(identity) + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockImplementation(async () => { + publishGitRefChange(identity.commonDir) + return snapshot('successor') + }) + const before = searchBaseRefDetails(identity.cwd, '', 20) + await started.promise + publishGitRefChange(identity.commonDir) + const after = searchBaseRefDetails(identity.cwd, '', 20) + await new Promise(setImmediate) + old.resolve(snapshot('overlapping')) + expect(await before).toEqual([ + { refName: 'refs/heads/overlapping', localBranchName: 'overlapping' } + ]) + expect(await after).toEqual([{ refName: 'refs/heads/successor', localBranchName: 'successor' }]) +}) + +it('returns the initiating local-list output when the capture cannot be retained', async () => { + const value = store() + mocks.read.mockImplementationOnce(async (_cwd, _git, onRef) => { + for (const ref of snapshot('local').snapshot.refs) { + onRef(ref) + } + return { snapshot: null, oversized: true } + }) + expect((await value.localRefs(identity)).map((ref) => ref.refName)).toEqual(['refs/heads/local']) +}) + +it('bounds concurrent capture retention and admits a temporarily pressured repository again', async () => { + const value = store() + const other = { + ...identity, + key: 'host\0/other/.git', + cwd: '/other', + commonDir: '/other/.git', + checkoutKey: '/other/.git' + } + mocks.identity.mockImplementation(async (cwd) => (cwd === '/other' ? other : identity)) + const started = deferred() + const held = deferred() + mocks.read.mockImplementationOnce(async (_cwd, _git, _onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(true) + started.resolve() + await held.promise + return snapshot('first') + }) + mocks.read.mockImplementationOnce(async (_cwd, _git, onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(false) + onRef(snapshot('pressured').snapshot.refs[0]) + return { snapshot: null, oversized: false } + }) + const first = value.search(identity, '', 20) + await started.promise + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/pressured', localBranchName: 'pressured' } + ]) + held.resolve() + await first + mocks.read.mockImplementationOnce(async (_cwd, _git, _onRef, _max, lease) => { + expect(lease.reserve(40 * 1024 * 1024)).toBe(true) + return snapshot('retained') + }) + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/retained', localBranchName: 'retained' } + ]) + mocks.read.mockRejectedValue(new Error('a retained repeat must not reread')) + expect(await value.search(other, '', 20)).toEqual([ + { refName: 'refs/heads/retained', localBranchName: 'retained' } + ]) +}) + +it('shares a fill while independently projecting each caller query', async () => { + const value = store() + const started = deferred() + const fill = deferred>() + mocks.read.mockImplementation(() => { + started.resolve() + return fill.promise + }) + const matching = value.search(identity, 'TOPIC', 20) + const absent = value.search(identity, 'unmatched', 20) + await started.promise + fill.resolve(snapshot('topic')) + expect(await matching).toEqual([{ refName: 'refs/heads/topic', localBranchName: 'topic' }]) + expect(await absent).toEqual([]) +}) + +it('retries failed fills without extending the original metadata deadline', async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(0) + const value = store() + expect(await value.remoteNames(identity)).toEqual([]) + clock.mockReturnValue(60_000) + mocks.read.mockRejectedValueOnce(new Error('temporary read error')) + await expect(value.search(identity, '', 20)).rejects.toThrow('temporary read error') + mocks.read.mockResolvedValue(snapshot('first')) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/first', localBranchName: 'first' } + ]) + clock.mockReturnValue(120_001) + mocks.read.mockResolvedValue(snapshot('second')) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/second', localBranchName: 'second' } + ]) +}) + +it('refreshes remote metadata and recovers retention after repeated oversized captures', async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(0) + const value = store() + mocks.remotes.mockResolvedValue(['origin']) + const ref: BranchRef = { + refName: 'refs/remotes/team/fork/topic', + label: 'team/fork/topic', + searchName: 'team/fork/topic', + oid: 'a'.repeat(40), + committedAt: 0, + symref: '' + } + let oversized = true + mocks.read.mockImplementation( + async (...args: Parameters) => { + const [, , onRef, maxBytes = 0] = args + onRef(ref) + return { snapshot: !oversized && maxBytes > 0 ? { refs: [ref] } : null, oversized } + } + ) + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'fork/topic' } + ]) + mocks.remotes.mockResolvedValue(['origin', 'team/fork']) + for (const now of [60_000, 119_000]) { + clock.mockReturnValue(now) + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'fork/topic' } + ]) + } + clock.mockReturnValue(120_001) + oversized = false + expect(await value.search(identity, 'topic', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'topic' } + ]) + expect(await value.remoteNames(identity)).toEqual(['origin', 'team/fork']) + mocks.read.mockRejectedValue(new Error('retained queries must survive an unavailable reader')) + expect(await value.search(identity, 'TOPIC', 20)).toEqual([ + { refName: 'refs/remotes/team/fork/topic', localBranchName: 'topic' } + ]) +}) + +it('does not resurrect a retired fill after a store reset', async () => { + const value = store() + const started = deferred() + const old = deferred>() + mocks.read.mockImplementationOnce(() => { + started.resolve() + return old.promise + }) + mocks.read.mockResolvedValue(snapshot('fresh')) + const result = value.search(identity, '', 20) + await started.promise + value.reset() + old.resolve(snapshot('retired')) + expect(await result).toEqual([{ refName: 'refs/heads/retired', localBranchName: 'retired' }]) + expect(await value.search(identity, '', 20)).toEqual([ + { refName: 'refs/heads/fresh', localBranchName: 'fresh' } + ]) +}) + +it('keeps demanded captures warm during a mutation and invalidates late owners only on termination', async () => { + const other = { ...identity, key: 'host\0/late/.git', commonDir: '/late/.git', cwd: '/late' } + mocks.identity.mockImplementation(async (cwd: string) => (cwd === '/late' ? other : identity)) + mocks.read.mockResolvedValue(snapshot('topic')) + await searchBaseRefDetails(identity.cwd, 'topic', 20) + expect(mocks.read).toHaveBeenCalledTimes(1) + const end = trackGitRefMutation(['commit']) + expect(mocks.read).toHaveBeenCalledTimes(1) + await searchBaseRefDetails(identity.cwd, 'TOPIC', 20) + await searchBaseRefDetails(identity.cwd, 'absent', 20) + await searchBaseRefDetails(other.cwd, 'topic', 20) + await searchBaseRefDetails(other.cwd, 'absent', 20) + expect(mocks.read).toHaveBeenCalledTimes(3) + end() + expect(mocks.read).toHaveBeenCalledTimes(3) + await searchBaseRefDetails(identity.cwd, 'topic', 20) + await searchBaseRefDetails(other.cwd, 'topic', 20) + expect(mocks.read).toHaveBeenCalledTimes(5) +}) diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts b/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts new file mode 100644 index 00000000000..09e30addd0e --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot-store.ts @@ -0,0 +1,174 @@ +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import type { BranchSnapshotIdentity } from './branch-ref-snapshot-identity' +import { + BranchSnapshotOwners, + BranchSnapshotIdentityChanged, + type Owner, + type Capture, + type BranchSnapshotSignals +} from './branch-ref-snapshot-owners' +import { BranchSnapshotMetadata } from './branch-ref-snapshot-metadata' +import { + createBranchRefProjection, + projectBranchRefs, + type BranchRef +} from './branch-ref-snapshot-data' +import { + BRANCH_SNAPSHOT_MAX_BYTES, + readBranchRefSnapshot, + readBranchRemoteNames +} from './branch-ref-snapshot-read' +export { BranchSnapshotIdentityChanged } from './branch-ref-snapshot-owners' + +/** One physical capture per owner; each caller projects its own page or local list. */ +export class BranchRefSnapshotStore { + private readonly cache: BranchSnapshotOwners + private readonly metadata: BranchSnapshotMetadata + constructor(signals: BranchSnapshotSignals) { + this.cache = new BranchSnapshotOwners(signals) + this.metadata = new BranchSnapshotMetadata(this.cache) + } + + private async capture( + owner: Owner | null, + identity: BranchSnapshotIdentity, + request: string, + onRef: (ref: BranchRef) => boolean | void, + page: BaseRefSearchResult[], + locals: BranchRef[] | null + ): Promise { + const admitted = owner?.generation + // A post-fence caller waits for the physical old read, but never consumes that generation. + if (owner?.flight && owner.flight.generation !== admitted) { + await owner.flight.promise.catch((error: unknown) => { + if (error instanceof BranchSnapshotIdentityChanged) { + throw error + } + }) + } + if (owner?.snapshot) { + return { snapshot: owner.snapshot, request, page, locals } + } + if (owner?.flight) { + return owner.flight.promise + } + const generation = owner?.generation + const lease = owner ? this.cache.lease(owner, () => owner.generation === generation) : undefined + const promise = readBranchRefSnapshot( + identity.cwd, + identity.git, + onRef, + !owner || owner.oversized ? 0 : BRANCH_SNAPSHOT_MAX_BYTES, + lease + ) + .then(async (result): Promise => { + await this.cache.validate(identity, owner ?? undefined) + if (owner && !owner.disposed && owner.generation === generation) { + owner.snapshot = result.snapshot + owner.oversized ||= result.oversized + if (result.snapshot) { + owner.snapshotLease = lease + } else { + lease?.release() + } + } else { + lease?.release() + } + return { snapshot: result.snapshot, request, page, locals } + }) + .catch((error: unknown) => { + lease?.release() + throw error + }) + .finally(() => { + if (owner?.flight?.promise === promise) { + owner.flight = undefined + } + }) + if (owner) { + owner.flight = { generation: generation!, promise } + } + return promise + } + + async localRefs(identity: BranchSnapshotIdentity): Promise { + const owner = this.cache.owner(identity) + const locals: BranchRef[] = [] + const collect = (ref: BranchRef): void => { + if (ref.refName.startsWith('refs/heads/')) { + locals.push(ref) + } + } + const capture = await this.capture(owner, identity, 'locals', collect, [], locals) + if (capture.snapshot && owner?.snapshot === capture.snapshot && owner.localRefs) { + return owner.localRefs + } + let refs = capture.snapshot + ? sortLocalRefs(capture.snapshot.refs) + : capture.locals + ? sortLocalRefs(capture.locals) + : null + if (!refs) { + // A different page initiated an unretainable capture; local output still requires the full population. + await readBranchRefSnapshot(identity.cwd, identity.git, collect, 0) + await this.cache.validate(identity) + refs = sortLocalRefs(locals) + } + if (owner && capture.snapshot && owner.snapshot === capture.snapshot) { + const lease = this.cache.lease(owner) + if (lease.reserve(64 + refs.length * 8)) { + owner.localRefs = refs + owner.localLease = lease + } + } + return refs + } + + async search( + identity: BranchSnapshotIdentity, + query: string, + limit: number, + remoteOnly = false + ): Promise { + const owner = this.cache.owner(identity) + const context = owner ? this.metadata.context(owner, identity) : undefined + const remotes = await (context?.remotes ?? readBranchRemoteNames(identity.cwd, identity.git)) + const request = JSON.stringify([identity.checkoutKey, query, limit, remoteOnly]) + const page: BaseRefSearchResult[] = [] + const project = createBranchRefProjection(remotes, query, remoteOnly) + const collect = (ref: BranchRef): boolean => { + if (page.length < limit) { + const row = project(ref) + if (row) { + page.push(row) + } + } + return page.length >= limit + } + const capture = await this.capture(owner, identity, request, collect, page, null) + if (capture.snapshot) { + return projectBranchRefs(capture.snapshot.refs, remotes, query, limit, remoteOnly) + } + if (capture.request === request) { + return capture.page + } + await readBranchRefSnapshot(identity.cwd, identity.git, collect, 0) + await this.cache.validate(identity, owner ?? undefined) + return page + } + + remoteNames(identity: BranchSnapshotIdentity) { + return this.metadata.remoteNames(identity) + } + reset(): void { + this.cache.reset() + } +} + +function sortLocalRefs(refs: readonly BranchRef[]): BranchRef[] { + const local = refs + .filter((ref) => ref.refName.startsWith('refs/heads/')) + .map((ref) => ({ ref, key: Buffer.from(ref.refName) })) + local.sort((left, right) => Buffer.compare(left.key, right.key)) + return local.map(({ ref }) => ref) +} diff --git a/src/main/git/refs/snapshot/branch-ref-snapshot.ts b/src/main/git/refs/snapshot/branch-ref-snapshot.ts new file mode 100644 index 00000000000..71317810d8e --- /dev/null +++ b/src/main/git/refs/snapshot/branch-ref-snapshot.ts @@ -0,0 +1,80 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { BaseRefSearchResult } from '../../../../shared/repo-types' +import type { LocalGitExecOptions } from '../resolution/repo-default-base-ref' +import { + resolveBranchSnapshotIdentity, + type BranchSnapshotIdentity +} from './branch-ref-snapshot-identity' +import { BranchRefSnapshotStore, BranchSnapshotIdentityChanged } from './branch-ref-snapshot-store' +import { subscribeGitRefChanges } from '../git-ref-change-signal' +import { readTranslatedWorktreeGraph } from '../../worktrees/catalog/worktree-list-reader' + +const snapshots = new BranchRefSnapshotStore({ subscribe: subscribeGitRefChanges }) + +async function withIdentity( + path: string, + git: LocalGitExecOptions, + read: (identity: BranchSnapshotIdentity) => Promise +): Promise { + for (let attempt = 0; attempt < 2; attempt++) { + const identity = await resolveBranchSnapshotIdentity(path, git) + if (!identity) { + throw new Error('The project is not a Git repository') + } + try { + return await read(identity) + } catch (error) { + if (!(error instanceof BranchSnapshotIdentityChanged)) { + throw error + } + } + } + throw new Error('The Git repository changed while reading branches. Try again.') +} + +export function searchBranchRefSnapshot( + path: string, + query: string, + limit: number, + git: LocalGitExecOptions = {}, + remoteOnly = false +): Promise { + return withIdentity(path, git, (identity) => snapshots.search(identity, query, limit, remoteOnly)) +} + +export function snapshotRemoteNames( + path: string, + git: LocalGitExecOptions = {} +): Promise { + return withIdentity(path, git, (identity) => snapshots.remoteNames(identity)) +} + +export function snapshotLocalBranchMetadata(path: string, git: LocalGitExecOptions = {}) { + return withIdentity(path, git, async (identity) => { + const [refs, worktrees, head] = await Promise.all([ + snapshots.localRefs(identity), + readTranslatedWorktreeGraph(identity.cwd, identity.git), + readFile(join(identity.gitDir, 'HEAD'), 'utf8').catch(() => '') + ]) + const currentRef = /^ref: (refs\/heads\/[^\r\n]+)/.exec(head)?.[1] + const current = + currentRef && + worktrees.some( + (worktree) => worktree.branch === currentRef && /[1-9a-f]/i.test(worktree.head) + ) + ? currentRef.slice('refs/heads/'.length) + : null + const worktreePaths = new Map() + for (const worktree of worktrees) { + if (worktree.branch.startsWith('refs/heads/')) { + worktreePaths.set(worktree.branch.slice('refs/heads/'.length), worktree.path) + } + } + return { refs, worktreePaths, current } + }) +} + +export function _resetBranchRefSnapshotsForTests(): void { + snapshots.reset() +} diff --git a/src/main/git/remotes/repo-remote-queries.ts b/src/main/git/remotes/repo-remote-queries.ts index 4de9c4e5cef..fd66a1f14e8 100644 --- a/src/main/git/remotes/repo-remote-queries.ts +++ b/src/main/git/remotes/repo-remote-queries.ts @@ -1,3 +1,4 @@ +import { snapshotRemoteNames } from '../refs/snapshot/branch-ref-snapshot' import { parseGitRevListAheadBehindCounts } from '../../../shared/git/refs/git-rev-list-output' import { buildHostedRemoteCommitUrl, buildHostedRemoteFileUrl } from './hosted-remote-url' import { getRemoteFileTarget } from './repo-remote-file-target' @@ -72,18 +73,13 @@ export async function getRecentDriftSubjects( } } -function parseRemoteCount(stdout: string): number { - return stdout.split('\n').filter((line) => line.trim().length > 0).length -} - /** Count configured remotes; zero means either none or unavailable. */ export async function getRemoteCount( path: string, options: LocalGitExecOptions = {} ): Promise { try { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - return parseRemoteCount(stdout) + return (await snapshotRemoteNames(path, options)).length } catch (err) { console.warn('[getRemoteCount] git remote failed', { path, err }) return 0 @@ -118,11 +114,7 @@ export async function getDefaultRemote( try { let remotes = knownRemoteNames if (remotes === undefined) { - const { stdout } = await gitExecFileAsync(['remote'], gitExecOptions(path, options)) - remotes = stdout - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) + remotes = await snapshotRemoteNames(path, options) } if (remotes.includes('origin')) { return 'origin' diff --git a/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts b/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts index 1a2b1d22279..47b7d4301da 100644 --- a/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts +++ b/src/main/git/worktrees/checkout/branch-switch-target-real-git.test.ts @@ -233,11 +233,32 @@ it('reads live worktree occupancy and discovers remotes despite 50 local matches }) expect(transaction.code).toBe(0) const page = await searchRemoteRefPage(directory, 'topic', 50) - expect(page.refDetails).toEqual([{ refName: 'origin/topic', localBranchName: 'topic' }]) + expect(page.refDetails).toEqual([ + { refName: 'refs/remotes/origin/topic', localBranchName: 'topic' } + ]) const occupied = join(directory, '.git', 'checkout-test') await git('worktree', 'add', '-q', occupied, 'topic-0') expect((await listLocalBranches(directory)).worktreePaths?.['topic-0']).toBe(occupied) await git('worktree', 'remove', occupied) expect((await listLocalBranches(directory)).worktreePaths?.['topic-0']).toBeUndefined() + await git('worktree', 'add', '-q', occupied, 'topic-1') + await rm(occupied, { recursive: true }) + expect((await listLocalBranches(directory)).worktreePaths?.['topic-1']).toBe(occupied) + await git('checkout', '-qb', 'external-current') + const updated = await listLocalBranches(directory) + expect(updated.current).toBe('external-current') + expect(updated.branches[0]).toBe('external-current') + expect(updated.branches).toContain('topic-0') + expect(updated.branches).toContain('topic-9') +}) +it('does not overlay an unborn local branch over a remote branch', async () => { + await git('update-ref', 'refs/remotes/origin/main', initialHead) + await git('update-ref', '-d', 'refs/heads/main') + const local = await listLocalBranches(directory) + expect(local.current).toBeNull() + expect(local.branches).toEqual([]) + expect((await searchRemoteRefPage(directory, 'main', 30)).refDetails).toEqual([ + { refName: 'refs/remotes/origin/main', localBranchName: 'main' } + ]) }) installRealWorkerThreadChildProcesses() diff --git a/src/main/git/worktrees/checkout/checkout.ts b/src/main/git/worktrees/checkout/checkout.ts index bd1b0626701..9cc162159df 100644 --- a/src/main/git/worktrees/checkout/checkout.ts +++ b/src/main/git/worktrees/checkout/checkout.ts @@ -1,3 +1,4 @@ +import { snapshotLocalBranchMetadata } from '../../refs/snapshot/branch-ref-snapshot' import type { RuntimeGitLocalBranches } from '../../../../shared/runtime-worktree-contracts' import type { BranchSwitchCreation } from '../../../../shared/git/branch-switch-target' @@ -42,61 +43,33 @@ export async function checkoutBranch( return { skippedPaths: parseCheckoutSkippedPaths(stderr) } } -/** for-each-ref avoids localized branch decoration; return the current branch first. */ +/** Current checkout state stays request-specific while the shared branch population is reused. */ export async function listLocalBranches( worktreePath: string, options: GitRuntimeOptions = {} ): Promise { - const execution = gitOptionsForWorktree(worktreePath, options) - let extended = true - const { stdout } = await gitExecFileAsync( - [ - 'for-each-ref', - '--format=%(HEAD)%09%(refname:lstrip=2)%09%(committerdate:unix)%09%(worktreepath)', - 'refs/heads/' - ], - execution - ).catch((error) => { - if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) { - throw error + options.signal?.throwIfAborted() + const { + refs, + current, + worktreePaths: occupied + } = await snapshotLocalBranchMetadata(worktreePath, options) + options.signal?.throwIfAborted() + const branches = refs.map((ref) => ref.label) + if (current) { + const index = branches.indexOf(current) + if (index !== -1) { + branches.splice(index, 1) } - extended = false - return gitExecFileAsync( - ['for-each-ref', '--format=%(HEAD)%09%(refname:lstrip=2)', 'refs/heads/'], - execution - ) - }) - let current: string | null = null - const branches: string[] = [] + branches.unshift(current) + } const committedAt: Record = Object.create(null) const worktreePaths: Record = Object.create(null) - for (const line of stdout.split('\n')) { - if (line.length === 0) { - continue - } - const [marker, name, timestamp, occupiedPath] = line.split('\t') - if (!name) { - continue - } - if (marker === '*') { - current = name - } - branches.push(name) - if (timestamp && Number.isFinite(Number(timestamp))) { - committedAt[name] = Number(timestamp) * 1000 - } - if (occupiedPath) { - worktreePaths[name] = translateWorktreePath(occupiedPath, worktreePath, options) - } + for (const ref of refs) { + committedAt[ref.label] = ref.committedAt } - branches.sort((a, b) => { - if (a === current) { - return -1 - } - if (b === current) { - return 1 - } - return 0 - }) - return { current, branches, ...(extended ? { committedAt, worktreePaths } : {}) } + for (const [name, path] of occupied) { + worktreePaths[name] = translateWorktreePath(path, worktreePath, options) + } + return { current, branches, committedAt, worktreePaths } } 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/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/ipc/pty/ipc/closed-pane-spawn-refusal.ts b/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts index 8b97f170546..e292b849803 100644 --- a/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts +++ b/src/main/ipc/pty/ipc/closed-pane-spawn-refusal.ts @@ -1,4 +1,4 @@ -import { isClosedPaneFenced } from '../../../persistence/terminal-topology/closed-pane-binding-fence' +import { isClosedPaneFenced } from '../../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' import type { Store } from '../../../persistence/loading-store/store' import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' diff --git a/src/main/ipc/pty/pane/adopt-stable.ts b/src/main/ipc/pty/pane/adopt-stable.ts index 2e330c375ee..5a9a73c9b95 100644 --- a/src/main/ipc/pty/pane/adopt-stable.ts +++ b/src/main/ipc/pty/pane/adopt-stable.ts @@ -1,5 +1,5 @@ import type { PtySpawnOutcome } from '../spawn-outcome' -import { isClosedPaneFenced } from '../../../persistence/terminal-topology/closed-pane-binding-fence' +import { isClosedPaneFenced } from '../../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' import { hasClosedTerminalTabRecord } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' import { toSshExecutionHostId, diff --git a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts index f19b228919b..e8b12909c8b 100644 --- a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts +++ b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts @@ -6,7 +6,7 @@ import { _resetClosedPaneFencesForTests, fencedIfLayoutOwner, partitionsFence -} from '../../persistence/terminal-topology/closed-pane-binding-fence' +} from '../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' import { Store } from '../../persistence/loading-store/store' import { spawnMock } from './pty-ipc-mock-registry' import { setupPtyIpcSuite } from './pty-ipc-test-harness' diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index e4f0915ff0c..6650934dc3d 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -294,5 +294,5 @@ export function registerCoreHandlers( } }) registerUpdaterHandlers(store) - registerSpeechHandlers(store) + registerSpeechHandlers(store, commitMessageAgentEnv) } diff --git a/src/main/ipc/renderer-shutdown-checkpoint.ts b/src/main/ipc/renderer-shutdown-checkpoint.ts index ba7e49055cc..1a8f736c51b 100644 --- a/src/main/ipc/renderer-shutdown-checkpoint.ts +++ b/src/main/ipc/renderer-shutdown-checkpoint.ts @@ -5,7 +5,7 @@ import { type ExecutionHostId } from '../../shared/execution-host' import type { SleepingAgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-resume' -import { applyCommandToSession } from '../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { PersistedUIState } from '../../shared/persisted-ui-state-types' import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../persistence/loading-store/store' diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index 98f7f52f9b0..102a758c7a4 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -7,6 +7,7 @@ import { } from 'electron' import { abortWhenRendererGone } from './renderer-lifetime-abort' import { dictationTermsFor } from '../../shared/dictation-dictionary' +import { dictationTextSettingsFor } from '../../shared/dictation-cleanup' import { SPEECH_MODEL_CATALOG } from '../speech/model-catalog' import { deleteLocalSpeechModel } from '../speech/speech-model-deletion' import { getSpeechModelManager, getSpeechSttService } from '../speech/speech-runtime-service' @@ -25,8 +26,49 @@ import { } from '../speech/openai-compatible-speech-provider-store' import type { DictationContext, OpenAiCompatibleSpeechProvider } from '../../shared/speech-types' import type { Store } from '../persistence/loading-store/store' +import type { DictationCleanupResult } from '../../shared/dictation-cleanup' +import { cancelDictationCleanup, cleanUpDictatedText } from '../speech/dictation-cleanup-service' +import type { CommitMessageAgentEnvironmentResolvers } from '../text-generation/commit-message-agent-environment' + +// Ten minutes of fast speech is under 20,000 characters; anything far past it isn't dictation. +const MAX_CLEANUP_TEXT_LENGTH = 100_000 + +export function registerSpeechHandlers( + store: Store, + agentEnvResolvers?: CommitMessageAgentEnvironmentResolvers +): void { + ipcMain.handle( + 'speech:cleanUpDictation', + ( + _event, + args: { text: string; context?: DictationContext; requestId: string } + ): Promise => { + if (typeof args?.text !== 'string' || args.text.length > MAX_CLEANUP_TEXT_LENGTH) { + return Promise.resolve({ + status: 'failed', + reason: 'Dictated text is too long to clean up.' + }) + } + return cleanUpDictatedText( + { + text: args.text, + terms: dictationTermsFor(store.getSettings().voice, { + dictationTerms: args.context?.repoTerms, + displayName: args.context?.repoName + }), + requestId: typeof args.requestId === 'string' ? args.requestId : undefined + }, + { getSettings: () => store.getSettings(), getAgentEnvResolvers: () => agentEnvResolvers } + ) + } + ) + + ipcMain.handle('speech:cancelDictationCleanup', (_event, requestId: unknown) => { + if (typeof requestId === 'string') { + cancelDictationCleanup(requestId) + } + }) -export function registerSpeechHandlers(store: Store): void { ipcMain.handle('speech:getCatalog', () => { return SPEECH_MODEL_CATALOG }) @@ -225,7 +267,7 @@ export function registerSpeechHandlers(store: Store): void { displayName: context?.repoName }), owner, - store.getSettings().voice + dictationTextSettingsFor(store.getSettings()) ) // Coalesced starts install no sink; only an accepted start supersedes the close hook. if (sessionReady) { 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/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/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/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/kimi/kimi-acp-launch-spec.ts b/src/main/kimi/kimi-acp-launch-spec.ts new file mode 100644 index 00000000000..a8e79da9734 --- /dev/null +++ b/src/main/kimi/kimi-acp-launch-spec.ts @@ -0,0 +1,46 @@ +import { join } from 'node:path' +import type { AcpLaunchSpec } from '../acp/launch/acp-launch-contract' +import { KIMI_ACP_DIALECT } from '../acp/acp-dialects/kimi-dialect' +import { directoryAccountBinding } from '../acp/launch/acp-account-binding' +import { agentSessionSetupFor } from '../../shared/agent-session/lifecycle/agent-session-setup-commands' +import { + resumeInvocationFromOptions, + type StructuredAgentSessionHistory +} from '../native-chat/conversation-adoption/structured-agent-cli-conversations' + +// Chats and terminals share Kimi's session store and `session_` ids. +const KIMI_SESSION_HISTORY: StructuredAgentSessionHistory = { + rowAgents: ['kimi'], + rowSessionId: (link) => link.handle.nativeId, + parseResumeArgs: (args) => + resumeInvocationFromOptions(args, { + targetless: ['-c', '--continue'], + markers: ['-S', '--session', '-r', '--resume'] + }) +} + +export const KIMI_LAUNCH_SPEC: AcpLaunchSpec = { + agent: 'kimi', + command: 'kimi', + args: () => ['acp'], + // A staged update would otherwise replace the binary when the chat starts. + env: { KIMI_CODE_NO_AUTO_UPDATE: '1' }, + dialect: KIMI_ACP_DIALECT, + loginCommand: agentSessionSetupFor('kimi')?.loginCommand ?? [], + account: directoryAccountBinding('KIMI_CODE_HOME', (homePath) => join(homePath, '.kimi-code')), + // The install scripts' default location. + installDirectories: ({ homePath }) => [join(homePath, '.kimi-code', 'bin')], + // 2.5.0 stopped failing initialize when the client's first request arrives during startup. + minimumVersions: ['2.5.0'], + // Kimi enforces its modes, and config.toml's default_permission_mode applies until one is set. + // Its ACP descriptions swap these: `yolo` still asks before risky commands, `auto` never asks. + permissionModeConfig: { + values: { ask: 'default', auto: 'yolo', 'full-access': 'auto' } + }, + // Session discovery deletes its listing session. + modelDiscovery: { kind: 'session', listingNamesConfiguredModel: false }, + compaction: true, + compactionInstructions: true, + transcriptImport: null, + sessionHistory: KIMI_SESSION_HISTORY +} 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/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts index 229f9d18d36..3fd364a11d2 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition.ts @@ -102,6 +102,7 @@ export async function acquireOwner( sessionId: record.sessionId, fence, ...(acquired.link ? { link: acquired.link } : {}), + ...(acquired.accountHome ? { launchedAccountHome: acquired.accountHome } : {}), ...(acquired.accountRecipe ? { accountAcquisition: { diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts index 59972ae9ea4..cc6774857f9 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-mutations.ts @@ -22,7 +22,14 @@ import { type MutationPlan } from '../operations/structured-agent-session-mutation-plans' import type { CommandReceiptResult } from '../../agent-session-journal/writing/command-receipt-schema' -import { structuredQueueHold } from './structured-agent-session-queued-gate' +import { + canSteerStructuredQueuedMessage, + structuredQueueHold +} from './structured-agent-session-queued-gate' +import { + structuredInputExecutionWorking, + structuredInputHandoverWorking +} from './structured-agent-session-input-selection' import { refuse } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import { queuedMessageOwed } from './structured-agent-session-queued-mail' import { resumeStructuredQueue } from './structured-agent-session-queued-pause' @@ -124,6 +131,30 @@ export function sendQueuedStructuredAgentMessage( if (row.body.command && work.working()) { return invalid("A command can't be sent while the agent is working.") } + if ( + structuredInputExecutionWorking(ctx.journal, work) && + (work.activeTurnId() === null || + structuredInputHandoverWorking(ctx.journal, work) || + !canSteerStructuredQueuedMessage( + { + record, + work, + child: context.sessions.get(ctx.sessionId)?.child, + stopping: context.readStopping(ctx.sessionId), + adapter: context.deps.adapter + }, + row + )) + ) { + return { + ok: false, + refusal: refuse( + 'agent_session_operation_invalid', + { reason: 'turnActive' }, + 'The current turn cannot accept this queued message yet.' + ) + } + } const submissionId = operationId const owed = queuedMessageOwed(context.deps, ctx.sessionId, row.body) try { diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts index 63d3cdce0f4..2517f8a6f91 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts @@ -1,4 +1,11 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { CodexAppServerConnection } from '../../../../codex/app-server/codex-app-server-connection-types' +import { optionSession } from '../../../../codex/structured/catalog/codex-structured-option-session.test-fixture' +import { + readCodexAppliedInputOptions, + resolvedCodexMessageOptions +} from '../../../../codex/structured/turns/codex-structured-message-options' +import { dispatchCodexTurn } from '../../../../codex/structured/turns/codex-structured-turn-start' import { createQueuedMessageTestRig, QUEUED_RIG_CALLER @@ -17,7 +24,24 @@ import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/j let rig: QueuedMessageTestRig beforeEach(async () => { + const request = vi.fn(async () => ({})) + const native = optionSession(request) + native.threadId = THREAD rig = await createQueuedMessageTestRig({ restartable: true }) + rig.host.deps.adapter.readAppliedInputOptions = (input) => + input.sessionId === SESSION ? readCodexAppliedInputOptions(native, input) : null + rig.host.deps.adapter.holdsLiveProviderProcess = (sessionId, generation) => + sessionId === SESSION && + generation === native.acquisitionGeneration && + !native.ended && + !native.connection.closed + rig.dispatch.mockImplementation(async (input) => + dispatchCodexTurn( + native, + { ...input, turnOptions: await resolvedCodexMessageOptions(native, input.executionOptions) }, + undefined + ) + ) }) afterEach(() => rig.dispose()) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts index 0b9ed81b67b..e5635725f0d 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-goal-steering.test.ts @@ -108,3 +108,41 @@ it('holds a Plan choice until the goal turn ends', async () => { await eventually(() => expect(rig.dispatch).toHaveBeenCalledTimes(2)) expect(rig.dispatch.mock.calls[1]?.[0].executionOptions).toEqual(choices) }) + +it('keeps an incompatible Send-now card intact until a new turn can use its choices', async () => { + await startGoalTurn() + const choices = { model: 'gpt-ran', effort: 'high', serviceTier: 'priority' } + const queued = rig.send('Keep my selected speed', 'queue-if-active', { carried: choices }) + expect(await queued.result).toMatchObject({ ok: true, value: { queued: {} } }) + const operationId = hostTestOperationId() + for (let press = 0; press < 2; press += 1) { + expect(await rig.sendNow(queued.id, operationId)).toMatchObject({ + ok: false, + refusal: { details: { reason: 'turnActive' } } + }) + } + expect(await rig.handoff(queued.id)).toBeUndefined() + expect( + rig.host.collaboratorsForTests().sessions.get(SESSION)?.journal.queuedMessages.get(queued.id) + ).toMatchObject({ + state: 'waiting', + body: { blocks: [{ type: 'text', text: 'Keep my selected speed' }] }, + options: choices + }) + + native.activeTurnIds = new Set() + rig + .providerEvents() + .appendItem( + { provider: 'codex', threadId: THREAD, turnId: 'goal-turn', ordinal: 99 }, + { kind: 'turn', turnId: 'goal-turn', state: 'completed' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await rig.host.flushStreamedEvents(SESSION) + await eventually(async () => expect((await rig.handoff(queued.id))?.handedOverAt).toBeDefined()) + expect(rig.dispatch.mock.calls[1]?.[0].executionOptions).toEqual(choices) + expect(await rig.sendNow(queued.id, operationId)).toMatchObject({ + ok: true, + value: { submission: { queuedMessageId: queued.id } } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts index 2532613fed9..29181aacbf0 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-repeat-press.test.ts @@ -32,7 +32,9 @@ async function queuedDraft(text: string): Promise { describe('a repeated draft press under a fresh operation id', () => { it('Send-now pressed twice sends the draft once and answers both presses with its submission', async () => { - await openRigTurnFor(rig, await rig.workingSend()) + const opening = await rig.workingSend() + await rig.settleAccepted(opening, 'opening') + await openRigTurnFor(rig, opening) const draftId = await queuedDraft('send me now') const [first, second] = await Promise.all([rig.sendNow(draftId), rig.sendNow(draftId)]) expect(first).toMatchObject({ ok: true, replayed: false }) diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts index 56fc8f54434..7368ae644c0 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-stop-row.test.ts @@ -135,10 +135,11 @@ describe("Stop's event", () => { it('a stopped unconfirmed hand-off stays ordinary while Resume drains waiting cards', async () => { const working = await rig.workingSend() await openRigTurnFor(rig, working) + await rig.settleAccepted(working, 'stopped') const steered = await queuedDraft('sent now into the turn') const opening = await queuedDraft('opens its own turn') const last = await queuedDraft('waiting behind them') - await rig.sendNow(steered) + expect(await rig.sendNow(steered)).toMatchObject({ ok: true }) await eventually(async () => expect((await rig.handoff(steered))?.handedOverAt).toBeDefined()) const steer = await rig.handoffId(steered) // Codex ends the stopped turn without taking the steer: the agent may have it, nothing proves @@ -153,7 +154,6 @@ describe("Stop's event", () => { }, via: 'steer' }) - await rig.settleAccepted(working, 'stopped') await openRigTurnFor(rig, working, 'interrupted') await expectHeld('stopped', opening, last) expect(await rig.drafts()).toEqual([ diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts index 3bd4356bc7a..5e160b2cf1f 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-usage-limit-account-hold.test.ts @@ -75,6 +75,15 @@ async function heldChat() { launchUnder: (next: UsageLimitAccountScope) => { attributed = next }, + /** The cut's runtime launched on account A; a start of this chat would now launch on `path`. */ + switchAccount: async (path: string) => { + const fence = journal.itemFence(cut.turnItemId)! + await current.store.transitionHandoff(SESSION, (record) => ({ + ...record, + launchedAccount: { fence, accountHome: { variable: 'CODEX_HOME', path: '/homes/a' } } + })) + current.host.deps.launchAccountHome = async () => ({ variable: 'CODEX_HOME', path }) + }, setEnabled: (next: boolean) => { enabled = next }, @@ -134,6 +143,33 @@ it('holds again on spending inside the grace, and leaves an unknown reset once r await settleOne(await refused.pass(room + 15_000, (now) => weekly(0, null, now))) }) +it('continues before the cut resets once the chat would start on another account with room', async () => { + const chat = await heldChat() + const start = chat.cut.resetsAt - 60_000 + await chat.switchAccount('/homes/b') + expect(await chat.pass(start + 5_000, (now) => weekly(0, null, now))).toEqual([]) + expect(chat.state()).toMatchObject({ state: 'scheduled', continueAt: start + 5_000 }) + await settleOne(await chat.pass(start + 20_000, (now) => weekly(0, null, now))) +}) + +it('keeps the new account spent from a reading before the switch until a later one shows room', async () => { + const chat = await heldChat() + const start = chat.cut.resetsAt - 60_000 + const newAccountReset = start + 2 * HOUR + await chat.switchAccount('/homes/b') + expect(await chat.pass(start + 5_000, () => weekly(100, newAccountReset, start + 1_000))).toEqual( + [] + ) + expect(chat.state()).toMatchObject({ continueAt: newAccountReset }) + expect(await chat.pass(start + 10 * 60_000, () => weekly(100, newAccountReset, start))).toEqual( + [] + ) + const room = start + 20 * 60_000 + expect(await chat.pass(room, (now) => weekly(0, null, now))).toEqual([]) + expect(chat.state()).toMatchObject({ continueAt: room }) + await settleOne(await chat.pass(room + 15_000, (now) => weekly(0, null, now))) +}) + it('retires a hold when the launch moves to billing the reading does not describe', async () => { const chat = await heldChat() const weeklyReset = chat.cut.resetsAt + 3 * HOUR diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts index 114e895ff21..002d599aea9 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-current-work.ts @@ -25,7 +25,7 @@ import type { AgentSessionLatestTurn } from '../../../../shared/agent-session/ag import type { StructuredAgentSessionWorkScope } from '../../../../shared/agent-session/view/structured-agent-session-main-agent-working' import { isUnansweredStructuredAgentSessionDispatch } from '../../../../shared/agent-session/requests/structured-agent-session-unanswered-dispatch' import type { AgentSessionJournal } from '../../agent-session-journal/journal-store' -import { DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED } from '../../agent-session-journal/projection/journal-dispatch-doubt-reasons' +import { admittedStructuredSubmission } from './structured-agent-session-submission-presentation' import { continuingStructuredAgentSessionInput, finalizingStructuredAgentSessionInput, @@ -155,12 +155,7 @@ export class StructuredAgentSessionCurrentWork { * answer, reads in doubt: no client counts it as work, and its echo or refusal still settles it. */ publishedSubmission = (submission: AgentJournalSubmission): AgentJournalSubmission => this.unanswered(submission) && !this.holds(submission) - ? { - ...submission, - dispatchState: 'unknown', - recovered: true, - reason: submission.reason ?? DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED - } + ? admittedStructuredSubmission(submission, this.generationEnded(submission)) : submission private unanswered(submission: AgentJournalSubmission): boolean { diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts index 2ebdcfae18f..fe4d0cd83e4 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection.ts @@ -125,7 +125,8 @@ export class StructuredAgentSessionJournalProjections { contextId, usageLimitCut: hostUsageLimitCut( snapshot, - latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions, journal.itemBody) + latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions, journal.itemBody), + journal.itemFence ), firstInputSubmissionKey, submissionCount: journal.inputOrder.inputCount(), diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts new file mode 100644 index 00000000000..2cfb43ce545 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-submission-presentation.ts @@ -0,0 +1,22 @@ +import type { AgentJournalSubmission } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { + DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED, + DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN +} from '../../agent-session-journal/projection/journal-dispatch-doubt-reasons' + +/** Admission releases presentation only; the journal still awaits an exact receipt. */ +export function admittedStructuredSubmission( + submission: AgentJournalSubmission, + generationEnded: boolean +): AgentJournalSubmission { + return { + ...submission, + dispatchState: 'unknown', + recovered: true, + reason: + submission.reason ?? + (generationEnded + ? DISPATCH_DOUBT_PROVIDER_ENDED_UNANSWERED + : DISPATCH_DOUBT_WRITE_OUTCOME_UNKNOWN) + } +} diff --git a/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts b/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts index 0100641739c..e063b122593 100644 --- a/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts +++ b/src/main/native-chat/agent-session-wire/options/structured-agent-session-message-options.ts @@ -46,9 +46,12 @@ export function codexTurnOptionsDiffer( next: options }) if (!applied) { - return options === undefined || Object.values(options).some((value) => value !== undefined) + return false } return OPTION_ORDER.some( - (key) => applied.next[key] !== undefined && applied.next[key] !== applied.active[key] + (key) => + applied.active[key] !== undefined && + applied.next[key] !== undefined && + applied.next[key] !== applied.active[key] ) } diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts index 503e3471d8f..7f67ac9cc57 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-account-hold.ts @@ -10,8 +10,11 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecy import type { AgentSessionRecordStore } from '../../../runtime/agent-session/records/agent-session-record-store' import { agentSessionAccountHomePath, + agentSessionAccountHomesEqual, + isLegacyAgentSessionAccountHome, type AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' +import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { usageLimitContinueIdentity as identity } from './structured-agent-session-usage-limit-chain' /** The polled usage of the account a chat continues on, as the host attributes it. */ @@ -75,6 +78,11 @@ export class UsageLimitAccountHolds { private readonly scopes = new Map() /** The source witness each chat's attribution was computed under. */ private readonly witnesses = new Map() + /** When each chat was first seen continuing on another account than the one its cut hit. */ + private readonly movedSince = new Map< + string, + { cut: string; to: AgentSessionAccountHome; at: number } + >() /** Shared by every chat of a pass and keyed by source witness: work scales with accounts and * their changes, not chats. */ private launchHomes = new Map>() @@ -90,15 +98,22 @@ export class UsageLimitAccountHolds { this.readings = new Map() } - /** Re-attributed each pass: the account a chat continues on follows the host's selection. */ - async attribute(id: string, host: AttributionHost): Promise { + /** Re-attributed each pass: the account a chat continues on follows the host's selection. + * `hit` names the cut and the account it hit, when known. */ + async attribute( + id: string, + host: AttributionHost, + hit?: { cut: string; home: AgentSessionAccountHome | null }, + now = Date.now() + ): Promise { const record = host.store.getRecord(id) const read = host.usageLimitAutoContinue?.accountUsage const witness = record ? liveWitness(host, record.provider) : undefined let scope: UsageLimitAccountScope | undefined + let movedTo: AgentSessionAccountHome | null = null try { // WSL readings never reach this host, so a WSL launch keeps the cut's own reset. - if (record && read && record.location.wslDistro === null) { + if (record && record.location.wslDistro === null) { // Off WSL a launch home follows only the provider's selection, never the chat. const target = JSON.stringify([witness, record.provider]) let launch = this.launchHomes.get(target) @@ -107,8 +122,9 @@ export class UsageLimitAccountHolds { this.launchHomes.set(target, launch) } const home = (await launch) ?? record.accountHome + movedTo = hit?.home && !sameAccountHome(home, hit.home) ? home : null const path = agentSessionAccountHomePath(home) - if (home && path) { + if (read && home && path) { const key = JSON.stringify([witness, record.provider, path]) let reading = this.readings.get(key) if (!reading) { @@ -129,6 +145,13 @@ export class UsageLimitAccountHolds { } this.scopes.set(id, scope) this.witnesses.set(id, witness) + const since = this.movedSince.get(id) + if (!movedTo || !hit) { + this.movedSince.delete(id) + } else if (since?.cut !== hit.cut || !sameAccountHome(since.to, movedTo)) { + // Each destination counts from when it was chosen, so an older reading of it never releases. + this.movedSince.set(id, { cut: hit.cut, to: movedTo, at: now }) + } } /** The witness the chat's attribution was computed under; a send binds to this one. */ @@ -155,20 +178,30 @@ export class UsageLimitAccountHolds { } } } + for (const id of this.movedSince.keys()) { + if (!shown.has(id)) { + this.movedSince.delete(id) + } + } } clear(): void { this.holds.clear() this.scopes.clear() this.witnesses.clear() + this.movedSince.clear() this.beginPass() } verdict( id: string, - cut: { turnItemId: string; resetsAt: number }, + limited: { turnItemId: string; resetsAt: number }, now: number ): UsageLimitAccountVerdict { + // The account the chat moved to never hit this cut: from the move on, only its reading holds. + const moved = this.movedSince.get(id) + const movedCut = moved?.cut === identity(limited) + const cut = movedCut ? { ...limited, resetsAt: Math.min(limited.resetsAt, moved.at) } : limited const scope = this.scopes.get(id) let hold = this.holds.get(id) // Nothing attributed and nothing held: the cut decides, and nothing is kept for it. @@ -202,10 +235,11 @@ export class UsageLimitAccountHolds { (hold.unknownReset && hold.spentSeenAt) || cut.resetsAt, typeof covering === 'number' ? covering : cut.resetsAt ) + // Spending the new account showed before the move still holds; only a later reading releases it. if ( account && reading && - fresh(cut.resetsAt) && + fresh(movedCut ? Number.NEGATIVE_INFINITY : cut.resetsAt) && now - anchor <= NATIVE_CHAT_USAGE_LIMIT_MAX_OVERDUE_MS ) { if (typeof covering === 'number') { @@ -220,7 +254,10 @@ export class UsageLimitAccountHolds { hold.heldUntil = Math.max(hold.heldUntil ?? spentUntil, spentUntil) } hold.spentSeenAt = Math.max(hold.spentSeenAt ?? reading.updatedAt, reading.updatedAt) - } else if (reading.updatedAt > (hold.spentSeenAt ?? Number.NEGATIVE_INFINITY)) { + } else if ( + fresh(cut.resetsAt) && + reading.updatedAt > (hold.spentSeenAt ?? Number.NEGATIVE_INFINITY) + ) { // Room newer than any spending seen releases the hold at that reading, so it counts from now. if (hold.unknownReset || (hold.heldUntil ?? Number.NEGATIVE_INFINITY) > reading.updatedAt) { hold.heldUntil = reading.updatedAt @@ -293,6 +330,14 @@ export class UsageLimitAccountHolds { } } +function sameAccountHome(left: AgentSessionAccountHome, right: AgentSessionAccountHome): boolean { + return isLegacyAgentSessionAccountHome(left) && isLegacyAgentSessionAccountHome(right) + ? left.variable === right.variable && + normalizeRuntimePathForComparison(left.path) === + normalizeRuntimePathForComparison(right.path) + : agentSessionAccountHomesEqual(left, right) +} + /** Changes whenever a source the provider's attribution reads changes. */ function liveWitness( host: AttributionHost, diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts index ee1e8927915..cf16f2a024f 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.ts @@ -11,6 +11,7 @@ import { readAgentJournalTurn } from '../../../../shared/agent-session/lifecycle import { restoreJournal } from '../../agent-session-journal/replay/journal-open' import { renderJournalStatus } from '../../agent-session-journal/projection/journal-public-read' import { journalInputOrder } from '../../agent-session-journal/input-order/journal-input-order' +import { journalItemExecutionFence } from '../../agent-session-journal/projection/journal-item-provenance' import type Database from '../../../sqlite/sync-database' import { latestNativeChatUsageLimitCut, @@ -168,18 +169,25 @@ export function usageLimitContinueChain( return chain } -/** A cut as the host's sweep reads it: with the chain that led to it. */ -export type HostUsageLimitCut = NativeChatUsageLimitCut & { chain: number } +/** A cut as the host's sweep reads it: with the chain that led to it and the runtime fence that + * ran its turn, which names the account it hit. */ +export type HostUsageLimitCut = NativeChatUsageLimitCut & { chain: number; fence?: number } export function hostUsageLimitCut( snapshot: { items: readonly AgentJournalRenderItem[] submissions: readonly ChainSubmission[] }, - cut: NativeChatUsageLimitCut | null + cut: NativeChatUsageLimitCut | null, + fenceOf: (itemId: string) => number | undefined ): HostUsageLimitCut | null { + const fence = cut ? fenceOf(cut.turnItemId) : undefined return cut - ? { ...cut, chain: usageLimitContinueChain(snapshot.items, snapshot.submissions, cut) } + ? { + ...cut, + chain: usageLimitContinueChain(snapshot.items, snapshot.submissions, cut), + ...(fence === undefined ? {} : { fence }) + } : null } @@ -189,14 +197,13 @@ export function readSavedUsageLimitCut( id: string ): HostUsageLimitCut | null { const load = restoreJournal(db, id) - const snapshot = - load && !load.newer && !load.damage - ? renderJournalStatus(load.state, journalInputOrder(load.state)) - : null - return snapshot - ? hostUsageLimitCut( - snapshot, - latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions) - ) - : null + if (!load || load.newer || load.damage) { + return null + } + const snapshot = renderJournalStatus(load.state, journalInputOrder(load.state)) + return hostUsageLimitCut( + snapshot, + latestNativeChatUsageLimitCut(snapshot.items, snapshot.submissions), + (itemId) => journalItemExecutionFence(load.state, itemId) + ) } diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts index 7160665287b..9cd0ecac485 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts @@ -132,7 +132,9 @@ export class StructuredAgentSessionUsageLimitContinue { turnItemId: cut.turnItemId, resetsAt: cut.resetsAt, // While the reset is unknown, `hold.resetsAt` is a reading time, not a reset. - ...(!hold.unknownReset && hold.resetsAt > cut.resetsAt ? { continueAt: hold.resetsAt } : {}), + ...(!hold.unknownReset && hold.resetsAt !== cut.resetsAt + ? { continueAt: hold.resetsAt } + : {}), state } } @@ -172,13 +174,7 @@ export class StructuredAgentSessionUsageLimitContinue { if (this.running || this.disposed) { return } - // Off, nothing can be scheduled; the settings listener publishes the switch itself. - if (!this.enabled()) { - if (this.holds.size + this.cold.size + this.attempts.size > 0) { - this.retainShown(this.deps.host.store.listVisibleSessionIds()) - } - return - } + // Off, nothing is sent, but an account switch still moves when Continue applies. this.running = true try { const visible = this.deps.host.store.listVisibleSessionIds() @@ -197,10 +193,10 @@ export class StructuredAgentSessionUsageLimitContinue { if (!cut || previous?.identity !== identity(cut)) { this.attempts.delete(id) } - // Before the overdue check: after a restart only the reading still knows a later reset. - // Only a reading taken after the cut's reset counts, so attribution waits for it. - if (cut?.resetsAt !== undefined && this.deps.now() >= cut.resetsAt) { - await this.holds.attribute(id, this.deps.host) + // Before the overdue check: after a restart only the reading still knows a later reset, + // and a switched account frees the chat before it. + if (cut?.resetsAt !== undefined) { + await this.attribute(id, cut) } const attempt = this.attempts.get(id) if (!cut || !this.eligible(id, cut) || attempt?.unconfirmed || (attempt?.count ?? 0) >= 5) { @@ -226,6 +222,13 @@ export class StructuredAgentSessionUsageLimitContinue { } } + /** The account a cut hit is the one its turn's runtime launched under, when the record names it. */ + private attribute(id: string, cut: HostUsageLimitCut): Promise { + const launched = this.deps.host.store.getRecord(id)?.launchedAccount + const home = launched && launched.fence === cut.fence ? launched.accountHome : null + return this.holds.attribute(id, this.deps.host, { cut: identity(cut), home }, this.deps.now()) + } + private deferUnchangedCut(id: string, cut: Cut, at: number): void { const current = this.cold.read(id) // Admission also refuses temporary backlog; yield the next passes without spending a failure. @@ -243,7 +246,7 @@ export class StructuredAgentSessionUsageLimitContinue { private async send(id: string, cut: Cut): Promise { // Earlier sends take time; moved sources resolve again, once per new witness for every chat. if (!this.holds.attributionCurrent(id, this.deps.host)) { - await this.holds.attribute(id, this.deps.host) + await this.attribute(id, cut) } const record = this.deps.host.store.getRecord(id) if (!record) { diff --git a/src/main/opencode/text-tasks/opencode-text-task.ts b/src/main/opencode/text-tasks/opencode-text-task.ts index e56f2c6ae78..d56a8ebe0b4 100644 --- a/src/main/opencode/text-tasks/opencode-text-task.ts +++ b/src/main/opencode/text-tasks/opencode-text-task.ts @@ -1,6 +1,6 @@ import { mergeCommandEnvironment } from '../../../shared/command-environment' import { textGenerationFailure } from '../../../shared/text-generation-failure-copy' -import { cleanGeneratedCommitMessage } from '../../../shared/source-control/ai/generation/commit-message-agent-output' +import { cleanAgentAnswer } from '../../text-generation/source-control-agent-failure' import { wslDistroForCommand } from '../../../shared/wsl-paths' import type { CommitMessagePlan } from '../../../shared/source-control/ai/generation/commit-message-plan' import { OpenCodeTextTaskError, runOwnedOpenCodeTextTask } from './opencode-owned-text-task' @@ -82,7 +82,7 @@ export async function runOpenCodeTextTask(input: { stop: killSourceControlAgentProcess, shouldExecute: input.shouldExecute }) - const cleaned = cleanGeneratedCommitMessage(rawOutput) + const cleaned = cleanAgentAnswer(rawOutput, input.operation) if (!cleaned) { throw new OpenCodeTextTaskError('session') } diff --git a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts index 4f0b0513031..7938efaadde 100644 --- a/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts +++ b/src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts @@ -25,7 +25,8 @@ const request = z.object({ 'pull-request-fields', 'branch-name', 'jira-issue-summary', - 'conversation-name' + 'conversation-name', + 'dictation-cleanup' ]) .optional(), timeoutMs: z.number().int().positive() diff --git a/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts index df765279535..77616a1843f 100644 --- a/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts @@ -38,7 +38,7 @@ import { setOrcaCloudSignInLink, startOrcaCloudSignInProgress } from './profile-cloud-sign-in-progress' -import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/relay-region-preference' +import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/region-selection/relay-region-preference' import './profile-cloud-capability-refresh' 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/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/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/main/persistence/closed-terminal-tab-write-fence.test.ts b/src/main/persistence/closed-terminal-tab-write-fence.test.ts index 9f637850ea5..61c37a856b9 100644 --- a/src/main/persistence/closed-terminal-tab-write-fence.test.ts +++ b/src/main/persistence/closed-terminal-tab-write-fence.test.ts @@ -14,7 +14,7 @@ import { WORKTREE_PATH, makeSession } from '../runtime/__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from './terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from './terminal-topology/pane-ownership/terminal-topology-membership' const SSH_HOST_ID = 'ssh:target-1' const SSH_WORKTREE_ID = 'ssh-repo::/srv/app' @@ -148,36 +148,4 @@ describe('a write cannot bring back a tab its partition recorded as closed (#124 OTHER_TAB_ID ]) }) - - it.each(['set', 'stage-before-unload'] as const)( - 'accepts a browser-only host slice once the partition has a close record (%s)', - async (write) => { - const { store, runtime } = createPersistedStore() - store.setWorkspaceSession( - { ...getDefaultWorkspaceSession(), tabsByWorktree: { [SSH_WORKTREE_ID]: [] } }, - SSH_HOST_ID - ) - await runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: SSH_WORKTREE_ID, - target: { kind: 'tab', tabId: TAB_ID } - }) - const { - tabsByWorktree: _omitted, - terminalLayoutsByTabId: _alsoOmitted, - ...slice - } = { ...getDefaultWorkspaceSession(), activeWorktreeId: SSH_WORKTREE_ID } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: models the renderer's host split, which omits empty terminal maps from its IPC payload. - const sparse = slice as WorkspaceSessionState - - if (write === 'set') { - store.setWorkspaceSession(sparse, SSH_HOST_ID) - } else { - store.stageWorkspaceSessionBeforeUnload(sparse, SSH_HOST_ID) - } - - const after = store.getWorkspaceSession(SSH_HOST_ID) - expect(after.activeWorktreeId).toBe(SSH_WORKTREE_ID) - expect(after.closedTerminalTabTombstonesByTabId?.[TAB_ID]).toBeDefined() - } - ) }) diff --git a/src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-ssh-pending-pty-kill.test.ts rename to src/main/persistence/leasing-ssh-ptys/persistence-ssh-pending-pty-kill.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts similarity index 77% rename from src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts rename to src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts index 535a691065d..590d1853630 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-leases.test.ts +++ b/src/main/persistence/leasing-ssh-ptys/persistence-ssh-remote-pty-leases.test.ts @@ -1,17 +1,16 @@ import { closeTestStores, testState, - createStore, - createStoreWithSshRemotePtyLeases, - writeDataFile + type createStore, + createStoreWithSshRemotePtyLeases } 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' -import { getDefaultPersistedState } from '../../../shared/constants' -import { sshRemotePtyLeaseAllowsReattach } from '../../../shared/ssh-types' +import '../../../shared/constants' +import '../../../shared/ssh-types' import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' import { PtyExitProof } from '../../pty/process-retirement/pty-exit-proof' @@ -202,50 +201,3 @@ describe('Store', () => { expect(session.terminalLayoutsByTabId.tab1.ptyIdsByLeafId).toEqual({}) }) }) - -// Round-trip retirement marks through the strict loader; older rows omit them and older builds ignore them. -describe('ssh remote pty lease route-retirement marks survive the disk round trip', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - }) - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - function persistLeases(leases: unknown[]): void { - const persisted = getDefaultPersistedState(testState.dir) - writeDataFile({ ...persisted, sshRemotePtyLeases: leases }) - } - - it('salvages both marks rather than stripping them', async () => { - persistLeases([ - { - targetId: 'ssh-1', - ptyId: 'pty-1', - state: 'expired', - createdAt: 1, - updatedAt: 2, - supersededBy: 'pty-2' - }, - { - targetId: 'ssh-1', - ptyId: 'pty-3', - state: 'expired', - createdAt: 1, - updatedAt: 2, - relayIdRecycled: true - } - ]) - - const store = await createStore() - - expect(store.getSshRemotePtyLeases('ssh-1')).toEqual([ - expect.objectContaining({ ptyId: 'pty-1', supersededBy: 'pty-2' }), - expect.objectContaining({ ptyId: 'pty-3', relayIdRecycled: true }) - ]) - expect(store.getSshRemotePtyLeases('ssh-1').filter(sshRemotePtyLeaseAllowsReattach)).toEqual([]) - }) - - // Missing retirement marks on older rows must preserve reattachability. -}) diff --git a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts b/src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts similarity index 94% rename from src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts rename to src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts index 530e7c5a9b6..bdc9f7bd55f 100644 --- a/src/main/persistence/terminal-topology/persistence-floating-workspace-trust-load.test.ts +++ b/src/main/persistence/loading-store/profile-loading/persistence-floating-workspace-trust-load.test.ts @@ -5,7 +5,7 @@ import { writeDataFile, readDataFile, symlinkDirectorySync -} from '../persistence-test-harness' +} from '../../persistence-test-harness' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { rmSync, mkdtempSync, mkdirSync, realpathSync } from 'node:fs' import { join } from 'node:path' @@ -16,7 +16,7 @@ const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -42,11 +42,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts b/src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts similarity index 96% rename from src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts rename to src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts index 8b3d420c0b6..86e4ce73394 100644 --- a/src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts +++ b/src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts @@ -3,21 +3,21 @@ import { createStore, registerWorkspaceRepos, testState -} from '../persistence-test-harness' +} 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' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -43,11 +43,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts similarity index 92% rename from src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts rename to src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts index 2673cdb3ece..56c848a5617 100644 --- a/src/main/persistence/terminal-topology/persistence-split-pane-incarnation.test.ts +++ b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts @@ -1,20 +1,20 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' +import { closeTestStores, createStore, testState } 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' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -40,11 +40,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts index 74e6a58b209..e11a0b98c5d 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts @@ -14,7 +14,7 @@ import { resolveHostId, type SessionHostPartitionOperations } from '../workspace import { withdrawUnstartedPane, type UnstartedPaneKept -} from '../../terminal-topology/unstarted-pane-withdraw' +} from '../../terminal-topology/pane-admission/unstarted-pane-withdraw' import { evaluatePtyBindingFastLane } from './pty-binding-fast-lane' import { durabilityOnlyBindingResult, isDurabilityOnlyMatch } from './pty-binding-durability-only' import { ptyBindingIsRefused } from './pty-binding-refusals' @@ -41,7 +41,7 @@ import { import type { TerminalPaneAdmission, TerminalPaneAdmissionOutcome -} from '../../terminal-topology/terminal-pane-admission' +} from '../../terminal-topology/pane-admission/terminal-pane-admission' import type { CommandOf, LayoutRefusalCode diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts index eafe3bfb92d..1a8dd2f463f 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-refusals.ts @@ -6,7 +6,7 @@ import '../../restoring-sessions/terminal-layout-normalization' import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import type { PtyBindingSourceExpectation } from '../store' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { isClosedPaneFenced } from '../../terminal-topology/closed-pane-binding-fence' +import { isClosedPaneFenced } from '../../terminal-topology/pane-ownership/closed-pane-binding-fence' export type PtyBindingRefusalRequest = { tabId: string diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts index 11bdf1186d2..786d0f983a8 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts @@ -5,7 +5,7 @@ import { cloneLayoutNode } from '../../restoring-sessions/terminal-layout-normal import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' import { createMinimalPersistedTerminalTab } from '../../restoring-sessions/session-owner-fields' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { placedSplitRoot } from '../../terminal-topology/terminal-pane-placement-graft' +import { placedSplitRoot } from '../../terminal-topology/pane-admission/terminal-pane-placement-graft' import { tabRowPtyIdAfterLeafBinding } from './terminal-tab-pty-ownership' import type { PersistPtyBindingArgs } from './pty-binding-persistence' import { reusedTerminalIdUnbinding } from './reused-terminal-id-unbind' diff --git a/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts b/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts index 6e572eaa4c6..89325a8ad30 100644 --- a/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts +++ b/src/main/persistence/loading-store/terminal-bindings/pty-binding-span.ts @@ -3,7 +3,7 @@ import type { PtyBindingFastLaneMiss } from './pty-binding-fast-lane' import { terminalPanePlacementAgreement, type TerminalPanePlacementAgreement -} from '../../terminal-topology/terminal-pane-placement-agreement' +} from '../../terminal-topology/pane-admission/terminal-pane-placement-agreement' import { findTerminalBindingConflict, type TerminalOwnerConflictReason diff --git a/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts b/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts deleted file mode 100644 index 7d920f44371..00000000000 --- a/src/main/persistence/loading-store/terminal-bindings/terminal-close-async-durability.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import { _resetClosedPaneFencesForTests } from '../../terminal-topology/closed-pane-binding-fence' -import { fixture } from '../profile-writing/profile-state-delayed-authority-fixture' -import { OrcaRuntimeService } from '../../../runtime/orca-runtime' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' - -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: () => ({ nth_repo_added: 2 }) -})) -vi.mock('../../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -// Clear process-wide close fences because these tests reuse pane IDs. -beforeEach(_resetClosedPaneFencesForTests) - -const binding = { - worktreeId: 'repo-local::/fixture/local', - tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', - ptyId: 'closing-pty', - incarnationId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' -} -const siblingLeafId = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd' - -class CloseRuntime extends OrcaRuntimeService { - async closeHeadlessTab(): Promise { - const snapshot = this.mobileSessionTabsByWorktree.get(binding.worktreeId) - const tab = snapshot?.tabs[0] - if (!snapshot || tab?.type !== 'terminal') { - throw new Error('missing test tab') - } - await this.closeHeadlessMobileTerminalTab(binding.worktreeId, snapshot, tab) - } - publish(): void { - const snapshot: RuntimeMobileSessionTabsSnapshot = { - worktree: binding.worktreeId, - publicationEpoch: 'close-test', - snapshotVersion: 1, - activeGroupId: null, - activeTabId: `${binding.tabId}::${binding.leafId}`, - activeTabType: 'terminal', - tabs: [ - { - type: 'terminal', - id: `${binding.tabId}::${binding.leafId}`, - parentTabId: binding.tabId, - leafId: binding.leafId, - ptyId: binding.ptyId, - title: 'Terminal', - isActive: true - } - ] - } - this.storeMobileSessionSnapshot(binding.worktreeId, snapshot) - } -} - -async function closeFixture(options: { split?: boolean } = {}) { - const result = await fixture() - await result.store.persistPtyBinding(binding) - if (options.split) { - await result.store.persistPtyBinding({ - ...binding, - leafId: siblingLeafId, - ptyId: 'sibling-pty', - incarnationId: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', - expectedSourceBinding: binding - }) - } - const runtime = new CloseRuntime(result.store) - const kill = vi.fn(() => true) - runtime.setPtyController({ write: () => true, kill, getForegroundProcess: async () => null }) - return { - ...result, - runtime, - kill, - persistedLeafIds: () => - Object.keys( - result.readState().workspaceSession.terminalLayoutsByTabId[binding.tabId]?.ptyIdsByLeafId ?? - {} - ), - liveLeafIds: () => - Object.keys( - result.store.getWorkspaceSession().terminalLayoutsByTabId[binding.tabId]?.ptyIdsByLeafId ?? - {} - ) - } -} - -it.each([ - ['tab', { kind: 'tab' as const, tabId: binding.tabId }, []], - [ - 'split pane', - { kind: 'pane' as const, tabId: binding.tabId, leafId: binding.leafId }, - [siblingLeafId] - ] -])('acknowledges a renderer %s close only once it is durable', async (kind, target, remaining) => { - const { authority, runtime, persistedLeafIds } = await closeFixture({ split: kind !== 'tab' }) - const before = persistedLeafIds() - const gate = authority.pause() - let acknowledged = false - const closing = runtime - .closeTerminalSurfaceFromRenderer({ worktreeId: binding.worktreeId, target: target }) - .then(() => { - acknowledged = true - }) - try { - await Promise.race([gate.started.promise, closing]) - expect(acknowledged).toBe(false) - expect(persistedLeafIds()).toEqual(before) - } finally { - gate.finish.resolve() - } - await closing - expect(persistedLeafIds()).toEqual(remaining) -}) - -it('commits a renderer tab close whose split pane bound while the close waited for the writer', async () => { - const { authority, store, runtime, persistedLeafIds, liveLeafIds } = await closeFixture() - const gate = authority.pause() - const session = store.getWorkspaceSession() - store.setWorkspaceSession({ ...session, activeTabIdByWorktree: { [binding.worktreeId]: null } }) - const earlierWrite = store.flushPendingOrThrowAsync() - await gate.started.promise - // Queue the split before close executes to test a sibling added after capture. - const split = store.persistPtyBinding({ - ...binding, - leafId: siblingLeafId, - ptyId: 'sibling-pty', - incarnationId: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', - expectedSourceBinding: binding - }) - const closing = runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: binding.worktreeId, - target: { - kind: 'tab', - tabId: binding.tabId - } - }) - gate.finish.resolve() - await earlierWrite - await expect(split).resolves.toBe(true) - await expect(closing).resolves.toBeUndefined() - - expect(persistedLeafIds()).toEqual([]) - expect(liveLeafIds()).toEqual([]) - expect( - store - .getWorkspaceSession() - .tabsByWorktree[binding.worktreeId]?.some((tab) => tab.id === binding.tabId) - ).toBe(false) - expect(store.getWorkspaceSession().closedTerminalTabTombstonesByTabId?.[binding.tabId]).toEqual( - expect.objectContaining({ worktreeId: binding.worktreeId, reason: 'user' }) - ) -}) diff --git a/src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts b/src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts similarity index 95% rename from src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts rename to src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts index 38a030c9d76..e35067540d2 100644 --- a/src/main/persistence/terminal-topology/persistence-layout-binding-recovery.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/persistence-layout-binding-recovery.test.ts @@ -3,19 +3,19 @@ import { testState, createStore, createStoreWithSshRemotePtyLeases -} from '../persistence-test-harness' +} 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' -import { TEST_LEAF_1 } from '../persistence-session-fixtures' +import { TEST_LEAF_1 } from '../../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -41,11 +41,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts b/src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts similarity index 87% rename from src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts rename to src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts index b1f823fc82e..eaf4b24a8a3 100644 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-pty-binding-replay.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/persistence-ssh-remote-pty-binding-replay.test.ts @@ -1,17 +1,17 @@ -import { closeTestStores, testState, createStore } from '../persistence-test-harness' +import { closeTestStores, testState, createStore } 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' -import { TEST_LEAF_1 } from '../persistence-session-fixtures' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { TEST_LEAF_1 } from '../../persistence-session-fixtures' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), sshConfigHostsToTargetsMock: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: loadUserSshConfigMock, sshConfigHostsToTargets: sshConfigHostsToTargetsMock })) @@ -37,11 +37,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../telemetry/client', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../../telemetry/cohort-classifier', () => ({ +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts b/src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts similarity index 88% rename from src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts rename to src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts index d31ec45ea4a..c7d6c9aaf53 100644 --- a/src/main/persistence/terminal-topology/terminal-sleep-quit-resume.test.ts +++ b/src/main/persistence/loading-store/workspace-sessions/terminal-sleep-quit-resume.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import { buildAgentResumeStartupPlan } from '../../../shared/agent-launch/startup/tui-agent-resume-startup' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { Store } from '../loading-store/store' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import { buildAgentResumeStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-resume-startup' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { Store } from '../store' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID as WORKTREE, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../../terminal-topology/testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) 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/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts b/src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-cross-host-pane-identity.test.ts rename to src/main/persistence/restoring-sessions/persistence-cross-host-pane-identity.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts b/src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts similarity index 78% rename from src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts rename to src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts index 8ecdcb4efbd..dd8d11c3b9e 100644 --- a/src/main/persistence/terminal-topology/persistence-empty-root-layout-load.test.ts +++ b/src/main/persistence/restoring-sessions/persistence-empty-root-layout-load.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from 'node:os' import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { isTerminalLeafId } from '../../../shared/workspace-layout/stable-pane-id' +import '../../../shared/workspace-layout/stable-pane-id' import { makeTerminalTab, TEST_LEAF_1 } from '../persistence-session-fixtures' vi.mock('electron', () => ({ @@ -80,26 +80,6 @@ describe('a saved layout with an empty root', () => { expect(session.terminalLayoutsByTabId['tab-1']?.ptyIdsByLeafId).toEqual({ [leafId]: 'pty-1' }) }) - it('names a fresh pane when the old layout names none', () => { - const layout = loadOldSession({ - root: null, - activeLeafId: null, - expandedLeafId: null - }).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - const leafId = layout?.activeLeafId ?? '' - expect(isTerminalLeafId(leafId)).toBe(true) - expect(layout?.root).toEqual({ type: 'leaf', leafId }) - }) - - it('names the same pane on every load until something saves', async () => { - const emptyRoot = { root: null, activeLeafId: null, expandedLeafId: null } - const first = loadOldSession(emptyRoot).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - await closeTestStores() - const second = loadOldSession(emptyRoot).getWorkspaceSession().terminalLayoutsByTabId['tab-1'] - - expect(second?.root).toEqual(first?.root) - }) - it('names the pane the old layout was already bound to', () => { const store = loadOldSession({ root: null, diff --git a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts b/src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts rename to src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts diff --git a/src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts b/src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts similarity index 100% rename from src/main/persistence/terminal-topology/persistence-tab-terminal-pane-binding-load.test.ts rename to src/main/persistence/restoring-sessions/persistence-tab-terminal-pane-binding-load.test.ts diff --git a/src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts b/src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts similarity index 94% rename from src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts rename to src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts index 262a7b960cc..05004921f64 100644 --- a/src/main/persistence/terminal-topology/windowless-restart-lost-binding.test.ts +++ b/src/main/persistence/restoring-sessions/windowless-restart-lost-binding.test.ts @@ -4,13 +4,13 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { Store } from '../loading-store/store' -import { leafIds } from './terminal-topology-window-session-fixture' +import { leafIds } from '../terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../terminal-topology/testing/terminal-topology-profile-fixture' vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) diff --git a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts deleted file mode 100644 index 1740f709dfc..00000000000 --- a/src/main/persistence/terminal-topology/closed-pane-binding-fence.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { - _resetClosedPaneFencesForTests, - fencedIfLayoutOwner, - isClosedPaneFenced, - partitionsFence -} from './closed-pane-binding-fence' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const LOCAL: ExecutionHostId = 'local' -const SSH: ExecutionHostId = 'ssh:box' - -function sessionWith(tabId: string, leafIds: string[]): WorkspaceSessionState { - const [first, second] = leafIds - return { - ...getDefaultWorkspaceSession(), - terminalLayoutsByTabId: first - ? { - [tabId]: { - root: second - ? { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: first }, - second: { type: 'leaf', leafId: second } - } - : { type: 'leaf', leafId: first }, - activeLeafId: first, - expandedLeafId: null - } - } - : {} - } -} - -function partitions(initial: Partial>) { - const sessions = new Map(Object.entries(initial)) - return { - get: (hostId: ExecutionHostId) => sessions.get(hostId), - set: (hostId: ExecutionHostId, session: WorkspaceSessionState) => sessions.set(hostId, session) - } -} - -describe('the closed-pane fence', () => { - afterEach(() => _resetClosedPaneFencesForTests()) - - it('a write elsewhere that only keeps a fenced pane does not lift its fence', () => { - // An old relay reattach left the tab in both partitions; the SSH copy is taken back. - const store = partitions({ - [SSH]: sessionWith('t', ['a', 'b']), - [LOCAL]: sessionWith('t', ['a', 'b']) - }) - fencedIfLayoutOwner( - () => partitionsFence([SSH], store.get, true), - () => (store.set(SSH, sessionWith('t', ['a'])), { value: null }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - - fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, false), - () => (store.set(LOCAL, sessionWith('t', ['a', 'b'])), { value: null }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - }) - - it('a rolled-back close lifts the fence it wrote, and a rolled-back create restores the one it lifted', () => { - const store = partitions({ [LOCAL]: sessionWith('t', ['a', 'b']) }) - const close = fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, true), - () => (store.set(LOCAL, sessionWith('t', ['a'])), { value: null, rollback: () => {} }) - )() - expect(isClosedPaneFenced('t:b')).toBe(true) - close.rollback?.() - store.set(LOCAL, sessionWith('t', ['a', 'b'])) - expect(isClosedPaneFenced('t:b')).toBe(false) - - fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, true), - () => (store.set(LOCAL, sessionWith('t', ['a'])), { value: null }) - )() - const create = fencedIfLayoutOwner( - () => partitionsFence([LOCAL], store.get, false), - () => (store.set(LOCAL, sessionWith('t', ['a', 'b'])), { value: null, rollback: () => {} }) - )() - expect(isClosedPaneFenced('t:b')).toBe(false) - create.rollback?.() - expect(isClosedPaneFenced('t:b')).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts b/src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts similarity index 82% rename from src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts rename to src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts index a4db926d57e..3d11f3ffd55 100644 --- a/src/main/persistence/terminal-topology/editor-renames-across-partitions.test.ts +++ b/src/main/persistence/terminal-topology/command-application/editor-renames-across-partitions.test.ts @@ -1,18 +1,18 @@ import { describe, expect, it, vi } from 'vitest' -import { getDefaultUIState } from '../../../shared/constants' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' +import { getDefaultUIState } from '../../../../shared/constants' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { addWorkspace, emptySession, GIT_KEY, SSH_KEY -} from '../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' +} from '../../../../shared/workspace-layout/persistence/workspace-layout-session.test-fixture' import { commitLayoutCommandsAcrossPartitions } from './layout-command-commit' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) const SSH: ExecutionHostId = 'ssh:target-1' diff --git a/src/main/persistence/terminal-topology/layout-command-commit.ts b/src/main/persistence/terminal-topology/command-application/layout-command-commit.ts similarity index 85% rename from src/main/persistence/terminal-topology/layout-command-commit.ts rename to src/main/persistence/terminal-topology/command-application/layout-command-commit.ts index f295da221c7..b58cde5d3b1 100644 --- a/src/main/persistence/terminal-topology/layout-command-commit.ts +++ b/src/main/persistence/terminal-topology/command-application/layout-command-commit.ts @@ -1,28 +1,31 @@ // Apply routed-partition commands first while carrying in-memory editor views through saved-session loads. -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { LayoutApplyOutcome, LayoutCommand, LayoutEffects -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' import { keepPartitionEditorViews, partitionEditorViewsOf -} from '../loading-store/workspace-sessions/layout-editor-views' -import { keepWslMoveFrozenSessionsForStore } from '../moving-wsl-projects/terminal-state/wsl-move-session-freeze' +} from '../../loading-store/workspace-sessions/layout-editor-views' +import { keepWslMoveFrozenSessionsForStore } from '../../moving-wsl-projects/terminal-state/wsl-move-session-freeze' import { applyCommandToSession, type LayoutLiveContext, type PaneLayoutChange -} from './terminal-pane-admission' -import { writeMovedLeafProfileRecords } from './terminal-leaf-move' +} from '../pane-admission/terminal-pane-admission' +import { writeMovedLeafProfileRecords } from '../pane-moves/terminal-leaf-move' import { writeRestorable } from './restorable-write' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' -import { resolveWindowPaneDetach, type WindowPaneDetachCommand } from './window-pane-detach' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' +import { assignWorkspaceSessionPartition } from '../pane-ownership/terminal-topology-membership' +import { + resolveWindowPaneDetach, + type WindowPaneDetachCommand +} from '../pane-moves/window-pane-detach' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' export type LayoutCommandRun = { live?: LayoutLiveContext diff --git a/src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts b/src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts similarity index 90% rename from src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts rename to src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts index 89213bb966d..c455968f62c 100644 --- a/src/main/persistence/terminal-topology/open-in-new-group-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/command-application/open-in-new-group-layout-apply.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/pane-last-grid.test.ts b/src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts similarity index 89% rename from src/main/persistence/terminal-topology/pane-last-grid.test.ts rename to src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts index ade8d50f6ea..39cdec85300 100644 --- a/src/main/persistence/terminal-topology/pane-last-grid.test.ts +++ b/src/main/persistence/terminal-topology/command-application/pane-last-grid.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { OrcaRuntimeService } from '../../runtime/orca-runtime' -import type { Store } from '../loading-store/store' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import type { Store } from '../../loading-store/store' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/restorable-write.ts b/src/main/persistence/terminal-topology/command-application/restorable-write.ts similarity index 100% rename from src/main/persistence/terminal-topology/restorable-write.ts rename to src/main/persistence/terminal-topology/command-application/restorable-write.ts diff --git a/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts new file mode 100644 index 00000000000..53c06f6ab50 --- /dev/null +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-store.test.ts @@ -0,0 +1,46 @@ +import { expect, it, vi } from 'vitest' +import { + admitRuntimeSpawnPane, + fixture +} from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' + +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ + loadUserSshConfig: () => ({ hosts: [] }), + sshConfigHostsToTargets: () => [] +})) + +const pane = { + worktreeId: 'repo-local::/fixture/local', + tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +} + +async function openWithTab() { + const opened = await fixture() + await admitRuntimeSpawnPane(opened.store, pane) + + return { + ...opened + } +} + +it('still refuses and rolls back a rename whose profile write fails', async () => { + const { store, authority } = await openWithTab() + authority.failNextWrite() + + await expect( + store.applyLayoutCommand({ + type: 'renameTab', + workspace: pane.worktreeId, + tabId: pane.tabId, + kind: 'custom', + title: 'Renamed' + }) + ).rejects.toThrow('profile_state_write_failed') + const tab = store + .getWorkspaceSession() + .tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId) + expect(tab?.customTitle ?? null).toBeNull() +}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts similarity index 74% rename from src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts index 058a7110b83..6b4fa340665 100644 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure-switch-off.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure-switch-off.test.ts @@ -1,14 +1,14 @@ import { expect, it, vi } from 'vitest' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { admitRuntimeSpawnPane, fixture -} from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' +} from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' // Preserve switch-off behavior regardless of the active build switch. -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: false })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure.ts b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-close-write-failure.ts rename to src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts index 7a99713e98a..8bd12cccc05 100644 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-close-write-failure.ts @@ -1,7 +1,7 @@ // Keep applied closes after failed saves and retry persistence; frozen writes still refuse before mutation. -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' export function isTerminalClose(command: LayoutCommand): boolean { return command.type === 'closeTabs' || command.type === 'closePane' diff --git a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts similarity index 91% rename from src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts index 39a8c1d6dd0..e3dbdc703e4 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-pane-ops.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-pane-ops.test.ts @@ -1,19 +1,19 @@ -import { withoutGitGraph } from '../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import { withoutGitGraph } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { applyCommandToSession } from './terminal-pane-admission' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import { applyCommandToSession } from '../pane-admission/terminal-pane-admission' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts similarity index 88% rename from src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts index 7bf8631a50a..7d49d98b77b 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-rename-tabs.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-rename-tabs.test.ts @@ -2,21 +2,21 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts similarity index 74% rename from src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts index 51ad7f2b371..58b895ad2fc 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-renames-commit.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-renames-commit.ts @@ -1,14 +1,14 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' import type { CommandOf, LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' import { writeRestorable } from './restorable-write' -import { applyRenamesToSession } from './terminal-pane-admission' -import { traced, type TerminalTopologyCommitContext } from './terminal-topology-commit' +import { applyRenamesToSession } from '../pane-admission/terminal-pane-admission' +import { traced, type TerminalTopologyCommitContext } from '../terminal-topology-commit' import { keepFrozen } from './layout-command-commit' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' +import { assignWorkspaceSessionPartition } from '../pane-ownership/terminal-topology-membership' /** Publish routed tab renames in one frame and return per-tab refusals. */ export function applyLayoutRenames( diff --git a/src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts b/src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts similarity index 83% rename from src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts rename to src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts index 62951725f84..d4b999986f5 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-sleep-wake.test.ts +++ b/src/main/persistence/terminal-topology/command-application/terminal-layout-sleep-wake.test.ts @@ -2,19 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -116,28 +116,6 @@ describe('Store.applyLayoutCommand sleep and wake (layout.apply)', () => { }) }) - it('a wake starts the pane and keeps its record, which the start resumes from', async () => { - const { store } = await storeWithSplitTab() - const left = record(LEFT, 'left-session') - await store.applyLayoutCommand({ - type: 'sleep', - workspace: WORKTREE, - paneKeys: [left.paneKey], - records: [left] - }) - const onEffects = vi.fn() - - const reply = await store.applyLayoutCommand( - { type: 'wake', workspace: WORKTREE, paneKeys: [left.paneKey] }, - [], - { onEffects } - ) - - expect(reply).toEqual({ ok: true, result: { woken: [left.paneKey] } }) - expect(onEffects).toHaveBeenCalledWith({ stopPtyIds: [], startPaneKeys: [left.paneKey] }) - expect(store.getWorkspaceSession().sleepingAgentSessionsByPaneKey?.[left.paneKey]).toEqual(left) - }) - it('wakes nothing for a pane that holds no record', async () => { const { store } = await storeWithSplitTab() const before = store.getWorkspaceSession() diff --git a/src/main/persistence/terminal-topology/layout-command-persistence.ts b/src/main/persistence/terminal-topology/layout-command-persistence.ts index e9c0589991d..982c8a676d6 100644 --- a/src/main/persistence/terminal-topology/layout-command-persistence.ts +++ b/src/main/persistence/terminal-topology/layout-command-persistence.ts @@ -7,7 +7,7 @@ import type { LayoutEffects, LayoutRefusalCode } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { LayoutLiveContext } from './terminal-pane-admission' +import type { LayoutLiveContext } from './pane-admission/terminal-pane-admission' import { resolveHostId, type SessionHostPartitionOperations @@ -22,22 +22,25 @@ import { applyEditorFileRenamesInPartitions, topologyCommitContext } from './terminal-topology-commit' -import { keepFrozen } from './layout-command-commit' -import { applyLayoutRenames } from './terminal-layout-renames-commit' -import { isTerminalClose, keptOnWriteFailure } from './terminal-close-write-failure' +import { keepFrozen } from './command-application/layout-command-commit' +import { applyLayoutRenames } from './command-application/terminal-layout-renames-commit' +import { + isTerminalClose, + keptOnWriteFailure +} from './command-application/terminal-close-write-failure' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { moveTabAcrossPartitions } from './cross-partition-tab-move' -import { writeRestorable } from './restorable-write' -import { raisingBindingGenerations } from './layout-command-binding-generations' +import { moveTabAcrossPartitions } from './pane-moves/cross-partition-tab-move' +import { writeRestorable } from './command-application/restorable-write' +import { raisingBindingGenerations } from './pane-ownership/layout-command-binding-generations' import { keepPartitionEditorViews, partitionEditorViewsOf } from '../loading-store/workspace-sessions/layout-editor-views' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' +import { assignWorkspaceSessionPartition } from './pane-ownership/terminal-topology-membership' import { repairDuplicatePtyPanesMutation, type DuplicatePtyPaneTransfer -} from './duplicate-pty-pane-repair' +} from './pane-ownership/duplicate-pty-pane-repair' /** Scope publication so readers reload only changed partitions. */ function writingOnly( diff --git a/src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts b/src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts similarity index 93% rename from src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts rename to src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts index 4256cba8ad4..ffc1da6f38c 100644 --- a/src/main/persistence/terminal-topology/persistence-runtime-admitted-terminal-membership.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/persistence-runtime-admitted-terminal-membership.test.ts @@ -1,11 +1,11 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' +import { closeTestStores, createStore, testState } from '../../persistence-test-harness' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, diff --git a/src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts similarity index 79% rename from src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts index 6280d70c5a1..a79bbc87f30 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-create-resend.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create-resend.test.ts @@ -2,21 +2,21 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' -import type { Store } from '../loading-store/store' -import { _resetClosedPaneFencesForTests } from './closed-pane-binding-fence' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' +import type { Store } from '../../loading-store/store' +import { _resetClosedPaneFencesForTests } from '../pane-ownership/closed-pane-binding-fence' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts similarity index 69% rename from src/main/persistence/terminal-topology/terminal-layout-create.test.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts index 3f5835f0fb1..05a81c14bcc 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-create.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-layout-create.test.ts @@ -2,20 +2,20 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { CommandOf } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { CommandOf } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { Store } from '../../loading-store/store' +import { WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -85,42 +85,6 @@ describe('Store.applyLayoutCommand: a window’s terminal tab create', () => { }) }) - it('then accepts a split of the new pane before any window save', async () => { - const { store } = await openStore(withOneTab) - await store.applyLayoutCommand(create) - - const reply = await store.applyLayoutCommand({ - type: 'splitPane', - workspace: WORKTREE, - tabId: NEW_TAB, - leafId: NEW_LEAF, - direction: 'vertical' - }) - - expect(reply.ok).toBe(true) - const root = store.getWorkspaceSession().terminalLayoutsByTabId[NEW_TAB]?.root - expect(leafIds(root)).toEqual([NEW_LEAF, reply.ok ? reply.result.leafId : undefined]) - }) - - it('keeps records the create did not touch exactly as stored', async () => { - const { store } = await openStore((window) => { - withOneTab(window) - // Verify record patches preserve residue that full load/save normalization would drop. - window.session.terminalPtyIncarnationsByPaneKey = { [`${TAB}:${LEAF}`]: 'incarnation-1' } - window.session.tabsByWorktree[WORKTREE]![0]!.sortOrder = 7 - }) - const stored = store.getWorkspaceSession() - - await store.applyLayoutCommand(create) - - const written = store.getWorkspaceSession() - expect(written.terminalPtyIncarnationsByPaneKey).toEqual( - stored.terminalPtyIncarnationsByPaneKey - ) - expect(written.tabsByWorktree[WORKTREE]?.[0]).toEqual(stored.tabsByWorktree[WORKTREE]?.[0]) - expect(written.unifiedTabs?.[WORKTREE]?.[0]).toEqual(stored.unifiedTabs?.[WORKTREE]?.[0]) - }) - it('writes an SSH workspace’s tab into that host’s partition only', async () => { const { store } = await openStore(withOneTab, 'ssh:target-1') const local = store.getWorkspaceSession() diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts similarity index 86% rename from src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts index b7a6d1baf6a..cecab47edb1 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-admission-layout-owner.test.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission-layout-owner.test.ts @@ -2,18 +2,18 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../loading-store/store' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/persistence/terminal-topology/terminal-pane-admission.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts similarity index 87% rename from src/main/persistence/terminal-topology/terminal-pane-admission.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts index 7b2caa3a768..eb3730fe03d 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-admission.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-admission.ts @@ -1,12 +1,12 @@ // Persist runtime pane membership before spawning through the same layout model used by client commands. import { randomUUID } from 'node:crypto' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { leafIdsOf, locatePane -} from '../../../shared/workspace-layout/commands/workspace-layout-command-steps' +} from '../../../../shared/workspace-layout/commands/workspace-layout-command-steps' import type { CommandOf, LayoutApplyOutcome, @@ -14,27 +14,27 @@ import type { LayoutContext, LayoutEffects, LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load' -import type { LoadedWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { paneKeyOf, type WorkspaceLayoutModel -} from '../../../shared/workspace-layout/workspace-layout-model' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-save' -import { patchStoredSession } from '../../../shared/workspace-layout/persistence/workspace-layout-record-patch' +} from '../../../../shared/workspace-layout/workspace-layout-model' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' +import { patchStoredSession } from '../../../../shared/workspace-layout/persistence/workspace-layout-record-patch' import { followRemoteSessionAfterPaneClose, followRemoteSessionAfterPaneDetach -} from './pane-remote-session-follow' -import { pruneClosedTerminalTabTombstones } from '../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' +} from '../pane-moves/pane-remote-session-follow' +import { pruneClosedTerminalTabTombstones } from '../../../../shared/workspace-layout/terminal-surfaces/closed-terminal-tab-tombstones' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import { editorViewsOfModel, type PartitionEditorViews -} from '../loading-store/workspace-sessions/layout-editor-views' +} from '../../loading-store/workspace-sessions/layout-editor-views' export type TerminalPaneAdmission = | (CommandOf<'createTerminalTab'> & { tabId: string; leafId: string }) diff --git a/src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts similarity index 78% rename from src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts index 3ac2c67fb72..2472991785a 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-placement-agreement.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-agreement.ts @@ -1,6 +1,6 @@ -import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { layoutContainsLeafId } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' /** Low-cardinality span attribute; absent tracks new leaves relying on legacy mint/graft placement. */ export type TerminalPanePlacementAgreement = diff --git a/src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts rename to src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts index cf5dbec6c7e..8a3976e2eab 100644 --- a/src/main/persistence/terminal-topology/terminal-pane-placement-graft.ts +++ b/src/main/persistence/terminal-topology/pane-admission/terminal-pane-placement-graft.ts @@ -1,13 +1,13 @@ -import type { TerminalPanePlacement } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' -import type { TerminalPaneLayoutNode } from '../../../shared/workspace-layout/terminal-tab-types' +import type { TerminalPanePlacement } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-placement' +import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import { collectLayoutLeafIdsInOrder, insertLeafBeside, layoutContainsLeafId, removeLayoutLeaf, samePanesIgnoringRatios -} from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import { cloneLayoutNode } from '../restoring-sessions/terminal-layout-normalization' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { cloneLayoutNode } from '../../restoring-sessions/terminal-layout-normalization' /** Accept a proposed tree only if it adds this leaf alone; otherwise split beside the parent or return null. */ export function placedSplitRoot( diff --git a/src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts b/src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts similarity index 76% rename from src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts rename to src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts index 784f4b0d4a9..c67ea42c4b0 100644 --- a/src/main/persistence/terminal-topology/unstarted-pane-withdraw.ts +++ b/src/main/persistence/terminal-topology/pane-admission/unstarted-pane-withdraw.ts @@ -1,10 +1,10 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../shared/execution-host' import type { CommandOf, LayoutRefusalCode -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { withdrawPane, type TerminalTopologyCommitContext } from './terminal-topology-commit' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' +import { withdrawPane, type TerminalTopologyCommitContext } from '../terminal-topology-commit' export type UnstartedPaneKept = 'bound' | 'starting' diff --git a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts b/src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts similarity index 72% rename from src/main/persistence/terminal-topology/cross-partition-tab-move.ts rename to src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts index 538b38da223..669b8506020 100644 --- a/src/main/persistence/terminal-topology/cross-partition-tab-move.ts +++ b/src/main/persistence/terminal-topology/pane-moves/cross-partition-tab-move.ts @@ -1,28 +1,28 @@ // Main moves editor tabs across partitions and writes only changed records, retaining in-memory views. -import type { LayoutClientVisibility } from '../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' +import type { LayoutClientVisibility } from '../../../../shared/workspace-layout/client-views/workspace-layout-client-visibility' import { randomUUID } from 'node:crypto' -import type { ExecutionHostId } from '../../../shared/execution-host' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { CommandOf, LayoutApplyOutcome -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { updateLegacyPersistence } from '../../../shared/workspace-layout/persistence/workspace-layout-legacy-persistence' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load' -import type { LoadedWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load-types' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { updateLegacyPersistence } from '../../../../shared/workspace-layout/persistence/workspace-layout-legacy-persistence' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import type { LoadedWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load-types' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import type { WorkspaceLayout, WorkspaceLayoutModel -} from '../../../shared/workspace-layout/workspace-layout-model' -import { patchStoredSession } from '../../../shared/workspace-layout/persistence/workspace-layout-record-patch' -import { saveWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-save' -import { applyLayoutCommand } from '../../../shared/workspace-layout/workspace-layout-commands' +} from '../../../../shared/workspace-layout/workspace-layout-model' +import { patchStoredSession } from '../../../../shared/workspace-layout/persistence/workspace-layout-record-patch' +import { saveWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-save' +import { applyLayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-commands' import { editorViewsOfModel, type PartitionEditorViews -} from '../loading-store/workspace-sessions/layout-editor-views' +} from '../../loading-store/workspace-sessions/layout-editor-views' type PartitionSession = { hostId: ExecutionHostId diff --git a/src/main/persistence/terminal-topology/pane-remote-session-follow.ts b/src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts similarity index 90% rename from src/main/persistence/terminal-topology/pane-remote-session-follow.ts rename to src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts index 7c1c876cf2c..dadbecc7118 100644 --- a/src/main/persistence/terminal-topology/pane-remote-session-follow.ts +++ b/src/main/persistence/terminal-topology/pane-moves/pane-remote-session-follow.ts @@ -1,5 +1,5 @@ -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' /** Remote session IDs live outside the layout model and must follow the remaining pane after close. */ export function followRemoteSessionAfterPaneClose( diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts similarity index 92% rename from src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts index cf64e068de4..5388c811229 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move-concurrent-close.test.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move-concurrent-close.test.ts @@ -1,7 +1,7 @@ import { tmpdir } from 'node:os' import { afterEach, expect, it, vi } from 'vitest' -import '../persistence-test-harness' +import '../../persistence-test-harness' import { closeMoveTestStores, MOVED, @@ -13,8 +13,8 @@ import { TARGET, tabsHoldingLeaf, WT -} from './terminal-leaf-move-fixture' -import './terminal-topology-commit' +} from '../testing/terminal-leaf-move-fixture' +import '../terminal-topology-commit' vi.mock('electron', () => ({ app: { diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts similarity index 97% rename from src/main/persistence/terminal-topology/terminal-leaf-move.test.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts index 3e7c628392b..0ba41a168b5 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move.test.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { toSshExecutionHostId } from '../../../shared/execution-host' -import { _resetTracerForTests } from '../../observability/tracer' -import { makeRepo } from '../persistence-test-harness' +import { toSshExecutionHostId } from '../../../../shared/execution-host' +import { _resetTracerForTests } from '../../../observability/tracer' +import { makeRepo } from '../../persistence-test-harness' import { closeMoveTestStores, @@ -21,7 +21,7 @@ import { tabsHoldingLeaf, TO, WT -} from './terminal-leaf-move-fixture' +} from '../testing/terminal-leaf-move-fixture' vi.mock('electron', () => ({ app: { diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts similarity index 89% rename from src/main/persistence/terminal-topology/terminal-leaf-move.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts index 9976454221a..332c842e43f 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-leaf-move.ts @@ -1,27 +1,27 @@ -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { collectLeafIds } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { SshRemotePtyLease } from '../../../../shared/ssh-types' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-layout-tree' import { terminalLeafMovePaneKeys, type TerminalLeafMoveRequest, type TerminalLeafMoveResult -} from '../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-leaf-move' import type { TerminalLayoutSnapshot, TerminalTab -} from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { retireLeavesFromTerminalLayout } from '../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' -import { createMinimalPersistedTerminalTab } from '../restoring-sessions/session-owner-fields' -import { layoutContainsLeafId } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import { writeRestorable } from './restorable-write' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' +} from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' +import { createMinimalPersistedTerminalTab } from '../../restoring-sessions/session-owner-fields' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { writeRestorable } from '../command-application/restorable-write' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' import { advanceTerminalTopologyRevision, isTerminalOwnerPartition, type TerminalSessionPartition -} from './terminal-topology-membership' +} from '../pane-ownership/terminal-topology-membership' type PlannedTerminalLeafMove = { result: TerminalLeafMoveResult diff --git a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts b/src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts similarity index 97% rename from src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts rename to src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts index 1155756d26f..158412257fc 100644 --- a/src/main/persistence/terminal-topology/terminal-window-pane-detach.test.ts +++ b/src/main/persistence/terminal-topology/pane-moves/terminal-window-pane-detach.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { toSshExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { makeRepo } from '../persistence-test-harness' -import type { Store } from '../loading-store/store' +import { toSshExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { makeRepo } from '../../persistence-test-harness' +import type { Store } from '../../loading-store/store' import { closeMoveTestStores, FROM, @@ -20,7 +20,7 @@ import { tabsHoldingLeaf, TO, WT -} from './terminal-leaf-move-fixture' +} from '../testing/terminal-leaf-move-fixture' vi.mock('electron', () => ({ app: { diff --git a/src/main/persistence/terminal-topology/window-pane-detach.ts b/src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts similarity index 80% rename from src/main/persistence/terminal-topology/window-pane-detach.ts rename to src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts index a07b5bd70b9..335eb023f84 100644 --- a/src/main/persistence/terminal-topology/window-pane-detach.ts +++ b/src/main/persistence/terminal-topology/pane-moves/window-pane-detach.ts @@ -1,25 +1,25 @@ // Validate every holder before any partition writes a renderer-requested detach. import { randomUUID } from 'node:crypto' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import type { ExecutionHostId } from '../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import type { ExecutionHostId } from '../../../../shared/execution-host' import { collectLayoutLeafIdsInOrder, layoutContainsLeafId -} from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import { findTerminal } from '../../../shared/workspace-layout/commands/workspace-layout-command-steps' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { findTerminal } from '../../../../shared/workspace-layout/commands/workspace-layout-command-steps' import type { CommandOf, LayoutRefusalCode, WindowPaneDetach -} from '../../../shared/workspace-layout/workspace-layout-command-types' -import { loadWorkspaceLayout } from '../../../shared/workspace-layout/persistence/workspace-layout-load' -import { nameBasedLoadContext } from '../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' +} from '../../../../shared/workspace-layout/workspace-layout-command-types' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/persistence/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/persistence/workspace-layout-minted-ids' import { leafHeldByOtherTab } from './terminal-leaf-move' import { isTerminalOwnerPartition, type TerminalSessionPartition -} from './terminal-topology-membership' +} from '../pane-ownership/terminal-topology-membership' export type WindowPaneDetachCommand = CommandOf<'movePaneToNewTab'> & { windowDetach: WindowPaneDetach diff --git a/src/main/persistence/terminal-topology/closed-pane-binding-fence.ts b/src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts similarity index 88% rename from src/main/persistence/terminal-topology/closed-pane-binding-fence.ts rename to src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts index 77cb27d182a..9caa1a91329 100644 --- a/src/main/persistence/terminal-topology/closed-pane-binding-fence.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/closed-pane-binding-fence.ts @@ -1,11 +1,11 @@ // Layout-owner builds fence removed panes against late spawns that would recreate missing membership. -import type { ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' // Five minutes covers credential/connect/relay waits; unique pane IDs make longer fences harmless apart from memory. export const CLOSED_PANE_BINDING_FENCE_MS = 5 * 60_000 diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts similarity index 75% rename from src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts rename to src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts index ad1b9e316fb..78fc059cb6a 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.test.ts @@ -2,24 +2,24 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' -import type { OrcaRuntimeService } from '../../runtime/orca-runtime' -import { repairDuplicatePtyPanesOnStart } from '../../runtime/terminal/identity/moved-pane-owner-rekey' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { DelayedAuthority } from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { Store } from '../loading-store/store' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import type { OrcaRuntimeService } from '../../../runtime/orca-runtime' +import { repairDuplicatePtyPanesOnStart } from '../../../runtime/terminal/identity/moved-pane-owner-rekey' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { DelayedAuthority } from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' +import { Store } from '../../loading-store/store' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' import { planDuplicatePtyPaneRepair } from './duplicate-pty-pane-repair' -import { leafIds, WindowSession } from './terminal-topology-window-session-fixture' +import { leafIds, WindowSession } from '../testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID -} from './terminal-topology-profile-fixture' +} from '../testing/terminal-topology-profile-fixture' -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -147,26 +147,6 @@ describe('duplicate-terminal pane repair at load (layout-owner builds)', () => { expect(storedLeafIds(directory)).toEqual([KEPT]) expect(JSON.parse(storedLayouts(directory))[TAB].ptyIdsByLeafId).toEqual({ [KEPT]: 'pty-1' }) }) - - it('writes nothing when a pane owner move fails, so the next start retries', async () => { - const directory = seededDirectory() - const seeded = storedLayouts(directory) - const { store } = await load(directory) - vi.spyOn(agentHookServer, 'transferPaneAuthority').mockImplementation(() => {}) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the repair reads only the orchestration DB accessor. - const runtime = { - getExistingOrchestrationDb: () => ({ - rekeyWorkerTerminalResourcePaneKey: () => { - throw new Error('database is locked') - } - }) - } as unknown as OrcaRuntimeService - - await repairDuplicatePtyPanesOnStart(store, runtime) - await quit(store) - - expect(storedLayouts(directory)).toBe(seeded) - }) }) describe('planDuplicatePtyPaneRepair', () => { diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts similarity index 83% rename from src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts rename to src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts index fcff563776f..1c78a2a132d 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/duplicate-pty-pane-repair.ts @@ -1,22 +1,22 @@ -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { isTerminalLeafId, makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { normalizeTerminalLayoutPtyOwnership, resolveTerminalLayoutPtyOwnershipTransfers -} from '../../../shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership' -import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { DurableProfileStateMutation } from '../loading-store/store-runtime-state' -import { isWslMoveWorkspaceSessionFrozen } from '../moving-wsl-projects/quiescence/wsl-move-scope-guard' -import { findWorktreeIdForTab } from '../restoring-sessions/pane-identity-migration' -import { writeRestorable } from './restorable-write' +} from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership' +import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import type { DurableProfileStateMutation } from '../../loading-store/store-runtime-state' +import { isWslMoveWorkspaceSessionFrozen } from '../../moving-wsl-projects/quiescence/wsl-move-scope-guard' +import { findWorktreeIdForTab } from '../../restoring-sessions/pane-identity-migration' +import { writeRestorable } from '../command-application/restorable-write' import { moveRecordKey, rekeyPaneProfileRecords, writeRekeyedProfileRecords -} from './terminal-leaf-move' -import type { TerminalTopologyCommitContext } from './terminal-topology-commit' -import { keepFrozen } from './layout-command-commit' +} from '../pane-moves/terminal-leaf-move' +import type { TerminalTopologyCommitContext } from '../terminal-topology-commit' +import { keepFrozen } from '../command-application/layout-command-commit' import { assignWorkspaceSessionPartition } from './terminal-topology-membership' export type DuplicatePtyPaneTransfer = { diff --git a/src/main/persistence/terminal-topology/layout-command-binding-generations.ts b/src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts similarity index 77% rename from src/main/persistence/terminal-topology/layout-command-binding-generations.ts rename to src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts index d51c1bdd839..36a530b2b03 100644 --- a/src/main/persistence/terminal-topology/layout-command-binding-generations.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/layout-command-binding-generations.ts @@ -1,14 +1,14 @@ // Layout-owner commands and rollback advance generations only for changed bindings, excluding moves/removals. -import type { ExecutionHostId } from '../../../shared/execution-host' -import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { bumpPtyBindingGeneration } from '../loading-store/terminal-bindings/pty-binding-generations' +import type { ExecutionHostId } from '../../../../shared/execution-host' +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { bumpPtyBindingGeneration } from '../../loading-store/terminal-bindings/pty-binding-generations' import type { DurableProfileStateMutation, StoreRuntimeState -} from '../loading-store/store-runtime-state' +} from '../../loading-store/store-runtime-state' function bindingsOf(session: WorkspaceSessionState): Map { return new Map( diff --git a/src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts b/src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts similarity index 91% rename from src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts rename to src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts index 2423b572a17..1f785a3115b 100644 --- a/src/main/persistence/terminal-topology/persistence-closed-pane-binding-fence.test.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/persistence-closed-pane-binding-fence.test.ts @@ -1,21 +1,21 @@ -import { closeTestStores, createStore, testState } from '../persistence-test-harness' +import { closeTestStores, createStore, testState } from '../../persistence-test-harness' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' -import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import { TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' import { _resetClosedPaneFencesForTests } from './closed-pane-binding-fence' -import './terminal-topology-commit' -import '../../runtime/terminal/surface/terminal-surface-close' +import '../terminal-topology-commit' +import '../../../runtime/terminal/surface/terminal-surface-close' -import '../../../shared/execution-host' +import '../../../../shared/execution-host' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, safeStorage: { isEncryptionAvailable: () => false } })) -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) const WORKTREE = 'repo1::/worktree' const TAB = 'host-tab' diff --git a/src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts b/src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts similarity index 86% rename from src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts rename to src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts index 28b6c2e0cc6..37c32fdcfcd 100644 --- a/src/main/persistence/terminal-topology/persistence-pty-binding-leaf-tab-resolution.test.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/persistence-pty-binding-leaf-tab-resolution.test.ts @@ -1,20 +1,20 @@ -import { closeTestStores, testState, createStore } from '../persistence-test-harness' +import { closeTestStores, testState, createStore } 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' -import { getDefaultWorkspaceSession } from '../../../shared/constants' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { findTerminalTabIdForLeaf } from './terminal-topology-membership' -import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' +import { makeTerminalTab, TEST_LEAF_1, TEST_LEAF_2 } from '../../persistence-session-fixtures' vi.mock('electron', () => ({ app: { getPath: () => testState.dir }, safeStorage: { isEncryptionAvailable: () => false } })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) describe('findTerminalTabIdForLeaf after persistPtyBinding grafts a leaf', () => { beforeEach(() => { diff --git a/src/main/persistence/terminal-topology/terminal-topology-membership.ts b/src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts similarity index 84% rename from src/main/persistence/terminal-topology/terminal-topology-membership.ts rename to src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts index f71e6e8a0ac..cbe54299f7d 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-membership.ts +++ b/src/main/persistence/terminal-topology/pane-ownership/terminal-topology-membership.ts @@ -2,11 +2,11 @@ import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, type ExecutionHostId -} from '../../../shared/execution-host' -import type { PersistedState } from '../../../shared/persisted-state-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' -import { layoutContainsLeafId } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +} from '../../../../shared/execution-host' +import type { PersistedState } from '../../../../shared/persisted-state-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import { layoutContainsLeafId } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' export function advanceTerminalTopologyRevision( session: WorkspaceSessionState, diff --git a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts deleted file mode 100644 index 40929cbf9dd..00000000000 --- a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { closeTestStores, createStore, dataFile, testState } from '../persistence-test-harness' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' -import { - clearMigrationUnsupportedPty, - setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/observations/migration-unsupported-pty-state' -import { StateSerializationSecretHandlingOperations } from '../loading-store/profile-writing/state-serialization-secret-handling' -import { openProfileStateDatabaseReadOnly } from '../profile-state/database/profile-state-database' -import { profileStateDatabaseFile } from '../../../shared/profile-state-storage-paths' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' - -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: vi.fn() })) - -const SOURCE = makePaneKey('tab-source', '11111111-1111-4111-8111-111111111111') -const TARGET = makePaneKey('tab-target', '22222222-2222-4222-8222-222222222222') -const migrationEntry = { - ptyId: 'ssh:ssh-1@@legacy-pty', - worktreeId: 'repo-1::/worktree', - tabId: 'tab-1', - reason: 'legacy-numeric-pane-key' as const, - source: 'ssh' as const, - updatedAt: 1_700_000_000_123 -} - -type DocumentRow = { domain: string; payload: string; revision: number } - -function isDocumentRow(row: unknown): row is DocumentRow { - return ( - typeof row === 'object' && - row !== null && - 'domain' in row && - typeof row.domain === 'string' && - 'payload' in row && - typeof row.payload === 'string' && - 'revision' in row && - typeof row.revision === 'number' - ) -} - -// Read independently of Store, using one SQL statement for a consistent snapshot. -function readDocuments(): Map { - const opened = openProfileStateDatabaseReadOnly( - profileStateDatabaseFile(dirname(dataFile())), - 'persistence-test' - ) - try { - const rows = opened.db - .prepare('SELECT domain, payload, revision FROM profile_state_documents') - .all() - return new Map(rows.filter(isDocumentRow).map((row) => [row.domain, row])) - } finally { - opened.db.close() - } -} - -async function runBackgroundSave(store: Awaited>): Promise { - vi.advanceTimersByTime(1_000) - await store.waitForPendingWrite() -} - -describe('pane alias and migration listeners save only their sections', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-alias-saves-')) - }) - - afterEach(async () => { - vi.useRealTimers() - vi.restoreAllMocks() - await closeTestStores() - agentHookServer.setPaneKeyAliasPersistenceListener(null) - setMigrationUnsupportedPtyPersistenceListener(null) - agentHookServer.retirePaneAuthority(TARGET) - for (const ptyId of ['pty-1', 'ssh:ssh-1@@pty-1', 'local-pty']) { - agentHookServer.clearPaneKeyAliasesForPty(ptyId) - } - clearMigrationUnsupportedPty(migrationEntry.ptyId) - rmSync(testState.dir, { recursive: true, force: true }) - }) - - async function durableBaseline() { - const store = await createStore() - store.flushOrThrow() - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const fullPreparation = vi.spyOn( - StateSerializationSecretHandlingOperations.prototype, - 'buildStateToSave' - ) - const domainWrites = vi.spyOn(ProfileStateSqliteAuthority.prototype, 'writeSerializedDomains') - return { store, fullPreparation, domainWrites, before: readDocuments() } - } - - function expectOnlyChanged( - before: Map, - after: Map, - changed: readonly string[] - ): void { - for (const [domain, row] of before) { - if (!changed.includes(domain)) { - expect(after.get(domain), domain).toEqual(row) - } - } - } - - it('commits a co-batched SSH host session with the alias in one transaction', async () => { - const { store, fullPreparation, domainWrites, before } = await durableBaseline() - const remoteSession = { ...getDefaultWorkspaceSession(), activeRepoId: 'remote-repo' } - store.setWorkspaceSession(remoteSession, 'ssh:ssh-1') - agentHookServer.transferPaneAuthority(SOURCE, TARGET, 'ssh:ssh-1@@pty-1', 30) - await runBackgroundSave(store) - - expect(fullPreparation).not.toHaveBeenCalled() - expect(domainWrites).toHaveBeenCalledOnce() - expect(domainWrites.mock.calls[0]?.[0].map(({ domain }) => domain).toSorted()).toEqual([ - 'legacyPaneKeyAliasEntries', - 'workspaceSessionsByHostId' - ]) - const after = readDocuments() - const sessions = JSON.parse(after.get('workspaceSessionsByHostId')?.payload ?? '{}') - expect(sessions['ssh:ssh-1']).toMatchObject({ activeRepoId: 'remote-repo' }) - expect(after.get('workspaceSessionsByHostId')?.revision).toBe( - after.get('legacyPaneKeyAliasEntries')?.revision - ) - expectOnlyChanged(before, after, ['legacyPaneKeyAliasEntries', 'workspaceSessionsByHostId']) - }) -}) diff --git a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts b/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts deleted file mode 100644 index 3a7d2672515..00000000000 --- a/src/main/persistence/terminal-topology/persistence-ssh-remote-cli-control-migration.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { - closeTestStores, - testState, - createStore, - writeDataFile, - readDataFile -} 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' -import type { SshTarget } from '../../../shared/ssh-types' -import { isRemoteCliControlAllowed } from '../../../shared/ssh-remote-cli-control' -import { SshConnectionStore } from '../../ssh/targets/ssh-connection-store' - -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: vi.fn(), - sshConfigHostsToTargets: vi.fn() -})) -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 }) -})) - -const host = (id: string, extra: Partial = {}): SshTarget => ({ - id, - label: id, - host: `${id}.example.com`, - port: 22, - username: 'dev', - ...extra -}) - -function writeProfile(sshTargets: SshTarget[], settings: Record = {}): void { - writeDataFile({ - schemaVersion: 1, - repos: [], - worktreeMeta: {}, - settings, - ui: {}, - githubCache: { pr: {}, issue: {} }, - workspaceSession: {}, - sshTargets - }) -} - -async function reopenStore(): Promise> { - await closeTestStores() - return createStore() -} - -// The orcad serve host uses the same SSH-target loading path. -describe("pinning existing hosts' orca CLI control switch on upgrade", () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - }) - - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('turns an existing absent switch off and keeps explicit values', async () => { - writeProfile([ - host('absent'), - host('on', { allowRemoteCliControl: true }), - host('off', { allowRemoteCliControl: false }) - ]) - - const store = await createStore() - - expect(store.getSshTarget('absent')?.allowRemoteCliControl).toBe(false) - expect(isRemoteCliControlAllowed(store.getSshTarget('absent'))).toBe(false) - expect(store.getSshTarget('on')?.allowRemoteCliControl).toBe(true) - expect(store.getSshTarget('off')?.allowRemoteCliControl).toBe(false) - expect(store.getSettings().sshRemoteCliControlExistingHostsMigrated).toBe(true) - - store.flush() - expect(readDataFile()).toMatchObject({ - sshTargets: expect.arrayContaining([ - expect.objectContaining({ id: 'absent', allowRemoteCliControl: false }) - ]), - settings: expect.objectContaining({ sshRemoteCliControlExistingHostsMigrated: true }) - }) - }) - - it('runs once, so hosts added afterwards keep the on-by-default switch', async () => { - writeProfile([host('existing')]) - const store = await createStore() - const added = new SshConnectionStore(store).addTarget({ - label: 'new', - host: 'new.example.com', - port: 22, - username: 'dev', - allowRemoteCliControl: true - }) - store.flush() - - const reopened = await reopenStore() - - expect(reopened.getSshTarget('existing')?.allowRemoteCliControl).toBe(false) - expect(reopened.getSshTarget(added.id)?.allowRemoteCliControl).toBe(true) - expect(isRemoteCliControlAllowed(reopened.getSshTarget(added.id))).toBe(true) - }) -}) diff --git a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts b/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts deleted file mode 100644 index 00d489fb044..00000000000 --- a/src/main/persistence/terminal-topology/terminal-close-write-failure-store.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { - admitRuntimeSpawnPane, - fixture -} from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const pane = { - worktreeId: 'repo-local::/fixture/local', - tabId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' -} - -async function openWithTab() { - const opened = await fixture() - await admitRuntimeSpawnPane(opened.store, pane) - const tabIds = (session: { tabsByWorktree?: Record }) => - (session.tabsByWorktree?.[pane.worktreeId] ?? []).map((tab) => tab.id) - return { - ...opened, - liveTabIds: () => tabIds(opened.store.getWorkspaceSession()), - savedTabIds: () => tabIds(opened.readState().workspaceSession ?? {}) - } -} - -it('keeps a tab closed when its profile write fails, and saves it on a later write', async () => { - const { store, authority, liveTabIds, savedTabIds } = await openWithTab() - expect(savedTabIds()).toContain(pane.tabId) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - authority.failNextWrite() - - const reply = await store.applyLayoutCommand({ - type: 'closeTabs', - workspace: pane.worktreeId, - tabIds: [pane.tabId] - }) - - expect(reply.ok).toBe(true) - expect(liveTabIds()).not.toContain(pane.tabId) - expect(savedTabIds()).toContain(pane.tabId) - await vi.waitFor(() => expect(savedTabIds()).not.toContain(pane.tabId), { timeout: 5000 }) -}) - -it('still refuses and rolls back a rename whose profile write fails', async () => { - const { store, authority } = await openWithTab() - authority.failNextWrite() - - await expect( - store.applyLayoutCommand({ - type: 'renameTab', - workspace: pane.worktreeId, - tabId: pane.tabId, - kind: 'custom', - title: 'Renamed' - }) - ).rejects.toThrow('profile_state_write_failed') - const tab = store - .getWorkspaceSession() - .tabsByWorktree[pane.worktreeId]?.find((row) => row.id === pane.tabId) - expect(tab?.customTitle ?? null).toBeNull() -}) diff --git a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts index 799c29d815b..f95ff084f38 100644 --- a/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts +++ b/src/main/persistence/terminal-topology/terminal-layout-apply.test.ts @@ -6,13 +6,13 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../shared/constants' import type { Store } from '../loading-store/store' -import { WindowSession } from './terminal-topology-window-session-fixture' +import { WindowSession } from './testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from './testing/terminal-topology-profile-fixture' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../ssh/config/ssh-config-parser', () => ({ diff --git a/src/main/persistence/terminal-topology/terminal-topology-commit.ts b/src/main/persistence/terminal-topology/terminal-topology-commit.ts index 73b62df3b57..edc27b39f36 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-commit.ts +++ b/src/main/persistence/terminal-topology/terminal-topology-commit.ts @@ -18,7 +18,7 @@ import { type PaneLayoutChange, type TerminalPaneAdmission, type TerminalPaneAdmissionOutcome -} from './terminal-pane-admission' +} from './pane-admission/terminal-pane-admission' import { startSpan } from '../../observability/tracer' import { terminalSurfaceCloseMutation, @@ -29,21 +29,21 @@ import type { StoreRuntimeState } from '../loading-store/store-runtime-state' import type { SessionHostPartitionOperations } from '../loading-store/workspace-sessions/session-host-partitions' -import { planTerminalLeafMove, writeMovedLeafProfileRecords } from './terminal-leaf-move' -import { writeRestorable } from './restorable-write' -import { assignWorkspaceSessionPartition } from './terminal-topology-membership' +import { planTerminalLeafMove, writeMovedLeafProfileRecords } from './pane-moves/terminal-leaf-move' +import { writeRestorable } from './command-application/restorable-write' +import { assignWorkspaceSessionPartition } from './pane-ownership/terminal-topology-membership' import { commitLayoutCommand, commitLayoutCommandsAcrossPartitions, commitWindowPaneDetach, keepFrozen, type LayoutCommandRun -} from './layout-command-commit' +} from './command-application/layout-command-commit' import { fencedIfLayoutOwner, layoutCommandFence, partitionsFence -} from './closed-pane-binding-fence' +} from './pane-ownership/closed-pane-binding-fence' /** Binding writes already have their own persistence.pty-binding span. */ type TerminalTopologyCommitKind = diff --git a/src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts similarity index 83% rename from src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts index 53fdc10c030..9668bf9f61c 100644 --- a/src/main/persistence/terminal-topology/terminal-leaf-move-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-leaf-move-fixture.ts @@ -2,11 +2,11 @@ import { mkdtempSync, realpathSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { vi } from 'vitest' -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { closeTestStores, createSqliteTestStore } from '../persistence-test-harness' -import { Store } from '../loading-store/store' -import { collectLayoutLeafIdsInOrder } from '../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' +import { closeTestStores, createSqliteTestStore } from '../../persistence-test-harness' +import { Store } from '../../loading-store/store' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-topology/terminal-pane-tree' // Import only after the test mocks electron. diff --git a/src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts similarity index 80% rename from src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts index 5742a0a89a3..53ab655f8ec 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-profile-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-topology-profile-fixture.ts @@ -1,9 +1,9 @@ import { join } from 'node:path' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { DelayedAuthority } from '../loading-store/profile-writing/profile-state-delayed-authority-fixture' -import { Store } from '../loading-store/store' -import { buildProfileStateCutoverFixture } from '../profile-state-cutover-fixture' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import { DelayedAuthority } from '../../loading-store/profile-writing/profile-state-delayed-authority-fixture' +import { Store } from '../../loading-store/store' +import { buildProfileStateCutoverFixture } from '../../profile-state-cutover-fixture' +import { ProfileStateSqliteAuthority } from '../../profile-state/profile-state-sqlite-authority' // Register this fixture repo so load pruning preserves its workspace. export const FIXTURE_GIT_WORKTREE_ID = 'repo-local::/fixture/local' diff --git a/src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts b/src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts similarity index 92% rename from src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts rename to src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts index 0caf345bf7a..4b64a9acb28 100644 --- a/src/main/persistence/terminal-topology/terminal-topology-window-session-fixture.ts +++ b/src/main/persistence/terminal-topology/testing/terminal-topology-window-session-fixture.ts @@ -1,10 +1,10 @@ -import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' -import type { Tab } from '../../../shared/tab-types' +import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume' +import type { Tab } from '../../../../shared/tab-types' import type { TerminalPaneLayoutNode, TerminalTab -} from '../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +} from '../../../../shared/workspace-layout/terminal-tab-types' +import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' export function leafIds(node: TerminalPaneLayoutNode | null | undefined): string[] { if (!node) { diff --git a/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts b/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts deleted file mode 100644 index 312ba9c8826..00000000000 --- a/src/main/persistence/terminal-topology/windowless-host-reload-keeps-terminals.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import type { Store } from '../loading-store/store' -import { leafIds } from './terminal-topology-window-session-fixture' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from './terminal-topology-profile-fixture' - -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const WORKTREE = FIXTURE_GIT_WORKTREE_ID -const leaf = (n: number): string => `${n}${n}${n}${n}${n}${n}${n}${n}-1111-4111-8111-111111111111` -const directories: string[] = [] - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -const on = { workspace: WORKTREE } - -async function apply(store: Store, command: LayoutCommand): Promise { - const result = await store.applyLayoutCommand(command) - expect(result.ok, command.type).toBe(true) -} - -async function bind(store: Store, tabId: string, leafId: string, ptyId: string): Promise { - await store.persistPtyBinding({ - worktreeId: WORKTREE, - tabId, - leafId, - ptyId, - incarnationId: `inc-${ptyId}` - }) -} - -function terminalsOf(session: WorkspaceSessionState) { - return { - rows: (session.tabsByWorktree[WORKTREE] ?? []).map((row) => [row.id, row.ptyId]), - tabBar: (session.unifiedTabs?.[WORKTREE] ?? []).map((tab) => tab.id), - panes: Object.fromEntries( - Object.entries(session.terminalLayoutsByTabId).map(([tabId, layout]) => [ - tabId, - { leaves: leafIds(layout.root), bindings: layout.ptyIdsByLeafId } - ]) - ), - sleeping: Object.keys(session.sleepingAgentSessionsByPaneKey ?? {}) - } -} - -describe('a windowless host reloaded in the layout-owner build', () => { - it('drops no terminal tab, pane or sleeping agent that main wrote itself', async () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-windowless-reload-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-split', leafId: leaf(1) }) - await bind(store, 'tab-split', leaf(1), 'pty-1') - await apply(store, { - ...on, - type: 'splitPane', - tabId: 'tab-split', - leafId: leaf(1), - direction: 'vertical', - newLeafId: leaf(2) - }) - await bind(store, 'tab-split', leaf(2), 'pty-2') - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-closed', leafId: leaf(3) }) - await bind(store, 'tab-closed', leaf(3), 'pty-3') - await apply(store, { ...on, type: 'closeTabs', tabIds: ['tab-closed'] }) - await apply(store, { ...on, type: 'createTerminalTab', tabId: 'tab-asleep', leafId: leaf(4) }) - await bind(store, 'tab-asleep', leaf(4), 'pty-4') - const paneKey = makePaneKey('tab-asleep', leaf(4)) - await apply(store, { - ...on, - type: 'sleep', - paneKeys: [paneKey], - records: [ - { - paneKey, - tabId: 'tab-asleep', - worktreeId: WORKTREE, - agent: 'codex', - providerSession: { key: 'session_id', id: 'session-4' }, - prompt: 'p', - state: 'working', - capturedAt: 1, - updatedAt: 1, - origin: 'live' - } - ] - }) - await apply(store, { - ...on, - type: 'createTerminalTab', - tabId: 'tab-unstarted', - leafId: leaf(5) - }) - await store.flushPendingOrThrowAsync() - const written = terminalsOf(store.getWorkspaceSession()) - expect(written.rows.map(([id]) => id)).toEqual(['tab-split', 'tab-asleep', 'tab-unstarted']) - expect(written.sleeping).toEqual([paneKey]) - - const relaunched = await reopenTopologyStore(store, directory) - - expect(terminalsOf(relaunched.getWorkspaceSession())).toEqual(written) - }) -}) diff --git a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts index 5c6b11b11b3..727cee43b38 100644 --- a/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts +++ b/src/main/rate-limits/providers/claude/claude-oauth-credentials.ts @@ -109,7 +109,7 @@ export async function readClaudeOAuthCredentials( return keychain } try { - return parseClaudeOAuthCredentialsJson( + const file = parseClaudeOAuthCredentialsJson( await readFile( path.join( options?.credentialsFileConfigDir ?? path.join(homedir(), '.claude'), @@ -119,6 +119,10 @@ export async function readClaudeOAuthCredentials( ), 'credentials-file' ) + // A file with no token must not hide a refreshable or unreadable Keychain login. + return file.token || !(keychain.hasRefreshableCredentials || keychain.unavailable) + ? file + : keychain } catch (error) { return isDefinitiveAbsence(error) ? keychain : { ...keychain, unavailable: true } } diff --git a/src/main/runtime/__fixtures__/main-layout-close-fixture.ts b/src/main/runtime/__fixtures__/main-layout-close-fixture.ts index 51bb4a029d7..adc2c3979ae 100644 --- a/src/main/runtime/__fixtures__/main-layout-close-fixture.ts +++ b/src/main/runtime/__fixtures__/main-layout-close-fixture.ts @@ -8,11 +8,11 @@ import type { import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { DurableProfileStateMutation } from '../../persistence/loading-store/store-runtime-state' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { isTerminalClose, keptOnWriteFailure -} from '../../persistence/terminal-topology/terminal-close-write-failure' +} from '../../persistence/terminal-topology/command-application/terminal-close-write-failure' type SessionCell = { get: () => WorkspaceSessionState diff --git a/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts b/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts index 96941027333..8aeb7a387fb 100644 --- a/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts +++ b/src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts @@ -1,165 +1,6 @@ import { expect, it, vi } from 'vitest' import { createChatTabLayoutQueue } from './agent-session-tab-layout-queue' -const open = (sessionId: string) => ({ - worktreeId: 'wt', - change: { open: { sessionId, agent: 'codex' as const, tabId: `tab-${sessionId}` } } -}) - -it('settles continuous placement changes and drains the next worktree open', async () => { - const { getDefaultWorkspaceSession } = await import('../../../shared/constants') - const { withChatTabChanges } = await import('./agent-session-tab-layout') - const { applyCommandToSession } = - await import('../../persistence/terminal-topology/terminal-pane-admission') - let session = withChatTabChanges('local', getDefaultWorkspaceSession(), 'wt', [ - open('source').change, - open('B').change, - open('other').change - ])! - const group1 = session.tabGroups!['wt']![0]!.id - const applyNow = (command: Parameters[2]) => { - const result = applyCommandToSession('local', session, command) - session = result.session ?? session - return result.value - } - expect( - applyNow({ - type: 'splitGroup', - workspace: 'wt', - tabId: 'tab-other', - besideGroupId: group1, - direction: 'right' - }).ok - ).toBe(true) - const group2 = session.tabGroups!['wt']!.find((group) => group.id !== group1)!.id - let attempts = 0 - const written: string[] = [] - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const queue = createChatTabLayoutQueue({ - sessionOf: () => session, - hostIdOf: () => 'local', - apply: async (command, run) => { - if (command.type === 'openAgentSessionTab' && command.sessionId === 'child') { - attempts++ - expect( - applyNow({ - type: 'moveTab', - workspace: 'wt', - tabId: 'tab-source', - toGroupId: command.groupId === group1 ? group2 : group1, - index: 0 - }).ok - ).toBe(true) - } - const admitted = run?.admit([session]) !== false - // Let the uncapped regression fail without leaving its asynchronous loop running. - if (command.type === 'openAgentSessionTab' && command.sessionId === 'child' && attempts > 4) { - throw new Error('placement attempts did not settle') - } - if (!admitted) { - return { ok: false, code: 'tab_not_found' } - } - const result = applyNow(command) - if (result.ok && command.type === 'openAgentSessionTab') { - written.push(command.sessionId) - } - return result - } - }) - try { - queue([ - { - worktreeId: 'wt', - change: { - open: { - sessionId: 'child', - agent: 'codex', - tabId: 'tab-child', - placement: { afterTabId: 'agent-session:source' } - } - }, - eligible: () => true - } - ]) - await queue([{ ...open('next'), worktreeId: 'next-worktree' }]) - expect(attempts).toBe(4) - expect(written).toEqual(['next']) - expect(session.unifiedTabs?.['next-worktree']?.map((tab) => tab.entityId)).toEqual(['next']) - expect(queue.pendingOpens()).toEqual([]) - } finally { - warn.mockRestore() - } -}) - -it('checks admission inside the actual profile queue before replacement close effects, and does not freeze later writes', async () => { - const { fixture } = - await import('../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture') - const { applyWindowLayoutCommand } = await import('../terminal/layout/runtime-layout-apply') - const { store, authority } = await fixture() - const workspace = 'chat-inner-queue' - const opened = await store.applyLayoutCommand({ - type: 'openAgentSessionTab', - workspace, - sessionId: 'session-a', - agent: 'codex', - tabId: 'agent-chat-tab-v1-old' - }) - expect(opened.ok).toBe(true) - const gate = authority.pause() - const holding = store.runDurableMutation(() => { - store.updateSettings({ theme: 'dark' }) - return { value: undefined } - }) - await gate.started.promise - let current = true - const effects = vi.fn() - const entered = Promise.withResolvers(), - settled = Promise.withResolvers() - const queue = createChatTabLayoutQueue({ - sessionOf: () => store.getWorkspaceSession(), - hostIdOf: () => 'local', - apply: async (command, run) => { - entered.resolve() - try { - return await applyWindowLayoutCommand(store, () => ['local'], command, undefined, { - ...run, - onEffects: effects - }) - } finally { - settled.resolve() - } - } - }) - queue(() => [ - { - worktreeId: workspace, - change: { close: 'session-a', tabId: 'agent-chat-tab-v1-old' }, - eligible: () => current - } - ]) - await entered.promise - current = false - const before = authority.captures.length - gate.finish.resolve() - await holding - await settled.promise - expect(effects).not.toHaveBeenCalled() - expect(authority.captures.length).toBe(before) - expect(store.getWorkspaceSession().unifiedTabs?.[workspace]?.map((tab) => tab.id)).toEqual([ - 'agent-chat-tab-v1-old' - ]) - expect( - await applyWindowLayoutCommand( - store, - () => ['local'], - { type: 'closeTabs', workspace, tabIds: ['agent-chat-tab-v1-old'], force: true }, - undefined, - { admit: () => true } - ) - ).toMatchObject({ ok: true }) - expect(store.getWorkspaceSession().unifiedTabs?.[workspace] ?? []).toEqual([]) -}) - it('refuses a captured close when another actual holder now uses that id for a different session', async () => { const { fixture } = await import('../../persistence/loading-store/profile-writing/profile-state-delayed-authority-fixture') diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts index 65c8852b335..7c83f6b87b7 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts @@ -181,8 +181,8 @@ export function structuredChatNamingDeps( }) const useChatAgent = !recipe.agentId && !recipe.agentArgs?.trim() const log = { scope: 'conversation-name', sessionId: record.sessionId } - // Copilot saves every run, so a naming run would sit in the user's Copilot history. - if (useChatAgent && record.provider === 'copilot') { + // These save every CLI run, so a naming run would sit in the user's own history. + if (useChatAgent && (record.provider === 'copilot' || record.provider === 'kimi')) { return null } if (useChatAgent && (record.provider === 'grok' || record.provider === 'antigravity')) { diff --git a/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts b/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts index c0278d40d9d..cd54e93b6c3 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-owner-proof.ts @@ -1,5 +1,6 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionProviderHandleLink } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { AgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import { withAcquiredAgentSessionAccount, type ClaudeAccountRecipe @@ -21,9 +22,11 @@ export function createAgentSessionOwnerProof( now: number leaseTtlMs?: number accountAcquisition?: { generation: string; recipe: ClaudeAccountRecipe } + /** The account this runtime launched under, when the provider reports one. */ + launchedAccountHome?: AgentSessionAccountHome }): Promise => - mutate(args.sessionId, (record) => - withAcquiredAgentSessionAccount( + mutate(args.sessionId, (record) => { + const { launchedAccount: _previous, ...proved } = withAcquiredAgentSessionAccount( proveAgentSessionOwner({ record, fence: args.fence, @@ -33,5 +36,12 @@ export function createAgentSessionOwnerProof( }), args.accountAcquisition ) - ) + // A runtime that reports no account leaves no stale claim about where this fence ran. + return args.launchedAccountHome + ? { + ...proved, + launchedAccount: { fence: args.fence, accountHome: args.launchedAccountHome } + } + : proved + }) } diff --git a/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts b/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts deleted file mode 100644 index 64a273fe303..00000000000 --- a/src/main/runtime/browser/headless/serve-browser-tabs-layout-owner.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { - LayoutApplyOutcome, - LayoutCommand -} from '../../../../shared/workspace-layout/workspace-layout-command-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import { ServeBrowserTabs } from './serve-browser-tabs' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const WT = 'repo-1::/repo' -const PAGE = { worktreeId: WT, pageId: 'page-1', url: 'https://example.com/', title: 'Example' } - -/** A host with no window whose layout writes go through `layout.apply`'s record patch. */ -function servedHost(initial: WorkspaceSessionState = getDefaultWorkspaceSession()) { - let session = initial - const save = vi.fn((_worktreeId: string, next: WorkspaceSessionState) => { - session = next - }) - const applyLayout = vi.fn( - async (command: LayoutCommand, hostId: ExecutionHostId): Promise => { - const change = applyCommandToSession(hostId, session, command) - session = change.session ?? session - return change.value - } - ) - const tabs = new ServeBrowserTabs({ - backend: () => ({ createTab: vi.fn(), closeTab: vi.fn(), ownsTab: () => true }), - livePageIds: () => new Set(), - savedWorktreeIds: () => [WT], - session: () => session, - hostId: () => 'local', - save, - applyLayout - }) - return { tabs, applyLayout, save, session: () => session } -} - -const settle = () => new Promise((resolve) => setTimeout(resolve, 0)) - -describe('served browser tabs in a layout-owner build', () => { - it('closes a window-saved tab by its own tab-bar entry', async () => { - const host = servedHost() - host.tabs.opened(PAGE) - await settle() - // As a window saves it: the tab-bar entry has its own id. - const saved = host.session() - host.save(WT, { - ...saved, - unifiedTabs: { - [WT]: saved.unifiedTabs![WT]!.map((entry) => ({ ...entry, id: 'unified-1' })) - }, - tabGroups: { - [WT]: saved.tabGroups![WT]!.map((group) => ({ - ...group, - activeTabId: null, - tabOrder: ['unified-1'] - })) - } - }) - - host.tabs.closed(WT, 'page-1') - await settle() - - expect(host.applyLayout).toHaveBeenLastCalledWith( - { type: 'closeTabs', workspace: WT, tabIds: ['unified-1'], force: true }, - 'local' - ) - expect(host.session().browserTabsByWorktree?.[WT] ?? []).toEqual([]) - expect(host.session().unifiedTabs?.[WT] ?? []).toEqual([]) - }) - - it('saves the address a page reached while main was writing its tab', async () => { - const host = servedHost() - - host.tabs.opened(PAGE) - host.tabs.navigated({ ...PAGE, url: 'https://example.com/next', title: 'Next' }) - await settle() - - expect(host.session().browserPagesByWorkspace?.['page-1']).toEqual([ - expect.objectContaining({ url: 'https://example.com/next', title: 'Next' }) - ]) - expect(host.session().browserTabsByWorktree?.[WT]?.[0]).toMatchObject({ title: 'Next' }) - }) - - it('closes a tab closed while main was writing it, and saves no page for it', async () => { - const host = servedHost() - - host.tabs.opened(PAGE) - expect(host.tabs.closed(WT, 'page-1')).toBe(true) - await settle() - - expect(host.session().browserTabsByWorktree?.[WT] ?? []).toEqual([]) - expect(host.session().browserPagesByWorkspace?.['page-1']).toBeUndefined() - expect(host.tabs.listUnstarted(WT)).toEqual([]) - }) -}) diff --git a/src/main/runtime/construction/runtime-service-command-surface.ts b/src/main/runtime/construction/runtime-service-command-surface.ts index 5c35c36b2da..8cd562414d0 100644 --- a/src/main/runtime/construction/runtime-service-command-surface.ts +++ b/src/main/runtime/construction/runtime-service-command-surface.ts @@ -201,7 +201,8 @@ export function installRuntimeServiceCommandSurface( clearOpenAiSpeechKey: speech.clearOpenAiKey.bind(speech), startMobileDictation: dictation.start.bind(dictation), feedMobileDictation: dictation.feed.bind(dictation), - finishMobileDictation: dictation.finish.bind(dictation), + finishMobileDictation: (params) => + dictation.finish(params, accounts.getCommitMessageAgentEnvironment()), cancelMobileDictation: dictation.cancel.bind(dictation), getAllBrowserDrivers: browsers.getAll.bind(browsers), reclaimBrowserForDesktop: browsers.reclaimForDesktop.bind(browsers), 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/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/runtime/mobile-cloud-relay/relay-auth-context.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts similarity index 76% rename from src/main/runtime/mobile-cloud-relay/relay-auth-context.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts index 6f4b751dec0..ca0a2c01bdf 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-context.ts @@ -1,6 +1,6 @@ -import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' -import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' -import { readFreshOrcaCloudSession } from '../../orca-profiles/cloud-session/profile-cloud-session-refresh' +import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { ensureActiveOrcaProfile } from '../../../orca-profiles/profile-index-store' +import { readFreshOrcaCloudSession } from '../../../orca-profiles/cloud-session/profile-cloud-session-refresh' import type { RelayAuthContext } from './relay-auth-identity' export async function readRelayAuthContext( diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts new file mode 100644 index 00000000000..d0e235f41bc --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator-readiness.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import '../desktop-relay-service' +import { RelayAuthCoordinator } from './relay-auth-coordinator' +import type { RelayAuthContext } from './relay-auth-identity' +import { RelayHttpError } from '../director/relay-http-client' + +import '../session-lifecycle/relay-session-broker' + +const context: RelayAuthContext = { + identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, + accessToken: 'access-1', + relayEntitled: true +} + +describe('relay readiness', () => { + afterEach(() => vi.useRealTimers()) + + it('stops waiting when a fence cancels the scheduled retry', async () => { + vi.useFakeTimers() + const coordinator = new RelayAuthCoordinator({ + readContext: async () => context, + openBroker: async () => { + throw new RelayHttpError('token-exchange', 502) + }, + onStatus: () => {}, + random: () => 1 + }) + coordinator.reconcile() + const waiting = coordinator.waitForReadiness(20_000) + await vi.advanceTimersByTimeAsync(0) + coordinator.fenceAndCloseNow() + await expect(waiting).resolves.toEqual({ + ready: false, + reason: 'control_not_active', + retryAt: null + }) + }) + + function coldStartWithHungRetry(): RelayAuthCoordinator { + const openBroker = vi + .fn() + .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) + .mockImplementationOnce(() => new Promise(() => {})) + return new RelayAuthCoordinator({ + readContext: async () => context, + openBroker, + onStatus: () => {}, + random: () => 0.5 + }) + } + + it('returns at its deadline while the retry it followed is still opening', async () => { + vi.useFakeTimers() + const coordinator = coldStartWithHungRetry() + coordinator.reconcile() + let settled: unknown = null + void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness)) + await vi.advanceTimersByTimeAsync(9_999) + expect(settled).toBeNull() + await vi.advanceTimersByTimeAsync(1) + expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' }) + coordinator.stop() + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts index ef73086b5af..cbc73d071d9 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { RelayAuthCoordinator } from './relay-auth-coordinator' import type { RelayAuthContext } from './relay-auth-identity' -import type { RelayAccessTokenRefresh } from './relay-session-broker-contract' +import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract' function deferred() { let resolve!: (value: T) => void diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts similarity index 96% rename from src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts index ad2554d1185..4a2b5b101a2 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-coordinator.ts @@ -1,12 +1,12 @@ import { RELAY_HOST_CLOSE_REASON, type RelayHostCloseReason -} from '../../../shared/relay-host-close-reason' -import { relayStatusCellUrl } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type * as RelayStatus from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { RelayAccessTokenRefresh } from './relay-session-broker-contract' +} from '../../../../shared/relay-host-close-reason' +import { relayStatusCellUrl } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type * as RelayStatus from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { RelayAccessTokenRefresh } from '../session-lifecycle/relay-session-broker-contract' -import { shouldRetryRelayConnectionError } from './relay-http-client' +import { shouldRetryRelayConnectionError } from '../director/relay-http-client' import { RelayReadinessWaiters, relayRetryFloorMs, diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts similarity index 74% rename from src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts index 7251ba8d998..fee2cb49707 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-identity.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-auth-identity.ts @@ -1,4 +1,4 @@ -import type { RelayIdentity } from './relay-session-broker-contract' +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' export type RelayAuthContext = { identity: RelayIdentity diff --git a/src/main/runtime/mobile-cloud-relay/relay-linger-timer.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-linger-timer.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-linger-timer.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-linger-timer.ts diff --git a/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts new file mode 100644 index 00000000000..7a311015e68 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness-retention.test.ts @@ -0,0 +1,24 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters' +import { RelayReadinessWaiters } from './relay-readiness' + +afterEach(() => vi.useRealTimers()) + +describe('relay readiness wait lifetime', () => { + it('releases callers without cancelling shared work and permits a later wait', async () => { + vi.useFakeTimers() + let finish = (): void => {} + const work = new Promise((resolve) => { + finish = resolve + }) + const waiters = new RelayReadinessWaiters() + const first = waiters.until(work, Date.now() + 10_000) + waiters.releaseAll() + await expect(first).resolves.toBe(false) + expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0) + const next = waiters.until(work, Date.now() + 10_000) + finish() + await expect(next).resolves.toBe(true) + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-readiness.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts index f8949fc7eb7..2b943e73014 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts +++ b/src/main/runtime/mobile-cloud-relay/authentication/relay-readiness.ts @@ -1,6 +1,6 @@ -import { RelayHttpError } from './relay-http-client' -import { RelayHostProofClockSkewError } from './relay-host-proof' -import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' +import { RelayHttpError } from '../director/relay-http-client' +import { RelayHostProofClockSkewError } from '../control-channel/relay-host-proof' +import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason' // Lowercase reason tokens must form valid relay_ mint-failure codes. export type RelayUnavailableReason = diff --git a/src/main/runtime/mobile-cloud-relay/relay-retry-schedule.ts b/src/main/runtime/mobile-cloud-relay/authentication/relay-retry-schedule.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-retry-schedule.ts rename to src/main/runtime/mobile-cloud-relay/authentication/relay-retry-schedule.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts similarity index 91% rename from src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts index 5a67bdeb8c9..7902b07c633 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client-options.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client-options.ts @@ -1,5 +1,5 @@ import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' import type { RelayConnectionOpenMessage, RelayDrainMessage } from './relay-control-protocol' export type RelayControlClientOptions = { diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts similarity index 99% rename from src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts index a43d8abd3d7..b9acf8e13c6 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.test.ts @@ -4,7 +4,7 @@ import type { Server, Socket } from 'node:net' import { afterEach, describe, expect, it, vi } from 'vitest' import nacl from 'tweetnacl' import { WebSocketServer, type WebSocket } from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' import { RelayControlClient } from './relay-control-client' diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-client.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts index e5227a79034..7dc56857d58 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-client.ts @@ -1,8 +1,8 @@ import type { RelayControlClientOptions } from './relay-control-client-options' import { randomUUID } from 'node:crypto' import WebSocket, { type RawData } from 'ws' -import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/remote-runtime/relay/mobile-relay-close-codes' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' +import { MOBILE_RELAY_CLOSE_CODE } from '../../../../shared/remote-runtime/relay/mobile-relay-close-codes' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' import { RelayConnectionOpenMessageSchema, RelayControlErrorMessageSchema, diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts index 1d85b1431a0..fab2ddd9cf7 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-liveness.ts @@ -1,5 +1,5 @@ import type { RelayControlRequestTimeout } from './relay-control-requests' -import { RELAY_RENEWAL_JITTER_RATIO } from './relay-renewal-jitter' +import { RELAY_RENEWAL_JITTER_RATIO } from '../session-lifecycle/relay-renewal-jitter' import { RELAY_CLIENT_KEEPALIVE_FRAME, RelayKeepaliveAckMessageSchema, diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts index a0fca00db85..619ceaebecf 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-protocol.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol.ts @@ -3,7 +3,7 @@ import type { RawData } from 'ws' import { DeviceCredentialInstalledSchema, DeviceResumeConfirmedSchema -} from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' +} from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract' const OpaqueIdSchema = z.string().min(1).max(128) const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-requests.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-requests.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-control-requests.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-requests.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts similarity index 88% rename from src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts index f215c9c40cc..9a46710e060 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-socket-close.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-socket-close.ts @@ -1,5 +1,5 @@ import type WebSocket from 'ws' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' const NORMAL_CLOSE_CODE = 1000 const REASONED_CLOSE_FLUSH_MS = 1_000 diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-url.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-control-url.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-control-url.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-control-url.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts similarity index 88% rename from src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts index 9e491599db5..0b2f06a5564 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.test.ts @@ -1,4 +1,4 @@ -import { createHmac, randomBytes } from 'node:crypto' +import { randomBytes } from 'node:crypto' import { describe, expect, it } from 'vitest' import nacl from 'tweetnacl' import { @@ -84,7 +84,6 @@ function buildChallengeFixture(options: { }): { challenge: RelayHostChallenge context: RelayHostProofContext - expectedProof: string } { const hostKeys = nacl.box.keyPair() const relayKeys = nacl.box.keyPair() @@ -130,27 +129,11 @@ function buildChallengeFixture(options: { resumeRequested: false, now: () => options.localNow } - const expectedProof = createHmac('sha256', secret) - .update(text(`${HOST_PROOF_DOMAIN}\0ack\0`)) - .update(transcript) - .digest('base64') - return { challenge, context, expectedProof } + + return { challenge, context } } describe('answerRelayHostChallenge clock skew (#10401)', () => { - it('accepts challenges at the clock-skew boundaries', () => { - const issuedAt = 1_700_000_000_000 - const expiresAt = issuedAt + 10_000 - for (const localNow of [issuedAt - CLOCK_SKEW_MS, expiresAt + CLOCK_SKEW_MS]) { - const { challenge, context, expectedProof } = buildChallengeFixture({ - issuedAt, - expiresAt, - localNow - }) - expect(answerRelayHostChallenge(challenge, context)).toBe(expectedProof) - } - }) - it('still rejects challenges outside the allowed skew window', () => { const serverNow = 1_700_000_000_000 const issuedAt = serverNow diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-host-proof.ts rename to src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts index 69e536eed38..c2700838753 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts +++ b/src/main/runtime/mobile-cloud-relay/control-channel/relay-host-proof.ts @@ -6,7 +6,7 @@ import { openHostChallengeEnvelope, parseHostChallengeTranscript, readTranscriptUint64 -} from '../hosts/identity/host-challenge-envelope' +} from '../../hosts/identity/host-challenge-envelope' const HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-relay-host-proof/v1' const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1' diff --git a/src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts b/src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts similarity index 93% rename from src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts rename to src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts index 965d81fc203..1d12fe2e45f 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-demand-ledger.ts +++ b/src/main/runtime/mobile-cloud-relay/demand/relay-demand-ledger.ts @@ -1,5 +1,5 @@ -import type { DeviceRegistry } from '../rpc/server/pairing/device-registry' -import type { RelayRevokeOutbox } from './relay-revoke-outbox' +import type { DeviceRegistry } from '../../rpc/server/pairing/device-registry' +import type { RelayRevokeOutbox } from '../pairing/relay-revoke-outbox' type RelayDemandLedgerOptions = { deviceRegistry: DeviceRegistry diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts index 20f26c42aa0..482676a9e06 100644 --- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts +++ b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts @@ -8,22 +8,22 @@ import type { PairingProvisionRelayParams } from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import { readRelayAuthContext } from './relay-auth-context' -import { relayIdentityKey } from './relay-auth-identity' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import { RelayUnavailableError } from './relay-readiness' -import { RelaySessionBroker } from './relay-session-broker' +import { readRelayAuthContext } from './authentication/relay-auth-context' +import { relayIdentityKey } from './authentication/relay-auth-identity' +import { RelayAuthCoordinator } from './authentication/relay-auth-coordinator' +import { RelayUnavailableError } from './authentication/relay-readiness' +import { RelaySessionBroker } from './session-lifecycle/relay-session-broker' import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status' import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' import type { RelayRevokeOutbox, RelayDeviceBinding, RelayRevokeOutboxItem -} from './relay-revoke-outbox' -import { pairingAuthorizationForContext } from './relay-pairing-authorization' -import { deriveRelayHostId } from './relay-http-client' -import { RelayDemandLedger } from './relay-demand-ledger' -import { createRelayRegionPreferenceReader } from './relay-region-preference-reader' +} from './pairing/relay-revoke-outbox' +import { pairingAuthorizationForContext } from './pairing/relay-pairing-authorization' +import { deriveRelayHostId } from './director/relay-http-client' +import { RelayDemandLedger } from './demand/relay-demand-ledger' +import { createRelayRegionPreferenceReader } from './region-selection/relay-region-preference-reader' type DesktopRelayServiceOptions = { authConfig: OrcaCloudAuthConfig diff --git a/src/main/runtime/mobile-cloud-relay/relay-assign-rate-gate.ts b/src/main/runtime/mobile-cloud-relay/director/relay-assign-rate-gate.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-assign-rate-gate.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-assign-rate-gate.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-http-client.test.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-http-client.ts b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-http-client.ts rename to src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts index c3cd5b23094..d601bb8e23d 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-http-client.ts +++ b/src/main/runtime/mobile-cloud-relay/director/relay-http-client.ts @@ -1,8 +1,8 @@ import { createHash } from 'node:crypto' import { z } from 'zod' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' -import { parseRetryAfterHeaderMs } from '../../../shared/retry-after-header' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' +import { parseRetryAfterHeaderMs } from '../../../../shared/retry-after-header' import { RelayAssignAbortedError, RelayAssignRateLimitedError, @@ -10,11 +10,11 @@ import { sharedRelayAssignRateGate, type RelayAssignRateGate } from './relay-assign-rate-gate' -import type { RelayRegion } from './relay-region-probe' +import type { RelayRegion } from '../region-selection/relay-region-probe' import { RelayRegionCorrectionResponseSchema, type RelayRegionCorrectionRequest -} from './relay-region-correction-protocol' +} from '../region-selection/relay-region-correction-protocol' const RELAY_HTTP_REQUEST_DEADLINE_MS = 15_000 const RELAY_RETRY_AFTER_MAX_MS = 5 * 60_000 diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts similarity index 67% rename from src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts index 44e5a4e5858..2f74e8a1c7f 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-origin-options.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin-options.ts @@ -1,10 +1,10 @@ import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring' -import type { RelayIdentity } from './relay-session-broker-contract' -import type { RelayAssignment } from './relay-http-client' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' +import type { RelayAssignment } from '../director/relay-http-client' import type { RelayControlOrigin } from './relay-control-origin' -import type { RelayDrainMessage } from './relay-control-protocol' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' export type RelayControlOriginOptions = { assignment: RelayAssignment diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-origin.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-control-origin.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts index e89917cfc6b..002df4b73de 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-origin.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-origin.ts @@ -1,14 +1,14 @@ import type { RelayControlOriginOptions } from './relay-control-origin-options' -import { CloudRelayTransport } from '../rpc/transports/relay-transport' -import { RelayControlClient } from './relay-control-client' -import { RELAY_HOST_ATTACH_DEADLINE_MS } from './relay-control-protocol' +import { CloudRelayTransport } from '../../rpc/transports/relay-transport' +import { RelayControlClient } from '../control-channel/relay-control-client' +import { RELAY_HOST_ATTACH_DEADLINE_MS } from '../control-channel/relay-control-protocol' import type { RelayConnectionOpenMessage, RelayHostHelloAckMessage, RelayPendingConnection -} from './relay-control-protocol' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { RelayAssignment } from './relay-http-client' +} from '../control-channel/relay-control-protocol' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { RelayAssignment } from '../director/relay-http-client' const OBSERVED_OPEN_LIMIT = 16 diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts similarity index 92% rename from src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts index 2f1de94e6c0..b3e620a7277 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-control-rotation.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-control-rotation.ts @@ -1,6 +1,6 @@ import type { RelayControlOrigin } from './relay-control-origin' -import type { RelayAssignment } from './relay-http-client' -import { relayRenewalDelayMs } from './relay-renewal-jitter' +import type { RelayAssignment } from '../director/relay-http-client' +import { relayRenewalDelayMs } from '../session-lifecycle/relay-renewal-jitter' type RotationOptions = { current: () => RelayControlOrigin | null diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts similarity index 62% rename from src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts index c20a4c567d3..c31f90108e3 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-pool-options.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool-options.ts @@ -1,9 +1,9 @@ import type WebSocket from 'ws' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring' -import type { RelayIdentity } from './relay-session-broker-contract' -import type { MobileRelayStatus as RelayBrokerStatus } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { RelayRegion } from './relay-region-probe' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayIdentity } from '../session-lifecycle/relay-session-broker-contract' +import type { MobileRelayStatus as RelayBrokerStatus } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { RelayRegion } from '../region-selection/relay-region-probe' export type RelayOriginPoolOptions = { directorUrl: string diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts similarity index 94% rename from src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts index c189ef8b908..e135de4eeae 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-pool.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool.ts @@ -1,11 +1,15 @@ import { RelayOriginRetirement } from './relay-origin-retirement' import type { RelayOriginPoolOptions } from './relay-origin-pool-options' import { RelayControlOrigin } from './relay-control-origin' -import type { RelayControlClient } from './relay-control-client' -import type { RelayDrainMessage } from './relay-control-protocol' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import { RelayRetrySchedule } from './relay-retry-schedule' -import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' +import type { RelayControlClient } from '../control-channel/relay-control-client' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import { RelayRetrySchedule } from '../authentication/relay-retry-schedule' +import { + RelayHttpError, + requestRelayAssignment, + type RelayAssignment +} from '../director/relay-http-client' import { RelayControlRotation } from './relay-control-rotation' export class RelayOriginPool { diff --git a/src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts rename to src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts index bcc2a439ef2..8ae08bd49c0 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-origin-retirement.ts +++ b/src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-retirement.ts @@ -1,4 +1,4 @@ -import type { RelayDrainMessage } from './relay-control-protocol' +import type { RelayDrainMessage } from '../control-channel/relay-control-protocol' import type { RelayControlOrigin } from './relay-control-origin' export class RelayOriginRetirement { diff --git a/src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts similarity index 76% rename from src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts rename to src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts index 9f2d5e48132..97e87ea5b94 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-pairing-authorization.ts +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-pairing-authorization.ts @@ -1,5 +1,5 @@ -import type { MobilePairingConnectionContext } from '../rpc/server/runtime-rpc-pairing-types' -import type { DeviceCredentialInstallAuthorization } from './relay-control-requests' +import type { MobilePairingConnectionContext } from '../../rpc/server/runtime-rpc-pairing-types' +import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests' // Derives install authorization only from immutable connection metadata, never from request params. export function pairingAuthorizationForContext( diff --git a/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts new file mode 100644 index 00000000000..2fd60c56a06 --- /dev/null +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.test.ts @@ -0,0 +1,33 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +import { RelayRevokeOutbox } from './relay-revoke-outbox' + +describe('RelayRevokeOutbox', () => { + const paths: string[] = [] + afterEach(() => { + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } + }) + + it('durably retains an idempotent account-scoped revoke after local deletion', () => { + const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) + paths.push(path) + const binding = { + relayHostId: 'AbCdEf0123_-xyZ9', + relayDeviceId: 'device-1', + ownerIdentityKey: 'user-1\0profile-1\0org-1' + } + const first = new RelayRevokeOutbox(path).enqueue(binding) + const reloaded = new RelayRevokeOutbox(path) + expect(reloaded.enqueue(binding).reqId).toBe(first.reqId) + expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first]) + reloaded.remove(first.reqId) + expect( + new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) + ).toEqual([]) + }) +}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts rename to src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts index fba0a05ef81..f800980229e 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +++ b/src/main/runtime/mobile-cloud-relay/pairing/relay-revoke-outbox.ts @@ -5,7 +5,7 @@ import { hardenExistingSecureFile, isUnreadableError, writeSecureJsonFile -} from '../../../shared/secure-storage/secure-file' +} from '../../../../shared/secure-storage/secure-file' export type RelayDeviceBinding = { relayHostId: string diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts similarity index 91% rename from src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts index 64566b89b94..385eab9e41e 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-catalog-fetch.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-catalog-fetch.ts @@ -1,5 +1,5 @@ -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' -import { readFetchResponseJsonWithinLimit } from '../../../shared/fetch-response-body' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' +import { readFetchResponseJsonWithinLimit } from '../../../../shared/fetch-response-body' import { RelayRegionCatalogSchema, type RelayRegionCatalog } from './relay-region-probe' const CATALOG_MAX_BYTES = 16 * 1024 diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-correction-protocol.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-correction-protocol.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-correction-protocol.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-correction-protocol.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-decision.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-decision.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-decision.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-decision.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference-reader.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference-reader.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference-reader.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference-reader.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference.test.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.test.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts similarity index 99% rename from src/main/runtime/mobile-cloud-relay/relay-region-preference.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts index db5e0205449..7276e4dab77 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-preference.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-preference.ts @@ -6,7 +6,7 @@ import { z } from 'zod' import { hardenExistingSecureFile, writeSecureJsonFile -} from '../../../shared/secure-storage/secure-file' +} from '../../../../shared/secure-storage/secure-file' import { fetchRelayRegionCatalog, relayDirectorHost } from './relay-region-catalog-fetch' import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' import { diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-probe-log.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe-log.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-region-probe-log.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe-log.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-probe.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts similarity index 98% rename from src/main/runtime/mobile-cloud-relay/relay-region-probe.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts index f296c3f6a18..fee8f97d5c3 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-probe.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-probe.ts @@ -1,6 +1,6 @@ import { performance } from 'node:perf_hooks' import { z } from 'zod' -import { cancelUnreadResponseBody } from '../../lib/unread-response-body' +import { cancelUnreadResponseBody } from '../../../lib/unread-response-body' export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const export type RelayRegion = (typeof RELAY_REGIONS)[number] diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts similarity index 97% rename from src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts rename to src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts index c93a9d9618e..88fba8fe921 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.ts +++ b/src/main/runtime/mobile-cloud-relay/region-selection/relay-region-refresh.ts @@ -1,4 +1,8 @@ -import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' +import { + RelayHttpError, + requestRelayAssignment, + type RelayAssignment +} from '../director/relay-http-client' import type { RelayRegionCorrectionRequest, RelayRegionDecision, diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts deleted file mode 100644 index c6e724ee319..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-readiness.test.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { DesktopRelayService } from './desktop-relay-service' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import { RelayHttpError } from './relay-http-client' - -import { RelaySessionBroker } from './relay-session-broker' - -const context: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-1', - relayEntitled: true -} - -function fakeSessionBroker(): RelaySessionBroker { - const broker = Object.create(RelaySessionBroker.prototype) - Object.defineProperties(broker, { - closeNow: { value: vi.fn() }, - isLive: { value: () => true }, - createPairingRelay: { value: vi.fn(async () => ({ inviteExpiresAt: 1 })) }, - endpoint: { value: null }, - hostId: { value: 'host-1' }, - ownerIdentityKey: { value: 'owner-1' } - }) - return broker -} - -function serviceWith(coordinator: RelayAuthCoordinator): DesktopRelayService { - const service = Object.create(DesktopRelayService.prototype) - return Object.assign(service, { - coordinator, - stopped: false, - livenessTimer: null, - demandExpiryTimer: null, - demandLedger: { acquireTransient: () => () => {}, nextPendingExpiry: () => null } - }) -} - -describe('relay readiness', () => { - afterEach(() => vi.useRealTimers()) - - it('waits through the retry a cold-start failure scheduled instead of failing the mint', async () => { - vi.useFakeTimers() - const broker = fakeSessionBroker() - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) - .mockResolvedValueOnce(broker) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: () => {}, - random: () => 1 - }) - const service = serviceWith(coordinator) - const mint = service.createPairingRelay('device-1') - await vi.advanceTimersByTimeAsync(2_000) - await expect(mint).resolves.toMatchObject({ binding: { relayHostId: 'host-1' } }) - expect(openBroker).toHaveBeenCalledTimes(2) - service.stop() - }) - - it('stops waiting when a fence cancels the scheduled retry', async () => { - vi.useFakeTimers() - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker: async () => { - throw new RelayHttpError('token-exchange', 502) - }, - onStatus: () => {}, - random: () => 1 - }) - coordinator.reconcile() - const waiting = coordinator.waitForReadiness(20_000) - await vi.advanceTimersByTimeAsync(0) - coordinator.fenceAndCloseNow() - await expect(waiting).resolves.toEqual({ - ready: false, - reason: 'control_not_active', - retryAt: null - }) - }) - - function coldStartWithHungRetry(): RelayAuthCoordinator { - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503)) - .mockImplementationOnce(() => new Promise(() => {})) - return new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: () => {}, - random: () => 0.5 - }) - } - - it('returns at its deadline while the retry it followed is still opening', async () => { - vi.useFakeTimers() - const coordinator = coldStartWithHungRetry() - coordinator.reconcile() - let settled: unknown = null - void coordinator.waitForReadiness(10_000).then((readiness) => (settled = readiness)) - await vi.advanceTimersByTimeAsync(9_999) - expect(settled).toBeNull() - await vi.advanceTimersByTimeAsync(1) - expect(settled).toMatchObject({ ready: false, reason: 'director_assignment_503' }) - coordinator.stop() - }) - - it.each(['fence', 'stop'] as const)( - 'a %s releases a waiter whose followed retry is still opening', - async (action) => { - vi.useFakeTimers() - const coordinator = coldStartWithHungRetry() - coordinator.reconcile() - let settled: unknown = null - void coordinator.waitForReadiness(20_000).then((readiness) => (settled = readiness)) - await vi.advanceTimersByTimeAsync(1_000) - expect(settled).toBeNull() - if (action === 'fence') { - coordinator.fenceAndCloseNow() - } else { - coordinator.stop() - } - await vi.advanceTimersByTimeAsync(0) - expect(settled).toMatchObject({ ready: false, retryAt: null }) - coordinator.stop() - } - ) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts deleted file mode 100644 index 955701e1ae3..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator-recovery.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import { RelayHttpError } from './relay-http-client' - -const context: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-1', - relayEntitled: true -} - -afterEach(() => { - vi.useRealTimers() -}) - -describe('RelayAuthCoordinator transient recovery', () => { - it('does not carry a pending retry across an identity switch', async () => { - vi.useFakeTimers() - let current = context - const broker = { closeNow: vi.fn() } - const openBroker = vi - .fn() - .mockRejectedValueOnce(new Error('temporary control open failure')) - .mockResolvedValueOnce(broker) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => current, - openBroker, - onStatus: vi.fn(), - random: () => 0.75 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - current = { - ...context, - identity: { ...context.identity, profileId: 'profile-2' } - } - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - expect(coordinator.getActiveBroker()).toBe(broker) - await vi.advanceTimersByTimeAsync(120_000) - - expect(openBroker).toHaveBeenCalledTimes(2) - }) -}) - -describe('RelayAuthCoordinator liveness safety net', () => { - it('reopens a broker that died leaving no retry timer behind', async () => { - // Expired-token refresh failure leaves no retry; ensureLive must revive it. - vi.useFakeTimers() - const dead = { closeNow: vi.fn(), isLive: () => false } - const live = { closeNow: vi.fn(), isLive: () => true } - const openBroker = vi.fn().mockResolvedValueOnce(dead).mockResolvedValueOnce(live) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn(), - random: () => 0.5 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(coordinator.getActiveBroker()).toBe(dead) - await vi.advanceTimersByTimeAsync(600_000) - expect(openBroker).toHaveBeenCalledOnce() - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - expect(dead.closeNow).toHaveBeenCalled() - expect(coordinator.getActiveBroker()).toBe(live) - }) - - it('does not disturb a live broker, a scheduled retry, or an open in flight', async () => { - vi.useFakeTimers() - const broker = { closeNow: vi.fn(), isLive: () => true } - let releaseOpen: ((value: typeof broker) => void) | undefined - const openBroker = vi - .fn() - .mockRejectedValueOnce(new RelayHttpError('assignment', 503, 30_000)) - .mockImplementationOnce( - () => - new Promise((resolve) => { - releaseOpen = resolve - }) - ) - const coordinator = new RelayAuthCoordinator({ - readContext: async () => context, - openBroker, - onStatus: vi.fn(), - random: () => 0.5 - }) - - coordinator.reconcile() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledOnce() - - await vi.advanceTimersByTimeAsync(30_000) - expect(openBroker).toHaveBeenCalledTimes(2) - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - releaseOpen?.(broker) - await vi.advanceTimersByTimeAsync(0) - expect(coordinator.getActiveBroker()).toBe(broker) - - coordinator.ensureLive() - await vi.advanceTimersByTimeAsync(0) - expect(openBroker).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts deleted file mode 100644 index aa103136bdb..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-control-liveness.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { RelayControlLiveness } from './relay-control-liveness' - -describe('RelayControlLiveness keepalive', () => { - afterEach(() => { - vi.useRealTimers() - }) - - function liveness(live = { value: true }) { - const terminate = vi.fn() - // The relay's ack is an inbound frame. - const sendKeepalive = vi.fn((frame: string) => { - expect(frame).toBe('{"type":"keepalive"}') - instance.noteInbound() - }) - const instance: RelayControlLiveness = new RelayControlLiveness({ - cellUrl: 'https://relay.test', - ping: vi.fn(), - isLive: () => live.value, - terminate, - send: sendKeepalive - }) - return { instance, sendKeepalive, terminate, live } - } - - it('sends a keepalive instead of tearing down when its own timers were held back', () => { - vi.useFakeTimers() - const terminate = vi.fn() - const send = vi.fn() - const instance = new RelayControlLiveness({ - cellUrl: 'https://relay.test', - ping: vi.fn(), - isLive: () => true, - terminate, - send - }) - instance.start() - instance.startKeepalive(25_000) - // A throttled app: no timer ran for 100 s, then the silence check runs before the keepalive. - vi.setSystemTime(Date.now() + 100_000) - vi.advanceTimersToNextTimer() - expect(terminate).not.toHaveBeenCalled() - expect(send).toHaveBeenCalledWith('{"type":"keepalive"}') - // Still unanswered at a later check: the link is judged dead as before. - vi.advanceTimersByTime(80_000) - expect(terminate).toHaveBeenCalledOnce() - }) - - it('ignores an offer before the control is active and stops with the control', () => { - vi.useFakeTimers() - const { instance, sendKeepalive } = liveness() - instance.startKeepalive(25_000) - vi.advanceTimersByTime(50_000) - expect(sendKeepalive).not.toHaveBeenCalled() - instance.start() - instance.startKeepalive(25_000) - instance.stop() - vi.advanceTimersByTime(100_000) - expect(sendKeepalive).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts b/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts deleted file mode 100644 index cc2e7796f52..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-readiness-retention.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { sharedPromiseSettlementWaiters } from '../../../shared/promise-settlement-waiters' -import { RelayReadinessWaiters } from './relay-readiness' - -afterEach(() => vi.useRealTimers()) - -describe('relay readiness wait lifetime', () => { - it('detaches expired mint callers while shared reconnect work remains pending', async () => { - vi.useFakeTimers() - let finish = (): void => {} - const work = new Promise((resolve) => { - finish = resolve - }) - const observed = vi.spyOn(work, 'then') - const waiters = new RelayReadinessWaiters() - const anchor = waiters.until(work, Date.now() + 10_000) - for (let index = 0; index < 100; index += 1) { - const waiting = waiters.until(work, Date.now() + 1) - await vi.advanceTimersByTimeAsync(1) - await expect(waiting).resolves.toBe(false) - } - expect(observed).toHaveBeenCalledOnce() - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(1) - finish() - await expect(anchor).resolves.toBe(true) - expect(vi.getTimerCount()).toBe(0) - }) - - it('releases callers without cancelling shared work and permits a later wait', async () => { - vi.useFakeTimers() - let finish = (): void => {} - const work = new Promise((resolve) => { - finish = resolve - }) - const waiters = new RelayReadinessWaiters() - const first = waiters.until(work, Date.now() + 10_000) - waiters.releaseAll() - await expect(first).resolves.toBe(false) - expect(sharedPromiseSettlementWaiters(work).waiterCount).toBe(0) - const next = waiters.until(work, Date.now() + 10_000) - finish() - await expect(next).resolves.toBe(true) - expect(vi.getTimerCount()).toBe(0) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts b/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts deleted file mode 100644 index 2d9387c773a..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-region-refresh.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { RelayAssignment } from './relay-http-client' -import type * as RelayHttpClientModule from './relay-http-client' -import type { RelayRegionWindow } from './relay-region-correction-protocol' -const fake = vi.hoisted(() => ({ assign: vi.fn() })) -vi.mock('./relay-http-client', async (original) => ({ - ...(await original()), - requestRelayAssignment: fake.assign -})) -import { RelayRegionRefresh } from './relay-region-refresh' -const HOUR = 60 * 60_000 -const window: RelayRegionWindow = { - generation: 1, - assignmentEpoch: 1, - incumbentRegion: 'asia-east2', - expiresAt: 24 * HOUR, - policyVersion: 1 -} -const assignment: RelayAssignment = { - v: 1, - cellUrl: 'https://source.example.test', - assignmentEpoch: 1, - lease: 'test', - regionCorrection: { v: 1, window } -} -let scheduler: RelayRegionRefresh -function setup(random = 0.5) { - const measure = vi.fn().mockResolvedValue({ - outcome: 'conclusive', - measurements: { 'us-central1': 30, 'asia-east2': 200 } - }) - const applyAssignment = vi.fn(() => true) - const isOnline = vi.fn(() => true) - scheduler = new RelayRegionRefresh({ - directorUrl: 'https://director.example.test', - relayHostId: 'test-host', - token: () => 'test-token', - assignment: () => assignment, - isCurrent: () => true, - isOnline, - applyAssignment, - measure, - random: () => random, - now: () => Date.now() - }) - return { measure, applyAssignment, isOnline } -} -describe('broker-owned region decision refresh', () => { - beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(0) - fake.assign.mockReset() - }) - afterEach(() => { - scheduler?.close() - vi.useRealTimers() - }) - - it('retries exactly the same report without probing or extending its window', async () => { - const { measure } = setup() - fake.assign - .mockRejectedValueOnce(new Error('offline')) - .mockResolvedValue({ ...assignment, regionCorrection: { v: 1, reportStatus: 'accepted' } }) - scheduler.start(assignment) - await vi.advanceTimersByTimeAsync(60_000) - expect(measure).toHaveBeenCalledOnce() - expect(fake.assign).toHaveBeenCalledTimes(2) - expect(fake.assign.mock.calls[0]![0].regionCorrection).toEqual( - fake.assign.mock.calls[1]![0].regionCorrection - ) - }) - - it('does not report a measurement that completed after broker close', async () => { - const { measure } = setup() - let resolve!: (value: unknown) => void - measure.mockReturnValue( - new Promise((done) => { - resolve = done - }) - ) - scheduler.start(assignment) - scheduler.close() - resolve({ outcome: 'inconclusive', reason: 'incomplete-measurement' }) - await vi.advanceTimersByTimeAsync(0) - expect(fake.assign).not.toHaveBeenCalled() - }) - it('uses a successor window after an expired report retry', async () => { - setup() - fake.assign.mockRejectedValueOnce(new Error('offline')).mockResolvedValue({ - ...assignment, - regionCorrection: { v: 1, window: { ...window, generation: 2, expiresAt: 48 * HOUR } } - }) - scheduler.start(assignment) - await vi.advanceTimersByTimeAsync(0) - vi.setSystemTime(25 * HOUR) - await vi.advanceTimersByTimeAsync(60_000) - expect(fake.assign.mock.calls[1]![0].regionCorrection).toEqual({ v: 1, action: 'issue-window' }) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts b/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts deleted file mode 100644 index 5784b632239..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as SecureFileModule from '../../../shared/secure-storage/secure-file' -import { RelayRevokeOutbox } from './relay-revoke-outbox' - -const secureFileMocks = vi.hoisted(() => ({ failWrites: false })) - -vi.mock('../../../shared/secure-storage/secure-file', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeSecureJsonFile: (targetPath: string, value: unknown) => { - if (secureFileMocks.failWrites) { - throw new Error('disk full') - } - actual.writeSecureJsonFile(targetPath, value) - } - } -}) - -describe('RelayRevokeOutbox', () => { - const paths: string[] = [] - afterEach(() => { - secureFileMocks.failWrites = false - for (const path of paths.splice(0)) { - rmSync(path, { recursive: true, force: true }) - } - }) - - it('durably retains an idempotent account-scoped revoke after local deletion', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const first = new RelayRevokeOutbox(path).enqueue(binding) - const reloaded = new RelayRevokeOutbox(path) - expect(reloaded.enqueue(binding).reqId).toBe(first.reqId) - expect(reloaded.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([first]) - reloaded.remove(first.reqId) - expect( - new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) - ).toEqual([]) - }) - - it('does not retain an enqueue that failed to reach disk', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const outbox = new RelayRevokeOutbox(path) - secureFileMocks.failWrites = true - expect(() => outbox.enqueue(binding)).toThrow('disk full') - - secureFileMocks.failWrites = false - const persisted = outbox.enqueue(binding) - expect( - new RelayRevokeOutbox(path).pendingFor(binding.ownerIdentityKey, binding.relayHostId) - ).toEqual([persisted]) - }) - - it('does not remove an item in memory when the durable removal fails', () => { - const path = mkdtempSync(join(tmpdir(), 'orca-relay-revoke-')) - paths.push(path) - const binding = { - relayHostId: 'AbCdEf0123_-xyZ9', - relayDeviceId: 'device-1', - ownerIdentityKey: 'user-1\0profile-1\0org-1' - } - const outbox = new RelayRevokeOutbox(path) - const item = outbox.enqueue(binding) - secureFileMocks.failWrites = true - expect(() => outbox.remove(item.reqId)).toThrow('disk full') - - secureFileMocks.failWrites = false - expect(outbox.pendingFor(binding.ownerIdentityKey, binding.relayHostId)).toEqual([item]) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts b/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts deleted file mode 100644 index a5461458549..00000000000 --- a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayWallClockTimer } from './relay-wall-clock-timer' - -function resumeSource(): { - subscribe: (onResume: () => void) => () => void - resume: () => void - count: () => number -} { - const listeners = new Set<() => void>() - return { - subscribe: (onResume) => { - listeners.add(onResume) - onResume() - return () => listeners.delete(onResume) - }, - resume: () => { - for (const listener of Array.from(listeners)) { - listener() - } - }, - count: () => listeners.size - } -} - -describe('RelayWallClockTimer', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('runs a task that fell due during a sleep as soon as the machine resumes', () => { - vi.useFakeTimers() - let wall = 1_000_000 - const source = resumeSource() - const timer = new RelayWallClockTimer(() => wall, source.subscribe) - const task = vi.fn() - timer.schedule(180_000, task) - // Asleep: the wall clock moves, the timer clock does not. - wall += 200_000 - source.resume() - expect(task).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(180_000) - expect(task).toHaveBeenCalledTimes(1) - expect(source.count()).toBe(0) - }) -}) diff --git a/src/main/runtime/mobile-cloud-relay/relay-renewal-jitter.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-renewal-jitter.ts similarity index 100% rename from src/main/runtime/mobile-cloud-relay/relay-renewal-jitter.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-renewal-jitter.ts diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts similarity index 66% rename from src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts index 6d7932e5cd3..c64035b95e5 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker-contract.ts @@ -1,11 +1,14 @@ import type WebSocket from 'ws' -import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' -import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { RelayRegion } from './relay-region-probe' -import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' +import type { OrcaCloudAuthConfig } from '../../../orca-profiles/cloud-auth/profile-cloud-auth-config' +import type { MobileRelayStatusPublisher } from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { E2EEKeypair } from '../../rpc/server/pairing/e2ee-keypair' +import type { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { RelayRegion } from '../region-selection/relay-region-probe' +import type { + RelayRegionDecision, + RelayRegionWindow +} from '../region-selection/relay-region-correction-protocol' export type RelayIdentity = { userId: string diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts similarity index 93% rename from src/main/runtime/mobile-cloud-relay/relay-session-broker.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts index d7be7f45381..c4ae1d3a7e9 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker.ts +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-session-broker.ts @@ -3,21 +3,21 @@ import type { RelaySessionBrokerOptions } from './relay-session-broker-contract' import { relayStatusCellUrl, type MobileRelayStatus as RelayBrokerStatus -} from '../../../shared/remote-runtime/relay/mobile-relay-status' -import type { PairingRelay } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import type * as RelayCredentials from '../../../shared/remote-runtime/relay/mobile-relay-credential-contract' -import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { DeviceCredentialInstallAuthorization } from './relay-control-requests' +} from '../../../../shared/remote-runtime/relay/mobile-relay-status' +import type { PairingRelay } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type * as RelayCredentials from '../../../../shared/remote-runtime/relay/mobile-relay-credential-contract' +import type { RelayHostCloseReason } from '../../../../shared/relay-host-close-reason' +import type { DeviceCredentialInstallAuthorization } from '../control-channel/relay-control-requests' import { deriveRelayHostId, exchangeRelayAuthorization, requestRelayAssignment, type RelayAuthorization, type RelayAssignment -} from './relay-http-client' -import { relayIdentityKey } from './relay-auth-identity' -import { RelayOriginPool } from './relay-origin-pool' -import { RelayRegionRefresh } from './relay-region-refresh' +} from '../director/relay-http-client' +import { relayIdentityKey } from '../authentication/relay-auth-identity' +import { RelayOriginPool } from '../origin-lifecycle/relay-origin-pool' +import { RelayRegionRefresh } from '../region-selection/relay-region-refresh' import { relayRenewalDelayMs } from './relay-renewal-jitter' import { RelayWallClockTimer } from './relay-wall-clock-timer' diff --git a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts similarity index 95% rename from src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts rename to src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts index da84d170f86..c04c38765e6 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-wall-clock-timer.ts +++ b/src/main/runtime/mobile-cloud-relay/session-lifecycle/relay-wall-clock-timer.ts @@ -1,4 +1,4 @@ -import { subscribeSystemPowerLifecycle } from '../../power/system-power-lifecycle' +import { subscribeSystemPowerLifecycle } from '../../../power/system-power-lifecycle' type SubscribeResume = (onResume: () => void) => () => void diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts b/src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts similarity index 67% rename from src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts rename to src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts index e25df17f42e..11af3b19dff 100644 --- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service-installer.test.ts +++ b/src/main/runtime/mobile-cloud-relay/testing/desktop-relay-service-installer.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import type { DesktopRelayService } from './desktop-relay-service' -import { createDesktopRelayServiceInstaller } from './desktop-relay-service-installer' +import type { DesktopRelayService } from '../desktop-relay-service' +import { createDesktopRelayServiceInstaller } from '../desktop-relay-service-installer' function fakeService(): DesktopRelayService { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installer only calls start() and wraps the provider methods. @@ -25,21 +25,6 @@ function installerWith(overrides: { } describe('createDesktopRelayServiceInstaller', () => { - it('holds the first install until the network is ready and shares one in-flight install', async () => { - let ready!: () => void - const whenNetworkReady = new Promise((resolve) => (ready = resolve)) - const create = vi.fn(() => fakeService()) - const { installer } = installerWith({ create, whenNetworkReady }) - - const first = installer.ensure() - const second = installer.ensure() - await Promise.resolve() - expect(create).not.toHaveBeenCalled() - ready() - await expect(Promise.all([first, second])).resolves.toEqual([true, true]) - expect(create).toHaveBeenCalledOnce() - }) - it('refuses installs after sign-out, including one already waiting, until the next auth change', async () => { let ready!: () => void const whenNetworkReady = new Promise((resolve) => (ready = resolve)) diff --git a/src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts b/src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts similarity index 96% rename from src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts rename to src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts index bc0d3b812ed..b0215561891 100644 --- a/src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts +++ b/src/main/runtime/mobile-cloud-relay/testing/mobile-relay-e2ee.integration.test.ts @@ -4,10 +4,10 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import nacl from 'tweetnacl' import WebSocketClient, { WebSocketServer, type RawData, type WebSocket } from 'ws' -import { DeviceRegistry } from '../rpc/server/pairing/device-registry' -import { MobileSocketWiring } from '../rpc/mobile/mobile-socket-wiring' -import { CloudRelayTransport } from '../rpc/transports/relay-transport' -import { deriveRelayHostId } from './relay-http-client' +import { DeviceRegistry } from '../../rpc/server/pairing/device-registry' +import { MobileSocketWiring } from '../../rpc/mobile/mobile-socket-wiring' +import { CloudRelayTransport } from '../../rpc/transports/relay-transport' +import { deriveRelayHostId } from '../director/relay-http-client' import { SimulatedMobileE2EEV2Peer } from './simulated-mobile-e2ee-v2-peer' function deferred() { diff --git a/src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts b/src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts similarity index 90% rename from src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts rename to src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts index e4fd1d59291..acc3d389f44 100644 --- a/src/main/runtime/mobile-cloud-relay/simulated-mobile-e2ee-v2-peer.ts +++ b/src/main/runtime/mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer.ts @@ -4,13 +4,13 @@ import { validateMobileE2EEV2Handshake, type MobileE2EEPayloadKind, type MobileE2EEV2Hello -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' +} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-contract' import { openMobileE2EEV2Frame, sealMobileE2EEV2Frame -} from '../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' -import { deriveSharedKey } from '../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { deriveMobileE2EEV2KeySchedule } from '../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' +} from '../../../../shared/remote-runtime/e2ee/mobile-e2ee-v2-framing' +import { deriveSharedKey } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' +import { deriveMobileE2EEV2KeySchedule } from '../../../../shared/remote-runtime/e2ee/node/mobile-e2ee-v2-node-key-schedule' // Independent mobile wire peer for desktop tests, avoiding Expo imports. export class SimulatedMobileE2EEV2Peer { diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts index 13ea9a0884b..6769e9ab3d2 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-layout-owner-start-fixture.ts @@ -3,7 +3,7 @@ import { vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../shared/constants' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' import { withDurableRuntimeStore, withRuntimePaneAdmission } from './runtime-durable-store-fixture' import { OrcaRuntimeService } from '../orca-runtime' diff --git a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts index 0a06d23d348..94cacf7a6ab 100644 --- a/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts +++ b/src/main/runtime/orca-runtime-tests/orca-runtime-test-fixtures.spec.ts @@ -16,7 +16,7 @@ import { import { getDefaultWorkspaceSession } from '../../../shared/constants' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' import { toComparableRelaySshPtyId } from '../../../shared/ssh-pty-id' import '../terminal/launch/spawned-pty-env-fixtures' 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/runtime-durable-store-fixture.ts b/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts index 3b1fe262b57..82f00edb76e 100644 --- a/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/runtime-durable-store-fixture.ts @@ -6,7 +6,7 @@ import { withdrawPaneFromSession, type PaneLayoutChange, type TerminalPaneAdmission -} from '../../persistence/terminal-topology/terminal-pane-admission' +} from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { CommandOf, LayoutRefusalCode diff --git a/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts b/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts index 3aec8eb3e3c..35af315e20c 100644 --- a/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts +++ b/src/main/runtime/orca-runtime-tests/session-layout-apply.test-fixture.ts @@ -1,7 +1,7 @@ // Apply layout record patches to plain session maps as Store does, including main-owned chat tabs. import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { LayoutCommand } from '../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../persistence/loading-store/workspace-sessions/session-host-partitions' export function layoutApplyOn( 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/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts index e52a2845e81..5faea46c987 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-mail-custody.test.ts @@ -2,6 +2,8 @@ // its mailbox, and that mailbox still this chat's. The queue asks at handover; cleanup is visible only. import { describe, expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' +import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' import { structuredAgentSessionMessageSendMutation } from '../../../../../shared/agent-session/requests/structured-agent-session-send-mutation' import { formatOrcaSessionAddress } from '../../../../../shared/orca-session-address' import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' @@ -26,9 +28,19 @@ import { turnText } from './structured-chat-coordinator-mail-rig.test-fixture' -/** A chat with a turn running, so mail waits as cards behind it. */ -async function busyChat(sessionId: string) { +/** A running turn, optionally with its first handover still unanswered. */ +async function busyChat(sessionId: string, startReply?: Promise) { const chat = await openChat(sessionId) + if (startReply) { + const request = chat.request + chat.request = async (...args) => { + const response = await request(...args) + if (args[0] === 'turn/start') { + await startReply + } + return response + } + } expect(await sendUserMessage(sessionId, 'go')).toMatchObject({ ok: true }) await vi.waitFor(() => expect(chat.turns).toHaveLength(1), WAIT) chat.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) @@ -36,6 +48,10 @@ async function busyChat(sessionId: string) { return chat } +function journalOf(sessionId: string): AgentSessionJournal { + return host.collaboratorsForTests().sessions.get(sessionId)!.journal +} + /** Queue a card behind the running turn: the person's own, or another agent's with `from`. */ async function queueCard(text: string, from?: AgentMessageSource): Promise { const mutation = structuredAgentSessionMessageSendMutation({ @@ -129,30 +145,37 @@ describe('a queued mail card runs only while its chat still owes it', () => { }) it("lets the person's cards pass mail it cannot decide on now, then hands the mail over first once it can", async () => { - const chat = await busyChat(COORDINATOR) - const { taskId } = await coordinatorRunAndTask() - await finishWorker(taskId) - await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) - await queueCard('first question of mine') - await queueCard('second question of mine') - const unreadable = vi.spyOn(db, 'areUnreadMessages').mockImplementation(() => { - throw new Error('database unavailable') - }) - await settleTurn(COORDINATOR, 0) - await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) - // The person's first card went, in their order; the report and their second card still wait. - expect(turnText(chat.turns[1]!)).toContain('first question of mine') - const waiting = await queuedCardTexts() - expect(waiting).toHaveLength(2) - expect(waiting[0]).toContain('(worker_done)') - unreadable.mockRestore() - await settleTurn(COORDINATOR, 1) - // Readable again: the older report goes before the person's later card. - await vi.waitFor(() => expect(chat.turns).toHaveLength(3), WAIT) - expect(isWholeMail(turnText(chat.turns[2]!))).toBe(true) - await settleTurn(COORDINATOR, 2) - await vi.waitFor(() => expect(chat.turns).toHaveLength(4), WAIT) - expect(turnText(chat.turns[3]!)).toContain('second question of mine') + const reply = Promise.withResolvers() + try { + const chat = await busyChat(COORDINATOR, reply.promise) + const { taskId } = await coordinatorRunAndTask() + await finishWorker(taskId) + await vi.waitFor(async () => expect(await queuedCardTexts()).toHaveLength(1), WAIT) + await queueCard('first question of mine') + await queueCard('second question of mine') + const unreadable = vi.spyOn(db, 'areUnreadMessages').mockImplementation(() => { + throw new Error('database unavailable') + }) + expect(chat.steers).toEqual([]) + reply.resolve() + await settleTurn(COORDINATOR, 0) + await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) + // The person's first card went, in their order; the report and their second card still wait. + expect(turnText(chat.turns[1]!)).toContain('first question of mine') + const waiting = await queuedCardTexts() + expect(waiting).toHaveLength(2) + expect(waiting[0]).toContain('(worker_done)') + unreadable.mockRestore() + await settleTurn(COORDINATOR, 1) + // Readable again: the older report goes before the person's later card. + await vi.waitFor(() => expect(chat.turns).toHaveLength(3), WAIT) + expect(isWholeMail(turnText(chat.turns[2]!))).toBe(true) + await settleTurn(COORDINATOR, 2) + await vi.waitFor(() => expect(chat.turns).toHaveLength(4), WAIT) + expect(turnText(chat.turns[3]!)).toContain('second question of mine') + } finally { + reply.resolve() + } }) it('hands a Task over without opening the mail database', async () => { @@ -197,4 +220,71 @@ describe('a queued mail card runs only while its chat still owes it', () => { expect(db.getUnreadMessages(`run:${runId}`)).toMatchObject([{ read: 0, delivered_at: null }]) await vi.waitFor(() => expect(selectable).toContain(1), WAIT) }) + + it('sends a report refused for queue room once the queue frees room', async () => { + const reply = Promise.withResolvers() + try { + const chat = await busyChat(COORDINATOR, reply.promise) + const { runId, taskId } = await coordinatorRunAndTask() + // The person's queue holds almost all the room an agent's message may use. + for (let card = 0; card < 4; card += 1) { + const mutation = structuredAgentSessionMessageSendMutation({ + sessionId: COORDINATOR, + clientOperationId: operationId(), + expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, + body: { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'x'.repeat(240_000) }] + }, + delivery: 'queue-if-active' + }) + expect( + await host.send({ callerKey: 'test-surface' }, { ...mutation, userSend: true }) + ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) + } + const send = vi.spyOn(host, 'send') + await finishWorker(taskId) + await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1), WAIT) + // The refusal releases the reservation made before the send. + await vi.waitFor( + () => expect(db.getUnreadMessages(`run:${runId}`)).toMatchObject([{ delivered_at: null }]), + WAIT + ) + // Deleting the person's cards frees room: that journal edge alone sends the report. + for (const card of journalOf(COORDINATOR).queuedMessages.list()) { + const fields = { messageId: card.messageId } + expect( + await host.queuedMessageDelete( + { callerKey: 'test-surface' }, + { + envelope: { + sessionId: COORDINATOR, + clientOperationId: operationId(), + expectedRuntimeFence: host.deps.store.getConversation(COORDINATOR)!.currentFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.queuedMessageDelete', + sessionId: COORDINATOR, + fields + }) + }, + ...fields + } + ) + ).toMatchObject({ ok: true }) + } + await vi.waitFor(async () => { + const cards = await queuedCardTexts() + expect(cards).toHaveLength(1) + expect(cards[0]).toContain('(worker_done)') + }, WAIT) + expect(chat.steers).toEqual([]) + reply.resolve() + await settleTurn(COORDINATOR, 0) + await vi.waitFor(() => expect(chat.turns).toHaveLength(2), WAIT) + expect(isWholeMail(turnText(chat.turns[1]!))).toBe(true) + } finally { + reply.resolve() + } + }) }) diff --git a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts index ec1cb24120d..b3ed3286fc3 100644 --- a/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts @@ -306,44 +306,59 @@ describe('a send to a finished structured worker', () => { const { taskId } = await coordinatorRunAndTask() const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') const worker = connectionFor(identity.sessionId) - expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) - worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) - await host.flushStreamedEvents(identity.sessionId) - await sendTo(firstDispatchId, 'and the docs') - // The mail waits as a card behind the running turn; the worker reports before it is handed over. - await vi.waitFor( - async () => expect(await queuedCardTexts(identity.sessionId)).toHaveLength(1), - WAIT - ) + const reply = Promise.withResolvers() + const request = worker.request + worker.request = async (...args) => { + const response = await request(...args) + if (args[0] === 'turn/start') { + await reply.promise + } + return response + } + try { + expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await sendTo(firstDispatchId, 'and the docs') + // The mail waits as a card behind the running turn; the worker reports before it is handed over. + await vi.waitFor( + async () => expect(await queuedCardTexts(identity.sessionId)).toHaveLength(1), + WAIT + ) + expect(worker.steers).toEqual([]) - expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ - ok: true - }) - // The follow-up took the mail: the old card is gone, its Task waits first, then the mail itself. - await vi.waitFor(async () => { - const cards = await queuedCardTexts(identity.sessionId) - expect(cards).toHaveLength(2) - expect(cards[0]).toContain('arrive next, one at a time') - expect(isWholeMail(cards[1]!)).toBe(true) - expect(cards[1]).toContain('and the docs') - }, WAIT) - expect((await queuedCardTexts(identity.sessionId)).join('\n')).not.toContain('`check`') - worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) - await host.flushStreamedEvents(identity.sessionId) - await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) - expect(turnText(worker.turns[1]!)).toContain('arrive next, one at a time') - await settleTurn(identity.sessionId, 1) - await vi.waitFor(() => expect(worker.turns).toHaveLength(3), WAIT) - expect(isWholeMail(turnText(worker.turns[2]!))).toBe(true) - expect(turnText(worker.turns[2]!)).toContain('and the docs') - await settleTurn(identity.sessionId, 2) + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + // The follow-up took the mail: the old card is gone, its Task waits first, then the mail itself. + await vi.waitFor(async () => { + const cards = await queuedCardTexts(identity.sessionId) + expect(cards).toHaveLength(2) + expect(cards[0]).toContain('arrive next, one at a time') + expect(isWholeMail(cards[1]!)).toBe(true) + expect(cards[1]).toContain('and the docs') + }, WAIT) + expect((await queuedCardTexts(identity.sessionId)).join('\n')).not.toContain('`check`') + reply.resolve() + worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) + expect(turnText(worker.turns[1]!)).toContain('arrive next, one at a time') + await settleTurn(identity.sessionId, 1) + await vi.waitFor(() => expect(worker.turns).toHaveLength(3), WAIT) + expect(isWholeMail(turnText(worker.turns[2]!))).toBe(true) + expect(turnText(worker.turns[2]!)).toContain('and the docs') + await settleTurn(identity.sessionId, 2) - const followUp = getFollowUpDispatch(db, firstDispatchId)! - await vi.waitFor( - () => expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toEqual([]), - WAIT - ) - expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toEqual([]) + const followUp = getFollowUpDispatch(db, firstDispatchId)! + await vi.waitFor( + () => expect(db.getUnreadMessages(`dispatch:${followUp.id}`)).toEqual([]), + WAIT + ) + expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toEqual([]) + } finally { + reply.resolve() + } }) }) diff --git a/src/main/runtime/push/push-gateway-session.ts b/src/main/runtime/push/push-gateway-session.ts index b062002032b..26ba19c1bd8 100644 --- a/src/main/runtime/push/push-gateway-session.ts +++ b/src/main/runtime/push/push-gateway-session.ts @@ -1,7 +1,7 @@ import { z } from 'zod' import { cancelUnreadResponseBody } from '../../lib/unread-response-body' import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' -import { deriveRelayHostId } from '../mobile-cloud-relay/relay-http-client' +import { deriveRelayHostId } from '../mobile-cloud-relay/director/relay-http-client' import { answerPushHostChallenge } from './push-host-proof' import { postPushGatewayJson, diff --git a/src/main/runtime/repositories/runtime-repository-ref-queries.ts b/src/main/runtime/repositories/runtime-repository-ref-queries.ts index c47baeb4fc8..c5151d72932 100644 --- a/src/main/runtime/repositories/runtime-repository-ref-queries.ts +++ b/src/main/runtime/repositories/runtime-repository-ref-queries.ts @@ -40,7 +40,7 @@ export class RuntimeRepositoryRefQueries { if (getRepoRoutingConnectionId(repo)) { throw new Error('This project is not served by this host.') } - const page = await searchRemoteRefPage(repo.path, query, effectiveLimit) + const page = await searchRemoteRefPage(repo.path, query, effectiveLimit, includeQualifiedRefs) return { ...page, refs: page.refDetails.map((row) => row.refName), namespace } } // Unserved SSH hosts report no refs; never search local files for them. 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/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/mobile/device-key-auth.test.ts b/src/main/runtime/rpc/mobile/device-key-auth.test.ts index fa76cfce221..d032522bc0c 100644 --- a/src/main/runtime/rpc/mobile/device-key-auth.test.ts +++ b/src/main/runtime/rpc/mobile/device-key-auth.test.ts @@ -10,7 +10,7 @@ import { } from '../../../../shared/remote-runtime/pairing/device-key-proof' import { DeviceRegistry } from '../server/pairing/device-registry' import { DEVICE_REGISTRY_FILENAME } from '../server/pairing/mobile-pairing-files' -import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' +import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/testing/simulated-mobile-e2ee-v2-peer' import { registerSocketDeviceKey } from '../server/runtime-rpc-device-key-registration' import { generateKeyPair } from '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' import { diff --git a/src/main/runtime/rpc/server/pairing/device-entry.ts b/src/main/runtime/rpc/server/pairing/device-entry.ts index efdde1adba4..00a1efdaa36 100644 --- a/src/main/runtime/rpc/server/pairing/device-entry.ts +++ b/src/main/runtime/rpc/server/pairing/device-entry.ts @@ -2,7 +2,7 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contract import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import type { MobilePushRegistration } from '../../../../../shared/mobile-push-contract' import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { RuntimeDeviceGrant } from '../../callers/rpc-method-permission' import type { NetworkSourceClass } from '../../transports/websocket/source-admission/network-source-class' diff --git a/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts b/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts index f6070faaccb..c076dd99cfc 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry-row-validation.ts @@ -1,5 +1,5 @@ import type { DeviceScope } from '../../../../../shared/runtime-session-contracts' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { DeviceEntry } from './device-entry' import { parseMobilePushRegistration } from '../../../../../shared/mobile-push-contract' import { isDevicePublicKeyB64 } from '../../../../../shared/remote-runtime/pairing/device-key-proof' diff --git a/src/main/runtime/rpc/server/pairing/device-registry.ts b/src/main/runtime/rpc/server/pairing/device-registry.ts index 41483df775d..84904c7c0a7 100644 --- a/src/main/runtime/rpc/server/pairing/device-registry.ts +++ b/src/main/runtime/rpc/server/pairing/device-registry.ts @@ -10,7 +10,7 @@ import { } from './pairing-ticket-exchange' import { planIdleEphemeralPrune } from './ephemeral-device-rows' import { DeviceRegistrySightings } from './device-registry-sightings' -import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/relay-revoke-outbox' +import type { RelayDeviceBinding } from '../../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { MobilePairingConnectionMode } from '../../../../../shared/remote-runtime/pairing/mobile-pairing-connection-mode' import type { RuntimePairingReach } from '../../../../../shared/runtime-pairing-reach' import type { DelegatedPhone } from '../../../../../shared/delegated-mobile-device-contract' diff --git a/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts b/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts index f4dbfce7108..0a500107afb 100644 --- a/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts +++ b/src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts @@ -1,7 +1,7 @@ import { mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync, type Stats } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { loadWindowsSecurity, type WindowsSecurity @@ -131,54 +131,9 @@ describeOnWindows('a secure store that exists but cannot be read', () => { expectUntouched(filePath, locked) }) - it('does not blank the plugin secret vault on write', async () => { - vi.doMock('electron', () => ({ - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (value: string) => Buffer.from(`enc:${value}`), - decryptString: (buffer: Buffer) => buffer.toString().replace(/^enc:/, '') - } - })) - const { PluginSecretsStore } = await import('../../../../plugins/plugin-secrets-store') - const dir = join(root, 'plugin-secrets') - mkdirSync(dir, { recursive: true }) - const store = new PluginSecretsStore(dir, 'publisher.plugin') - // Reach the path the store computes rather than restating its layout here. - const filePath = (store as unknown as { filePath: string }).filePath - mkdirSync(join(filePath, '..'), { recursive: true }) - const original = JSON.stringify({ - version: 1, - format: 'electron-safe-storage-v1', - ciphertexts: { existing: Buffer.from('enc:keep-me').toString('base64') } - }) - writeFileSync(filePath, original) - const locked = makeUnreadable(filePath) - - expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) }) - store.delete('existing') - - expectUntouched(filePath, locked) - vi.doUnmock('electron') - }) - it('does not blank the plugin KV store on write', async () => { - const { PluginKvStore } = await import('../../../../plugins/plugin-storage-store') - const dir = join(root, 'plugin-kv') - mkdirSync(dir, { recursive: true }) - const store = new PluginKvStore(dir, 'publisher.plugin', 'storage.json') - const filePath = (store as unknown as { filePath: string }).filePath - mkdirSync(join(filePath, '..'), { recursive: true }) - const original = JSON.stringify({ keep: 'me' }) - writeFileSync(filePath, original) - const locked = makeUnreadable(filePath) - - expect(store.set('added', 'value')).toEqual({ ok: false, error: expect.any(String) }) - store.delete('keep') - - expectUntouched(filePath, locked) - }) - it('does not drop pending relay revocations', async () => { - const { RelayRevokeOutbox } = await import('../../../mobile-cloud-relay/relay-revoke-outbox') + const { RelayRevokeOutbox } = + await import('../../../mobile-cloud-relay/pairing/relay-revoke-outbox') const dir = join(root, 'relay') mkdirSync(dir, { recursive: true }) const filePath = join(dir, 'mobile-relay-revoke-outbox.json') diff --git a/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts b/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts deleted file mode 100644 index 3e4790f5d71..00000000000 --- a/src/main/runtime/rpc/server/runtime-rpc-device-revocation.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import type * as WorktreeScanCacheModule from '../../../git/worktrees/catalog/worktree-scan-cache' -import type * as WorktreeListingModule from '../../../git/worktrees/catalog/worktree-listing' -import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import { encodeDeviceProofMessage } from '../../../../shared/remote-runtime/pairing/device-key-proof' -import { SimulatedMobileE2EEV2Peer } from '../../mobile-cloud-relay/simulated-mobile-e2ee-v2-peer' -import { OrcaRuntimeService } from '../../orca-runtime' -import { DeviceRegistry } from './pairing/device-registry' -import { DEVICE_REGISTRY_FILENAME } from './pairing/mobile-pairing-files' -import { makeStore } from './runtime-rpc-worktree-store-fixtures' -import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' -import { - TerminalStreamOpcode, - encodeTerminalStreamFrame, - encodeTerminalStreamText -} from '../../../../shared/terminal/stream/terminal-stream-protocol' -import { OrcaRuntimeRpcServer } from './runtime-rpc' -import { - encodePairingOffer, - parsePairingCode -} from '../../../../shared/remote-runtime/pairing/pairing' -import type { PairingOffer } from '../../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import '../../../../shared/remote-runtime/e2ee/node/e2ee-crypto' -import { waitFor } from './runtime-rpc-test-harness' -import { - connectWs, - nextWsMessage, - waitForWsClose, - authenticateMobileWs -} from './runtime-rpc-mobile-ws-test-harness' - -vi.mock('../../../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktrees: listings.listWorktrees - } -}) - -vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal) => { - const listings = getWorktreeListingMocks() - return { - ...(await importOriginal()), - listWorktreesStrict: listings.listWorktreesStrict - } -}) - -const { getWorktreeListingMocks } = vi.hoisted(() => { - function createWorktreeListingMocks() { - const worktrees = [ - { - path: '/tmp/worktree-a', - head: 'abc', - branch: 'feature/foo', - isBare: false, - isMainWorktree: false - } - ] - return { - listWorktrees: vi.fn().mockResolvedValue(worktrees), - listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) - } - } - let listings: ReturnType | undefined - return { getWorktreeListingMocks: () => (listings ??= createWorktreeListingMocks()) } -}) - -async function authenticateKeyedWs(offer: PairingOffer, deviceId: string, key: nacl.SignKeyPair) { - const ws = await connectWs(offer.endpoint) - const peer = new SimulatedMobileE2EEV2Peer( - nacl.box.keyPair(), - Uint8Array.from(Buffer.from(offer.publicKeyB64, 'base64')), - null - ) - ws.send(JSON.stringify(peer.hello)) - expect(peer.acceptReady(JSON.parse(await nextWsMessage(ws)))).toBe(true) - const transcriptHashB64 = peer.transcriptHashB64 - const proof = nacl.sign.detached( - encodeDeviceProofMessage('auth', Buffer.from(transcriptHashB64, 'base64')), - key.secretKey - ) - ws.send( - peer.sealText( - JSON.stringify({ - type: 'e2ee_auth', - v: 2, - transcriptHashB64, - deviceId, - deviceProofB64: Buffer.from(proof).toString('base64') - }) - ) - ) - expect(JSON.parse(peer.openText(await nextWsMessage(ws))!)).toMatchObject({ - type: 'e2ee_authenticated' - }) - return { ws, peer } -} - -describe('OrcaRuntimeRpcServer', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it.each([ - ['mobile', false], - ['runtime', false], - ['mobile', true] - ] as const)( - 'revoking a %s bearer, removed on disk %s, removes descendants and closes their sockets', - async (scope, removedOnDisk) => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-revoke-')) - const server = new OrcaRuntimeRpcServer({ - runtime: new OrcaRuntimeService(), - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - await server.start() - try { - const offer = server.createPairingOffer({ address: '127.0.0.1', name: 'Parent', scope }) - if (!offer.available) { - throw new Error('WebSocket pairing unavailable') - } - const parsed = parsePairingCode(offer.pairingUrl)! - const parentSocket = await authenticateMobileWs(offer.pairingUrl) - const registry = server.getDeviceRegistry()! - const key = nacl.sign.keyPair() - const fork = registry.forkDeviceKey( - offer.deviceId, - Buffer.from(key.publicKey).toString('base64'), - 'Fork' - ) - const idleFork = registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 9).toString('base64'), - 'Offline fork' - ) - const { ws: forkSocket } = await authenticateKeyedWs(parsed, fork.deviceId, key) - const children = - scope === 'runtime' - ? registry.upsertDelegatedMobileDevices(fork, [{ phoneKey: 'p', name: 'Pixel' }]) - : [] - const sockets = [parentSocket, forkSocket] - for (const child of children) { - sockets.push( - await authenticateMobileWs( - encodePairingOffer({ - ...parsed, - deviceToken: child.token, - pairedDeviceId: child.deviceId, - scope: 'mobile' - }) - ) - ) - } - const unrelated = registry.addDevice('Unrelated', scope) - const unrelatedSocket = await authenticateMobileWs( - encodePairingOffer({ - ...parsed, - deviceToken: unrelated.token, - pairedDeviceId: unrelated.deviceId - }) - ) - const closed = sockets.map(waitForWsClose) - if (removedOnDisk) { - const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) - const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) - writeFileSync(path, JSON.stringify(rows.filter((row) => row.deviceId !== offer.deviceId))) - } - - const revoked = - scope === 'mobile' - ? await server.revokeMobileDevice(offer.deviceId) - : server.revokeRuntimeAccess(offer.deviceId) - - expect(revoked).toBe(true) - for (const device of [fork, idleFork, ...children]) { - expect(registry.getDevice(device.deviceId)).toBeNull() - expect(new DeviceRegistry(userDataPath).getDevice(device.deviceId)).toBeNull() - } - await Promise.all(closed) - expect(registry.validateToken(unrelated.token)?.deviceId).toBe(unrelated.deviceId) - expect(unrelatedSocket.readyState).toBe(unrelatedSocket.OPEN) - unrelatedSocket.close() - } finally { - await server.stop() - } - }, - 15_000 - ) - - it.each(['binary', 'text', 'sibling-cascade'] as const)( - 'retires an established keyed terminal subscription through %s revocation', - async (kind) => { - vi.useFakeTimers({ toFake: ['performance'] }) - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-fork-stream-revoke-')) - const runtime = new OrcaRuntimeService(partialRuntimeStore(makeStore())) - const write = vi.fn(() => true) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: 'fork-stream-pty' }), - write, - kill: () => true, - getForegroundProcess: async () => null - }) - const cleanup = vi.spyOn(runtime, 'cleanupSubscriptionsForConnection') - const server = new OrcaRuntimeRpcServer({ - runtime, - userDataPath, - enableWebSocket: true, - wsPort: 0 - }) - await server.start() - try { - const terminal = await runtime.createTerminal('id:repo-1::/tmp/worktree-a') - const offer = server.createPairingOffer({ - address: '127.0.0.1', - name: 'Parent', - scope: kind === 'sibling-cascade' ? 'mobile' : 'runtime' - }) - if (!offer.available) { - throw new Error('WebSocket pairing unavailable') - } - const registry = server.getDeviceRegistry()! - const key = nacl.sign.keyPair() - const earlier = - kind === 'sibling-cascade' - ? registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 7).toString('base64'), - 'Earlier' - ) - : null - const fork = registry.forkDeviceKey( - offer.deviceId, - Buffer.from(key.publicKey).toString('base64'), - 'Fork' - ) - const later = - kind === 'sibling-cascade' - ? registry.forkDeviceKey( - offer.deviceId, - Buffer.alloc(32, 8).toString('base64'), - 'Later' - ) - : null - if (kind === 'sibling-cascade') { - server.setMobileRelayBinding(fork.deviceId, { - relayHostId: 'host', - relayDeviceId: fork.deviceId, - ownerIdentityKey: 'owner' - }) - registry.setPushRegistration(fork.deviceId, { - registrationId: 'fork-push', - filter: {}, - expiresAt: 4_000_000_000_000 - }) - } - const { ws, peer } = await authenticateKeyedWs( - parsePairingCode(offer.pairingUrl)!, - fork.deviceId, - key - ) - const responses: { result?: { type?: string; streamId?: number } }[] = [] - ws.on('message', (data, isBinary) => { - if (isBinary && Buffer.isBuffer(data)) { - peer.openBinary(data) - } else if (!isBinary) { - responses.push(JSON.parse(peer.openText(data.toString())!)) - } - }) - ws.send( - peer.sealText( - JSON.stringify({ - id: 'subscribe', - method: 'terminal.subscribe', - params: { terminal: terminal.handle, capabilities: { terminalBinaryStream: 1 } } - }) - ) - ) - await waitFor(() => responses.some((response) => response.result?.type === 'subscribed')) - const streamId = responses.find((response) => response.result?.type === 'subscribed') - ?.result?.streamId - if (streamId === undefined) { - throw new Error('Expected binary terminal subscription') - } - const sendInput = (text: string) => - ws.send( - peer.sealBinary( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId, - seq: 1, - payload: encodeTerminalStreamText(text) - }) - ) - ) - sendInput('before') - await waitFor(() => write.mock.calls.length === 1) - const path = join(userDataPath, DEVICE_REGISTRY_FILENAME) - const rows: { deviceId: string }[] = JSON.parse(readFileSync(path, 'utf8')) - writeFileSync( - path, - JSON.stringify( - rows.filter( - (row) => - row.deviceId !== (kind === 'sibling-cascade' ? fork.deviceId : offer.deviceId) - ) - ) - ) - // The registry sees another process's edit once its one-second stat window has passed. - vi.advanceTimersByTime(1000) - const closed = waitForWsClose(ws) - - if (kind === 'sibling-cascade') { - expect(await server.revokeMobileDevice(offer.deviceId)).toBe(true) - for (const device of [earlier, fork, later]) { - if (device) { - expect(registry.getDevice(device.deviceId)).toBeNull() - } - } - expect(registry.getDevice(offer.deviceId)).toBeNull() - expect(server.getRelayRevokeOutbox().pendingFor('owner', 'host')).toMatchObject([ - { relayDeviceId: fork.deviceId } - ]) - expect(server.getPushUnregisterOutbox().pending()).toMatchObject([ - { deviceId: fork.deviceId, registrationId: 'fork-push' } - ]) - } else if (kind === 'binary') { - sendInput('after') - } else { - ws.send(peer.sealText(JSON.stringify({ id: 'denied', method: 'status.get' }))) - } - - await waitFor( - () => - cleanup.mock.calls.length > 0 || - write.mock.calls.length > 1 || - responses.some((response) => 'error' in response) - ) - expect(write).toHaveBeenCalledTimes(1) - expect(cleanup).toHaveBeenCalledOnce() - await closed - expect(server['mobileSocketWiring']?.channelCount).toBe(0) - expect(server['mobileSocketWiring']?.connectionCount).toBe(0) - } finally { - cleanup.mockRestore() - await server.stop() - } - } - ) -}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts index efddca9334a..eb2b91a8cab 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts @@ -1,7 +1,7 @@ import type { RelayDeviceBinding, RelayRevokeOutboxItem -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { DelegatedPhone, DelegatedMobileDeviceSyncResult diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts index 2dba4a6ee48..924c96665c4 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing-types.ts @@ -16,7 +16,7 @@ import type { import type { RelayDeviceBinding, RelayRevokeOutboxItem -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' export const DEFAULT_WS_PORT = 6768 diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts index e64ad093930..6327d2446b0 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts @@ -7,7 +7,7 @@ import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring' import type { RelayDeviceBinding, RelayRevokeOutbox -} from '../../mobile-cloud-relay/relay-revoke-outbox' +} from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import type { PushUnregisterOutbox } from '../../push/push-unregister-outbox' 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/runtime/rpc/server/runtime-rpc-state.ts b/src/main/runtime/rpc/server/runtime-rpc-state.ts index 72d8796c20a..9006bde0562 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-state.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-state.ts @@ -12,7 +12,7 @@ import type { UnpairedDeviceAuthThrottle } from '../mobile/unpaired-device-auth- import type { MobileSocketWiring } from '../mobile/mobile-socket-wiring' import type { MobileDesktopRelay } from '../../mobile-desktop-relay/mobile-desktop-relay' import type { MobileRelayHostCatalog } from '../../mobile-desktop-relay/mobile-relay-host-catalog' -import { RelayRevokeOutbox } from '../../mobile-cloud-relay/relay-revoke-outbox' +import { RelayRevokeOutbox } from '../../mobile-cloud-relay/pairing/relay-revoke-outbox' import { PushUnregisterOutbox } from '../../push/push-unregister-outbox' import { RuntimeBinaryMessageRouter } from './runtime-binary-message-router' 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/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts b/src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts deleted file mode 100644 index a8b1b6d5b39..00000000000 --- a/src/main/runtime/session-lifecycle/close/close-by-split-handle-layout-owner.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - withDurableRuntimeStore, - withRuntimePaneAdmission -} from '../../orca-runtime-tests/runtime-durable-store-fixture' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import type { RuntimeMobileSessionTabsSnapshot } from '../../../../shared/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalTab } from '../../../../shared/runtime-mobile-session-tab-contracts' -import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -const REPO_ID = 'repo-1' -const WORKTREE_ID = `${REPO_ID}::/workspace` -const TAB_ID = 'tab-1' -const SOURCE_LEAF_ID = '11111111-1111-4111-8111-111111111111' -const SOURCE_PTY_ID = 'pty-source' -const SPLIT_PTY_ID = 'pty-split' - -function sourceLayout(): TerminalLayoutSnapshot { - return { - root: { type: 'leaf', leafId: SOURCE_LEAF_ID }, - activeLeafId: SOURCE_LEAF_ID, - expandedLeafId: null, - ptyIdsByLeafId: { [SOURCE_LEAF_ID]: SOURCE_PTY_ID } - } -} - -function persistedSession(): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: TAB_ID, - ptyId: SOURCE_PTY_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { [TAB_ID]: sourceLayout() } - } -} - -function surface( - leafId: string, - ptyId: string | null, - parentLayout: TerminalLayoutSnapshot -): RuntimeMobileSessionTerminalTab { - return { - type: 'terminal', - id: `${TAB_ID}::${leafId}`, - parentTabId: TAB_ID, - leafId, - ptyId, - title: 'Terminal', - parentLayout, - isActive: leafId === SOURCE_LEAF_ID - } -} - -/** The window's own publication: one surface per pane it has mounted. */ -function windowSnapshot( - version: number, - surfaces: RuntimeMobileSessionTerminalTab[] -): RuntimeMobileSessionTabsSnapshot { - return { - worktree: WORKTREE_ID, - publicationEpoch: 'window', - snapshotVersion: version, - activeGroupId: 'group-1', - activeTabId: `${TAB_ID}::${SOURCE_LEAF_ID}`, - activeTabType: 'terminal', - tabGroups: [{ id: 'group-1', activeTabId: TAB_ID, tabOrder: [TAB_ID] }], - tabs: surfaces - } -} - -function windowGraph( - leaves: { leafId: string; ptyId: string | null }[], - snapshot: RuntimeMobileSessionTabsSnapshot -) { - return { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: SOURCE_LEAF_ID, - layout: null - } - ], - leaves: leaves.map(({ leafId, ptyId }, index) => ({ - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId, - paneRuntimeId: index + 1, - ptyId - })), - mobileSessionTabs: [snapshot] - } -} - -/** What the window's list holds for main's new pane when it lands, after main's own. */ -type WindowListing = 'pane-without-terminal' | 'no-new-pane' - -function setup(listing: WindowListing, pinned = false) { - let session = persistedSession() - if (pinned) { - session = { - ...session, - tabsByWorktree: { - [WORKTREE_ID]: [{ ...session.tabsByWorktree[WORKTREE_ID]![0]!, isPinned: true }] - } - } - } - // The Store tells its write listeners after each write, as main's terminal list relies on. - const written = new Set<(hostId: ExecutionHostId | null) => void>() - const write = (next: WorkspaceSessionState): void => { - session = next - for (const listener of written) { - listener('local') - } - } - const repo = { - id: REPO_ID, - path: '/workspace', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1 - } - const store = withDurableRuntimeStore( - withRuntimePaneAdmission({ - getRepos: () => [repo], - getRepo: (id: string) => (id === REPO_ID ? repo : undefined), - getWorkspaceSession: () => session, - getWorkspaceSessionHostIds: (): ExecutionHostId[] => ['local'], - onWorkspaceSessionWritten: (listener: (hostId: ExecutionHostId | null) => void) => { - written.add(listener) - return () => written.delete(listener) - }, - setWorkspaceSession: (next: WorkspaceSessionState) => { - write(next) - }, - // Main's own layout close, as the Store applies it. - applyLayoutCommand: async (command: LayoutCommand, hostIds: readonly ExecutionHostId[]) => { - const change = applyCommandToSession(hostIds[0]!, session, command) - if (change.session) { - write(change.session) - } - return change.value - }, - persistPtyBinding: async () => true, - flushOrThrow: () => undefined - }) - ) - const runtime = new OrcaRuntimeService(partialRuntimeStore(store)) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: WORKTREE_ID, - path: '/workspace', - connectionId: null, - repo, - folderWorkspace: null - })) - }) - runtime.setPtyController({ - // The real spawn writes the new pane's binding into main's session; the fake does the same. - spawn: vi.fn(async (args: { tabId?: string; leafId?: string }) => { - const layout = session.terminalLayoutsByTabId[args.tabId!]! - write({ - ...session, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - [args.tabId!]: { - ...layout, - ptyIdsByLeafId: { ...layout.ptyIdsByLeafId, [args.leafId!]: SPLIT_PTY_ID } - } - } - }) - return { id: SPLIT_PTY_ID } - }), - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - // The window's list lags main: built before main's first frame (no new pane), or from it (the - // pane, but not yet its terminal). Either lands after main's own listing. - const revealTerminalSession = vi.fn(async (_worktreeId: string, args: { leafId?: string }) => { - const newLeafId = args.leafId! - const twoPanes = { - ...sourceLayout(), - root: { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: SOURCE_LEAF_ID }, - second: { type: 'leaf' as const, leafId: newLeafId } - } - } - runtime.syncWindowGraph( - 1, - windowGraph( - [{ leafId: SOURCE_LEAF_ID, ptyId: SOURCE_PTY_ID }], - windowSnapshot( - 2, - listing === 'no-new-pane' - ? [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, sourceLayout())] - : [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, twoPanes), surface(newLeafId, null, twoPanes)] - ) - ) - ) - return { tabId: TAB_ID } - }) - const notifier = { - revealTerminalSession, - splitTerminal: vi.fn(), - closeTerminalTab: vi.fn(async () => undefined) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the split and the tab close call only these notices. - runtime.setNotifier(notifier as never) - runtime.syncWindowGraph( - 1, - windowGraph( - [{ leafId: SOURCE_LEAF_ID, ptyId: SOURCE_PTY_ID }], - windowSnapshot(1, [surface(SOURCE_LEAF_ID, SOURCE_PTY_ID, sourceLayout())]) - ) - ) - runtime.registerPty(SOURCE_PTY_ID, WORKTREE_ID, null, { tabId: TAB_ID, leafId: SOURCE_LEAF_ID }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: both members are declared on OrcaRuntimeService's inheritance chain. - const internals = runtime as unknown as { - issuePtyHandle: (pty: unknown) => string - ptysById: Map - } - // A terminal listing can name the source by its terminal, so the split runs main-side. - const handle = internals.issuePtyHandle(internals.ptysById.get(SOURCE_PTY_ID)) - // Main's layout drops the pane, as a close of it would. - const dropPane = (leafId: string): void => { - const layout = session.terminalLayoutsByTabId[TAB_ID]! - const { [leafId]: _dropped, ...ptyIdsByLeafId } = layout.ptyIdsByLeafId ?? {} - write({ - ...session, - terminalLayoutsByTabId: { - ...session.terminalLayoutsByTabId, - [TAB_ID]: { ...layout, root: sourceLayout().root, ptyIdsByLeafId } - } - }) - } - return { runtime, handle, dropPane } -} - -describe("a tab close by a main-side split's handle while the window's list lags, in a layout-owner build", () => { - it.each(['pane-without-terminal', 'no-new-pane'])( - "closes the tab on main's own record of the pane (%s)", - async (listing) => { - const { runtime, handle } = setup(listing) - - const split = await runtime.splitTerminal(handle, { direction: 'vertical' }) - - await expect(runtime.closeTerminalTab(split.handle)).resolves.toMatchObject({ - tabId: TAB_ID, - closeMode: 'tab' - }) - } - ) - - it('still refuses once main no longer holds the pane', async () => { - const { runtime, handle, dropPane } = setup('no-new-pane') - - const split = await runtime.splitTerminal(handle, { direction: 'vertical' }) - dropPane(split.leafId!) - - await expect(runtime.closeTerminalTab(split.handle)).rejects.toThrow('terminal_handle_stale') - }) -}) - -describe('a CLI close of a pinned tab main owns, in a layout-owner build', () => { - it('refuses the tab close and keeps the tab, as the window-era close did', async () => { - const { runtime, handle } = setup('no-new-pane', true) - - await expect(runtime.closeTerminalTab(handle)).rejects.toThrow('terminal_tab_pinned') - await expect(runtime.closeTerminal(handle)).rejects.toThrow('terminal_tab_pinned') - expect( - runtime.getWorkspaceSessionForWorktree(WORKTREE_ID)?.tabsByWorktree[WORKTREE_ID] - ).toHaveLength(1) - }) -}) diff --git a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts index fb15a6994a1..c9cf1c1696c 100644 --- a/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts +++ b/src/main/runtime/session-lifecycle/projection/reconcile-headless-mobile-session-browser-tabs.ts @@ -21,7 +21,7 @@ import { sshRemotePtyLeaseAllowsReattach } from '../../../../shared/ssh-types' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { RuntimeStore } from '../../construction/runtime-store-contract' import { SSH_PANE_RECOVERY_GRACE_MS } from '../../terminal/recovery/ssh-pane-recovery-window' -import { findTerminalTabIdForLeaf } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { findTerminalTabIdForLeaf } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import { isServeMintedPtySessionId } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' export abstract class OrcaRuntimeWithReconcileHeadlessMobileSessionBrowserTabs extends OrcaRuntimeWithHydrateHeadlessMobileSessionTabsFromWorkspaceSession { 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/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts index 24f10dc2de4..4df86c84d06 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-fixture.ts @@ -12,7 +12,7 @@ import { Store } from '../../persistence/loading-store/store' import { OrcaRuntimeService } from '../orca-runtime' import { buildHeadlessMobileSessionTerminalTabs } from '../terminal/surface/mobile-session-terminal-projection' import { setRuntimeDesktopSurface } from '../construction/runtime-desktop-surface' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' export const ACK_WORKTREE = 'repo1::/tmp/worktree' export const ACK_TAB = '11111111-1111-4111-8111-111111111111' diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts index 756a61d6b83..b545254f31b 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts @@ -1,15 +1,13 @@ // Main-owned counterparts to acknowledged-terminal-tab-retirement.test.ts: close waits for layout durability without a window-ack race. import { afterEach, expect, it, vi } from 'vitest' import { - ACK_INCARNATION, ACK_LEAF, ACK_SECOND_LEAF, ACK_TAB, - ACK_WORKTREE, createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' -import '../../persistence/terminal-topology/terminal-topology-membership' -import { _resetClosedPaneFencesForTests } from '../../persistence/terminal-topology/closed-pane-binding-fence' +import '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' +import { _resetClosedPaneFencesForTests } from '../../persistence/terminal-topology/pane-ownership/closed-pane-binding-fence' vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) @@ -37,38 +35,6 @@ function fixture(bound = false) { return { ...result, stopped } } -it.each([false, true])( - 'durably closes the row in main without the window, graph republished first=%s', - async (graphFirst) => { - const f = fixture() - if (graphFirst) { - f.publish(false, 2) - } - await expect(f.close()).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - expect(f.closeTerminalTab).not.toHaveBeenCalled() - await f.store.flushPendingOrThrowAsync() - expect(f.readDisk().workspaceSession?.tabsByWorktree?.[ACK_WORKTREE] ?? []).toEqual([]) - } -) - -it.each([false, true])( - 'closes a split after one pane exited, with remote-session promotion=%s', - async (remoteSession) => { - const f = fixture(true) - if (remoteSession) { - f.store.setWorkspaceSession({ - ...f.store.getWorkspaceSession(), - remoteSessionIdsByTabId: { [ACK_TAB]: 'pty-a' } - }) - } - await f.runtime.onPtyExit('pty-a', 0, ACK_INCARNATION, { providerExitObserved: true }) - await expect(f.close()).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - expect(f.stopped).toContain('pty-b') - } -) - it("stops a sibling a partial mobile snapshot omitted, from main's own panes", async () => { const f = fixture(true) f.publish(true, 2, [ACK_LEAF]) diff --git a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts index 8778998d861..fdbff114d03 100644 --- a/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts +++ b/src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts @@ -5,7 +5,7 @@ import { ACK_WORKTREE, createAcknowledgedTabRetirementFixture } from './acknowledged-terminal-tab-retirement-fixture' -import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' // Main-owned closes have no window ack; their counterparts live in acknowledged-terminal-tab-retirement-main-close.test.ts. @@ -24,22 +24,6 @@ function fixture(bound = false) { return result } -itSwitchOff.each([false, true])( - 'durably retires an acknowledged row with graph-before-ack=%s', - async (graphBeforeAck) => { - const f = fixture() - const pending = f.close() - await f.entered.promise - expect(f.hasTab()).toBe(true) - if (graphBeforeAck) { - f.publish(false, 2) - } - f.acknowledgement.resolve() - await expect(pending).resolves.toEqual({ closed: true, retirementConfirmed: true }) - expect(f.hasTab()).toBe(false) - } -) - itSwitchOff( 'protects a persisted incarnation replacement on the same leaf and raw PTY ID', async () => { diff --git a/src/main/runtime/session-tabs/mobile-session-membership.ts b/src/main/runtime/session-tabs/mobile-session-membership.ts index 881d9d14ff4..4b23804cb30 100644 --- a/src/main/runtime/session-tabs/mobile-session-membership.ts +++ b/src/main/runtime/session-tabs/mobile-session-membership.ts @@ -5,7 +5,7 @@ import type { OrcaRuntimeWithGetTerminalInteractiveWait as GetTerminalInteractiv import { OrcaRuntimeWithPublishPtyBackedMobileSessionTerminal } from './pty-backed-session-publication' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { hasHostAuthoritativeTerminalMembership } from '../../persistence/terminal-topology/terminal-topology-membership' +import { hasHostAuthoritativeTerminalMembership } from '../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import type { RuntimeMobileSessionTabsSnapshot, RuntimeSyncedLeaf diff --git a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts index 2bbf14ed4ed..12e31c2d0b4 100644 --- a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts +++ b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts @@ -13,6 +13,10 @@ import { } from './mobile-dictation-chunk-order' import type { RuntimeStore } from '../construction/runtime-store-contract' import { hostDictationTerms } from './runtime-dictation-terms' +import { dictationTextSettingsFor } from '../../../shared/dictation-cleanup' +import type { DictationTerm } from '../../../shared/dictation-dictionary' +import { cleanUpDictatedText } from '../../speech/dictation-cleanup-service' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' import { DictationTranscript, type DictationTranscriptSnapshot @@ -22,6 +26,8 @@ type MobileDictationSession = { id: string owner: string clientId: string + /** The dictionary it was transcribed with, which cleanup spells by too. */ + terms: DictationTerm[] state: 'starting' | 'active' | 'closing' transcript: DictationTranscript errors: string[] @@ -74,10 +80,12 @@ export class RuntimeMobileDictationController { } const owner = `mobile:${clientId}:${params.dictationId}` + const terms = hostDictationTerms(store, params.worktreeId) const session: MobileDictationSession = { id: params.dictationId, owner, clientId, + terms, state: 'starting', transcript: new DictationTranscript(), errors: [], @@ -91,9 +99,9 @@ export class RuntimeMobileDictationController { await getSpeechSttService(store).startDictation( modelId, (event) => acceptEvent(session, event), - hostDictationTerms(store, params.worktreeId), + terms, owner, - voice + dictationTextSettingsFor({ ...store.getSettings(), voice }) ) if (this.sessions.get(clientId) !== session) { throw new Error('dictation_canceled') @@ -149,10 +157,11 @@ export class RuntimeMobileDictationController { return { ...reply, ...session.transcript.snapshot() } } - async finish(params: { - dictationId: string - clientId?: string - }): Promise<{ dictationId: string; text: string }> { + /** `agentEnv`: what AI cleanup runs the user's agent with, when it's on. */ + async finish( + params: { dictationId: string; clientId?: string }, + agentEnv?: CommitMessageAgentEnvironmentResolvers + ): Promise<{ dictationId: string; text: string }> { const session = this.requireOwnedSession(params) for (const chunk of session.chunkOrder.drain()) { this.feedChunk(session, chunk) @@ -161,7 +170,17 @@ export class RuntimeMobileDictationController { if (session.errors.length > 0) { throw new Error(session.errors[0]) } - return { dictationId: params.dictationId, text: session.transcript.snapshot().text } + const heard = session.transcript.snapshot().text + // The phone waits out cleanup inside its finish deadline; on any failure it gets the words as heard. + const store = this.requireStore() + const cleaned = await cleanUpDictatedText( + { text: heard, terms: session.terms }, + { getSettings: () => store.getSettings(), getAgentEnvResolvers: () => agentEnv } + ) + return { + dictationId: params.dictationId, + text: cleaned.status === 'cleaned' ? cleaned.text : heard + } } async cancel(params: { diff --git a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts index ddca47df479..b4daa1815e1 100644 --- a/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts +++ b/src/main/runtime/terminal/adoption/runtime-terminal-orphan-session-adoption.ts @@ -14,7 +14,7 @@ import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' import { mergeTerminalOrphanGroupLayout } from './terminal-orphan-topology' import { canonicalizeTerminalSessionWorktreeId } from '../identity/workspace-session-worktree-id' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' type Claim = RuntimeTerminalOrphanAdoptionRequest['claims'][number] type Topology = NonNullable diff --git a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts b/src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts similarity index 87% rename from src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts rename to src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts index fb6c00f9ea1..3f7c8c12f10 100644 --- a/src/main/persistence/terminal-topology/unshown-live-terminal-placement-restart.test.ts +++ b/src/main/runtime/terminal/adoption/unshown-live-terminal-placement-restart.test.ts @@ -2,23 +2,23 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { Store } from '../loading-store/store' +import { getDefaultWorkspaceSession } from '../../../../shared/constants' +import type { Store } from '../../../persistence/loading-store/store' import { placeUnshownLiveTerminals, type LiveTerminalPlacementPorts -} from '../../runtime/terminal/adoption/unshown-live-terminal-placement' -import { WindowSession } from './terminal-topology-window-session-fixture' +} from './unshown-live-terminal-placement' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID, openTopologyStore, reopenTopologyStore -} from './terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' -vi.mock('../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) +vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) diff --git a/src/main/runtime/terminal/launch/runtime-pane-admission.ts b/src/main/runtime/terminal/launch/runtime-pane-admission.ts index 5dd1934bba2..9f9cc3d102a 100644 --- a/src/main/runtime/terminal/launch/runtime-pane-admission.ts +++ b/src/main/runtime/terminal/launch/runtime-pane-admission.ts @@ -9,7 +9,7 @@ import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-top import type { TerminalPaneAdmission, TerminalPaneAdmissionOutcome -} from '../../../persistence/terminal-topology/terminal-pane-admission' +} from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { LayoutRefusalCode } from '../../../../shared/workspace-layout/workspace-layout-command-types' import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-contract' import type { RuntimeStore } from '../../construction/runtime-store-contract' diff --git a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts index cd44d04166b..6b64e967fa8 100644 --- a/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts +++ b/src/main/runtime/terminal/layout/agent-generated-tab-titles.test.ts @@ -9,12 +9,12 @@ import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/cont import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID as GIT, openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ diff --git a/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts b/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts index 6b305f8cc54..79b74962adf 100644 --- a/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts +++ b/src/main/runtime/terminal/layout/editor-view-layout-apply.test.ts @@ -7,14 +7,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { LayoutEditorView } from '../../../../shared/workspace-layout/editor-tabs/layout-editor-view' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStore, reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) diff --git a/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts b/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts index c601b3cab01..f5de295e744 100644 --- a/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts +++ b/src/main/runtime/terminal/layout/editor-view-partition-changes.test.ts @@ -8,13 +8,13 @@ import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { LayoutEditorView } from '../../../../shared/workspace-layout/editor-tabs/layout-editor-view' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStoreWithAuthority -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) @@ -126,29 +126,4 @@ describe("main's Store keeps an editor view where its tab's session is", () => { expect(publishedTab(runtime, FOLDER, 'd1-moved')).toBeUndefined() subscription.unsubscribe() }) - - it('a failed write puts a move across partitions back with its view', async () => { - const { store, authority, subscription } = await harness() - await store.applyLayoutCommand(openDiff(WT, 'd1')) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - authority.failNextWrite() - - await expect( - store.moveTabToWorkspaceAcrossPartitions( - { - type: 'moveTabToWorkspace', - workspace: WT, - toWorkspace: SSH_WORKTREE, - tabs: [{ tabId: 'd1', newTabId: 'd1', newEntityId: 'diff::moved' }], - groupId: `group-${SSH_WORKTREE}` - }, - 'local', - SSH_HOST - ) - ).rejects.toThrow() - - expect(store.getLayoutEditorViews('local')).toEqual({ [WT]: { d1: DIFF_VIEW } }) - expect(store.getLayoutEditorViews(SSH_HOST) ?? {}).toEqual({}) - subscription.unsubscribe() - }) }) diff --git a/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts b/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts index 68ba0a25dc2..1d16da84661 100644 --- a/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts +++ b/src/main/runtime/terminal/layout/main-owned-workspace-runtime-fixture.ts @@ -4,7 +4,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import type { TerminalPaneLayoutNode } from '../../../../shared/workspace-layout/terminal-tab-types' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../../shared/runtime-session-contracts' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { resolveHostId } from '../../../persistence/loading-store/workspace-sessions/session-host-partitions' import { withDurableRuntimeStore, diff --git a/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts b/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts index 25f1889fa46..f466d3bbe42 100644 --- a/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts +++ b/src/main/runtime/terminal/layout/profile-session-store.test-fixture.ts @@ -3,7 +3,7 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session import { getDefaultWorkspaceSession } from '../../../../shared/constants' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' import { resolveHostId } from '../../../persistence/loading-store/workspace-sessions/session-host-partitions' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import type { OrcaRuntimeService } from '../../orca-runtime' import type { RuntimeStore } from '../../construction/runtime-store-contract' diff --git a/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts b/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts index 783a56b87b2..2e411948444 100644 --- a/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts +++ b/src/main/runtime/terminal/layout/restored-editor-move-restart.test.ts @@ -7,14 +7,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { getDefaultWorkspaceSession } from '../../../../shared/constants' import { ownedEditorFileId } from '../../../../shared/workspace-session/workspace-session-pane-ownership' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_FOLDER_WORKTREE_ID as FOLDER, FIXTURE_GIT_WORKTREE_ID as WT, openTopologyStore, reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { OrcaRuntimeService } from '../../orca-runtime' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) 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 diff --git a/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts b/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts deleted file mode 100644 index b024e777b7d..00000000000 --- a/src/main/runtime/terminal/stop/hook-status-resume-sleep-ordering.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -// Queued pre-sleep hook writes must not replace the newer saved sleep record. -import { describe, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { ExecutionHostId } from '../../../../shared/execution-host' -import type { LayoutApplyOutcome } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' -import type { WorktreeSleepResumeCapture } from './worktree-sleep-resume-records' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -// Preserve side-effect order: mocks, lifecycle, 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 { - HEADLESS_LEAF_ID, - TEST_WORKTREE_ID, - makeRuntimeStoreWithWorkspaceSession, - makeWorkspaceSessionWithHeadlessTerminal -} = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec') - -const PANE_KEY = `host-tab:${HEADLESS_LEAF_ID}` -const PTY_ID = 'pty-slept' -const SESSION = { key: 'session_id' as const, id: 'codex-session-1' } - -function codexRow(overrides: Partial = {}): AgentStatusIpcPayload { - return { - paneKey: PANE_KEY, - worktreeId: TEST_WORKTREE_ID, - agentType: 'codex', - providerSession: SESSION, - state: 'working', - prompt: 'keep working', - receivedAt: 10, - stateStartedAt: 10, - connectionId: null, - ...overrides - } -} - -function makeRuntimeWithSlowFirstWrite() { - const { runtimeStore, getSession, setSession } = makeRuntimeStoreWithWorkspaceSession( - makeWorkspaceSessionWithHeadlessTerminal() - ) - let releaseFirstWrite = (): void => {} - const firstWriteDurable = new Promise((resolve) => { - releaseFirstWrite = resolve - }) - const firstWriteEntered = Promise.withResolvers() - let writes = 0 - const applyLayoutCommand = vi.fn( - async ( - command: Parameters[2], - hostIds: ExecutionHostId[] - ): Promise => { - for (const hostId of hostIds) { - const change = applyCommandToSession(hostId, getSession(), command) - if (change.session) { - setSession(change.session) - } - } - writes += 1 - if (writes === 1) { - firstWriteEntered.resolve() - await firstWriteDurable - } - return { ok: true, result: {} } - } - ) - const runtime = new OrcaRuntimeService(Object.assign(runtimeStore, { applyLayoutCommand })) - runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) - return { runtime, getSession, releaseFirstWrite, firstWriteEntered: firstWriteEntered.promise } -} - -function sleepCapture(updatedAt: number): WorktreeSleepResumeCapture { - return new Map([ - [ - PTY_ID, - { - retiredPaneKeys: [], - records: [ - { - paneKey: PANE_KEY, - tabId: 'host-tab', - worktreeId: TEST_WORKTREE_ID, - agent: 'codex', - providerSession: SESSION, - prompt: 'keep working', - state: 'done', - capturedAt: 20, - updatedAt, - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true, - connectionId: null - } - ] - } - ] - ]) -} - -describe('a queued hook status and a workspace sleep', () => { - it('keeps the sleep’s record when a status accepted before the sleep is written after it', async () => { - const { runtime, getSession, releaseFirstWrite, firstWriteEntered } = - makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await firstWriteEntered - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - - const slept = runtime['sleepResumeRecords'].persist(TEST_WORKTREE_ID, sleepCapture(11), [ - PTY_ID - ]) - releaseFirstWrite() - await slept - await runtime['hookStatusResumeWrites'] - - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toMatchObject({ - origin: 'worktree-sleep', - state: 'done', - restoreOnTabOpenOnly: true - }) - }) - - it('keeps a window sleep’s record when a status accepted before it is written after it', async () => { - const { runtime, getSession, releaseFirstWrite, firstWriteEntered } = - makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await firstWriteEntered - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - - const [record] = sleepCapture(11).get(PTY_ID)!.records - const slept = runtime.applyLayoutCommand({ - type: 'sleep', - workspace: TEST_WORKTREE_ID, - tabId: 'host-tab', - paneKeys: [PANE_KEY], - records: [record!] - }) - releaseFirstWrite() - await slept - await runtime['hookStatusResumeWrites'] - - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toMatchObject({ - origin: 'worktree-sleep', - state: 'done' - }) - }) -}) - -it.each([false, true])( - 'orders refused cleanup after queued status and preserves newer same-conversation recipe (%s)', - async (newer) => { - const { runtime, getSession, releaseFirstWrite } = makeRuntimeWithSlowFirstWrite() - runtime.recordHookStatusResume(codexRow()) - await vi.waitFor(() => - expect(getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]).toBeDefined() - ) - runtime.recordHookStatusResume(codexRow({ state: 'blocked', receivedAt: 11 })) - const sourcePromise = runtime.readSavedResumeSource(TEST_WORKTREE_ID, PANE_KEY) - releaseFirstWrite() - const source = await sourcePromise - if (!source) { - throw new Error('missing captured source') - } - const refused = { - agent: 'codex' as const, - providerSession: SESSION, - expectedStatus: { paneKey: PANE_KEY, receivedAt: 11, stateStartedAt: 10 }, - expectedSavedRecord: { - paneKey: PANE_KEY, - capturedAt: source.capturedAt, - updatedAt: source.updatedAt - } - } - if (newer) { - runtime.recordHookStatusResume(codexRow({ receivedAt: 30, prompt: 'new explicit C' })) - } - await runtime.forgetRefusedSavedResume(TEST_WORKTREE_ID, PANE_KEY, refused, source) - await runtime['hookStatusResumeWrites'] - const record = getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY] - if (newer) { - expect(record).toMatchObject({ prompt: 'new explicit C', updatedAt: 30 }) - } else { - expect(getSession().sleepingAgentSessionsByPaneKey).toEqual({}) - } - } -) diff --git a/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts b/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts index c459c274c5e..85272f3c85d 100644 --- a/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts +++ b/src/main/runtime/terminal/stop/terminal-intentional-stop-exit.test.ts @@ -30,11 +30,10 @@ import { WORKTREE_PATH, makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const REPLACEMENT_PTY_ID = 'pty-close-continuity-replacement' const REPLACEMENT_INCARNATION_ID = '77777777-7777-4777-8777-777777777777' -const LATER_INCARNATION_ID = '88888888-8888-4888-8888-888888888888' const directories: string[] = [] const stores: Store[] = [] @@ -217,37 +216,6 @@ describe('intentional stops keep the pane through the exit', () => { ]) }) - it('never reads the exit of a later process on the same id as the stop', async () => { - const harness = createHarness({ lateProviderExit: true }) - await stopRendererOwnedPty(harness.deps, { id: PTY_ID, keepHistory: true }) - // The later process's commit binds its pane before it registers, as the spawn commit does. - await harness.store.persistPtyBinding({ - worktreeId: WORKTREE_ID, - tabId: TAB_ID, - leafId: LEAF_ID, - ptyId: PTY_ID, - incarnationId: LATER_INCARNATION_ID, - origin: 'reattach' - }) - harness.runtime.registerPty(PTY_ID, WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: LATER_INCARNATION_ID - }) - ptyIncarnationById.set(PTY_ID, LATER_INCARNATION_ID) - - harness.emitProviderExit(LATER_INCARNATION_ID) - - // Why wait: an unstopped exit retires the pane through an async durable save. - await vi.waitFor(() => expect(harness.boundPtyId()).toBeNull()) - expect(harness.rendererExits().at(-1)).toEqual({ - id: PTY_ID, - code: 0, - incarnationId: LATER_INCARNATION_ID, - hostId: 'local' - }) - }) - it('keeps the tab and its wake binding when the runtime puts the worktree to sleep', async () => { const harness = createHarness({ folder: true }) const inventories = [[{ id: PTY_ID, worktreeId: WORKTREE_ID, cwd: WORKTREE_PATH, title: 'a' }]] 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/runtime/terminal/surface/main-terminal-acquisition.test.ts b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts deleted file mode 100644 index 126ad8e8c4f..00000000000 --- a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import '../../orca-runtime-tests/runtime-test-module-registration.spec' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { OrcaRuntimeService } from '../../orca-runtime' -import { OrchestrationDb } from '../../orchestration/db/orchestration-db' -import '../../orchestration/db/contract-constants' -import '../../orchestration/db/messages/mailbox-routing-page' -import '../../orchestration/db/dispatch-row-writer' -import '../../orchestration/db/attempt-outcome-projection' -import { - openTopologyStoreWithAuthority, - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' -import { expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -class MainCrewRuntime extends OrcaRuntimeService { - seedPty(id: string, handle: string): void { - this.recordPtyWorktree(id, FIXTURE_GIT_WORKTREE_ID, { connected: true }) - this.terminalIdentity.bindPty(id, handle) - this.terminalIdentity.setHandle(handle, { - handle, - runtimeId: this.runtimeId, - rendererGraphEpoch: this.rendererGraphEpoch, - worktreeId: FIXTURE_GIT_WORKTREE_ID, - tabId: `pty:${id}`, - leafId: `pty:${id}`, - ptyId: id, - ptyGeneration: 0 - }) - } -} - -it('retires raw main bindings on real Store-only writes with Crew as sole observer and no installed graph', async () => { - for (const population of [3, 30]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-pr34890-main-')) - const { store, authority } = await openTopologyStoreWithAuthority( - directory, - emptyTerminalSessionProfile() - ) - const db = new OrchestrationDb(':memory:') - let stop = () => {} - try { - const saved = new WindowSession(getDefaultWorkspaceSession()) - for (let i = 0; i < population; i++) { - const leaf = `aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` - saved.addTab(FIXTURE_GIT_WORKTREE_ID, `tab-main-${i}`, leaf) - saved.bind(`tab-main-${i}`, leaf, `pty-main-${i}`) - } - store.setWorkspaceSession(saved.snapshot(), 'local') - await store.flushPendingOrThrowAsync() - const runtime = new MainCrewRuntime(store) - runtime.setOrchestrationDb(db) - runtime.seedPty('coord', 'term_coord') - for (let i = 0; i < population; i++) { - runtime.seedPty(`pty-main-${i}`, `term_main_${i}`) - } - runtime.seedPty('replacement', 'term_replacement') - const pane = 'tab-main-0:aaaaaaaa-aaaa-4aaa-8aaa-000000000000' - const run = db.createRun({ - objective: 'Main source', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: 'coord-pane' - }) - db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'Main worker' }).id, - assigneeHandle: 'term_missing_stored', - assigneePaneKey: pane, - creator: { kind: 'system' }, - maxDepth: 10 - }) - const capture = vi.spyOn(runtime, 'createTerminalIdentityRawInputs') - const generations = vi.spyOn(store, 'getPtyBindingGeneration') - stop = runtime.watchOrchestrationCrew(() => {}) - const read = () => runtime.getOrchestrationCrewSnapshot('term_coord').sections.managing[0] - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_main_0' }) - expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_main_0') - read() - const initial = capture.mock.calls.length - const visits = generations.mock.calls.length - const irrelevant = store.getWorkspaceSession() - store.setWorkspaceSession({ ...irrelevant, activeTabId: 'tab-main-1' }, 'local') - await store.flushPendingOrThrowAsync() - read() - expect(capture).toHaveBeenCalledTimes(initial) - expect(generations.mock.calls.length - visits).toBe(population) - await store.applyLayoutCommand({ - type: 'renameTab', - workspace: FIXTURE_GIT_WORKTREE_ID, - tabId: 'tab-main-0', - kind: 'custom', - title: 'Named main worker' - }) - expect(read().label).toBe( - runtime.orchestrationSenderNames.nameOf( - { address: 'term_main_0', terminalHandle: 'term_main_0', orcaSessionId: null }, - undefined, - 'Main worker', - null - ) ?? 'Main worker' - ) - expect(capture).toHaveBeenCalledTimes(initial) - const current = store.getWorkspaceSession() - const layout = current.terminalLayoutsByTabId['tab-main-0'] - store.setWorkspaceSession( - { - ...current, - terminalLayoutsByTabId: { - ...current.terminalLayoutsByTabId, - 'tab-main-0': { - ...layout, - ptyIdsByLeafId: { - ...layout.ptyIdsByLeafId, - 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000': 'replacement' - } - } - } - }, - 'local' - ) - await store.flushPendingOrThrowAsync() - expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_replacement') - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect(capture.mock.calls.length).toBeGreaterThan(initial) - const leaf = 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000' - const beforeGeneration = store.getPtyBindingGeneration('local', leaf) ?? 0 - const beforeCapture = capture.mock.calls.length - const binding = { - worktreeId: FIXTURE_GIT_WORKTREE_ID, - tabId: 'tab-main-0', - leafId: leaf, - ptyId: 'replacement', - correctStartupCwd: '/main-source' - } - expect(await store.persistPtyBinding(binding, 'local')).toBe(true) - expect(store.getPtyBindingGeneration('local', leaf)).toBe(beforeGeneration + 1) - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect(capture.mock.calls.length).toBeGreaterThan(beforeCapture) - const stable = capture.mock.calls.length - authority.failNextWrite() - await expect( - store.persistPtyBinding({ ...binding, correctStartupCwd: '/rolled-back' }, 'local') - ).rejects.toThrow('profile_state_write_failed') - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) - expect( - store.getWorkspaceSession().tabsByWorktree[FIXTURE_GIT_WORKTREE_ID][0].startupCwd - ).toBe('/main-source') - read() - expect(capture.mock.calls.length).toBeLessThanOrEqual(stable + 1) - runtime.seedPty('reentrant', 'term_reentrant') - const seen: (string | null)[] = [] - const stopReentrant = store.onWorkspaceSessionWritten(() => { - seen.push(runtime.getTerminalHandleForPaneKey(pane)) - expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_reentrant' }) - }) - try { - const reentrant = structuredClone(store.getWorkspaceSession()) - reentrant.terminalLayoutsByTabId['tab-main-0'].ptyIdsByLeafId = { [leaf]: 'reentrant' } - store.setWorkspaceSession(reentrant, 'local') - await store.flushPendingOrThrowAsync() - expect(seen).toEqual(['term_reentrant']) - } finally { - stopReentrant() - } - expect( - runtime.getTerminalHandleForPaneKey('absent:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') - ).toBeNull() - } finally { - stop() - db.close() - await store.freezeWritesAsync() - rmSync(directory, { recursive: true, force: true }) - } - } -}) diff --git a/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts b/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts index cc11b9f39e9..c3f0f57f7e6 100644 --- a/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts +++ b/src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.ts @@ -7,7 +7,7 @@ import { } from './mobile-session-terminal-retirement' import { retireLeavesFromTerminalLayout } from '../../../../shared/workspace-layout/terminal-topology/terminal-layout-leaf-retirement' import { rebaseWorkspaceSessionTerminalMembership } from './workspace-session-terminal-membership-authority' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' function visibleTypeForContentType( contentType: string | undefined diff --git a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts b/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts deleted file mode 100644 index 8e8d61f4e22..00000000000 --- a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership-layout-owner.test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { vi } from 'vitest' - -// Main-owned layout variant: registration must publish once without waiting for a later frame. -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) - -await import('./orca-runtime-cold-restore-terminal-membership.test') diff --git a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts b/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts deleted file mode 100644 index f3fdadcd7d2..00000000000 --- a/src/main/runtime/terminal/surface/orca-runtime-cold-restore-terminal-membership.test.ts +++ /dev/null @@ -1,568 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultWorkspaceSession } from '../../../../shared/constants' -import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' -import type { RuntimeMobileSessionSnapshotTab } from '../../../../shared/runtime-mobile-session-tab-contracts' -import type { - RuntimeMobileSessionTabsResult, - RuntimeMobileSessionTabsSnapshot -} from '../../../../shared/runtime-session-contracts' -import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' -import { OrcaRuntimeService } from '../../orca-runtime' -import { setRuntimeDesktopSurface } from '../../construction/runtime-desktop-surface' -import { withDurableRuntimeStore } from '../../orca-runtime-tests/runtime-durable-store-fixture' -import { bindPaneFirst } from '../../orca-runtime-tests/bind-first-pane.test-fixture' - -import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' - -const WORKTREE_ID = 'repo::/worktree' -const REPO_ID = 'repo' -const LEFT = '11111111-1111-4111-8111-111111111111' -const RIGHT = '22222222-2222-4222-8222-222222222222' -const SPLIT_ROOT = { - type: 'split' as const, - direction: 'vertical' as const, - first: { type: 'leaf' as const, leafId: LEFT }, - second: { type: 'leaf' as const, leafId: RIGHT } -} - -type RestoreHost = { - repo: { - id: string - path: string - displayName: string - badgeColor: string - addedAt: number - connectionId?: string - executionHostId?: ExecutionHostId - } - hostId: ExecutionHostId - connectionId: string | null - ptyIds: { left: string; right: string } - /** SSH relaunch can register before its persisted PTY binding. */ - persistsPtyBindings: boolean -} - -const LOCAL_HOST: RestoreHost = { - repo: { id: REPO_ID, path: '/worktree', displayName: 'repo', badgeColor: 'blue', addedAt: 1 }, - hostId: LOCAL_EXECUTION_HOST_ID, - connectionId: null, - ptyIds: { left: 'pty-left', right: 'pty-right' }, - persistsPtyBindings: true -} -const SSH_HOST: RestoreHost = { - repo: { ...LOCAL_HOST.repo, connectionId: 'ssh-1' }, - hostId: 'ssh:ssh-1', - connectionId: 'ssh-1', - ptyIds: { left: 'ssh:ssh-1@@pty-left', right: 'ssh:ssh-1@@pty-right' }, - persistsPtyBindings: false -} -const RUNTIME_HOST: RestoreHost = { - ...LOCAL_HOST, - repo: { ...LOCAL_HOST.repo, executionHostId: 'runtime:env-1' }, - hostId: 'runtime:env-1' -} - -// Restore saved split and host-authoritative membership before any PTY registers. -function makeColdRestoredSession(host: RestoreHost): WorkspaceSessionState { - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: [ - { - id: 'tab', - ptyId: host.persistsPtyBindings ? host.ptyIds.left : null, - worktreeId: WORKTREE_ID, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - terminalLayoutsByTabId: { - tab: { - root: SPLIT_ROOT, - activeLeafId: LEFT, - expandedLeafId: null, - ptyIdsByLeafId: host.persistsPtyBindings - ? { [LEFT]: host.ptyIds.left, [RIGHT]: host.ptyIds.right } - : {} - } - }, - terminalTopologyRevisionByRepoId: { [REPO_ID]: 2 } - } -} - -function makeRendererFrame( - host: RestoreHost, - options: { - version?: number - leaves?: readonly string[] - extraTabs?: readonly RuntimeMobileSessionSnapshotTab[] - } = {} -): RuntimeMobileSessionTabsSnapshot { - const leaves = options.leaves ?? [LEFT, RIGHT] - const ptyIdByLeaf: Record = { - [LEFT]: host.ptyIds.left, - [RIGHT]: host.ptyIds.right - } - const parentLayout = { - root: leaves.length === 2 ? SPLIT_ROOT : { type: 'leaf' as const, leafId: leaves[0] }, - activeLeafId: leaves[0], - expandedLeafId: leaves[0], - ptyIdsByLeafId: Object.fromEntries(leaves.map((leafId) => [leafId, ptyIdByLeaf[leafId]])) - } - const extraTabs = options.extraTabs ?? [] - return { - worktree: WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: options.version ?? 1, - activeGroupId: 'group', - activeTabId: `tab::${leaves[0]}`, - activeTabType: 'terminal', - tabGroups: [ - { id: 'group', activeTabId: 'tab', tabOrder: ['tab', ...extraTabs.map((tab) => tab.id)] } - ], - tabs: [ - ...leaves.map((leafId, index) => ({ - type: 'terminal' as const, - id: `tab::${leafId}`, - parentTabId: 'tab', - leafId, - ptyId: ptyIdByLeaf[leafId], - title: leafId === LEFT ? 'Left' : 'Right', - parentLayout, - isActive: index === 0 - })), - ...extraTabs - ] - } -} - -const RENDERER_TABS = [ - { - tabId: 'tab', - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: LEFT, - layout: SPLIT_ROOT - } -] - -function publishRendererFrame( - runtime: OrcaRuntimeService, - frame: RuntimeMobileSessionTabsSnapshot -): ReturnType { - return runtime.syncWindowGraph(1, { tabs: RENDERER_TABS, leaves: [], mobileSessionTabs: [frame] }) -} - -function coldRestoredRuntime(host: RestoreHost = LOCAL_HOST): { - runtime: OrcaRuntimeService - sessions: Map -} { - const sessions = new Map([ - [host.hostId, makeColdRestoredSession(host)] - ]) - // Live windows own tab publications; main must not rebuild them from persistence. - const liveWindow = { - isDestroyed: () => false, - webContents: { isDestroyed: () => false, send: () => {} } - } - setRuntimeDesktopSurface({ - showNotification: () => false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only liveness and send off its authoritative window on these paths. - findWindowById: () => liveWindow as never, - onIpc: () => {}, - removeIpcListener: () => {} - }) - const runtime = new OrcaRuntimeService( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the list, fence, exit and close paths read only repos and the workspace session; the rest of Store is unreached. - withDurableRuntimeStore({ - getRepos: () => [host.repo], - getRepo: (id: string) => (id === REPO_ID ? host.repo : undefined), - getAllWorktreeMeta: () => ({}), - getWorktreeMeta: () => undefined, - getSettings: () => ({ workspaceDir: '/tmp/workspaces' }), - getProjects: () => [], - getWorkspaceSessionHostIds: () => [...sessions.keys()], - getWorkspaceSession: (hostId?: ExecutionHostId) => - sessions.get(hostId ?? LOCAL_EXECUTION_HOST_ID) ?? getDefaultWorkspaceSession(), - setWorkspaceSession: (next: WorkspaceSessionState, hostId?: ExecutionHostId) => { - sessions.set(hostId ?? LOCAL_EXECUTION_HOST_ID, next) - }, - applyLayoutCommand: async (command: LayoutCommand, hostIds: readonly ExecutionHostId[]) => { - const hostId = hostIds[0] ?? LOCAL_EXECUTION_HOST_ID - const change = applyCommandToSession( - hostId, - sessions.get(hostId) ?? getDefaultWorkspaceSession(), - command - ) - if (change.session) { - sessions.set(hostId, change.session) - } - return change.value - }, - flushPendingOrThrowAsync: async () => {}, - // Production commits asynchronously; fail if these paths synchronously flush. - flushOrThrow: () => { - throw new Error('synchronous flush') - } - }) as never - ) - runtime.attachWindow(1) - return { runtime, sessions } -} - -/** Bind in the host partition before registration, matching PTY spawn commit. */ -function registerBound( - runtime: OrcaRuntimeService, - hostId: ExecutionHostId, - ptyId: string, - connectionId: string | null, - binding: { tabId: string; leafId: string; incarnationId: string } -) { - bindPaneFirst(runtime, { worktreeId: WORKTREE_ID, ptyId, ...binding }, hostId) - runtime.registerPty(ptyId, WORKTREE_ID, connectionId, binding) -} - -function registerLeaf(runtime: OrcaRuntimeService, host: RestoreHost, leaf: 'left' | 'right') { - registerBound(runtime, host.hostId, host.ptyIds[leaf], host.connectionId, { - tabId: 'tab', - leafId: leaf === 'left' ? LEFT : RIGHT, - incarnationId: `incarnation-${leaf}` - }) -} - -function surfaces(result: RuntimeMobileSessionTabsResult | undefined): string[] { - return (result?.tabs ?? []).map((tab) => `${tab.id}:${'status' in tab ? tab.status : ''}`) -} - -async function listedSurfaces(runtime: OrcaRuntimeService): Promise { - return surfaces(await runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)) -} - -const COALESCED_PUSH_MS = 250 - -describe('a restored terminal published before its PTY registers', () => { - afterEach(() => { - setRuntimeDesktopSurface(null) - vi.useRealTimers() - }) - - it.each([ - ['local', LOCAL_HOST], - ['SSH without a saved PTY binding', SSH_HOST], - ['runtime host', RUNTIME_HOST] - ])('%s: is listed pending, then pushed ready when its PTY registers', async (_label, host) => { - vi.useFakeTimers() - const { runtime } = coldRestoredRuntime(host) - publishRendererFrame(runtime, makeRendererFrame(host)) - expect(await listedSurfaces(runtime)).toEqual([ - `tab::${LEFT}:pending-handle`, - `tab::${RIGHT}:pending-handle` - ]) - vi.advanceTimersByTime(COALESCED_PUSH_MS) - const published: RuntimeMobileSessionTabsResult[] = [] - const unsubscribe = runtime.onMobileSessionTabsChanged((event) => published.push(event)) - - registerLeaf(runtime, host, 'left') - vi.advanceTimersByTime(COALESCED_PUSH_MS) - - // No later renderer/graph event can rescue a missing registration push. - expect(surfaces(published.at(-1))).toEqual([ - `tab::${LEFT}:ready`, - `tab::${RIGHT}:pending-handle` - ]) - const pushes = published.length - expect( - runtime.syncWindowGraph(1, { - tabs: RENDERER_TABS, - leaves: [], - mobileSessionTabs: [], - unchangedMobileSessionWorktrees: [WORKTREE_ID] - }).mobileSessionResyncWorktrees - ).toBeUndefined() - publishRendererFrame(runtime, makeRendererFrame(host)) - vi.advanceTimersByTime(COALESCED_PUSH_MS) - expect(published).toHaveLength(pushes) - expect(await listedSurfaces(runtime)).toEqual([ - `tab::${LEFT}:ready`, - `tab::${RIGHT}:pending-handle` - ]) - - registerLeaf(runtime, host, 'right') - vi.advanceTimersByTime(COALESCED_PUSH_MS) - - expect(surfaces(published.at(-1))).toEqual([`tab::${LEFT}:ready`, `tab::${RIGHT}:ready`]) - unsubscribe() - }) -}) - -describe('a retired restored terminal stays out of a later renderer frame', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('after its process exits and the retirement is saved', async () => { - const { runtime, sessions } = coldRestoredRuntime() - registerLeaf(runtime, LOCAL_HOST, 'left') - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - expect(await listedSurfaces(runtime)).toContain(`tab::${LEFT}:ready`) - - await runtime.onPtyExit('pty-left', 0, 'incarnation-left') - - expect(sessions.get(LOCAL_EXECUTION_HOST_ID)?.terminalLayoutsByTabId.tab?.root).toEqual({ - type: 'leaf', - leafId: RIGHT - }) - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 2 })) - expect(await listedSurfaces(runtime)).not.toContain(`tab::${LEFT}:ready`) - expect(await listedSurfaces(runtime)).not.toContain(`tab::${LEFT}:pending-handle`) - }) - - it('after its last pane exits from a runtime-host partition an older copy still lists', async () => { - const { runtime, sessions } = coldRestoredRuntime(RUNTIME_HOST) - // Retain an older same-id copy in another host partition. - sessions.set(LOCAL_EXECUTION_HOST_ID, makeColdRestoredSession(RUNTIME_HOST)) - registerLeaf(runtime, RUNTIME_HOST, 'left') - registerLeaf(runtime, RUNTIME_HOST, 'right') - publishRendererFrame(runtime, makeRendererFrame(RUNTIME_HOST)) - - await runtime.onPtyExit('pty-left', 0, 'incarnation-left') - await runtime.onPtyExit('pty-right', 0, 'incarnation-right') - // Emptying the owner partition exposes the older copy. - expect(sessions.get(RUNTIME_HOST.hostId)?.tabsByWorktree[WORKTREE_ID]).toEqual([]) - - publishRendererFrame(runtime, makeRendererFrame(RUNTIME_HOST, { version: 2 })) - expect(await listedSurfaces(runtime)).toEqual([]) - }) - - it('after the user closes it on the desktop', async () => { - const { runtime, sessions } = coldRestoredRuntime() - registerLeaf(runtime, LOCAL_HOST, 'left') - registerLeaf(runtime, LOCAL_HOST, 'right') - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - expect(await listedSurfaces(runtime)).toEqual([`tab::${LEFT}:ready`, `tab::${RIGHT}:ready`]) - - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 2, leaves: [LEFT] })) - await runtime.onPtyExit('pty-right', 0, 'incarnation-right') - expect(sessions.get(LOCAL_EXECUTION_HOST_ID)?.terminalLayoutsByTabId.tab?.root).toEqual({ - type: 'leaf', - leafId: LEFT - }) - - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST, { version: 3 })) - expect(await listedSurfaces(runtime)).toEqual([`tab::${LEFT}:ready`]) - }) -}) - -// Phone closes one SSH tab before a relaunched sibling registers. -const SSH_PTY_X = 'ssh:ssh-1@@pty-x' -const SSH_PTY_Y = 'ssh:ssh-1@@pty-y' - -function makeSshSession(tabIds: readonly ('tab-x' | 'tab-y')[]): WorkspaceSessionState { - // The unbound relaunched tab-x has no persisted relay binding yet. - const specs = { - 'tab-x': { leafId: LEFT, ptyId: null }, - 'tab-y': { leafId: RIGHT, ptyId: SSH_PTY_Y } - } - return { - ...getDefaultWorkspaceSession(), - tabsByWorktree: { - [WORKTREE_ID]: tabIds.map((id, index) => ({ - id, - ptyId: specs[id].ptyId, - worktreeId: WORKTREE_ID, - title: id, - customTitle: null, - color: null, - sortOrder: index, - createdAt: index + 1 - })) - }, - terminalLayoutsByTabId: Object.fromEntries( - tabIds.map((id) => [ - id, - { - root: { type: 'leaf' as const, leafId: specs[id].leafId }, - activeLeafId: specs[id].leafId, - expandedLeafId: null, - ptyIdsByLeafId: specs[id].ptyId ? { [specs[id].leafId]: specs[id].ptyId } : {} - } - ]) - ), - terminalTopologyRevisionByRepoId: { [REPO_ID]: 2 } - } -} - -function publishSshRendererFrame(runtime: OrcaRuntimeService): void { - const tabs = [ - { tabId: 'tab-x', leafId: LEFT, ptyId: SSH_PTY_X }, - { tabId: 'tab-y', leafId: RIGHT, ptyId: SSH_PTY_Y } - ] - runtime.syncWindowGraph(1, { - tabs: tabs.map(({ tabId, leafId }) => ({ - tabId, - worktreeId: WORKTREE_ID, - title: tabId, - activeLeafId: leafId, - layout: { type: 'leaf' as const, leafId } - })), - leaves: [], - mobileSessionTabs: [ - { - worktree: WORKTREE_ID, - publicationEpoch: 'renderer', - snapshotVersion: 1, - activeGroupId: 'group', - activeTabId: `tab-y::${RIGHT}`, - activeTabType: 'terminal', - tabGroups: [{ id: 'group', activeTabId: 'tab-y', tabOrder: ['tab-x', 'tab-y'] }], - tabs: tabs.map(({ tabId, leafId, ptyId }) => ({ - type: 'terminal' as const, - id: `${tabId}::${leafId}`, - parentTabId: tabId, - leafId, - ptyId, - title: tabId, - isActive: tabId === 'tab-y' - })) - } - ] - }) -} - -describe('a surface the host retired stays retired when a restored sibling registers', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('keeps a phone-closed SSH terminal closed while its remote PTY is still exiting', async () => { - const { runtime, sessions } = coldRestoredRuntime(SSH_HOST) - sessions.set(SSH_HOST.hostId, makeSshSession(['tab-x', 'tab-y'])) - const kill = vi.fn(() => true) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the close path uses only these two relays. - runtime.setNotifier({ - closeTerminal: vi.fn(), - // Renderer persistence commits before its pruned frame arrives. - closeTerminalTab: vi.fn(async () => { - sessions.set(SSH_HOST.hostId, makeSshSession(['tab-x'])) - }) - } as never) - runtime.setPtyController({ - write: () => true, - kill, - listProcesses: vi.fn(async () => - [SSH_PTY_X, SSH_PTY_Y].map((id) => ({ id, cwd: '/worktree', title: 'shell' })) - ), - getForegroundProcess: async () => null - }) - publishSshRendererFrame(runtime) - registerBound(runtime, SSH_HOST.hostId, SSH_PTY_Y, 'ssh-1', { - tabId: 'tab-y', - leafId: RIGHT, - incarnationId: 'incarnation-y' - }) - expect(await listedSurfaces(runtime)).toContain(`tab-y::${RIGHT}:ready`) - - await runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, 'tab-y', { reason: 'user' }) - expect(kill).toHaveBeenCalledWith(SSH_PTY_Y) - registerBound(runtime, SSH_HOST.hostId, SSH_PTY_X, 'ssh-1', { - tabId: 'tab-x', - leafId: LEFT, - incarnationId: 'incarnation-x' - }) - - expect(await listedSurfaces(runtime)).not.toContain(`tab-y::${RIGHT}:ready`) - }) - - it('keeps a phone-closed chat tab closed', async () => { - const { runtime } = coldRestoredRuntime() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the chat close path uses only this relay. - runtime.setNotifier({ closeSessionTab: vi.fn(async () => {}) } as never) - publishRendererFrame( - runtime, - makeRendererFrame(LOCAL_HOST, { - extraTabs: [ - { - type: 'agent-session', - id: 'chat', - title: 'Chat', - sessionId: 'session-chat', - agent: 'claude', - isActive: false - } - ] - }) - ) - expect(await listedSurfaces(runtime)).toContain('chat:') - - await runtime.closeMobileSessionTab(`id:${WORKTREE_ID}`, 'chat', { reason: 'user' }) - registerLeaf(runtime, LOCAL_HOST, 'left') - - expect(await listedSurfaces(runtime)).not.toContain('chat:') - }) -}) - -// Paired create has registered/published, but the desktop frame still lacks it; preserve this in-flight tab. -const PHONE_LEAF = '33333333-3333-4333-8333-333333333333' - -async function runtimeWithUnpublishedPhoneCreate(): Promise { - const { runtime } = coldRestoredRuntime() - const handlers = new Map void>() - const webContents = { - isDestroyed: () => false, - setBackgroundThrottling: () => {}, - capturePage: async () => null, - send: (channel: string, payload: { requestId: string }) => { - if (channel !== 'terminal:requestTabCreate') { - return - } - registerBound(runtime, LOCAL_EXECUTION_HOST_ID, 'pty-phone', null, { - tabId: 'tab-phone', - leafId: PHONE_LEAF, - incarnationId: 'incarnation-phone' - }) - handlers.get('terminal:tabCreateReply')?.( - { sender: webContents }, - { requestId: payload.requestId, tabId: 'tab-phone', title: 'Terminal' } - ) - } - } - setRuntimeDesktopSurface({ - showNotification: () => false, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path reads only liveness and these webContents members off its authoritative window. - findWindowById: () => ({ isDestroyed: () => false, webContents }) as never, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the tab-create reply channel is registered on this path. - onIpc: (channel, listener) => handlers.set(channel, listener as never), - removeIpcListener: (channel) => handlers.delete(channel) - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create path focuses only when activating, which this create does not. - runtime.setNotifier({ focusTerminal: vi.fn() } as never) - Object.assign(runtime, { - resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({ - id: WORKTREE_ID, - path: '/worktree', - connectionId: null, - repo: LOCAL_HOST.repo, - folderWorkspace: null - })) - }) - publishRendererFrame(runtime, makeRendererFrame(LOCAL_HOST)) - await runtime.createMobileSessionTerminal(`id:${WORKTREE_ID}`, { - activate: false, - clientNavigationId: 'phone' - }) - return runtime -} - -describe('a surface the host added stays listed when a restored sibling registers', () => { - afterEach(() => setRuntimeDesktopSurface(null)) - - it('keeps a phone-created terminal listed', async () => { - const runtime = await runtimeWithUnpublishedPhoneCreate() - expect(await listedSurfaces(runtime)).toContain(`tab-phone::${PHONE_LEAF}:ready`) - - registerLeaf(runtime, LOCAL_HOST, 'left') - - expect(await listedSurfaces(runtime)).toContain(`tab-phone::${PHONE_LEAF}:ready`) - }) -}) diff --git a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts index b9add9059b7..33036d33c4f 100644 --- a/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts +++ b/src/main/runtime/terminal/surface/orca-runtime-terminal-close-records.test.ts @@ -19,7 +19,7 @@ import { WORKTREE_PATH, makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const SSH_REPO_ID = 'ssh-repo' const SSH_HOST_ID = 'ssh:target-1' diff --git a/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts b/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts index 78e4f1220b1..9de1fedbc9f 100644 --- a/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts +++ b/src/main/runtime/terminal/surface/orca-runtime-terminal-surface-close.test.ts @@ -23,12 +23,9 @@ import { makeSession } from '../../__fixtures__/orca-runtime-terminal-close-continuity-state-fixture' import { createHarness } from '../../__fixtures__/orca-runtime-terminal-close-continuity-fixtures' -import { expectDesktopDropsPane } from '../../__fixtures__/main-layout-close-fixture' -import { - retireTerminalSurfaceFromPersistence, - sanitizeWorkspaceSessionTerminalRetirements -} from './mobile-session-terminal-persistence-retirement' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import '../../__fixtures__/main-layout-close-fixture' +import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' const splitLayout = { root: { @@ -124,18 +121,6 @@ function rendererSaveWithout( } describe('renderer close intents', () => { - it('keeps a closed tab closed across a renderer save and a reload', async () => { - const { store, runtime, reload } = createPersistedRuntime(makeSession()) - - await runtime.closeTerminalSurfaceFromRenderer({ - worktreeId: WORKTREE_ID, - target: { kind: 'tab', tabId: TAB_ID } - }) - store.setWorkspaceSession(rendererSaveWithout(store.getWorkspaceSession())) - - expect((await reload()).tabsByWorktree[WORKTREE_ID]).toEqual([]) - }) - it('keeps a closed split pane closed across a renderer save and a reload', async () => { const { store, runtime, reload } = createPersistedRuntime(splitSession()) @@ -183,46 +168,6 @@ describe('renderer close intents', () => { }) describe('CLI close of one pane in a split tab', () => { - it.each([ - ['reports no exit', false], - ['throws, as an unreachable SSH host does', new Error('ssh_host_unreachable')] - ] as const)( - 'closes only that pane, never the live sibling, when its stop %s', - async (_case, stopResult) => { - const harness = createHarness({ publishMobileSurface: true, registerPtyBacked: true }) - harness.syncSplitFixtureGraph() - harness.syncFixtureTabWithoutLeaf() - harness.setVerifiedStopResult(stopResult) - // Honor erroneous tab close so widening destroys the sibling and fails visibly. - harness.setCloseTerminalTabAction(() => harness.retirePersistedTab()) - const terminal = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals.find( - (candidate) => candidate.ptyId === PTY_ID - )! - - const receipt = await harness.runtime.closeTerminal(terminal.handle) - - const saved = sanitizeWorkspaceSessionTerminalRetirements( - { ...harness.getSession(), terminalLayoutsByTabId: { [TAB_ID]: splitLayout } }, - harness.getSession() - ) - expect(saved.tabsByWorktree[WORKTREE_ID]).toEqual([expect.objectContaining({ id: TAB_ID })]) - expect(saved.terminalLayoutsByTabId[TAB_ID]?.root).toEqual({ - type: 'leaf', - leafId: SIBLING_LEAF_ID - }) - expectDesktopDropsPane(harness, TAB_ID, LEAF_ID) - expect(harness.closeTerminalTab).not.toHaveBeenCalled() - // Controller kill also records pending SSH stops; it must still run. - expect(harness.kill).toHaveBeenCalledWith(PTY_ID) - expect(harness.kill).not.toHaveBeenCalledWith(SIBLING_PTY_ID) - expect(receipt).toMatchObject({ - tabId: TAB_ID, - ptyKilled: false, - ptyStopVerdict: 'unverifiable' - }) - } - ) - // L255: expected main-owned headless pane-close failure until its fix lands. it('keeps the sibling when the stop delivers the exit before the pane commit', async () => { diff --git a/src/main/runtime/terminal/surface/terminal-surface-close.ts b/src/main/runtime/terminal/surface/terminal-surface-close.ts index bde21115a65..4a3273f1e9a 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-close.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-close.ts @@ -14,7 +14,7 @@ import { type WorkspaceSessionTerminalTabCloseResult } from '../../../../shared/workspace-session/workspace-session-terminal-tab-close' import { retireTerminalSurfaceFromPersistence } from './mobile-session-terminal-persistence-retirement' -import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/terminal-topology-membership' +import { advanceTerminalTopologyRevision } from '../../../persistence/terminal-topology/pane-ownership/terminal-topology-membership' import type { DurableProfileStateMutation } from '../../../persistence/loading-store/store-runtime-state' import type { ExecutionHostId } from '../../../../shared/execution-host' import { diff --git a/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts b/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts index 1f6342333e9..092cc3142ae 100644 --- a/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts +++ b/src/main/runtime/terminal/surface/terminal-surface-replies.test-fixture.ts @@ -17,7 +17,7 @@ import type { RuntimeTerminalShow } from '../../../../shared/runtime-terminal-co import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { LayoutCommand } from '../../../../shared/workspace-layout/workspace-layout-command-types' -import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission' +import { applyCommandToSession } from '../../../persistence/terminal-topology/pane-admission/terminal-pane-admission' import { partialRuntimeStore } from '../../orca-runtime-tests/runtime-store-partial-fixture' export const SURFACE_TAB_ID = '44444444-4444-4444-8444-444444444444' diff --git a/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts b/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts index 3aaa3a4e3ff..52b7714a1db 100644 --- a/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts +++ b/src/main/runtime/terminal/surface/workspace-layout-operation-frames.test.ts @@ -9,12 +9,12 @@ import type { ExecutionHostId } from '../../../../shared/execution-host' import type { GeneratedTabTitle } from '../../../../shared/workspace-layout/workspace-layout-command-types' import type { Store } from '../../../persistence/loading-store/store' -import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/testing/terminal-topology-window-session-fixture' import { emptyTerminalSessionProfile, FIXTURE_GIT_WORKTREE_ID as GIT, openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +} from '../../../persistence/terminal-topology/testing/terminal-topology-profile-fixture' import { applyWindowLayoutCommand } from '../layout/runtime-layout-apply' import { installLayoutFrameModelCheck } from './workspace-layout-frame-model-check.test-fixture' import './workspace-layout-stream' 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[] = [] 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/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts b/src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts deleted file mode 100644 index f707f8d6e24..00000000000 --- a/src/main/runtime/workspaces/persisted-surfaces/live-terminal-placement-before-initial-tab.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it, vi } from 'vitest' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { OrcaRuntimeService } from '../../orca-runtime' -import { FIRST_SURFACE_PLACEMENT_WAIT_MS } from './restored-terminal-placement' -import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) - -// Activation must await main's in-flight placement census so the existing live terminal becomes the first tab without an extra shell. - -const WT = FIXTURE_GIT_WORKTREE_ID -const LIVE_PTY = `${WT}@@live` -const WINDOW_TAB = '33333333-3333-4333-8333-333333333333' -const WINDOW_LEAF = '44444444-4444-4444-8444-444444444444' -const directories: string[] = [] - -class CensusRuntime extends OrcaRuntimeService { - protected override async getResolvedWorktreeMap(): Promise> { - const worktree = this.buildResolvedWorktreeFromId(WT) - return new Map(worktree ? [[WT, worktree]] : []) - } -} - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -async function hostPlacingALiveTerminal() { - const directory = mkdtempSync(join(tmpdir(), 'orca-placement-before-initial-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - const live = [{ id: LIVE_PTY, cwd: '/fixture/local', title: 'zsh', worktreeId: WT }] - let answerCensus = (): void => {} - const census = new Promise((resolve) => { - answerCensus = () => resolve(live) - }) - const listProcesses = vi.fn(() => census) - const spawn = vi.fn() - const runtime = new CensusRuntime(store) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses - }) - const placing = runtime.placeUnshownLiveTerminals() - await vi.waitFor(() => expect(listProcesses).toHaveBeenCalled()) - const activate = () => - runtime.applyLayoutCommand({ - type: 'createTerminalTab', - workspace: WT, - tabId: WINDOW_TAB, - leafId: WINDOW_LEAF, - initial: 'activation' - }) - const tabsOf = () => store.getWorkspaceSession().tabsByWorktree[WT] ?? [] - return { store, spawn, placing, answerCensus, activate, tabsOf } -} - -it("gives an activating workspace no fresh shell beside a live terminal main's placement is still placing", async () => { - const { store, spawn, placing, answerCensus, activate, tabsOf } = await hostPlacingALiveTerminal() - - const activation = activate() - answerCensus() - await placing - const reply = await activation - - const tabs = tabsOf() - expect(tabs).toHaveLength(1) - expect( - Object.values( - store.getWorkspaceSession().terminalLayoutsByTabId[tabs[0]!.id]?.ptyIdsByLeafId ?? {} - ) - ).toEqual([LIVE_PTY]) - expect(reply.ok && reply.result.tabId).toBeFalsy() - expect(spawn).not.toHaveBeenCalled() -}) - -it('admits the first tab once the cap passes while the placement pass is still reading the census', async () => { - const { placing, answerCensus, activate, tabsOf } = await hostPlacingALiveTerminal() - - const startedAt = performance.now() - const reply = await activate() - const waitedMs = performance.now() - startedAt - - expect(waitedMs).toBeGreaterThanOrEqual(FIRST_SURFACE_PLACEMENT_WAIT_MS - 20) - expect(waitedMs).toBeLessThan(FIRST_SURFACE_PLACEMENT_WAIT_MS + 1_000) - expect(reply.ok && reply.result.tabId).toBe(WINDOW_TAB) - expect(tabsOf().map((tab) => tab.id)).toEqual([WINDOW_TAB]) - answerCensus() - await placing -}) diff --git a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts deleted file mode 100644 index 10e19b330d0..00000000000 --- a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { Store } from '../../../persistence/loading-store/store' -import { - emptyTerminalSessionProfile, - FIXTURE_GIT_WORKTREE_ID, - openTopologyStore, - reopenTopologyStore -} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' -import { OrcaRuntimeService } from '../../orca-runtime' -import type { ResolvedWorktree } from '../catalog/runtime-worktree-path-identity' -import { TERMINAL_QUERY_METHODS } from '../../rpc/methods/terminal/terminal-query-methods' - -vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) -vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) - -// A window sweep must let main place only that workspace's unshown live terminals before listing them. - -const SWEPT = FIXTURE_GIT_WORKTREE_ID -const OTHER = 'repo-local::/fixture/other' -const directories: string[] = [] - -type LiveSession = { - id: string - cwd: string - title: string - worktreeId: string - incarnationId?: string - exiting?: true -} - -class SweepRuntime extends OrcaRuntimeService { - protected override async getResolvedWorktreeMap(): Promise> { - return new Map( - [SWEPT, OTHER].flatMap((id) => { - const worktree = this.buildResolvedWorktreeFromId(id) - return worktree ? [[id, worktree] as const] : [] - }) - ) - } - - ptyRecord(ptyId: string) { - return this.ptysById.get(ptyId) - } -} - -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -function session(id: string, worktreeId = SWEPT): LiveSession { - return { id, cwd: '/fixture/local', title: 'zsh', worktreeId, incarnationId: `${id}-inc` } -} - -function runtimeOn(store: Store, live: LiveSession[]): SweepRuntime { - const runtime = new SweepRuntime(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [...live], - listProcessesWithHostScope: async () => ({ processes: [...live], hostIds: ['local' as const] }) - }) - return runtime -} - -async function hostWith(live: LiveSession[]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-sweep-placement-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - return { store, directory, runtime: runtimeOn(store, live) } -} - -function boundPtyIds(store: Store, worktreeId: string): string[] { - const session = store.getWorkspaceSession() - return (session.tabsByWorktree[worktreeId] ?? []).flatMap((tab) => - Object.values(session.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {}) - ) -} - -function terminalListHandler() { - const method = TERMINAL_QUERY_METHODS.find((candidate) => candidate.name === 'terminal.list') - if (!method) { - throw new Error('terminal.list is not defined') - } - return method.handler -} - -describe('main places the swept workspace’s live terminals, layout-owner build', () => { - it('shows the swept workspace’s unshown terminal in a tab, and leaves another workspace’s', async () => { - const { store, runtime } = await hostWith([session('pty-swept'), session('pty-other', OTHER)]) - - await runtime.placeUnshownLiveTerminalsOf(`id:${SWEPT}`) - - expect(boundPtyIds(store, SWEPT)).toEqual(['pty-swept']) - expect(boundPtyIds(store, OTHER)).toEqual([]) - }) - - it('the sweep’s listing places before it lists, so it names the placed terminal’s pane', async () => { - const { runtime } = await hostWith([session('pty-swept')]) - - const context = { runtime } - const listing = await terminalListHandler()( - { - worktree: `id:${SWEPT}`, - limit: 200, - requireFreshPtyLiveness: true, - includeVisualLayouts: false, - placeUnshownLiveTerminals: true - }, - context - ) - - const listed = listing.terminals.find((terminal) => terminal.ptyId === 'pty-swept') - expect(listed).toMatchObject({ orphaned: false }) - expect(listed?.tabId).not.toMatch(/^pty:/) - }) - - it('leaves a terminal whose registration is still binding its pane, as a census does', async () => { - const { store, runtime } = await hostWith([session('pty-registering')]) - runtime.beginPtyRegistration('pty-registering', 'pty-registering-inc') - - await runtime.placeUnshownLiveTerminals() - - expect(boundPtyIds(store, SWEPT)).toEqual([]) - }) - - it('never brings back a closed tab’s terminal its host is killing', async () => { - const { store, runtime } = await hostWith([{ ...session('pty-closing'), exiting: true }]) - - await runtime.placeUnshownLiveTerminals() - - expect(boundPtyIds(store, SWEPT)).toEqual([]) - }) -}) - -describe('a terminal created by the CLI, across a restart, layout-owner build', () => { - it('is left alone while its run owns it, and after a restart is shown like any other', async () => { - const live = [session('pty-cli')] - const { store, directory, runtime } = await hostWith(live) - // The census records it; the CLI's create marks it owned by this run (terminal-create.ts). - await runtime.listTerminals(`id:${SWEPT}`) - runtime.ptyRecord('pty-cli')!.runtimeSessionOwned = true - - await runtime.placeUnshownLiveTerminals() - expect(boundPtyIds(store, SWEPT)).toEqual([]) - - // Run ownership is not saved; after restart, main must place the surviving unshown terminal as the window-owned sweep would. - const relaunched = await reopenTopologyStore(store, directory) - const restarted = runtimeOn(relaunched, live) - await restarted.placeUnshownLiveTerminals() - - expect(restarted.ptyRecord('pty-cli')?.runtimeSessionOwned).toBe(false) - expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) - }) - - it('one whose pane was saved stays in that pane after a restart, with no second tab', async () => { - const live = [session('pty-cli')] - const { store, directory, runtime } = await hostWith(live) - await runtime.placeUnshownLiveTerminals() - expect(boundPtyIds(store, SWEPT)).toEqual(['pty-cli']) - - const relaunched = await reopenTopologyStore(store, directory) - await runtimeOn(relaunched, live).placeUnshownLiveTerminals() - - expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) - }) -}) 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/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/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/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' +} diff --git a/src/main/speech/dictation-cleanup-service.ts b/src/main/speech/dictation-cleanup-service.ts new file mode 100644 index 00000000000..6ae234774e9 --- /dev/null +++ b/src/main/speech/dictation-cleanup-service.ts @@ -0,0 +1,105 @@ +import { mkdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + DICTATION_CLEANUP_TIMEOUT_MS, + isDictationCleanupOn, + type DictationCleanupResult +} from '../../shared/dictation-cleanup' +import type { DictationTerm } from '../../shared/dictation-dictionary' +import type { VoiceSettings } from '../../shared/speech-types' +import { getCommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' +import { + prepareLocalCommitMessageAgentEnv, + type CommitMessageAgentEnvironmentResolvers +} from '../text-generation/commit-message-agent-environment' +import { resolveTextGenerationParams } from '../text-generation/commit-message-text-generation' +import { generateDictationCleanup } from '../text-generation/dictation-cleanup-generation-request' +import { cancelLocalGeneration } from '../text-generation/source-control-generation-lanes' + +export type DictationCleanupDeps = { + getSettings: () => Parameters[0] & { voice?: VoiceSettings } + getAgentEnvResolvers: () => CommitMessageAgentEnvironmentResolvers | undefined +} + +const skipsByRequest = new Map void>() + +export function cancelDictationCleanup(requestId: string): void { + skipsByRequest.get(requestId)?.() +} + +// One folder for every run, so the agent reads no project and keeps one history bucket, not one per dictation. +const cleanupFolder = (): string => join(tmpdir(), 'orca-dictation-cleanup') + +/** Runs the user's agent on dictated text, on this computer, in an empty folder of its own. */ +export async function cleanUpDictatedText( + input: { text: string; terms: readonly DictationTerm[]; requestId?: string }, + deps: DictationCleanupDeps +): Promise { + const settings = deps.getSettings() + if (!input.text.trim() || !isDictationCleanupOn(settings)) { + return { status: 'off' } + } + const startedAt = Date.now() + const stop = Promise.withResolvers<'timed-out' | 'canceled'>() + const timer = setTimeout(() => stop.resolve('timed-out'), DICTATION_CLEANUP_TIMEOUT_MS) + if (input.requestId) { + skipsByRequest.set(input.requestId, () => stop.resolve('canceled')) + } + let stopped = false + const cwd = cleanupFolder() + try { + const resolved = resolveTextGenerationParams(settings, undefined, 'dictationCleanup') + if (!resolved.ok) { + return { status: 'failed', reason: resolved.error } + } + const { params } = resolved + const prepared = await Promise.race([ + prepareLocalCommitMessageAgentEnv(params.agentId, deps.getAgentEnvResolvers()), + stop.promise + ]) + if (typeof prepared === 'string') { + return { status: prepared } + } + if (!prepared.ok) { + return { status: 'failed', reason: prepared.error } + } + await mkdir(cwd, { recursive: true }) + const generation = generateDictationCleanup({ + text: input.text, + voice: settings.voice, + terms: input.terms, + params, + target: { kind: 'local', cwd, ...(prepared.env ? { env: prepared.env } : {}) } + }) + const outcome = await Promise.race([generation, stop.promise]) + if (typeof outcome === 'string') { + stopped = true + return { status: outcome } + } + if (!outcome.success) { + return outcome.canceled ? { status: 'canceled' } : { status: 'failed', reason: outcome.error } + } + return { + status: 'cleaned', + text: outcome.text, + agentLabel: outcome.agentLabel ?? params.agentId, + model: + (params.agentId !== 'custom' && + getCommitMessageModel(params.agentId, params.model)?.label) || + params.model, + elapsedMs: Date.now() - startedAt + } + } catch (error) { + return { status: 'failed', reason: error instanceof Error ? error.message : String(error) } + } finally { + clearTimeout(timer) + if (input.requestId) { + skipsByRequest.delete(input.requestId) + } + // Stops the agent still running after a timeout or a skip. + if (stopped) { + cancelLocalGeneration('dictation-cleanup', cwd) + } + } +} diff --git a/src/main/speech/model-catalog.ts b/src/main/speech/model-catalog.ts index e8a315a5c27..8a2d3b44124 100644 --- a/src/main/speech/model-catalog.ts +++ b/src/main/speech/model-catalog.ts @@ -180,8 +180,7 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [ ...getSpeechModelErrorRates('nemotron-3.5-asr-streaming-0.6b'), licence: 'OpenMDW-1.1', sampleRate: 16000, - // Decoded per chunk for now; live text arrives with the streaming engine path. - streaming: false + streaming: true }, { id: 'openai-gpt-transcribe', diff --git a/src/main/speech/stt-live-decode.test.ts b/src/main/speech/stt-live-decode.test.ts new file mode 100644 index 00000000000..dcd8d97c00d --- /dev/null +++ b/src/main/speech/stt-live-decode.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import type * as TranscribeCpp from 'transcribe-cpp' +import { LiveDecode } from './stt-live-decode' + +// One scripted decode step per feed: the text so far and how much audio (ms) the stream has decoded. +function fakeSession(steps: { text: string; decodedMs: number }[]) { + let step = -1 + const stream = { + feed: async () => { + step += 1 + return { resultChanged: true, audioCommittedMs: steps[step].decodedMs } + }, + finalize: async () => ({}), + get text() { + return { full: steps[step].text } + }, + reset: () => {} + } + const session = { + stream: async () => stream + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: LiveDecode calls only stream(), feed(), finalize(), text and reset(). + return session as unknown as TranscribeCpp.Session +} + +describe('LiveDecode', () => { + it('shows text as it grows and commits it once quiet, covering up to a second before the decode', async () => { + const session = fakeSession([ + { text: 'I have', decodedMs: 1120 }, + { text: 'I have two questions', decodedMs: 2240 }, + { text: 'I have two questions', decodedMs: 3360 }, + { text: 'I have two questions', decodedMs: 4480 }, + { text: 'I have two questions. First', decodedMs: 5600 } + ]) + const live = new LiveDecode(session, {}, 16000, null) + const feed = (index: number) => live.feed(new Float32Array(17920), 32000 + 17920 * (index + 1)) + + expect(await feed(0)).toEqual({ type: 'partial', text: 'I have' }) + expect(await feed(1)).toEqual({ type: 'partial', text: 'I have two questions' }) + expect(await feed(2)).toBeNull() + // Started at 32000 samples (2 s in); quiet from 2.24 s decoded, committed up to 3.48 s decoded. + expect(await feed(3)).toEqual({ + type: 'quiet', + text: 'I have two questions', + covered: 32000 + 55680 + }) + expect(await feed(4)).toEqual({ type: 'partial', text: '. First' }) + expect(await live.end(true)).toBe('. First') + }) +}) diff --git a/src/main/speech/stt-live-decode.ts b/src/main/speech/stt-live-decode.ts new file mode 100644 index 00000000000..541251cfe0f --- /dev/null +++ b/src/main/speech/stt-live-decode.ts @@ -0,0 +1,147 @@ +import type * as TranscribeCpp from 'transcribe-cpp' +import { SILENCE_PROBABILITY, type VadStream } from './stt-vad-pause-segmenter' + +// Commit once the text has not changed for twice this much decoded audio, covering all but this much: +// a CPU replay then starts in the quiet, clear of the last word posted and the next one. +const QUIET_MARGIN_MS = 1000 +// Silence this long sits between words, so a stream ended there cuts none in two. +const PAUSE_SECONDS = 0.15 + +export type LiveDecodeUpdate = + /** Text since the last commit, which may still change. */ + | { type: 'partial'; text: string } + /** The speaker went quiet: `text` is new since the last commit, and `covered` (stream position) accounts for it. */ + | { type: 'quiet'; text: string; covered: number } + +/** + * A streaming model's decode for one dictation, fed every chunk so its text keeps context across pauses. + * transcribe-cpp's own committed text stalls for good after the first sentence (0.4.1, Nemotron), so the + * text is committed here instead, when the speaker goes quiet; this model family never revises emitted text. + */ +export class LiveDecode { + private native: TranscribeCpp.Stream | null = null + /** Stream position (model-rate samples) where `native` began. */ + private from = 0 + private text = '' + /** Characters of `text` already committed. */ + private committed = 0 + /** How much audio `native` had decoded (ms) when its text last changed. */ + private changedAtMs = 0 + /** Silero frames of silence at the end of the audio so far. */ + private silentFrames = 0 + + private readonly pauseFrames: number + + /** Without Silero the stream is never known to be at a pause. */ + constructor( + private readonly session: TranscribeCpp.Session, + private readonly options: TranscribeCpp.StreamOptions, + private readonly modelRate: number, + private silero: { vad: VadStream; frameSamples: number } | null + ) { + this.pauseFrames = silero ? Math.ceil((PAUSE_SECONDS * modelRate) / silero.frameSamples) : 0 + } + + /** A running native stream holds the whole model; nothing else can decode until it ends. */ + get holdsModel(): boolean { + return this.native !== null + } + + /** The speaker is pausing, so ending the stream now cuts no word in two. */ + get atPause(): boolean { + return !!this.silero && this.silentFrames >= this.pauseFrames + } + + /** `position`: stream position (model-rate samples) at the end of `samples`. */ + async feed(samples: Float32Array, position: number): Promise { + // transcribe-cpp rejects an empty feed, and a phone can send one. + if (samples.length === 0) { + return null + } + if (!this.native) { + this.native = await this.session.stream(this.options) + this.from = position - samples.length + this.text = '' + this.committed = 0 + this.changedAtMs = 0 + } + await this.notePauses(samples) + const native = this.native + const update = await native.feed(samples).catch((error: unknown) => { + // A failed stream has let go of the model; the next feed starts a new one. + this.reset() + throw error + }) + const text = update.resultChanged ? native.text.full : this.text + if (text !== this.text) { + this.text = text + this.changedAtMs = update.audioCommittedMs + return { type: 'partial', text: text.slice(this.committed).trim() } + } + if (update.audioCommittedMs - this.changedAtMs < 2 * QUIET_MARGIN_MS) { + return null + } + const quietAt = update.audioCommittedMs - QUIET_MARGIN_MS + return { + type: 'quiet', + text: this.commit(), + covered: this.from + Math.round((quietAt * this.modelRate) / 1000) + } + } + + /** Ends the native stream, returning its uncommitted text, or null when none was running; the next feed starts another. */ + async end(finalize: boolean): Promise { + const native = this.native + if (!native) { + return null + } + this.native = null + try { + if (finalize) { + await native.finalize() + this.text = native.text.full + } + } finally { + native.reset() + } + return this.commit() + } + + private async notePauses(samples: Float32Array): Promise { + try { + for (const probability of (await this.silero?.vad.streamFeed(samples))?.probs ?? []) { + this.silentFrames = probability < SILENCE_PROBABILITY ? this.silentFrames + 1 : 0 + } + } catch (error) { + // Optional, as for pause-cut dictation: without it the stream restarts only at the hard bound. + console.warn('[speech] Silero VAD failed; this dictation restarts only at its bound:', error) + this.silero = null + } + } + + reset(): void { + this.native?.reset() + this.native = null + } + + private commit(): string { + const text = this.text.slice(this.committed).trim() + this.committed = this.text.length + return text + } +} + +/** Runs one decode step on silence, so the stream path's GPU pipelines compile before the first dictation. */ +export async function warmUpLiveDecode( + session: TranscribeCpp.Session, + options: TranscribeCpp.StreamOptions, + modelRate: number +): Promise { + const stream = await session.stream(options) + try { + // Longer than a streaming family's decode step (Nemotron's is 1.12 s). + await stream.feed(new Float32Array(Math.round(modelRate * 1.5))) + } finally { + stream.reset() + } +} diff --git a/src/main/speech/stt-offline-audio-chunker.ts b/src/main/speech/stt-offline-audio-chunker.ts index d34be24ec33..2ed0b531768 100644 --- a/src/main/speech/stt-offline-audio-chunker.ts +++ b/src/main/speech/stt-offline-audio-chunker.ts @@ -88,3 +88,38 @@ export class OfflineAudioChunker { return Math.max(1, bestIndex) } } + +// Without the detector, audio is still cut at the decode bound, just not at pauses. +export type AudioSegmenter = { + readonly heldSamples: number + readonly phraseOpen?: boolean + push(samples: Float32Array): Float32Array[] | Promise + flush(): Float32Array[] | Promise +} + +export function boundedChunks(sampleRate: number): AudioSegmenter { + const chunker = new OfflineAudioChunker(sampleRate) + return { + get heldSamples() { + return chunker.heldSamples + }, + push: (samples) => chunker.push(samples), + flush: () => { + const rest = chunker.flush() + return rest ? [rest] : [] + } + } +} + +export function joinAudio(parts: Float32Array[]): Float32Array { + if (parts.length === 1) { + return parts[0] + } + const joined = new Float32Array(parts.reduce((total, part) => total + part.length, 0)) + let offset = 0 + for (const part of parts) { + joined.set(part, offset) + offset += part.length + } + return joined +} diff --git a/src/main/speech/stt-recognizer.ts b/src/main/speech/stt-recognizer.ts index 667e3d6d719..d73b24a8030 100644 --- a/src/main/speech/stt-recognizer.ts +++ b/src/main/speech/stt-recognizer.ts @@ -11,9 +11,9 @@ export type SttRecognizerInit = { } export type SttRecognizerEvent = - /** One committed offline chunk; `samples` counts the stream's input-rate samples committed so far. */ + /** Newly committed text; `samples` counts the stream's input-rate samples it and earlier chunks account for. */ | { type: 'chunk'; streamId: string; text: string; samples: number } - /** The uncommitted phrases' live text so far; the next chunk replaces it. */ + /** The uncommitted text so far, which may still change; the next chunk replaces it. */ | { type: 'partial'; streamId: string; text: string } /** Pause-cut streams only: speech was heard whose text hasn't arrived yet. */ | { type: 'speech-pending'; streamId: string; pending: boolean } diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.test.ts b/src/main/speech/stt-transcribe-cpp-recognizer.test.ts new file mode 100644 index 00000000000..0f1eb33bbeb --- /dev/null +++ b/src/main/speech/stt-transcribe-cpp-recognizer.test.ts @@ -0,0 +1,190 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { SttRecognizer, SttRecognizerEvent } from './stt-recognizer' +import { createTranscribeCppRecognizer } from './stt-transcribe-cpp-recognizer' +import { installFakeTranscribeCpp } from './transcribe-cpp-fake.test-fixture' + +// 100 Hz audio in 0.1 s VAD frames. A sample's value names the word spoken there (1 = "one"), 0 is silence. +const RATE = 100 +const WORDS = ['', 'one', 'two', 'three', 'four', 'five'] + +const speech = (word: number, seconds: number, rate = RATE) => + new Float32Array(Math.round(seconds * rate)).fill(word) +const silence = (seconds: number, rate = RATE) => new Float32Array(Math.round(seconds * rate)) + +function audio(...parts: Float32Array[]): Float32Array { + const out = new Float32Array(parts.reduce((total, part) => total + part.length, 0)) + let offset = 0 + for (const part of parts) { + out.set(part, offset) + offset += part.length + } + return out +} + +// Like Parakeet, one decode is one sentence, so a phrase decoded alone ends in a full stop. +function sentence(pcm: Float32Array): string { + const words: string[] = [] + let last = 0 + for (const sample of pcm) { + const word = Math.round(sample) + if (word !== 0 && word !== last) { + words.push(WORDS[word]) + } + last = word + } + const text = words.join(' ') + return text ? `${text[0].toUpperCase()}${text.slice(1)}.` : '' +} + +let decode: (pcm: Float32Array) => string | Promise = sentence +let dispose: (() => void) | undefined + +afterEach(() => { + dispose?.() + dispose = undefined + decode = sentence +}) + +async function start(): Promise<{ recognizer: SttRecognizer; posted: SttRecognizerEvent[] }> { + const fake = installFakeTranscribeCpp({ + sampleRate: RATE, + vadFrameSamples: 10, + speechProbability: (frame) => (frame.some((sample) => Math.round(sample) !== 0) ? 0.9 : 0), + transcribe: (pcm) => decode(pcm) + }) + dispose = fake.dispose + const posted: SttRecognizerEvent[] = [] + const recognizer = await createTranscribeCppRecognizer( + { + speechModulesDir: fake.speechModulesDir, + modelDir: '/models/parakeet', + files: ['model.gguf'], + sampleRate: 16000, + vadModelPath: '/models/silero-vad.gguf' + }, + (event) => posted.push(event) + ) + recognizer.open('s', []) + return { recognizer, posted } +} + +type Transcript = ({ partial: string } | { chunk: string; samples: number })[] + +// Text and coverage only; loading and speech-pending events are other behaviour. +const transcript = (posted: SttRecognizerEvent[]): Transcript => + posted.flatMap((event) => + event.type === 'partial' + ? [{ partial: event.text }] + : event.type === 'chunk' + ? [{ chunk: event.text, samples: event.samples }] + : [] + ) + +describe('createTranscribeCppRecognizer', () => { + it('shows each phrase live at a pause and commits the span as one decode', async () => { + const { recognizer, posted } = await start() + await recognizer.feed('s', audio(speech(1, 2), silence(1), speech(2, 2), silence(1)), RATE) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { chunk: 'One two.', samples: 600 } + ]) + }) + + it('commits a single-phrase span with its live text, without decoding again', async () => { + const { recognizer, posted } = await start() + await recognizer.feed('s', audio(speech(1, 2), silence(1)), RATE) + decode = () => 'A second decode.' + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([{ partial: 'One.' }, { chunk: 'One.', samples: 300 }]) + }) + + it('commits once 20 s of audio waits, then starts a new span', async () => { + const { recognizer, posted } = await start() + for (const word of [1, 2, 3, 4, 5]) { + await recognizer.feed('s', audio(speech(word, 4), silence(1)), RATE) + } + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { partial: 'One. Two. Three.' }, + { partial: 'One. Two. Three. Four.' }, + // The pause's last 0.4 s is held as the next phrase's lead-in, so it isn't covered yet. + { chunk: 'One two three four.', samples: 1960 }, + { partial: 'Five.' }, + { chunk: 'Five.', samples: 2500 } + ]) + }) + + it('commits before a phrase that would take the span past 30 s', async () => { + const { recognizer, posted } = await start() + await recognizer.feed( + 's', + audio(speech(1, 12), silence(1), speech(2, 12), silence(1), speech(3, 12), silence(1)), + RATE + ) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + { partial: 'One.' }, + { partial: 'One. Two.' }, + { chunk: 'One two.', samples: 2560 }, + { partial: 'Three.' }, + { chunk: 'Three.', samples: 3900 } + ]) + }) + + it('reports coverage in fed input samples, through resampling and dropped silence', async () => { + const { recognizer, posted } = await start() + // 160 Hz in 161-sample feeds: each resamples to 101 samples, so the nominal 1.6 ratio would drift. + for (let feed = 0; feed < 6; feed += 1) { + await recognizer.feed('s', silence(161 / 160, 160), 160) + } + await recognizer.feed('s', audio(speech(1, 2, 160), silence(1, 160)), 160) + await recognizer.finish('s') + + expect(transcript(posted)).toEqual([ + // Over 5 s of silence: no text, but the host may drop that audio from its replay buffer. + { chunk: '', samples: 893 }, + { partial: 'One.' }, + { chunk: 'One.', samples: 1446 } + ]) + }) + + // The running decode finishes; nothing after it decodes or commits, though the 26 s fed is past the 20 s commit. + it.each<{ cancelDuring: string; expected: Transcript }>([ + { cancelDuring: 'One.', expected: [{ partial: 'One.' }] }, + { cancelDuring: 'Two.', expected: [{ partial: 'One.' }, { partial: 'One. Two.' }] } + ])('skips the rest of a stream canceled while decoding "$cancelDuring"', async (testCase) => { + const { recognizer, posted } = await start() + let decodeStarted!: () => void + const started = new Promise((resolve) => (decodeStarted = resolve)) + let releaseDecode!: () => void + const released = new Promise((resolve) => (releaseDecode = resolve)) + decode = async (pcm) => { + const text = sentence(pcm) + if (text === testCase.cancelDuring) { + decodeStarted() + await released + } + return text + } + const feeding = recognizer.feed( + 's', + audio(speech(1, 12), silence(1), speech(2, 12), silence(1)), + RATE + ) + await started + recognizer.cancel('s') + releaseDecode() + await feeding + recognizer.discard('s') + + expect(transcript(posted)).toEqual(testCase.expected) + }) +}) diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.ts b/src/main/speech/stt-transcribe-cpp-recognizer.ts index 26b3a793039..d0968dbb69b 100644 --- a/src/main/speech/stt-transcribe-cpp-recognizer.ts +++ b/src/main/speech/stt-transcribe-cpp-recognizer.ts @@ -4,8 +4,14 @@ import { pathToFileURL } from 'node:url' import type * as TranscribeCpp from 'transcribe-cpp' import { appendDictationText } from '../../shared/dictation-transcript-spacing' import { resampleToRate } from './stt-audio-resample' -import { OFFLINE_DECODE_CHUNK_SECONDS, OfflineAudioChunker } from './stt-offline-audio-chunker' -import { VadPauseSegmenter } from './stt-vad-pause-segmenter' +import { + type AudioSegmenter, + boundedChunks, + joinAudio, + OFFLINE_DECODE_CHUNK_SECONDS +} from './stt-offline-audio-chunker' +import { LiveDecode, warmUpLiveDecode } from './stt-live-decode' +import { loadSileroVad, VadPauseSegmenter } from './stt-vad-pause-segmenter' import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer' // Past ~8 threads decode slowed 2-4x under load in the 2026-11 benchmark; E-cores and SMT siblings @@ -15,31 +21,11 @@ function performanceCoreThreads(): number { return Math.min(logical, 8, Math.max(4, Math.floor(logical / 2))) } -// Without the detector, audio is still cut at the decode bound, just not at pauses. -type AudioSegmenter = { - readonly heldSamples: number - readonly phraseOpen?: boolean - push(samples: Float32Array): Float32Array[] | Promise - flush(): Float32Array[] | Promise -} - -function boundedChunks(sampleRate: number): AudioSegmenter { - const chunker = new OfflineAudioChunker(sampleRate) - return { - get heldSamples() { - return chunker.heldSamples - }, - push: (samples) => chunker.push(samples), - flush: () => { - const rest = chunker.flush() - return rest ? [rest] : [] - } - } -} - // Totals, not the nominal rate ratio: per-feed resampling rounds, and the drift would replay decoded audio. type StreamCoverage = { options: TranscribeCpp.TranscribeOptions + /** Streaming models only, unless another dictation already streams. */ + live: LiveDecode | null segmenter: AudioSegmenter vad: TranscribeCpp.VadSession | null inputSamples: number @@ -63,31 +49,8 @@ const SILENCE_COVERAGE_REPORT_SECONDS = 5 // The CPU fallback keeps uncommitted audio for a replay and takes over 30 s of it for a stalled GPU. const COMMIT_AFTER_SECONDS = 20 - -// Optional: without it dictation still works, with text only at the decode bound and at stop. -async function loadSileroVad( - transcribe: typeof TranscribeCpp, - path: string | undefined, - sampleRate: number -): Promise { - if (!path) { - return null - } - try { - // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. - const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) - if (model.vadInfo.sampleRate === sampleRate) { - return model - } - console.warn( - `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` - ) - model.dispose() - } catch (error) { - console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) - } - return null -} +// A live dictation with no quiet to commit at restarts its stream by then, at a pause if it can. +const LIVE_COMMIT_BY_SECONDS = 25 export async function createTranscribeCppRecognizer( init: SttRecognizerInit, @@ -127,10 +90,22 @@ export async function createTranscribeCppRecognizer( const vadModel = await loadSileroVad(transcribe, init.vadModelPath, modelRate) const streams = new Map() const openStream = (streamId: string, vocabulary: readonly string[]): StreamCoverage => { + // A dictation that starts beside a live one is pause-cut, so the two don't take the model from each other per feed. + const live = + model.capabilities.supportsStreaming && + ![...streams].some(([id, other]) => id !== streamId && other.live) // A VAD stream is per-dictation state, so each dictation gets its own session. const vad = vadModel?.createVadSession({ nThreads: 1 }) ?? null const stream: StreamCoverage = { options: streamOptions(vocabulary), + live: live + ? new LiveDecode( + session, + streamOptions(vocabulary), + modelRate, + vad && vadModel && { vad, frameSamples: vadModel.vadInfo.frameSamples } + ) + : null, segmenter: boundedChunks(modelRate), vad, inputSamples: 0, @@ -141,7 +116,7 @@ export async function createTranscribeCppRecognizer( speechPending: false, span: { audio: [], samples: 0, texts: [] } } - if (vad && vadModel) { + if (vad && vadModel && !live) { stream.segmenter = new VadPauseSegmenter( vad, modelRate, @@ -149,15 +124,28 @@ export async function createTranscribeCppRecognizer( () => stream.slowPhraseDecodes < SLOW_PHRASE_DECODES_BEFORE_NO_CUTS ) } - streams.get(streamId)?.vad?.dispose() + const replaced = streams.get(streamId) + if (replaced) { + dropStream(replaced) + } streams.set(streamId, stream) return stream } + const dropStream = (stream: StreamCoverage) => { + stream.vad?.dispose() + stream.live?.reset() + } + const transcribeChunk = async ( chunk: Float32Array, options: TranscribeCpp.TranscribeOptions ): Promise => { + // transcribe-cpp lets one native stream hold the model at a time. + const holder = [...streams].find(([, other]) => other.live?.holdsModel) + if (holder) { + await endLive(...holder) + } try { return (await session.run(chunk, options)).text } catch (error) { @@ -169,16 +157,13 @@ export async function createTranscribeCppRecognizer( } } - // The first run compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop. - await transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions) - // Stream position (model-rate samples) the segmenter has handed on, less chunks still waiting to be decoded. const position = (stream: StreamCoverage, undecoded: number) => stream.resampledSamples - stream.segmenter.heldSamples - undecoded - // Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay. - const report = (streamId: string, stream: StreamCoverage, text: string, undecoded: number) => { - const covered = position(stream, undecoded) + // `covered`: stream position (model-rate samples) the posted text accounts for. Reported in input-rate samples + // so the host can trim the audio it keeps for a CPU replay. + const report = (streamId: string, stream: StreamCoverage, text: string, covered: number) => { stream.reportedSamples = covered post({ type: 'chunk', @@ -204,7 +189,7 @@ export async function createTranscribeCppRecognizer( audio.length === 1 && texts.length === 1 ? texts[0] : (await transcribeChunk(joinAudio(audio), stream.options)).trim() - report(streamId, stream, text, undecoded) + report(streamId, stream, text, position(stream, undecoded)) } /** `live`: decode each phrase as it ends for live text; at stop only the commit decodes. */ @@ -244,7 +229,7 @@ export async function createTranscribeCppRecognizer( } const dropped = position(stream, 0) - stream.reportedSamples if (stream.span.samples === 0 && dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) { - report(streamId, stream, '', 0) + report(streamId, stream, '', position(stream, 0)) } } @@ -268,12 +253,50 @@ export async function createTranscribeCppRecognizer( } } + const feedLive = async ( + streamId: string, + stream: StreamCoverage, + live: LiveDecode, + samples: Float32Array + ) => { + if (canceled.has(streamId)) { + return + } + const update = await live.feed(samples, stream.resampledSamples) + if (update?.type === 'partial') { + post({ type: 'partial', streamId, text: update.text }) + } else if (update) { + const silence = + update.covered - stream.reportedSamples >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate + if (update.text || silence) { + report(streamId, stream, update.text, update.covered) + } + } + const held = (stream.resampledSamples - stream.reportedSamples) / modelRate + if (held >= LIVE_COMMIT_BY_SECONDS || (held >= COMMIT_AFTER_SECONDS && live.atPause)) { + await endLive(streamId, stream) + } + } + + // At stop, or when another dictation needs the model. + const endLive = async (streamId: string, stream: StreamCoverage) => { + const text = await stream.live?.end(!canceled.has(streamId)) + if (text != null && !canceled.has(streamId)) { + report(streamId, stream, text, stream.resampledSamples) + } + } + const closeStream = (streamId: string): StreamCoverage | undefined => { const stream = streams.get(streamId) streams.delete(streamId) return stream } + // The first decode compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop. + await (model.capabilities.supportsStreaming + ? warmUpLiveDecode(session, baseOptions, modelRate) + : transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions)) + return { open(streamId, vocabulary) { openStream(streamId, vocabulary) @@ -286,11 +309,18 @@ export async function createTranscribeCppRecognizer( ) stream.inputSamples += samples.length stream.resampledSamples += resampled.length + if (stream.live) { + await feedLive(streamId, stream, stream.live, resampled) + return + } const phrases = await stream.segmenter.push(resampled) // A cut phrase stays pending until its text is posted. notePendingSpeech(streamId, stream, phrases.length > 0 || !!stream.segmenter.phraseOpen) - await decode(streamId, stream, phrases, true) - notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen) + // Only beside a live dictation, whose native stream each decode ends, so this one decodes only to commit. + const phraseText = !model.capabilities.supportsStreaming + await decode(streamId, stream, phrases, phraseText) + const textless = !phraseText && stream.span.samples > 0 + notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen || textless) }, async finish(streamId) { const stream = closeStream(streamId) @@ -298,32 +328,26 @@ export async function createTranscribeCppRecognizer( return } try { + if (stream.live) { + await endLive(streamId, stream) + return + } await decode(streamId, stream, await stream.segmenter.flush(), false) await commit(streamId, stream, 0) notePendingSpeech(streamId, stream, false) } finally { - stream.vad?.dispose() + dropStream(stream) } }, discard(streamId) { canceled.delete(streamId) - closeStream(streamId)?.vad?.dispose() + const stream = closeStream(streamId) + if (stream) { + dropStream(stream) + } }, cancel(streamId) { canceled.add(streamId) } } } - -function joinAudio(parts: Float32Array[]): Float32Array { - if (parts.length === 1) { - return parts[0] - } - const joined = new Float32Array(parts.reduce((total, part) => total + part.length, 0)) - let offset = 0 - for (const part of parts) { - joined.set(part, offset) - offset += part.length - } - return joined -} diff --git a/src/main/speech/stt-vad-pause-segmenter.test.ts b/src/main/speech/stt-vad-pause-segmenter.test.ts index a5e8285fb1e..20a18f128fe 100644 --- a/src/main/speech/stt-vad-pause-segmenter.test.ts +++ b/src/main/speech/stt-vad-pause-segmenter.test.ts @@ -1,34 +1,12 @@ import { describe, expect, it } from 'vitest' -import { VadPauseSegmenter, type VadStream } from './stt-vad-pause-segmenter' +import { VadPauseSegmenter } from './stt-vad-pause-segmenter' +import { fakeVadSession } from './transcribe-cpp-fake.test-fixture' // 100 Hz audio in 10-sample (0.1 s) frames; each sample holds its frame's speech probability, so outputs show which frames survived. const RATE = 100 const FRAME = 10 -function fakeVad(): VadStream { - let pending: number[] = [] - let frames = 0 - const score = (flush: boolean) => { - const probs: number[] = [] - while (pending.length >= FRAME || (flush && pending.length > 0)) { - probs.push(pending[0]) - pending = pending.slice(FRAME) - } - const firstFrame = frames - frames = flush ? 0 : frames + probs.length - return { probs, firstFrame, segments: [] } - } - return { - streamFeed: async (pcm) => { - if (!(pcm instanceof Float32Array)) { - throw new Error('the segmenter feeds Float32Array') - } - pending.push(...pcm) - return score(false) - }, - streamFlush: async () => score(true) - } -} +const fakeVad = () => fakeVadSession(FRAME, (frame) => frame[0]) function audio(frames: number[]): Float32Array { return Float32Array.from(frames.flatMap((probability) => Array(FRAME).fill(probability))) diff --git a/src/main/speech/stt-vad-pause-segmenter.ts b/src/main/speech/stt-vad-pause-segmenter.ts index 04af6067957..e18c0d0e8a7 100644 --- a/src/main/speech/stt-vad-pause-segmenter.ts +++ b/src/main/speech/stt-vad-pause-segmenter.ts @@ -3,7 +3,7 @@ import { OfflineAudioChunker } from './stt-offline-audio-chunker' // Silero's own defaults: a frame at or above this is speech; inside speech, one below the second is silence. const SPEECH_PROBABILITY = 0.5 -const SILENCE_PROBABILITY = 0.35 +export const SILENCE_PROBABILITY = 0.35 // A pause this long ends the phrase before it, which then decodes for live text; every cut costs a decode. export const VAD_PAUSE_SECONDS = 0.6 // Silence kept ahead of detected speech so a soft first syllable isn't clipped. @@ -162,3 +162,28 @@ function concat(a: Float32Array, b: Float32Array): Float32Array { out.set(b, a.length) return out } + +// Optional: without it dictation still works, with text only at the decode bound and at stop. +export async function loadSileroVad( + transcribe: typeof TranscribeCpp, + path: string | undefined, + sampleRate: number +): Promise { + if (!path) { + return null + } + try { + // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. + const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) + if (model.vadInfo.sampleRate === sampleRate) { + return model + } + console.warn( + `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` + ) + model.dispose() + } catch (error) { + console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) + } + return null +} diff --git a/src/main/speech/transcribe-cpp-fake.test-fixture.ts b/src/main/speech/transcribe-cpp-fake.test-fixture.ts new file mode 100644 index 00000000000..2435685985a --- /dev/null +++ b/src/main/speech/transcribe-cpp-fake.test-fixture.ts @@ -0,0 +1,103 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { VadStream } from './stt-vad-pause-segmenter' + +export type FakeTranscribeEngine = { + /** The speech model's native rate; the VAD takes the same rate. */ + sampleRate: number + /** Samples per VAD probability. */ + vadFrameSamples: number + /** Speech probability of one VAD frame (the last one of a flush is zero padded). */ + speechProbability: (frame: Float32Array) => number + /** Text of one decode of this audio. */ + transcribe: (pcm: Float32Array) => string | Promise +} + +class OutputTruncated extends Error { + partialResult?: { text: string } +} + +/** A Silero VAD stream scoring each frame with `speechProbability`. */ +export function fakeVadSession( + frameSamples: number, + speechProbability: (frame: Float32Array) => number +): VadStream & { dispose: () => void } { + let pending: number[] = [] + let frames = 0 + const score = (flush: boolean) => { + const probs: number[] = [] + while (pending.length >= frameSamples || (flush && pending.length > 0)) { + const frame = new Float32Array(frameSamples) + frame.set(pending.slice(0, frameSamples)) + probs.push(speechProbability(frame)) + pending = pending.slice(frameSamples) + } + const firstFrame = frames + frames = flush ? 0 : frames + probs.length + return { probs, firstFrame, segments: [] } + } + return { + streamFeed: async (pcm) => { + if (!(pcm instanceof Float32Array)) { + throw new Error('the segmenter feeds Float32Array') + } + pending.push(...pcm) + return score(false) + }, + streamFlush: async () => score(true), + dispose: () => {} + } +} + +function fakeModel(engine: FakeTranscribeEngine) { + const languages: string[] = [] + return { + capabilities: { nativeSampleRate: engine.sampleRate, languages }, + vadInfo: { sampleRate: engine.sampleRate, frameSamples: engine.vadFrameSamples }, + supports: () => false, + createSession: () => ({ + run: async (pcm: Float32Array) => ({ text: await engine.transcribe(pcm) }) + }), + createVadSession: () => fakeVadSession(engine.vadFrameSamples, engine.speechProbability), + dispose: () => {} + } +} + +const MODULE_KEY = Symbol.for('orca.test.fakeTranscribeCpp') + +/** + * Writes a transcribe-cpp package backed by `engine` and returns the node_modules directory holding it, so the + * recognizer loads it the way it loads the real one. The package reads the engine from a global, which works + * whether the test runner transforms the file or Node loads it natively. + */ +export function installFakeTranscribeCpp(engine: FakeTranscribeEngine): { + speechModulesDir: string + dispose: () => void +} { + const speechModulesDir = mkdtempSync(join(tmpdir(), 'orca-fake-transcribe-cpp-')) + const dist = join(speechModulesDir, 'transcribe-cpp', 'dist') + mkdirSync(dist, { recursive: true }) + Reflect.set(globalThis, MODULE_KEY, { + initialize: async () => {}, + OutputTruncated, + TranscribeModel: { + // One model serves both roles: speech decodes and the Silero VAD. + load: async () => fakeModel(engine) + } + }) + writeFileSync(join(speechModulesDir, 'transcribe-cpp', 'package.json'), '{"type":"module"}\n') + writeFileSync( + join(dist, 'index.js'), + `const fake = globalThis[Symbol.for('orca.test.fakeTranscribeCpp')] +export const { initialize, OutputTruncated, TranscribeModel } = fake +` + ) + return { + speechModulesDir, + dispose: () => { + Reflect.deleteProperty(globalThis, MODULE_KEY) + rmSync(speechModulesDir, { recursive: true, force: true }) + } + } +} 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/text-generation/agent-generation-request.ts b/src/main/text-generation/agent-generation-request.ts index cb4eadb106e..4275bcb86bb 100644 --- a/src/main/text-generation/agent-generation-request.ts +++ b/src/main/text-generation/agent-generation-request.ts @@ -1,10 +1,7 @@ import { conversationNameTaskPrompt } from '../../shared/source-control/ai/generation/conversation-name-generation' import { textGenerationFailureCodeFields } from '../../shared/text-generation-failure-copy' import { runClaudeGenerationAttempts } from '../../shared/claude-background-run-isolation' -import { - cleanGeneratedCommitMessage, - stripPrefilledReasoningPreamble -} from '../../shared/source-control/ai/generation/commit-message-agent-output' +import { stripPrefilledReasoningPreamble } from '../../shared/source-control/ai/generation/commit-message-agent-output' import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' import { isCustomAgentId } from '../../shared/source-control/ai/generation/commit-message-agent-spec' import { @@ -16,7 +13,7 @@ import { openCodeVariantRetryPlan } from '../../shared/opencode-generation-comma import { copilotUnavailableModelRetryPlan } from './copilot-unavailable-model-retry' import { runLocalPlanForAgent } from './source-control-local-generation' import { runOpenCodeTextTask } from '../opencode/text-tasks/opencode-text-task' -import { emptyResultFailure } from './source-control-agent-failure' +import { cleanAgentAnswer, emptyResultFailure } from './source-control-agent-failure' import { runRemoteSourceControlPlan } from './source-control-remote-generation' import type { CommitMessageGenerationTarget, @@ -44,7 +41,8 @@ export async function runGenerationRequest(input: { }): Promise { const params = { ...input.params, - backslash: commandBackslashMode(input.target) + backslash: commandBackslashMode(input.target), + toolFree: input.operation === 'dictation-cleanup' } const prompt = input.operation === 'conversation-name' @@ -86,6 +84,13 @@ export async function runGenerationRequest(input: { if (attempt.strictMcp && !attempt.legacyToolPolicy) { return execute(plan) } + // Old CLIs can't deny MCP tools by pattern, so a tool-free task stops rather than load them. + if (params.toolFree && !attempt.strictMcp && attempt.legacyToolPolicy) { + return Promise.resolve({ + success: false, + error: 'This Claude CLI can’t run without tools under its MCP policy. Update Claude Code.' + }) + } const retry = planCommitMessageGeneration(params, prompt, attempt) return retry.ok ? execute(retry.plan) @@ -126,7 +131,7 @@ export async function runGenerationRequest(input: { if (answer === result.rawOutput) { return result } - const rawOutput = cleanGeneratedCommitMessage(answer) + const rawOutput = cleanAgentAnswer(answer, input.operation) return rawOutput ? { ...result, rawOutput } : { success: false, ...emptyResultFailure(input.operation, plan.label) } diff --git a/src/main/text-generation/dictation-cleanup-generation-request.ts b/src/main/text-generation/dictation-cleanup-generation-request.ts new file mode 100644 index 00000000000..7612a5f548e --- /dev/null +++ b/src/main/text-generation/dictation-cleanup-generation-request.ts @@ -0,0 +1,42 @@ +import { + buildDictationCleanupPrompt, + sanitizeDictationCleanupOutput +} from '../../shared/dictation-cleanup' +import type { DictationTerm } from '../../shared/dictation-dictionary' +import { renderSourceControlActionCommandTemplate } from '../../shared/source-control/ai/recipes/source-control-ai-actions' +import type { ResolvedSourceControlAiGenerationParams } from '../../shared/source-control/ai/source-control-ai-operation-resolution' +import type { VoiceSettings } from '../../shared/speech-types' +import { runGenerationRequest } from './agent-generation-request' +import { spawnSourceControlAgent } from './source-control-agent-launch' +import type { CommitMessageGenerationTarget } from './source-control-text-generation-types' + +export type GenerateDictationCleanupResult = + | { success: true; text: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + +export async function generateDictationCleanup(input: { + text: string + voice: VoiceSettings | undefined + terms: readonly DictationTerm[] + params: ResolvedSourceControlAiGenerationParams + target: CommitMessageGenerationTarget +}): Promise { + const basePrompt = buildDictationCleanupPrompt(input) + const result = await runGenerationRequest({ + params: input.params, + prompt: renderSourceControlActionCommandTemplate( + input.params.commandInputTemplate ?? '{basePrompt}', + { basePrompt } + ), + target: input.target, + operation: 'dictation-cleanup', + spawnAgent: spawnSourceControlAgent + }) + if (!result.success) { + return { success: false, error: result.error, canceled: result.canceled } + } + const text = sanitizeDictationCleanupOutput(result.rawOutput) + return text + ? { success: true, text, agentLabel: result.agentLabel } + : { success: false, error: `${result.agentLabel ?? input.params.agentId} returned no text.` } +} diff --git a/src/main/text-generation/source-control-agent-failure.ts b/src/main/text-generation/source-control-agent-failure.ts index 6a0aa9397dd..6fff7048b24 100644 --- a/src/main/text-generation/source-control-agent-failure.ts +++ b/src/main/text-generation/source-control-agent-failure.ts @@ -1,5 +1,5 @@ import { - cleanGeneratedCommitMessage, + cleanGeneratedText, excerptAgentFailureOutput, sanitizeAgentFailureDetail } from '../../shared/source-control/ai/generation/commit-message-agent-output' @@ -25,6 +25,18 @@ import { type TextGenerationFailureFields } from '../../shared/text-generation-failure-copy' +// Their stdout is a name or the user's own dictated words, not a diagnostic worth keeping in the error. +const OPERATIONS_WITHOUT_STDOUT_DETAIL: ReadonlySet = new Set([ + 'branch-name', + 'conversation-name', + 'dictation-cleanup' +]) + +/** The agent's answer without CLI framing; dictated text keeps the lines and markers Git text drops. */ +export function cleanAgentAnswer(raw: string, operation: TextGenerationOperation): string { + return cleanGeneratedText(raw, operation === 'dictation-cleanup' ? 'prose' : 'git') +} + type AgentCliFailureOptions = { includeLocalMacDnsHint?: boolean includeStdoutDetail?: boolean @@ -82,7 +94,8 @@ const EMPTY_RESULT_FAILURES = { const UNCODED_EMPTY_RESULT_NAMES = { 'branch-name': 'branch name', - 'conversation-name': 'chat name' + 'conversation-name': 'chat name', + 'dictation-cleanup': 'cleanup' } as const export function emptyResultFailure( @@ -90,7 +103,11 @@ export function emptyResultFailure( label: string, detail?: string | null ): TextGenerationFailureFields { - if (operation === 'branch-name' || operation === 'conversation-name') { + if ( + operation === 'branch-name' || + operation === 'conversation-name' || + operation === 'dictation-cleanup' + ) { // Background rename failures are stored as English rename errors, outside the coded result path. const name = UNCODED_EMPTY_RESULT_NAMES[operation] return { @@ -116,6 +133,11 @@ export function finalizeFromAgentOutput(args: { outputFormat?: CommitMessagePlan['outputFormat'] }): InternalTextGenerationResult { const { code, stdout, stderr, label } = args + const options = { + ...args, + includeStdoutDetail: + args.includeStdoutDetail ?? !OPERATIONS_WITHOUT_STDOUT_DETAIL.has(args.operation) + } const parsed = args.outputFormat === 'opencode-json' ? parseOpenCodeGenerationOutput(stdout) @@ -134,14 +156,14 @@ export function finalizeFromAgentOutput(args: { return { success: false, ...(args.outputFormat === 'kimi-stream-json' - ? formatKimiGenerationFailure(findKimiGenerationFailure(stdout), stderr, code, args) + ? formatKimiGenerationFailure(findKimiGenerationFailure(stdout), stderr, code, options) : agentCliFailure( label, stdout, // Orca's own parse failures (coded) say nothing about why the agent exited. parsed && !parsed.ok && parsed.errorCode === undefined ? parsed.error : stderr, code, - args + options )), failureOutput: captureFailureOutput(label, code, stdout, stderr) } @@ -158,7 +180,7 @@ export function finalizeFromAgentOutput(args: { failureOutput: captureFailureOutput(label, code, stdout, stderr) } } - const cleaned = cleanGeneratedCommitMessage(parsed?.ok ? parsed.text : stdout) + const cleaned = cleanAgentAnswer(parsed?.ok ? parsed.text : stdout, args.operation) if (cleaned) { return { success: true, rawOutput: cleaned, agentLabel: label } } diff --git a/src/main/text-generation/source-control-local-process.ts b/src/main/text-generation/source-control-local-process.ts index fe75e880b9d..db91e525792 100644 --- a/src/main/text-generation/source-control-local-process.ts +++ b/src/main/text-generation/source-control-local-process.ts @@ -238,8 +238,7 @@ export function runLocalSourceControlPlan( stderr, label: plan.label, outputFormat: plan.outputFormat, - operation, - includeStdoutDetail: operation !== 'branch-name' && operation !== 'conversation-name' + operation }) ) } diff --git a/src/main/text-generation/source-control-remote-generation.ts b/src/main/text-generation/source-control-remote-generation.ts index 6f734710f11..554bda8172d 100644 --- a/src/main/text-generation/source-control-remote-generation.ts +++ b/src/main/text-generation/source-control-remote-generation.ts @@ -70,7 +70,6 @@ export async function runRemoteSourceControlPlan(input: { label: plan.label, outputFormat: plan.outputFormat, operation, - includeLocalMacDnsHint: false, - includeStdoutDetail: operation !== 'branch-name' && operation !== 'conversation-name' + includeLocalMacDnsHint: false }) } diff --git a/src/main/text-generation/source-control-text-generation-types.ts b/src/main/text-generation/source-control-text-generation-types.ts index bf51fcd19b9..b42e40e0512 100644 --- a/src/main/text-generation/source-control-text-generation-types.ts +++ b/src/main/text-generation/source-control-text-generation-types.ts @@ -50,6 +50,7 @@ export type TextGenerationOperation = | 'branch-name' | 'jira-issue-summary' | 'conversation-name' + | 'dictation-cleanup' export type CommitMessageGenerationTarget = | { kind: 'local'; cwd: string; env?: NodeJS.ProcessEnv; wslDistro?: string } 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/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/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/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/src/preload/api/speech-api.ts b/src/preload/api/speech-api.ts index c7415932ba7..3120e6ec82e 100644 --- a/src/preload/api/speech-api.ts +++ b/src/preload/api/speech-api.ts @@ -1,4 +1,5 @@ import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' +import type { DictationCleanupResult } from '../../shared/dictation-cleanup' import type { DictationContext, OpenAiCompatibleSpeechProvider, @@ -38,6 +39,13 @@ export type SpeechApi = { stopDictation: (sessionId?: string) => Promise /** Drops the session's audio and any text it hasn't returned yet, without transcribing the rest. */ cancelDictation: (sessionId: string) => Promise + /** Absent in the paired web client: its host cleans up inside `speech.dictation.finish`. */ + cleanUpDictation?: ( + text: string, + context: DictationContext | undefined, + requestId: string + ) => Promise + cancelDictationCleanup?: (requestId: string) => Promise onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onFinalTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onSpeechPending: (callback: (data: SpeechPendingEvent) => void) => () => void diff --git a/src/preload/api/speech-bridge.ts b/src/preload/api/speech-bridge.ts index 66acdfc0bac..ee3eb951e4a 100644 --- a/src/preload/api/speech-bridge.ts +++ b/src/preload/api/speech-bridge.ts @@ -1,4 +1,5 @@ import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' +import type { DictationCleanupResult } from '../../shared/dictation-cleanup' import { ipcRenderer } from 'electron' import type { DictationContext, @@ -99,6 +100,14 @@ export const speechApi = { audioPorts.delete(sessionId) return ipcRenderer.invoke('speech:cancelDictation', sessionId) }, + cleanUpDictation: ( + text: string, + context: DictationContext | undefined, + requestId: string + ): Promise => + ipcRenderer.invoke('speech:cleanUpDictation', { text, context, requestId }), + cancelDictationCleanup: (requestId: string): Promise => + ipcRenderer.invoke('speech:cancelDictationCleanup', requestId), onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent, data: SpeechTranscriptEvent): void => diff --git a/src/preload/runtime-environment-subscriptions.test.ts b/src/preload/runtime-environment-subscriptions.test.ts deleted file mode 100644 index aaeef25d77d..00000000000 --- a/src/preload/runtime-environment-subscriptions.test.ts +++ /dev/null @@ -1,461 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - subscribeRuntimeEnvironmentFromPreload, - subscribeCrewAttemptFromPreload, - cancelRuntimeEnvironmentSubscriptionFromPreload -} from './runtime-environment-subscriptions' - -function deferred(): { - promise: Promise - resolve: (value: T) => void - reject: (error: unknown) => void -} { - let resolve!: (value: T) => void - let reject!: (error: unknown) => void - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve - reject = promiseReject - }) - return { promise, resolve, reject } -} - -type SubscriptionEvent = - | { - subscriptionId: string - type: 'response' - response: { ok: true; id: string; result: unknown; _meta: { runtimeId: string } } - } - | { subscriptionId: string; type: 'binary'; bytes: Uint8Array } - | { subscriptionId: string; type: 'error'; code: string; message: string } - | { subscriptionId: string; type: 'close' } - -type SubscriptionEventListener = (_event: unknown, payload: SubscriptionEvent) => void - -function createIpc() { - const listeners = new Set() - return { - invoke: vi.fn((_channel: string, _args?: unknown) => Promise.resolve({}) as Promise), - send: vi.fn(), - on: vi.fn((_channel: string, listener: SubscriptionEventListener) => { - listeners.add(listener) - }), - removeListener: vi.fn((_channel: string, listener: SubscriptionEventListener) => { - listeners.delete(listener) - }), - emitSubscriptionEvent: (event: SubscriptionEvent): void => { - const currentListeners = Array.from(listeners) - for (const listener of currentListeners) { - listener(null, event) - } - }, - listenerCount: (): number => listeners.size - } -} - -function dispatch(ipc: ReturnType, event: SubscriptionEvent): void { - ipc.emitSubscriptionEvent(event) -} - -describe('subscribeRuntimeEnvironmentFromPreload', () => { - it('registers the subscription event listener before invoking main', async () => { - const subscription = deferred<{ subscriptionId: string; requestId: string }>() - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? (subscription.promise as Promise) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - const onBinary = vi.fn() - - const cleanupPromise = subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse, onBinary }, - () => 'sub-1' - ) - - expect(ipc.on).toHaveBeenCalledWith( - 'runtimeEnvironments:subscriptionEvent', - expect.any(Function) - ) - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:subscribe', { - selector: 'desk', - method: 'terminal.subscribe', - subscriptionId: 'sub-1' - }) - - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { - id: 'rpc-1', - ok: true, - result: { type: 'subscribed' }, - _meta: { runtimeId: 'rt' } - } - }) - expect(onResponse).toHaveBeenCalledWith({ - id: 'rpc-1', - ok: true, - result: { type: 'subscribed' }, - _meta: { runtimeId: 'rt' } - }) - const inboundBytes = new Uint8Array([4, 5, 6]) - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'binary', - bytes: inboundBytes - }) - expect(onBinary).toHaveBeenCalledWith(inboundBytes) - - subscription.resolve({ subscriptionId: 'sub-1', requestId: 'rpc-1' }) - const cleanup = await cleanupPromise - const bytes = new Uint8Array([1, 2, 3]) - cleanup.sendBinary(bytes) - expect(ipc.send).toHaveBeenCalledWith('runtimeEnvironments:subscriptionBinary', { - subscriptionId: 'sub-1', - bytes - }) - cleanup.unsubscribe() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-1' - }) - expect(ipc.removeListener).toHaveBeenCalledWith( - 'runtimeEnvironments:subscriptionEvent', - ipc.on.mock.calls[0][1] - ) - expect(ipc.listenerCount()).toBe(0) - - onResponse.mockClear() - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { id: 'rpc-2', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('shares a single channel listener across many subscriptions on one ipc', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string, args: unknown) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ - subscriptionId: (args as { subscriptionId: string }).subscriptionId, - requestId: 'rpc' - }) - : (Promise.resolve({}) as Promise) - ) - - let counter = 0 - const onResponses = Array.from({ length: 25 }, () => vi.fn()) - const handles = await Promise.all( - onResponses.map((onResponse) => - subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'session.tabs.subscribe' }, - { onResponse }, - () => `sub-${counter++}` - ) - ) - ) - - expect(ipc.on).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(handles).toHaveLength(25) - - handles[0].unsubscribe() - dispatch(ipc, { - subscriptionId: 'sub-0', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - dispatch(ipc, { - subscriptionId: 'sub-1', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponses[0]).not.toHaveBeenCalled() - expect(onResponses[1]).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(ipc.listenerCount()).toBe(1) - - for (const handle of handles.slice(1)) { - handle.unsubscribe() - } - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - }) - - it('keeps the subscription mapped on error frames but releases it on unsubscribe', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-err', requestId: 'rpc-err' }) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - const onError = vi.fn() - - const cleanup = await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'runtime.clientEvents.subscribe' }, - { onResponse, onError }, - () => 'sub-err' - ) - - for (let i = 0; i < 50; i++) { - dispatch(ipc, { - subscriptionId: 'sub-err', - type: 'error', - code: 'TIMEOUT', - message: 'Timed out waiting for the remote Orca runtime to respond.' - }) - } - expect(onError).toHaveBeenCalledTimes(50) - expect(ipc.removeListener).not.toHaveBeenCalled() - expect(ipc.listenerCount()).toBe(1) - - cleanup.unsubscribe() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-err' - }) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - onError.mockClear() - dispatch(ipc, { - subscriptionId: 'sub-err', - type: 'error', - code: 'TIMEOUT', - message: 'still erroring' - }) - expect(onError).not.toHaveBeenCalled() - }) - - it('removes the subscription from dispatch when main rejects the subscribe call', async () => { - const subscription = deferred<{ subscriptionId: string; requestId: string }>() - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? (subscription.promise as Promise) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - - const cleanupPromise = subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse }, - () => 'sub-2' - ) - - const error = new Error('subscribe failed') - subscription.reject(error) - await expect(cleanupPromise).rejects.toThrow(error) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - dispatch(ipc, { - subscriptionId: 'sub-2', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('releases the subscription from dispatch when main resolves a different id', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-other', requestId: 'rpc' }) - : (Promise.resolve({}) as Promise) - ) - const onResponse = vi.fn() - - await expect( - subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse }, - () => 'sub-expected' - ) - ).rejects.toThrow('Runtime environment subscription id mismatch') - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - dispatch(ipc, { - subscriptionId: 'sub-expected', - type: 'response', - response: { id: 'rpc', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(onResponse).not.toHaveBeenCalled() - }) - - it('releases the subscription when main reports the remote subscription closed', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-closed', requestId: 'rpc-closed' }) - : (Promise.resolve({}) as Promise) - ) - const onClose = vi.fn() - - const cleanup = await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse: vi.fn(), onClose }, - () => 'sub-closed' - ) - - dispatch(ipc, { subscriptionId: 'other-sub', type: 'close' }) - expect(onClose).not.toHaveBeenCalled() - - dispatch(ipc, { subscriptionId: 'sub-closed', type: 'close' }) - expect(onClose).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - - onClose.mockClear() - cleanup.unsubscribe() - dispatch(ipc, { subscriptionId: 'sub-closed', type: 'close' }) - expect(onClose).not.toHaveBeenCalled() - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:unsubscribe', { - subscriptionId: 'sub-closed' - }) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - }) - - it('releases close frames before calling onClose', async () => { - const ipc = createIpc() - ipc.invoke.mockImplementation((channel: string) => - channel === 'runtimeEnvironments:subscribe' - ? Promise.resolve({ subscriptionId: 'sub-throw', requestId: 'rpc-throw' }) - : (Promise.resolve({}) as Promise) - ) - const onClose = vi.fn(() => { - throw new Error('close failed') - }) - - await subscribeRuntimeEnvironmentFromPreload( - ipc, - { selector: 'desk', method: 'terminal.subscribe' }, - { onResponse: vi.fn(), onClose }, - () => 'sub-throw' - ) - - expect(() => dispatch(ipc, { subscriptionId: 'sub-throw', type: 'close' })).toThrow( - 'close failed' - ) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - expect(ipc.listenerCount()).toBe(0) - }) -}) - -describe('opt-in crew setup registration', () => { - const args = { - selector: 'desk', - method: 'orchestration.crewSubscribe', - subscriptionId: 'crew', - expectedEnvironmentPairingRevision: 1, - expectedEnvironmentRuntimeId: null - } as const - - it('forwards plain failure after a terminal event and releases the exact registration', async () => { - const ipc = createIpc() - const pending = deferred() - ipc.invoke.mockReturnValue(pending.promise) - const onClose = vi.fn() - const onError = vi.fn() - const first = subscribeCrewAttemptFromPreload(ipc, args, { - onResponse: vi.fn(), - onClose, - onError - }) - expect(ipc.invoke).toHaveBeenCalledWith('runtimeEnvironments:subscribe', { - ...args, - setupResult: 'crew' - }) - dispatch(ipc, { - subscriptionId: 'crew', - type: 'error', - code: 'remote_runtime_unavailable', - message: 'offline' - }) - dispatch(ipc, { subscriptionId: 'crew', type: 'close' }) - const failure = { - subscriptionId: 'crew', - ok: false, - failure: { message: 'revoked', fact: { kind: 'remote', code: 'unauthorized' } } - } - pending.resolve(failure) - await expect(first).resolves.toBe(failure) - expect(ipc.listenerCount()).toBe(0) - expect(onClose).toHaveBeenCalledTimes(1) - expect(onError).toHaveBeenCalledTimes(1) - }) - - it('releases cancelled registrations while held invoke tails settle in either order', async () => { - const count = 2 - const ipc = createIpc() - const held = Array.from({ length: count }, () => deferred()) - let next = 0 - ipc.invoke.mockImplementation((channel) => - channel === 'runtimeEnvironments:subscribe' ? held[next++].promise : Promise.resolve({}) - ) - const responses = vi.fn() - const attempts = held.map((_, index) => - subscribeCrewAttemptFromPreload( - ipc, - { ...args, subscriptionId: `crew-${index}` }, - { onResponse: responses } - ).catch((error: unknown) => error) - ) - expect(ipc.listenerCount()).toBe(1) - for (let index = 0; index < count; index++) { - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, `crew-${index}`) - } - expect(ipc.listenerCount()).toBe(0) - expect(ipc.on).toHaveBeenCalledTimes(1) - expect(ipc.removeListener).toHaveBeenCalledTimes(1) - for (let index = 0; index < count; index++) { - if (index % 2) { - held[index].reject(new Error('late invoke rejection')) - } else { - held[index].resolve({ subscriptionId: `crew-${index}`, ok: true }) - } - dispatch(ipc, { - subscriptionId: `crew-${index}`, - type: 'response', - response: { id: 'late', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - } - await Promise.all(attempts) - expect(ipc.listenerCount()).toBe(0) - expect(responses).not.toHaveBeenCalled() - expect(ipc.invoke).toHaveBeenCalledTimes(count * 2) - }) - - it('keeps a replacement registration when an old cancelled invoke later rejects', async () => { - const ipc = createIpc() - const old = deferred() - ipc.invoke.mockImplementation((channel) => - channel === 'runtimeEnvironments:subscribe' ? old.promise : Promise.resolve({}) - ) - const first = subscribeCrewAttemptFromPreload(ipc, args, { onResponse: vi.fn() }) - const rejected = expect(first).rejects.toThrow('old invoke') - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, 'crew') - ipc.invoke.mockResolvedValue({ subscriptionId: 'crew', ok: true }) - const response = vi.fn() - await subscribeCrewAttemptFromPreload(ipc, args, { onResponse: response }) - old.reject(new Error('old invoke')) - await rejected - dispatch(ipc, { - subscriptionId: 'crew', - type: 'response', - response: { id: 'current', ok: true, result: {}, _meta: { runtimeId: 'rt' } } - }) - expect(response).toHaveBeenCalledOnce() - expect(ipc.listenerCount()).toBe(1) - await cancelRuntimeEnvironmentSubscriptionFromPreload(ipc, 'crew') - }) -}) 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' )} > 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/dictation/DictationCleanupNoticePill.tsx b/src/renderer/src/components/dictation/DictationCleanupNoticePill.tsx new file mode 100644 index 00000000000..f257d13bb29 --- /dev/null +++ b/src/renderer/src/components/dictation/DictationCleanupNoticePill.tsx @@ -0,0 +1,57 @@ +import { CircleAlert } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { useTranslate } from '@/i18n/use-translate' +import { DictationPillCloseButton } from './DictationPillFailure' +import { DictationPillShell } from './DictationPillShell' +import { openVoiceSettings } from './dictation-toasts' +import type { DictationCleanupNotice } from './use-dictation-cleanup' + +/** After the words landed as heard because cleanup failed or took too long; closes itself. */ +export function DictationCleanupNoticePill({ + notice, + onClose +}: { + notice: DictationCleanupNotice + onClose: () => void +}) { + const t = useTranslate() + const message = + notice.kind === 'timed-out' + ? t( + 'components.dictation.cleanupNotice.timedOut', + 'Cleanup took too long. Inserted as heard.' + ) + : t('components.dictation.cleanupNotice.failed', 'Cleanup failed. Inserted as heard.') + return ( + + + {message} + + + + + {message} + + {notice.kind === 'failed' ? ( + + ) : null} + + ) +} diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index b10035c6acd..0a683b72483 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -8,13 +8,13 @@ import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pi import { canRetryDictation, createDictationKeptRecording, - transcribeKeptRecording, type DictationKeptRecording } from './dictation-kept-recording' +import { useDictationRetry } from './use-dictation-retry' import { useDictationControls } from './use-dictation-controls' import { useDictationQueuedSend } from './use-dictation-queued-send' import { createDictationTranscriptDelivery } from './dictation-transcript-delivery' -import { recordStoppedSession, waitForStoppedSession } from './dictation-stopped-sessions' +import { createDictationStoppedSessions } from './dictation-stopped-sessions' import { showDictationDisabledToast, showDictationNoModelToast, @@ -33,6 +33,7 @@ import { useDictationSilenceStop } from './use-dictation-silence-stop' import { stopAfterSilenceSeconds } from '../../../../shared/dictation-silence-stop' import { useDictationSpeechEvents } from './use-dictation-speech-events' import { useDictationSpeechModelSetup } from './use-dictation-speech-model-setup' +import { shouldHoldForCleanup, useDictationCleanup } from './use-dictation-cleanup' import { NO_DICTATION_LIVE_TEXT } from '@/store/slices/dictation/dictation' import { canStartDictation, @@ -63,8 +64,7 @@ export function DictationController() { const sessionRef = useRef(initialDictationSession) // Inserts the current session's finals where dictation started. const deliverRef = useRef<((text: string) => void) | null>(null) - const stoppedSessionIdsRef = useRef(new Set()) - const stoppedResolversRef = useRef(new Map void>()) + const [stoppedSessions] = useState(createDictationStoppedSessions) // Push-to-talk restarts per utterance; report a missing preferred microphone once per preference. const micFallbackNotifiedForRef = useRef(null) const [captureLive, setCaptureLive] = useState(false) @@ -80,6 +80,8 @@ export function DictationController() { useDictationSpeechModelSetup(settings?.voice, isIdle, setPillAnchor) const queuedSend = useDictationQueuedSend(sessionRef, keptRef) const { clear: clearQueuedSend, release: releaseQueuedSend } = queuedSend + const cleanup = useDictationCleanup(keptRef) + const { land: landCleanup, interrupt: interruptCleanup } = cleanup const dispatch = useCallback( (event: DictationSessionEvent): DictationSession => { @@ -110,10 +112,6 @@ export function DictationController() { [setDictationState, setLiveText, clearQueuedSend] ) - const drainStoppedSession = useCallback((sessionId: string) => { - void waitForStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef) - }, []) - const finishDictationSession = useCallback( async ({ run, sessionId }: DictationSession, beforeEnd?: () => void) => { if (sessionId === null) { @@ -130,7 +128,7 @@ export function DictationController() { // Swallow stop errors — the worker may already be torn down. } // Main stop completion can precede renderer final-text IPC; wait for this session’s stopped event before accepting the next run. - await waitForStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef) + await stoppedSessions.wait(sessionId) if (sessionRef.current.run !== run) { return } @@ -138,17 +136,26 @@ export function DictationController() { showNoSpeechDetectedToast() } beforeEnd?.() + await landCleanup() await releaseQueuedSend(run) if (sessionRef.current.run === run) { dispatch({ type: 'ended' }) } }, - [dispatch, finishCapture, getCapturedChunkCount, releaseQueuedSend] + [ + dispatch, + finishCapture, + getCapturedChunkCount, + stoppedSessions, + releaseQueuedSend, + landCleanup + ] ) /** The error pill when the recording can be retried; otherwise the toast, as nothing is left to retry. */ const showFailure = useCallback( (kind: DictationFailureKind | null, showToast: () => void) => { + interruptCleanup() dispatch({ type: 'fail' }) if (kind && canRetryDictation(keptRef.current)) { setFailure(kind) @@ -157,11 +164,15 @@ export function DictationController() { showToast() dispatch({ type: 'ended' }) }, - [dispatch] + [dispatch, interruptCleanup] ) // Words that already landed stay; the engine drops the rest instead of transcribing it. const cancelDictation = useCallback(() => { + // ✕ while cleaning up skips cleanup; the words then land as heard. + if (interruptCleanup()) { + return + } invalidatePendingStart() if (sessionRef.current.phase === 'error') { dispatch({ type: 'ended' }) @@ -173,8 +184,8 @@ export function DictationController() { } stopCapture() void window.api.speech.cancelDictation(previous.sessionId).catch(() => undefined) - drainStoppedSession(previous.sessionId) - }, [dispatch, stopCapture, drainStoppedSession, invalidatePendingStart]) + void stoppedSessions.wait(previous.sessionId) + }, [dispatch, stopCapture, stoppedSessions, invalidatePendingStart, interruptCleanup]) const stopDictation = useCallback(async () => { invalidatePendingStart() @@ -217,7 +228,7 @@ export function DictationController() { } const isCurrent = (): boolean => sessionRef.current.run === run const insertionTarget = captureInsertionTarget() - const deliver = createDictationTranscriptDelivery() + const deliver = createDictationTranscriptDelivery(shouldHoldForCleanup()) deliverRef.current = (text) => deliver(text, insertionTarget) const context = captureDictationContext() const kept = createDictationKeptRecording(insertionTarget, deliver, context) @@ -235,7 +246,7 @@ export function DictationController() { } if (engineStarted) { await window.api.speech.cancelDictation(sessionId).catch(() => undefined) - drainStoppedSession(sessionId) + void stoppedSessions.wait(sessionId) } } @@ -323,38 +334,21 @@ export function DictationController() { stopCapture, stopDictation, finishDictationSession, - drainStoppedSession, + stoppedSessions, recordFeatureInteraction, showFailure, readyToRecord ]) - // Sends the failed session's recording through the speech host again, into the same place. - const retryDictation = useCallback(async () => { - const kept = keptRef.current - const modelId = settings?.voice?.sttModel - if (sessionRef.current.phase !== 'error' || !modelId || !kept || !canRetryDictation(kept)) { - return - } - const { run, sessionId } = dispatch({ type: 'retry' }) - if (sessionId === null) { - return - } - await transcribeKeptRecording({ - recording: kept, - modelId, - sessionId, - isCurrent: () => sessionRef.current.run === run, - routeFinals: (sink) => { - deliverRef.current = sink - }, - finish: (beforeEnd) => finishDictationSession(sessionRef.current, beforeEnd), - fail: (message) => - showFailure(dictationStartFailureKind(message) ?? 'transcribe', () => - showDictationStartErrorToast(message) - ) - }) - }, [settings, dispatch, finishDictationSession, showFailure]) + const retryDictation = useDictationRetry({ + modelId: settings?.voice?.sttModel, + sessionRef, + keptRef, + deliverRef, + dispatch, + finish: finishDictationSession, + showFailure + }) const toggleDictation = useCallback(() => { // A second press while the model check runs takes the first one back. @@ -377,10 +371,7 @@ export function DictationController() { retry: () => void retryDictation(), enterQueues: (event) => queuedSend.queueTerminalEnter(event.target), // The error pill leaves Esc to Settings and dialogs; only its ✕ discards the recording. - escCancels: () => - hasPendingStart() || - isDictationUnderway(sessionRef.current.phase) || - sessionRef.current.phase === 'stopping' + escCancels: () => hasPendingStart() || !canStartDictation(sessionRef.current.phase) }) const { isHolding } = useHoldDictationGesture({ @@ -408,15 +399,14 @@ export function DictationController() { dispatch({ type: 'final-text' }) deliverRef.current?.(text) }, - onStopped: (sessionId) => - recordStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef), + onStopped: (sessionId) => stoppedSessions.record(sessionId), onError: (sessionId, error) => { const { run } = dispatch({ type: 'abandon' }) stopCapture() discardBufferedAudio() void (async () => { await window.api.speech.stopDictation(sessionId).catch(() => undefined) - await waitForStoppedSession(sessionId, stoppedSessionIdsRef, stoppedResolversRef) + await stoppedSessions.wait(sessionId) if (sessionRef.current.run !== run) { return } @@ -432,6 +422,7 @@ export function DictationController() { anchor={pillAnchor} failure={failure} queued={queuedSend.queuedKind} + cleanup={cleanup} setup={setupTarget} onSetupClose={closeSetup} /> diff --git a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx index 294c70cb1f8..cf982f2cdf1 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx @@ -6,17 +6,22 @@ import type { DictationFailureKind } from './dictation-toasts' import type { SpeechModelUpdateTarget } from './speech-model-update-target' import type { SpeechModelManifest, SpeechModelState } from '../../../../shared/speech-types' import type { DictationQueuedSendKind } from './use-dictation-queued-send' +import type { DictationCleanupNotice } from './use-dictation-cleanup' function PaneWithPill({ captureLive = true, failure = null, queued = null, - setup = null + setup = null, + cleaning = false, + notice = null }: { captureLive?: boolean failure?: DictationFailureKind | null queued?: DictationQueuedSendKind | null setup?: SpeechModelUpdateTarget | null + cleaning?: boolean + notice?: DictationCleanupNotice['kind'] | null }) { const [pane, setPane] = useState(null) const anchor = useMemo( @@ -31,6 +36,11 @@ function PaneWithPill({ anchor={anchor} failure={failure} queued={queued} + cleanup={{ + cleaning, + notice: notice ? { kind: notice, anchor } : null, + dismissNotice: () => {} + }} setup={setup} onSetupClose={() => {}} /> @@ -131,6 +141,32 @@ export const modelFailed = defineFixture({ render: () => }) +export const cleaningUp = defineFixture({ + width: 520, + store: { + dictationState: 'stopping', + liveText: { + committed: 'move the retry into the worker at four scratch that at five', + tentative: '', + speechPending: false + } + }, + setup: resetDictationMeter, + render: () => +}) + +export const cleanupFailed = defineFixture({ + width: 520, + store: { dictationState: 'idle' }, + render: () => +}) + +export const cleanupTimedOut = defineFixture({ + width: 520, + store: { dictationState: 'idle' }, + render: () => +}) + export const queuedChatSend = defineFixture({ width: 520, store: { dictationState: 'stopping' }, diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index 28121e94e28..a243ecdbf4d 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -22,6 +22,8 @@ import { loadSpeechCatalog } from './speech-model-update-check' import type { SpeechModelUpdateTarget } from './speech-model-update-target' import type { DictationFailureKind } from './dictation-toasts' import type { DictationQueuedSendKind } from './use-dictation-queued-send' +import type { DictationCleanupNotice } from './use-dictation-cleanup' +import { DictationCleanupNoticePill } from './DictationCleanupNoticePill' // The finish button turns into a spinner only when finishing is slow enough to notice. const FINISH_SPINNER_DELAY_MS = 200 @@ -36,6 +38,12 @@ type DictationIndicatorProps = { failure: DictationFailureKind | null /** A send waiting for this dictation's words to land. */ queued: DictationQueuedSendKind | null + cleanup: { + /** AI cleanup is running on the finished dictation's words. */ + cleaning: boolean + notice: DictationCleanupNotice | null + dismissNotice: () => void + } } type DictationSetupProps = { @@ -53,9 +61,11 @@ export function DictationIndicator({ if (isDictationPillShown(dictationState)) { return } - return setup ? ( - - ) : null + if (setup) { + return + } + const { notice, dismissNotice } = props.cleanup + return notice ? : null } function formatElapsed(seconds: number): string { @@ -150,7 +160,7 @@ function DictationPendingDots() { ) } -function DictationPill({ captureLive, anchor, failure, queued }: DictationIndicatorProps) { +function DictationPill({ captureLive, anchor, failure, queued, cleanup }: DictationIndicatorProps) { const t = useTranslate() const dictationState = useAppStore((state) => state.dictationState) const liveText = useAppStore((state) => state.liveText) @@ -167,8 +177,11 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica const failedKind = dictationState === 'error' ? failure : null const { committed, speechPending } = liveText const tentative = liveText.tentative.trim() - const queuedStatus = - queued === 'chat' + const { cleaning } = cleanup + // While cleaning up, the pill says so; the queued send shows again once the text lands. + const queuedStatus = cleaning + ? null + : queued === 'chat' ? t( 'auto.components.dictation.DictationIndicator.sendsWhenLanded', 'Sends when the text lands' @@ -179,13 +192,17 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica 'Presses Enter when the text lands' ) : null - const status = finishing - ? t('auto.components.dictation.DictationIndicator.finishing', 'Finishing…') - : t('auto.components.dictation.DictationIndicator.listening', 'Listening…') + const status = cleaning + ? t('components.dictation.DictationIndicator.cleaningUp', 'Cleaning up…') + : finishing + ? t('auto.components.dictation.DictationIndicator.finishing', 'Finishing…') + : t('auto.components.dictation.DictationIndicator.listening', 'Listening…') const announced = nearCloudLimit ? `${status} ${t('auto.components.dictation.DictationIndicator.oneMinuteLeft', 'One minute left.')}` : (queuedStatus ?? status) - const cancelLabel = t('auto.components.dictation.DictationIndicator.cancel', 'Cancel') + const cancelLabel = cleaning + ? t('components.dictation.DictationIndicator.skipCleanup', 'Skip cleanup and insert as heard') + : t('auto.components.dictation.DictationIndicator.cancel', 'Cancel') const finishLabel = t('auto.components.dictation.DictationIndicator.finish', 'Finish') return ( @@ -212,7 +229,7 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica )} {queuedStatus} - ) : committed || tentative || speechPending ? ( + ) : !cleaning && (committed || tentative || speechPending) ? ( // Right-aligned so the newest words stay in view; older ones fade off the left edge. void + /** Resolves once the session's stopped event arrives, or after a second. */ + wait: (sessionId: string) => Promise +} + +export function createDictationStoppedSessions(): DictationStoppedSessions { + const stoppedSessionIds = { current: new Set() } + const stoppedResolvers = { current: new Map void>() } + return { + record: (sessionId) => recordStoppedSession(sessionId, stoppedSessionIds, stoppedResolvers), + wait: (sessionId) => waitForStoppedSession(sessionId, stoppedSessionIds, stoppedResolvers) + } +} diff --git a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts index 3cfeadbae95..bcbbdec6aa6 100644 --- a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts +++ b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts @@ -12,15 +12,24 @@ export type DictationTranscriptDelivery = (( landedText: () => string /** Waits for every final so far to land; false if any went to the clipboard instead. */ settled: () => Promise + /** What AI cleanup is holding back, or null when nothing is held. */ + held: () => string | null + /** Stops holding: `text` (the cleaned words), else the held words as heard, lands once where they were going. */ + releaseHeld: (text?: string) => void + /** Holds the finals that follow, as a retry of a failed session does while cleanup is on. */ + hold: () => void } -/** One session's finals, inserted in order; text that can't land goes to the clipboard so it isn't lost. */ -export function createDictationTranscriptDelivery(): DictationTranscriptDelivery { +/** One session's finals, inserted in order; text that can't land goes to the clipboard so it isn't lost. With `hold`, finals wait for AI cleanup and land together. */ +export function createDictationTranscriptDelivery(hold = false): DictationTranscriptDelivery { let lastLanded = '' let allLanded = '' let missed = '' let queue = Promise.resolve() - const deliver = (text: string, target: DictationInsertionTarget | null): void => { + let holding = hold + let held = '' + let heldTarget: DictationInsertionTarget | null = null + const insert = (text: string, target: DictationInsertionTarget | null): void => { queue = queue.then(async () => { const landed = target ? await insertText(text, target, lastLanded).catch(() => false) : false if (landed) { @@ -32,9 +41,31 @@ export function createDictationTranscriptDelivery(): DictationTranscriptDelivery await copyMissedDictation(missed, target !== null) }) } + const deliver = (text: string, target: DictationInsertionTarget | null): void => { + if (!holding) { + insert(text, target) + return + } + held = appendDictationText(held, text) + heldTarget = target + } return Object.assign(deliver, { landedText: () => allLanded, - settled: () => queue.then(() => missed === '') + settled: () => queue.then(() => missed === ''), + held: () => (holding && held ? held : null), + hold: (): void => { + holding = true + held = '' + }, + releaseHeld: (text = held): void => { + if (!holding) { + return + } + holding = false + if (text) { + insert(text, heldTarget) + } + } }) } diff --git a/src/renderer/src/components/dictation/use-dictation-cleanup.ts b/src/renderer/src/components/dictation/use-dictation-cleanup.ts new file mode 100644 index 00000000000..05cafa6305c --- /dev/null +++ b/src/renderer/src/components/dictation/use-dictation-cleanup.ts @@ -0,0 +1,92 @@ +import { useCallback, useEffect, useRef, useState, type RefObject } from 'react' +import { useAppStore } from '@/store' +import { + isDictationCleanupOn, + type DictationCleanupResult +} from '../../../../shared/dictation-cleanup' +import { createNonSecureContextUuid } from '../../../../shared/non-secure-context-uuid' +import { appendDictationText } from '../../../../shared/dictation-transcript-spacing' +import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pill-anchor' +import type { DictationKeptRecording } from './dictation-kept-recording' + +const NOTICE_MS = 4000 + +export type DictationCleanupNotice = { + kind: 'failed' | 'timed-out' + anchor: DictationPillAnchor | null +} + +/** Whether this desktop cleans dictated text itself; a paired web client's host does it in `speech.dictation.finish`. */ +export function shouldHoldForCleanup(): boolean { + const settings = useAppStore.getState().settings + return Boolean(window.api.speech.cleanUpDictation && settings && isDictationCleanupOn(settings)) +} + +/** Runs AI cleanup on the session's held words at finish; ✕ skips it, and the words then land as heard. */ +export function useDictationCleanup(keptRef: RefObject) { + const [cleaning, setCleaning] = useState(false) + const [notice, setNotice] = useState(null) + const skipRef = useRef<(() => void) | null>(null) + + useEffect(() => { + if (!notice) { + return + } + const id = window.setTimeout(() => setNotice(null), NOTICE_MS) + return () => window.clearTimeout(id) + }, [notice]) + + /** Lands the held words once: cleaned, or as heard when cleanup fails, takes too long or is skipped. */ + const land = useCallback(async (): Promise => { + const kept = keptRef.current + const heard = kept?.deliver.held() ?? null + const cleanUp = window.api.speech.cleanUpDictation + if (!kept || heard === null || !cleanUp) { + kept?.deliver.releaseHeld() + return + } + const requestId = createNonSecureContextUuid() + const skipped = Promise.withResolvers() + skipRef.current = () => { + skipped.resolve({ status: 'canceled' }) + void window.api.speech.cancelDictationCleanup?.(requestId).catch(() => undefined) + } + setNotice(null) + setCleaning(true) + const result = await Promise.race([ + cleanUp(heard, kept.context, requestId).catch((error: unknown): DictationCleanupResult => ({ + status: 'failed', + reason: String(error) + })), + skipped.promise + ]) + skipRef.current = null + setCleaning(false) + // A final that arrived during cleanup follows the cleaned words instead of being dropped. + const late = kept.deliver.held()?.slice(heard.length) ?? '' + kept.deliver.releaseHeld( + result.status === 'cleaned' ? appendDictationText(result.text, late.trim()) : undefined + ) + if (result.status === 'failed') { + console.warn('[dictation] AI cleanup failed:', result.reason) + } + if (result.status === 'failed' || result.status === 'timed-out') { + setNotice({ kind: result.status, anchor: dictationPillAnchorFor(kept.target) }) + } + }, [keptRef]) + + /** Skips a cleanup in progress (true), else lands any held words as heard: the session ends unfinished. */ + const interrupt = useCallback((): boolean => { + const skip = skipRef.current + if (skip) { + skip() + return true + } + keptRef.current?.deliver.releaseHeld() + return false + }, [keptRef]) + + const dismissNotice = useCallback(() => setNotice(null), []) + + return { cleaning, notice, land, interrupt, dismissNotice } +} diff --git a/src/renderer/src/components/dictation/use-dictation-retry.ts b/src/renderer/src/components/dictation/use-dictation-retry.ts new file mode 100644 index 00000000000..e2a73d9122d --- /dev/null +++ b/src/renderer/src/components/dictation/use-dictation-retry.ts @@ -0,0 +1,64 @@ +import { useCallback, type RefObject } from 'react' +import type { + DictationSession, + DictationSessionEvent +} from '../../../../shared/dictation-session-machine' +import { + canRetryDictation, + transcribeKeptRecording, + type DictationKeptRecording +} from './dictation-kept-recording' +import { + dictationStartFailureKind, + showDictationStartErrorToast, + type DictationFailureKind +} from './dictation-toasts' +import { shouldHoldForCleanup } from './use-dictation-cleanup' + +/** Sends the failed session's recording through the speech host again, into the same place. */ +export function useDictationRetry({ + modelId, + sessionRef, + keptRef, + deliverRef, + dispatch, + finish, + showFailure +}: { + modelId: string | undefined + sessionRef: RefObject + keptRef: RefObject + deliverRef: RefObject<((text: string) => void) | null> + dispatch: (event: DictationSessionEvent) => DictationSession + finish: (session: DictationSession, beforeEnd: () => void) => Promise + showFailure: (kind: DictationFailureKind | null, showToast: () => void) => void +}): () => Promise { + return useCallback(async () => { + const kept = keptRef.current + if (sessionRef.current.phase !== 'error' || !modelId || !kept || !canRetryDictation(kept)) { + return + } + const { run, sessionId } = dispatch({ type: 'retry' }) + if (sessionId === null) { + return + } + // The failure landed what was held as heard; what the retry adds waits for cleanup again. + if (shouldHoldForCleanup()) { + kept.deliver.hold() + } + await transcribeKeptRecording({ + recording: kept, + modelId, + sessionId, + isCurrent: () => sessionRef.current.run === run, + routeFinals: (sink) => { + deliverRef.current = sink + }, + finish: (beforeEnd) => finish(sessionRef.current, beforeEnd), + fail: (message) => + showFailure(dictationStartFailureKind(message) ?? 'transcribe', () => + showDictationStartErrorToast(message) + ) + }) + }, [modelId, sessionRef, keptRef, deliverRef, dispatch, finish, showFailure]) +} 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/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/notices/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx index 9e569b40797..95ceca40858 100644 --- a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx @@ -321,7 +321,9 @@ export function NativeChatNoticeRow({ ) : usageLimitContinue ? ( ) : null} diff --git a/src/renderer/src/components/native-chat/messages/notices/native-chat-orca-stop-context.ts b/src/renderer/src/components/native-chat/messages/notices/native-chat-orca-stop-context.ts index bb995befe84..bb0395228f0 100644 --- a/src/renderer/src/components/native-chat/messages/notices/native-chat-orca-stop-context.ts +++ b/src/renderer/src/components/native-chat/messages/notices/native-chat-orca-stop-context.ts @@ -12,6 +12,8 @@ export type NativeChatOrcaStopView = { continueNow: () => void usageLimitTurnItemId: string | null usageLimitAutoContinue?: NativeChatUsageLimitAutoContinueState | null + /** When Continue past the usage limit applies; earlier than its reset after an account switch. */ + usageLimitContinueAt?: number onUsageLimitHandOffStarted?: () => void usageLimitContinueDisabled?: boolean continueUsageLimit: (hadFocus?: boolean) => void 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: () => +}) 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(() => { diff --git a/src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.tsx b/src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.tsx index 403a8dd907f..ba52745f3da 100644 --- a/src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.tsx +++ b/src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.tsx @@ -93,11 +93,8 @@ export function useNativeChatInterruptedContinuation(input: { () => latestNativeChatUsageLimitCut(input.journalItems, input.submissions), [input.journalItems, input.submissions] ) - const usageLimitAutoContinue = useNativeChatUsageLimitAutoContinue( - target, - sessionId, - usageLimitCut - ) + const { auto: usageLimitAutoContinue, continueAt: usageLimitContinueAt } = + useNativeChatUsageLimitAutoContinue(target, sessionId, usageLimitCut) const [attempt, setAttempt] = useState(NO_NATIVE_CHAT_INTERRUPTED_CONTINUE_ATTEMPT) const [usageFailure, setUsageFailure] = useState(null) if (usageFailure !== null && input.pending.some((entry) => entry.phase === 'sending')) { @@ -193,6 +190,7 @@ export function useNativeChatInterruptedContinuation(input: { continueNow, usageLimitTurnItemId, usageLimitAutoContinue, + usageLimitContinueAt, onUsageLimitHandOffStarted: usageLimitAutoContinue?.kind === 'scheduled' ? usageLimitAutoContinue.cancel : undefined, usageLimitContinueDisabled: usageCapability === 'unknown', @@ -207,6 +205,7 @@ export function useNativeChatInterruptedContinuation(input: { continueNow, usageLimitTurnItemId, usageLimitAutoContinue, + usageLimitContinueAt, usageCapability, continueUsageLimit ] diff --git a/src/renderer/src/components/native-chat/usage/use-native-chat-usage-limit-auto-continue.ts b/src/renderer/src/components/native-chat/usage/use-native-chat-usage-limit-auto-continue.ts index a6d8b8dee80..d2d9ae3514c 100644 --- a/src/renderer/src/components/native-chat/usage/use-native-chat-usage-limit-auto-continue.ts +++ b/src/renderer/src/components/native-chat/usage/use-native-chat-usage-limit-auto-continue.ts @@ -24,7 +24,11 @@ export function useNativeChatUsageLimitAutoContinue( target: RuntimeClientTarget, sessionId: string, cut: NativeChatUsageLimitCut | null -): NativeChatUsageLimitAutoContinueState | null { +): { + auto: NativeChatUsageLimitAutoContinueState | null + /** When the host lets Continue apply: earlier than the cut's reset once the chat moved accounts. */ + continueAt: number | undefined +} { const capability = useStructuredAgentSessionHostCapabilityState( target, AGENT_SESSION_USAGE_LIMIT_AUTO_CONTINUE_RUNTIME_CAPABILITY @@ -101,7 +105,7 @@ export function useNativeChatUsageLimitAutoContinue( }) .finally(() => setCancelling(false)) }, [cancelling, readCutState, target, sessionId, turnItemId, resetsAt]) - return useMemo(() => { + const auto = useMemo(() => { const kind = capability === 'supported' ? nativeChatUsageLimitAutoContinueKind(cutState, { @@ -116,4 +120,14 @@ export function useNativeChatUsageLimitAutoContinue( ? { kind, resetsAt: continueAt, cancelDisabled: cancelling, cancel } : { kind } }, [capability, continueAt, cutState, schedulable, target.kind, cancelling, cancel]) + return useMemo( + () => ({ + auto, + continueAt: + resetsAt === undefined || continueAt === undefined + ? resetsAt + : Math.min(resetsAt, continueAt) + }), + [auto, resetsAt, continueAt] + ) } 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/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx b/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx index 89440567c0d..e489aa76369 100644 --- a/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx +++ b/src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.fixture.tsx @@ -1,6 +1,7 @@ import { useState } from 'react' import { defineFixture } from '../../component-fixtures/component-fixture' import { NewWorkspaceComposerNameSection } from './NewWorkspaceComposerNameSection' +import { buildWorkspaceSourceSelection } from '../../../../shared/new-workspace/workspace-source' function BranchReusePreview({ busy = false, @@ -18,6 +19,9 @@ function BranchReusePreview({ const [reuse, setReuse] = useState(initialReuse) const [branchName, setBranchName] = useState(initialBranchName) const [name, setName] = useState('Feature review') + const baseBranch = remote + ? `refs/remotes/origin/${existingBranch}` + : `refs/heads/${existingBranch}` return (
{}} onSmartBranchSelect={() => {}} onSmartLinearIssueSelect={() => {}} - smartNameSelection={{ - kind: 'branch', - label: remote ? `origin/${existingBranch}` : existingBranch - }} + smartNameSelection={buildWorkspaceSourceSelection({ linkedWorkItem: null, baseBranch })} onClearSmartNameSelection={() => {}} selectedRepoRequiresConnection={false} selectedRepoIsGit @@ -49,9 +50,7 @@ function BranchReusePreview({ setBranchName(undefined) }} onOpenSelectedBranchWorkspace={busy && reuse ? () => {} : undefined} - baseBranch={ - remote ? `refs/remotes/origin/${existingBranch}` : `refs/heads/${existingBranch}` - } + baseBranch={baseBranch} onNamePlainEnter={() => {}} />
diff --git a/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx b/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx index 491faeb5873..e22af1ec0e2 100644 --- a/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx +++ b/src/renderer/src/components/new-workspace/smart-workspace-source-row-content.tsx @@ -12,6 +12,7 @@ import { JiraIcon } from '@/components/icons/JiraIcon' import { Trans } from 'react-i18next' import { i18n } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' +import { branchRefLabel } from '../../../../shared/git/refs/branch-ref-label' import type { JiraSite } from '../../../../shared/jira/jira-types' import type { RowEntry, SmartWorkspaceNameSelection } from './smart-workspace-name-field-model' @@ -130,7 +131,11 @@ export function RowLabel({ ) } if (row.kind === 'branch') { - return {row.refName} + return ( + + {row.label ?? branchRefLabel(row.refName)} + + ) } if (row.kind === 'jira') { const siteLabel = jiraSite 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/repo/CreateFromPicker.fixture.tsx b/src/renderer/src/components/repo/CreateFromPicker.fixture.tsx new file mode 100644 index 00000000000..91030005d82 --- /dev/null +++ b/src/renderer/src/components/repo/CreateFromPicker.fixture.tsx @@ -0,0 +1,55 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { CreateFromPicker } from './CreateFromPicker' + +const repo = { + id: 'branch-snapshot-fixture', + path: '/repo', + displayName: 'Orca', + badgeColor: '', + addedAt: 0 +} +export const collidingBranches = defineFixture({ + width: 380, + setup: () => { + window.api.repos.getBaseRefDefault = async () => ({ + defaultBaseRef: 'origin/main', + remoteCount: 1 + }) + window.api.repos.searchBaseRefs = async () => [ + 'refs/heads/origin/main', + 'refs/remotes/origin/main', + 'refs/heads/feature/a-long-branch-name-for-review' + ] + }, + render: () => ( +
+ {}} + /> +
+ ), + interact: async (frame) => { + frame.querySelector('button[role="combobox"]')?.click() + await new Promise((resolve, reject) => { + if (document.querySelectorAll('[cmdk-item]').length >= 3) { + return resolve() + } + const timeout = setTimeout(() => { + observer.disconnect() + reject(new Error('Branch fixture did not load')) + }, 5000) + const observer = new MutationObserver(() => { + if (document.querySelectorAll('[cmdk-item]').length >= 3) { + observer.disconnect() + clearTimeout(timeout) + resolve() + } + }) + observer.observe(document.body, { childList: true, subtree: true }) + }) + } +}) diff --git a/src/renderer/src/components/repo/CreateFromPicker.test.tsx b/src/renderer/src/components/repo/CreateFromPicker.test.tsx new file mode 100644 index 00000000000..f842851a9cc --- /dev/null +++ b/src/renderer/src/components/repo/CreateFromPicker.test.tsx @@ -0,0 +1,146 @@ +// @vitest-environment happy-dom +import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { CreateFromPicker } from './CreateFromPicker' +import { TooltipProvider } from '../ui/tooltip' +import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture' + +const refs = vi.hoisted(() => ({ + defaultRef: 'origin/main', + values: ['refs/heads/origin/main', 'refs/remotes/origin/main'] +})) +vi.mock('@/runtime/source-control/references/runtime-repo-client', () => ({ + getRuntimeRepoBaseRefDefault: async () => ({ defaultBaseRef: refs.defaultRef, remoteCount: 1 }), + searchRuntimeRepoBaseRefs: async () => refs.values +})) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + refs.defaultRef = 'origin/main' + refs.values = ['refs/heads/origin/main', 'refs/remotes/origin/main'] +}) + +it('keeps deferred search focus through typing and cancels it when the picker closes', async () => { + const frames = new Map() + let nextFrame = 0 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++nextFrame, callback) + return nextFrame + }) + vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id)) + const flushFrames = () => { + const pending = [...frames.values()] + frames.clear() + act(() => pending.forEach((callback) => callback(0))) + } + const repo = { id: 'repo', path: '/repo', displayName: 'Repo', badgeColor: '', addedAt: 0 } + const view = render( + + {}} + /> + + ) + const trigger = view.getByRole('combobox') + fireEvent.click(trigger) + const input = await view.findByPlaceholderText('Search repo branches...') + fireEvent.change(input, { target: { value: 'origin' } }) + flushFrames() + expect(document.activeElement).toBe(input) + + fireEvent.click(trigger) + fireEvent.click(trigger) + const reopened = await view.findByPlaceholderText('Search repo branches...') + const focus = vi.spyOn(reopened, 'focus') + fireEvent.click(trigger) + flushFrames() + expect(focus).not.toHaveBeenCalled() +}) + +it('uses the latest project default and default action after a rerender', async () => { + refs.values = ['refs/heads/main', 'refs/heads/topic'] + refs.defaultRef = 'main' + const initial = vi.fn() + const latest = vi.fn() + const repo = { id: 'repo', path: '/repo', displayName: 'Repo', badgeColor: '', addedAt: 0 } + const picker = (defaultRef: string, onSetDefault: (branch: string) => void) => ( + + {}} + onSetDefault={onSetDefault} + /> + + ) + const view = render(picker('refs/heads/main', initial)) + fireEvent.click(view.getByRole('combobox')) + await view.findByRole('option', { name: 'topic' }) + view.rerender(picker('refs/heads/topic', latest)) + fireEvent.contextMenu(view.getByRole('option', { name: 'topic (default)' })) + expect( + (await view.findByRole('menuitem', { name: 'Current default' })).getAttribute('aria-disabled') + ).toBe('true') + fireEvent.keyDown(view.getByRole('menu'), { key: 'Escape' }) + await waitFor(() => expect(view.queryByRole('menu')).toBeNull()) + fireEvent.contextMenu(view.getByRole('option', { name: 'main' })) + fireEvent.click(view.getByRole('menuitem', { name: 'Set as default' })) + expect(initial).not.toHaveBeenCalled() + expect(latest).toHaveBeenCalledWith('refs/heads/main') +}) + +it('keeps the colliding local branch selectable beside a remote project default', async () => { + const selected = vi.fn() + const repo = { id: 'repo', path: '/repo', displayName: 'Repo', badgeColor: '', addedAt: 0 } + const view = render( + + + + ) + fireEvent.click(view.getByRole('combobox')) + const local = await view.findByRole('option', { name: 'refs/heads/origin/main' }) + expect(view.getByRole('option', { name: 'origin/main (default)' })).toBeTruthy() + fireEvent.click(local) + expect(selected).toHaveBeenCalledWith('refs/heads/origin/main') +}) + +it.each(['main', 'origin/main'])( + 'merges an older server default %s without changing its action', + async (ref) => { + refs.defaultRef = ref + refs.values = [ref, 'topic'] + const selected = vi.fn() + const repo = { id: 'repo', path: '/repo', displayName: 'Repo', badgeColor: '', addedAt: 0 } + const view = render( + + + + ) + fireEvent.click(view.getByRole('combobox')) + const topic = await view.findByRole('option', { name: 'topic' }) + expect(view.getAllByRole('option')).toHaveLength(2) + expect(view.getByRole('option', { name: `${ref} (default)` })).toBeTruthy() + fireEvent.click(topic) + expect(selected).toHaveBeenCalledWith('topic') + } +) diff --git a/src/renderer/src/components/repo/CreateFromPicker.tsx b/src/renderer/src/components/repo/CreateFromPicker.tsx index 2df1c6440ee..d5636ae517b 100644 --- a/src/renderer/src/components/repo/CreateFromPicker.tsx +++ b/src/renderer/src/components/repo/CreateFromPicker.tsx @@ -16,6 +16,11 @@ import { } from '@/components/ui/context-menu' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/class-names' +import { + branchRefLabel, + branchRefLabels, + probedDefaultBranchRef +} from '../../../../shared/git/refs/branch-ref-label' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' import { getRepoExecutionHostId } from '../../../../shared/execution-host' @@ -24,14 +29,40 @@ import { searchRuntimeRepoBaseRefs } from '@/runtime/source-control/references/runtime-repo-client' import { isRuntimeRepoRefSearchQueryWithinLimit } from '@/runtime/source-control/references/runtime-repo-search-bounds' -import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { FilePathCursorTooltip } from '@/components/file-path-cursor-tooltip' const DEFAULT_VALUE = '__project_default__' -function displayBranchName(branch: string): string { - return branch.replace(/^refs\/heads\//, '') +function createBranchOptions( + effectiveDefault: string | null, + searchResults: readonly string[], + worktrees: readonly Worktree[] +) { + const options = new Set() + if (effectiveDefault) { + options.add(effectiveDefault) + } + for (const worktree of worktrees) { + const branch = worktree.branch.trim().replace(/^refs\/heads\//, '') + if (branch) { + options.add(searchResults.includes(branch) ? branch : `refs/heads/${branch}`) + } + } + for (const branch of searchResults) { + options.add(branch) + } + const merged = Array.from(options) + const labels = branchRefLabels(merged) + merged.sort((left, right) => (labels.get(left) ?? left).localeCompare(labels.get(right) ?? right)) + return { options: merged, labels } +} + +function cancelFocusFrame(frame: { current: number | null }): void { + if (frame.current !== null) { + cancelAnimationFrame(frame.current) + frame.current = null + } } export function CreateFromPicker({ @@ -66,93 +97,77 @@ export function CreateFromPicker({ const [searchResults, setSearchResults] = React.useState([]) const [isSearching, setIsSearching] = React.useState(false) const listId = React.useId() - const effectiveDefault = repo?.worktreeBaseRef ?? defaultBaseRef + const effectiveDefault = + repo?.worktreeBaseRef ?? probedDefaultBranchRef(defaultBaseRef, searchResults) const selectedValue = value || DEFAULT_VALUE const projectDefaultLabel = t( 'auto.components.automations.CreateFromPicker.ef6d762538', 'Project default' ) const selectedLabel = - value || (effectiveDefault ? `${effectiveDefault} (default)` : projectDefaultLabel) - const compactLabel = value || effectiveDefault || projectDefaultLabel - const branchOptions = React.useMemo(() => { - const options = new Set() - if (effectiveDefault) { - options.add(effectiveDefault) - } - for (const worktree of worktrees) { - const branch = displayBranchName(worktree.branch).trim() - if (branch) { - options.add(branch) - } - } - for (const branch of searchResults) { - options.add(branch) - } - return Array.from(options).sort((left, right) => left.localeCompare(right)) - }, [effectiveDefault, searchResults, worktrees]) - - const renderBranchContextMenu = React.useCallback( - (branch: string, row: React.ReactNode): React.ReactNode => { - if (!onSetDefault || !branch) { - return row - } - const isDefault = branch === effectiveDefault - return ( - - {row} - - { - void onSetDefault(branch) - }} - > - - {isDefault - ? translate('auto.components.agent.AgentCombobox.1b0d6965fa', 'Current default') - : translate('auto.components.agent.AgentCombobox.9c6b59fe58', 'Set as default')} - - - - ) - }, - [effectiveDefault, onSetDefault] + (value ? branchRefLabel(value) : null) || + (effectiveDefault ? `${branchRefLabel(effectiveDefault)} (default)` : projectDefaultLabel) + const compactLabel = value + ? branchRefLabel(value) + : effectiveDefault + ? branchRefLabel(effectiveDefault) + : projectDefaultLabel + const { options: branchOptions, labels } = React.useMemo( + () => createBranchOptions(effectiveDefault, searchResults, worktrees), + [effectiveDefault, searchResults, worktrees] ) - const cancelFocusFrame = React.useCallback((): void => { - if (focusFrameRef.current !== null) { - cancelAnimationFrame(focusFrameRef.current) - focusFrameRef.current = null + function renderBranchContextMenu(branch: string, row: React.ReactNode): React.ReactNode { + if (!onSetDefault || !branch) { + return row } - }, []) + const isDefault = effectiveDefault === branch + return ( + + {row} + + { + void onSetDefault(branch) + }} + > + + {isDefault + ? t('auto.components.agent.AgentCombobox.1b0d6965fa', 'Current default') + : t('auto.components.agent.AgentCombobox.9c6b59fe58', 'Set as default')} + + + + ) + } const setInputNode = React.useCallback( (node: HTMLInputElement | null): void => { if (node === null) { - cancelFocusFrame() + cancelFocusFrame(focusFrameRef) } inputRef.current = node }, - [cancelFocusFrame] + [focusFrameRef, inputRef] ) const focusSearchInput = React.useCallback(() => { - cancelFocusFrame() + cancelFocusFrame(focusFrameRef) focusFrameRef.current = requestAnimationFrame(() => { focusFrameRef.current = null inputRef.current?.focus() }) - }, [cancelFocusFrame]) + }, [focusFrameRef, inputRef]) const handleOpenChange = React.useCallback( (nextOpen: boolean) => { setOpen(nextOpen) if (!nextOpen) { - cancelFocusFrame() + cancelFocusFrame(focusFrameRef) } }, - [cancelFocusFrame] + [focusFrameRef, setOpen] ) React.useEffect(() => { @@ -331,7 +346,7 @@ export function CreateFromPicker({ ? t( 'auto.components.automations.CreateFromPicker.e53d306056', '{{value0}} (default)', - { value0: effectiveDefault } + { value0: branchRefLabel(effectiveDefault) } ) : t( 'auto.components.automations.CreateFromPicker.ef6d762538', @@ -342,7 +357,7 @@ export function CreateFromPicker({ )} {branchOptions - .filter((branch) => branch !== effectiveDefault) + .filter((branch) => !(effectiveDefault === branch)) .map((branch) => renderBranchContextMenu( branch, @@ -358,7 +373,7 @@ export function CreateFromPicker({ className={cn('size-4', value === branch ? 'opacity-100' : 'opacity-0')} /> - {branch} + {labels.get(branch)} ) 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/settings/page/settings-capability-section-renderers.tsx b/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx index f4776568666..69ca9429d21 100644 --- a/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx +++ b/src/renderer/src/components/settings/page/settings-capability-section-renderers.tsx @@ -183,7 +183,11 @@ export function renderDesktopCapabilitySettingsSections( searchEntries={navigation.getSectionSearchEntries('voice')} > {view.isSectionMounted('voice') ? ( - + ) : null} diff --git a/src/renderer/src/components/settings/source-control/source-control-action-recipe-options.ts b/src/renderer/src/components/settings/source-control/source-control-action-recipe-options.ts index 1d6d04b032c..95559c36dbc 100644 --- a/src/renderer/src/components/settings/source-control/source-control-action-recipe-options.ts +++ b/src/renderer/src/components/settings/source-control/source-control-action-recipe-options.ts @@ -27,6 +27,10 @@ export const getActionDescriptions = createLocalizedCatalog((): Record(['amp', 'muse']) + const FALLBACK_AGENT_ARGS_PLACEHOLDER = '--model sonnet' const AGENT_ARGS_PLACEHOLDER_OVERRIDES: Partial> = { @@ -108,7 +115,10 @@ export function getAgentCatalogForAction( return getAgentCatalog() } return getAgentCatalog().filter( - (agent) => TEXT_GENERATION_AGENT_ID_SET.has(agent.id) || agent.id === selectedAgent + (agent) => + (TEXT_GENERATION_AGENT_ID_SET.has(agent.id) && + !(actionId === 'dictationCleanup' && NAMING_ONLY_TEXT_AGENT_IDS.has(agent.id))) || + agent.id === selectedAgent ) } diff --git a/src/renderer/src/components/settings/source-control/text-actions/SourceControlTextActionAgentPicker.tsx b/src/renderer/src/components/settings/source-control/text-actions/SourceControlTextActionAgentPicker.tsx index 469f6f0d646..b6ae73cffc1 100644 --- a/src/renderer/src/components/settings/source-control/text-actions/SourceControlTextActionAgentPicker.tsx +++ b/src/renderer/src/components/settings/source-control/text-actions/SourceControlTextActionAgentPicker.tsx @@ -35,7 +35,10 @@ import { registeredRepoTextModelHostKeys } from './source-control-text-action-mo import { useTextActionModelDiscovery } from './use-text-action-model-discovery' import { textActionPickerEntryView } from './source-control-text-action-picker-entries' -import { AI_TEXT_ACTION_IDS } from '../../../../../../shared/source-control/ai/recipes/source-control-ai-actions' +import { + AI_TEXT_ACTION_IDS, + isGlobalAiTextAction +} from '../../../../../../shared/source-control/ai/recipes/source-control-ai-actions' import type { SourceControlAiSettingsPatch } from '../../../../../../shared/source-control/ai/settings/source-control-ai-settings-types' import { agentPickerDraft, @@ -124,7 +127,7 @@ const TextActionPicker = memo( } const inheritedSource = { ...source, modelOverridesByOperation: inheritedChoices } const repoChoices = { ...repoAi?.modelOverridesByOperation } - if (operation !== 'conversationName') { + if (!isGlobalAiTextAction(operation)) { delete repoChoices[operation] } const inheritedRepo = { ...repoAi, modelOverridesByOperation: repoChoices } @@ -165,18 +168,17 @@ const TextActionPicker = memo( [operation]: { ...source.actions?.[operation], agentId: agent.id } } } - const forcedRepo = - operation !== 'conversationName' - ? { - sourceControlAi: { - ...(ownRepo ?? repoAi), - actionOverrides: { - ...repoAi?.actionOverrides, - [operation]: { ...repoAi?.actionOverrides?.[operation], agentId: agent.id } - } + const forcedRepo = !isGlobalAiTextAction(operation) + ? { + sourceControlAi: { + ...(ownRepo ?? repoAi), + actionOverrides: { + ...repoAi?.actionOverrides, + [operation]: { ...repoAi?.actionOverrides?.[operation], agentId: agent.id } } } - : null + } + : null const inherited = resolveSourceControlAiActionModelDefault( { settings: { diff --git a/src/renderer/src/components/settings/source-control/text-actions/source-control-text-action-picker-save.ts b/src/renderer/src/components/settings/source-control/text-actions/source-control-text-action-picker-save.ts index 69808f28810..76e07a683de 100644 --- a/src/renderer/src/components/settings/source-control/text-actions/source-control-text-action-picker-save.ts +++ b/src/renderer/src/components/settings/source-control/text-actions/source-control-text-action-picker-save.ts @@ -1,3 +1,4 @@ +import { isGlobalAiTextAction } from '../../../../../../shared/source-control/ai/recipes/source-control-ai-actions' import { agentPickerEffectiveChoices, type AgentPickerEntry, @@ -61,7 +62,7 @@ export function saveSourceControlTextPickerDraft({ } } let currentRepo: Pick | null = - operation !== 'conversationName' && repoId + !isGlobalAiTextAction(operation) && repoId ? { sourceControlAi: { ...repoAi, @@ -103,7 +104,7 @@ export function saveSourceControlTextPickerDraft({ currentSource = saved.sourceControlAi nextChoice = currentSource.modelOverridesByOperation?.[operation] nextArgs = currentSource.actions?.[operation]?.agentArgs ?? nextArgs - } else if (operation !== 'conversationName') { + } else if (!isGlobalAiTextAction(operation)) { currentRepo = { sourceControlAi: saved.update.sourceControlAi ?? undefined } nextChoice = currentRepo.sourceControlAi?.modelOverridesByOperation?.[operation] nextArgs = currentRepo.sourceControlAi?.actionOverrides?.[operation]?.agentArgs ?? nextArgs diff --git a/src/renderer/src/components/settings/voice/VoiceCleanupConsentDialog.tsx b/src/renderer/src/components/settings/voice/VoiceCleanupConsentDialog.tsx new file mode 100644 index 00000000000..95780832d7e --- /dev/null +++ b/src/renderer/src/components/settings/voice/VoiceCleanupConsentDialog.tsx @@ -0,0 +1,114 @@ +import { useTranslate, type Translate } from '@/i18n/use-translate' +import { Button } from '../../ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '../../ui/dialog' + +// Only agents whose service is fixed; the others go wherever the user set them up to send. +const AGENT_SERVICES: Record = { + claude: { company: 'Anthropic', plan: 'Claude' }, + codex: { company: 'OpenAI', plan: 'ChatGPT' } +} + +function destination( + request: { agentId: string; agentLabel: string; commandOverridden: boolean }, + t: Translate +): string { + const { agentId, agentLabel } = request + // A replaced command can send prompts anywhere, so only the stock CLI names its company. + const service = request.commandOverridden ? undefined : AGENT_SERVICES[agentId] + return service + ? t( + 'components.settings.voice.cleanup.consent.goesToKnown', + '{{company}}, through {{agent}} on this computer. Counts toward your {{plan}} plan.', + { ...service, agent: agentLabel } + ) + : t( + 'components.settings.voice.cleanup.consent.goesToAgent', + 'Wherever {{agent}} on this computer is set up to send prompts.', + { agent: agentLabel } + ) +} + +/** Asked before dictated text first goes to an agent, and again for each new agent. */ +export function VoiceCleanupConsentDialog({ + request, + onCancel, + onConfirm +}: { + /** The agent text would go to; null keeps the dialog closed. */ + request: { agentId: string; agentLabel: string; commandOverridden: boolean } | null + onCancel: () => void + onConfirm: () => void +}): React.JSX.Element { + const t = useTranslate() + const agentLabel = request?.agentLabel ?? '' + const rows = request + ? [ + { + label: t('components.settings.voice.cleanup.consent.sentLabel', 'Sent'), + value: t( + 'components.settings.voice.cleanup.consent.sent', + 'The dictated text, your vocabulary and your instructions.' + ) + }, + { + label: t('components.settings.voice.cleanup.consent.notSentLabel', 'Not sent'), + value: t( + 'components.settings.voice.cleanup.consent.notSent', + 'Audio, files, or what’s on screen.' + ) + }, + { + label: t('components.settings.voice.cleanup.consent.goesToLabel', 'Goes to'), + value: destination(request, t) + }, + { + label: t('components.settings.voice.cleanup.consent.waitLabel', 'Wait'), + value: t( + 'components.settings.voice.cleanup.consent.wait', + 'Text lands a few seconds later.' + ) + } + ] + : [] + return ( + !open && onCancel()}> + + + + {t('components.settings.voice.cleanup.consent.title', 'Turn on AI cleanup?')} + + + {t( + 'components.settings.voice.cleanup.consent.description', + 'After each dictation, Orca sends the text to {{agent}} to tidy it before it lands.', + { agent: agentLabel } + )} + + +
+ {rows.map((row) => ( +
+
{row.label}
+
{row.value}
+
+ ))} +
+ + + + +
+
+ ) +} diff --git a/src/renderer/src/components/settings/voice/VoiceCleanupInstructionsSetting.tsx b/src/renderer/src/components/settings/voice/VoiceCleanupInstructionsSetting.tsx new file mode 100644 index 00000000000..339cb26b183 --- /dev/null +++ b/src/renderer/src/components/settings/voice/VoiceCleanupInstructionsSetting.tsx @@ -0,0 +1,86 @@ +import { useId, useState } from 'react' +import { BUILT_IN_DICTATION_CLEANUP_INSTRUCTIONS } from '../../../../../shared/dictation-cleanup' +import { useTranslate } from '@/i18n/use-translate' +import { Button } from '../../ui/button' +import { Label } from '../../ui/label' +import { Textarea } from '../../ui/textarea' +import { SettingsRow } from '../form-controls/SettingsFormControls' + +/** Collapsed to a summary; Edit opens the built-in or saved text to change in place. */ +export function VoiceCleanupInstructionsSetting({ + instructions, + onSave +}: { + /** Absent: the built-in instructions. */ + instructions: string | undefined + onSave: (instructions: string | undefined) => void +}): React.JSX.Element { + const t = useTranslate() + const fieldId = useId() + const [draft, setDraft] = useState(null) + const custom = instructions?.trim() ? instructions : undefined + const label = t('components.settings.voice.cleanup.instructions.label', 'Instructions') + if (draft === null) { + return ( + setDraft(custom ?? BUILT_IN_DICTATION_CLEANUP_INSTRUCTIONS)} + > + {t('components.settings.voice.cleanup.instructions.edit', 'Edit')} + + } + /> + ) + } + const save = (): void => { + const text = draft.trim() + onSave(text && text !== BUILT_IN_DICTATION_CLEANUP_INSTRUCTIONS ? text : undefined) + setDraft(null) + } + return ( +
+
+ +

+ {t( + 'components.settings.voice.cleanup.instructions.emptyHint', + 'Leave empty for the built-in ones.' + )} +

+
+