Files
orca/src/main/runtime/runtime-project-host-setup-controller.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

220 lines
8.1 KiB
TypeScript

import type {
Project,
ProjectHostSetup,
ProjectHostSetupCloneArgs,
ProjectHostSetupCreateArgs,
ProjectHostSetupCreateResult,
ProjectHostSetupDeleteArgs,
ProjectHostSetupDeleteResult,
ProjectHostSetupExistingFolderArgs,
ProjectHostSetupResult,
ProjectHostSetupUpdateArgs,
ProjectHostSetupUpdateResult,
ProjectUpdateArgs
} from '../../shared/project-types'
import type { Repo } from '../../shared/repo-types'
import {
getSshTargetIdForExecutionHost,
parseExecutionHostId,
type ExecutionHostId
} from '../../shared/execution-host'
import { getProjectIdForProviderIdentity } from '../../shared/project-host-setup-projection'
import { getProjectHostSetupForRepo } from '../../shared/project-host-setup-lookup'
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
import { prepareLocalWorktreeRootForRepo } from '../worktree-root-preparation'
import type { RuntimeStore } from './runtime-store-contract'
type RuntimeProjectHostSetupDependencies = {
getStore: () => RuntimeStore | null
listRepos: () => Repo[]
addRepo: (path: string, kind: 'folder' | 'git', hostId: ExecutionHostId) => Promise<Repo>
/** Register an existing path that lives on an SSH host; `addRepo` only reaches local/runtime hosts. */
addRemoteRepo: (args: {
connectionId: string
remotePath: string
displayName?: string
kind: 'folder' | 'git'
}) => Promise<Repo>
cloneRepo: (url: string, destination: string, hostId: ExecutionHostId) => Promise<Repo>
invalidateResolvedWorktrees: () => void
invalidateWorktreeScan: (repoId: string) => void
notifyReposChanged: () => void
}
// Why clone alone still refuses: nothing in this process clones onto an SSH host. `cloneRepo` runs
// `git clone` on the client, so accepting `ssh:*` here would register the client's copy as the
// host's repo — a local answer to a remote question. Registering an existing remote path, by
// contrast, has a correct implementation this process already uses over IPC.
function assertCloneHostIsSupported(hostId: ExecutionHostId | null | undefined): void {
if (parseExecutionHostId(hostId)?.kind !== 'ssh') {
return
}
throw new Error(
'Cloning onto an SSH host is not supported. Clone the repository on the host, then set the project up from that existing folder.'
)
}
export class RuntimeProjectHostSetupController {
constructor(private readonly deps: RuntimeProjectHostSetupDependencies) {}
listProjects(): Project[] {
return this.deps.getStore()?.getProjects?.() ?? []
}
updateProject(projectId: string, updates: ProjectUpdateArgs['updates']): Project {
const store = this.deps.getStore()
if (!store?.updateProject) {
throw new Error('runtime_unavailable')
}
const project = store.updateProject(projectId, updates)
if (!project) {
throw new Error(`Project not found: ${projectId}`)
}
this.deps.invalidateResolvedWorktrees()
this.deps.notifyReposChanged()
return project
}
listSetups(): ProjectHostSetup[] {
return this.deps.getStore()?.getProjectHostSetups?.() ?? []
}
createSetup(args: ProjectHostSetupCreateArgs): ProjectHostSetupCreateResult {
const store = this.deps.getStore()
if (!store?.createProjectHostSetup) {
throw new Error('runtime_unavailable')
}
const result = store.createProjectHostSetup(args)
if (!result) {
throw new Error(`Project not found: ${args.projectId}`)
}
return result
}
async setupExistingFolder(
args: ProjectHostSetupExistingFolderArgs
): Promise<ProjectHostSetupResult> {
if (!this.deps.getStore()) {
throw new Error('runtime_unavailable')
}
const kind = args.kind === 'folder' ? 'folder' : 'git'
const knownRepoIds = new Set(this.deps.listRepos().map((repo) => repo.id))
// Why route rather than refuse: this process owns the SSH connection, and its own IPC handler
// already registers `ssh:*` hosts correctly. Refusing here only made the CLI and runtime RPC
// disagree with the desktop app about what the same process can do.
const sshTargetId = getSshTargetIdForExecutionHost(args.hostId)
const repo = sshTargetId
? await this.deps.addRemoteRepo({
connectionId: sshTargetId,
remotePath: args.path,
...(args.displayName ? { displayName: args.displayName } : {}),
kind
})
: await this.deps.addRepo(args.path, kind, args.hostId)
return this.completeSetup(args, repo, !knownRepoIds.has(repo.id))
}
async setupClone(args: ProjectHostSetupCloneArgs): Promise<ProjectHostSetupResult> {
assertCloneHostIsSupported(args.hostId)
const knownRepoIds = new Set(this.deps.listRepos().map((repo) => repo.id))
const repo = await this.deps.cloneRepo(args.url, args.destination, args.hostId)
return this.completeSetup(
{ ...args, path: repo.path, kind: 'git', setupMethod: 'cloned' },
repo,
!knownRepoIds.has(repo.id)
)
}
updateSetup(args: ProjectHostSetupUpdateArgs): ProjectHostSetupUpdateResult {
const store = this.deps.getStore()
if (!store?.updateProjectHostSetup) {
throw new Error('runtime_unavailable')
}
const result = store.updateProjectHostSetup(args)
if (!result) {
throw new Error(`Project host setup not found: ${args.setupId}`)
}
if ('worktreeBasePath' in args.updates && result.repo) {
void prepareLocalWorktreeRootForRepo(store, result.repo)
invalidateAuthorizedRootsCache()
}
return result
}
deleteSetup(args: ProjectHostSetupDeleteArgs): ProjectHostSetupDeleteResult {
const store = this.deps.getStore()
if (!store?.deleteProjectHostSetup) {
throw new Error('runtime_unavailable')
}
const result = store.deleteProjectHostSetup(args)
if (!result) {
throw new Error(`Project host setup not found: ${args.setupId}`)
}
return result
}
private completeSetup(
args: ProjectHostSetupExistingFolderArgs,
initialRepo: Repo,
repoWasCreated: boolean
): ProjectHostSetupResult {
try {
return this.linkRepo(args, initialRepo)
} catch (error) {
if (repoWasCreated) {
this.deps.getStore()?.removeProject?.(initialRepo.id)
this.deps.invalidateResolvedWorktrees()
this.deps.invalidateWorktreeScan(initialRepo.id)
invalidateAuthorizedRootsCache()
this.deps.notifyReposChanged()
}
throw error
}
}
private linkRepo(
args: ProjectHostSetupExistingFolderArgs,
initialRepo: Repo
): ProjectHostSetupResult {
const store = this.deps.getStore()
if (!store) {
throw new Error('runtime_unavailable')
}
let repo = initialRepo
let setup = getProjectHostSetupForRepo(this.listSetups(), repo)
if (setup.projectId !== args.projectId) {
const existingProject = this.listProjects().find((project) => project.id === args.projectId)
const identity = existingProject?.providerIdentity ?? args.projectProviderIdentity
if (!identity || getProjectIdForProviderIdentity(identity) !== args.projectId) {
throw new Error('Imported folder does not match the selected project identity.')
}
const updated = store.updateRepo(repo.id, {
upstream: {
owner: identity.owner,
repo: identity.repo,
...(identity.host ? { host: identity.host } : {})
}
})
if (!updated) {
throw new Error(`Project setup repo disappeared before it could be linked: ${repo.id}`)
}
repo = updated
setup = getProjectHostSetupForRepo(this.listSetups(), repo)
}
const setupMethod = args.setupMethod ?? 'imported-existing-folder'
const updated = store.updateRepo(repo.id, { projectHostSetupMethod: setupMethod })
if (!updated) {
throw new Error(
`Project setup repo disappeared before setup metadata could be linked: ${repo.id}`
)
}
repo = updated
setup = getProjectHostSetupForRepo(this.listSetups(), repo)
const project = this.listProjects().find((entry) => entry.id === setup.projectId)
if (!project) {
throw new Error(`Project setup was created without a project record: ${setup.projectId}`)
}
return { project, setup, repo }
}
}