Skip to content

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

Merged
brennanb2025 merged 19 commits into
stablyai:mainfrom
dommer1:feat/cli-account-add
Jul 30, 2026
Merged

brennanb2025 merged 19 commits into
stablyai:mainfrom
dommer1:feat/cli-account-add

Conversation

@dommer1

@dommer1 dommer1 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a host-local CLI for managing agent accounts on a headless Orca runtime:
orca account add [--agent claude|codex] and orca account list.

The desktop "Add account" UI is disabled whenever the renderer drives a remote
runtime (isRemoteAccountScope → active runtime target kind: 'environment').
So an orca serve host reached from a remote desktop/web client has no way to
register managed Claude/Codex accounts — the runtime falls back to the system
default login and the account switcher stays empty. Switching (select) already
works 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 shared
    with the existing add flow).
  • RPC accounts.addClaudeFromConfigDir / accounts.addCodexFromHome, bridged via
    OrcaRuntime; both reject mobile device tokens (host-local only).
  • orca account add runs the agent login (claude login / codex login) in the
    user's own terminal into a temp config dir, then registers it via the local
    runtime. orca account list renders 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 --help shows the
    new commands; orca account list returns live managed accounts).
  • Added unit tests: 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 / addAccountFromHome must match the existing add flow's
persistence + rollback semantics), RPC surface exposure, and cross-platform behavior.

Findings & resolutions:

  • Extracted the shared persist/rollback tail (persistCaptured*Account) so the new
    path 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.
  • Cross-platform (macOS / Linux / Windows) explicitly checked:
    • Credential storage: on Linux/Windows both agents persist plaintext credential
      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 isRemoteAccountScope is false and the GUI add flow is used), so the macOS
      Keychain temp-item cleanup path is not exercised here — noted as follow-up.
    • Paths use node:path (join/resolve) and env vars (CLAUDE_CONFIG_DIR /
      CODEX_HOME) — no hardcoded separators.
    • The CLI login spawn is POSIX-oriented (spawn('claude'|'codex', args) without a
      shell); Windows .cmd shim resolution for the CLI-side login is a follow-up
      (the runtime-side login already handles this via getSpawnArgsForWindows).
    • WSL is untouched: the CLI always targets the host runtime; the existing WSL
      managed-home/dir branches only trigger for --runtime wsl on win32.

