Files
orca/src/cli/workspaces/worktree-parent-environment.ts
T
506d116ee3 Move saved server reads and writes off the main thread (#42253)
* Move environment store operations off the main thread

* Preserve CLI startup speed with the serialized environment owner

* Handle absent paired host labels in the producer regression fixture

* Preserve publication ownership and copy selected environment results

* Correct publication and WSL readiness regression fixtures

* Include environment store worker in deployed server artifacts

* Check fresh listing publication across an intervening store update

* Await store-backed results in new recovery coverage

* Retire failed page publications and retain CLI worker support entries

* Unpack environment store support modules for the installed CLI

* Align async store callers with their return contracts

* Avoid hardening work for absent environment store files

* Keep permission repair bounded to one hardening attempt

* Align store test fixtures and await pairing replacement

* Use the semantic store operation for external pairing fixtures

* Provide the live sender frame in the timed subscription fixture

* Share pending server lookups and settle retired phone requests

* Keep the relay error type import

* Keep status ownership and transport imports acyclic

* Await replacement pairing in status retirement cases

* Keep asynchronous server rows bound to their admitted pairing

* Keep inventory snapshots and queued delivery at one publication boundary

* Await saved-host and graph test setup through publication completion

* Finish async fixture types and remove foreground timing probe

* Await renderer surface transitions in process identity coverage

* Await nested graph publication fixtures through their callers

* Await restored pane graph publication before hook assertions

* Include imported store worker and sidebar files in web typecheck

* Prepare saved host storage in source-based WSL test rigs

* Await saved server lookups in the source retirement diagnostic

* Preserve newer WSL status across async saved-host reads

* Fence stopped probes when a newer WSL Ready arrives

* Keep saved WSL host selection covered when admission is off

* Check WSL probe ownership after async admission

* Preserve WSL stop authority without cancelling Ready persistence

* Prune removed WSL E2E real-time wait from flaky-test baseline

* Limit WSL callback invalidation to confirmed stops

* Retire pending WSL notices on every confirmed stop

* Close the WSL picker dialog explicitly between scenarios

* perf(layout): skip unused normalization reports in pane commands (#42615)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Clarify cleanup pinning and ignored-file protection (#42616)

* test: remove 55 low-value suites and assertion driver (#42605)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>

* fix(skills): skip Claude sync scratch folders during skill discovery (#42610)

Claude Code parks replaced skill copies in `.trash` and in-progress syncs
in `.staging` under its skills roots. Discovery walked into both, so each
synced skill showed up as duplicates. Prune those directory names in the
native file walk and in the generated WSL `find` command.

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>

* test: remove 78 low-value suites and trim redundant cases (#42621)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>

* Keep quit teardown within the source line budget

---------

Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: OrcaWin <alpha-eng@stably.ai>
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
Co-authored-by: BingZ <zzb@gxsmjx.com>
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
2026-11-15 02:45:45 -08:00

300 lines
12 KiB
TypeScript

import { isRecoverableRemoteRuntimeConnectionError } from '../../shared/remote-runtime/remote-runtime-client-error-classification'
import { listEnvironments } from '../../shared/remote-runtime/host-store/runtime-environment-store'
import type { RuntimeStatus } from '../../shared/remote-runtime/session-graph/runtime-session-contracts'
import type { RuntimeWorktreeRecord } from '../../shared/worktree/catalog/runtime-worktree-contracts'
import type { CrossStoreParentRef } from '../../shared/worktree/lineage-types'
import { crossStoreParentRefOfRow } from '../../shared/worktree/lineage/lineage-row-identity'
import {
supportsCrossStoreLineage,
WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY
} from '../../shared/remote-runtime/protocol/worktree-runtime-capabilities'
import { getOptionalParentSelector } from '../workspace-selection/caller-folder-workspace'
import { getOptionalStringFlag } from '../arguments/flags'
import { mayNameFolderWorkspace } from '../workspace-selection/folder-workspace-selector'
import { isLocalEnvironmentSelector, LOCAL_ENVIRONMENT } from '../hosts/local-environment-selector'
import { RuntimeClient } from '../runtime/client'
import { RuntimeClientError } from '../runtime/connection/types'
import type { RuntimeRpcSuccess } from '../../shared/remote-runtime/rpc/runtime-rpc-envelope'
import { quoteCliCommandArgument } from '../arguments/shell-command-quote'
import { describeClientEnvironment, environmentLabel } from './workspace-address'
import { attachCliErrorData } from './worktree-setup-decision-recovery'
/** The Orca a parent lives in: `local` or a saved environment's id. */
export type ParentEnvironment = { route: string; name: string }
const LOCAL: ParentEnvironment = { route: LOCAL_ENVIRONMENT, name: LOCAL_ENVIRONMENT }
function isCallerRelative(selector: string | undefined): boolean {
return selector === 'active' || selector === 'current'
}
async function savedParentEnvironment(
userDataPath: string,
value: string
): Promise<ParentEnvironment> {
const saved = await listEnvironments(userDataPath)
const byId = saved.find((environment) => environment.id === value)
const byName = saved.filter((environment) => environment.name === value)
const found = byId ?? (byName.length === 1 ? byName[0] : undefined)
if (found) {
return { route: found.id, name: found.name }
}
if (byName.length > 1) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-environment ${value} is ambiguous: ${byName.length} saved environments have that name. Use the environment id.`,
{ nextSteps: byName.map((environment) => `--parent-environment ${environment.id}`) }
)
}
throw new RuntimeClientError(
'environment_not_paired',
`--parent-environment ${value} is not a saved environment here, so its workspaces can't be reached from this machine.`,
{
environment: value,
knownEnvironments: saved.map(({ id, name }) => ({ id, name })),
nextSteps: [
'Pass local, or the id or name of a saved environment from `orca environment list`.',
'Pair it first with `orca environment add --name <name> --pairing-code <code>`.'
]
}
)
}
/**
* Which environment `--parent-worktree` names, when that differs from the child's. Undefined keeps
* same-environment parents. A caller-relative parent (active/current) is always on the caller's own
* Orca, so against another environment it is implicitly `local`.
*/
export async function resolveParentEnvironment(
flags: Map<string, string | boolean>,
client: RuntimeClient
): Promise<ParentEnvironment | undefined> {
const parentSelector = getOptionalStringFlag(flags, 'parent-worktree')
const value = getOptionalStringFlag(flags, 'parent-environment')
if (flags.has('parent-environment')) {
if (value === undefined) {
throw new RuntimeClientError('invalid_argument', 'Missing required --parent-environment')
}
if (flags.get('no-parent') === true || !parentSelector) {
throw new RuntimeClientError(
'invalid_argument',
'--parent-environment says where --parent-worktree lives; pass it with --parent-worktree, not with --no-parent or alone.'
)
}
}
const named = value
? isLocalEnvironmentSelector(value)
? LOCAL
: await savedParentEnvironment(client.userDataPath, value)
: undefined
if (isCallerRelative(parentSelector) && named && named.route !== LOCAL_ENVIRONMENT) {
throw new RuntimeClientError(
'invalid_argument',
`--parent-worktree ${parentSelector} names the workspace containing this terminal or cwd, which is on this machine's own Orca, not ${named.name}.`,
{
nextSteps: [
`Drop --parent-environment, or pass --parent-environment local.`,
`For a workspace in ${named.name}, list it with \`orca worktree ps --environment ${quoteCliCommandArgument(named.route)} --json\` and pass its address.worktree as --parent-worktree.`
]
}
)
}
const parentEnvironment = named ?? (isCallerRelative(parentSelector) ? LOCAL : undefined)
return parentEnvironment &&
parentEnvironment.route !== (await describeClientEnvironment(client)).id
? parentEnvironment
: undefined
}
function parentEnvironmentClient(
client: RuntimeClient,
environment: ParentEnvironment
): RuntimeClient {
return new RuntimeClient(
client.userDataPath,
undefined,
null,
environment.route === LOCAL_ENVIRONMENT ? null : environment.route
)
}
/** Refuses before any request: an older child Orca would apply the rest and drop the parent. */
async function assertChildSavesCrossStoreParents(client: RuntimeClient): Promise<void> {
const status = (await client.call<RuntimeStatus>('status.get')).result
if (supportsCrossStoreLineage(status.capabilities)) {
return
}
const environment = await describeClientEnvironment(client)
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environmentLabel(environment)} to nest workspaces under a parent in another environment. Nothing was changed.`,
{ environment: environment.id, requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY }
)
}
function unavailableError(error: unknown, environment: ParentEnvironment): unknown {
if (!(error instanceof RuntimeClientError) || !isRecoverableRemoteRuntimeConnectionError(error)) {
return error
}
return new RuntimeClientError(
'environment_unavailable',
`${environment.name} didn't answer, so the parent couldn't be checked. Nothing was changed. (${error.message})`,
{
environment: environment.route,
nextSteps: [`orca status --environment ${quoteCliCommandArgument(environment.route)} --json`]
}
)
}
type ParentLookupCode = 'LINEAGE_PARENT_NOT_FOUND' | 'LINEAGE_PARENT_AMBIGUOUS'
function isParentLookupCode(code: string): code is ParentLookupCode {
return code === 'LINEAGE_PARENT_NOT_FOUND' || code === 'LINEAGE_PARENT_AMBIGUOUS'
}
/** The lineage code for a parent lookup's own error, as the runtime reports an explicit parent. */
function parentLookupCode(error: RuntimeClientError): ParentLookupCode | undefined {
if (isParentLookupCode(error.code)) {
return error.code
}
return error.code === 'selector_not_found'
? 'LINEAGE_PARENT_NOT_FOUND'
: error.code === 'selector_ambiguous'
? 'LINEAGE_PARENT_AMBIGUOUS'
: undefined
}
/**
* Error data for a parent miss or ambiguity: the environment searched, and recovery that lists that
* environment. Inherited steps are dropped because they inspect the caller's default route.
*/
function searchedEnvironmentData(
error: RuntimeClientError,
code: ParentLookupCode,
environment: { route: string | null; name: string },
extraSteps: readonly string[] = []
): Record<string, unknown> {
const list = environment.route
? `orca worktree ps --environment ${quoteCliCommandArgument(environment.route)} --json`
: undefined
const listStep = list
? code === 'LINEAGE_PARENT_AMBIGUOUS'
? `Compare the choices with \`${list}\`, then pass one as --parent-worktree.`
: list
: 'This one-off connection has no listing route; save it with `orca environment add --name <name> --pairing-code <code>`, then run `orca worktree ps --environment <name> --json`.'
return {
...(error.data && typeof error.data === 'object' ? error.data : {}),
environment: environment.route,
nextSteps: [listStep, ...extraSteps]
}
}
function parentLookupError(error: unknown, environment: ParentEnvironment): unknown {
if (!(error instanceof RuntimeClientError)) {
return error
}
const code = parentLookupCode(error)
if (!code) {
return error
}
const message =
code === 'LINEAGE_PARENT_NOT_FOUND'
? `No workspace in ${environment.name} matched the parent selector. Nothing was changed; no other environment was searched.`
: `${error.message} (in ${environment.name}; nothing was changed)`
return new RuntimeClientError(code, message, searchedEnvironmentData(error, code, environment))
}
/**
* The verified ref a child saves for a parent in another environment, built as the app builds it:
* the parent store's own installationId plus the parent row's identity. No other environment is
* searched, and every check runs before the child is changed.
*/
export async function resolveCrossEnvironmentParent(
client: RuntimeClient,
args: { flags: Map<string, string | boolean>; cwd: string; environment: ParentEnvironment }
): Promise<CrossStoreParentRef> {
const { flags, cwd, environment } = args
await assertChildSavesCrossStoreParents(client)
const parentClient = parentEnvironmentClient(client, environment)
try {
const raw = getOptionalStringFlag(flags, 'parent-worktree') ?? ''
// active/current keep their own cwd recovery; only an explicit selector's miss is the parent's.
const selector = isCallerRelative(raw)
? ((await getOptionalParentSelector(flags, cwd, parentClient)) ?? raw)
: raw
const parent = await parentClient
.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
worktree: selector,
...(mayNameFolderWorkspace(selector) ? { matchFolderWorkspaces: true } : {})
})
.catch((error: unknown) => {
throw parentLookupError(error, environment)
})
const { installationId } = (
await parentClient.call<{ installationId?: string }>('worktree.lineageList')
).result
const ref = crossStoreParentRefOfRow(installationId, parent.result.worktree)
if (!installationId) {
throw new RuntimeClientError(
'incompatible_runtime',
`Update Orca in ${environment.name} so workspaces in other environments can name it as a parent. Nothing was changed.`,
{
environment: environment.route,
requires: WORKTREE_CROSS_STORE_LINEAGE_RUNTIME_CAPABILITY
}
)
}
if (!ref) {
throw new RuntimeClientError(
'invalid_argument',
"Couldn't confirm the parent's workspace identity. Refresh it in the Orca app and try again."
)
}
return ref
} catch (error) {
throw unavailableError(error, environment)
}
}
/** Sends a create/set; a miss or ambiguity on its same-environment parent names where it looked
* and how to list it, and a miss says how to name a parent elsewhere. */
export async function callNamingParentEnvironment<
T,
Params extends { parentWorktree?: string; parentWorkspace?: string; crossStoreParent?: unknown } =
Record<string, unknown>
>(
client: RuntimeClient,
method: 'worktree.create' | 'worktree.set',
params: Params
): Promise<RuntimeRpcSuccess<T>> {
try {
return await client.call<T>(method, params)
} catch (error) {
const parentSelector = params.parentWorktree ?? params.parentWorkspace
// A selector_* error here may be the child's own selector; only lineage codes name the parent.
if (
!(error instanceof RuntimeClientError) ||
!isParentLookupCode(error.code) ||
!parentSelector ||
params.crossStoreParent
) {
throw error
}
const code = error.code
const environment = await describeClientEnvironment(client)
throw attachCliErrorData(
error,
searchedEnvironmentData(
error,
code,
{ route: environment.id, name: environmentLabel(environment) },
code === 'LINEAGE_PARENT_NOT_FOUND'
? [
`Only ${environmentLabel(environment)} was searched for "${parentSelector}". For a parent in another environment, add --parent-environment <local|environment-id> (a row's address.environment from \`orca worktree ps --environment <id> --json\`).`
]
: []
)
)
}
}