Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.
TypeScript adeagent-ideai-agentsautomationbotclaude-codecodexghosttygrok-bothermes-agentmobile-appmuseopenclawopencodeorchestrationpiruntimeterminalworktreesyc-backed
Keep worktree branches unless CLI deletion is requested (#35948)
Brennan Bensoncf5f427d4372
diff --git a/src/cli/handlers/worktree-removal-request.ts b/src/cli/handlers/worktree-removal-request.tsindex 34ec500a15c..bc1cb0c2f73 100644--- a/src/cli/handlers/worktree-removal-request.ts+++ b/src/cli/handlers/worktree-removal-request.ts@@ -1,3 +1,5 @@+import { z } from 'zod'+import { WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY } from '../../shared/worktree-runtime-capabilities'import type { RuntimeWorktreeRemoveResult } from '../../shared/runtime-types'import { worktreeRemovalReplyTimeoutMs } from '../../shared/worktree/archive-hook-removal-gate'import { RuntimeClientError, type RuntimeClient, type RuntimeRpcSuccess } from '../runtime-client'@@ -6,6 +8,7 @@ export type WorktreeRemovalRequest = {worktree: stringhostId: stringforce: boolean+ deleteBranch?: booleanrunHooks: booleanallowFailedArchiveHook: boolean}@@ -15,20 +18,44 @@ export async function requestWorktreeRemoval(client: RuntimeClient,request: WorktreeRemovalRequest): Promise<RuntimeRpcSuccess<RuntimeWorktreeRemoveResult>> {+ let dispatched = false+ const { deleteBranch, ...legacyRequest } = request+ const legacy = {+ ...legacyRequest,+ // --force also waives PTY-stop proof.+ allowUnverifiedPtyStop: request.force,+ waitForBackgroundRemoval: true+ }try {- return await client.call<RuntimeWorktreeRemoveResult>(- 'worktree.rm',- {- ...request,- // --force also waives PTY-stop proof.- allowUnverifiedPtyStop: request.force,- waitForBackgroundRemoval: true- },- { timeoutMs: worktreeRemovalReplyTimeoutMs(request.runHooks) }- )+ return await client.call<RuntimeWorktreeRemoveResult>('worktree.rm', legacy, {+ timeoutMs: worktreeRemovalReplyTimeoutMs(request.runHooks),+ requestSelection: {+ paramsForStatus: (raw) => {+ const parsed = BranchPolicyStatus.safeParse(raw)+ if (!parsed.success) {+ throw new RuntimeClientError(+ 'invalid_runtime_response',+ 'The Orca host returned an invalid status response.'+ )+ }+ if (+ parsed.data.capabilities?.includes(WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY)+ ) {+ return deleteBranch === undefined ? legacy : { ...legacy, deleteBranch }+ }+ console.error(+ 'warning: This Orca host is older and uses its existing branch policy. Keep-by-default and --delete-branch do not apply.'+ )+ return legacy+ },+ onDispatch: () => {+ dispatched = true+ }+ }+ })} catch (error) {// The host keeps deleting after this client stops waiting.- if (error instanceof RuntimeClientError && error.code === 'runtime_timeout') {+ if (dispatched && error instanceof RuntimeClientError && error.code === 'runtime_timeout') {throw new RuntimeClientError('worktree_removal_in_progress',`Stopped waiting, but Orca may still be deleting the checkout. Check \`orca worktree show --worktree ${request.worktree}\` before retrying.`@@ -37,3 +64,5 @@ export async function requestWorktreeRemoval(throw error}}++const BranchPolicyStatus = z.object({ capabilities: z.array(z.string()).optional() })diff --git a/src/cli/handlers/worktree.ts b/src/cli/handlers/worktree.tsindex da0dde3b5fe..024effe719d 100644--- a/src/cli/handlers/worktree.ts+++ b/src/cli/handlers/worktree.ts@@ -285,6 +285,7 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {worktree,hostId,force: flags.get('force') === true,+ deleteBranch: flags.get('delete-branch') === true,runHooks: flags.get('run-hooks') === true,// Archive failure waivers protect user data separately from --force's PTY-stop waiver.allowFailedArchiveHook: flags.get('allow-failed-archive-hook') === true@@ -295,7 +296,9 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {// Hosts that predate waiting answer on acceptance.value.removing? 'removed: false\nOrca is still deleting the checkout in the background.'- : `removed: ${value.removed}`+ : value.removed === true+ ? 'removed: true'+ : 'Removal is not confirmed.')}}diff --git a/src/cli/index.test.ts b/src/cli/index.test.tsindex 392de5ff691..813bf9bf869 100644--- a/src/cli/index.test.ts+++ b/src/cli/index.test.ts@@ -134,7 +134,13 @@ describe('command aliases dispatch to the canonical handler', () => {2,'worktree.rm',expect.objectContaining({ waitForBackgroundRemoval: true }),- { timeoutMs: worktreeRemovalReplyTimeoutMs(true) }+ {+ timeoutMs: worktreeRemovalReplyTimeoutMs(true),+ requestSelection: {+ paramsForStatus: expect.any(Function),+ onDispatch: expect.any(Function)+ }+ })expect(logSpy).toHaveBeenCalledWith('removed: true')})@@ -153,6 +159,23 @@ describe('command aliases dispatch to the canonical handler', () => {)})+ it('leaves missing removal and branch outcomes unconfirmed', async () => {+ queueFixtures(+ callMock,+ okFixture('show', { worktree: { hostId: 'local' } }),+ okFixture('rm', {})+ )+ await main(['worktree', 'rm', '--worktree', 'id:wt-1', '--delete-branch'], '/tmp/repo')+ expect(logSpy).toHaveBeenCalledWith('Removal is not confirmed.')+ queueFixtures(+ callMock,+ okFixture('show', { worktree: { hostId: 'local' } }),+ okFixture('rm', {})+ )+ await main(['worktree', 'rm', '--worktree', 'id:wt-1', '--json'], '/tmp/repo')+ expect(JSON.parse(String(logSpy.mock.calls.at(-1)?.[0])).result).toEqual({})+ })+it('fails closed when worktree removal cannot resolve a host', async () => {queueFixtures(callMock, okFixture('req_show', { worktree: { id: 'wt-1' } }))const priorExitCode = process.exitCodediff --git a/src/cli/runtime/client-execution-host.test.ts b/src/cli/runtime/client-execution-host.test.tsindex 8b6a14c9e6d..e2fc80d5ac5 100644--- a/src/cli/runtime/client-execution-host.test.ts+++ b/src/cli/runtime/client-execution-host.test.ts@@ -83,6 +83,7 @@ it("stays on its own server with an agent's empty selectors, and explicit flagsundefined,60_000,expect.anything(),+ undefined,undefined)expect(await requestServer(new RuntimeClient(root, undefined, null, 'other-server'))).toBe(diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.tsindex 951984e7bdd..b711baee051 100644--- a/src/cli/runtime/client.ts+++ b/src/cli/runtime/client.ts@@ -1,7 +1,6 @@import { randomUUID } from 'node:crypto'import type { CliStatusResult, RuntimeStatus } from '../../shared/runtime-types'import { runtimeHostConnectionState } from '../../shared/runtime-host-connection-state'-import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope'import {isDurableMutation,isOrchestrationMutation,@@ -18,7 +17,12 @@ import {projectRemoteAppStatus} from './status'import { sendRequest } from './transport'-import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcSuccess } from './types'+import {+ RuntimeClientError,+ RuntimeRpcFailureError,+ type RuntimeRpcSuccess,+ type RuntimeCallOptions+} from './types'import {attachDurableMutationRecovery,attachLegacyTerminalPromptRecovery,@@ -52,7 +56,6 @@ const loadWebSocketTransport = async () => await import('./websocket-transport.jexport class RuntimeClient {readonly userDataPath: string- private readonly requestTimeoutMs: numberprivate readonly remote: PairedRuntimeConnection | nullreadonly environmentSelector: string | nullprivate readonly cliExecutable: string@@ -67,14 +70,13 @@ export class RuntimeClient {// Browser session cold starts can take 15–30 seconds; allow time for initialization.constructor(userDataPath = getDefaultUserDataPath(),- requestTimeoutMs = 60_000,+ private readonly requestTimeoutMs = 60_000,remotePairingCode = process.env.ORCA_PAIRING_CODE ?? process.env.ORCA_REMOTE_PAIRING ?? null,environmentSelector = process.env.ORCA_ENVIRONMENT ?? null,cliExecutable = resolveOrchestrationCliExecutable(),originalArgs?: readonly string[]) {this.userDataPath = userDataPath- this.requestTimeoutMs = requestTimeoutMsthis.environmentSelector = environmentSelectorthis.cliExecutable = cliExecutablethis.originalArgs = originalArgs ? [...originalArgs] : undefined@@ -90,11 +92,7 @@ export class RuntimeClient {async call<TResult>(method: string,params?: unknown,- options?: {- timeoutMs?: number- legacyTerminalPrompt?: true- terminalPromptPreflight?: { runtimeId: string | null }- } & RuntimeOrchestrationEnvelope+ options?: RuntimeCallOptions): Promise<RuntimeRpcSuccess<TResult>> {const effectiveTimeoutMs = options?.timeoutMs ?? this.resolveMethodTimeoutMs(method, params)const orchestrationMutation = isOrchestrationMutation(method, params)@@ -152,7 +150,8 @@ export class RuntimeClient {method,params,timeoutMs: effectiveTimeoutMs,- envelope+ envelope,+ requestSelection: options?.requestSelection})} catch (error) {throw recover(error, null)@@ -178,7 +177,8 @@ export class RuntimeClient {params,effectiveTimeoutMs,envelope,- expectedRuntimeSource+ expectedRuntimeSource,+ options?.requestSelection ? { requestSelection: options.requestSelection } : undefined)} catch (error) {throw recover(error, metadata.runtimeId ?? null)diff --git a/src/cli/runtime/remote-runtime-compat-gate.ts b/src/cli/runtime/remote-runtime-compat-gate.tsindex 0efe1d825b4..06e7350fa69 100644--- a/src/cli/runtime/remote-runtime-compat-gate.ts+++ b/src/cli/runtime/remote-runtime-compat-gate.ts@@ -4,7 +4,10 @@ import {MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,RUNTIME_PROTOCOL_VERSION} from '../../shared/protocol-version'-import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope'+import type {+ RuntimeRequestSelection,+ RuntimeOrchestrationEnvelope+} from '../../shared/runtime-rpc-envelope'import type { RuntimeStatus } from '../../shared/runtime-types'import { markEnvironmentUsed } from './environments'import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } from './types'@@ -33,8 +36,9 @@ export class RemoteRuntimeCompatGate {params: unknowntimeoutMs: numberenvelope?: RuntimeOrchestrationEnvelope+ requestSelection?: RuntimeRequestSelection}): Promise<RuntimeRpcResponse<TResult>> {- if (this.checked || args.method === 'status.get') {+ if (!args.requestSelection && (this.checked || args.method === 'status.get')) {return args.transport.sendWebSocketRequest<TResult>(args.connection,args.method,@@ -59,7 +63,8 @@ export class RemoteRuntimeCompatGate {})}},- args.envelope+ args.envelope,+ args.requestSelection)}diff --git a/src/cli/runtime/status.ts b/src/cli/runtime/status.tsindex 0abe4d62c9e..4714e4ff83d 100644--- a/src/cli/runtime/status.ts+++ b/src/cli/runtime/status.ts@@ -68,11 +68,13 @@ export async function getOfflineRuntimeAdmission(1000,undefined,undefined,- (error) => {- const code = 'code' in error ? error.code : undefined- return (code === 'EPERM' || code === 'EACCES') && isProcessRunning(metadata.pid)- ? runtimeAccessDeniedError(error)- : null+ {+ classifySocketError: (error) => {+ const code = 'code' in error ? error.code : undefined+ return (code === 'EPERM' || code === 'EACCES') && isProcessRunning(metadata.pid)+ ? runtimeAccessDeniedError(error)+ : null+ }})const status = projectConnectedStatus(metadata, response)diff --git a/src/cli/runtime/transport.test.ts b/src/cli/runtime/transport.test.tsindex caab9ceb794..31871e1b96f 100644--- a/src/cli/runtime/transport.test.ts+++ b/src/cli/runtime/transport.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync } from 'node:fs'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { once } from 'node:events'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -7,8 +7,11 @@ import type * as Net from 'node:net'import { afterEach, describe, expect, it, vi } from 'vitest'import type { RuntimeMetadata } from '../../shared/runtime-bootstrap'import { MAX_TIMER_DELAY_MS } from '../../shared/timer-delay'-import { formatCliError } from '../cli-error'import { sendRequest } from './transport'+import { formatCliError } from '../cli-error'+import { RuntimeClient } from './client'+import { getRuntimeMetadataPath } from '../../shared/runtime-bootstrap'+import { requestWorktreeRemoval } from '../handlers/worktree-removal-request'vi.mock('node:net', async (importOriginal) => {const net = await importOriginal<typeof Net>()@@ -110,6 +113,189 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => {)})+ it.each(['preflight', 'mutation'] as const)(+ 'reports a timeout during %s truthfully',+ async (phase) => {+ const directory = mkdtempSync(join(tmpdir(), 'orca-removal-timeout-'))+ roots.push(directory)+ const endpoint = join(directory, 'runtime.sock')+ const received = Promise.withResolvers<void>()+ const methods: string[] = []+ const server = createServer((socket) => {+ sockets.add(socket)+ socket.once('close', () => sockets.delete(socket))+ socket.on('data', (data) => {+ const request = JSON.parse(String(data).trim())+ methods.push(request.method)+ if (phase === 'mutation' && request.method === 'status.get') {+ socket.write(+ `${JSON.stringify({+ id: request.id,+ ok: true,+ result: { capabilities: ['worktree.remove-branch-policy.v1'] },+ _meta: { runtimeId: 'timeout' }+ })}\n`+ )+ } else {+ received.resolve()+ }+ })+ })+ servers.add(server)+ await new Promise<void>((resolve) => server.listen(endpoint, resolve))+ writeFileSync(+ getRuntimeMetadataPath(directory),+ JSON.stringify({+ runtimeId: 'timeout',+ pid: process.pid,+ transports: [{ kind: 'unix', endpoint }],+ authToken: 'test',+ startedAt: 1+ })+ )+ const client = new RuntimeClient(directory, 5000, null, null)+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ const response = requestWorktreeRemoval(client, {+ worktree: 'id:task',+ hostId: 'local',+ force: false,+ deleteBranch: false,+ runHooks: false,+ allowFailedArchiveHook: false+ }).catch((error: unknown) => error)+ await received.promise+ await vi.runAllTimersAsync()+ expect(await response).toMatchObject({+ code: phase === 'preflight' ? 'runtime_timeout' : 'worktree_removal_in_progress'+ })+ expect(methods).toEqual(+ phase === 'preflight' ? ['status.get'] : ['status.get', 'worktree.rm']+ )+ }+ )++ it.each([+ 'capable',+ 'absent',+ 'empty',+ 'unrelated',+ 'malformed',+ 'error',+ 'close',+ 'after-send',+ 'prepare'+ ] as const)('selects the local wire request without replay: %s', async (mode) => {+ const root = mkdtempSync(join(tmpdir(), 'orca-selection-'))+ roots.push(root)+ const endpoint = join(root, 'runtime.sock')+ const requests: { id: string; method: string; params?: unknown }[] = []+ const server = createServer((socket) => {+ sockets.add(socket)+ socket.once('close', () => sockets.delete(socket))+ socket.on('data', (data) => {+ const request: { id: string; method: string; params?: unknown } = JSON.parse(+ String(data).trim()+ )+ requests.push(request)+ if (mode === 'close' || (mode === 'after-send' && request.method === 'worktree.rm')) {+ socket.end()+ return+ }+ socket.write(+ `${JSON.stringify({+ id: request.id,+ ok: mode !== 'error',+ ...(mode === 'error'+ ? { error: { code: 'failed', message: 'status failed' } }+ : {+ result:+ request.method === 'worktree.rm'+ ? { removed: true }+ : mode === 'capable'+ ? { capabilities: ['worktree.remove-branch-policy.v1'] }+ : mode === 'empty'+ ? { capabilities: [] }+ : mode === 'unrelated'+ ? { capabilities: ['future'] }+ : mode === 'malformed'+ ? { capabilities: 42 }+ : {}+ }),+ _meta: { runtimeId: 'selection' }+ })}\n`+ )+ })+ })+ servers.add(server)+ await new Promise<void>((resolve) => server.listen(endpoint, resolve))+ writeFileSync(+ getRuntimeMetadataPath(root),+ JSON.stringify({+ runtimeId: 'selection',+ pid: process.pid,+ transports: [{ kind: 'unix', endpoint }],+ authToken: 'test',+ startedAt: 1+ })+ )+ const warning = vi.spyOn(console, 'error').mockImplementation(() => {})+ const selected = {+ worktree: 'id:task',+ hostId: 'local',+ force: false,+ runHooks: false,+ allowFailedArchiveHook: false+ }+ try {+ if (mode === 'prepare') {+ const dispatched = vi.fn()+ await expect(+ sendRequest(+ {+ runtimeId: 'selection',+ pid: process.pid,+ transports: [{ kind: 'unix', endpoint }],+ authToken: 'test',+ startedAt: 1+ },+ 'worktree.rm',+ {},+ 5000,+ undefined,+ undefined,+ { requestSelection: { paramsForStatus: () => ({ value: 1n }), onDispatch: dispatched } }+ )+ ).rejects.toThrow()+ expect(dispatched).not.toHaveBeenCalled()+ } else {+ const promise = requestWorktreeRemoval(new RuntimeClient(root, 5000, null, null), {+ ...selected,+ deleteBranch: false+ })+ await (['capable', 'absent', 'empty', 'unrelated'].includes(mode)+ ? expect(promise).resolves.toMatchObject({ result: { removed: true } })+ : expect(promise).rejects.toBeInstanceOf(Error))+ }+ const sent = ['capable', 'absent', 'empty', 'unrelated', 'after-send'].includes(mode)+ expect(requests.map((request) => request.method)).toEqual(+ sent ? ['status.get', 'worktree.rm'] : ['status.get']+ )+ if (sent) {+ expect(requests[1].params).toEqual({+ ...selected,+ allowUnverifiedPtyStop: false,+ waitForBackgroundRemoval: true,+ ...(mode === 'capable' ? { deleteBranch: false } : {})+ })+ }+ expect(warning.mock.calls).toHaveLength(+ ['absent', 'empty', 'unrelated', 'after-send'].includes(mode) ? 1 : 0+ )+ } finally {+ warning.mockRestore()+ }+ })+it('refreshes the per-call timeout when the runtime sends keepalive frames', async () => {const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-'))roots.push(userDataPath)diff --git a/src/cli/runtime/transport.ts b/src/cli/runtime/transport.tsindex 981deaa87ec..8dab3d6a3de 100644--- a/src/cli/runtime/transport.ts+++ b/src/cli/runtime/transport.ts@@ -3,10 +3,11 @@ import { randomUUID } from 'node:crypto'import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap'import type {ExpectedRuntimeSource,- RuntimeOrchestrationEnvelope+ RuntimeOrchestrationEnvelope,+ RuntimeRequestSelection} from '../../shared/runtime-rpc-envelope'import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema'-import { RuntimeClientError, type RuntimeRpcResponse } from './types'+import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcResponse } from './types'import { MAX_TIMER_DELAY_MS, isSafeTimerDelayMs } from '../../shared/timer-delay'import { runtimeAccessDeniedError } from './runtime-access-denied'@@ -18,8 +19,12 @@ export async function sendRequest<TResult>(envelope?: RuntimeOrchestrationEnvelope,// Federation forwards envelopes; the runtime fence must stay local.expectedRuntimeSource?: ExpectedRuntimeSource,- classifySocketError: (error: Error) => RuntimeClientError | null = runtimeAccessDeniedError+ options: {+ classifySocketError?: (error: Error) => RuntimeClientError | null+ requestSelection?: RuntimeRequestSelection+ } = {}): Promise<RuntimeRpcResponse<TResult>> {+ const { classifySocketError = runtimeAccessDeniedError, requestSelection } = optionsif (!isSafeTimerDelayMs(timeoutMs)) {throw new RuntimeClientError('invalid_argument',@@ -41,6 +46,9 @@ export async function sendRequest<TResult>(let lineSegments: string[] = []let settled = falseconst requestId = randomUUID()+ const statusRequestId = requestSelection ? randomUUID() : null+ let awaitingStatus = statusRequestId !== null+ let selectedParams = paramsconst timeout = setTimeout(() => {if (settled) {@@ -159,7 +167,7 @@ export async function sendRequest<TResult>(}const response = frame as RuntimeRpcResponse<TResult>- if (response.id !== requestId) {+ if (response.id !== (awaitingStatus ? statusRequestId : requestId)) {finish({ok: false,error: new RuntimeClientError(@@ -180,17 +188,31 @@ export async function sendRequest<TResult>(})return}+ if (awaitingStatus) {+ try {+ if (frame.ok === false) {+ throw new RuntimeRpcFailureError(frame)+ }+ selectedParams = requestSelection?.paramsForStatus(frame.result)+ } catch (error) {+ finish({ ok: false, error: error instanceof Error ? error : new Error(String(error)) })+ return+ }+ awaitingStatus = false+ send(requestId, method, selectedParams)+ continue+ }finish({ ok: true, response })return}})- socket.on('connect', () => {- socket.write(- `${JSON.stringify({- id: requestId,+ const send = (id: string, requestedMethod: string, requestedParams: unknown): void => {+ try {+ const serialized = `${JSON.stringify({+ id,authToken: metadata.authToken,- method,- params,+ method: requestedMethod,+ params: requestedParams,orchestrationCapability: envelope?.orchestrationCapability,orchestrationContractVersion: envelope?.orchestrationContractVersion,orchestrationRequestId: envelope?.orchestrationRequestId,@@ -198,6 +220,19 @@ export async function sendRequest<TResult>(orchestrationCompatibilityEvidence: envelope?.orchestrationCompatibilityEvidence,expectedRuntimeSource})}\n`+ if (id === requestId) {+ requestSelection?.onDispatch?.()+ }+ socket.write(serialized)+ } catch (error) {+ finish({ ok: false, error: error instanceof Error ? error : new Error(String(error)) })+ }+ }+ socket.on('connect', () => {+ send(+ statusRequestId ?? requestId,+ statusRequestId ? 'status.get' : method,+ statusRequestId ? undefined : params)})})diff --git a/src/cli/runtime/types.ts b/src/cli/runtime/types.tsindex 0e46ff1eebd..127c86fe2cf 100644--- a/src/cli/runtime/types.ts+++ b/src/cli/runtime/types.ts@@ -1,4 +1,8 @@-import type { RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope'+import type {+ RuntimeOrchestrationEnvelope,+ RuntimeRequestSelection,+ RuntimeRpcFailure+} from '../../shared/runtime-rpc-envelope'import { redactOrchestrationCompatibilitySecrets } from '../../shared/orchestration-compatibility-evidence'export type {@@ -7,6 +11,13 @@ export type {RuntimeRpcSuccess} from '../../shared/runtime-rpc-envelope'+export type RuntimeCallOptions = {+ timeoutMs?: number+ legacyTerminalPrompt?: true+ terminalPromptPreflight?: { runtimeId: string | null }+ requestSelection?: RuntimeRequestSelection+} & RuntimeOrchestrationEnvelope+export class RuntimeClientError extends Error {readonly code: string// Structured recovery data is exposed in both human and JSON errors.diff --git a/src/cli/runtime/websocket-transport.test.ts b/src/cli/runtime/websocket-transport.test.tsindex c2cf50088e7..be4116e710b 100644--- a/src/cli/runtime/websocket-transport.test.ts+++ b/src/cli/runtime/websocket-transport.test.ts@@ -15,7 +15,10 @@ import {generateKeyPair,publicKeyToBase64} from '../../shared/e2ee-crypto'+import { sendWebSocketRequestWithStatusPreflight } from './websocket-transport'+import { getRemoteRuntimeRequestAdmissionEvidence } from '../../shared/remote-runtime/requests/remote-runtime-prepared-request-admission'import { RuntimeClient } from './client'+import { requestWorktreeRemoval } from '../handlers/worktree-removal-request'import { launchOrcaApp } from './launch'import { addEnvironmentFromPairingCode } from './environments'import { RuntimeClientError } from './types'@@ -50,6 +53,7 @@ type TestRuntime = {deviceToken: stringauthFrames: Record<string, unknown>[]requestMethods: string[]+ requestParams: unknown[]connectionCount: () => numberclose: () => Promise<void>}@@ -266,6 +270,188 @@ describe('CLI remote WebSocket transport', () => {}})})++ it.each(['status', 'capable-mutation', 'legacy-mutation'] as const)(+ 'reports paired timeout at %s without replay',+ async (phase) => {+ const received = Promise.withResolvers<void>()+ const status: Parameters<typeof startTestRuntime>[1] = {+ capabilities: ['worktree.remove-branch-policy.v1']+ }+ const runtime = await startTestRuntime('timeout', status)+ servers.push(runtime)+ const client = new RuntimeClient(+ '/tmp/unused',+ 5000,+ encodePairingOffer({+ v: 2,+ endpoint: runtime.endpoint,+ deviceToken: runtime.deviceToken,+ publicKeyB64: runtime.publicKeyB64+ })+ )+ await client.getCliStatus()+ status.hold = phase === 'status' ? 'status.get' : 'worktree.rm'+ if (phase === 'legacy-mutation') {+ status.capabilities = undefined+ }+ status.onRequest = (method) => {+ if (method === status.hold) {+ received.resolve()+ }+ }+ const warning = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ try {+ const response = requestWorktreeRemoval(client, {+ worktree: 'id:task',+ hostId: 'local',+ force: false,+ deleteBranch: false,+ runHooks: false,+ allowFailedArchiveHook: false+ }).catch((error: unknown) => error)+ await received.promise+ await vi.runAllTimersAsync()+ expect(await response).toMatchObject({+ code: phase === 'status' ? 'runtime_timeout' : 'worktree_removal_in_progress'+ })+ expect(runtime.requestMethods).toEqual(+ phase === 'status'+ ? ['status.get', 'status.get']+ : ['status.get', 'status.get', 'worktree.rm']+ )+ expect(warning.mock.calls).toHaveLength(phase === 'legacy-mutation' ? 1 : 0)+ expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({+ pendingRequestCount: 0,+ retainedBytes: 0+ })+ } finally {+ vi.useRealTimers()+ warning.mockRestore()+ }+ }+ )++ it('selects paired params before serialization and releases failed preparation without dispatch', async () => {+ const runtime = await startTestRuntime('prepare')+ servers.push(runtime)+ const dispatched = vi.fn()+ await expect(+ sendWebSocketRequestWithStatusPreflight(+ {+ endpoint: runtime.endpoint,+ hostPublicKeyB64: runtime.publicKeyB64,+ credential: { kind: 'token', deviceToken: runtime.deviceToken }+ },+ 'worktree.rm',+ {},+ 5000,+ () => {},+ undefined,+ { paramsForStatus: () => ({ value: 1n }), onDispatch: dispatched }+ )+ ).rejects.toBeInstanceOf(Error)+ expect(dispatched).not.toHaveBeenCalled()+ expect(runtime.requestMethods).toEqual(['status.get'])+ expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({+ pendingRequestCount: 0,+ retainedBytes: 0+ })+ })++ it.each([+ 'capable',+ 'absent',+ 'empty',+ 'unrelated',+ 'malformed',+ 'failed',+ 'disconnect',+ 'after-send',+ 'protocol',+ 'auth'+ ] as const)(+ 'preflights branch intent on the mutation socket after cached compatibility: %s',+ async (mode) => {+ const status: NonNullable<Parameters<typeof startTestRuntime>[1]> = {+ capabilities: ['worktree.remove-branch-policy.v1'],+ malformed: false,+ failure: false,+ disconnect: false,+ mutationDisconnect: false,+ rejectAuth: false,+ runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION+ }+ const runtime = await startTestRuntime('removal', status)+ servers.push(runtime)+ const client = new RuntimeClient(+ '/tmp/unused',+ 5000,+ encodePairingOffer({+ v: 2,+ endpoint: runtime.endpoint,+ deviceToken: runtime.deviceToken,+ publicKeyB64: runtime.publicKeyB64+ })+ )+ await client.getCliStatus()+ if (mode === 'absent') {+ status.capabilities = undefined+ }+ if (mode === 'empty') {+ status.capabilities = []+ }+ if (mode === 'unrelated') {+ status.capabilities = ['future.capability']+ }+ status.malformed = mode === 'malformed'+ const successful = ['capable', 'absent', 'empty', 'unrelated'].includes(mode)+ const warning = vi.spyOn(console, 'error').mockImplementation(() => {})+ status.failure = mode === 'failed'+ status.disconnect = mode === 'disconnect'+ status.mutationDisconnect = mode === 'after-send'+ status.rejectAuth = mode === 'auth'+ if (mode === 'protocol') {+ status.runtimeProtocolVersion = 0+ }+ const removal = requestWorktreeRemoval(client, {+ worktree: 'id:task',+ hostId: 'local',+ force: false,+ deleteBranch: false,+ runHooks: false,+ allowFailedArchiveHook: false+ })+ await (successful+ ? expect(removal).resolves.toMatchObject({ result: { removed: true } })+ : expect(removal).rejects.toBeInstanceOf(Error))+ expect(+ warning.mock.calls.filter(([message]) => String(message).includes('host is older'))+ ).toHaveLength(successful && mode !== 'capable' ? 1 : 0)+ if (successful) {+ expect(runtime.requestParams.at(-1)).toEqual({+ worktree: 'id:task',+ hostId: 'local',+ force: false,+ runHooks: false,+ allowFailedArchiveHook: false,+ allowUnverifiedPtyStop: false,+ waitForBackgroundRemoval: true,+ ...(mode === 'capable' ? { deleteBranch: false } : {})+ })+ }+ warning.mockRestore()+ expect(runtime.connectionCount()).toBe(2)+ expect(runtime.requestMethods).toEqual(+ successful || mode === 'after-send'+ ? ['status.get', 'status.get', 'worktree.rm']+ : mode === 'auth'+ ? ['status.get']+ : ['status.get', 'status.get']+ )+ }+ )})async function startTestRuntime(@@ -281,6 +467,13 @@ async function startTestRuntime(reason: 'manual-service-update-required'}capabilities?: string[]+ malformed?: boolean+ failure?: boolean+ hold?: string+ onRequest?: (method: string) => void+ disconnect?: boolean+ mutationDisconnect?: boolean+ rejectAuth?: booleandegradations?: RuntimeStatus['degradations']} = {}): Promise<TestRuntime> {@@ -290,6 +483,7 @@ async function startTestRuntime(const wss = new WebSocketServer({ server: httpServer })const authFrames: Record<string, unknown>[] = []const requestMethods: string[] = []+ const requestParams: unknown[] = []let connectionCount = 0wss.on('connection', (ws) => {@@ -321,7 +515,11 @@ async function startTestRuntime(deviceToken?: string}authFrames.push(auth)- if (auth.type !== 'e2ee_auth' || auth.deviceToken !== deviceToken) {+ if (+ auth.type !== 'e2ee_auth' ||+ auth.deviceToken !== deviceToken ||+ statusOverrides.rejectAuth+ ) {ws.send(encrypt(JSON.stringify({ type: 'e2ee_error' }), sharedKey))ws.close(4001, 'auth failed')return@@ -331,39 +529,63 @@ async function startTestRuntime(return}- const request = JSON.parse(plaintext) as { id: string; method: string }+ const request: { id: string; method: string; params?: unknown } = JSON.parse(plaintext)requestMethods.push(request.method)+ requestParams.push(request.params)+ statusOverrides.onRequest?.(request.method)+ if (request.method === statusOverrides.hold) {+ return+ }+ if (request.method === 'status.get' && statusOverrides.disconnect) {+ ws.close()+ return+ }+ if (request.method === 'worktree.rm' && statusOverrides.mutationDisconnect) {+ ws.close()+ return+ }const response =- request.method === 'status.get'+ request.method === 'status.get' && statusOverrides.failure? {- id: request.id,- ok: true,- result: {- runtimeId,- rendererGraphEpoch: 1,- graphStatus: 'ready',- authoritativeWindowId: null,- desktopWindowStatus: statusOverrides.desktopWindowStatus,- liveTabCount: 0,- liveLeafCount: 0,- runtimeProtocolVersion:- statusOverrides.runtimeProtocolVersion ?? RUNTIME_PROTOCOL_VERSION,- minCompatibleRuntimeClientVersion:- statusOverrides.minCompatibleRuntimeClientVersion ??- MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,- appVersion: statusOverrides.appVersion,- remoteUpdateSupport: statusOverrides.remoteUpdateSupport,- capabilities: statusOverrides.capabilities,- degradations: statusOverrides.degradations- },- _meta: { runtimeId }- }- : {id: request.id,ok: false,- error: { code: 'method_not_found', message: 'Unknown method' },+ error: { code: 'runtime_unavailable', message: 'status failed' },_meta: { runtimeId }}+ : request.method === 'worktree.rm'+ ? { id: request.id, ok: true, result: { removed: true }, _meta: { runtimeId } }+ : request.method === 'status.get'+ ? {+ id: request.id,+ ok: true,+ result: statusOverrides.malformed+ ? { capabilities: 42 }+ : {+ runtimeId,+ rendererGraphEpoch: 1,+ graphStatus: 'ready',+ authoritativeWindowId: null,+ desktopWindowStatus: statusOverrides.desktopWindowStatus,+ liveTabCount: 0,+ liveLeafCount: 0,+ runtimeProtocolVersion:+ statusOverrides.runtimeProtocolVersion ?? RUNTIME_PROTOCOL_VERSION,+ minCompatibleRuntimeClientVersion:+ statusOverrides.minCompatibleRuntimeClientVersion ??+ MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,+ appVersion: statusOverrides.appVersion,+ remoteUpdateSupport: statusOverrides.remoteUpdateSupport,+ capabilities: statusOverrides.capabilities,+ degradations: statusOverrides.degradations+ },+ _meta: { runtimeId }+ }+ : {+ id: request.id,+ ok: false,+ error: { code: 'method_not_found', message: 'Unknown method' },+ _meta: { runtimeId }+ }ws.send(encrypt(JSON.stringify(response), sharedKey))})})@@ -380,6 +602,7 @@ async function startTestRuntime(deviceToken,authFrames,requestMethods,+ requestParams,connectionCount: () => connectionCount,close: async () => {await new Promise<void>((resolve) => {diff --git a/src/cli/runtime/websocket-transport.ts b/src/cli/runtime/websocket-transport.tsindex 5ed2177da82..76253b4d92f 100644--- a/src/cli/runtime/websocket-transport.ts+++ b/src/cli/runtime/websocket-transport.ts@@ -1,5 +1,8 @@import type { PairedRuntimeConnection } from '../../shared/paired-runtime-connection'-import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope'+import type {+ RuntimeRequestSelection,+ RuntimeOrchestrationEnvelope+} from '../../shared/runtime-rpc-envelope'import { RemoteRuntimeClientError } from '../../shared/remote-runtime/remote-runtime-client-error'import { AGENT_LAUNCH_RUNTIME_CAPABILITY } from '../../shared/agent-launch-runtime-capability'import {@@ -43,7 +46,8 @@ export async function sendWebSocketRequestWithStatusPreflight<TResult>(params: unknown,timeoutMs: number,validateStatus: (response: RuntimeRpcResponse<RuntimeStatus>) => void,- envelope?: RuntimeOrchestrationEnvelope+ envelope?: RuntimeOrchestrationEnvelope,+ requestSelection?: RuntimeRequestSelection): Promise<RuntimeRpcResponse<TResult>> {try {return await sendRemoteRuntimeRequestWithStatusPreflight<TResult>(@@ -53,7 +57,9 @@ export async function sendWebSocketRequestWithStatusPreflight<TResult>(timeoutMs,validateStatus,envelope,- CLI_CLIENT_CAPABILITIES+ CLI_CLIENT_CAPABILITIES,+ undefined,+ requestSelection)} catch (error) {if (error instanceof RemoteRuntimeClientError) {diff --git a/src/cli/specs/core.ts b/src/cli/specs/core.tsindex 2ee4c9faa69..9eb93abda59 100644--- a/src/cli/specs/core.ts+++ b/src/cli/specs/core.ts@@ -141,15 +141,22 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [destructive: true,summary: 'Remove a Git worktree or a folder workspace entry from Orca',usage:- 'orca worktree rm --worktree <selector> [--force] [--run-hooks] [--allow-failed-archive-hook] [--json]',- allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'force', 'run-hooks', 'allow-failed-archive-hook'],+ 'orca worktree rm --worktree <selector> [--force] [--delete-branch] [--run-hooks] [--allow-failed-archive-hook] [--json]',+ allowedFlags: [+ ...GLOBAL_FLAGS,+ 'worktree',+ 'force',+ 'delete-branch',+ 'run-hooks',+ 'allow-failed-archive-hook'+ ],notes: ['For a non-root folder workspace, removes its Orca entry and stops its sessions without deleting the folder or touching Git. The folder project root cannot be removed with this command.','Use --worktree "id:<full-instance-id>" with the full id from orca worktree list --json to select one folder workspace; several entries can share the same path.','Repo-defined orca.yaml archive hooks are skipped unless --run-hooks is passed.','With --run-hooks, a failed archive hook blocks the removal: nothing is stopped, deleted or deregistered, and the command exits non-zero with error code worktree_archive_hook_failed. --force does not waive this.','Pass --allow-failed-archive-hook to delete anyway after the hook has run and failed; the waived failure is reported back on result.archiveHookOverride. It requires --run-hooks and is rejected without it, because with no hook running there is no failure to waive.',- 'For Git worktrees, removal also attempts to delete the checked-out local branch, with or without --force. Orca retains branches it knows predated the worktree and any branch whose changes it cannot prove are already merged.'+ 'On newer hosts with branch-choice support, Git worktree removal keeps the local branch, including with --force. Pass --delete-branch to attempt safe branch deletion, including branches that predated the worktree. Branches whose changes Orca cannot prove are already merged are retained. Older hosts keep their existing branch policy and print a warning; keep-by-default and --delete-branch do not apply there. A removal result without branch evidence does not confirm branch deletion.']},{diff --git a/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts b/src/main/runtime/rpc/worktree-rm-cli.integration.test.tsnew file mode 100644index 00000000000..920b91fb74a--- /dev/null+++ b/src/main/runtime/rpc/worktree-rm-cli.integration.test.ts@@ -0,0 +1,671 @@+import './unused-default-rpc-methods.test-fixture'+import { execFile } from 'node:child_process'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, realpath, readFile, 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 '../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 type { RemoveWorktreeResult } from '../../../shared/worktree/create-types'+import type { CliStatusResult, RuntimeWorktreeRemoveResult } from '../../../shared/runtime-types'+import type { RuntimeRpcSuccess } from '../../../shared/runtime-rpc-envelope'+import * as appEnvironment from '../../../shared/app-environment'+import type { SshTarget } from '../../../shared/ssh-types'+import { orcadMigrationCutoverFixture } from '../../ssh/orcad-migration-cutover-fixture'+import { writeOrcadMigrationSourceCutover } from '../../ssh/orcad-migration-cutover-journal'+import { removalPtyProvider } from './worktree-rm-pty.test-fixture'+import { pairedRemovalReceiver } from './worktree-rm-paired.test-fixture'+import { addManagedOrcadEnvironment } from '../../../shared/runtime-environment-managed-orcad-store'+import { getRuntimeMetadataPath } from '../../../shared/runtime-bootstrap'+import { WorktreeRemove } from '../../../shared/rpc-contract/worktree-params'+import { UnixSocketTransport } from './unix-socket-transport'+import { RpcDispatcher } from './dispatcher'+import { WORKTREE_METHODS } from './methods/worktree'+import { STATUS_METHODS } from './methods/status'+import type { RpcRequest } from './core'+import { WorkspaceLifecycleQueue } from '../workspaces/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,+ startBackgroundWorktreeRemoval,+ waitForPendingWorktreeRemoval+} from '../../worktree-background-removal'+import * as acceptance from '../../worktree-removal-acceptance-queue'+import { failedWorktreeRemovals, pendingWorktreeRemovals } from '../../worktree-removal-table'++installRealWorkerThreadChildProcesses()+const cliPath = '../../../cli/index'+const { main }: { main: (argv: string[], cwd: string) => Promise<void> } = await import(cliPath)+type RemovalClient = {+ call<TResult>(method: string, params: unknown): Promise<RuntimeRpcSuccess<TResult>>+ getCliStatus(): Promise<RuntimeRpcSuccess<CliStatusResult>>+}+const clientPath = '../../../cli/runtime/client'+const {+ RuntimeClient+}: {+ RuntimeClient: new (+ userDataPath: string,+ requestTimeoutMs: number,+ remotePairingCode: string | null,+ environmentSelector: string | null+ ) => RemovalClient+} = await import(clientPath)+const removalRequestPath = '../../../cli/handlers/worktree-removal-request'+const {+ requestWorktreeRemoval+}: {+ requestWorktreeRemoval: (+ client: RemovalClient,+ request: {+ worktree: string+ hostId: string+ force: boolean+ deleteBranch?: boolean+ runHooks: boolean+ allowFailedArchiveHook: boolean+ }+ ) => Promise<RuntimeRpcSuccess<RuntimeWorktreeRemoveResult>>+} = await import(removalRequestPath)+const exec = promisify(execFile)+const received = vi.fn<(method: string, params: unknown) => void>()+let directory = ''+let repoPath = ''+let checkout = ''+let id = ''+let repo: Repo+let folderRepo: Repo+let repos: Repo[]+let sshTargets: SshTarget[]+let meta: Record<string, WorktreeMeta>+let socket: UnixSocketTransport+let client: RemovalClient+let runtime: RemovalRuntime+let dispatcher: RpcDispatcher+let supported = true+let afterShow: () => void | Promise<void> = () => {}+let beforeStatus: () => void | Promise<void> = () => {}+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()+ override async showManagedWorktree(selector: string) {+ const shown = await super.showManagedWorktree(selector)+ await afterShow()+ return shown+ }+}+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+ })+ )+}+async function dispatch(request: RpcRequest, legacy = !supported) {+ received(request.method, request.params)+ if (request.method === 'status.get') {+ await beforeStatus()+ }+ const projected =+ legacy && request.method === 'worktree.rm'+ ? { ...request, params: WorktreeRemove.omit({ deleteBranch: true }).parse(request.params) }+ : request+ const response = await dispatcher.dispatch(projected)+ if (legacy && request.method === 'status.get' && response.ok) {+ // Historical status is successful and has no branch capability; keep the real producer's other fields.+ const { capabilities: _capabilities, ...status } = runtime.getStatus()+ return { ...response, result: status }+ }+ return response+}+beforeEach(async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ vi.spyOn(console, 'error').mockImplementation(() => {})+ directory = await realpath(await mkdtemp(join(tmpdir(), 'orca-cli-rm-')))+ repoPath = join(directory, 'repo')+ checkout = join(directory, 'checkout')+ id = `repo::${checkout}`+ supported = true+ received.mockClear()+ stopped.mockClear()+ afterShow = () => {}+ beforeStatus = () => {}+ 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', '[email protected]')+ 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<WorktreeMeta>) =>+ (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 dispatch(request).then((response) => reply(JSON.stringify(response)))+ })+ await socket.start()+ await discover(endpoint)+ client = new RuntimeClient(directory, 5000, null, null)+})+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)+ }+ }+)++it.each([false, true])('preserves legacy omitted-field metadata policy %s', async (preserve) => {+ meta[id].preserveBranchOnDelete = preserve+ await client.call('worktree.rm', { worktree: `id:${id}`, waitForBackgroundRemoval: true })+ expect(existsSync(checkout)).toBe(false)+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe(+ preserve ? 'task' : ''+ )+})++it('does not apply a failed record’s branch choice to a freshly registered checkout', async () => {+ failedWorktreeRemovals.set(id, {+ worktreeId: id,+ repoId: 'repo',+ repoPath,+ worktreePath: checkout,+ branch: 'old-task',+ head: '',+ deleteBranch: true,+ force: false,+ requestedAt: 1,+ failure: { message: 'old failure', failedAt: 2 }+ })+ await main(['worktree', 'rm', '--worktree', `id:${id}`, '--json'], repoPath)+ expect(process.exitCode).not.toBe(1)+ expect(existsSync(checkout)).toBe(false)+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe('task')+})++it.each([false, true])(+ 'rechecks branch intent after acceptance-queue wait, accepted=%s',+ async (deleteBranch) => {+ const block = Promise.withResolvers<void>()+ const gitPending = Promise.withResolvers<RemoveWorktreeResult>()+ const run = vi.fn(() => gitPending.promise)+ const first = acceptance.runSerializedWorktreeRemovalAcceptance(repoPath, () => block.promise)+ const entering = vi.spyOn(acceptance, 'runSerializedWorktreeRemovalAcceptance')+ const request = runtime.removeManagedWorktree(`id:${id}`, {+ deleteBranch: !deleteBranch,+ waitForBackgroundRemoval: true+ })+ // Observe rejection immediately so the forced schedule cannot create an unhandled rejection.+ const refused = expect(request).rejects.toThrow('different branch choice')+ try {+ await vi.waitFor(() => expect(entering).toHaveBeenCalledOnce())+ void startBackgroundWorktreeRemoval({+ removal: {+ worktreeId: id,+ repoId: 'repo',+ repoPath,+ worktree: { path: checkout, branch: 'task', head: '' },+ deleteBranch,+ force: false+ },+ run,+ publish: () => {}+ })+ const record = pendingWorktreeRemovals.get(id)+ const joined = waitForPendingWorktreeRemoval(id, 'local', deleteBranch)+ expect(waitForPendingWorktreeRemoval(id, 'local')).toBe(joined)+ expect(joined).toBeDefined()+ block.resolve()+ await first+ await new Promise((resolve) => setImmediate(resolve))+ expect(pendingWorktreeRemovals.get(id)).toBe(record)+ expect(record?.deleteBranch).toBe(deleteBranch)+ expect(existsSync(checkout)).toBe(true)+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe('task')+ gitPending.resolve({})+ await refused+ await expect(joined).resolves.toEqual({})+ expect(run).toHaveBeenCalledOnce()+ } finally {+ block.resolve()+ gitPending.resolve({})+ await first+ }+ }+)++it('settles the same dirty-checkout refusal for omitted and explicit keep intent', async () => {+ await writeFile(join(checkout, 'file'), 'unsaved')+ const head = await git('rev-parse', 'task')+ const registered = await git('worktree', 'list', '--porcelain')+ const failures: string[] = []+ for (const deleteBranch of [undefined, false]) {+ const failure = await client+ .call('worktree.rm', {+ worktree: `id:${id}`,+ hostId: 'local',+ force: false,+ runHooks: false,+ allowUnverifiedPtyStop: false,+ allowFailedArchiveHook: false,+ ...(deleteBranch === undefined ? {} : { deleteBranch }),+ waitForBackgroundRemoval: true+ })+ .then(+ () => {+ throw new Error('Expected dirty refusal')+ },+ (error: unknown) => String(error)+ )+ failures.push(failure)+ expect(await readFile(join(checkout, 'file'), 'utf8')).toBe('unsaved')+ expect(await git('rev-parse', 'task')).toBe(head)+ expect(await git('worktree', 'list', '--porcelain')).toBe(registered)+ expect(pendingWorktreeRemovals.size).toBe(0)+ }+ expect(failures[0]).toContain('M file')+ expect(failures[1]).toBe(failures[0])+ expect(stopped).not.toHaveBeenCalled()+})++function legacyParams(worktree = `id:${id}`, hostId = 'local', force = false) {+ return {+ worktree,+ hostId,+ force,+ runHooks: false,+ allowFailedArchiveHook: false,+ allowUnverifiedPtyStop: force,+ waitForBackgroundRemoval: true+ }+}+function warnings() {+ return vi+ .mocked(console.error)+ .mock.calls.filter(([value]) => String(value).includes('host is older'))+}+it.each([false, true])('sends exact legacy params and one warning, JSON=%s', async (json) => {+ supported = false+ const args = ['worktree', 'rm', '--worktree', 'name:task', '--delete-branch', '--force']+ await main(json ? [...args, '--json'] : args, repoPath)+ expect(process.exitCode).not.toBe(1)+ expect(received.mock.calls.at(-1)).toEqual([+ 'worktree.rm',+ legacyParams('name:task', 'local', true)+ ])+ expect(warnings()).toHaveLength(1)+ expect(existsSync(checkout)).toBe(false)+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe('')+ if (json) {+ expect(JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))).toMatchObject({+ ok: true,+ result: { removed: true }+ })+ }+})+it.each<{ capable: boolean; flags: string[]; root: boolean }>([+ { capable: true, flags: [], root: false },+ { capable: true, flags: ['--delete-branch'], root: false },+ { capable: false, flags: [], root: false },+ { capable: false, flags: [], root: true }+])(+ 'uses actual folder producer/removal, capable=$capable root=$root flags=$flags',+ async ({ capable, flags, root }) => {+ supported = capable+ const folderId = root+ ? `folder-repo::${directory}`+ : `folder-repo::${directory}::workspace:00000000-0000-4000-8000-000000000001`+ const sibling = `folder-repo::${directory}::workspace:00000000-0000-4000-8000-000000000002`+ meta[folderId] = storeWorktreeMeta({ instanceId: 'folder-one', hostId: 'local' })+ meta[sibling] = storeWorktreeMeta({ instanceId: 'folder-two', hostId: 'local' })+ const own = `${folderId}@@own`+ const sessions = removalPtyProvider([+ { id: own, cwd: directory, title: 'shell', worktreeId: folderId },+ { id: `${sibling}@@other`, cwd: directory, title: 'shell', worktreeId: sibling }+ ])+ vi.spyOn(runtime, 'getLocalProvider').mockReturnValue(sessions.provider)+ const shown = await runtime.showManagedWorktree(`id:${folderId}`)+ expect(shown).not.toHaveProperty('workspaceKind')+ const cleanup = vi.spyOn(runtime, 'removeWorktreeMetadataAndHistory')+ const head = await git('rev-parse', 'task')+ await main(['worktree', 'rm', '--worktree', `id:${folderId}`, ...flags, '--json'], repoPath)+ expect(process.exitCode === 1).toBe(root)+ expect(cleanup).toHaveBeenCalledTimes(root ? 0 : 1)+ expect(sessions.shutdown).toHaveBeenCalledTimes(root ? 0 : 1)+ if (!root) {+ expect(sessions.shutdown).toHaveBeenCalledWith(own, expect.anything())+ }+ expect(Boolean(meta[folderId])).toBe(root)+ expect(meta[sibling]).toBeDefined()+ expect(existsSync(directory)).toBe(true)+ expect(await git('rev-parse', 'task')).toBe(head)+ expect(received.mock.calls.at(-1)).toEqual([+ 'worktree.rm',+ {+ ...legacyParams(`id:${folderId}`),+ ...(capable ? { deleteBranch: flags.includes('--delete-branch') } : {})+ }+ ])+ expect(warnings()).toHaveLength(capable ? 0 : 1)+ const output = String(vi.mocked(console.log).mock.calls.at(-1)?.[0])+ expect(output).not.toContain('branch')+ if (root) {+ expect(output).toContain('root workspace')+ }+ }+)+it('sends the original selector after actual folder show and rename, with explicit keep for Git', async () => {+ const folderId = `folder-repo::${directory}::workspace:00000000-0000-4000-8000-000000000001`+ meta[folderId] = storeWorktreeMeta({+ displayName: 'target',+ instanceId: 'folder',+ hostId: 'local'+ })+ afterShow = () => {+ afterShow = () => {}+ meta[folderId].displayName = 'renamed'+ meta[id].displayName = 'target'+ runtime.invalidateResolvedWorktreeCache()+ }+ const head = await git('rev-parse', 'task')+ await main(['worktree', 'rm', '--worktree', 'name:target', '--json'], repoPath)+ expect(process.exitCode).not.toBe(1)+ expect(received.mock.calls.at(-1)).toEqual([+ 'worktree.rm',+ { ...legacyParams('name:target'), deleteBranch: false }+ ])+ expect(meta[folderId]).toBeDefined()+ expect(meta[id]).toBeUndefined()+ expect(existsSync(checkout)).toBe(false)+ expect(await git('rev-parse', 'task')).toBe(head)+})+it('selects legacy on B after lookup on A and cannot rediscover C during B status', async () => {+ const kind = process.platform === 'win32' ? 'named-pipe' : 'unix'+ const endpoint =+ process.platform === 'win32'+ ? String.raw`\\.\pipe\orca-rm-${process.pid}-B`+ : join(directory, 'B.sock')+ const legacy = new UnixSocketTransport({ kind, endpoint })+ const methods: string[] = []+ legacy.onMessage((message, reply) => {+ const request: RpcRequest = JSON.parse(message)+ methods.push(request.method)+ void dispatch(request, true).then((response) => reply(JSON.stringify(response)))+ })+ try {+ await legacy.start()+ afterShow = async () => {+ afterShow = () => {}+ await discover(endpoint)+ }+ beforeStatus = async () => {+ await discover(join(directory, 'never-C.sock'))+ }+ await main(['worktree', 'rm', '--worktree', `id:${id}`, '--json'], repoPath)+ expect(process.exitCode).not.toBe(1)+ expect(methods).toEqual(['status.get', 'worktree.rm'])+ expect(received.mock.calls.at(-1)).toEqual(['worktree.rm', legacyParams()])+ expect(warnings()).toHaveLength(1)+ expect(existsSync(checkout)).toBe(false)+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe('')+ } finally {+ await legacy.stop()+ }+})+it('does not dispatch or replay after preflight disconnect', async () => {+ beforeStatus = () => socket.stop()+ const head = await git('rev-parse', 'task')+ await main(['worktree', 'rm', '--worktree', `id:${id}`, '--json'], repoPath)+ expect(process.exitCode).toBe(1)+ expect(received.mock.calls.map(([method]) => method)).toEqual(['worktree.show', 'status.get'])+ expect(existsSync(checkout)).toBe(true)+ expect(await git('rev-parse', 'task')).toBe(head)+ expect(warnings()).toHaveLength(0)+})++it.each([true, false])(+ 'routes actual argv through a served SSH environment, capable=%s',+ async (capable) => {+ supported = capable+ const receiver = await pairedRemovalReceiver(dispatch)+ const clientRepo = join(directory, 'client-repo')+ try {+ await mkdir(clientRepo)+ await exec('git', ['init', '-q', clientRepo])+ await exec('git', [+ '-C',+ clientRepo,+ '-c',+ 'user.name=Client',+ '-c',+ '[email protected]',+ 'commit',+ '--allow-empty',+ '-qm',+ 'client'+ ])+ const localHead = (await exec('git', ['-C', clientRepo, 'rev-parse', 'HEAD'])).stdout+ const head = await git('rev-parse', 'task')+ const environment = addManagedOrcadEnvironment(directory, {+ id: 'served-ssh',+ name: 'served-ssh',+ pairingCode: receiver.pairingCode,+ orcadDeployment: {+ sshTargetId: 'fixture-ssh',+ sshTargetGeneration: 1,+ localPort: receiver.port,+ remotePort: 6768+ }+ })+ await main(+ ['worktree', 'rm', '--environment', environment.id, '--worktree', `id:${id}`, '--json'],+ clientRepo+ )+ expect(process.exitCode, JSON.stringify(vi.mocked(console.log).mock.calls)).not.toBe(1)+ expect(receiver.connections).toEqual([+ ['status.get', 'worktree.show'],+ ['status.get', 'worktree.rm']+ ])+ expect(received.mock.calls.at(-1)).toEqual([+ 'worktree.rm',+ { ...legacyParams(), ...(capable ? { deleteBranch: false } : {}) }+ ])+ expect(warnings()).toHaveLength(capable ? 0 : 1)+ expect(existsSync(checkout)).toBe(false)+ if (capable) {+ expect(await git('rev-parse', 'task')).toBe(head)+ } else {+ expect(await git('for-each-ref', '--format=%(refname:short)', 'refs/heads/task')).toBe('')+ }+ expect((await exec('git', ['-C', clientRepo, 'rev-parse', 'HEAD'])).stdout).toBe(localHead)+ // Runtime-local host spelling is translated by the actual receiving RPC method.+ await git('worktree', 'add', '-qb', 'second', checkout)+ runtime.invalidateResolvedWorktreeCache()+ const paired = new RuntimeClient(directory, 5000, receiver.pairingCode, null)+ await paired.getCliStatus()+ await requestWorktreeRemoval(paired, {+ worktree: `id:${id}`,+ hostId: `runtime:${environment.id}`,+ force: false,+ deleteBranch: false,+ runHooks: false,+ allowFailedArchiveHook: false+ })+ expect(existsSync(checkout)).toBe(false)+ expect(receiver.connections.at(-1)).toEqual(['status.get', 'worktree.rm'])+ expect(await git('rev-parse', 'main')).not.toBe('')+ } finally {+ await receiver.close()+ }+ }+)++it('retains legacy hidden SSH folder removal with a raw-ID local twin', async () => {+ supported = false+ sshTargets = [+ {+ id: 'source',+ label: 'Source',+ host: 'unused.invalid',+ port: 22,+ username: 'test',+ generation: 2,+ orcadFence: { environmentId: 'env-1' }+ }+ ]+ writeOrcadMigrationSourceCutover(directory, {+ ...orcadMigrationCutoverFixture('move', 'source'),+ phase: 'destination-committed'+ })+ const hidden = storeRepo({ ...folderRepo, connectionId: 'source' })+ repos = [repo, folderRepo, hidden]+ const folderId = `folder-repo::${directory}::workspace:11111111-1111-4111-8111-111111111111`+ meta[folderId] = storeWorktreeMeta({+ hostId: 'ssh:source',+ instanceId: '11111111-1111-4111-8111-111111111111'+ })+ expect(runtime.listVisibleRepos()).not.toContainEqual(hidden)+ expect(runtime.listRepos()).toContainEqual(hidden)+ expect(await runtime.showManagedWorktree(`id:${folderId}`)).toMatchObject({+ id: folderId,+ hostId: 'ssh:source'+ })+ const head = await git('rev-parse', 'task')+ await main(['worktree', 'rm', '--worktree', `id:${folderId}`, '--json'], repoPath)+ expect(process.exitCode, JSON.stringify(vi.mocked(console.log).mock.calls)).not.toBe(1)+ expect(received.mock.calls.at(-1)).toEqual([+ 'worktree.rm',+ legacyParams(`id:${folderId}`, 'ssh:source')+ ])+ expect(meta[folderId]).toBeUndefined()+ expect(repos).toContain(folderRepo)+ expect(existsSync(directory)).toBe(true)+ expect(await git('rev-parse', 'task')).toBe(head)+ expect(warnings()).toHaveLength(1)+})++it('keeps the legacy warning on JSON refusal without implying branch success', async () => {+ supported = false+ await writeFile(join(checkout, 'file'), 'unsaved')+ const head = await git('rev-parse', 'task')+ await main(['worktree', 'rm', '--worktree', `id:${id}`, '--delete-branch', '--json'], repoPath)+ expect(process.exitCode).toBe(1)+ expect(warnings()).toHaveLength(1)+ const output = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]))+ expect(output).toMatchObject({ ok: false })+ expect(output).not.toHaveProperty('result')+ expect(await readFile(join(checkout, 'file'), 'utf8')).toBe('unsaved')+ expect(await git('rev-parse', 'task')).toBe(head)+ expect(runtime.workspaceLifecycle.hints()).toEqual({})+})++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/worktree-rm-paired.test-fixture.ts b/src/main/runtime/rpc/worktree-rm-paired.test-fixture.tsnew file mode 100644index 00000000000..a5271d66871--- /dev/null+++ b/src/main/runtime/rpc/worktree-rm-paired.test-fixture.ts@@ -0,0 +1,80 @@+import { createServer } from 'node:http'+import { WebSocketServer } from 'ws'+import {+ decrypt,+ deriveSharedKey,+ encrypt,+ generateKeyPair,+ publicKeyToBase64+} from '../../../shared/e2ee-crypto'+import { encodePairingOffer } from '../../../shared/pairing'+import type { RpcRequest, RpcResponse } from './core'++/** Authenticated transport around the real dispatcher supplied by the integration fixture. */+export async function pairedRemovalReceiver(+ dispatch: (request: RpcRequest) => Promise<RpcResponse>+) {+ const keys = generateKeyPair()+ const deviceToken = 'removal-fixture'+ const server = createServer()+ const sockets = new WebSocketServer({ server })+ const connections: string[][] = []+ sockets.on('connection', (socket) => {+ const methods: string[] = []+ connections.push(methods)+ let key: Uint8Array | null = null+ let authenticated = false+ socket.on('message', (data) => {+ if (!key) {+ const hello: { publicKeyB64: string } = JSON.parse(data.toString())+ key = deriveSharedKey(keys.secretKey, Buffer.from(hello.publicKeyB64, 'base64'))+ socket.send(JSON.stringify({ type: 'e2ee_ready' }))+ return+ }+ const plaintext = decrypt(data.toString(), key)+ if (!plaintext) {+ socket.close(4003)+ return+ }+ if (!authenticated) {+ const auth: { type: string; deviceToken: string } = JSON.parse(plaintext)+ if (auth.type !== 'e2ee_auth' || auth.deviceToken !== deviceToken) {+ socket.close(4001)+ return+ }+ authenticated = true+ socket.send(encrypt(JSON.stringify({ type: 'e2ee_authenticated' }), key))+ return+ }+ const request: RpcRequest = JSON.parse(plaintext)+ methods.push(request.method)+ const sharedKey = key+ void dispatch(request).then((response) =>+ socket.send(encrypt(JSON.stringify(response), sharedKey))+ )+ })+ })+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const address = server.address()+ if (!address || typeof address === 'string') {+ throw new Error('Expected TCP receiver')+ }+ return {+ port: address.port,+ pairingCode: encodePairingOffer({+ v: 2,+ endpoint: `ws://127.0.0.1:${address.port}`,+ deviceToken,+ publicKeyB64: publicKeyToBase64(keys.publicKey),+ scope: 'runtime'+ }),+ connections,+ async close() {+ for (const socket of sockets.clients) {+ socket.terminate()+ }+ await new Promise<void>((resolve) => sockets.close(() => resolve()))+ await new Promise<void>((resolve) => server.close(() => resolve()))+ }+ }+}diff --git a/src/main/runtime/rpc/worktree-rm-pty.test-fixture.ts b/src/main/runtime/rpc/worktree-rm-pty.test-fixture.tsnew file mode 100644index 00000000000..21ff96a4f60--- /dev/null+++ b/src/main/runtime/rpc/worktree-rm-pty.test-fixture.ts@@ -0,0 +1,38 @@+import { vi } from 'vitest'+import type { IPtyProvider, PtyProcessInfo } from '../../providers/pty-provider-contract'++/** Only the provider's external effects are controlled; runtime teardown selects the sessions. */+export function removalPtyProvider(initial: PtyProcessInfo[]) {+ let processes = initial+ const unused = async (): Promise<never> => {+ throw new Error('Unexpected PTY effect')+ }+ const shutdown = vi.fn<IPtyProvider['shutdown']>(async (id) => {+ processes = processes.filter((entry) => entry.id !== id)+ })+ const provider: IPtyProvider = {+ spawn: unused,+ attach: unused,+ write: () => {},+ writeWithSettlement: unused,+ resize: () => {},+ shutdown,+ sendSignal: unused,+ getCwd: unused,+ getInitialCwd: unused,+ clearBuffer: unused,+ resetInputModes: unused,+ acknowledgeDataEvent: () => {},+ hasChildProcesses: async () => false,+ getForegroundProcess: async () => null,+ serialize: unused,+ revive: unused,+ listProcesses: async () => processes,+ getDefaultShell: unused,+ getProfiles: unused,+ onData: () => () => {},+ onReplay: () => () => {},+ onExit: () => () => {}+ }+ return { provider, shutdown }+}diff --git a/src/main/runtime/runtime-interrupted-local-worktree-removal.test.ts b/src/main/runtime/runtime-interrupted-local-worktree-removal.test.tsindex 2aeea4743e3..2712560cee4 100644--- a/src/main/runtime/runtime-interrupted-local-worktree-removal.test.ts+++ b/src/main/runtime/runtime-interrupted-local-worktree-removal.test.ts@@ -52,6 +52,8 @@ import {writeWorktreeRemovalRecords,type WorktreeRemovalRecord} from '../worktree-removal-records'+import { queueWorkspaceDelete } from './workspaces/workspace-lifecycle-commands'+import { WorkspaceLifecycleQueue } from './workspaces/workspace-lifecycle-queue'import { interruptedLocalWorktreeRemovalJob } from './runtime-interrupted-local-worktree-removal'vi.mock('node:fs/promises', async (importOriginal) => {@@ -79,6 +81,7 @@ let repoPath = ''let worktreePath = ''let repo: Repolet pushTarget: GitPushTarget | undefined+let lifecycle: WorkspaceLifecycleQueueasync function git(args: string[], cwd = repoPath): Promise<string> {const { stdout } = await execFileAsync('git', args, { cwd })@@ -94,6 +97,7 @@ async function isRegistered(path: string): Promise<boolean> {beforeEach(async () => {pushTarget = undefined+ lifecycle = new WorkspaceLifecycleQueue()vi.mocked(getLocalProjectWorktreeGitOptions).mockReturnValue({})// realpath: macOS hands out /var/... temp paths while Git reports /private/var/....scratchDir = await realpath(await mkdtemp(join(tmpdir(), 'orca-interrupted-removal-')))@@ -130,6 +134,7 @@ async function finishAfterRestart(branch?: stringhead?: stringforce?: boolean+ deleteBranch?: booleanstopPtys?: () => Promise<void>} = {}): Promise<{@@ -145,7 +150,7 @@ async function finishAfterRestart(worktreePath,branch: options.branch ?? 'feature',head: options.head ?? (await git(['rev-parse', 'feature'])).trim(),- deleteBranch: true,+ deleteBranch: options.deleteBranch ?? true,force: options.force ?? false,requestedAt: 1}@@ -240,7 +245,8 @@ async function deleteViaEntry(entry: RemovalEntry,force: boolean,stop = async () => {},- teardown = vi.fn()+ teardown = vi.fn(),+ deleteBranch?: boolean): Promise<unknown> {const worktreeId = `repo-1::${worktreePath}`const host = removalHost(false, stop, teardown)@@ -249,6 +255,9 @@ async function deleteViaEntry(Object.create(OrcaRuntimeWithResolveWorktreeRemovalTarget.prototype),{store,+ workspaceLifecycle: lifecycle,+ listRepos: store.getRepos,+ listTerminals: async () => ({ totalCount: 0 }),requireStore: () => store,resolveWorktreeRemovalTarget: async () => ({id: worktreeId,@@ -286,10 +295,17 @@ async function deleteViaEntry(worktreePath,'local')- : await runtime.removeManagedWorktree(`id:${worktreeId}`, {- force,- waitForBackgroundRemoval: true- })+ : await queueWorkspaceDelete(+ runtime,+ `id:${worktreeId}`,+ 'local',+ { force, deleteBranch },+ (removal) =>+ runtime.removeManagedWorktree(`id:${worktreeId}`, {+ ...removal,+ waitForBackgroundRemoval: true+ })+ )return await backgroundRemoval.finishAcceptedWorktreeRemoval(accepted, worktreeId)} finally {await _settlePendingWorktreeRemovalsForTests()@@ -303,7 +319,7 @@ async function orphanAdmin(): Promise<void> {await writeFile(join(worktreePath, '.git'), ` gitdir: ${admin}\nignored second line\n`)}-async function recordFailedRemoval(force: boolean): Promise<void> {+async function recordFailedRemoval(force: boolean, deleteBranch = true): Promise<void> {await writeWorktreeRemovalRecords(recordsDir, () => [{worktreeId: `repo-1::${worktreePath}`,@@ -312,7 +328,7 @@ async function recordFailedRemoval(force: boolean): Promise<void> {worktreePath,branch: 'feature',head: '',- deleteBranch: true,+ deleteBranch,force,requestedAt: 1,failure: { message: 'held file', failedAt: 2 }@@ -551,23 +567,86 @@ describe('finishing an interrupted worktree removal after a restart', () => {})- it.each(['partial', 'detached'])(+ it.each(['partial', 'detached', 'keep-registered', 'keep-unregistered'])('finishes the accepted %s pending checkout after restart',async (kind) => {- await (kind === 'partial'- ? unlink(join(worktreePath, 'seed.txt'))- : git(['checkout', '--detach', '-q'], worktreePath))+ const head = (await git(['rev-parse', 'feature'])).trim()+ if (kind === 'keep-unregistered') {+ await git(['worktree', 'remove', worktreePath])+ }+ const keep = kind.startsWith('keep-')+ if (!keep) {+ await (kind === 'partial'+ ? unlink(join(worktreePath, 'seed.txt'))+ : git(['checkout', '--detach', '-q'], worktreePath))+ }const { outcome, purged, records } = await finishAfterRestart({force: kind === 'partial',branch: kind === 'detached' ? '' : 'feature',- head: (await git(['rev-parse', 'HEAD'], worktreePath)).trim()+ head: keep ? head : (await git(['rev-parse', 'HEAD'], worktreePath)).trim(),+ deleteBranch: keep ? false : undefined})expect(outcome).toMatchObject({ status: 'removed' })expect(records).toEqual([])expect(existsSync(worktreePath)).toBe(false)expect(await isRegistered(worktreePath)).toBe(false)- expect((await git(['branch', '--list', 'feature'])).trim() !== '').toBe(kind === 'detached')+ expect((await git(['branch', '--list', 'feature'])).trim() !== '').toBe(+ keep || kind === 'detached'+ )expect(purged).toEqual([`repo-1::${worktreePath}`])+ if (keep) {+ expect((await git(['rev-parse', 'feature'])).trim()).toBe(head)+ expect(outcome).not.toHaveProperty('preservedBranch')+ }+ }+ )++ it.each([false, undefined])(+ 'settles persisted failed keep through lifecycle retry, intent=%s',+ async (intent) => {+ const head = (await git(['rev-parse', 'feature'])).trim()+ await git(['worktree', 'remove', worktreePath])+ await mkdir(worktreePath)+ await writeFile(join(worktreePath, 'leftover'), 'held')+ await recordFailedRemoval(false, false)+ const id = `repo-1::${worktreePath}`+ const record = removalTable.failedWorktreeRemovals.get(id)+ expect(record).toMatchObject({ deleteBranch: false, failure: { message: 'held file' } })+ await expect(deleteViaEntry('runtime', false, undefined, undefined, intent)).rejects.toThrow(+ 'folder was left on disk'+ )+ expect(removalTable.failedWorktreeRemovals.get(id)).toBe(record)+ expect(lifecycle.hints()).toEqual({})+ // Removing only this fixture's leftover is the legitimate external wake for retry.+ await removeTree(worktreePath)+ await expect(deleteViaEntry('runtime', false, undefined, undefined, true)).rejects.toThrow(+ 'different branch choice'+ )+ expect(removalTable.failedWorktreeRemovals.get(id)).toBe(record)+ expect(lifecycle.hints()).toEqual({})+ const entered = Promise.withResolvers<void>()+ const release = Promise.withResolvers<void>()+ const stopPtys = async () => {+ entered.resolve()+ await release.promise+ }+ const retry = deleteViaEntry('runtime', false, stopPtys, undefined, intent)+ try {+ await entered.promise+ expect(removalTable.pendingWorktreeRemovals.get(id)).toMatchObject({ deleteBranch: false })+ expect(removalTable.failedWorktreeRemovals.has(id)).toBe(false)+ } finally {+ release.resolve()+ }+ const result = await retry+ expect(result).not.toHaveProperty('preservedBranch')+ expect((await git(['rev-parse', 'feature'])).trim()).toBe(head)+ expect(await isRegistered(worktreePath)).toBe(false)+ expect(existsSync(worktreePath)).toBe(false)+ expect(waitForPendingWorktreeRemoval(id)).toBeUndefined()+ expect(removalTable.failedWorktreeRemovals.has(id)).toBe(false)+ expect(await readWorktreeRemovalRecords(recordsDir)).toEqual([])+ expect(lifecycle.hints()).toEqual({})})diff --git a/src/main/runtime/runtime-registered-local-worktree-removal.ts b/src/main/runtime/runtime-registered-local-worktree-removal.tsindex 8a2255560e3..eab595c555b 100644--- a/src/main/runtime/runtime-registered-local-worktree-removal.ts+++ b/src/main/runtime/runtime-registered-local-worktree-removal.ts@@ -46,7 +46,7 @@ export function removeRuntimeRegisteredLocalWorktree(args.repo.path,async (): Promise<RemoveWorktreeResult & { warning?: string }> =>// Recheck after queue wait: another client may already have accepted this deletion.- waitForPendingWorktreeRemoval(args.target.id)+ waitForPendingWorktreeRemoval(args.target.id, undefined, args.requestedDeleteBranch)? { removing: true }: acceptRuntimeRegisteredLocalWorktreeRemoval(args))@@ -66,6 +66,8 @@ async function acceptRuntimeRegisteredLocalWorktreeRemoval(args: {allowFailedArchiveHook: booleanallowUnverifiedPtyStop: booleandeleteBranch: boolean+ /** Legacy callers join accepted policy; explicit requests must match it. */+ requestedDeleteBranch?: booleanacquireWatcherRemoval: (path: string) => Promise<{ finish: (removed: boolean) => Promise<void> }>stopPtys: () => Promise<void>closeWatchers: (path: string) => Promise<void>diff --git a/src/main/runtime/runtime-worktree-selection.test.ts b/src/main/runtime/runtime-worktree-selection.test.tsindex 814b1e6cf2e..f8aab4e34ba 100644--- a/src/main/runtime/runtime-worktree-selection.test.ts+++ b/src/main/runtime/runtime-worktree-selection.test.ts@@ -16,6 +16,8 @@ describe('getRuntimeWorktreeRemovalOptionsKey', () => {const keys = [{},{ force: true },+ { deleteBranch: false },+ { deleteBranch: true },{ runHooks: true },{ allowUnverifiedPtyStop: true },{ allowFailedArchiveHook: true }diff --git a/src/main/runtime/runtime-worktree-selection.ts b/src/main/runtime/runtime-worktree-selection.tsindex 8a8529de717..8459f7500c1 100644--- a/src/main/runtime/runtime-worktree-selection.ts+++ b/src/main/runtime/runtime-worktree-selection.ts@@ -17,6 +17,7 @@ export type RuntimeWorktreeRemovalTarget = {/** Named options prevent interchangeable safety-waiver booleans from silently authorizing the wrong destructive delete. */export type RemoveManagedWorktreeOptions = {force?: boolean+ deleteBranch?: booleanrunHooks?: boolean/** Waives proof that every PTY stopped (#11960). Set by explicit Force Delete only. */allowUnverifiedPtyStop?: boolean@@ -30,7 +31,7 @@ export type RemoveManagedWorktreeOptions = {export function getRuntimeWorktreeRemovalOptionsKey(options: Pick<RemoveManagedWorktreeOptions,- 'force' | 'runHooks' | 'allowUnverifiedPtyStop' | 'allowFailedArchiveHook'+ 'force' | 'runHooks' | 'allowUnverifiedPtyStop' | 'allowFailedArchiveHook' | 'deleteBranch'>): string {// Forced retries must not coalesce onto an attempt refusing unverified PTY stop.@@ -38,7 +39,13 @@ export function getRuntimeWorktreeRemovalOptionsKey(// Archive-waiver retries must not inherit an in-flight attempt's hook refusal.const archiveKey = options.allowFailedArchiveHook ? 'allow-failed-archive' : 'require-archive'const hooksKey = options.runHooks ? 'run-hooks' : 'skip-hooks'- return `${options.force ? 'force' : 'normal'}:${hooksKey}:${ptyKey}:${archiveKey}`+ const branchKey =+ options.deleteBranch === undefined+ ? 'legacy-branch'+ : options.deleteBranch+ ? 'delete-branch'+ : 'keep-branch'+ return `${options.force ? 'force' : 'normal'}:${hooksKey}:${ptyKey}:${archiveKey}:${branchKey}`}// Null host is host-unaware; unstamped legacy rows are adoptable, but either explicit host spelling must match exactly.diff --git a/src/main/runtime/workspaces/workspace-lifecycle-commands.ts b/src/main/runtime/workspaces/workspace-lifecycle-commands.tsindex 326061144d2..50cfa7c1e1f 100644--- a/src/main/runtime/workspaces/workspace-lifecycle-commands.ts+++ b/src/main/runtime/workspaces/workspace-lifecycle-commands.ts@@ -17,6 +17,7 @@ import {getRuntimeWorktreeRemovalOptionsKey} from '../runtime-worktree-selection'+import type { RemoveManagedWorktreeOptions } from '../runtime-worktree-selection'import { hostSleepKey } from '../terminal/stop/worktree-terminal-sleep-key'import { resolveWorktreeHostRouting, type LaunchHostRepo } from '../worktree-launch-host-repo'import type {@@ -161,10 +162,15 @@ export function queueWorkspaceDelete<T>(runtime: LifecycleRuntime & ObservingRuntime,selector: string,hostId: string | undefined,- requested: Partial<Record<RemovalFlag, boolean>>,- run: (removal: Record<RemovalFlag, boolean> & { hostId?: string }) => Promise<T>+ requested: Partial<Record<RemovalFlag, boolean>> &+ Pick<RemoveManagedWorktreeOptions, 'deleteBranch'>,+ run: (+ removal: Record<RemovalFlag, boolean> &+ Pick<RemoveManagedWorktreeOptions, 'hostId' | 'deleteBranch'>+ ) => Promise<T>): Promise<T> {- const removal: Record<RemovalFlag, boolean> = {+ const removal = {+ ...(requested.deleteBranch !== undefined ? { deleteBranch: requested.deleteBranch } : {}),force: requested.force === true,runHooks: requested.runHooks === true,allowUnverifiedPtyStop: requested.allowUnverifiedPtyStop === true,diff --git a/src/main/runtime/workspaces/workspace-removal-target.ts b/src/main/runtime/workspaces/workspace-removal-target.tsindex 7a88e9cf99b..fe502d92906 100644--- a/src/main/runtime/workspaces/workspace-removal-target.ts+++ b/src/main/runtime/workspaces/workspace-removal-target.ts@@ -83,9 +83,9 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends OrcaRuprotected joinPendingWorktreeRemoval(worktreeId: string,- options: RemoveManagedWorktreeOptions+ { hostId, deleteBranch }: RemoveManagedWorktreeOptions): Promise<RemoveWorktreeResult> | undefined {- return waitForPendingWorktreeRemoval(worktreeId, parseExecutionHostId(options.hostId)?.id)+ return waitForPendingWorktreeRemoval(worktreeId, parseExecutionHostId(hostId)?.id, deleteBranch)}/** Failed intent schedules a retry; current Git/filesystem proof still controls every deletion. */@@ -119,7 +119,8 @@ export abstract class OrcaRuntimeWithResolveWorktreeRemovalTarget extends OrcaRuallowUnverifiedStop: allowUnverifiedPtyStop})}),- options.force === true+ options.force === true,+ options.deleteBranch))}diff --git a/src/main/runtime/workspaces/workspace-removal.ts b/src/main/runtime/workspaces/workspace-removal.tsindex 1bc3e71a297..16d0401332c 100644--- a/src/main/runtime/workspaces/workspace-removal.ts+++ b/src/main/runtime/workspaces/workspace-removal.ts@@ -109,7 +109,8 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends OrcaRuntimeWiforce,runHooks,allowUnverifiedPtyStop,- allowFailedArchiveHook+ allowFailedArchiveHook,+ deleteBranch: options.deleteBranch})const inFlightRemoval = this.removeManagedWorktreeInFlight.get(cleanupScopeKey,@@ -212,7 +213,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends OrcaRuntimeWi})}const canonicalWorktreePath = registeredWorktree.path- const deleteBranch = removedMeta?.preserveBranchOnDelete !== true+ const deleteBranch = options.deleteBranch ?? removedMeta?.preserveBranchOnDelete !== trueif (await isStaleLocalWorktreeRegistration(registeredWorktree,@@ -259,6 +260,7 @@ export abstract class OrcaRuntimeWithRemoveManagedWorktree extends OrcaRuntimeWiallowFailedArchiveHook,allowUnverifiedPtyStop,deleteBranch,+ requestedDeleteBranch: options.deleteBranch,acquireWatcherRemoval: this.acquireFileWatcherRemoval,stopPtys: () =>this.stopPtysForDestructiveWorktreeRemoval(removalTarget.id, {diff --git a/src/main/worktree-background-removal.ts b/src/main/worktree-background-removal.tsindex 07923d0f77b..f1f3f51a6b7 100644--- a/src/main/worktree-background-removal.ts+++ b/src/main/worktree-background-removal.ts@@ -97,11 +97,25 @@ function addPendingRemoval(record: WorktreeRemovalRecord): RemovalSettlement {/** Pending removals are host-local; never join a same-ID checkout on another host. */export function waitForPendingWorktreeRemoval(worktreeId: string,- hostId?: ExecutionHostId+ hostId?: ExecutionHostId,+ deleteBranch?: boolean): Promise<RemoveWorktreeResult> | undefined {- return (hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID- ? settlementsByWorktreeId.get(worktreeId)?.result- : 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. */@@ -150,15 +164,17 @@ export function retryFailedWorktreeRemoval(worktreeId: string,hostId: ExecutionHostId | undefined,jobFor: (record: WorktreeRemovalRecord) => BackgroundWorktreeRemovalJob,- force?: boolean+ force?: boolean,+ deleteBranch?: boolean): Promise<RemoveWorktreeResult> | undefined {const failed =(hostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID? failedWorktreeRemovals.get(worktreeId): undefinedif (!failed) {- return waitForPendingWorktreeRemoval(worktreeId, hostId)+ return waitForPendingWorktreeRemoval(worktreeId, hostId, deleteBranch)}+ assertAcceptedBranchChoice(failed, deleteBranch)const { failure: _failure, ...original } = failedconst record = { ...original, force: force ?? original.force }const settlement = addPendingRemoval(record)diff --git a/src/renderer/src/web/web-preload-api-workspace-catalog.test.ts b/src/renderer/src/web/web-preload-api-workspace-catalog.test.tsindex 353dc28d922..0884b74e099 100644--- a/src/renderer/src/web/web-preload-api-workspace-catalog.test.ts+++ b/src/renderer/src/web/web-preload-api-workspace-catalog.test.ts@@ -209,7 +209,7 @@ describe('web worktree preload API', () => {const { installWebPreloadApi } = await import('./web-preload-api')installWebPreloadApi()- await globals.window.api.worktrees.remove({+ const removed = await globals.window.api.worktrees.remove({worktreeId: 'repo-1::/workspace/locked',force: true,skipArchive: false@@ -220,6 +220,7 @@ describe('web worktree preload API', () => {skipArchive: true})+ expect(removed).toEqual({ removed: true })expect(runtimeCalls).toEqual([{method: 'worktree.rm',diff --git a/src/shared/cli-argument-boundary.ts b/src/shared/cli-argument-boundary.tsindex a5b3d14ee38..e59e79c679f 100644--- a/src/shared/cli-argument-boundary.ts+++ b/src/shared/cli-argument-boundary.ts@@ -14,6 +14,7 @@ export const CLI_BOOLEAN_FLAGS = new Set(['current-json','current-sqlite','debug',+ 'delete-branch','dry-run','enter','focus',diff --git a/src/shared/remote-runtime/remote-runtime-client.ts b/src/shared/remote-runtime/remote-runtime-client.tsindex 58521f6f1ea..cbedb021639 100644--- a/src/shared/remote-runtime/remote-runtime-client.ts+++ b/src/shared/remote-runtime/remote-runtime-client.ts@@ -7,7 +7,11 @@ import type {RemoteRuntimeSubscriptionOptions,RemoteRuntimeTransportSubscriptionCallbacks} from './requests/remote-runtime-subscription-contract'-import type { RuntimeOrchestrationEnvelope, RuntimeRpcResponse } from '../runtime-rpc-envelope'+import type {+ RuntimeRequestSelection,+ RuntimeOrchestrationEnvelope,+ RuntimeRpcResponse+} from '../runtime-rpc-envelope'import type { RuntimeStatus } from '../runtime-session-contracts'export type RemoteRuntimeSubscription = {@@ -57,7 +61,8 @@ export function sendRemoteRuntimeRequestWithStatusPreflight<TResult>(validateStatus: (response: RuntimeRpcResponse<RuntimeStatus>) => void,envelope?: RuntimeOrchestrationEnvelope,clientCapabilities: readonly RuntimeCapability[] = [],- signal?: AbortSignal+ signal?: AbortSignal,+ requestSelection?: RuntimeRequestSelection): Promise<RuntimeRpcResponse<TResult>> {return sendRemoteRuntimeRequestOnSocket(connection,@@ -67,7 +72,8 @@ export function sendRemoteRuntimeRequestWithStatusPreflight<TResult>(envelope,validateStatus,signal,- clientCapabilities+ clientCapabilities,+ requestSelection)}diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-response-router.ts b/src/shared/remote-runtime/requests/remote-runtime-request-response-router.tsindex 2e15d209b4a..acc150020e0 100644--- a/src/shared/remote-runtime/requests/remote-runtime-request-response-router.ts+++ b/src/shared/remote-runtime/requests/remote-runtime-request-response-router.ts@@ -18,7 +18,7 @@ type RequestResponseRouterOptions<TResult> = {statusRequestId: string | nullvalidateStatus?: (response: RuntimeRpcResponse<RuntimeStatus>) => voidsend: (frame: string) => void- sendRequestedRpc: () => void+ sendRequestedRpc: (status?: unknown) => voidrefreshTimeout: () => voidfinishError: (error: Error) => voidfinishResponse: (response: RuntimeRpcResponse<TResult>) => void@@ -170,7 +170,7 @@ export class RemoteRuntimeRequestResponseRouter<TResult> {this.awaitingStatus = falsethis.awaitingRequestId = this.options.requestIdthis.options.refreshTimeout()- this.options.sendRequestedRpc()+ this.options.sendRequestedRpc(parsed.data.ok ? parsed.data.result : undefined)return}this.options.finishResponse(parsed.data as RuntimeRpcResponse<TResult>)diff --git a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts b/src/shared/remote-runtime/requests/remote-runtime-request-socket.tsindex 5240a3faddb..22b05a9c477 100644--- a/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts+++ b/src/shared/remote-runtime/requests/remote-runtime-request-socket.ts@@ -25,7 +25,11 @@ import {takeRemoteRuntimePreparedRequest} from './remote-runtime-prepared-request-admission'import { RemoteRuntimeRequestResponseRouter } from './remote-runtime-request-response-router'-import type { RuntimeOrchestrationEnvelope, RuntimeRpcResponse } from '../../runtime-rpc-envelope'+import type {+ RuntimeRequestSelection,+ RuntimeOrchestrationEnvelope,+ RuntimeRpcResponse+} from '../../runtime-rpc-envelope'import type { RuntimeStatus } from '../../runtime-types'import { isSafeTimerDelayMs, MAX_TIMER_DELAY_MS } from '../../timer-delay'@@ -37,7 +41,8 @@ export async function sendRemoteRuntimeRequestOnSocket<TResult>(envelope?: RuntimeOrchestrationEnvelope,validateStatus?: (response: RuntimeRpcResponse<RuntimeStatus>) => void,signal?: AbortSignal,- clientCapabilities: readonly RuntimeCapability[] = []+ clientCapabilities: readonly RuntimeCapability[] = [],+ requestSelection?: RuntimeRequestSelection): Promise<RuntimeRpcResponse<TResult>> {throwIfSignalAborted(signal)if (!isSafeTimerDelayMs(timeoutMs)) {@@ -55,18 +60,23 @@ export async function sendRemoteRuntimeRequestOnSocket<TResult>(method: 'status.get'}): null- const pendingRequest = {- preparedRequest: prepareRemoteRuntimeRequest(new Map(), () =>+ const prepare = (selectedParams: unknown) =>+ prepareRemoteRuntimeRequest(new Map(), () =>serializeRemoteRuntimeRpcRequest({requestId,deviceToken: connection.credential.deviceToken,method,- params,+ params: selectedParams,envelope}))+ const pendingRequest: { preparedRequest: ReturnType<typeof prepare> | null } = {+ // Reserve this connection before authentication; select mutation params only after status.+ preparedRequest:+ requestSelection && serializedStatusRequest+ ? prepareRemoteRuntimeRequest(new Map(), () => serializedStatusRequest)+ : prepare(params)}- let serializedRequest = takeRemoteRuntimePreparedRequest(pendingRequest)return await new Promise<RuntimeRpcResponse<TResult>>((resolve, reject) => {const handshake = createRemoteRuntimeClientHandshake(connection.hostPublicKeyB64)let settled = false@@ -139,19 +149,26 @@ export async function sendRemoteRuntimeRequestOnSocket<TResult>(const finishResponse = (response: RuntimeRpcResponse<TResult>): void =>finish({ ok: true, response })- function sendRequestedRpc(): void {- const request = serializedRequest- serializedRequest = null- if (request === null) {- finishError(- new RemoteRuntimeClientError(+ function sendRequestedRpc(status?: unknown): void {+ try {+ if (requestSelection) {+ const selectedParams = requestSelection.paramsForStatus(status)+ releaseRemoteRuntimePreparedRequest(pendingRequest)+ pendingRequest.preparedRequest = prepare(selectedParams)+ }+ const request = takeRemoteRuntimePreparedRequest(pendingRequest)+ if (request === null) {+ throw new RemoteRuntimeClientError('remote_runtime_unavailable','Remote Orca runtime request was released before it could be sent.')- )- return+ }+ const frame = handshake.channel.sealText(request)+ requestSelection?.onDispatch?.()+ ws?.send(frame)+ } catch (error) {+ finishError(error instanceof Error ? error : new Error(String(error)))}- ws?.send(handshake.channel.sealText(request))}router = new RemoteRuntimeRequestResponseRouter({diff --git a/src/shared/rpc-contract/worktree-params.ts b/src/shared/rpc-contract/worktree-params.tsindex 5dfe6e1abf0..90937bba19e 100644--- a/src/shared/rpc-contract/worktree-params.ts+++ b/src/shared/rpc-contract/worktree-params.ts@@ -194,6 +194,8 @@ export const WorktreeSet = WorktreeSelector.extend({})export const WorktreeRemove = WorktreeSelector.extend({+ // Omission retains legacy/UI metadata policy; explicit CLI intent overrides it.+ deleteBranch: OptionalBoolean,hostId: OptionalExecutionHostId,force: OptionalBoolean,// Desktop force also means ordinary confirmed delete; PTY-stop waivers need their own field (#11960).diff --git a/src/shared/runtime-rpc-envelope.ts b/src/shared/runtime-rpc-envelope.tsindex a702748fe29..16f9fadfdf7 100644--- a/src/shared/runtime-rpc-envelope.ts+++ b/src/shared/runtime-rpc-envelope.ts@@ -105,3 +105,9 @@ export type RuntimeRpcDispatchObservation = {responseTimeoutMs: numberresponseExpiresAt?: number}++/** Select request params from the status of the socket that will send them. */+export type RuntimeRequestSelection = {+ paramsForStatus: (status: unknown) => unknown+ onDispatch?: () => void+}diff --git a/src/shared/worktree-runtime-capabilities.ts b/src/shared/worktree-runtime-capabilities.tsindex 203487c8bd0..deca1d3aad3 100644--- a/src/shared/worktree-runtime-capabilities.ts+++ b/src/shared/worktree-runtime-capabilities.ts@@ -29,6 +29,8 @@ export const FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY =// Replay ambiguous creates only with advertised idempotency support; older hosts strip clientMutationId. status.worktreeCreateIdempotency supplies optional retention policy.export const WORKTREE_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY ='worktree.create-idempotency.v1' as const+export const WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY =+ 'worktree.remove-branch-policy.v1' as const// A failed running archive hook blocks deletion. This does not prove a hook was found: unreadable SSH orca.yaml is indistinguishable from absence (#20196).// Advertise the gate so callers need not risk their checkout by probing a failure (#19334).export const WORKTREE_ARCHIVE_FAILURE_BLOCKING_RUNTIME_CAPABILITY =@@ -61,6 +63,7 @@ export const WORKTREE_RUNTIME_CAPABILITIES = [FOLDER_WORKSPACE_PATH_STATUS_RUNTIME_CAPABILITY,WORKTREE_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY,WORKTREE_ARCHIVE_FAILURE_BLOCKING_RUNTIME_CAPABILITY,+ WORKTREE_REMOVE_BRANCH_POLICY_RUNTIME_CAPABILITY,WORKTREE_VISIBILITY_DEFAULTS_RUNTIME_CAPABILITY,WORKTREE_VISIBILITY_SOURCE_DEFAULTS_RUNTIME_CAPABILITY,WORKTREE_CLIENT_AUTOMATION_PROVENANCE_RUNTIME_CAPABILITY