Refactor runtime app architecture (#1878)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
+2
-1
@@ -14,7 +14,7 @@ export type CommandSpec = {
|
||||
notes?: string[]
|
||||
}
|
||||
|
||||
export const GLOBAL_FLAGS = ['help', 'json']
|
||||
export const GLOBAL_FLAGS = ['help', 'json', 'pairing-code', 'environment']
|
||||
|
||||
export function parseArgs(argv: string[]): ParsedArgs {
|
||||
const commandPath: string[] = []
|
||||
@@ -93,6 +93,7 @@ export function isCommandGroup(commandPath: string[]): boolean {
|
||||
'storage',
|
||||
'orchestration',
|
||||
'computer',
|
||||
'environment',
|
||||
'note'
|
||||
].includes(commandPath[0])) ||
|
||||
(commandPath.length === 2 &&
|
||||
|
||||
@@ -14,6 +14,7 @@ import { BROWSER_ENV_HANDLERS } from './handlers/browser-env'
|
||||
import { BROWSER_STORAGE_HANDLERS } from './handlers/browser-storage'
|
||||
import { ORCHESTRATION_HANDLERS } from './handlers/orchestration'
|
||||
import { COMPUTER_HANDLERS } from './handlers/computer'
|
||||
import { ENVIRONMENT_HANDLERS } from './handlers/environment'
|
||||
import { NOTE_HANDLERS } from './handlers/note'
|
||||
|
||||
export type HandlerContext = {
|
||||
@@ -42,6 +43,7 @@ function buildHandlers(): Map<string, CommandHandler> {
|
||||
BROWSER_STORAGE_HANDLERS,
|
||||
ORCHESTRATION_HANDLERS,
|
||||
COMPUTER_HANDLERS,
|
||||
ENVIRONMENT_HANDLERS,
|
||||
NOTE_HANDLERS
|
||||
]
|
||||
for (const group of groups) {
|
||||
|
||||
@@ -33,6 +33,7 @@ import type {
|
||||
RuntimeWorktreePsResult,
|
||||
RuntimeWorktreeRecord
|
||||
} from '../shared/runtime-types'
|
||||
import type { PublicKnownRuntimeEnvironment } from '../shared/runtime-environments'
|
||||
import type { NoteListResult, NoteMutationResult, NoteShowResult } from '../shared/notes-types'
|
||||
import type { RuntimeRpcFailure, RuntimeRpcSuccess } from './runtime-client'
|
||||
import { RuntimeClientError, RuntimeRpcFailureError } from './runtime-client'
|
||||
@@ -101,6 +102,33 @@ export function formatStatus(status: CliStatusResult): string {
|
||||
return formatCliStatus(status)
|
||||
}
|
||||
|
||||
export function formatEnvironmentList(result: {
|
||||
environments: PublicKnownRuntimeEnvironment[]
|
||||
}): string {
|
||||
if (result.environments.length === 0) {
|
||||
return 'No saved environments.'
|
||||
}
|
||||
return result.environments
|
||||
.map(
|
||||
(environment) =>
|
||||
`${environment.id} ${environment.name} ${environment.endpoints[0]?.endpoint ?? 'no-endpoint'}`
|
||||
)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
export function formatEnvironment(environment: PublicKnownRuntimeEnvironment): string {
|
||||
return [
|
||||
`id: ${environment.id}`,
|
||||
`name: ${environment.name}`,
|
||||
`runtimeId: ${environment.runtimeId ?? 'unknown'}`,
|
||||
`lastUsedAt: ${environment.lastUsedAt ?? 'never'}`,
|
||||
`preferredEndpointId: ${environment.preferredEndpointId}`,
|
||||
...environment.endpoints.map(
|
||||
(endpoint) => `endpoint: ${endpoint.id} ${endpoint.kind} ${endpoint.endpoint}`
|
||||
)
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function formatTerminalList(result: RuntimeTerminalListResult): string {
|
||||
if (result.terminals.length === 0) {
|
||||
return 'No live terminals.'
|
||||
|
||||
@@ -1,11 +1,38 @@
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { formatCliStatus, formatStatus, printResult } from '../format'
|
||||
import { RuntimeClientError, serveOrcaApp } from '../runtime-client'
|
||||
|
||||
export const CORE_HANDLERS: Record<string, CommandHandler> = {
|
||||
open: async ({ client, json }) => {
|
||||
const result = await client.openOrca()
|
||||
printResult(result, json, formatCliStatus)
|
||||
},
|
||||
serve: async ({ flags, json }) => {
|
||||
if (flags.get('no-pairing') === true && flags.get('mobile-pairing') === true) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Use either --mobile-pairing or --no-pairing, not both.'
|
||||
)
|
||||
}
|
||||
const rawPort = flags.get('port')
|
||||
if (typeof rawPort === 'string') {
|
||||
const port = Number(rawPort)
|
||||
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
||||
throw new RuntimeClientError('invalid_argument', `Invalid --port value: ${rawPort}`)
|
||||
}
|
||||
}
|
||||
const exitCode = await serveOrcaApp({
|
||||
json,
|
||||
port: typeof rawPort === 'string' ? rawPort : null,
|
||||
pairingAddress:
|
||||
typeof flags.get('pairing-address') === 'string'
|
||||
? (flags.get('pairing-address') as string)
|
||||
: null,
|
||||
noPairing: flags.get('no-pairing') === true,
|
||||
mobilePairing: flags.get('mobile-pairing') === true
|
||||
})
|
||||
process.exitCode = exitCode
|
||||
},
|
||||
status: async ({ client, json }) => {
|
||||
const result = await client.getCliStatus()
|
||||
if (!json && !result.result.runtime.reachable) {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { formatEnvironment, formatEnvironmentList, printResult } from '../format'
|
||||
import { getDefaultUserDataPath } from '../runtime-client'
|
||||
import type { RuntimeRpcSuccess } from '../runtime-client'
|
||||
import { RuntimeClientError } from '../runtime-client'
|
||||
import { redactRuntimeEnvironment } from '../../shared/runtime-environments'
|
||||
import {
|
||||
addEnvironmentFromPairingCode,
|
||||
listEnvironments,
|
||||
removeEnvironment,
|
||||
resolveEnvironment,
|
||||
type EnvironmentAddResult,
|
||||
type EnvironmentRemoveResult
|
||||
} from '../runtime/environments'
|
||||
|
||||
export const ENVIRONMENT_HANDLERS: Record<string, CommandHandler> = {
|
||||
'environment add': async ({ flags, json }) => {
|
||||
const name = getRequiredStringFlag(flags, 'name')
|
||||
const pairingCode = getRequiredStringFlag(flags, 'pairing-code')
|
||||
const environment = redactRuntimeEnvironment(
|
||||
addEnvironmentFromPairingCode(getDefaultUserDataPath(), {
|
||||
name,
|
||||
pairingCode
|
||||
})
|
||||
)
|
||||
printResult(
|
||||
localSuccess({ environment }),
|
||||
json,
|
||||
(result: EnvironmentAddResult) =>
|
||||
`Saved environment ${result.environment.name} (${result.environment.id}).`
|
||||
)
|
||||
},
|
||||
'environment list': async ({ json }) => {
|
||||
const environments = listEnvironments(getDefaultUserDataPath()).map(redactRuntimeEnvironment)
|
||||
printResult(localSuccess({ environments }), json, formatEnvironmentList)
|
||||
},
|
||||
'environment show': async ({ flags, json }) => {
|
||||
const selector = getRequiredStringFlag(flags, 'environment')
|
||||
const environment = redactRuntimeEnvironment(
|
||||
resolveEnvironment(getDefaultUserDataPath(), selector)
|
||||
)
|
||||
printResult(localSuccess({ environment }), json, ({ environment: value }) =>
|
||||
formatEnvironment(value)
|
||||
)
|
||||
},
|
||||
'environment rm': async ({ flags, json }) => {
|
||||
const selector = getRequiredStringFlag(flags, 'environment')
|
||||
const removed = redactRuntimeEnvironment(removeEnvironment(getDefaultUserDataPath(), selector))
|
||||
printResult(
|
||||
localSuccess({ removed }),
|
||||
json,
|
||||
(result: EnvironmentRemoveResult) =>
|
||||
`Removed environment ${result.removed.name} (${result.removed.id}).`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function getRequiredStringFlag(flags: Map<string, string | boolean>, name: string): string {
|
||||
const value = flags.get(name)
|
||||
if (typeof value !== 'string' || value.length === 0) {
|
||||
throw new RuntimeClientError('invalid_argument', `Missing required --${name}`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function localSuccess<TResult>(result: TResult): RuntimeRpcSuccess<TResult> {
|
||||
return {
|
||||
id: 'local',
|
||||
ok: true,
|
||||
result,
|
||||
_meta: {
|
||||
runtimeId: 'local'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,43 @@
|
||||
import { resolve as resolvePath } from 'path'
|
||||
import type { RuntimeRepoList, RuntimeRepoSearchRefs } from '../../shared/runtime-types'
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { formatRepoList, formatRepoRefs, formatRepoShow, printResult } from '../format'
|
||||
import { getOptionalPositiveIntegerFlag, getRequiredStringFlag } from '../flags'
|
||||
import { RuntimeClientError } from '../runtime-client'
|
||||
|
||||
function isAbsoluteServerPath(value: string): boolean {
|
||||
return (
|
||||
value.startsWith('/') ||
|
||||
/^[A-Za-z]:[\\/]/.test(value) ||
|
||||
value.startsWith('\\\\') ||
|
||||
value.startsWith('//')
|
||||
)
|
||||
}
|
||||
|
||||
function resolveRepoAddPath(inputPath: string, cwd: string, isRemote: boolean): string {
|
||||
if (!isRemote) {
|
||||
return resolvePath(cwd, inputPath)
|
||||
}
|
||||
// Why: the local CLI cwd is unrelated to a paired runtime's filesystem.
|
||||
// Relative remote paths would silently target the wrong machine.
|
||||
if (!isAbsoluteServerPath(inputPath)) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Remote repo add requires --path to be an absolute path on the remote server.'
|
||||
)
|
||||
}
|
||||
return inputPath
|
||||
}
|
||||
|
||||
export const REPO_HANDLERS: Record<string, CommandHandler> = {
|
||||
'repo list': async ({ client, json }) => {
|
||||
const result = await client.call<RuntimeRepoList>('repo.list')
|
||||
printResult(result, json, formatRepoList)
|
||||
},
|
||||
'repo add': async ({ flags, client, json }) => {
|
||||
'repo add': async ({ flags, client, cwd, json }) => {
|
||||
const repoPath = getRequiredStringFlag(flags, 'path')
|
||||
const result = await client.call<{ repo: Record<string, unknown> }>('repo.add', {
|
||||
path: getRequiredStringFlag(flags, 'path')
|
||||
path: resolveRepoAddPath(repoPath, cwd, client.isRemote)
|
||||
})
|
||||
printResult(result, json, formatRepoShow)
|
||||
},
|
||||
|
||||
@@ -116,6 +116,12 @@ export const TERMINAL_HANDLERS: Record<string, CommandHandler> = {
|
||||
printResult(result, json, formatTerminalRename)
|
||||
},
|
||||
'terminal create': async ({ flags, client, cwd, json }) => {
|
||||
if (client.isRemote && !flags.has('worktree')) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Remote terminal create requires --worktree because the client cwd cannot identify a server worktree.'
|
||||
)
|
||||
}
|
||||
const result = await client.call<{ terminal: RuntimeTerminalCreate }>('terminal.create', {
|
||||
worktree: await getBrowserWorktreeSelector(flags, cwd, client),
|
||||
command: getOptionalStringFlag(flags, 'command'),
|
||||
|
||||
@@ -8,8 +8,15 @@ Usage: orca <command> [options]
|
||||
|
||||
Startup:
|
||||
open Launch Orca and wait for the runtime to be reachable
|
||||
serve Start a headless Orca runtime server
|
||||
status Show app/runtime/graph readiness
|
||||
|
||||
Environments:
|
||||
environment add Save a remote Orca runtime from a pairing code
|
||||
environment list List saved remote Orca runtimes
|
||||
environment show Show one saved remote Orca runtime
|
||||
environment rm Remove a saved remote Orca runtime
|
||||
|
||||
Repos:
|
||||
repo list List repos registered in Orca
|
||||
repo add Add a project to Orca by filesystem path
|
||||
@@ -138,7 +145,12 @@ Browser Automation:
|
||||
|
||||
Common Commands:
|
||||
orca open [--json]
|
||||
orca serve [--port <port>] [--pairing-address <host>] [--mobile-pairing] [--no-pairing] [--json]
|
||||
orca status [--json]
|
||||
orca environment add --name <name> --pairing-code <code> [--json]
|
||||
orca environment list [--json]
|
||||
orca environment show --environment <selector> [--json]
|
||||
orca environment rm --environment <selector> [--json]
|
||||
orca worktree list [--repo <selector>] [--limit <n>] [--json]
|
||||
orca worktree create --repo <selector> --name <name> [--base-branch <ref>] [--issue <number>] [--comment <text>] [--run-hooks] [--activate] [--json]
|
||||
orca worktree show --worktree <selector> [--json]
|
||||
@@ -178,10 +190,13 @@ Wait Options:
|
||||
|
||||
Output Options:
|
||||
--json Emit machine-readable JSON instead of human text
|
||||
--pairing-code <code> Connect to a remote Orca runtime using an orca://pair#... code
|
||||
--environment <selector> Connect using a saved environment id or name
|
||||
--help Show this help message
|
||||
|
||||
Behavior:
|
||||
Most commands require a running Orca runtime. If Orca is not open yet, run \`orca open\` first.
|
||||
Remote runtime access can also be supplied with ORCA_PAIRING_CODE or ORCA_ENVIRONMENT.
|
||||
Use selectors for discovery and handles for repeated live terminal operations.
|
||||
|
||||
Browser Workflow:
|
||||
|
||||
+367
-2
@@ -2,13 +2,47 @@
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const callMock = vi.fn()
|
||||
const {
|
||||
callMock,
|
||||
serveOrcaAppMock,
|
||||
getDefaultUserDataPathMock,
|
||||
addEnvironmentFromPairingCodeMock,
|
||||
listEnvironmentsMock
|
||||
} = vi.hoisted(() => ({
|
||||
callMock: vi.fn(),
|
||||
serveOrcaAppMock: vi.fn(),
|
||||
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
|
||||
addEnvironmentFromPairingCodeMock: vi.fn(),
|
||||
listEnvironmentsMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./runtime-client', () => {
|
||||
class RuntimeClient {
|
||||
readonly isRemote: boolean
|
||||
call = callMock
|
||||
getCliStatus = vi.fn()
|
||||
openOrca = vi.fn()
|
||||
|
||||
constructor(
|
||||
_userDataPath?: string,
|
||||
_requestTimeoutMs?: number,
|
||||
remotePairingCode?: string | null,
|
||||
environmentSelector?: string | null
|
||||
) {
|
||||
const effectivePairingCode =
|
||||
remotePairingCode === undefined
|
||||
? (process.env.ORCA_PAIRING_CODE ?? process.env.ORCA_REMOTE_PAIRING)
|
||||
: remotePairingCode
|
||||
const effectiveEnvironment =
|
||||
environmentSelector === undefined ? process.env.ORCA_ENVIRONMENT : environmentSelector
|
||||
if (effectivePairingCode && effectiveEnvironment) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Use either --pairing-code or --environment, not both.'
|
||||
)
|
||||
}
|
||||
this.isRemote = Boolean(effectivePairingCode || effectiveEnvironment)
|
||||
}
|
||||
}
|
||||
|
||||
class RuntimeClientError extends Error {
|
||||
@@ -32,10 +66,19 @@ vi.mock('./runtime-client', () => {
|
||||
return {
|
||||
RuntimeClient,
|
||||
RuntimeClientError,
|
||||
RuntimeRpcFailureError
|
||||
RuntimeRpcFailureError,
|
||||
serveOrcaApp: serveOrcaAppMock,
|
||||
getDefaultUserDataPath: getDefaultUserDataPathMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('./runtime/environments', () => ({
|
||||
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
|
||||
listEnvironments: listEnvironmentsMock,
|
||||
removeEnvironment: vi.fn(),
|
||||
resolveEnvironment: vi.fn()
|
||||
}))
|
||||
|
||||
import {
|
||||
buildCurrentWorktreeSelector,
|
||||
COMMAND_SPECS,
|
||||
@@ -58,9 +101,36 @@ describe('COMMAND_SPECS collision check', () => {
|
||||
describe('orca cli worktree awareness', () => {
|
||||
const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
|
||||
const originalUserDataPath = process.env.ORCA_USER_DATA_PATH
|
||||
const originalPairingCode = process.env.ORCA_PAIRING_CODE
|
||||
const originalRemotePairing = process.env.ORCA_REMOTE_PAIRING
|
||||
const originalEnvironment = process.env.ORCA_ENVIRONMENT
|
||||
|
||||
beforeEach(() => {
|
||||
callMock.mockReset()
|
||||
serveOrcaAppMock.mockReset()
|
||||
getDefaultUserDataPathMock.mockClear()
|
||||
addEnvironmentFromPairingCodeMock.mockReset()
|
||||
listEnvironmentsMock.mockReset()
|
||||
addEnvironmentFromPairingCodeMock.mockReturnValue({
|
||||
id: 'env-1',
|
||||
name: 'desk',
|
||||
createdAt: 100,
|
||||
updatedAt: 100,
|
||||
lastUsedAt: null,
|
||||
runtimeId: null,
|
||||
endpoints: [
|
||||
{
|
||||
id: 'ws-env-1',
|
||||
kind: 'websocket',
|
||||
label: 'WebSocket',
|
||||
endpoint: 'ws://127.0.0.1:6768',
|
||||
deviceToken: 'token',
|
||||
publicKeyB64: 'pk'
|
||||
}
|
||||
],
|
||||
preferredEndpointId: 'ws-env-1'
|
||||
})
|
||||
listEnvironmentsMock.mockReturnValue([])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -75,6 +145,21 @@ describe('orca cli worktree awareness', () => {
|
||||
} else {
|
||||
process.env.ORCA_USER_DATA_PATH = originalUserDataPath
|
||||
}
|
||||
if (originalPairingCode === undefined) {
|
||||
delete process.env.ORCA_PAIRING_CODE
|
||||
} else {
|
||||
process.env.ORCA_PAIRING_CODE = originalPairingCode
|
||||
}
|
||||
if (originalRemotePairing === undefined) {
|
||||
delete process.env.ORCA_REMOTE_PAIRING
|
||||
} else {
|
||||
process.env.ORCA_REMOTE_PAIRING = originalRemotePairing
|
||||
}
|
||||
if (originalEnvironment === undefined) {
|
||||
delete process.env.ORCA_ENVIRONMENT
|
||||
} else {
|
||||
process.env.ORCA_ENVIRONMENT = originalEnvironment
|
||||
}
|
||||
})
|
||||
|
||||
it('builds the current worktree selector from cwd', () => {
|
||||
@@ -115,6 +200,25 @@ describe('orca cli worktree awareness', () => {
|
||||
expect(logSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects remote `worktree current` without listing worktrees from client cwd', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const priorExitCode = process.exitCode
|
||||
|
||||
await main(
|
||||
['worktree', 'current', '--pairing-code', 'remote-runtime', '--json'],
|
||||
'/tmp/repo/src'
|
||||
)
|
||||
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
|
||||
'current is a local cwd shortcut and cannot be resolved against a remote runtime.'
|
||||
)
|
||||
expect(process.exitCode).toBe(1)
|
||||
|
||||
process.exitCode = priorExitCode
|
||||
})
|
||||
|
||||
it('uses cwd when active is passed to worktree.set', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
@@ -171,6 +275,192 @@ describe('orca cli worktree awareness', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('starts a foreground headless server through `serve`', async () => {
|
||||
serveOrcaAppMock.mockResolvedValue(0)
|
||||
process.env.ORCA_ENVIRONMENT = 'stale-env'
|
||||
|
||||
await main(
|
||||
['serve', '--json', '--port', '6768', '--pairing-address', '100.64.1.20', '--no-pairing'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(serveOrcaAppMock).toHaveBeenCalledWith({
|
||||
json: true,
|
||||
port: '6768',
|
||||
pairingAddress: '100.64.1.20',
|
||||
noPairing: true,
|
||||
mobilePairing: false
|
||||
})
|
||||
})
|
||||
|
||||
it('starts a foreground headless server with mobile pairing enabled', async () => {
|
||||
serveOrcaAppMock.mockResolvedValue(0)
|
||||
|
||||
await main(
|
||||
['serve', '--pairing-address', '100.64.1.20', '--mobile-pairing', '--json'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(serveOrcaAppMock).toHaveBeenCalledWith({
|
||||
json: true,
|
||||
port: null,
|
||||
pairingAddress: '100.64.1.20',
|
||||
noPairing: false,
|
||||
mobilePairing: true
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects contradictory serve pairing flags', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const priorExitCode = process.exitCode
|
||||
|
||||
await main(['serve', '--mobile-pairing', '--no-pairing', '--json'], '/tmp/repo')
|
||||
|
||||
expect(serveOrcaAppMock).not.toHaveBeenCalled()
|
||||
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
|
||||
'Use either --mobile-pairing or --no-pairing, not both.'
|
||||
)
|
||||
expect(process.exitCode).toBe(1)
|
||||
|
||||
process.exitCode = priorExitCode
|
||||
})
|
||||
|
||||
it('rejects invalid serve ports before launching the app', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const priorExitCode = process.exitCode
|
||||
|
||||
await main(['serve', '--port', 'not-a-port', '--json'], '/tmp/repo')
|
||||
|
||||
expect(serveOrcaAppMock).not.toHaveBeenCalled()
|
||||
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
|
||||
'Invalid --port value: not-a-port'
|
||||
)
|
||||
expect(process.exitCode).toBe(1)
|
||||
|
||||
process.exitCode = priorExitCode
|
||||
})
|
||||
|
||||
it('lists saved environments even when ORCA_ENVIRONMENT is set', async () => {
|
||||
process.env.ORCA_ENVIRONMENT = 'stale-env'
|
||||
listEnvironmentsMock.mockReturnValue([addEnvironmentFromPairingCodeMock()])
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(['environment', 'list', '--json'], '/tmp/repo')
|
||||
|
||||
expect(listEnvironmentsMock).toHaveBeenCalledWith('/tmp/orca-user-data')
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
expect(logSpy.mock.calls[0]?.[0]).not.toContain('token')
|
||||
expect(logSpy.mock.calls[0]?.[0]).not.toContain('publicKeyB64')
|
||||
})
|
||||
|
||||
it('adds saved environments even when ORCA_ENVIRONMENT is set', async () => {
|
||||
process.env.ORCA_ENVIRONMENT = 'stale-env'
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(
|
||||
['environment', 'add', '--name', 'desk', '--pairing-code', 'orca://pair#abc', '--json'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(addEnvironmentFromPairingCodeMock).toHaveBeenCalledWith('/tmp/orca-user-data', {
|
||||
name: 'desk',
|
||||
pairingCode: 'orca://pair#abc'
|
||||
})
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
expect(logSpy.mock.calls[0]?.[0]).not.toContain('token')
|
||||
expect(logSpy.mock.calls[0]?.[0]).not.toContain('publicKeyB64')
|
||||
})
|
||||
|
||||
it('resolves repo.add paths against the invoking cli cwd', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
okFixture('req_repo_add', {
|
||||
repo: {
|
||||
id: 'repo-1',
|
||||
path: path.resolve('/tmp/repo/apps/web'),
|
||||
displayName: 'web'
|
||||
}
|
||||
})
|
||||
)
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(['repo', 'add', '--path', './apps/web', '--json'], '/tmp/repo')
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('repo.add', {
|
||||
path: path.resolve('/tmp/repo/apps/web')
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects remote repo.add relative paths instead of resolving against client cwd', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const priorExitCode = process.exitCode
|
||||
|
||||
await main(
|
||||
['repo', 'add', '--path', './apps/web', '--pairing-code', 'remote-runtime', '--json'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
|
||||
'Remote repo add requires --path to be an absolute path on the remote server.'
|
||||
)
|
||||
expect(process.exitCode).toBe(1)
|
||||
|
||||
process.exitCode = priorExitCode
|
||||
})
|
||||
|
||||
it('sends remote repo.add absolute paths unchanged', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
okFixture('req_repo_add', {
|
||||
repo: {
|
||||
id: 'repo-1',
|
||||
path: '/srv/orca/web',
|
||||
displayName: 'web'
|
||||
}
|
||||
})
|
||||
)
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(
|
||||
['repo', 'add', '--path', '/srv/orca/web', '--pairing-code', 'remote-runtime', '--json'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('repo.add', {
|
||||
path: '/srv/orca/web'
|
||||
})
|
||||
})
|
||||
|
||||
it.each(['C:\\repo', 'C:/repo', '\\\\server\\share\\repo', '//server/share/repo'])(
|
||||
'sends remote repo.add server absolute path %s unchanged',
|
||||
async (serverPath) => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
okFixture('req_repo_add', {
|
||||
repo: {
|
||||
id: 'repo-1',
|
||||
path: serverPath,
|
||||
displayName: 'web'
|
||||
}
|
||||
})
|
||||
)
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(
|
||||
['repo', 'add', '--path', serverPath, '--pairing-code', 'remote-runtime', '--json'],
|
||||
'/tmp/repo'
|
||||
)
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('repo.add', {
|
||||
path: serverPath
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
it('opts into setup and activation when worktree.create runs hooks', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
@@ -352,4 +642,79 @@ describe('orca cli worktree awareness', () => {
|
||||
limit: undefined
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects implicit remote terminal create instead of resolving from client cwd', async () => {
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const priorExitCode = process.exitCode
|
||||
|
||||
await main(
|
||||
['terminal', 'create', '--pairing-code', 'remote-runtime', '--json'],
|
||||
'/tmp/client/repo/src'
|
||||
)
|
||||
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
expect([...logSpy.mock.calls, ...errSpy.mock.calls].flat().join('\n')).toContain(
|
||||
'Remote terminal create requires --worktree'
|
||||
)
|
||||
expect(process.exitCode).toBe(1)
|
||||
|
||||
process.exitCode = priorExitCode
|
||||
})
|
||||
|
||||
it('sends explicit remote terminal create worktree selectors unchanged', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
okFixture('req_terminal_create', {
|
||||
terminal: {
|
||||
handle: 'term_1',
|
||||
worktreeId: 'repo-1::/srv/orca/feature',
|
||||
title: 'Server terminal'
|
||||
}
|
||||
})
|
||||
)
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(
|
||||
[
|
||||
'terminal',
|
||||
'create',
|
||||
'--worktree',
|
||||
'id:repo-1::/srv/orca/feature',
|
||||
'--pairing-code',
|
||||
'remote-runtime',
|
||||
'--json'
|
||||
],
|
||||
'/tmp/client/repo/src'
|
||||
)
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('terminal.create', {
|
||||
worktree: 'id:repo-1::/srv/orca/feature',
|
||||
command: undefined,
|
||||
title: undefined,
|
||||
focus: false
|
||||
})
|
||||
})
|
||||
|
||||
it('does not resolve implicit remote browser targets from client cwd', async () => {
|
||||
queueFixtures(
|
||||
callMock,
|
||||
okFixture('req_tab_current', {
|
||||
tab: {
|
||||
browserPageId: 'page-1',
|
||||
index: 0,
|
||||
url: 'https://example.com',
|
||||
title: 'Example',
|
||||
active: true,
|
||||
worktreeId: 'repo-1::/srv/orca/feature'
|
||||
}
|
||||
})
|
||||
)
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(['tab', 'current', '--pairing-code', 'remote-runtime', '--json'], '/tmp/client/src')
|
||||
|
||||
expect(callMock).toHaveBeenCalledTimes(1)
|
||||
expect(callMock).toHaveBeenCalledWith('browser.tabCurrent', { worktree: undefined })
|
||||
})
|
||||
})
|
||||
|
||||
+13
-1
@@ -15,6 +15,10 @@ import { COMMAND_SPECS } from './specs'
|
||||
export { COMMAND_SPECS } from './specs'
|
||||
export { buildCurrentWorktreeSelector, normalizeWorktreeSelector } from './selectors'
|
||||
|
||||
function shouldIgnoreRemoteSelection(commandPath: string[]): boolean {
|
||||
return commandPath[0] === 'environment' || commandPath[0] === 'serve'
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2), cwd = process.cwd()): Promise<void> {
|
||||
const parsed = parseArgs(argv)
|
||||
const helpPath = resolveHelpPath(parsed)
|
||||
@@ -40,7 +44,15 @@ export async function main(argv = process.argv.slice(2), cwd = process.cwd()): P
|
||||
// lookup so users do not get misleading "Orca is not running" failures for
|
||||
// simple command typos or unsupported flags.
|
||||
validateCommandAndFlags(COMMAND_SPECS, parsed)
|
||||
const client = new RuntimeClient()
|
||||
const ignoreRemoteSelection = shouldIgnoreRemoteSelection(parsed.commandPath)
|
||||
const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code')
|
||||
const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment')
|
||||
const client = new RuntimeClient(
|
||||
undefined,
|
||||
undefined,
|
||||
typeof pairingCode === 'string' ? pairingCode : undefined,
|
||||
typeof environmentSelector === 'string' ? environmentSelector : undefined
|
||||
)
|
||||
await dispatch(parsed.commandPath, {
|
||||
flags: parsed.flags,
|
||||
client,
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
// Why: subprocess-level test for the CLI heartbeat behavior described in
|
||||
// design doc §3.4. Spawns the real compiled CLI with no TTY, points it at a
|
||||
// real in-process runtime via ORCA_USER_DATA_PATH, and asserts:
|
||||
// - the first heartbeat line appears on stderr well under Claude Code's
|
||||
// ~2 min Bash-tool silence budget (we verify with a shortened interval;
|
||||
// production uses 15 s via the same code path)
|
||||
// - ≥3 heartbeats arrive during the wait window
|
||||
// - stderr is line-flushed (we observe each heartbeat as a separate chunk
|
||||
// before the process exits — not in one burst at the end)
|
||||
// - stdout stays a single clean JSON payload (no heartbeats leak to stdout)
|
||||
// - a `jq "select(._heartbeat|not)"` filter on the merged stream would
|
||||
// yield exactly the final result
|
||||
//
|
||||
// This test is skipped if the CLI hasn't been built yet (out/cli/index.js
|
||||
// missing) so `pnpm test` works on a fresh checkout without requiring a prior
|
||||
// `pnpm run build:cli`. The verification gate explicitly builds the CLI
|
||||
// before running this file.
|
||||
import { spawn } from 'child_process'
|
||||
import { existsSync, mkdtempSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../main/runtime/orca-runtime'
|
||||
import { OrchestrationDb } from '../main/runtime/orchestration/db'
|
||||
import { OrcaRuntimeRpcServer } from '../main/runtime/runtime-rpc'
|
||||
|
||||
// Why: Vitest runs tests with `process.cwd()` pinned to the repo root, so
|
||||
// join against it to locate the compiled CLI regardless of where this test
|
||||
// file itself lives.
|
||||
const CLI_PATH = join(process.cwd(), 'out', 'cli', 'index.js')
|
||||
|
||||
const describeIfBuilt = existsSync(CLI_PATH) ? describe : describe.skip
|
||||
|
||||
describeIfBuilt('orca orchestration check --wait subprocess (§3.4)', () => {
|
||||
it('emits newline-flushed JSON heartbeats to stderr while waiting', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-cli-sub-'))
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
runtime.setOrchestrationDb(db)
|
||||
const server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
|
||||
await server.start()
|
||||
|
||||
try {
|
||||
// Why: use the ORCA_HEARTBEAT_INTERVAL_MS escape hatch to shrink the
|
||||
// test to ~1 s wall time. Production callers never set this; the
|
||||
// production default (15 s) is exercised by §3.4's own unit tests
|
||||
// and by the fact that this same code path runs with the real
|
||||
// constant when the env var is absent.
|
||||
const heartbeatMs = 200
|
||||
const waitTimeoutMs = 1200
|
||||
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
CLI_PATH,
|
||||
'orchestration',
|
||||
'check',
|
||||
'--wait',
|
||||
'--timeout-ms',
|
||||
String(waitTimeoutMs),
|
||||
'--json'
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
ORCA_USER_DATA_PATH: userDataPath,
|
||||
ORCA_TERMINAL_HANDLE: 'term_nobody',
|
||||
ORCA_HEARTBEAT_INTERVAL_MS: String(heartbeatMs)
|
||||
},
|
||||
// Why: explicit pipe for all three fds so we can watch stderr
|
||||
// in real time; no TTY attached (Bash-tool parity).
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
}
|
||||
)
|
||||
|
||||
const stderrChunks: { at: number; data: string }[] = []
|
||||
const stdoutChunks: { at: number; data: string }[] = []
|
||||
const startedAt = Date.now()
|
||||
child.stderr.setEncoding('utf8')
|
||||
child.stdout.setEncoding('utf8')
|
||||
child.stderr.on('data', (d) => stderrChunks.push({ at: Date.now() - startedAt, data: d }))
|
||||
child.stdout.on('data', (d) => stdoutChunks.push({ at: Date.now() - startedAt, data: d }))
|
||||
|
||||
const exitCode = await new Promise<number>((resolveExit, rejectExit) => {
|
||||
child.once('exit', (code) => resolveExit(code ?? 1))
|
||||
child.once('error', rejectExit)
|
||||
})
|
||||
|
||||
expect(exitCode).toBe(0)
|
||||
|
||||
const stderr = stderrChunks.map((c) => c.data).join('')
|
||||
const stdout = stdoutChunks.map((c) => c.data).join('')
|
||||
|
||||
const heartbeatLines = stderr
|
||||
.split('\n')
|
||||
.filter((line) => line.trim().length > 0)
|
||||
.map((line) => {
|
||||
try {
|
||||
return JSON.parse(line) as Record<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})
|
||||
.filter((p): p is Record<string, unknown> => p !== null && p._heartbeat === true)
|
||||
|
||||
// ≥3 heartbeats in a 1.2s window with a 200ms interval
|
||||
expect(heartbeatLines.length).toBeGreaterThanOrEqual(3)
|
||||
expect(heartbeatLines[0]).toHaveProperty('elapsedMs')
|
||||
expect(heartbeatLines[0]).toHaveProperty('deadlineMs', waitTimeoutMs)
|
||||
|
||||
// Why: first heartbeat must arrive within one interval + scheduler
|
||||
// slack (300ms is generous); if the stream were fully buffered we'd
|
||||
// see everything only after exit.
|
||||
const firstHeartbeatChunk = stderrChunks.find((c) => c.data.includes('_heartbeat'))
|
||||
expect(firstHeartbeatChunk).toBeDefined()
|
||||
expect(firstHeartbeatChunk!.at).toBeLessThan(heartbeatMs + 300)
|
||||
|
||||
// Why: line-flushing proof — the *first* heartbeat chunk must arrive
|
||||
// strictly before the exit chunk; i.e. we got at least two separate
|
||||
// stderr data events (heartbeat + final). A single-chunk delivery
|
||||
// would indicate stderr was buffered until exit.
|
||||
const lastStderrAt = stderrChunks.at(-1)?.at ?? 0
|
||||
const firstStderrAt = stderrChunks.at(0)?.at ?? 0
|
||||
expect(lastStderrAt).toBeGreaterThan(firstStderrAt)
|
||||
|
||||
// Stdout: exactly one JSON payload, the terminal result. No heartbeats
|
||||
// leak, and the content parses as valid JSON.
|
||||
const stdoutTrimmed = stdout.trim()
|
||||
const stdoutPayload = JSON.parse(stdoutTrimmed) as Record<string, unknown>
|
||||
expect(stdoutPayload).not.toHaveProperty('_heartbeat')
|
||||
expect(stdoutTrimmed).not.toContain('_heartbeat')
|
||||
// Why: result should be an RPC success envelope with the expected
|
||||
// shape. `count: 0` and `messages: []` because the wait timed out
|
||||
// with no message for term_nobody.
|
||||
expect(stdoutPayload).toMatchObject({ ok: true })
|
||||
|
||||
// Why: the heartbeats-on-stderr design is meant to pair with shell
|
||||
// filters like `2>&1 | jq "select(._heartbeat|not)"`. jq is
|
||||
// line-oriented by default, but also accepts pretty-printed JSON
|
||||
// across multiple lines. What matters here is that every
|
||||
// heartbeat line on stderr is a standalone JSON object (so jq can
|
||||
// match it) and doesn't span multiple lines — assert that each
|
||||
// heartbeat is a single-line JSON with no embedded newlines.
|
||||
for (const line of stderr.split('\n')) {
|
||||
if (line.trim().length === 0) {
|
||||
continue
|
||||
}
|
||||
if (line.includes('_heartbeat')) {
|
||||
expect(() => JSON.parse(line)).not.toThrow()
|
||||
expect(line).not.toContain('\n')
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
await server.stop()
|
||||
}
|
||||
}, 30_000)
|
||||
})
|
||||
@@ -6,6 +6,7 @@ export {
|
||||
RuntimeClient,
|
||||
RuntimeClientError,
|
||||
RuntimeRpcFailureError,
|
||||
serveOrcaApp,
|
||||
getDefaultUserDataPath,
|
||||
type RuntimeRpcFailure,
|
||||
type RuntimeRpcResponse,
|
||||
|
||||
+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
|
||||
}
|
||||
}
|
||||
+27
-2
@@ -1,5 +1,6 @@
|
||||
import { isAbsolute, relative, resolve as resolvePath } from 'path'
|
||||
import type { ComputerAppQuery, RuntimeWorktreeListResult } from '../shared/runtime-types'
|
||||
import { isPathInsideOrEqual } from '../shared/cross-platform-path'
|
||||
import type { RuntimeClient } from './runtime-client'
|
||||
import { RuntimeClientError } from './runtime-client'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from './flags'
|
||||
@@ -26,7 +27,22 @@ export function normalizeWorktreeSelector(selector: string, cwd: string): string
|
||||
return selector
|
||||
}
|
||||
|
||||
function assertLocalCwdWorktreeSelector(selector: string, client: RuntimeClient): void {
|
||||
if (!client.isRemote) {
|
||||
return
|
||||
}
|
||||
// Why: a paired CLI's cwd belongs to the client machine, not the runtime
|
||||
// server, so cwd-derived worktree selectors are only valid locally.
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`${selector} is a local cwd shortcut and cannot be resolved against a remote runtime. Pass an explicit server-side worktree selector such as id:<id>, branch:<branch>, issue:<number>, or path:<absolute-server-path>.`
|
||||
)
|
||||
}
|
||||
|
||||
function isWithinPath(parentPath: string, childPath: string): boolean {
|
||||
if (isPathInsideOrEqual(parentPath, childPath)) {
|
||||
return true
|
||||
}
|
||||
const relativePath = relative(parentPath, childPath)
|
||||
return relativePath === '' || (!relativePath.startsWith('..') && !isAbsolute(relativePath))
|
||||
}
|
||||
@@ -35,6 +51,8 @@ export async function resolveCurrentWorktreeSelector(
|
||||
cwd: string,
|
||||
client: RuntimeClient
|
||||
): Promise<string> {
|
||||
assertLocalCwdWorktreeSelector('current', client)
|
||||
|
||||
const currentPath = resolvePath(cwd)
|
||||
const worktrees = await client.call<RuntimeWorktreeListResult>('worktree.list', {
|
||||
limit: 10_000
|
||||
@@ -68,6 +86,7 @@ export async function getOptionalWorktreeSelector(
|
||||
return undefined
|
||||
}
|
||||
if (value === 'active' || value === 'current') {
|
||||
assertLocalCwdWorktreeSelector(value, client)
|
||||
return await resolveCurrentWorktreeSelector(cwd, client)
|
||||
}
|
||||
return normalizeWorktreeSelector(value, cwd)
|
||||
@@ -81,13 +100,14 @@ export async function getRequiredWorktreeSelector(
|
||||
): Promise<string> {
|
||||
const value = getRequiredStringFlag(flags, name)
|
||||
if (value === 'active' || value === 'current') {
|
||||
assertLocalCwdWorktreeSelector(value, client)
|
||||
return await resolveCurrentWorktreeSelector(cwd, client)
|
||||
}
|
||||
return normalizeWorktreeSelector(value, cwd)
|
||||
}
|
||||
|
||||
// Why: browser commands default to the current worktree (auto-resolve from cwd).
|
||||
// --worktree all bypasses filtering. Omitting --worktree auto-resolves.
|
||||
// Why: local browser commands default to the current worktree by auto-resolving
|
||||
// from cwd. Remote commands omit worktree so the runtime uses server-side focus.
|
||||
export async function getBrowserWorktreeSelector(
|
||||
flags: Map<string, string | boolean>,
|
||||
cwd: string,
|
||||
@@ -99,10 +119,14 @@ export async function getBrowserWorktreeSelector(
|
||||
}
|
||||
if (value) {
|
||||
if (value === 'active' || value === 'current') {
|
||||
assertLocalCwdWorktreeSelector(value, client)
|
||||
return await resolveCurrentWorktreeSelector(cwd, client)
|
||||
}
|
||||
return normalizeWorktreeSelector(value, cwd)
|
||||
}
|
||||
if (client.isRemote) {
|
||||
return undefined
|
||||
}
|
||||
// Default: auto-resolve from cwd
|
||||
try {
|
||||
return await resolveCurrentWorktreeSelector(cwd, client)
|
||||
@@ -146,6 +170,7 @@ export async function getBrowserCommandTarget(
|
||||
return { page }
|
||||
}
|
||||
if (explicitWorktree === 'active' || explicitWorktree === 'current') {
|
||||
assertLocalCwdWorktreeSelector(explicitWorktree, client)
|
||||
return {
|
||||
page,
|
||||
worktree: await resolveCurrentWorktreeSelector(cwd, client)
|
||||
|
||||
@@ -9,6 +9,24 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
|
||||
allowedFlags: [...GLOBAL_FLAGS],
|
||||
examples: ['orca open', 'orca open --json']
|
||||
},
|
||||
{
|
||||
path: ['serve'],
|
||||
summary: 'Start an Orca runtime server without opening a desktop window',
|
||||
usage:
|
||||
'orca serve [--port <port>] [--pairing-address <host>] [--mobile-pairing] [--no-pairing] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'port', 'pairing-address', 'mobile-pairing', 'no-pairing'],
|
||||
notes: [
|
||||
'Runs in the foreground and prints the runtime endpoint. Stop it with Ctrl+C.',
|
||||
'Use --pairing-address when clients should connect through a LAN, Tailscale, SSH-forward, or public tunnel address.',
|
||||
'Use --mobile-pairing to print a mobile-scoped pairing QR/link instead of the default runtime-environment pairing link.'
|
||||
],
|
||||
examples: [
|
||||
'orca serve',
|
||||
'orca serve --json',
|
||||
'orca serve --port 6768 --pairing-address 100.64.1.20',
|
||||
'orca serve --pairing-address 100.64.1.20 --mobile-pairing'
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ['status'],
|
||||
summary: 'Show app/runtime/graph readiness',
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { CommandSpec } from '../args'
|
||||
import { GLOBAL_FLAGS } from '../args'
|
||||
|
||||
export const ENVIRONMENT_COMMAND_SPECS: CommandSpec[] = [
|
||||
{
|
||||
path: ['environment', 'add'],
|
||||
summary: 'Save a remote Orca runtime environment from a pairing code',
|
||||
usage: 'orca environment add --name <name> --pairing-code <code> [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'name'],
|
||||
examples: ['orca environment add --name work-laptop --pairing-code orca://pair#...']
|
||||
},
|
||||
{
|
||||
path: ['environment', 'list'],
|
||||
summary: 'List saved Orca runtime environments',
|
||||
usage: 'orca environment list [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS]
|
||||
},
|
||||
{
|
||||
path: ['environment', 'show'],
|
||||
summary: 'Show one saved Orca runtime environment',
|
||||
usage: 'orca environment show --environment <selector> [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS]
|
||||
},
|
||||
{
|
||||
path: ['environment', 'rm'],
|
||||
summary: 'Remove one saved Orca runtime environment',
|
||||
usage: 'orca environment rm --environment <selector> [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS]
|
||||
}
|
||||
]
|
||||
@@ -4,6 +4,7 @@ import { BROWSER_BASIC_COMMAND_SPECS } from './browser-basic'
|
||||
import { CORE_COMMAND_SPECS } from './core'
|
||||
import { ORCHESTRATION_COMMAND_SPECS } from './orchestration'
|
||||
import { COMPUTER_COMMAND_SPECS } from './computer'
|
||||
import { ENVIRONMENT_COMMAND_SPECS } from './environment'
|
||||
import { NOTE_COMMAND_SPECS } from './note'
|
||||
|
||||
export const COMMAND_SPECS: CommandSpec[] = [
|
||||
@@ -12,5 +13,6 @@ export const COMMAND_SPECS: CommandSpec[] = [
|
||||
...BROWSER_ADVANCED_COMMAND_SPECS,
|
||||
...ORCHESTRATION_COMMAND_SPECS,
|
||||
...COMPUTER_COMMAND_SPECS,
|
||||
...ENVIRONMENT_COMMAND_SPECS,
|
||||
...NOTE_COMMAND_SPECS
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user