Files
orca/src/shared/runtime-session-contracts.ts
T
Neil 5631aa00dd feat(orcad): items 2–7 — degradation, natives, daemon, ops, deploy (#16398)
* fix(ports): stop joining an undefined resourcesPath on a non-Electron host

`resolveWorkerEntryPath` branched on `isPackaged` alone and joined
`process.resourcesPath`. orcad reports `isPackaged` true — correctly, it is a
production build, and ~15 consumers read it that way to gate HTTPS-only skill
downloads and the real CLI name — but `process.resourcesPath` is Electron-only
and `undefined` under plain Node.

So the packaged branch threw
`TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string`
where a clean "worker unavailable" was the honest outcome. The type said
`resourcesPath: string`, which is how it went unnoticed; it is now
`string | undefined`, so the compiler carries the fact.

A host with no Electron resources tree has no asar to look in, so it falls back
to the module directory and lets the caller report a missing worker.

Found by the item 1 agent while auditing the same `isPackaged` defect class in
the watcher. Verified in both directions: reverting the guard reproduces the
TypeError.

* feat(orcad): prove node-pty loads before anything requires it

Of the two ways node-pty fails, only one is catchable. A missing module throws
MODULE_NOT_FOUND. A module built against the wrong libc or Node ABI is refused by
the dynamic loader, and in the worst case takes the process down before any handler
exists — that is #9902, which crashed the desktop app on Ubuntu 20.04 before a
window appeared. There was no libc or ABI precondition anywhere in the tree.

So orcad now proves the load in a CHILD process, from main.ts, before anything
requires node-pty. Whatever the child does — throw, abort, die on a signal — is data
rather than our own death, and the operator gets a sentence naming the host's libc,
Node ABI and prebuild slot plus the command to run. Proven-unloadable exits 78
(EX_CONFIG), so a supervisor does not restart an unequippable host forever. A probe
that never answered is unverifiable, not blocked: refusing to boot on an inconclusive
signal would take down hosts that work.

The child dlopens the file node-pty would have chosen, before requiring the package.
node-pty's loader walks several directories and rethrows only the LAST error, so a
refused binary reads as "Cannot find module ./prebuilds/..." — which sends the
operator to install a module that is already there. It also reports through stdout:
node echoes the whole -e source above a stack trace, and matching tokens against
stderr made the probe's own source text answer for the verdict.

Verdicts reach clients as a terminal_unavailable degradation alongside the existing
browser_unavailable one, through the same cause-registry shape. degradations[].code
is now an open vocabulary; clients already render only `message`.

Prebuilds are compiled from PATCHED sources — the patch IS the glibc-floor fix, so an
upstream tarball reproduces #9902 — into linux-{x64,arm64}-{glibc,musl} and
darwin-{x64,arm64} slots. libc is in the slot name because node-pty's loader falls
back to prebuilds/<platform>-<arch> and cannot tell glibc from musl. orcad installs
the matching slot at boot, so a host with no compiler serves terminals.

The relay's five pure toolchain-diagnosis functions moved to a transport-free module
so the Node bundle can reuse them without dragging ssh2 in behind them; the relay
keeps its API by re-export. macOS gets `xcode-select --install` rather than the
cross-distro apt/dnf/pacman/apk menu, every line of which is wrong there.

* test(orcad): pin the node-pty precondition to ground truth, not a prepared host

CI's test shard runs `vitest` directly, so `ensure-native-runtime --runtime=node`
never prepares node-pty for the Node ABI — `degraded` is the correct verdict
there, and asserting 'ok' encoded an environment the shard does not have.

Asserting whatever it returned would be vacuous, so the expectation is now
derived from an independent require() of node-pty. Verified it still bites:
forcing the precondition to always report 'ok' fails the suite.

* feat(orcad): run the terminal daemon, and the ops contract around it

orcad declared `canRecoverPersistentLocalPtys: () => false` because it did not
run the terminal daemon, so every restart, update and rollback SIGKILLed every
running terminal — on the host whose selling point is that work survives the
client going away. That is the one property `ssh-execution-boundary.md`
recommends the peer model for.

Item 4 — the daemon:

- Port the launch path off electron: `daemon-init.ts`,
  `daemon-host-relocation.ts` and `observability/logs-directory.ts` now read
  the `AppEnvironment` port. Relocation additionally asks whether the app root
  is an asar archive rather than whether the build is packaged, so a Node host
  answering `isPackaged() === true` no longer walks into an Electron-only
  NSIS-escape path (same precedent as `parcel-watcher-entry-path.ts`).
- `build-orcad.mjs` emits `daemon-entry.js` beside `orcad.js`, scans the
  forked children's metafiles for electron/node:sqlite, and load-checks the
  child under plain Node.
- orcad spawns and adopts the daemon; shutdown disconnects and never kills it.
  `canRecoverPersistentLocalPtys` now reads the live provider and is false
  under degraded routing, where fresh terminals would die with the process.

Item 3 — the ops contract (docs/reference/orcad-operations.md):

- Bind policy: `--bind`, default loopback, pinned so neither `orca serve`'s
  wide default nor the connected-device widen can override it, and so a paired
  client cannot rebind the listener from outside.
- Instance lock on the data root before profile load, scoped to the runtime
  role so it never refuses a restart that a live daemon makes worthwhile.
- Supervision: exit codes a supervisor can act on (78 = do not retry),
  second-signal escalation, a shutdown deadline, and crash-loop containment on
  daemon respawn.
- Health in the readiness payload: build hash, Node ABI, and a PTY self-test
  that spans both processes — the daemon spawns a real PTY in its own process
  and the verdict crosses its socket.

Both bundle load-checks now assert on exit codes: these bundles are minified
onto one line, so Node's uncaught-exception report echoes every string literal
in the bundle and the previous message match passed against a bundle that
never loaded.

* feat(orcad): deploy, activate and roll back a versioned orcad install

Plan items 6 and 7 from docs/design/shipping-orcad.html.

Install reuses the relay's transaction verbatim — per-version lock, staged
SFTP write, .install-complete sentinel, stale-lock recovery — under a
parameterized namespace, so orcad-<v>/ sits beside relay-<v>/ permanently
(§06). Parameterizing GC is the trap that creates: each model now collects
only its own directories, enforced twice (prefix-scoped remote listing plus
a local ownership re-check), and a client picks its model from how the host
is registered, never from what it finds on disk.

Activation is separate from installation, because a versioned directory
selects nothing. A candidate is launched, publishes orca_server_ready, and
only becomes active if its cross-process health payload passes: right build
hash, listening, daemon live, PTY self-test green. A rejected candidate is
stopped and the incumbent restarted, so a careful deploy cannot cause the
outage it was being careful about.

Update and rollback are shaped by the daemon. An update restarts orcad, the
daemon outlives it, and the surviving daemon was forked from the outgoing
bundle — so live terminals defer the update rather than proceed, and GC pins
the active version, the rollback target and the live daemon's bundle. Orca's
persisted state carries no schema version, so rollback restores a
pre-activation snapshot rather than trusting backward-readability; the point
past which it is unsafe is the first terminal created after activation,
which the snapshot cannot describe and the surviving daemon still owns.

Running the generated shell for real found two bugs the text assertions
missed: tar members re-quoted inside a shell variable captured nothing, and
kill -0 reports a zombie as alive.

* test(orcad): assert the precondition is self-consistent, not environment-shaped

The real-host case cannot predict a status: CI's shard runs vitest directly, so
node-pty is never built for the Node ABI and 'degraded' is correct there, while a
prepared checkout gives 'ok'.

The previous attempt used require('node-pty') as ground truth, which resolves the
JS wrapper while the native binding loads lazily — it proved strictly less than
the precondition checks, and failed CI for exactly that reason.

What is invariant on a host with node-pty installed: never 'blocked', and never a
degraded verdict carrying an unestablished reason. The injected-input tests keep
the logic coverage.

* fix(orcad): drop an eslint-disable the rule no longer needs

* test(orcad): separate slot placement from the load verdict

Both remaining CI failures were the same shape: tests reaching into node_modules
for a pty.node that only exists after `ensure-native-runtime --runtime=node`,
which CI's shard never runs because it invokes vitest directly.

Slot *placement* is the logic worth checking on every host, so it now uses a
synthetic payload and asserts the verdict stays honest about not loading. The
three assertions that genuinely need a Node-ABI binding are gated on it existing.

Verified: breaking slot installation fails both placement tests; with the real
pty.node hidden the file is 17 passed / 3 skipped instead of ENOENT.

* test(orcad): gate the load-dependent cases on a real load, not on the file existing

CI ships a pty.node built for Electron's ABI, so existsSync was true while require
still failed — the gate ran exactly the tests that host can never satisfy. It now
probes the binding in a child process, so a bad one cannot take the runner down.

The self-consistency assertion also allowed too little: 'blocked' is the honest
verdict for a corrupt binding, alongside 'ok' on a prepared host and 'degraded' on
an unprepared one. What stays invariant is that anything other than 'ok' names an
established cause, so a terminal is never declined for a reason nobody worked out.

Verified against all three host states: prepared (19 passed), unprepared, and a
corrupt binding (17 passed / 3 skipped, no failures).

* test(orcad): gate on the whole premise — binding AND spawn-helper

CI has a loadable pty.node but no spawn-helper, and a slot without the helper is
legitimately 'degraded'. So the previous gate let a test run whose premise ('a
complete slot yields ok') that host cannot satisfy.

Verified in both states: with the helper present 19 pass; with it removed the
load-dependent cases skip (17 passed / 3 skipped) instead of failing.

* fix(orcad): preserve degradation types after rebase
2026-08-27 00:18:51 -07:00

351 lines
11 KiB
TypeScript

import type { AgentStatusEntry, AgentStatusOrchestrationContext } from './agent-status-types'
import type { BrowserCertificateFailure, BrowserLoadError } from './browser-workspace-types'
import type { RemoteServerUpdateSupport } from './remote-server-update'
import type { RemoteRuntimeSharedConnectionDiagnostics } from './remote-runtime-shared-control-types'
import type { RuntimeBrowserPlacement } from './runtime-browser-placement'
import type { RuntimeCapability } from './protocol-version'
import type {
RuntimeBrowserUnavailableReason,
RuntimeDegradation
} from './runtime-capability-degradation'
import type { TabGroupLayoutNode } from './tab-types'
import type { TerminalColorOverrides } from './terminal-color-overrides'
import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode } from './terminal-tab-types'
import type { TuiAgent } from './tui-agent'
export type RuntimeGraphStatus = 'ready' | 'reloading' | 'unavailable'
export type RuntimeDesktopWindowStatus = 'available' | 'openable' | 'initializing' | 'blocked'
export const HEADLESS_RUNTIME_WINDOW_ID = 0
export type DeviceScope = 'mobile' | 'runtime'
export type RuntimeTerminalDriverState =
| { kind: 'idle' }
| { kind: 'desktop' }
| { kind: 'mobile'; clientId: string }
export type RuntimeBrowserDriverState = RuntimeTerminalDriverState
export const BROWSER_UNAVAILABLE_ERROR_CODE = 'browser_unavailable' as const
// Why: one sentence per cause, each naming the thing the operator can change. The host
// renders these so an older client still shows an accurate reason it cannot decode.
const BROWSER_UNAVAILABLE_MESSAGES: Record<RuntimeBrowserUnavailableReason, string> = {
unconfigured:
'Browser automation has no backend on this host. Install the Orca desktop app, or set ORCA_BROWSER_EXECUTABLE to a Chromium executable.',
driver_missing:
'ORCA_BROWSER_EXECUTABLE is set, but the bundled agent-browser driver is missing or not executable on this host, so Chromium cannot be driven.',
executable_not_found: 'ORCA_BROWSER_EXECUTABLE points at a path that does not exist.',
executable_not_executable:
'ORCA_BROWSER_EXECUTABLE points at a file that is not executable by this host.',
electron_start_failed: 'The installed Electron browser provider failed to start.',
chromium_start_failed:
'The Chromium browser provider named by ORCA_BROWSER_EXECUTABLE failed to start.',
provider_unhealthy: 'The browser provider started but is no longer answering health checks.',
desktop_window_unavailable:
'Browser automation on this host needs a desktop window, and none is available.',
unknown: 'Browser automation is unavailable on this host, and the cause could not be determined.'
}
export function browserUnavailableMessage(
reason: RuntimeBrowserUnavailableReason,
detail?: string
): string {
const base = BROWSER_UNAVAILABLE_MESSAGES[reason]
return detail ? `${base} (${detail})` : base
}
export type RuntimeStatus = {
runtimeId: string
/** Authenticated requester identity. Missing for in-process callers and older hosts. */
pairedDeviceId?: string
rendererGraphEpoch: number
graphStatus: RuntimeGraphStatus
authoritativeWindowId: number | null
desktopWindowStatus?: RuntimeDesktopWindowStatus
liveTabCount: number
liveLeafCount: number
runtimeProtocolVersion?: number
minCompatibleRuntimeClientVersion?: number
capabilities?: RuntimeCapability[]
/**
* Optional for mixed-version peers. Absence means the host predates structured
* degradation reporting, not that the host proved every optional feature available.
*/
degradations?: RuntimeDegradation[]
appVersion?: string
remoteUpdateSupport?: RemoteServerUpdateSupport
remoteControl?: RemoteRuntimeSharedConnectionDiagnostics | null
hostPlatform?: NodeJS.Platform
terminalWindowsShell?: string | null
deviceScope?: DeviceScope
floatingWorkspaceEnabled?: boolean
// COMPAT(runtimeStatusMobileAliases): added 2026-05-15 for older mobile builds.
protocolVersion?: number
minCompatibleMobileVersion?: number
}
export type CliRuntimeState =
| 'not_running'
| 'starting'
| 'ready'
| 'graph_not_ready'
| 'stale_bootstrap'
export type CliStatusResult = {
target?: { kind: 'local' } | { kind: 'environment'; environment: string }
app: {
running: boolean
pid: number | null
desktopWindowStatus?: RuntimeDesktopWindowStatus
}
runtime: {
state: CliRuntimeState
reachable: boolean
runtimeId: string | null
appVersion?: string
remoteUpdateSupport?: RemoteServerUpdateSupport
capabilities?: RuntimeCapability[]
degradations?: RuntimeDegradation[]
}
graph: {
state: RuntimeGraphStatus | 'not_running' | 'starting'
}
}
export type RuntimeSyncedTab = {
tabId: string
worktreeId: string
title: string | null
activeLeafId: string | null
layout: TerminalPaneLayoutNode | null
}
export type RuntimeSyncedLeaf = {
tabId: string
worktreeId: string
leafId: string
paneRuntimeId: number
ptyId: string | null
paneTitle?: string | null
title?: string | null
}
export type RuntimeSyncWindowGraph = {
tabs: RuntimeSyncedTab[]
leaves: RuntimeSyncedLeaf[]
mobileSessionTabs?: RuntimeMobileSessionTabsSnapshot[]
unchangedMobileSessionWorktrees?: string[]
}
export type RuntimeRendererSyncWindowGraph = RuntimeSyncWindowGraph & {
rendererGeneration: string
}
export type RuntimeNativeChatLaunchDraftResolution = {
tabId: string
text: string
createdAt: number
}
export type RuntimeSyncWindowGraphResult = RuntimeStatus & {
agentOrchestrationByPaneKey?: Record<string, AgentStatusOrchestrationContext>
nativeChatLaunchDraftResolutions?: RuntimeNativeChatLaunchDraftResolution[]
mobileSessionResyncWorktrees?: string[]
}
export type RuntimeMobileSessionTerminalTab = {
type: 'terminal'
id: string
title: string
quickCommandLabel?: string | null
parentTabId: string
leafId: string
ptyId?: string | null
terminalTheme?: RuntimeMobileTerminalTheme
agentStatus?: AgentStatusEntry | null
/** Event-only lead-turn end time for paired clients; never persisted in AgentStatusEntry. */
turnCompletedAt?: number
launchAgent?: TuiAgent
startupCwd?: string
parentLayout?: TerminalLayoutSnapshot
color?: string | null
isPinned?: boolean
viewMode?: 'terminal' | 'chat'
launchDraft?: string
launchDraftCreatedAt?: number
isActive: boolean
}
export type RuntimeMobileTerminalTheme = {
mode: 'dark' | 'light'
theme: TerminalColorOverrides
}
export type RuntimeMobileSessionMarkdownTab = {
type: 'markdown'
id: string
title: string
filePath: string
relativePath: string
language: 'markdown'
mode: 'edit' | 'markdown-preview'
isDirty: boolean
isActive: boolean
sourceFileId: string
sourceFilePath: string
sourceRelativePath: string
documentVersion: string
color?: string | null
isPinned?: boolean
}
export type RuntimeMobileSessionFileTab = {
type: 'file'
id: string
title: string
filePath: string
relativePath: string
language: string
mode?: 'edit' | 'diff'
diffSource?: 'staged' | 'unstaged'
isDirty: boolean
color?: string | null
isPinned?: boolean
isActive: boolean
}
export type RuntimeMobileSessionBrowserTab = {
type: 'browser'
id: string
title: string
browserWorkspaceId: string
browserPageId: string | null
browserProfileId?: string
executionHostKey?: string
placement?: RuntimeBrowserPlacement
url: string
loading: boolean
canGoBack: boolean
canGoForward: boolean
loadError?: BrowserLoadError | null
certificateFailure?: BrowserCertificateFailure | null
color?: string | null
isPinned?: boolean
isActive: boolean
}
export type RuntimeMobileSessionSnapshotTab =
| RuntimeMobileSessionTerminalTab
| RuntimeMobileSessionMarkdownTab
| RuntimeMobileSessionFileTab
| RuntimeMobileSessionBrowserTab
export type RuntimeMobileSessionTerminalClientTab =
| (RuntimeMobileSessionTerminalTab & { status: 'pending-handle'; terminal: null })
| (RuntimeMobileSessionTerminalTab & { status: 'ready'; terminal: string })
export type RuntimeMobileSessionClientTab =
| RuntimeMobileSessionTerminalClientTab
| RuntimeMobileSessionMarkdownTab
| RuntimeMobileSessionFileTab
| RuntimeMobileSessionBrowserTab
export type RuntimeMobileSessionTabGroup = {
id: string
activeTabId: string | null
tabOrder: string[]
recentTabIds?: string[]
}
type RuntimeMobileSessionTabMoveBase = {
tabId: string
targetGroupId: string
}
export type RuntimeMobileSessionTabMove =
| (RuntimeMobileSessionTabMoveBase & { kind: 'reorder'; tabOrder: string[] })
| (RuntimeMobileSessionTabMoveBase & { kind: 'move-to-group'; index?: number })
| (RuntimeMobileSessionTabMoveBase & {
kind: 'split'
splitDirection: 'left' | 'right' | 'up' | 'down'
})
export type RuntimeMobileSessionTabMoveResult = { moved: true }
export type RuntimeMobileSessionTabCloseResult = {
closed: true
refused?: true
refusalReason?:
| 'missing-intent'
| 'stale-publication'
| 'stale-terminal'
| 'live-host-pty'
| 'unknown-liveness'
| 'retirement-owner'
snapshotRepublished?: true
}
export type RuntimeSessionTabCloseReason = 'user' | 'pty-exit' | 'cleanup'
/**
* The publication epoch a runtime answers with for a worktree it has published nothing for yet —
* the state every worktree is in for a moment after the host process restarts.
*
* Paired with `snapshotVersion: 0` it marks a synthesized placeholder, not a host answer: the
* runtime is saying "ask me later", not "those tabs are gone". Clients must not read absence from
* such a frame as evidence a tab was closed.
*/
export const UNPUBLISHED_WORKTREE_PUBLICATION_EPOCH = 'none'
export type RuntimeMobileSessionTabsSnapshot = {
worktree: string
publicationEpoch: string
snapshotVersion: number
activeGroupId: string | null
activeTabId: string | null
activeTabType: 'terminal' | 'markdown' | 'file' | 'browser' | null
tabGroups?: RuntimeMobileSessionTabGroup[]
tabGroupLayout?: TabGroupLayoutNode | null
tabs: RuntimeMobileSessionSnapshotTab[]
}
export type RuntimeMobileSessionTabsResult = {
worktree: string
publicationEpoch: string
snapshotVersion: number
navigationIntent?: 'follow'
activeGroupId: string | null
activeTabId: string | null
activeTabType: 'terminal' | 'markdown' | 'file' | 'browser' | null
tabGroups?: RuntimeMobileSessionTabGroup[]
tabGroupLayout?: TabGroupLayoutNode | null
tabs: RuntimeMobileSessionClientTab[]
/**
* Set while a freshly started runtime has not yet taken back the client-hosted pages its paired
* hosts are still holding. Such a snapshot is authoritative about terminals, which it rehydrated
* from disk, but silently empty of browser rows it has simply not heard about yet — so a client
* must not read the absence of its own client-hosted rows here as "the host closed them".
*
* Always bounded: the runtime clears it once a host attaches, and drops it on a deadline so a
* host that never returns cannot hold rows open forever.
*/
clientHostedPagesUnreconciled?: true
}
export type RuntimeMobileSessionCreateTerminalResult = {
tab: RuntimeMobileSessionTerminalClientTab
publicationEpoch: string
snapshotVersion: number
}
export type RuntimeMobileSessionTabsRemovedResult = RuntimeMobileSessionTabsResult & {
removed: true
activeGroupId: null
activeTabId: null
activeTabType: null
tabs: []
}