Repository navigation
feat(cli): add orca account add / account list for headless hosts (Claude + Codex) - #9177
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Claude and Codex account import services that capture authenticated provider state, persist managed accounts, synchronize runtime selection, and roll back failed registrations. Exposes host-only runtime and RPC methods for importing provider configuration. Adds 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
src/cli/specs/account.ts (1)
10-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove manual
GLOBAL_FLAGSspreading inallowedFlags.Based on learnings, the CLI uses a shared
effectiveAllowedFlags(spec)helper to mergeGLOBAL_FLAGSwith a command'sallowedFlags. Manually spreadingGLOBAL_FLAGShere is redundant and circumvents the unified flag resolution pattern. Specify only the command-specific flags inallowedFlags.♻️ Proposed fix
{ 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'], + allowedFlags: ['agent'], notes: [ 'Runs the agent login (`claude login` / `codex login`) in this terminal, then registers the account with the local Orca runtime.', '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], + allowedFlags: [], examples: ['orca account list'] }Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 89b897c0-1b98-45d9-9377-82c3ab6f82a2
📥 Commits
Reviewing files that changed from the base of the PR and between 44686f3 and 84e4408a2c7f992c5299bce51a022213203650cd.
📒 Files selected for processing (12)
src/cli/args.tssrc/cli/dispatch.tssrc/cli/handlers/account.tssrc/cli/index.tssrc/cli/specs/account.tssrc/cli/specs/index.tssrc/main/claude-accounts/service.test.tssrc/main/claude-accounts/service.tssrc/main/codex-accounts/service.test.tssrc/main/codex-accounts/service.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/accounts.ts
|
Taking a look! |
|
Thanks for the contribution — I took this over and pushed a maintainer pass onto the PR branch. I rebased it onto current main and kept the core temporary-home capture design, while making the headless flow production-safe: Codex now uses device authorization; paired mobile/remote-runtime clients cannot submit host credential paths; Windows uses Orca’s existing command resolver instead of enabling a shell; JSON output stays machine-readable; temporary macOS Keychain state is cleaned up and restored; and failed Codex activation restores both settings and runtime selection. I also applied the flag-registration and portable-temp-path nits, fixed WSL active-account formatting, and added focused CLI/RPC/service coverage; 280 relevant tests, full typecheck, touched-file lint, and the max-lines ratchet all pass. |
|
Thanks for this — the headless gap is real, and capturing credentials from an already-authenticated config dir is the right shape for it. I confirmed the premise before touching anything: the desktop Add button calls a local Electron IPC, so un-gating it for remote scopes would have registered the account against the wrong machine. There's no existing remote add path to reuse. I rebased onto latest main (the branch was 411 commits behind and conflicting) and pushed fixes. In severity order: Packaging — both new commands were broken in a real build. Interrupted login stranded live OAuth tokens on disk. Node terminates on SIGINT without unwinding
Flag surface. Rebase conflict worth flagging: main had moved the Codex post-add quota probe to a background call, because it can take 10-25s and must never block or fail an already-durable account write. The extracted Also added coverage for the two desktop-flow behaviour changes that ride in the shared persist/rollback helpers — the guarded rollback rematerialization on the Claude side, and passing the account's selection target to Verified on an isolated headless |
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) <[email protected]>
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) <[email protected]>
- 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) <[email protected]>
- 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) <[email protected]>
- `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
`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.
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.
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.
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.
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.
`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.
- 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
electron.vite.config.ts (1)
278-282: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueKeep this configuration comment concise.
Proposed change
- // Why: the pop-out dashboard is a second top-level window with its own - // React root. It gets its own HTML entry so it can boot independently of - // the main window while reusing the same preload/window.api. `index` must - // stay listed — overriding input otherwise drops electron-vite's default - // renderer entry. + // Keep `index`; overriding input otherwise drops electron-vite's default renderer entry.As per coding guidelines, comments must be concise and limited to non-obvious information.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3ca2c337-38be-457c-acd4-1e9d5ac3fcef
📥 Commits
Reviewing files that changed from the base of the PR and between 5fb74081ca7d294d95266bc63125fd06e01ebbe7 and 935a73c.
📒 Files selected for processing (2)
config/tsconfig.cli.jsonelectron.vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- config/tsconfig.cli.json
|
Follow-up round — pushed four more commits and rebased onto latest main. The interrupt guard I added earlier had a bug of its own: its Also in this round:
Every fix has a test proven to fail when the fix is reverted. 1039 tests pass, typecheck and lint clean. |
| 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 }) |
There was a problem hiding this comment.
Unexplained pre-login
accounts.list call discards its result
assertAccountImportSupported already made a round-trip to verify the runtime is reachable and on a compatible version. This second call adds latency before every login (one full network RTT) but the return value is never assigned or used. There is no // Why: comment explaining the intent, so it is unclear whether this is a deliberate connectivity smoke-test, a duplicate-check stub that never received its follow-through logic, or leftover development code. If the intent is just an extra health probe, a comment should say so; if it was supposed to compare the existing account list for pre-login duplicate detection, the result should be consumed.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| 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)) | ||
| } |
There was a problem hiding this comment.
Cleanup error after a successful add surfaces as the command's exit error with no guidance
When the temp-dir removal throws (e.g. EBUSY on Windows, tested at line 615 of account.test.ts) the cleanup error propagates as the final rejection. At that point the runtime has already successfully registered the account, but the CLI exits non-zero and prints nothing to stdout — logSpy is explicitly asserted absent. A user who hits this on Windows will believe the add failed, retry, and immediately get a "This Codex account is already added" error from the runtime with no explanation.
A console.warn after the RPC succeeds (before the rmSync runs) — analogous to the mid-RPC interruption warning at interactive-login-interruption.ts line 142 — would let users know to run orca account list before retrying. This is an especially likely path because Windows .cmd spawn handling is explicitly noted as a follow-up, so cleanup races with still-alive codex descendants are the expected failure mode there.
Greptile SummaryAdds a host-local CLI for managing Claude and Codex accounts on headless Orca runtimes —
Confidence Score: 5/5This PR is safe to merge. The new capture path correctly reuses the existing persist/rollback helpers, and the local-socket gate on the new RPC methods is properly enforced. The refactored persistCapturedClaudeAccount / persistCapturedCodexAccount helpers eliminate the pre-existing rollback divergence risk. Signal handling is non-once with serialized cleanup so repeated interrupts do not race. The macOS Keychain SHA-256 baseline comparison is correctly scoped, and the service-layer changes are covered by new unit tests including rollback, rejection, and spawn-failure scenarios. Files Needing Attention: No files require special attention. The main handler in src/cli/handlers/account.ts has an unexplained pre-login accounts.list call (already noted in a prior thread) but no new correctness concerns.
|
| Filename | Overview |
|---|---|
| src/cli/handlers/account.ts | New CLI handler with complete signal-safe cleanup logic; accounts.list pre-login call result is discarded (noted in prior thread). |
| src/cli/handlers/interactive-login-interruption.ts | Well-structured signal-handling module with bounded POSIX grace and Windows taskkill-tree termination; non-once listener correctly serializes repeated signals. |
| src/main/claude-accounts/service.ts | Extract of persistCapturedClaudeAccount / cleanupFailedAdd fixes a pre-existing rollback bug; SHA-256 comparison for macOS Keychain baseline is correct. |
| src/main/codex-accounts/service.ts | importCodexAuthFromHome mirrors the existing add path; persistCapturedCodexAccount rollback correctly passes targetSelection for WSL runtime sync. |
| src/main/runtime/rpc/methods/accounts.ts | New RPC methods correctly gate on clientKind===undefined; ListAccountsParams default(true) preserves existing mobile caller behavior. |
| src/main/ssh/ssh-remote-orca-cli.ts | Blocking account add over SSH relay while bridging account list and --help is correctly gated by !parsed.flags.has('help'). |
| src/shared/protocol-version.ts | ACCOUNT_IMPORT_RUNTIME_CAPABILITY added correctly to RUNTIME_CAPABILITIES array. |
| src/cli/main-module-bundle-parity.test.ts | New structural guard ensures every main-process module imported by the CLI has a corresponding electron-vite entry. |
| src/cli/specs/account.ts | Command specs correctly exclude browser-page targeting and document account-provider semantics for --agent. |
Reviews (3): Last reviewed commit: "fix(cli): preserve merged skills runtime..." | Re-trigger Greptile
|
Thanks for the PR! Sorry for the delay in reviewing it |
… (Claude + Codex) (stablyai#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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Brennan Benson <[email protected]>
Summary
Adds a host-local CLI for managing agent accounts on a headless Orca runtime:
orca account add [--agent claude|codex]andorca account list.The desktop "Add account" UI is disabled whenever the renderer drives a remote
runtime (
isRemoteAccountScope→ active runtime targetkind: 'environment').So an
orca servehost reached from a remote desktop/web client has no way toregister managed Claude/Codex accounts — the runtime falls back to the system
default login and the account switcher stays empty. Switching (
select) alreadyworks remotely; only adding was blocked.
This adds a host-local path that reuses the existing capture logic instead of
driving the interactive browser login from inside the background runtime:
ClaudeAccountService.addAccountFromConfigDir()/CodexAccountService.addAccountFromHome()register a managed account by capturing credentials from an already-authenticated
CLAUDE_CONFIG_DIR/CODEX_HOME(persist/rollback helpers extracted and sharedwith the existing add flow).
accounts.addClaudeFromConfigDir/accounts.addCodexFromHome, bridged viaOrcaRuntime; both reject mobile device tokens (host-local only).orca account addruns the agent login (claude login/codex login) in theuser's own terminal into a temp config dir, then registers it via the local
runtime.
orca account listrenders both Claude and Codex managed accounts.Screenshots
No visual change (CLI only).
Testing
pnpm lint— passes (one pre-existing, unrelated react-hooks warning).pnpm typecheck— passes (node/cli/web).pnpm test— ran the affected suites (registry-parity, agent-context, cli args,Claude & Codex account services including the new capture tests, accounts RPC):
all passing. Full suite not run in the headless build environment.
pnpm build— Linux AppImage builds and runs (orca account --helpshows thenew commands;
orca account listreturns live managed accounts).ClaudeAccountService.addAccountFromConfigDir(capture +rollback/rejection) and
CodexAccountService.addAccountFromHome(auth.json import +rejection when missing).
AI Review Report
Reviewed the full diff with an AI agent, focused on: reuse correctness (the new
addAccountFromConfigDir/addAccountFromHomemust match the existing add flow'spersistence + rollback semantics), RPC surface exposure, and cross-platform behavior.
Findings & resolutions:
persistCaptured*Account) so the newpath cannot diverge from the login path in how it writes settings, syncs auth, and
rolls back on error. Verified rollback still removes the managed dir/home on failure.
files (
.credentials.json/auth.json) — the capture path reads/copies those,matching existing behavior. On macOS Claude uses the Keychain; that branch is
reachable but the CLI is intended for headless hosts (macOS runs the local GUI
where
isRemoteAccountScopeis false and the GUI add flow is used), so the macOSKeychain temp-item cleanup path is not exercised here — noted as follow-up.
node:path(join/resolve) and env vars (CLAUDE_CONFIG_DIR/CODEX_HOME) — no hardcoded separators.spawn('claude'|'codex', args)without ashell); Windows
.cmdshim resolution for the CLI-side login is a follow-up(the runtime-side login already handles this via
getSpawnArgsForWindows).managed-home/dir branches only trigger for
--runtime wslon win32.Security Audit
injection.
claude auth statusis invoked the same way. Copyingauth.jsonusesatomic file writes.
destination managed path is constrained by the existing
assertManagedAuthPath/assertManagedHomePathguards (path-traversal safe, must live under Orca storage).The source dir is caller-supplied but the caller is the local host CLI (runtime
connection); reads are limited to the credential file.
clientKind === 'mobile'(device tokens), so only the local runtime connection can add accounts — matching the
intent that add is host-local. Select/remove already existed and are unchanged.
storage — the same as the existing Linux/Windows add flow; managed
auth.jsoniswritten
0600, temp login dirs are created viamkdtempand removed infinally.No secrets are logged.
Follow-up: dedicated unit tests for the new capture methods; Windows
.cmdspawnhandling for the CLI-side login; macOS Keychain temp-item cleanup if the CLI path is
ever supported on macOS.
Notes
Primary target is a headless
orca servehost on Linux accessed from a remote client.Verified end-to-end on such a host:
orca account addregisters an account that thenappears in
orca account listand in the desktop switcher, and is selectable from theremote client (select was never the blocked part).
ELI5
On headless remote runtimes you can add and list Claude/Codex accounts with orca account add and orca account list. Managed accounts work without the desktop Add account UI, which is disabled for remote scopes.