Refactor runtime app architecture (#1878)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
+133
-4
@@ -1,9 +1,17 @@
|
||||
import type { CliStatusResult } from '../../shared/runtime-types'
|
||||
import type { CliStatusResult, RuntimeStatus } from '../../shared/runtime-types'
|
||||
import { parsePairingCode, type PairingOffer } from '../../shared/pairing'
|
||||
import { launchOrcaApp } from './launch'
|
||||
import { getDefaultUserDataPath, readMetadata } from './metadata'
|
||||
import { getCliStatus } from './status'
|
||||
import { sendRequest } from './transport'
|
||||
import { RuntimeClientError, RuntimeRpcFailureError, type RuntimeRpcSuccess } from './types'
|
||||
import { sendWebSocketRequest } from './websocket-transport'
|
||||
import { markEnvironmentUsed, resolveEnvironmentPairingOffer } from './environments'
|
||||
import { describeRuntimeCompatBlock, evaluateRuntimeCompat } from '../../shared/protocol-compat'
|
||||
import {
|
||||
MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
RUNTIME_PROTOCOL_VERSION
|
||||
} from '../../shared/protocol-version'
|
||||
|
||||
// Why: for `orchestration.check --wait` the caller's method-level
|
||||
// `params.timeoutMs` is the inner waiter budget; we extend the client-side
|
||||
@@ -16,13 +24,27 @@ const LONG_POLL_CLIENT_GRACE_MS = 10_000
|
||||
export class RuntimeClient {
|
||||
private readonly userDataPath: string
|
||||
private readonly requestTimeoutMs: number
|
||||
private readonly remotePairing: PairingOffer | null
|
||||
private readonly environmentSelector: string | null
|
||||
private remoteCompatChecked = false
|
||||
|
||||
// Why: browser commands trigger first-time session init (agent-browser connect +
|
||||
// CDP proxy setup) which can take 15-30s. 60s accommodates cold start without
|
||||
// being so large that genuine hangs go unnoticed.
|
||||
constructor(userDataPath = getDefaultUserDataPath(), requestTimeoutMs = 60_000) {
|
||||
constructor(
|
||||
userDataPath = getDefaultUserDataPath(),
|
||||
requestTimeoutMs = 60_000,
|
||||
remotePairingCode = process.env.ORCA_PAIRING_CODE ?? process.env.ORCA_REMOTE_PAIRING ?? null,
|
||||
environmentSelector = process.env.ORCA_ENVIRONMENT ?? null
|
||||
) {
|
||||
this.userDataPath = userDataPath
|
||||
this.requestTimeoutMs = requestTimeoutMs
|
||||
this.environmentSelector = environmentSelector
|
||||
this.remotePairing = resolveRemotePairing(userDataPath, remotePairingCode, environmentSelector)
|
||||
}
|
||||
|
||||
get isRemote(): boolean {
|
||||
return this.remotePairing !== null
|
||||
}
|
||||
|
||||
async call<TResult>(
|
||||
@@ -32,10 +54,30 @@ export class RuntimeClient {
|
||||
timeoutMs?: number
|
||||
}
|
||||
): Promise<RuntimeRpcSuccess<TResult>> {
|
||||
const metadata = readMetadata(this.userDataPath)
|
||||
const effectiveTimeoutMs = options?.timeoutMs ?? this.resolveMethodTimeoutMs(method, params)
|
||||
if (this.remotePairing) {
|
||||
if (method !== 'status.get') {
|
||||
await this.ensureRemoteRuntimeCompatible(effectiveTimeoutMs)
|
||||
}
|
||||
const response = await sendWebSocketRequest<TResult>(
|
||||
this.remotePairing,
|
||||
method,
|
||||
params,
|
||||
effectiveTimeoutMs
|
||||
)
|
||||
if (response.ok === false) {
|
||||
throw new RuntimeRpcFailureError(response)
|
||||
}
|
||||
if (this.environmentSelector) {
|
||||
markEnvironmentUsed(this.userDataPath, this.environmentSelector, {
|
||||
runtimeId: response._meta.runtimeId
|
||||
})
|
||||
}
|
||||
return response
|
||||
}
|
||||
const metadata = readMetadata(this.userDataPath)
|
||||
const response = await sendRequest<TResult>(metadata, method, params, effectiveTimeoutMs)
|
||||
if (!response.ok) {
|
||||
if (response.ok === false) {
|
||||
throw new RuntimeRpcFailureError(response)
|
||||
}
|
||||
return response
|
||||
@@ -58,9 +100,69 @@ export class RuntimeClient {
|
||||
}
|
||||
|
||||
async getCliStatus(): Promise<RuntimeRpcSuccess<CliStatusResult>> {
|
||||
if (this.remotePairing) {
|
||||
const response = await this.call<RuntimeStatus>('status.get')
|
||||
this.assertRemoteRuntimeStatusCompatible(response.result)
|
||||
this.remoteCompatChecked = true
|
||||
const graphState = response.result.graphStatus
|
||||
return {
|
||||
id: response.id,
|
||||
ok: true,
|
||||
result: {
|
||||
app: {
|
||||
running: true,
|
||||
pid: null
|
||||
},
|
||||
runtime: {
|
||||
state: graphState === 'ready' ? 'ready' : 'graph_not_ready',
|
||||
reachable: true,
|
||||
runtimeId: response.result.runtimeId
|
||||
},
|
||||
graph: {
|
||||
state: graphState
|
||||
}
|
||||
},
|
||||
_meta: response._meta
|
||||
}
|
||||
}
|
||||
return getCliStatus(this.userDataPath)
|
||||
}
|
||||
|
||||
private async ensureRemoteRuntimeCompatible(timeoutMs: number): Promise<void> {
|
||||
if (!this.remotePairing || this.remoteCompatChecked) {
|
||||
return
|
||||
}
|
||||
const response = await sendWebSocketRequest<RuntimeStatus>(
|
||||
this.remotePairing,
|
||||
'status.get',
|
||||
undefined,
|
||||
timeoutMs
|
||||
)
|
||||
if (response.ok === false) {
|
||||
throw new RuntimeRpcFailureError(response)
|
||||
}
|
||||
this.assertRemoteRuntimeStatusCompatible(response.result)
|
||||
this.remoteCompatChecked = true
|
||||
if (this.environmentSelector) {
|
||||
markEnvironmentUsed(this.userDataPath, this.environmentSelector, {
|
||||
runtimeId: response._meta.runtimeId
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private assertRemoteRuntimeStatusCompatible(status: RuntimeStatus): void {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
serverProtocolVersion: status.runtimeProtocolVersion ?? status.protocolVersion,
|
||||
serverMinCompatibleClientProtocolVersion:
|
||||
status.minCompatibleRuntimeClientVersion ?? status.minCompatibleMobileVersion
|
||||
})
|
||||
if (verdict.kind === 'blocked') {
|
||||
throw new RuntimeClientError('incompatible_runtime', describeRuntimeCompatBlock(verdict))
|
||||
}
|
||||
}
|
||||
|
||||
async openOrca(timeoutMs = 15_000): Promise<RuntimeRpcSuccess<CliStatusResult>> {
|
||||
const initial = await this.getCliStatus()
|
||||
if (initial.result.runtime.reachable) {
|
||||
@@ -84,6 +186,33 @@ export class RuntimeClient {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveRemotePairing(
|
||||
userDataPath: string,
|
||||
pairingCode: string | null,
|
||||
environmentSelector: string | null
|
||||
): PairingOffer | null {
|
||||
if (pairingCode && environmentSelector) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Use either --pairing-code or --environment, not both.'
|
||||
)
|
||||
}
|
||||
if (environmentSelector) {
|
||||
return resolveEnvironmentPairingOffer(userDataPath, environmentSelector)
|
||||
}
|
||||
if (!pairingCode) {
|
||||
return null
|
||||
}
|
||||
const pairing = parsePairingCode(pairingCode)
|
||||
if (!pairing) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Invalid remote pairing code. Expected an orca://pair#... URL or bare pairing payload.'
|
||||
)
|
||||
}
|
||||
return pairing
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
@@ -1,62 +1,5 @@
|
||||
// Why: the Orca runtime is a separate process and may drift in version from
|
||||
// the CLI (older CLI talking to newer app, or vice versa during dev HMR). A
|
||||
// Zod schema at the decode boundary means a malformed frame surfaces as a
|
||||
// single legible error instead of a silent mis-typed access downstream.
|
||||
//
|
||||
// The envelope shape mirrors src/main/runtime/rpc/core.ts. `result` is left
|
||||
// unknown here — method-level types are checked by the caller via generics —
|
||||
// so only the frame is validated, not the payload.
|
||||
import { z } from 'zod'
|
||||
|
||||
const MetaSuccess = z.object({
|
||||
runtimeId: z.string()
|
||||
})
|
||||
|
||||
const MetaFailure = z
|
||||
.object({
|
||||
runtimeId: z.union([z.string(), z.null()])
|
||||
})
|
||||
.optional()
|
||||
|
||||
const Success = z.object({
|
||||
id: z.string(),
|
||||
ok: z.literal(true),
|
||||
result: z.unknown(),
|
||||
_meta: MetaSuccess
|
||||
})
|
||||
|
||||
const Failure = z.object({
|
||||
id: z.string(),
|
||||
ok: z.literal(false),
|
||||
error: z.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
data: z.unknown().optional()
|
||||
}),
|
||||
_meta: MetaFailure
|
||||
})
|
||||
|
||||
// Why: transport-layer keepalive frame (server→client only). Not a terminal
|
||||
// frame — the client reads past it and keeps waiting for the real
|
||||
// success/failure. `id` and `_meta` are deliberately absent: keepalives carry
|
||||
// no method-level semantics and aren't tied to a particular request (one
|
||||
// connection handles one request today). See design doc §3.1.
|
||||
const Keepalive = z.object({
|
||||
_keepalive: z.literal(true)
|
||||
})
|
||||
|
||||
// Why: switched from z.discriminatedUnion('ok', …) to z.union because
|
||||
// keepalives have no `ok` field. Client code must branch on
|
||||
// `'_keepalive' in frame` before treating the frame as Success/Failure.
|
||||
export const RuntimeRpcEnvelopeSchema = z.union([Success, Failure, Keepalive])
|
||||
|
||||
export type RuntimeRpcKeepaliveFrame = z.infer<typeof Keepalive>
|
||||
|
||||
export function isKeepaliveFrame(frame: unknown): frame is RuntimeRpcKeepaliveFrame {
|
||||
return (
|
||||
typeof frame === 'object' &&
|
||||
frame !== null &&
|
||||
'_keepalive' in frame &&
|
||||
(frame as { _keepalive: unknown })._keepalive === true
|
||||
)
|
||||
}
|
||||
export {
|
||||
isKeepaliveFrame,
|
||||
RuntimeRpcEnvelopeSchema,
|
||||
type RuntimeRpcKeepaliveFrame
|
||||
} from '../../shared/runtime-rpc-envelope'
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { mkdtempSync, statSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { encodePairingOffer } from '../../shared/pairing'
|
||||
import {
|
||||
addEnvironmentFromPairingCode,
|
||||
getEnvironmentStorePath,
|
||||
listEnvironments,
|
||||
removeEnvironment,
|
||||
resolveEnvironmentPairingOffer
|
||||
} from './environments'
|
||||
|
||||
function pairingCode(endpoint = 'ws://127.0.0.1:6768'): string {
|
||||
return encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint,
|
||||
deviceToken: 'device-token',
|
||||
publicKeyB64: Buffer.from(new Uint8Array(32).fill(1)).toString('base64')
|
||||
})
|
||||
}
|
||||
|
||||
describe('CLI runtime environments', () => {
|
||||
it('saves, resolves, and removes a paired environment', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-env-store-'))
|
||||
const saved = addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'workstation',
|
||||
pairingCode: pairingCode(),
|
||||
now: 100
|
||||
})
|
||||
|
||||
expect(listEnvironments(userDataPath)).toHaveLength(1)
|
||||
expect(resolveEnvironmentPairingOffer(userDataPath, 'workstation')).toMatchObject({
|
||||
endpoint: 'ws://127.0.0.1:6768',
|
||||
deviceToken: 'device-token'
|
||||
})
|
||||
expect(resolveEnvironmentPairingOffer(userDataPath, saved.id)).toMatchObject({
|
||||
endpoint: 'ws://127.0.0.1:6768'
|
||||
})
|
||||
expect((statSync(getEnvironmentStorePath(userDataPath)).mode & 0o777).toString(8)).toBe('600')
|
||||
|
||||
const removed = removeEnvironment(userDataPath, 'workstation')
|
||||
expect(removed.id).toBe(saved.id)
|
||||
expect(listEnvironments(userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects an environment with the same name', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-env-store-'))
|
||||
const first = addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'workstation',
|
||||
pairingCode: pairingCode('ws://127.0.0.1:1111'),
|
||||
now: 100
|
||||
})
|
||||
|
||||
expect(() =>
|
||||
addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'workstation',
|
||||
pairingCode: pairingCode('ws://127.0.0.1:2222'),
|
||||
now: 200
|
||||
})
|
||||
).toThrow('A server named "workstation" already exists.')
|
||||
expect(listEnvironments(userDataPath)).toHaveLength(1)
|
||||
expect(resolveEnvironmentPairingOffer(userDataPath, 'workstation').endpoint).toBe(
|
||||
'ws://127.0.0.1:1111'
|
||||
)
|
||||
expect(listEnvironments(userDataPath)[0]?.id).toBe(first.id)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
addEnvironmentFromPairingCode as addEnvironmentFromPairingCodeInStore,
|
||||
getEnvironmentStorePath,
|
||||
listEnvironments,
|
||||
markEnvironmentUsed as markEnvironmentUsedInStore,
|
||||
removeEnvironment as removeEnvironmentFromStore,
|
||||
resolveEnvironment as resolveEnvironmentFromStore,
|
||||
resolveEnvironmentPairingOffer as resolveEnvironmentPairingOfferFromStore,
|
||||
RuntimeEnvironmentStoreError,
|
||||
type RuntimeEnvironmentStoreErrorCode
|
||||
} from '../../shared/runtime-environment-store'
|
||||
import type {
|
||||
KnownRuntimeEnvironment,
|
||||
PublicKnownRuntimeEnvironment
|
||||
} from '../../shared/runtime-environments'
|
||||
import type { PairingOffer } from '../../shared/pairing'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
export type EnvironmentAddResult = {
|
||||
environment: PublicKnownRuntimeEnvironment
|
||||
}
|
||||
|
||||
export type EnvironmentListResult = {
|
||||
environments: PublicKnownRuntimeEnvironment[]
|
||||
}
|
||||
|
||||
export type EnvironmentRemoveResult = {
|
||||
removed: PublicKnownRuntimeEnvironment
|
||||
}
|
||||
|
||||
export { getEnvironmentStorePath, listEnvironments }
|
||||
|
||||
export function addEnvironmentFromPairingCode(
|
||||
userDataPath: string,
|
||||
args: { name: string; pairingCode: string; now?: number }
|
||||
): KnownRuntimeEnvironment {
|
||||
return translateStoreError(() => addEnvironmentFromPairingCodeInStore(userDataPath, args))
|
||||
}
|
||||
|
||||
export function removeEnvironment(userDataPath: string, selector: string): KnownRuntimeEnvironment {
|
||||
return translateStoreError(() => removeEnvironmentFromStore(userDataPath, selector))
|
||||
}
|
||||
|
||||
export function resolveEnvironment(
|
||||
userDataPath: string,
|
||||
selector: string
|
||||
): KnownRuntimeEnvironment {
|
||||
return translateStoreError(() => resolveEnvironmentFromStore(userDataPath, selector))
|
||||
}
|
||||
|
||||
export function resolveEnvironmentPairingOffer(
|
||||
userDataPath: string,
|
||||
selector: string
|
||||
): PairingOffer {
|
||||
return translateStoreError(() => resolveEnvironmentPairingOfferFromStore(userDataPath, selector))
|
||||
}
|
||||
|
||||
export function markEnvironmentUsed(
|
||||
userDataPath: string,
|
||||
selector: string,
|
||||
args: { runtimeId?: string | null; now?: number } = {}
|
||||
): void {
|
||||
translateStoreError(() => markEnvironmentUsedInStore(userDataPath, selector, args))
|
||||
}
|
||||
|
||||
function translateStoreError<TResult>(fn: () => TResult): TResult {
|
||||
try {
|
||||
return fn()
|
||||
} catch (error) {
|
||||
if (error instanceof RuntimeEnvironmentStoreError) {
|
||||
throw new RuntimeClientError(toRuntimeClientErrorCode(error.code), error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function toRuntimeClientErrorCode(
|
||||
code: RuntimeEnvironmentStoreErrorCode
|
||||
): 'invalid_argument' | 'runtime_error' {
|
||||
return code
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export { RuntimeClient } from './client'
|
||||
export { serveOrcaApp } from './launch'
|
||||
export { getDefaultUserDataPath } from './metadata'
|
||||
export {
|
||||
RuntimeClientError,
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { resolve } from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { spawnMock } = vi.hoisted(() => ({
|
||||
spawnMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
spawn: spawnMock
|
||||
}))
|
||||
|
||||
import { serveOrcaApp } from './launch'
|
||||
|
||||
describe('serveOrcaApp', () => {
|
||||
beforeEach(() => {
|
||||
spawnMock.mockReset()
|
||||
process.env.ORCA_APP_EXECUTABLE = '/Applications/Orca.app/Contents/MacOS/Orca'
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.ORCA_APP_EXECUTABLE
|
||||
})
|
||||
|
||||
it('pins the Electron child cwd to the app root instead of the caller cwd', async () => {
|
||||
const child = {
|
||||
kill: vi.fn(),
|
||||
once: vi.fn(
|
||||
(event: string, handler: (code: number | null, signal: string | null) => void) => {
|
||||
if (event === 'exit') {
|
||||
queueMicrotask(() => handler(0, null))
|
||||
}
|
||||
return child
|
||||
}
|
||||
)
|
||||
}
|
||||
spawnMock.mockReturnValue(child)
|
||||
|
||||
await expect(serveOrcaApp({ json: true })).resolves.toBe(0)
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'/Applications/Orca.app/Contents/MacOS/Orca',
|
||||
['--serve', '--serve-json'],
|
||||
expect.objectContaining({
|
||||
cwd: resolve(__dirname, '../../..')
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('passes mobile pairing through to the foreground server child', async () => {
|
||||
const child = {
|
||||
kill: vi.fn(),
|
||||
once: vi.fn(
|
||||
(event: string, handler: (code: number | null, signal: string | null) => void) => {
|
||||
if (event === 'exit') {
|
||||
queueMicrotask(() => handler(0, null))
|
||||
}
|
||||
return child
|
||||
}
|
||||
)
|
||||
}
|
||||
spawnMock.mockReturnValue(child)
|
||||
|
||||
await expect(
|
||||
serveOrcaApp({
|
||||
json: true,
|
||||
port: '6768',
|
||||
pairingAddress: '100.64.1.20',
|
||||
mobilePairing: true
|
||||
})
|
||||
).resolves.toBe(0)
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'/Applications/Orca.app/Contents/MacOS/Orca',
|
||||
[
|
||||
'--serve',
|
||||
'--serve-json',
|
||||
'--serve-port',
|
||||
'6768',
|
||||
'--serve-pairing-address',
|
||||
'100.64.1.20',
|
||||
'--serve-mobile-pairing'
|
||||
],
|
||||
expect.objectContaining({
|
||||
cwd: resolve(__dirname, '../../..')
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawn as spawnProcess } from 'child_process'
|
||||
import { dirname } from 'path'
|
||||
import { dirname, resolve } from 'path'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
export function launchOrcaApp(): void {
|
||||
@@ -53,6 +53,93 @@ export function launchOrcaApp(): void {
|
||||
)
|
||||
}
|
||||
|
||||
export function serveOrcaApp(
|
||||
args: {
|
||||
json?: boolean
|
||||
port?: string | null
|
||||
pairingAddress?: string | null
|
||||
noPairing?: boolean
|
||||
mobilePairing?: boolean
|
||||
} = {}
|
||||
): Promise<number> {
|
||||
const executable = resolveForegroundOrcaExecutable()
|
||||
const childArgs = ['--serve']
|
||||
if (args.json) {
|
||||
childArgs.push('--serve-json')
|
||||
}
|
||||
if (args.port) {
|
||||
childArgs.push('--serve-port', args.port)
|
||||
}
|
||||
if (args.pairingAddress) {
|
||||
childArgs.push('--serve-pairing-address', args.pairingAddress)
|
||||
}
|
||||
if (args.noPairing) {
|
||||
childArgs.push('--serve-no-pairing')
|
||||
}
|
||||
if (args.mobilePairing) {
|
||||
childArgs.push('--serve-mobile-pairing')
|
||||
}
|
||||
|
||||
const child = spawnProcess(executable, childArgs, {
|
||||
cwd: resolveAppRoot(),
|
||||
stdio: 'inherit',
|
||||
env: stripElectronRunAsNode(process.env)
|
||||
})
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let forceKillTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const forwardSignal = (signal: NodeJS.Signals): void => {
|
||||
child.kill(signal)
|
||||
forceKillTimer ??= setTimeout(() => {
|
||||
child.kill('SIGKILL')
|
||||
}, 5000)
|
||||
}
|
||||
const cleanup = (): void => {
|
||||
process.off('SIGINT', forwardSignal)
|
||||
process.off('SIGTERM', forwardSignal)
|
||||
if (forceKillTimer) {
|
||||
clearTimeout(forceKillTimer)
|
||||
forceKillTimer = null
|
||||
}
|
||||
}
|
||||
process.on('SIGINT', forwardSignal)
|
||||
process.on('SIGTERM', forwardSignal)
|
||||
child.once('error', (error) => {
|
||||
cleanup()
|
||||
reject(error)
|
||||
})
|
||||
child.once('exit', (code, signal) => {
|
||||
cleanup()
|
||||
if (typeof code === 'number') {
|
||||
resolve(code)
|
||||
return
|
||||
}
|
||||
reject(new RuntimeClientError('runtime_serve_failed', `Orca serve exited via ${signal}`))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function resolveAppRoot(): string {
|
||||
// Why: dev-mode resource resolution in the Electron child may consult
|
||||
// process.cwd(). Pin it to the app root so `orca serve` behaves the same
|
||||
// regardless of the shell directory it was launched from.
|
||||
return resolve(__dirname, '../../..')
|
||||
}
|
||||
|
||||
function resolveForegroundOrcaExecutable(): string {
|
||||
const overrideExecutable = process.env.ORCA_APP_EXECUTABLE
|
||||
if (typeof overrideExecutable === 'string' && overrideExecutable.trim().length > 0) {
|
||||
return overrideExecutable
|
||||
}
|
||||
if (process.env.ELECTRON_RUN_AS_NODE === '1') {
|
||||
return process.execPath
|
||||
}
|
||||
throw new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
'Could not determine how to start Orca server. Set ORCA_APP_EXECUTABLE to the Orca executable.'
|
||||
)
|
||||
}
|
||||
|
||||
function stripElectronRunAsNode(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const next = { ...env }
|
||||
delete next.ELECTRON_RUN_AS_NODE
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function getCliStatus(
|
||||
|
||||
try {
|
||||
const response = await sendRequest<RuntimeStatus>(metadata, 'status.get', undefined, 1000)
|
||||
if (!response.ok) {
|
||||
if (response.ok === false) {
|
||||
throw new RuntimeRpcFailureError(response)
|
||||
}
|
||||
const graphState = response.result.graphStatus
|
||||
|
||||
@@ -49,10 +49,10 @@ export async function sendRequest<TResult>(
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
socket.end()
|
||||
if (result.ok) {
|
||||
resolve(result.response)
|
||||
} else {
|
||||
if (result.ok === false) {
|
||||
reject(result.error)
|
||||
} else {
|
||||
resolve(result.response)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,10 @@
|
||||
// Why: the RPC envelope shape is the contract the CLI shares with the main
|
||||
// runtime. Keeping the types and error classes in one leaf module lets every
|
||||
// other runtime module depend on them without pulling in transport or launch
|
||||
// code.
|
||||
import type { RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope'
|
||||
|
||||
export type RuntimeRpcSuccess<TResult> = {
|
||||
id: string
|
||||
ok: true
|
||||
result: TResult
|
||||
_meta: {
|
||||
runtimeId: string
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeRpcFailure = {
|
||||
id: string
|
||||
ok: false
|
||||
error: {
|
||||
code: string
|
||||
message: string
|
||||
data?: unknown
|
||||
}
|
||||
_meta?: {
|
||||
runtimeId: string | null
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeRpcResponse<TResult> = RuntimeRpcSuccess<TResult> | RuntimeRpcFailure
|
||||
export type {
|
||||
RuntimeRpcFailure,
|
||||
RuntimeRpcResponse,
|
||||
RuntimeRpcSuccess
|
||||
} from '../../shared/runtime-rpc-envelope'
|
||||
|
||||
export class RuntimeClientError extends Error {
|
||||
readonly code: string
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { createServer, type Server } from 'http'
|
||||
import { mkdtempSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { WebSocketServer } from 'ws'
|
||||
import { encodePairingOffer, type PairingOffer } from '../../shared/pairing'
|
||||
import {
|
||||
decrypt,
|
||||
deriveSharedKey,
|
||||
encrypt,
|
||||
generateKeyPair,
|
||||
publicKeyToBase64
|
||||
} from '../../shared/e2ee-crypto'
|
||||
import { RuntimeClient } from './client'
|
||||
import { addEnvironmentFromPairingCode } from './environments'
|
||||
import { RuntimeClientError } from './types'
|
||||
import {
|
||||
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
|
||||
RUNTIME_PROTOCOL_VERSION
|
||||
} from '../../shared/protocol-version'
|
||||
|
||||
type TestRuntime = {
|
||||
endpoint: string
|
||||
publicKeyB64: string
|
||||
deviceToken: string
|
||||
close: () => Promise<void>
|
||||
}
|
||||
|
||||
describe('CLI remote WebSocket transport', () => {
|
||||
const servers: TestRuntime[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(servers.splice(0).map((server) => server.close()))
|
||||
})
|
||||
|
||||
it('calls a remote runtime through a mobile pairing offer', async () => {
|
||||
const runtime = await startTestRuntime('runtime-ws-1')
|
||||
servers.push(runtime)
|
||||
|
||||
const pairingUrl = encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint: runtime.endpoint,
|
||||
deviceToken: runtime.deviceToken,
|
||||
publicKeyB64: runtime.publicKeyB64
|
||||
})
|
||||
const client = new RuntimeClient('/tmp/unused', 5_000, pairingUrl)
|
||||
const response = await client.call<{ runtimeId: string }>('status.get')
|
||||
|
||||
expect(response.ok).toBe(true)
|
||||
expect(response.result.runtimeId).toBe('runtime-ws-1')
|
||||
})
|
||||
|
||||
it('rejects malformed remote pairing codes before local runtime lookup', () => {
|
||||
expect(() => new RuntimeClient('/tmp/unused', 5_000, 'not-a-pairing-code')).toThrow(
|
||||
RuntimeClientError
|
||||
)
|
||||
})
|
||||
|
||||
it('accepts a bare pairing payload as well as the orca URL wrapper', async () => {
|
||||
const runtime = await startTestRuntime('runtime-ws-2')
|
||||
servers.push(runtime)
|
||||
const offer: PairingOffer = {
|
||||
v: 2,
|
||||
endpoint: runtime.endpoint,
|
||||
deviceToken: runtime.deviceToken,
|
||||
publicKeyB64: runtime.publicKeyB64
|
||||
}
|
||||
const barePayload = encodePairingOffer(offer).split('#')[1]!
|
||||
|
||||
const client = new RuntimeClient('/tmp/unused', 5_000, barePayload)
|
||||
const status = await client.getCliStatus()
|
||||
|
||||
expect(status.result.runtime.reachable).toBe(true)
|
||||
expect(status.result.runtime.runtimeId).toBe('runtime-ws-2')
|
||||
})
|
||||
|
||||
it('connects through a saved environment selector', async () => {
|
||||
const runtime = await startTestRuntime('runtime-env-1')
|
||||
servers.push(runtime)
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-cli-env-'))
|
||||
addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'remote-dev',
|
||||
pairingCode: encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint: runtime.endpoint,
|
||||
deviceToken: runtime.deviceToken,
|
||||
publicKeyB64: runtime.publicKeyB64
|
||||
})
|
||||
})
|
||||
|
||||
const client = new RuntimeClient(userDataPath, 5_000, null, 'remote-dev')
|
||||
const status = await client.getCliStatus()
|
||||
|
||||
expect(status.result.runtime.reachable).toBe(true)
|
||||
expect(status.result.runtime.runtimeId).toBe('runtime-env-1')
|
||||
})
|
||||
|
||||
it('blocks remote RPCs when the server protocol is too old', async () => {
|
||||
const runtime = await startTestRuntime('runtime-old', { runtimeProtocolVersion: 1 })
|
||||
servers.push(runtime)
|
||||
|
||||
const client = new RuntimeClient(
|
||||
'/tmp/unused',
|
||||
5_000,
|
||||
encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint: runtime.endpoint,
|
||||
deviceToken: runtime.deviceToken,
|
||||
publicKeyB64: runtime.publicKeyB64
|
||||
})
|
||||
)
|
||||
|
||||
await expect(client.call('repo.list')).rejects.toMatchObject({
|
||||
code: 'incompatible_runtime',
|
||||
message: expect.stringContaining('server is too old')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
async function startTestRuntime(
|
||||
runtimeId: string,
|
||||
statusOverrides: {
|
||||
runtimeProtocolVersion?: number
|
||||
minCompatibleRuntimeClientVersion?: number
|
||||
} = {}
|
||||
): Promise<TestRuntime> {
|
||||
const serverKeyPair = generateKeyPair()
|
||||
const deviceToken = `token-${runtimeId}`
|
||||
const httpServer = createServer()
|
||||
const wss = new WebSocketServer({ server: httpServer })
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
let sharedKey: Uint8Array | null = null
|
||||
let authenticated = false
|
||||
|
||||
ws.on('message', (data) => {
|
||||
const frame = data.toString()
|
||||
if (!sharedKey) {
|
||||
const hello = JSON.parse(frame) as { type?: string; publicKeyB64?: string }
|
||||
const clientPublicKey = Buffer.from(hello.publicKeyB64 ?? '', 'base64')
|
||||
sharedKey = deriveSharedKey(serverKeyPair.secretKey, clientPublicKey)
|
||||
ws.send(JSON.stringify({ type: 'e2ee_ready' }))
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (!plaintext) {
|
||||
ws.close(4003, 'decrypt failed')
|
||||
return
|
||||
}
|
||||
if (!authenticated) {
|
||||
const auth = JSON.parse(plaintext) as { type?: string; deviceToken?: string }
|
||||
if (auth.type !== 'e2ee_auth' || auth.deviceToken !== deviceToken) {
|
||||
ws.send(encrypt(JSON.stringify({ type: 'e2ee_error' }), sharedKey))
|
||||
ws.close(4001, 'auth failed')
|
||||
return
|
||||
}
|
||||
authenticated = true
|
||||
ws.send(encrypt(JSON.stringify({ type: 'e2ee_authenticated' }), sharedKey))
|
||||
return
|
||||
}
|
||||
|
||||
const request = JSON.parse(plaintext) as { id: string; method: string }
|
||||
const response =
|
||||
request.method === 'status.get'
|
||||
? {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: {
|
||||
runtimeId,
|
||||
rendererGraphEpoch: 1,
|
||||
graphStatus: 'ready',
|
||||
authoritativeWindowId: null,
|
||||
liveTabCount: 0,
|
||||
liveLeafCount: 0,
|
||||
runtimeProtocolVersion:
|
||||
statusOverrides.runtimeProtocolVersion ?? RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleRuntimeClientVersion:
|
||||
statusOverrides.minCompatibleRuntimeClientVersion ??
|
||||
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
|
||||
},
|
||||
_meta: { runtimeId }
|
||||
}
|
||||
: {
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: { code: 'method_not_found', message: 'Unknown method' },
|
||||
_meta: { runtimeId }
|
||||
}
|
||||
ws.send(encrypt(JSON.stringify(response), sharedKey))
|
||||
})
|
||||
})
|
||||
|
||||
await listen(httpServer)
|
||||
const address = httpServer.address()
|
||||
if (!address || typeof address === 'string') {
|
||||
throw new Error('Expected TCP test server')
|
||||
}
|
||||
|
||||
return {
|
||||
endpoint: `ws://127.0.0.1:${address.port}`,
|
||||
publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey),
|
||||
deviceToken,
|
||||
close: async () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
wss.close(() => resolve())
|
||||
for (const client of wss.clients) {
|
||||
client.close()
|
||||
}
|
||||
})
|
||||
await closeHttpServer(httpServer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listen(server: Server): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once('error', reject)
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
server.off('error', reject)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function closeHttpServer(server: Server): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { PairingOffer } from '../../shared/pairing'
|
||||
import {
|
||||
RemoteRuntimeClientError,
|
||||
sendRemoteRuntimeRequest
|
||||
} from '../../shared/remote-runtime-client'
|
||||
import { RuntimeClientError, type RuntimeRpcResponse } from './types'
|
||||
|
||||
export async function sendWebSocketRequest<TResult>(
|
||||
pairing: PairingOffer,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
): Promise<RuntimeRpcResponse<TResult>> {
|
||||
try {
|
||||
return await sendRemoteRuntimeRequest<TResult>(pairing, method, params, timeoutMs)
|
||||
} catch (error) {
|
||||
if (error instanceof RemoteRuntimeClientError) {
|
||||
throw new RuntimeClientError(error.code, error.message)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user