feat(cli): add orca account add / account list for headless hosts (Claude + Codex) (#9177)

* feat(cli): add `orca account add` / `account list` for headless hosts

The desktop "Add account" UI is disabled when the renderer drives a remote
runtime (isRemoteAccountScope === kind:'environment'), so a headless server
reached from a remote desktop/web client has no way to register managed
Claude accounts. Add a host-local CLI path that reuses the existing capture
logic:

- ClaudeAccountService.addAccountFromConfigDir(): register a managed account by
  capturing credentials from an already-authenticated CLAUDE_CONFIG_DIR instead
  of spawning the interactive browser login (extracted persist/rollback helpers
  shared with the existing add flow)
- RPC accounts.addClaudeFromConfigDir, bridged via OrcaRuntime; rejected for
  mobile device tokens (host-local only)
- `orca account add` runs `claude login` in the user's own terminal into a temp
  CLAUDE_CONFIG_DIR, then registers it via the local runtime; `orca account list`
  lists managed accounts

Switching (select) already works from a remote client; only adding was blocked.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(cli): support Codex in `orca account add` / `account list`

Mirror the Claude headless-account CLI for Codex:

- CodexAccountService.addAccountFromHome(): register a managed Codex account by
  importing auth.json from an already-authenticated CODEX_HOME, reusing a shared
  persist helper extracted from doAddAccount (no interactive login spawned here)
- RPC accounts.addCodexFromHome + OrcaRuntime.addCodexAccountFromHome bridge,
  rejected for mobile device tokens (host-local only)
- `orca account add --agent claude|codex` (default claude); `orca account list`
  now renders both Claude and Codex managed-account blocks

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test: cover headless account-add capture paths (Claude + Codex)

- ClaudeAccountService.addAccountFromConfigDir: registers a managed account by
  capturing an authenticated CLAUDE_CONFIG_DIR; rejects and rolls back when the
  dir has no .credentials.json
- CodexAccountService.addAccountFromHome: imports auth.json from an
  authenticated CODEX_HOME into a managed account; rejects when auth.json is
  missing

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: address CodeRabbit review on headless account-add flows

- CLI login spawn uses a shell on Windows so `.cmd` agent shims resolve without
  ENOENT (args are fixed literals, no injection risk)
- Claude capture skips the `.credentials.json` precheck on macOS, where creds
  live in the Keychain and captureAuthFromConfigDir reads them
- Claude add rollback is best-effort: a failed rematerialization no longer skips
  managed-auth cleanup or masks the original add error
- Codex persist restores the prior account/selection if a post-write sync or
  rate-limit refresh fails, so a failure can't leave a dangling managed account
- Codex sync passes the account's selection target (correct runtime for WSL)
- Add JSDoc to the new public service methods and CLI functions

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(cli): harden headless account capture

* fix(cli): correct account command flag surface and interrupt cleanup

- `account` commands no longer accept or advertise the browser `--page`
  flag; `supportsBrowserPageFlag` allow-listed them by omission, so
  `orca account list --page x` was silently accepted and `--help`
  rendered a browser-only option
- account specs declare GLOBAL_FLAGS, so `--help`/`--json` render in the
  Options block like every other command
- `--agent` on `account add` documents the account provider instead of
  the terminal TUI-agent meaning inherited from the shared flag table
- a SIGINT/SIGTERM during the interactive login now removes the temp
  login dir (and restores the macOS Keychain item) before exiting 130;
  Node terminates without unwinding `finally`, which stranded live OAuth
  credentials on disk

* perf(cli): stop `account list` forcing a provider usage refresh

`accounts.list` awaited refreshAccountsForMobile(), which runs
fetchAll({ force: true }) — bypassing both the poll throttle and the
per-provider Retry-After gate — then O(N) serial per-account round
trips. `orca account list` renders only emails and the active ids, so
all of that work was discarded. The RPC now takes `refreshUsage`
(default true, so mobile and web keep the forced lane) and the CLI opts
out. Older hosts declare `params: null` and ignore the field, so a newer
CLI degrades to the previous behavior rather than failing.

Also documents on `account list` that `--environment` does not retarget
it, matching the host-local behavior of shouldIgnoreRemoteSelection.

* fix(cli): survive repeated and hangup signals during account add

withInterruptCleanup latched cleanup behind a boolean, so a second signal
got an already-resolved promise and its process.exit fired while the first
cleanup was still inside a Keychain call (3s each) — the temp dir's OAuth
credentials and the swapped macOS Keychain item both survived. Memoize the
cleanup promise so every signal awaits the same run, and register with
`on` instead of `once` so a second Ctrl-C cannot fall through to Node's
terminate-immediately default mid-cleanup.

Handle SIGHUP too. This flow exists for headless/SSH hosts, where the most
likely interrupt is the connection dropping, which hangs up the login's
terminal and previously ran no cleanup at all.

Warn when the interrupt lands after sign-in completed: the runtime finishes
the add independently of this process, so exiting 130 silently would tell
the user it was cancelled when the account may exist.

Reject a valueless `--agent`; the parser turns it into boolean true, which
silently ran a full OAuth login for Claude when the user asked for another
provider.

Also lock two behaviors the refactor changed but left uncovered: a WSL Codex
add must sync the WSL runtime lane rather than the default host lane, and
rename the account-spec help test to describe the Options block it actually
asserts rather than the usage string it never reads.

* fix(build): bundle the main modules the account CLI imports

electron-vite cleans out/main and emits only its declared entries, and
`build:desktop` runs it after `build:cli`, so the tsc-emitted copies of
`claude-accounts/keychain`, `codex-cli/command` and `win32-utils` were
deleted before packaging. Both `orca account add` and `orca account list`
then died at require time with "Cannot find module
'../../main/claude-accounts/keychain'" — reproduced against a real
`--serve` host. `agent-hooks/managed-agent-hook-controls` already carried
an entry for exactly this reason; these three were missing.

Adds a parity test so any future CLI import of a `src/main` module fails
in CI rather than at a user's shell after packaging.

* test: cover the desktop add-path behavior this PR changes

Both changes ride in the persist/rollback helpers the existing GUI add
flow shares with the new headless path, and neither had coverage:

- Claude: rollbackAddAccount now guards forceMaterializeCurrentSelection-
  ForRollback, so a rejecting rematerialization no longer replaces the
  real add error nor skips safeRemoveManagedAuth. Asserts the original
  error surfaces and the throwaway auth dir is gone.
- Codex: the desktop add now passes the account's selection target to
  syncForCurrentSelection, matching reauthenticate and select. Asserts
  the host target alongside the existing WSL assertion.

Both fail when the corresponding change is reverted.

* fix(cli): close the remaining account-add interrupt and preflight gaps

The round-1 interrupt fix detached the signal handlers before running the
finally-path cleanup, so the very window it was meant to protect — the two
serial 3s `security` calls plus rmSync on the success/error path — was
still covered only by Node's terminate-immediately default. Both review
lanes reproduced it independently. Await cleanup first, detach in a nested
finally, and stop a cleanup failure from replacing the error that actually
explains why the add failed.

Do not burn the interactive login when the runtime is unreachable. The
RuntimeClient is lazily constructed and the first call was the registration
RPC itself, so "Requires the Orca runtime to be running" was discovered
only after the user completed a full OAuth round trip. Preflight with the
now-cheap `accounts.list { refreshUsage: false }`.

Reject `--environment` / `--pairing-code` on `account add`.
shouldIgnoreRemoteSelection pins account commands to the local runtime, so
`orca account add --environment homelab` silently registered the account on
the laptop instead of the headless host it names.

Survive a daemon that cannot spawn `claude`. `allowFailure` is honored in
onClose but not onError, and unlike the GUI flow nothing has run `claude` in
the daemon before this point — so a launchd/systemd daemon with a minimal
PATH hard-failed an add the user had already signed in for, even though
identity resolves fine from the config dir's oauthAccount.

Also align the `--agent` help description with the global flag column.

* fix(cli): reject runtime selectors on `account list` too

`orca account list --environment homelab` was accepted and silently
listed the LOCAL machine's accounts, because shouldIgnoreRemoteSelection
pins account commands to the local runtime. Documenting that in --help
does not reach someone who already typed the flag, and answering with the
wrong host's accounts is the specific wrong answer they would act on.

`account add` already errors; this makes the new command group internally
consistent. The other groups in shouldIgnoreRemoteSelection keep their
existing silent-ignore behavior — changing those is not this PR's job.

* test: harden account-add signal tests and cover cleanup failure

- Identify the handler under test by set difference instead of
  `process.listeners(sig).at(-1)`. Vitest installs its own once-wrapped
  SIGINT teardown, so the positional lookup could grab the wrong listener;
  the helper also asserts exactly one new listener was added.
- Mock rmSync while keeping the real implementation by default, so the
  temp-dir assertions elsewhere stay honest.
- Cover that a cleanup failure in the `finally` does not replace the error
  explaining why the add failed. Fails when that guard is removed.

Completes the review loop's final round; the loop died on an API error
before it could commit this, and its `import()` type annotation would
have failed oxlint.

* fix(cli): harden interactive account add

* test(cli): make account cancellation coverage portable

* fix(cli): preserve merged skills runtime modules

---------

Co-authored-by: Dominik <marketing@gavaplast.sk>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
This commit is contained in:
Dominik Mery
2026-07-30 12:50:07 -07:00
committed by GitHub
co-authored by Dominik Claude Opus 4.8 Brennan Benson
parent 967edeb49a
commit 650dd48ec9
28 changed files with 2389 additions and 129 deletions
+5
View File
@@ -232,6 +232,11 @@ describe('supportsBrowserPageFlag', () => {
it('does not expose browser page targeting on local agent discovery', () => {
expect(supportsBrowserPageFlag(['agent-context'])).toBe(false)
})
it('does not expose browser page targeting on host-local account commands', () => {
expect(supportsBrowserPageFlag(['account', 'add'])).toBe(false)
expect(supportsBrowserPageFlag(['account', 'list'])).toBe(false)
})
})
describe('validateCommandAndFlags', () => {
+2
View File
@@ -152,6 +152,7 @@ export function supportsBrowserPageFlag(commandPath: string[]): boolean {
}
if (
[
'account',
'automations',
'project',
'repo',
@@ -198,6 +199,7 @@ export function isCommandGroup(commandPath: string[]): boolean {
return (
(commandPath.length === 1 &&
[
'account',
'automations',
'project',
'repo',
+5
View File
@@ -17,6 +17,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
keys: ['claude-teams', 'open', 'serve', 'status'],
load: async () => (await import('./handlers/core.js')).CORE_HANDLERS
},
{
name: 'account',
keys: ['account add', 'account list'],
load: async () => (await import('./handlers/account.js')).ACCOUNT_HANDLERS
},
{
name: 'automations',
keys: [
+565
View File
@@ -0,0 +1,565 @@
import { EventEmitter } from 'node:events'
import { createHash } from 'node:crypto'
import { existsSync } from 'node:fs'
import { delimiter } from 'node:path'
import type * as NodeFs from 'node:fs'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const {
deleteKeychainMock,
getVersionManagerBinPathsMock,
readKeychainMock,
resolveCliCommandMock,
rmSyncMock,
spawnMock,
writeKeychainMock
} = vi.hoisted(() => ({
deleteKeychainMock: vi.fn(),
getVersionManagerBinPathsMock: vi.fn(),
readKeychainMock: vi.fn(),
resolveCliCommandMock: vi.fn(),
rmSyncMock: vi.fn(),
spawnMock: vi.fn(),
writeKeychainMock: vi.fn()
}))
// Why: keep real temp-dir cleanup by default so leak assertions stay honest,
// while allowing deterministic Windows EBUSY coverage.
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof NodeFs>()
rmSyncMock.mockImplementation(actual.rmSync)
return { ...actual, rmSync: rmSyncMock }
})
vi.mock('node:child_process', () => ({
execFile: vi.fn(),
execFileSync: vi.fn(),
spawn: spawnMock
}))
vi.mock('../../main/claude-accounts/keychain', () => ({
deleteActiveClaudeKeychainCredentialsStrict: deleteKeychainMock,
readActiveClaudeKeychainCredentialsStrict: readKeychainMock,
writeActiveClaudeKeychainCredentials: writeKeychainMock
}))
vi.mock('../../main/codex-cli/command', () => ({
getVersionManagerBinPaths: getVersionManagerBinPathsMock,
resolveCliCommand: resolveCliCommandMock
}))
import { ACCOUNT_HANDLERS } from './account'
import type { HandlerContext } from '../dispatch'
import type { RuntimeClient } from '../runtime-client'
import { getCmdExePath } from '../../main/win32-utils'
import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY } from '../../shared/protocol-version'
function successfulChild(): EventEmitter {
const child = new EventEmitter()
queueMicrotask(() => child.emit('exit', 0))
return child
}
// Why: identify the handler under test by set difference, not by position —
// `.at(-1)` picks up any listener a later registration appends (vitest installs
// its own once-wrapped SIGINT teardown), which made assertions flake.
function newSignalListener(
signal: NodeJS.Signals,
before: readonly unknown[]
): (signal: NodeJS.Signals) => void {
const added = process.listeners(signal).filter((listener) => !before.includes(listener))
if (added.length !== 1) {
throw new Error(`Expected 1 new ${signal} listener, found ${added.length}`)
}
return added[0] as (signal: NodeJS.Signals) => void
}
function accountState(email: string) {
return {
accounts: [{ id: 'account-1', email }],
activeAccountId: 'account-1',
activeAccountIdsByRuntime: { host: 'account-1', wsl: {} }
}
}
describe('account CLI handlers', () => {
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
const originalElectronRunAsNode = process.env.ELECTRON_RUN_AS_NODE
const originalPathAlias = process.env.Path
const callMock = vi.fn()
const client = { call: callMock } as unknown as RuntimeClient
let logSpy: ReturnType<typeof vi.spyOn>
function context(agent: string, json = false): HandlerContext {
return {
client,
cwd: process.cwd(),
flags: new Map([['agent', agent]]),
json,
rawArgs: []
}
}
beforeEach(() => {
Object.defineProperty(process, 'platform', originalPlatform)
spawnMock.mockReset().mockImplementation(() => successfulChild())
resolveCliCommandMock.mockReset().mockImplementation((command: string) => command)
getVersionManagerBinPathsMock.mockReset().mockReturnValue([])
readKeychainMock.mockReset().mockResolvedValue(null)
deleteKeychainMock.mockReset().mockResolvedValue(undefined)
writeKeychainMock.mockReset().mockResolvedValue(undefined)
callMock.mockReset().mockImplementation((method: string) =>
Promise.resolve({
id: 'test',
ok: true,
result:
method === 'status.get'
? { capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY] }
: accountState(method.includes('Claude') ? 'claude@example.com' : 'codex@example.com'),
_meta: { runtimeId: 'test-runtime' }
})
)
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
process.env.ELECTRON_RUN_AS_NODE = '1'
})
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform)
logSpy.mockRestore()
if (originalElectronRunAsNode === undefined) {
delete process.env.ELECTRON_RUN_AS_NODE
} else {
process.env.ELECTRON_RUN_AS_NODE = originalElectronRunAsNode
}
if (originalPathAlias === undefined) {
delete process.env.Path
} else {
process.env.Path = originalPathAlias
}
})
it('uses Codex device auth and keeps JSON stdout clean', async () => {
await ACCOUNT_HANDLERS['account add'](context('codex', true))
expect(spawnMock).toHaveBeenCalledWith(
'codex',
['login', '--device-auth'],
expect.objectContaining({
stdio: ['inherit', process.stderr, 'inherit'],
env: expect.objectContaining({ CODEX_HOME: expect.any(String) })
})
)
const spawnOptions = spawnMock.mock.calls[0]?.[2]
expect(spawnOptions.env.ELECTRON_RUN_AS_NODE).toBeUndefined()
expect(existsSync(spawnOptions.env.CODEX_HOME)).toBe(false)
expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', {
sourceHome: spawnOptions.env.CODEX_HOME
})
})
it('routes Windows package-manager shims through the safe cmd launcher', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
resolveCliCommandMock.mockReturnValue('C:\\tools\\codex.cmd')
await ACCOUNT_HANDLERS['account add'](context('codex'))
expect(spawnMock).toHaveBeenCalledWith(
getCmdExePath(),
['/d', '/c', 'C:\\tools\\codex.cmd', 'login', '--device-auth'],
expect.objectContaining({ stdio: ['inherit', 'inherit', 'inherit'] })
)
})
it('adds version-manager Node paths to the login child environment', async () => {
const nodeBin = '/home/test/.nvm/versions/node/v22.0.0/bin'
getVersionManagerBinPathsMock.mockReturnValue([nodeBin])
await ACCOUNT_HANDLERS['account add'](context('codex'))
const path = spawnMock.mock.calls[0]?.[2].env.PATH as string
expect(path.split(delimiter)[0]).toBe(nodeBin)
})
it('updates the effective Windows PATH regardless of native environment casing', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
process.env.Path = 'C:\\stale'
const nodeBin = 'C:\\Users\\test\\.volta\\bin'
const effectivePathBefore = process.env.PATH ?? process.env.Path ?? ''
getVersionManagerBinPathsMock.mockReturnValue([nodeBin])
await ACCOUNT_HANDLERS['account add'](context('codex'))
const env = spawnMock.mock.calls[0]?.[2].env as NodeJS.ProcessEnv
const pathValues = Object.entries(env)
.filter(([key]) => key.toLowerCase() === 'path')
.map(([, value]) => value)
expect(pathValues).toContain(`${nodeBin}${delimiter}${effectivePathBefore}`)
})
it('removes scoped Claude credentials and restores the legacy Keychain item', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
readKeychainMock.mockResolvedValue('legacy-credentials')
await ACCOUNT_HANDLERS['account add'](context('claude'))
const configDir = spawnMock.mock.calls[0]?.[2].env.CLAUDE_CONFIG_DIR
expect(deleteKeychainMock).toHaveBeenCalledWith(configDir)
expect(writeKeychainMock).toHaveBeenCalledWith('legacy-credentials')
expect(callMock).toHaveBeenCalledWith('accounts.addClaudeFromConfigDir', {
configDir,
previousLegacyCredentialsSha256: createHash('sha256')
.update('legacy-credentials')
.digest('hex')
})
expect(existsSync(configDir)).toBe(false)
})
it('waits for physical child close before removing interrupted login credentials', async () => {
// Why: deleting first lets the still-live login recreate credentials afterward.
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
const kill = vi.fn()
const child = Object.assign(new EventEmitter(), { kill })
let codexHome = ''
spawnMock.mockImplementation((_command, _args, options: { env: Record<string, string> }) => {
codexHome = options.env.CODEX_HOME
return child
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
const listenersBefore = process.listeners('SIGINT')
const pending = ACCOUNT_HANDLERS['account add'](context('codex')).catch(() => {})
await vi.waitFor(() => expect(codexHome).not.toBe(''))
expect(existsSync(codexHome)).toBe(true)
newSignalListener('SIGINT', listenersBefore)('SIGINT')
await vi.waitFor(() => expect(kill).toHaveBeenCalledWith('SIGINT'))
expect(exitSpy).not.toHaveBeenCalled()
expect(existsSync(codexHome)).toBe(true)
child.emit('exit', 1)
child.emit('close', 1)
await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(130))
expect(existsSync(codexHome)).toBe(false)
expect(callMock).not.toHaveBeenCalledWith('accounts.addCodexFromHome', expect.anything())
await pending
exitSpy.mockRestore()
})
it('cleans up when an SSH hangup ends the login', async () => {
// Why: this flow targets headless/SSH hosts, where a dropped connection
// delivers SIGHUP — Node's default terminates without running cleanup.
Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' })
const child = Object.assign(new EventEmitter(), { kill: vi.fn() })
let codexHome = ''
spawnMock.mockImplementation((_command, _args, options: { env: Record<string, string> }) => {
codexHome = options.env.CODEX_HOME
return child
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
const listenersBefore = process.listeners('SIGHUP')
const pending = ACCOUNT_HANDLERS['account add'](context('codex')).catch(() => {})
await vi.waitFor(() => expect(codexHome).not.toBe(''))
newSignalListener('SIGHUP', listenersBefore)('SIGHUP')
await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGHUP'))
expect(exitSpy).not.toHaveBeenCalled()
expect(existsSync(codexHome)).toBe(true)
child.emit('exit', 1)
child.emit('close', 1)
await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(129))
expect(existsSync(codexHome)).toBe(false)
await pending
exitSpy.mockRestore()
})
it('waits for in-flight cleanup when a second signal arrives', async () => {
// Why: a boolean latch lets the second signal's process.exit fire while the
// first cleanup is still inside a Keychain call, stranding the credentials.
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
readKeychainMock.mockResolvedValue('legacy-credentials')
let releaseKeychainDelete: (() => void) | undefined
deleteKeychainMock.mockImplementationOnce(
() =>
new Promise<void>((resolvePromise) => {
releaseKeychainDelete = () => resolvePromise()
})
)
const child = Object.assign(new EventEmitter(), { kill: vi.fn() })
let configDir = ''
spawnMock.mockImplementation((_command, _args, options: { env: Record<string, string> }) => {
configDir = options.env.CLAUDE_CONFIG_DIR
return child
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
const sigintBefore = process.listeners('SIGINT')
const sigtermBefore = process.listeners('SIGTERM')
const pending = ACCOUNT_HANDLERS['account add'](context('claude')).catch(() => {})
await vi.waitFor(() => expect(configDir).not.toBe(''))
const onSigint = newSignalListener('SIGINT', sigintBefore)
const onSigterm = newSignalListener('SIGTERM', sigtermBefore)
// Why: `rawListeners` exposes the `once` wrapper, so this fails if the handler
// is registered with `once` — where a second Ctrl-C falls through to Node's
// default and kills the process mid-cleanup.
expect(process.rawListeners('SIGINT')).toContain(onSigint)
onSigint('SIGINT')
await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGINT'))
child.emit('exit', 1)
child.emit('close', 1)
await vi.waitFor(() => expect(deleteKeychainMock).toHaveBeenCalledWith(configDir))
onSigterm('SIGTERM')
await new Promise<void>((resolvePromise) => {
setImmediate(resolvePromise)
})
expect(exitSpy).not.toHaveBeenCalled()
expect(writeKeychainMock).not.toHaveBeenCalled()
expect(existsSync(configDir)).toBe(true)
releaseKeychainDelete?.()
await vi.waitFor(() => expect(exitSpy).toHaveBeenCalled())
expect(writeKeychainMock).toHaveBeenCalledWith('legacy-credentials')
expect(existsSync(configDir)).toBe(false)
expect(child.kill).toHaveBeenCalledOnce()
await pending
exitSpy.mockRestore()
})
it('warns that the account may already be registered when interrupted mid-RPC', async () => {
// Why: the runtime finishes the add independently of this process, so an
// interrupt after sign-in cannot honestly be reported as "not added".
const child = Object.assign(new EventEmitter(), { kill: vi.fn() })
spawnMock.mockImplementation(() => {
queueMicrotask(() => child.emit('exit', 0))
return child
})
// Why: only the registration RPC hangs — the preflight must still resolve.
callMock.mockImplementation((method: string) =>
method === 'status.get'
? Promise.resolve({
id: 'test',
ok: true,
result: { capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY] },
_meta: { runtimeId: 'test-runtime' }
})
: method === 'accounts.list'
? Promise.resolve({
id: 'test',
ok: true,
result: { claude: accountState('c@e.com'), codex: accountState('x@e.com') },
_meta: { runtimeId: 'test-runtime' }
})
: new Promise(() => {})
)
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never)
const listenersBefore = process.listeners('SIGINT')
void ACCOUNT_HANDLERS['account add'](context('codex')).catch(() => {})
await vi.waitFor(() =>
expect(callMock).toHaveBeenCalledWith('accounts.addCodexFromHome', expect.anything())
)
newSignalListener('SIGINT', listenersBefore)('SIGINT')
await vi.waitFor(() => expect(exitSpy).toHaveBeenCalledWith(130))
expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('may still have been registered'))
warnSpy.mockRestore()
exitSpy.mockRestore()
})
it('stays armed for signals until post-success cleanup finishes', async () => {
// Why: detaching the handlers before cleanup leaves the multi-second Keychain
// calls covered only by Node's default handling, which kills mid-cleanup.
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
readKeychainMock.mockResolvedValue('legacy-credentials')
let releaseKeychainDelete: (() => void) | undefined
deleteKeychainMock.mockImplementationOnce(
() =>
new Promise<void>((resolvePromise) => {
releaseKeychainDelete = () => resolvePromise()
})
)
const listenersBefore = process.listeners('SIGINT')
const pending = ACCOUNT_HANDLERS['account add'](context('claude'))
await vi.waitFor(() => expect(deleteKeychainMock).toHaveBeenCalled())
// Why: cleanup is still in flight here, so this add's guard must still be installed.
const handler = newSignalListener('SIGINT', listenersBefore)
releaseKeychainDelete?.()
await pending
expect(process.listeners('SIGINT')).not.toContain(handler)
})
it('fails before the login when the runtime is unreachable', async () => {
// Why: discovering a dead runtime after sign-in wastes a full OAuth round trip.
callMock.mockRejectedValue(new Error('runtime not running'))
await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow(
'runtime not running'
)
expect(callMock).toHaveBeenCalledWith('status.get')
expect(spawnMock).not.toHaveBeenCalled()
})
it('fails before login when the running runtime predates account imports', async () => {
callMock.mockResolvedValue({
id: 'test',
ok: true,
result: { capabilities: [] },
_meta: { runtimeId: 'test-runtime' }
})
await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow(
'runtime is too old'
)
expect(callMock).toHaveBeenCalledOnce()
expect(callMock).toHaveBeenCalledWith('status.get')
expect(spawnMock).not.toHaveBeenCalled()
})
it.each(['environment', 'pairing-code'])(
'rejects --%s instead of silently ignoring it',
async (flag) => {
// Why: account commands are pinned to the local runtime, so honoring these
// silently would register the account on the wrong host.
await expect(
ACCOUNT_HANDLERS['account add']({
...context('codex'),
flags: new Map<string, string | boolean>([
['agent', 'codex'],
[flag, 'homelab']
])
})
).rejects.toThrow(`\`--${flag}\` does not retarget`)
expect(spawnMock).not.toHaveBeenCalled()
}
)
it.each(['environment', 'pairing-code'])(
'rejects --%s on `account list` instead of listing the local host',
async (flag) => {
// Why: listing is read-only, but answering with the LOCAL machine's accounts
// when the user named a remote host is the specific wrong answer they'd act on.
await expect(
ACCOUNT_HANDLERS['account list']({
...context('claude'),
flags: new Map<string, string | boolean>([[flag, 'homelab']])
})
).rejects.toThrow(`\`--${flag}\` does not retarget`)
expect(callMock).not.toHaveBeenCalled()
}
)
it('keeps the original add error when cleanup also fails', async () => {
// Why: cleanup runs in a `finally`, so an unguarded rejection there replaces
// the error that actually explains why the add failed.
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
rmSyncMock.mockImplementationOnce(() => {
throw new Error('EBUSY: resource busy or locked')
})
callMock.mockImplementation((method: string) =>
method === 'status.get'
? Promise.resolve({
id: 'test',
ok: true,
result: { capabilities: [ACCOUNT_IMPORT_RUNTIME_CAPABILITY] },
_meta: { runtimeId: 'test-runtime' }
})
: method === 'accounts.list'
? Promise.resolve({
id: 'test',
ok: true,
result: { claude: accountState('c@e.com'), codex: accountState('x@e.com') },
_meta: { runtimeId: 'test-runtime' }
})
: Promise.reject(new Error('registration rejected by runtime'))
)
await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow(
'registration rejected by runtime'
)
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('Failed to clean up the temporary login directory'),
expect.any(Error)
)
warnSpy.mockRestore()
})
it('fails a successful add when the temporary credentials cannot be removed', async () => {
rmSyncMock.mockImplementationOnce(() => {
throw new Error('EBUSY: resource busy or locked')
})
await expect(ACCOUNT_HANDLERS['account add'](context('codex', true))).rejects.toThrow('EBUSY')
expect(logSpy).not.toHaveBeenCalled()
})
it('fails a successful Claude add when Keychain cleanup fails', async () => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
readKeychainMock.mockResolvedValue('legacy-credentials')
deleteKeychainMock.mockRejectedValueOnce(new Error('Keychain denied cleanup'))
await expect(ACCOUNT_HANDLERS['account add'](context('claude'))).rejects.toThrow(
'Failed to clean up Claude login artifacts'
)
expect(writeKeychainMock).toHaveBeenCalledWith('legacy-credentials')
})
it('rejects `--agent` with no value instead of defaulting to Claude', async () => {
// Why: the parser turns a valueless flag into boolean true, so a silent
// default would run a full OAuth login for the wrong provider.
await expect(
ACCOUNT_HANDLERS['account add']({ ...context('claude'), flags: new Map([['agent', true]]) })
).rejects.toThrow('Missing a value for --agent')
expect(spawnMock).not.toHaveBeenCalled()
})
it('marks an account selected for WSL as active in human output', async () => {
callMock.mockResolvedValue({
id: 'test',
ok: true,
result: {
claude: {
accounts: [{ id: 'claude-wsl', email: 'claude@example.com' }],
activeAccountId: null,
activeAccountIdsByRuntime: { host: null, wsl: { Ubuntu: 'claude-wsl' } }
},
codex: { accounts: [], activeAccountId: null }
},
_meta: { runtimeId: 'test-runtime' }
})
await ACCOUNT_HANDLERS['account list']({ ...context('claude'), flags: new Map() })
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('claude@example.com (active)'))
})
it('lists accounts without forcing a provider usage refresh', async () => {
// Why: the forced lane bypasses the poll throttle and costs one serial
// round-trip per managed account, and this output shows no usage numbers.
callMock.mockResolvedValue({
id: 'test',
ok: true,
result: {
claude: { accounts: [], activeAccountId: null },
codex: { accounts: [], activeAccountId: null }
},
_meta: { runtimeId: 'test-runtime' }
})
await ACCOUNT_HANDLERS['account list']({ ...context('claude'), flags: new Map() })
expect(callMock).toHaveBeenCalledWith('accounts.list', { refreshUsage: false })
})
})
+298
View File
@@ -0,0 +1,298 @@
import { spawn } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join } from 'node:path'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { stripElectronRunAsNode } from '../runtime/launch'
import {
deleteActiveClaudeKeychainCredentialsStrict,
readActiveClaudeKeychainCredentialsStrict,
writeActiveClaudeKeychainCredentials
} from '../../main/claude-accounts/keychain'
import { getVersionManagerBinPaths, resolveCliCommand } from '../../main/codex-cli/command'
import { getSpawnArgsForWindows } from '../../main/win32-utils'
import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY } from '../../shared/protocol-version'
import type { RuntimeStatus } from '../../shared/runtime-types'
import type { ClaudeRateLimitAccountsState, CodexRateLimitAccountsState } from '../../shared/types'
import {
type InteractiveLoginSession,
withInteractiveLoginCleanup
} from './interactive-login-interruption'
// Why: add returns just that provider's state; list returns the full snapshot.
type AccountsListSnapshot = {
claude: ClaudeRateLimitAccountsState
codex: CodexRateLimitAccountsState
}
// Why: Claude and Codex managed-account summaries both carry id+email+active id,
// so one formatter renders either provider's block.
type AccountsBlock = {
accounts: readonly { id: string; email: string }[]
activeAccountId: string | null
activeAccountIdsByRuntime?: {
host: string | null
wsl: Record<string, string | null>
}
}
/** Renders a provider's managed-account list as a human-readable block, marking the active account. */
function formatAccountsBlock(label: string, block: AccountsBlock): string {
if (block.accounts.length === 0) {
return `No managed ${label} accounts.`
}
const activeAccountIds = new Set([
block.activeAccountId,
block.activeAccountIdsByRuntime?.host,
...Object.values(block.activeAccountIdsByRuntime?.wsl ?? {})
])
const lines = block.accounts.map(
(account) => ` ${account.email}${activeAccountIds.has(account.id) ? ' (active)' : ''}`
)
return `Managed ${label} accounts (${block.accounts.length}):\n${lines.join('\n')}`
}
function addAgentNodePaths(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const pathKey =
process.platform === 'win32' && env.Path !== undefined && env.PATH === undefined
? 'Path'
: 'PATH'
const currentEntries = (env[pathKey] ?? '').split(delimiter).filter(Boolean)
const existing = new Set(currentEntries)
const missing = getVersionManagerBinPaths().filter((entry) => !existing.has(entry))
if (missing.length > 0) {
env[pathKey] = [...missing, ...currentEntries].join(delimiter)
}
return env
}
/**
* Runs the real agent login attached to the user's terminal so the OAuth
* URL/device-code prompt is visible and the code can be pasted back — the desktop
* GUI flow drives this via a browser Orca can't reach on a headless host.
*/
async function runAgentLoginInTerminal(
command: string,
args: string[],
extraEnv: Record<string, string>,
json: boolean,
session: InteractiveLoginSession
): Promise<void> {
await new Promise<void>((resolvePromise, rejectPromise) => {
const resolvedCommand = resolveCliCommand(command)
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(resolvedCommand, args)
const env = addAgentNodePaths({ ...stripElectronRunAsNode(process.env), ...extraEnv })
const child = spawn(spawnCmd, spawnArgs, {
// Why: JSON mode reserves stdout for the response envelope while keeping
// the interactive login attached to the user's terminal via stderr.
stdio: ['inherit', json ? process.stderr : 'inherit', 'inherit'],
env
})
session.child = child
child.once('error', (error) =>
rejectPromise(
new RuntimeClientError(
'internal',
`Could not launch \`${command}\`. Is it installed and on PATH? (${
error instanceof Error ? error.message : String(error)
})`
)
)
)
child.once('exit', (code) => {
session.child = null
if (code === 0) {
resolvePromise()
return
}
rejectPromise(
new RuntimeClientError(
'internal',
`\`${command} ${args.join(' ')}\` exited with code ${code ?? 'null'}.`
)
)
})
})
}
async function cleanupClaudeLoginArtifacts(
configDir: string,
legacyCredentials: string | null,
restoreLegacyCredentials: boolean
): Promise<void> {
const errors: unknown[] = []
if (process.platform === 'darwin') {
try {
await deleteActiveClaudeKeychainCredentialsStrict(configDir)
} catch (error) {
errors.push(error)
}
if (restoreLegacyCredentials) {
try {
await (legacyCredentials
? writeActiveClaudeKeychainCredentials(legacyCredentials)
: deleteActiveClaudeKeychainCredentialsStrict())
} catch (error) {
errors.push(error)
}
}
}
try {
rmSync(configDir, { recursive: true, force: true })
} catch (error) {
errors.push(error)
}
if (errors.length > 0) {
throw new AggregateError(errors, 'Failed to clean up Claude login artifacts.')
}
}
/** Logs into a Claude account in a temp config dir, then registers it with the local runtime. */
async function addClaudeAccount({ client, json }: HandlerContext): Promise<void> {
const configDir = mkdtempSync(join(tmpdir(), 'orca-account-add-claude-'))
const session: InteractiveLoginSession = {
child: null,
registering: false,
terminationPromise: null
}
let legacyCredentials: string | null = null
let restoreLegacyCredentials = false
const result = await withInteractiveLoginCleanup(
session,
async () => {
await cleanupClaudeLoginArtifacts(configDir, legacyCredentials, restoreLegacyCredentials)
},
async () => {
if (process.platform === 'darwin') {
legacyCredentials = await readActiveClaudeKeychainCredentialsStrict()
restoreLegacyCredentials = true
}
await runAgentLoginInTerminal(
'claude',
['auth', 'login', '--claudeai'],
{
CLAUDE_CONFIG_DIR: configDir
},
json,
session
)
session.registering = true
return client.call<ClaudeRateLimitAccountsState>('accounts.addClaudeFromConfigDir', {
configDir,
...(process.platform === 'darwin'
? {
previousLegacyCredentialsSha256: legacyCredentials
? createHash('sha256').update(legacyCredentials).digest('hex')
: null
}
: {})
})
}
)
printResult(result, json, (state) => formatAccountsBlock('Claude', state))
}
/** Logs into a Codex account in a temp CODEX_HOME, then registers it with the local runtime. */
async function addCodexAccount({ client, json }: HandlerContext): Promise<void> {
const codexHome = mkdtempSync(join(tmpdir(), 'orca-account-add-codex-'))
const session: InteractiveLoginSession = {
child: null,
registering: false,
terminationPromise: null
}
const result = await withInteractiveLoginCleanup(
session,
async () => {
rmSync(codexHome, { recursive: true, force: true })
},
async () => {
// Why: plain OAuth binds a loopback callback the user's browser cannot reach
// on a headless/SSH host; device auth is explicitly designed for this flow.
await runAgentLoginInTerminal(
'codex',
['login', '--device-auth'],
{ CODEX_HOME: codexHome },
json,
session
)
session.registering = true
return client.call<CodexRateLimitAccountsState>('accounts.addCodexFromHome', {
sourceHome: codexHome
})
}
)
printResult(result, json, (state) => formatAccountsBlock('Codex', state))
}
/**
* Rejects the runtime-selector flags instead of ignoring them. shouldIgnoreRemoteSelection
* pins account commands to the local runtime, so honoring `--environment homelab`
* silently would target the laptop rather than the host the user named — the exact
* mistake this feature exists to avoid. A `--help` note does not reach someone who
* already typed the flag.
*/
function rejectRemoteSelectionFlags(ctx: HandlerContext, command: string): void {
for (const flag of ['environment', 'pairing-code']) {
if (ctx.flags.has(flag)) {
throw new RuntimeClientError(
'invalid_argument',
`\`--${flag}\` does not retarget \`${command}\`. Run it on the host whose accounts you want to manage.`
)
}
}
}
async function assertAccountImportSupported({ client }: HandlerContext): Promise<void> {
const status = await client.call<RuntimeStatus>('status.get')
if (!status.result.capabilities?.includes(ACCOUNT_IMPORT_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'The running Orca runtime is too old to add accounts from the CLI. Update or restart Orca and try again.'
)
}
}
/** CLI handlers for `orca account add [--agent claude|codex]` and `orca account list`. */
export const ACCOUNT_HANDLERS: Record<string, CommandHandler> = {
'account add': async (ctx) => {
const agentFlag = ctx.flags.get('agent')
// Why: a valueless `--agent` parses as boolean true; defaulting it to claude
// would silently run a full OAuth login for the provider the user did not ask for.
if (agentFlag !== undefined && typeof agentFlag !== 'string') {
throw new RuntimeClientError(
'invalid_argument',
'Missing a value for --agent. Use `--agent claude` or `--agent codex`.'
)
}
const agent = agentFlag ?? 'claude'
if (agent !== 'claude' && agent !== 'codex') {
throw new RuntimeClientError(
'invalid_argument',
`Unsupported --agent "${agent}". Use "claude" or "codex".`
)
}
rejectRemoteSelectionFlags(ctx, 'orca account add')
// Why: fail on runtime version skew before burning a full OAuth round trip.
await assertAccountImportSupported(ctx)
await ctx.client.call('accounts.list', { refreshUsage: false })
await (agent === 'claude' ? addClaudeAccount(ctx) : addCodexAccount(ctx))
},
'account list': async (ctx) => {
rejectRemoteSelectionFlags(ctx, 'orca account list')
const { client, json } = ctx
// Why: this command renders no usage numbers, so skip the forced provider
// refresh — it is one serial network round-trip per managed account.
const result = await client.call<AccountsListSnapshot>('accounts.list', {
refreshUsage: false
})
printResult(
result,
json,
(snapshot) =>
`${formatAccountsBlock('Claude', snapshot.claude)}\n\n${formatAccountsBlock('Codex', snapshot.codex)}`
)
}
}
@@ -0,0 +1,121 @@
import { EventEmitter } from 'node:events'
import type { ChildProcess } from 'node:child_process'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
LOGIN_PROCESS_CLOSE_FALLBACK_MS,
LOGIN_PROCESS_POSIX_GRACE_MS,
terminateInteractiveLoginProcess,
terminateWindowsLoginProcessTree,
WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS
} from './interactive-login-interruption'
function loginChild(pid = 4321): ChildProcess & EventEmitter {
return Object.assign(new EventEmitter(), {
kill: vi.fn(),
pid
}) as unknown as ChildProcess & EventEmitter
}
afterEach(() => {
vi.useRealTimers()
})
describe('terminateInteractiveLoginProcess', () => {
it('runs bounded taskkill /T /F without a shell', async () => {
const execFileImpl = vi.fn(
(
_command: string,
_args: readonly string[],
_options: { timeout?: number; windowsHide?: boolean },
callback: (error: Error | null) => void
) => callback(null)
)
await terminateWindowsLoginProcessTree(4321, execFileImpl as never)
expect(execFileImpl).toHaveBeenCalledWith(
'taskkill',
['/pid', '4321', '/T', '/F'],
{ timeout: WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS, windowsHide: true },
expect.any(Function)
)
})
it('waits for both Windows tree termination and physical wrapper close', async () => {
const child = loginChild()
let finishTreeKill: (() => void) | undefined
const killWindowsTree = vi.fn(
() =>
new Promise<void>((resolve) => {
finishTreeKill = resolve
})
)
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGTERM', {
platform: 'win32',
killWindowsTree
}).then(() => {
terminated = true
})
expect(killWindowsTree).toHaveBeenCalledWith(4321)
child.emit('close', 1)
await Promise.resolve()
expect(terminated).toBe(false)
finishTreeKill?.()
await pending
expect(child.kill).not.toHaveBeenCalled()
})
it('bounds Windows close waits and falls back to the direct wrapper', async () => {
vi.useFakeTimers()
const child = loginChild()
const pending = terminateInteractiveLoginProcess(child, 'SIGINT', {
platform: 'win32',
killWindowsTree: vi.fn().mockResolvedValue(undefined)
})
await vi.advanceTimersByTimeAsync(LOGIN_PROCESS_CLOSE_FALLBACK_MS)
expect(child.kill).toHaveBeenCalledOnce()
expect(child.kill).toHaveBeenCalledWith(undefined)
await vi.advanceTimersByTimeAsync(LOGIN_PROCESS_CLOSE_FALLBACK_MS)
await pending
})
it('forwards the interrupt signal to a direct POSIX child and awaits close', async () => {
const child = loginChild()
let terminated = false
const pending = terminateInteractiveLoginProcess(child, 'SIGHUP', {
platform: 'linux'
}).then(() => {
terminated = true
})
expect(child.kill).toHaveBeenCalledWith('SIGHUP')
await Promise.resolve()
expect(terminated).toBe(false)
child.emit('close', 1)
await pending
expect(child.kill).toHaveBeenCalledOnce()
})
it('force-kills an unresponsive POSIX child before the final bounded wait', async () => {
vi.useFakeTimers()
const child = loginChild()
const pending = terminateInteractiveLoginProcess(child, 'SIGINT', {
platform: 'darwin'
})
await vi.advanceTimersByTimeAsync(LOGIN_PROCESS_POSIX_GRACE_MS)
expect(child.kill).toHaveBeenNthCalledWith(1, 'SIGINT')
expect(child.kill).toHaveBeenNthCalledWith(2, 'SIGKILL')
await vi.advanceTimersByTimeAsync(LOGIN_PROCESS_CLOSE_FALLBACK_MS)
await pending
})
})
@@ -0,0 +1,184 @@
import { execFile, type ChildProcess } from 'node:child_process'
export const LOGIN_PROCESS_POSIX_GRACE_MS = 5_000
export const LOGIN_PROCESS_CLOSE_FALLBACK_MS = 1_000
export const WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS = 5_000
type WindowsTreeKiller = (rootPid: number) => Promise<void>
type TerminationDependencies = {
platform?: NodeJS.Platform
killWindowsTree?: WindowsTreeKiller
posixGraceMs?: number
closeFallbackMs?: number
}
export type InteractiveLoginSession = {
child: ChildProcess | null
registering: boolean
terminationPromise: Promise<void> | null
}
const INTERRUPT_EXIT_CODES: Record<string, number> = { SIGHUP: 129, SIGINT: 130, SIGTERM: 143 }
const INTERRUPT_SIGNALS = Object.keys(INTERRUPT_EXIT_CODES) as NodeJS.Signals[]
function waitForClose(closePromise: Promise<void>, timeoutMs: number): Promise<boolean> {
let timer: NodeJS.Timeout | undefined
return Promise.race([
closePromise.then(() => true),
new Promise<false>((resolve) => {
timer = setTimeout(() => resolve(false), timeoutMs)
})
]).finally(() => {
if (timer) {
clearTimeout(timer)
}
})
}
function killDirectChild(child: ChildProcess, signal?: NodeJS.Signals): void {
try {
child.kill(signal)
} catch {
// The child may close between the timeout and fallback signal.
}
}
export function terminateWindowsLoginProcessTree(
rootPid: number,
execFileImpl: typeof execFile = execFile
): Promise<void> {
if (!Number.isInteger(rootPid) || rootPid <= 0) {
return Promise.resolve()
}
return new Promise((resolve) => {
execFileImpl(
'taskkill',
['/pid', String(rootPid), '/T', '/F'],
{ timeout: WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS, windowsHide: true },
() => resolve()
)
})
}
/**
* Stops an interrupted interactive login before its credential directory is removed.
* The final close wait is bounded because a broken child handle must not hang Ctrl-C.
*/
export async function terminateInteractiveLoginProcess(
child: ChildProcess,
signal: NodeJS.Signals,
deps: TerminationDependencies = {}
): Promise<void> {
let closed = false
let resolveClose: (() => void) | undefined
const onClose = (): void => {
closed = true
resolveClose?.()
}
const closePromise = new Promise<void>((resolve) => {
resolveClose = resolve
})
child.once('close', onClose)
const platform = deps.platform ?? process.platform
const closeFallbackMs = deps.closeFallbackMs ?? LOGIN_PROCESS_CLOSE_FALLBACK_MS
try {
if (platform === 'win32') {
if (child.pid) {
const killTree = deps.killWindowsTree ?? terminateWindowsLoginProcessTree
await killTree(child.pid).catch(() => {})
if (closed || (await waitForClose(closePromise, closeFallbackMs))) {
return
}
}
killDirectChild(child)
if (closed) {
return
}
await waitForClose(closePromise, closeFallbackMs)
return
}
killDirectChild(child, signal)
const posixGraceMs = deps.posixGraceMs ?? LOGIN_PROCESS_POSIX_GRACE_MS
if (closed || (await waitForClose(closePromise, posixGraceMs))) {
return
}
killDirectChild(child, 'SIGKILL')
await waitForClose(closePromise, closeFallbackMs)
} finally {
child.off('close', onClose)
}
}
/**
* Runs an account add with signal-safe cleanup and primary-error precedence.
*/
export async function withInteractiveLoginCleanup<T>(
session: InteractiveLoginSession,
cleanup: () => Promise<void>,
add: () => Promise<T>
): Promise<T> {
let cleanupPromise: Promise<void> | null = null
let cleanupFailureReported = false
const cleanupOnce = (): Promise<void> =>
(cleanupPromise ??= (async () => {
await session.terminationPromise
await cleanup()
})())
const reportCleanupFailure = (error: unknown): void => {
if (cleanupFailureReported) {
return
}
cleanupFailureReported = true
console.warn('[account] Failed to clean up the temporary login directory:', error)
}
const onSignal = (signal: NodeJS.Signals): void => {
if (session.child) {
session.terminationPromise ??= terminateInteractiveLoginProcess(session.child, signal)
}
if (session.registering) {
console.warn(
'[account] Interrupted after sign-in completed; the account may still have been registered. Run `orca account list` to check.'
)
}
void cleanupOnce()
.catch(reportCleanupFailure)
.finally(() => process.exit(INTERRUPT_EXIT_CODES[signal] ?? 1))
}
// Why: repeated signals must keep awaiting the same cleanup instead of restoring Node defaults.
for (const signal of INTERRUPT_SIGNALS) {
process.on(signal, onSignal)
}
let addFailed = false
let addError: unknown
let addResult: { value: T } | null = null
try {
addResult = { value: await add() }
} catch (error) {
addFailed = true
addError = error
}
let cleanupError: unknown
try {
await cleanupOnce()
} catch (error) {
cleanupError = error
} finally {
for (const signal of INTERRUPT_SIGNALS) {
process.off(signal, onSignal)
}
}
if (addFailed) {
if (cleanupError !== undefined) {
// Why: retain the error that explains the failed account add.
reportCleanupFailure(cleanupError)
}
throw addError
}
if (cleanupError !== undefined) {
throw cleanupError
}
return addResult!.value
}
+11
View File
@@ -18,6 +18,10 @@ Diagnostics:
Agent Discovery:
agent-context Print the machine-readable command schema for agents
Accounts:
account add Add a managed Claude or Codex account on this Orca host
account list List managed Claude and Codex accounts on this Orca host
Skills:
skills list List version-matched skill guides bundled with this Orca CLI
skills get Print a version-matched skill guide as Markdown
@@ -214,6 +218,8 @@ Common Commands:
orca status [--json]
orca diagnostics memory [--json]
orca agent-context [--json]
orca account add [--agent claude|codex] [--json]
orca account list [--json]
orca environment add --name <name> --pairing-code <code> [--json]
orca environment list [--json]
orca environment show --environment <selector> [--json]
@@ -486,6 +492,11 @@ function formatCommandFlagHelp(flag: string, commandPath: string[]): string {
if (command === 'orchestration task-create' && flag === 'display-name') {
return '--display-name <text> UI label shown for dispatched worker rows'
}
// Why: the shared --agent help describes launching a TUI agent in a terminal,
// which is the wrong meaning here — this selects the account provider.
if (command === 'account add' && flag === 'agent') {
return '--agent <id> Account provider: claude or codex (default claude)'
}
if (flag === 'key' && command === 'computer hotkey') {
return '--key <key-combo> Modifier chord with one key, e.g. CmdOrCtrl+A'
}
+14
View File
@@ -306,6 +306,20 @@ describe('orca root help', () => {
logSpy.mockRestore()
})
it('advertises host-local account management', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
await main([], '/tmp/repo')
expect(logSpy.mock.calls.flat().join('\n')).toContain(
'account add Add a managed Claude or Codex account on this Orca host'
)
expect(logSpy.mock.calls.flat().join('\n')).toContain(
'account list List managed Claude and Codex accounts on this Orca host'
)
logSpy.mockRestore()
})
it('advertises computer-use capabilities discovery', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+1
View File
@@ -21,6 +21,7 @@ const COMMAND_PATHS = COMMAND_SPECS.flatMap((spec) => specPaths(spec))
function shouldIgnoreRemoteSelection(commandPath: string[]): boolean {
return (
commandPath[0] === 'account' ||
commandPath[0] === 'environment' ||
commandPath[0] === 'serve' ||
commandPath[0] === 'agent' ||
+58
View File
@@ -0,0 +1,58 @@
import { readFileSync, readdirSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
const REPO_ROOT = resolve(__dirname, '..', '..')
const CLI_ROOT = join(REPO_ROOT, 'src', 'cli')
function listCliSourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const path = join(dir, entry.name)
if (entry.isDirectory()) {
return listCliSourceFiles(path)
}
return entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts')
? [path]
: []
})
}
// Why: `import type` is erased by tsc, so it needs no emitted module at runtime.
const VALUE_IMPORT_FROM_MAIN = /(?<!\btype\s)from '\.\.\/\.\.\/main\/([^']+)'/g
function findMainImports(): { file: string; module: string }[] {
return listCliSourceFiles(CLI_ROOT).flatMap((file) => {
const source = readFileSync(file, 'utf-8')
return [...source.matchAll(VALUE_IMPORT_FROM_MAIN)].map((match) => ({
file: file.slice(REPO_ROOT.length + 1),
module: match[1]
}))
})
}
function findElectronViteMainEntries(): Set<string> {
const config = readFileSync(join(REPO_ROOT, 'electron.vite.config.ts'), 'utf-8')
return new Set(
// Why: entries wrap across lines once the path is long, so allow whitespace.
[...config.matchAll(/resolve\(\s*'src\/main\/([^']+)\.ts'\s*\)/g)].map((match) => match[1])
)
}
describe('CLI imports of main-process modules', () => {
// Why: electron-vite cleans out/main and emits only its declared entries, so a
// `src/main/*` module the CLI imports but the config omits is deleted by the
// build that runs after `build:cli` — the command then dies at require time
// with "Cannot find module". Nothing else catches this before packaging.
it('has an electron-vite entry for every main module the CLI imports', () => {
const entries = findElectronViteMainEntries()
const missing = findMainImports().filter(({ module }) => !entries.has(module))
expect(missing).toEqual([])
})
it('finds the imports it is meant to guard', () => {
// Why: a broken matcher would make the guard above vacuously pass.
expect(findMainImports().length).toBeGreaterThanOrEqual(4)
expect(findElectronViteMainEntries().size).toBeGreaterThanOrEqual(4)
})
})
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest'
import { ACCOUNT_COMMAND_SPECS } from './account'
import { effectiveAllowedFlags } from '../args'
import { formatCommandHelp } from '../help'
function spec(path: string): (typeof ACCOUNT_COMMAND_SPECS)[number] {
const found = ACCOUNT_COMMAND_SPECS.find((entry) => entry.path.join(' ') === path)
if (!found) {
throw new Error(`Missing account spec: ${path}`)
}
return found
}
describe('account command specs', () => {
it('does not accept or advertise browser page targeting', () => {
for (const entry of ACCOUNT_COMMAND_SPECS) {
expect(effectiveAllowedFlags(entry)).not.toContain('page')
expect(formatCommandHelp(entry)).not.toContain('--page')
}
})
// Why: named for what it asserts — the rendered Options block, not the `usage`
// string, which this test never reads.
it('renders --json and --help in its Options block', () => {
for (const entry of ACCOUNT_COMMAND_SPECS) {
const help = formatCommandHelp(entry)
expect(help).toContain('--json')
expect(help).toContain('--help')
}
})
it('describes --agent as the account provider, not a terminal agent', () => {
const help = formatCommandHelp(spec('account add'))
expect(help).toContain('Account provider: claude or codex (default claude)')
expect(help).not.toContain('TUI agent')
})
it('aligns the --agent description with the global flag descriptions', () => {
const descriptionColumn = (help: string, flag: string): number => {
const line = help.split('\n').find((entry) => entry.startsWith(` --${flag}`))
const match = line?.match(/^(\s*--\S+(?: <[^>]+>)?)(\s+)\S/)
if (!match) {
throw new Error(`No description found for --${flag}`)
}
return match[1].length + match[2].length
}
const help = formatCommandHelp(spec('account add'))
expect(descriptionColumn(help, 'agent')).toBe(descriptionColumn(help, 'json'))
})
})
+32
View File
@@ -0,0 +1,32 @@
import { GLOBAL_FLAGS, type CommandSpec } from '../args'
// Why: the desktop "Add account" button is disabled when the UI drives a remote
// runtime (a headless server). These commands run the interactive agent login
// (`claude login` / `codex login`) in the caller's own terminal on the host and
// register the captured account with the local runtime, giving headless hosts a
// way to manage Claude and Codex accounts.
export const ACCOUNT_COMMAND_SPECS: CommandSpec[] = [
{
path: ['account', 'add'],
summary: 'Add a managed Claude or Codex account by signing in on this Orca host',
usage: 'orca account add [--agent claude|codex] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'agent'],
notes: [
'Runs the agent login (`claude login` / `codex login`) in this terminal, then registers the account with the local Orca runtime.',
'Codex uses device authorization so the browser can complete sign-in from a different machine.',
'Sign in with the account you want to add (e.g. use a private/incognito browser window for a second account).',
'--agent defaults to claude. Requires the Orca runtime to be running on this machine.'
],
examples: ['orca account add', 'orca account add --agent codex']
},
{
path: ['account', 'list'],
summary: 'List managed Claude and Codex accounts on this Orca host',
usage: 'orca account list [--json]',
allowedFlags: [...GLOBAL_FLAGS],
notes: [
'Lists the accounts on this machine. `--environment` / `--pairing-code` are rejected rather than ignored; run it on the host whose accounts you want to see.'
],
examples: ['orca account list']
}
]
+2
View File
@@ -1,4 +1,5 @@
import type { CommandSpec } from '../args'
import { ACCOUNT_COMMAND_SPECS } from './account'
import { BROWSER_ADVANCED_COMMAND_SPECS } from './browser-advanced'
import { BROWSER_BASIC_COMMAND_SPECS } from './browser-basic'
import { AUTOMATION_COMMAND_SPECS } from './automations'
@@ -18,6 +19,7 @@ import { SKILL_COMMAND_SPECS } from './skills'
export const COMMAND_SPECS: CommandSpec[] = [
...CORE_COMMAND_SPECS,
...ACCOUNT_COMMAND_SPECS,
...PROJECT_COMMAND_SPECS,
...FILE_COMMAND_SPECS,
...AUTOMATION_COMMAND_SPECS,