Files
orca/src/shared/runtime-environment-store-file.ts
T
Neil a65fdc887f feat(wsl): WSL distro hosts, main-process wiring and persistence (WSL-via-orcad C7a, experimental) (#27933)
* feat(wsl): persist WSL host deployments in their own store and type orcad deployment links by kind

* chore(wsl): drop an unused link type export

* feat(wsl): add, persist and connect WSL distro hosts behind an experimental flag (WSL-via-orcad C7a)

Main-process wiring for WSL hosts: list registered WSL 2 distros, add one (C4 deploy and
launch through C6 liveness, then persist the paired environment and its C2 record), keep a
relaunch's new device token, connect a host only for the user or an open project or terminal,
adopt holders at startup, and remove a host (release its holder, drop both records). Refuses a
distro whose orcad this desktop already reaches as another server (R25).

* fix(wsl): read distro registrations through one reader that returns the canonical unbraced GUID

C4's registry reader returned the braced GUID while the C2 record only accepts it unbraced, and
C7 parsed the same output a second time. The one reader now yields lowercase unbraced ids and
each registration's WSL version; the host distro list uses it.

* fix(wsl): refuse to connect a WSL host while the experiment is off

Adding, connecting and background connects all stop while Experimental → WSL distros as hosts
is off; removing still works. The pre-deploy refusals move to their own module.

* fix(wsl): stop a connected WSL host's server when the host is removed

Remove ended the bridge and released the distro's holder but left orcad to exit with the
distro. A connected server is now ended right away, only in a distro already running.

* fix(wsl): import the orcad host errors from their new orcad/ home

* fix(wsl): refuse WSL hosts in a build without the orcad template, and say so up front

A build shipped without the orcad deployment template let the add dialog run and fail after
seconds with a raw internal error. Main now checks the template as SSH hosts do, refuses add
and connect (and skips lazy connects and holder adoption) before any deploy work, and exposes
the capability so the UI can show it.

* test(wsl): let the e2e WSL fake re-read its distro list, to register one mid-run

* fix(wsl): end a removed host's terminals and daemon, and stop WSL hosts when the experiment is off

Remove now ends the host's terminals through orcad's terminal RPC, waits for the terminal census
to prove none remain, closes the bridge, and runs the managed decommission SSH hosts use, which
stops orcad and retires its idle terminal daemon. What it could not end is reported back.

Turning Experimental → WSL distros as hosts off closes every connection and liveness watch,
releases the holders so distros can idle-stop, and keeps liveness from relaunching for visible
work; turning it on resumes only the hosts open work needs.

* fix(wsl): keep WSL hosts out of the servers a phone reaches through this desktop

They are this desktop's own distros, connected only for work open here; a phone listing or
routing to one would wake it behind the user's back.

* fix(wsl): end a removed host's terminals through its own route, and never respawn it

Removal reached orcad with the bridge's raw pairing offer rather than the routed environment and
saved pairing the app already uses for the host; on a real orcad ending terminals failed fast and
left them, the daemon and orcad running. It now calls by environment id through the same
transport as every other call to the host, and the e2e fake runs these real steps against a
headless server.

Removal also stops tracking the host first (open work, connects, runtime calls), so nothing
reconnects it while it stops, and a spawn guard in the connector refuses any holder, deploy or
bridge for a distro whose host is gone (the respawn loop after removal). A WSL host that isn't
connected answers runtime calls with why, instead of failing as an unreachable network server.

* fix(wsl): suggest reconnecting a WSL host, not Tailscale, when it can't be reached

Unreachable-server hints are chosen by the owner host's kind: a WSL host is a distro on this
computer, so it points at its reconnect instead of the Tailscale advice for network servers.

* test(wsl): parse the terminal list removal reads, and log the e2e fake's connects to a file

* fix(wsl): close a removed host's terminals by handle and report stopped only on proof

Removal stopped terminals per workspace, so one orphan whose project was gone threw
selector_not_found and aborted before orcad was stopped. It now closes each terminal by handle,
keeps going past failures and names them, and still asks orcad to stop.

It reports stopped only when the census shows no session left, the daemon retired, and the
orcad the distro records as active is the one this computer was connected to; a re-add that
adopted an orcad the record does not name is reported instead of claimed stopped.

* feat(wsl): close WSL hosts behind an internal-only gate in every build

WSL distros as hosts must not be reachable by users until moving a project
between hosts is lossless and the feature matches today's WSL support.
ORCA_INTERNAL_WSL_HOSTS=1 opens the gate; otherwise main creates no WSL host
service (no holder adoption, wsl.exe spawn or reconnect), refuses add,
connect, remove and every runtime call to a WSL host, keeps persisted WSL
hosts out of the server list, startup status probes and AI vault scans while
leaving them on disk, and the preload exposes no WSL host API.

* fix(wsl): keep SSH and paired servers listed whatever the WSL deployment file holds

An unreadable WSL record no longer hides an SSH-linked server, and with the internal gate closed a corrupt WSL file is warned about instead of failing the whole registry.

* fix(wsl): let an unreadable WSL record hide only a loopback pairing

A WSL host always pairs over a loopback endpoint, so a stale record can no longer remove a remote paired server from the list.

* fix(wsl): ignore unreadable WSL deployment state while the internal gate is closed

A newer or stale record could otherwise hide a re-paired loopback server for users who never open the gate.
2026-10-13 08:18:08 -07:00

156 lines
6.0 KiB
TypeScript

import { writeSecureJsonFileWithinLimit } from './bounded-secure-json-file'
import { JsonStringifyByteLimitError } from './node-bounded-json-stringify'
import {
RuntimeEnvironmentStoreSchema,
type KnownRuntimeEnvironment,
type RuntimeEnvironmentStore
} from './runtime-environments'
import {
overlayRuntimeEnvironmentSidecar,
readRuntimeEnvironmentSidecar,
RuntimeEnvironmentSidecarInvalidError
} from './runtime-environment-sidecar'
import {
getEnvironmentStorePath,
MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES,
readEnvironmentStoreRecords,
RuntimeEnvironmentStoreError,
warnUnreadableEnvironmentState
} from './runtime-environment-store-records'
import {
overlayWslHostDeployments,
readWslHostDeployments,
WslHostDeploymentStoreInvalidError
} from './wsl-host-deployment-store'
import { isWslHostsInternalGateOpen } from './wsl-host-internal-gate'
export {
getEnvironmentStorePath,
MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES,
RuntimeEnvironmentStoreError,
type RuntimeEnvironmentStoreErrorCode
} from './runtime-environment-store-records'
/**
* The orca-environments.json records this build can read. Unreadable ones (corrupt, or written by
* a newer build) are left out here and carried through every write by writeEnvironmentStore.
*/
export function readPersistedEnvironmentStore(
userDataPath: string,
options: { requireStoreFile?: boolean } = {}
): RuntimeEnvironmentStore {
const { environments, unreadable } = readEnvironmentStoreRecords(userDataPath, options)
if (unreadable.length > 0) {
warnUnreadableEnvironmentState(
`Skipping ${unreadable.length} unreadable server record(s) in ${getEnvironmentStorePath(userDataPath)} (ids: ${unreadable.map((record) => record.id ?? '<none>').join(', ')}); they may need a newer version of Orca and are kept on disk.`
)
}
return {
version: 1,
environments: environments.sort((a, b) => a.name.localeCompare(b.name))
}
}
/** Persisted environments with their sidecar state overlaid; stale sidecar entries are ignored. */
/**
* Only an open internal gate fails closed on WSL state this build cannot read (a corrupt file, a
* newer record). Closed, that state is ignored, so it can never hide an SSH or paired server.
*/
function readWslHostDeploymentsForRegistry(
userDataPath: string
): ReturnType<typeof readWslHostDeployments> {
const gateOpen = isWslHostsInternalGateOpen(process.env)
try {
const read = readWslHostDeployments(userDataPath)
return gateOpen ? read : { deployments: read.deployments, unreadableEnvironmentIds: new Set() }
} catch (error) {
if (!(error instanceof WslHostDeploymentStoreInvalidError) || gateOpen) {
throw error
}
warnUnreadableEnvironmentState(error.message)
return { deployments: [], unreadableEnvironmentIds: new Set() }
}
}
export function readEnvironmentStore(
userDataPath: string,
options: { requireStoreFile?: boolean } = {}
): {
version: 1
environments: KnownRuntimeEnvironment[]
} {
const store = readPersistedEnvironmentStore(userDataPath, options)
let sidecar: ReturnType<typeof readRuntimeEnvironmentSidecar>
let wslDeployments: ReturnType<typeof readWslHostDeployments>
try {
sidecar = readRuntimeEnvironmentSidecar(userDataPath)
wslDeployments = readWslHostDeploymentsForRegistry(userDataPath)
} catch (error) {
// Fail closed like the main file: a link we cannot read may pin a host key we must not drop.
if (
error instanceof RuntimeEnvironmentSidecarInvalidError ||
error instanceof WslHostDeploymentStoreInvalidError
) {
throw new RuntimeEnvironmentStoreError('runtime_error', error.message)
}
throw error
}
// Why hide rather than overlay nothing: the unreadable entry may hold this server's SSH pin or
// deployment ownership, and connecting or editing without it would silently drop that.
const isHidden = (id: string): boolean => Object.hasOwn(sidecar.unreadable, id)
const hidden = store.environments.filter((environment) => isHidden(environment.id))
if (hidden.length > 0) {
warnUnreadableEnvironmentState(
`Hiding ${hidden.length} server(s) whose links cannot be read (ids: ${hidden.map((environment) => environment.id).join(', ')}); they may need a newer version of Orca.`
)
}
return {
version: 1,
environments: overlayWslHostDeployments(
store.environments
.filter((environment) => !isHidden(environment.id))
.map((environment) =>
overlayRuntimeEnvironmentSidecar(environment, sidecar.entries[environment.id])
),
wslDeployments
)
}
}
/**
* Writes only persisted fields; sidecar state is written by the sidecar module. Records on disk
* this build cannot read are appended verbatim, in their original order.
*/
export function writeEnvironmentStore(userDataPath: string, store: RuntimeEnvironmentStore): void {
const path = getEnvironmentStorePath(userDataPath)
const environments = RuntimeEnvironmentStoreSchema.parse(store).environments
const onDisk = readEnvironmentStoreRecords(userDataPath)
const readableIds = new Set(onDisk.environments.map((environment) => environment.id))
const unreadableIds = new Set(onDisk.unreadable.map((record) => record.id))
// A new readable record must not shadow one a newer build owns under the same id.
if (environments.some(({ id }) => unreadableIds.has(id) && !readableIds.has(id))) {
throw new RuntimeEnvironmentStoreError(
'invalid_argument',
'A server with this id already exists in a format that needs a newer version of Orca.'
)
}
try {
writeSecureJsonFileWithinLimit(
path,
{
version: 1,
environments: [...environments, ...onDisk.unreadable.map((record) => record.raw)]
},
MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES
)
} catch (error) {
if (error instanceof JsonStringifyByteLimitError) {
throw new RuntimeEnvironmentStoreError(
'runtime_error',
`Could not write Orca environments at ${path}; the store exceeds its durable capacity.`
)
}
throw error
}
}