Files
orca/src/main/runtime/orca-runtime-create-managed-worktree.ts
T
Neil 7c94d12190 fix(ssh): route four host-blind seams through the resolved execution host (#17919)
* fix(host-routing): resolve the execution host before reading a connection

Three issues in one defect class: a resolver reads one spelling of one
arbitrarily chosen row instead of resolving the worktree's execution host,
so something local answers a question about a remote.

returned that row's connectionId. With duplicate repo rows for one repo id
it could pair a runtime owner with a client-owned SSH connection. It now
resolves through the same ambiguity-aware index getRuntimeEnvironmentIdForWorktree
uses, prefers the repo row for the host the worktree names, and derives the
connection from the resolved host. Conflicting rows return `undefined`
(this module's documented "cannot determine the host"), never `null`.

`store.getRepo(worktree.repoId)?.connectionId ?? null`. `getRepo` is
host-blind and the same repo id can exist on local, SSH and runtime hosts,
so a remote worktree could spawn its PTY on the client with the remote cwd.
resolveWorktreeLaunchHost picks the row for the worktree's host and reads
the connection off that host; conflicting rows are unresolved, not local.

session-partition owner maps that contradict each other. Both now compute
through one shared function whose argument records the divergence. No
behaviour change on either side: converging needs a read-both migration,
since both partitions hold real data written by shipping builds.

* fix(host-routing): keep nested SSH connections resolvable under a runtime host

getRepoSshConnectionId read only the resolved execution host, so a repo row
owned by a runtime that reaches a nested SSH target (connectionId: ssh-*,
executionHostId: runtime:*) resolved to no connection — answering 'local' for
a remote worktree, the same defect #17909 fixed in the other direction.

* fix(host-routing): resolve both sides of the execution host through one rule

The renderer resolver leaked between two different SSH hosts: a worktree on
`ssh:m4air` whose only indexed repo row belonged to `openclaw` answered
'openclaw', because the host-scoped lookup missing fell through to an id-only
one. Main's resolver, in the same change, answered 'm4air' — two resolvers, one
right and one wrong, on identical input.

Both sides now adapt one shared rule (`worktree-execution-host-resolution.ts`):
the worktree's own host outranks every repo row, and a row on a different host
is never evidence about this one. The renderer's WeakMap index becomes the
memoizing adapter it always was; `resolveWorktreeLaunchHost` becomes main's
mapping of unresolved onto its throw.

Settles the rule the change previously answered two ways.
`getRepoSshConnectionId` and `getSshTargetIdForExecutionHost` disagreed for a
runtime host carrying a nested `connectionId`; they now compose, so the
execution host is the single authority. On a `runtime:*` row that field is a
paired HUB's private SSH target, spread through by `repoWithFetchedOwner` and
unaddressable from this client — the project-first successor of the row nulls it
for exactly that reason. That also fixes the `kind !== 'ssh'` fallback, which
fired for `local`: a row declaring itself local handed out an SSH connection.

* fix(ssh): resolve the execution host in the worktree scan and managed create

The worktree scan and createManagedWorktree both picked remote-vs-local from
repo.connectionId, so a row stamped only executionHostId: 'ssh:*' was scanned
and created on the client against a remote path. The folder branch returns
before the check, so its agent-trust write landed locally too.

Refs #11163

* fix(ssh): stop over-rejecting and refusing SSH hosts the process owns

runtimeRepoMatchesExecutionHost rejected an unstamped SSH repo against its own
ssh:<connectionId>, so repo-add/clone dedupe could register a second row for a
path the host already owns. assertHostIsSupported made the CLI/runtime RPC
refuse --host ssh:* while the same process's IPC handler routed it correctly;
setupExistingFolder now shares that registration. Clone still refuses, because
nothing in this process clones onto an SSH host.

Refs #11163

* test(ssh): retarget the SSH host-setup guard spec at the substitution it prevents

setupProjectExistingFolder now registers the remote path through the same
addRemoteRepoFromPath the desktop IPC uses, so it fails on the host's terms
(connection not registered) rather than a categorical refusal. The local
clone/probe side effects it exists to catch are still asserted absent.

Refs #11163

* fix(cli): require an absolute path when setting a project up on an SSH host

Routing --host ssh:* to the remote registration made relative paths newly
reachable there, and they were resolved against the client cwd — registering a
path that names the wrong machine.

Refs #11163

* fix(repos): read the SSH registry directly so the runtime stays Node-bootable

Routing runtime project setup through addRemoteRepoFromPath dragged ipc/ssh --
and its 25-module electron graph -- into the runtime bundle. ssh-target-registry
already exists for exactly this; ipc/ssh only re-exports it.

* fix(ssh): close the agent-launch and session-export host-blind twins

Three sites left on the legacy spelling, all the same shape as the ones this
branch already fixed:

- `launchAgentTerminal` did `getRepo(worktree.repoId)` then wrote agent trust
  with that row's `connectionId`. Host-blind, so a repo id carried by two SSH
  hosts wrote a remote path into the *client's* Codex/Cursor/Copilot config and
  the agent on the host never saw the trust. Every sibling call site already
  passes the resolved `workspace.connectionId`; this was the last that did not.
- `targetForWorktree` (workspace-session export) fell back to the same
  host-blind read, so a session could be published to a machine that never
  owned the worktree. Unresolvable ownership now exports to nobody.
- `addRemoteRepoFromPath` minted `connectionId`-only rows while being the
  routing path this branch adds, so it kept creating rows in exactly the
  spelling the branch works around. It now stamps
  `toSshExecutionHostId(connectionId)` at creation; `reassignSshTargetId`
  already migrates both spellings, so target rename stays correct.

Tests cover two *different* SSH hosts throughout — the case none of the earlier
duplicate-row tests had, all of which were local-vs-ssh or runtime-vs-ssh.
2026-09-02 16:59:29 -07:00

292 lines
12 KiB
TypeScript

// @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests.
import { OrcaRuntimeWithGetWorktreeTerminalProvisioningHost } from './orca-runtime-get-worktree-terminal-provisioning-host'
import type { RuntimeManagedWorktreeCreateArgs } from './runtime-managed-worktree-create-types'
import type { CreateWorktreeResult } from '../../shared/worktree/create-types'
import { isTuiAgentEnabled } from '../../shared/tui-agent-selection'
import { isFolderRepo } from '../../shared/repo-kind'
import { getRepoSshConnectionId } from '../../shared/execution-host'
import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create'
import { createRuntimeLocalManagedWorktree } from './runtime-local-worktree-create'
import { prepareRuntimeLocalWorktreeSetup } from './runtime-local-worktree-setup'
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
import { startRuntimeLocalWorktreeTerminals } from './runtime-local-worktree-terminal-startup'
export class OrcaRuntimeWithCreateManagedWorktree extends OrcaRuntimeWithGetWorktreeTerminalProvisioningHost {
async createManagedWorktree(
args: RuntimeManagedWorktreeCreateArgs
): Promise<CreateWorktreeResult> {
if (!this.store) {
throw new Error('runtime_unavailable')
}
const repo = await this.resolveRepoSelector(args.repoSelector)
const createSettings = this.store.getSettings()
const requestedAgent = args.startupAgent ?? args.createdWithAgent
const requestedAgentEnabled =
requestedAgent !== undefined
? isTuiAgentEnabled(requestedAgent, createSettings.disabledTuiAgents)
: false
if ((args.startup || args.startupAgent) && requestedAgent && !requestedAgentEnabled) {
throw new Error('Selected agent is disabled. Choose an enabled agent before creating.')
}
if (
args.startup &&
args.startupDraftPaste &&
!isTuiAgentEnabled(args.startupDraftPaste.agent, createSettings.disabledTuiAgents)
) {
throw new Error('Selected agent is disabled. Choose an enabled agent before creating.')
}
const agentStartup =
!args.startup && args.startupAgent
? this.buildStartupForAgent(
repo,
args.startupAgent,
args.startupPrompt,
args.startupLaunchPreferences
)
: null
const draftStartup =
!args.startup && !agentStartup && args.startupDraft
? await this.buildStartupForDraft(repo, args.startupDraft, requestedAgent)
: null
const effectiveStartup = args.startup ?? agentStartup?.startup ?? draftStartup?.startup
const effectiveStartupFollowup = agentStartup?.followup
const effectiveCreatedWithAgent = args.startup
? args.createdWithAgent
: (agentStartup?.agent ??
draftStartup?.agent ??
(requestedAgentEnabled ? requestedAgent : undefined))
const effectiveDraftPaste = args.startupDraftPaste ?? draftStartup?.draftPaste
// Resolve the execution host once: SSH ownership has two spellings, and reading the raw
// `connectionId` field routes an `executionHostId: 'ssh:*'`-only repo down the local path,
// which runs `git worktree add` on the client against a remote path.
const sshConnectionId = getRepoSshConnectionId(repo)
if (isFolderRepo(repo)) {
// A folder workspace is a registration, not a filesystem create, so it is host-agnostic —
// except for the agent trust write, which must land on the host that will run the agent.
return createRuntimeFolderWorktree({
request: args,
repo,
startup: effectiveStartup,
startupFollowup: effectiveStartupFollowup,
createdWithAgent: effectiveCreatedWithAgent,
draftPaste: effectiveDraftPaste,
deps: {
store: this.store,
ptySpawnAvailable: Boolean(this.ptyController?.spawn),
createTerminal: (selector, options) => this.createTerminal(selector, options),
markTrusted: (agent, path) =>
this.markWorkspaceTrustedForAgent(agent, sshConnectionId, path),
pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft),
sendFollowup: (handle, followup) => this.sendStartupFollowupWhenReady(handle, followup),
invalidateResolvedWorktrees: () => this.invalidateResolvedWorktreeCache(),
notifyWorktreesChanged: (repoId) => this.notifyWorktreesChanged(repoId),
emitCreated: (event) => this.emitWorktreeLifecycle(event),
activate: (repoId, worktreeId, setup, startup) =>
this.notifyActivateWorktree(
repoId,
worktreeId,
setup,
startup,
undefined,
args.navigation
)
}
})
}
const lineageInput =
args.lineage || args.comment ? { ...args.lineage, comment: args.comment } : undefined
const lineageResolution = await this.resolveLineageForWorktreeCreate(lineageInput)
if (sshConnectionId) {
// Why normalize the row: the remote-create pipeline reads `repo.connectionId!` at every
// depth, so hand it the connection the resolved host actually names.
const result = await this.createManagedRemoteWorktree(
{ ...repo, connectionId: sshConnectionId },
{
...args,
activate: args.activate,
...(effectiveStartup ? { startup: effectiveStartup } : {}),
...(effectiveStartupFollowup ? { startupFollowup: effectiveStartupFollowup } : {}),
...(effectiveCreatedWithAgent ? { createdWithAgent: effectiveCreatedWithAgent } : {}),
...(effectiveDraftPaste ? { startupDraftPaste: effectiveDraftPaste } : {})
}
)
const recordedLineage = this.recordCreatedWorktreeLineage(result.worktree, lineageResolution)
this.emitWorktreeLifecycle({
kind: 'created',
worktreeId: result.worktree.id,
path: result.worktree.path,
branch: result.worktree.branch
})
return {
...result,
worktree: {
...result.worktree,
parentWorktreeId: recordedLineage.lineage?.parentWorktreeId ?? null,
childWorktreeIds: result.worktree.childWorktreeIds ?? [],
lineage: recordedLineage.lineage,
workspaceLineage: recordedLineage.workspaceLineage
},
...(lineageInput
? {
lineage: recordedLineage.lineage,
workspaceLineage: recordedLineage.workspaceLineage,
warnings: recordedLineage.warnings
}
: {})
}
}
const { worktree, worktreePath, includeCopyWarning, created, addResult, metadataResult } =
await createRuntimeLocalManagedWorktree({
request: args,
repo,
store: this.requireStore(),
createdWithAgent: effectiveCreatedWithAgent,
hostedReviewExecutionContext: this.getHostedReviewExecutionOptions(repo),
resolveRemoteTrackingBase: (path, base, ...options) =>
this.resolveRemoteTrackingBase(path, base, ...options),
hasRemoteTrackingRef: (path, base, ...options) =>
this.hasRemoteTrackingRef(path, base, ...options),
refreshRemoteTrackingBase: (path, base, ...options) =>
this.getOrStartRemoteTrackingBaseRefresh(path, base, ...options),
fetchRemote: (path, remote, ...options) =>
this.fetchRemoteWithCache(path, remote, ...options),
onWorktreeMetadataPersisted: (persistedWorktree) =>
this.recordCreatedWorktreeLineage(persistedWorktree, lineageResolution)
})
const settings = createSettings
const { lineage, workspaceLineage, warnings: lineageWarnings } = metadataResult
let {
setup,
defaultTabs,
warning,
effectiveDecision,
hookFound,
shouldRunSetup,
didStartInProcessSetupHook
} = await prepareRuntimeLocalWorktreeSetup({
request: args,
repo,
worktreePath,
settings,
runtimeTarget: this.getLocalGitExecutionOptionArgs(repo)[0],
shouldUseSetupRunner:
this.authoritativeWindowId !== null ||
Boolean(effectiveStartup) ||
Boolean(this.ptyController?.spawn),
warning: includeCopyWarning
})
this.invalidateResolvedWorktreeCache()
this.invalidateWorktreeScanCacheForRepo(repo.id)
// Why: the filesystem-auth layer maintains a separate cache of registered
// worktree roots used by git IPC handlers (branchCompare, diff, status, etc.)
// to authorize paths. Without invalidating it here, CLI-created worktrees
// are not recognized and all git operations fail with "Access denied:
// unknown repository or worktree path".
invalidateAuthorizedRootsCache()
this.notifyWorktreesChanged(repo.id)
const {
warning: terminalWarning,
returnedSetup,
didSpawnSetup,
didSpawnStartup,
setupTerminalHandle,
startupTerminalHandle,
startupTerminalTabId,
startupTerminalPaneKey,
startupTerminalPtyId
} = await startRuntimeLocalWorktreeTerminals({
request: args,
repo,
worktree,
setup,
defaultTabs,
startup: effectiveStartup,
startupFollowup: effectiveStartupFollowup,
createdWithAgent: effectiveCreatedWithAgent,
draftPaste: effectiveDraftPaste,
warning,
ports: {
canSpawn: Boolean(this.ptyController?.spawn),
markTrusted: (agent, path) => this.markLocalWorkspaceTrustedForAgent(agent, path),
createTerminal: (selector, options) => this.createTerminal(selector, options),
pasteDraft: (handle, draft) => this.pasteStartupDraftWhenReady(handle, draft),
sendFollowup: (handle, followup) => this.sendStartupFollowupWhenReady(handle, followup),
provision: (options) => this.provisionManagedWorktreeTerminals(options),
activate: (repoId, worktreeId, activationSetup, startup, activationDefaultTabs) =>
this.notifyActivateWorktree(
repoId,
worktreeId,
activationSetup,
startup,
activationDefaultTabs,
args.navigation
)
}
})
warning = terminalWarning
this.emitWorktreeLifecycle({
kind: 'created',
worktreeId: worktree.id,
path: worktree.path,
branch: worktree.branch
})
return {
worktree: {
...worktree,
parentWorktreeId: lineage?.parentWorktreeId ?? null,
childWorktreeIds: [],
lineage,
workspaceLineage,
git: created
},
...(lineageInput ? { lineage, workspaceLineage, warnings: lineageWarnings } : {}),
...(returnedSetup ? { setup: returnedSetup } : {}),
...(args.awaitTerminalProvisioning
? {
setupReceipt: {
requested: effectiveDecision,
hookFound,
startupPolicy: setup?.waitForAgentStartup
? ('wait-for-setup' as const)
: ('start-immediately' as const),
state: !hookFound
? ('not_configured' as const)
: effectiveDecision === 'skip' || !shouldRunSetup
? ('skipped' as const)
: // Why: the in-process hook is already executing, so reporting
// spawn_failed would strand callers that retry on it.
didSpawnSetup || didStartInProcessSetupHook
? ('running' as const)
: ('spawn_failed' as const),
...(setupTerminalHandle ? { terminalHandle: setupTerminalHandle } : {})
}
}
: {}),
...(defaultTabs ? { defaultTabs } : {}),
...(warning ? { warning } : {}),
...(addResult.localBaseRefRefresh
? { localBaseRefRefresh: addResult.localBaseRefRefresh }
: {}),
...(addResult.localBaseRefUpdateSuggestion
? { localBaseRefUpdateSuggestion: addResult.localBaseRefUpdateSuggestion }
: {}),
...(didSpawnStartup && startupTerminalHandle
? {
startupTerminal: {
spawned: true,
handle: startupTerminalHandle,
...(startupTerminalTabId ? { tabId: startupTerminalTabId } : {}),
...(startupTerminalPaneKey ? { paneKey: startupTerminalPaneKey } : {}),
...(startupTerminalPtyId ? { ptyId: startupTerminalPtyId } : {}),
surface: 'background' as const
}
}
: {})
}
}
}