Security Audit

  • Command execution: login is spawned with an args array and no shell → no shell
    injection. claude auth status is invoked the same way. Copying auth.json uses
    atomic file writes.
  • Input / path handling: RPC params validated with zod (non-empty strings). The
    destination managed path is constrained by the existing assertManagedAuthPath /
    assertManagedHomePath guards (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.
  • IPC / auth: both new RPC methods explicitly reject 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.
  • Secrets: OAuth credentials are copied as plaintext files into Orca's managed
    storage — the same as the existing Linux/Windows add flow; managed auth.json is
    written 0600, temp login dirs are created via mkdtemp and removed in finally.
    No secrets are logged.
  • Dependencies: none added.

Follow-up: dedicated unit tests for the new capture methods; Windows .cmd spawn
handling 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 serve host on Linux accessed from a remote client.
Verified end-to-end on such a host: orca account add registers an account that then
appears in orca account list and in the desktop switcher, and is selectable from the
remote 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.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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 account add and account list CLI commands with interactive provider login, account formatting, platform-specific cleanup, and validation. Updates command registration, remote-selection handling, tests, and Electron build entry points.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding account add/list CLI commands for headless Claude and Codex account management.
Description check ✅ Passed The description matches the template with all required sections and provides detailed summary, testing, review, security, and notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (1)
src/cli/specs/account.ts (1)

10-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove manual GLOBAL_FLAGS spreading in allowedFlags.

Based on learnings, the CLI uses a shared effectiveAllowedFlags(spec) helper to merge GLOBAL_FLAGS with a command's allowedFlags. Manually spreading GLOBAL_FLAGS here is redundant and circumvents the unified flag resolution pattern. Specify only the command-specific flags in allowedFlags.

♻️ 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.ts
  • src/cli/dispatch.ts
  • src/cli/handlers/account.ts
  • src/cli/index.ts
  • src/cli/specs/account.ts
  • src/cli/specs/index.ts
  • src/main/claude-accounts/service.test.ts
  • src/main/claude-accounts/service.ts
  • src/main/codex-accounts/service.test.ts
  • src/main/codex-accounts/service.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/accounts.ts

Comment thread src/cli/handlers/account.ts Resolved
Comment thread src/main/claude-accounts/service.ts Resolved
Comment thread src/main/claude-accounts/service.ts Resolved
Comment thread src/main/codex-accounts/service.ts Resolved
Comment thread src/main/codex-accounts/service.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@brennanb2025

Copy link
Copy Markdown
Contributor

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.

@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
@nwparker nwparker added the enhancement New feature or request label Jul 27, 2026
@brennanb2025

Copy link
Copy Markdown
Contributor

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. electron-vite cleans out/main and emits only its declared entries, and build:desktop runs it after build:cli. The three new CLI→main imports had no entries, so orca account add and orca account list both died at require time with Cannot find module '../../main/claude-accounts/keychain'. agent-hooks/managed-agent-hook-controls already carries an entry with a comment explaining exactly this. Added the three missing entries and a parity test, since unit tests resolve TS sources and structurally cannot catch it.

Interrupted login stranded live OAuth tokens on disk. Node terminates on SIGINT without unwinding finally, so Ctrl-C during sign-in left the temp dir with a usable token in it, and on macOS skipped the Keychain restore. Added a signal guard covering SIGINT/SIGTERM/SIGHUP (SSH hangup matters here), using on rather than once so a second Ctrl-C can't kill the process mid-cleanup, and awaiting in-flight cleanup rather than latching a boolean.

account list forced a provider refresh. accounts.list awaits refreshAccountsForMobile(), which bypasses both the poll throttle and the per-provider Retry-After gate, then does one serial round-trip per account — for output that renders no usage numbers. runtime-provider-accounts-client.ts already avoids this call for the same reason ("can hang for minutes behind broken auth"). Added a refreshUsage param defaulting to true, so mobile and web are unchanged, and the CLI opts out. Older hosts declare params: null and ignore the field, so a newer CLI degrades rather than failing.

Flag surface. account wasn't in supportsBrowserPageFlag's deny-list, so --page was silently accepted and advertised in help. The specs omitted GLOBAL_FLAGS, so --help/--json never rendered. --agent inherited the shared "Launch a known TUI agent in the first terminal" text. And a valueless --agent parsed as boolean true and silently ran a full Claude OAuth login for a provider the user hadn't asked for.

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 persistCapturedCodexAccount had reverted it to an awaited call — restored, and moved outside the new rollback try/catch.

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 syncForCurrentSelection on the Codex side (which is a genuine fix: reauthenticate and select already did this, add was the lone exception, so a WSL add materialized the host home that hadn't changed and never the WSL slot that had).

Verified on an isolated headless --serve host built in production order: account list end-to-end, the refresh opt-out honored, the new add RPC registered and reachable, --json keeping stdout to the envelope with the login prompt on stderr, and the interrupt case going from one token-bearing temp dir to zero with exit 130.

Dominik and others added 13 commits July 27, 2026 19:19
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
electron.vite.config.ts (1)

278-282: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Keep 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.json
  • electron.vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/tsconfig.cli.json

@brennanb2025

Copy link
Copy Markdown
Contributor

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 finally detached the signal handlers before running cleanup, so the two serial 3s security calls plus the temp-dir removal — exactly the window the guard exists to protect — ran with Node's terminate-immediately default restored. Two independent review lanes reproduced it. Cleanup now runs first and detaches in a nested finally, and a cleanup failure no longer replaces the error that explains why the add failed.

Also in this round:

  • Preflight the runtime before the login. RuntimeClient is lazily constructed and the first call was the registration RPC itself, so "Requires the Orca runtime to be running" surfaced only after a full interactive OAuth round trip. Now checked up front with the newly-cheap accounts.list { refreshUsage: false }.
  • 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.
  • Reject --environment / --pairing-code on both commands. shouldIgnoreRemoteSelection pins account commands to the local runtime, so orca account add --environment homelab silently registered on the laptop instead of the host it names, and orca account list --environment homelab silently listed the laptop's accounts. Both now error. The other command groups with the same silent-ignore behavior are left alone — out of scope here.
  • Test hardening: signal listeners are identified by set difference rather than process.listeners(sig).at(-1), which could pick up vitest's own once-wrapped SIGINT teardown.

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 })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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!

Comment on lines +206 to +228
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))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

Adds a host-local CLI for managing Claude and Codex accounts on headless Orca runtimes — orca account add [--agent claude|codex] and orca account list. The new path captures credentials from a temp CLAUDE_CONFIG_DIR / CODEX_HOME that the CLI runs the interactive agent login into, then registers them via an RPC-gated local-socket call, bypassing the desktop "Add account" UI that is intentionally disabled for remote scopes.

  • ClaudeAccountService.addAccountFromConfigDir and CodexAccountService.addAccountFromHome extract a shared persistCaptured*Account helper that both the existing interactive add flow and the new capture path now share, ensuring rollback and settings semantics stay in sync.
  • Two new RPC methods (accounts.addClaudeFromConfigDir / accounts.addCodexFromHome) are gated to clientKind === undefined (local socket only), blocking paired mobile and remote tokens from accessing host filesystem paths.
  • Signal handling (SIGINT/SIGTERM/SIGHUP) serializes child-process cleanup with a non-once listener so a second interrupt waits for in-flight Keychain or temp-dir cleanup rather than falling through to Node's default kill.

Confidence Score: 5/5

This 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.

Important Files Changed

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

@brennanb2025
brennanb2025 merged commit 650dd48 into stablyai:main Jul 30, 2026
48 checks passed
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the PR! Sorry for the delay in reviewing it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… (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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants