Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
1cf0f46
feat(claude-accounts): resolve --account selectors to managed Claude …
fardenghi Sep 24, 2026
8a7e4fd
feat(claude-accounts): track Claude PTYs pinned to a non-active account
fardenghi Sep 24, 2026
8f000ae
feat(claude-accounts): prepare pinned Claude launches on a non-active…
fardenghi Sep 24, 2026
51fa681
feat(claude-accounts): guard pinned accounts from host switches, remo…
fardenghi Sep 24, 2026
7f4f1e9
feat(pty): spawn runtime Claude PTYs pinned to a requested account
fardenghi Sep 24, 2026
6ea647b
feat(runtime): carry --account from terminal create to the PTY and re…
fardenghi Sep 24, 2026
100386e
feat(worktree): start a created worktree's Claude agent on a requeste…
fardenghi Sep 24, 2026
d739f79
feat(orchestration): run worker-start --account workers on a pinned C…
fardenghi Sep 24, 2026
fdb0edc
feat(cli): add --account to worker-start and worktree create for Claude
fardenghi Sep 24, 2026
36a8b8b
test(worktree): keep the --account mapping test out of the shared pro…
fardenghi Sep 24, 2026
05058eb
fix(claude-accounts): claim accounts atomically against pinned launches
fardenghi Sep 24, 2026
b9de81a
fix(cli): refuse worker-start --account with --terminal before callin…
fardenghi Sep 24, 2026
36f1060
fix(claude-accounts): revalidate startup pinned seed markers against …
fardenghi Sep 24, 2026
9295b63
fix(claude-accounts): wait for a pinned reservation outside the auth …
fardenghi Sep 24, 2026
629da63
fix(claude-accounts): claim a pinned account before re-authentication…
fardenghi Sep 24, 2026
87c9fe4
fix(claude-accounts): refuse to pin an account old host Claude termin…
fardenghi Sep 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/cli/handlers/claude-launch-account-flag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { getOptionalStringFlag } from '../flags'
import { RuntimeClientError, type RuntimeClient } from '../runtime-client'
import type { RuntimeStatus } from '../../shared/runtime-types'
import { CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/protocol-version'

/**
* `--account <id|email>`: the managed Claude account a launch runs on, resolved by the host.
*
* Why the capability check: an older host strips the unknown field and would quietly start the
* agent on its active account — exactly what the caller asked not to happen.
*/
export async function readClaudeLaunchAccountFlag(
flags: Map<string, string | boolean>,
client: RuntimeClient,
agent: string | undefined
): Promise<string | undefined> {
if (!flags.has('account')) {
return undefined
}
const account = getOptionalStringFlag(flags, 'account')?.trim()
if (!account) {
throw new RuntimeClientError(
'invalid_argument',
'--account requires a Claude account id or email.'
)
}
if (agent !== 'claude') {
throw new RuntimeClientError('invalid_argument', '--account requires --agent claude.')
}
const status = await client.call<RuntimeStatus>('status.get')
if (!status.result.capabilities?.includes(CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY)) {
throw new RuntimeClientError(
'incompatible_runtime',
'The connected Orca runtime does not support --account for Claude launches. Update or restart Orca and try again.'
)
}
return account
}
102 changes: 102 additions & 0 deletions src/cli/handlers/orchestration-worker-account-cli.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const callMock = vi.fn()

vi.mock('../format', () => ({ printResult: vi.fn() }))
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))

import { ORCHESTRATION_HANDLERS } from './orchestration'
import { CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY } from '../../shared/protocol-version'

describe('orchestration worker-start --account', () => {
beforeEach(() => {
callMock.mockReset()
process.exitCode = undefined
})

const invokeWorkerStart = (flags: Map<string, string | boolean>) =>
ORCHESTRATION_HANDLERS['orchestration worker-start']({
flags,
client: { call: callMock },
cwd: '/tmp/repo',
json: true
} as never)

it('forwards --account to a host that resolves Claude launch accounts', async () => {
callMock
.mockResolvedValueOnce({
result: { capabilities: [CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY] }
})
.mockResolvedValueOnce({
result: { runId: 'run_1', taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready' }
})

await invokeWorkerStart(
new Map<string, string | boolean>([
['task', 'task_1'],
['agent', 'claude'],
['account', 'pinned@example.com'],
['from', 'term_coord']
])
)

expect(callMock).toHaveBeenNthCalledWith(1, 'status.get')
expect(callMock).toHaveBeenNthCalledWith(
2,
'orchestration.workerStart',
expect.objectContaining({ agent: 'claude', account: 'pinned@example.com' })
)
})

it('fails before worker-start when --account would be stripped or misapplied', async () => {
callMock.mockResolvedValueOnce({ result: { capabilities: [] } })
const flags = (agent: string) =>
new Map<string, string | boolean>([
['task', 'task_1'],
['agent', agent],
['account', 'acct-b'],
['from', 'term_coord']
])

await expect(invokeWorkerStart(flags('claude'))).rejects.toMatchObject({
code: 'incompatible_runtime'
})
await expect(invokeWorkerStart(flags('codex'))).rejects.toThrow(
'--account requires --agent claude.'
)
expect(callMock).toHaveBeenCalledTimes(1)
})

it('never sends an account field when --account is absent', async () => {
callMock.mockResolvedValue({
result: { runId: 'run_1', taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready' }
})
await invokeWorkerStart(
new Map<string, string | boolean>([
['task', 'task_1'],
['agent', 'claude'],
['from', 'term_coord']
])
)
expect(callMock).toHaveBeenCalledTimes(1)
expect(callMock.mock.calls[0]?.[1]).not.toHaveProperty('account')
})

it('refuses --account with --terminal before calling any host', async () => {
await expect(
invokeWorkerStart(
new Map<string, string | boolean>([
['task', 'task_1'],
['terminal', 'term_worker'],
['account', 'acct-b'],
['from', 'term_coord']
])
)
).rejects.toMatchObject({
code: 'invalid_argument',
message:
'--account cannot be combined with --terminal; the reused terminal keeps its own account.'
})
expect(callMock).not.toHaveBeenCalled()
})
})
13 changes: 13 additions & 0 deletions src/cli/handlers/orchestration/worker-launch-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { isDevCliInvocation } from './runtime-compatibility'
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
import { formatWorkerStart } from './worker-output'
import { renderResolvedOrchestrationCommand } from '../../orchestration-mutation-recovery'
import { readClaudeLaunchAccountFlag } from '../claude-launch-account-flag'

export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler> = {
'orchestration worker-start': async ({ flags, client, cwd, json }) => {
Expand All @@ -28,6 +29,17 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler>
)
}
}
if (flags.has('account') && flags.has('terminal')) {
throw new RuntimeClientError(
'invalid_argument',
'--account cannot be combined with --terminal; the reused terminal keeps its own account.'
)
}
const account = await readClaudeLaunchAccountFlag(
flags,
client,
getOptionalStringFlag(flags, 'agent')
)
const task = getOptionalStringFlag(flags, 'task')
const spec = getOptionalStringFlag(flags, 'spec')
const taskTitle = getOptionalStringFlag(flags, 'task-title')
Expand Down Expand Up @@ -62,6 +74,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler>
agent: getOptionalStringFlag(flags, 'agent'),
model,
effort,
...(account ? { account } : {}),
terminal: getOptionalStringFlag(flags, 'terminal'),
retryOf: getOptionalStringFlag(flags, 'retry-of'),
timeoutMs: getOptionalPositiveIntegerValueFlag(flags, 'timeout-ms'),
Expand Down
5 changes: 4 additions & 1 deletion src/cli/handlers/worktree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { isTuiAgent } from '../../shared/tui-agent-config'
import { isWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope'
import { printLineageSummary } from './worktree-lineage-summary'
import { readClaudeLaunchAccountFlag } from './claude-launch-account-flag'
import {
assertWorkspaceTargetFlagsCompatible,
hasWorkspaceProjectTarget,
Expand Down Expand Up @@ -194,6 +195,7 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
const explicitParentWorktree = explicitParent.parentWorktree
const explicitParentWorkspace = explicitParent.parentWorkspace
const startupAgent = getOptionalStartupAgent(flags)
const claudeAccount = await readClaudeLaunchAccountFlag(flags, client, startupAgent)
const setupDecision = getOptionalSetupDecision(flags)
const noParent = flags.get('no-parent') === true
const envParentWorkspace =
Expand Down Expand Up @@ -245,7 +247,8 @@ export const WORKTREE_HANDLERS: Record<string, CommandHandler> = {
...(startupAgent
? {
startupAgent,
startupPrompt: getPresentStringFlag(flags, 'prompt', { allowEmpty: true }) ?? ''
startupPrompt: getPresentStringFlag(flags, 'prompt', { allowEmpty: true }) ?? '',
...(claudeAccount ? { startupClaudeAccount: claudeAccount } : {})
}
: {})
})
Expand Down
103 changes: 103 additions & 0 deletions src/cli/index-worktree-create-claude-account.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { describe, expect, it, vi } from 'vitest'
import { CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY } from '../shared/protocol-version'

const {
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
} = vi.hoisted(() => ({
callMock: vi.fn(),
runtimeClientConstructorMock: vi.fn(),
serveOrcaAppMock: vi.fn(),
getDefaultUserDataPathMock: vi.fn(() => '/tmp/orca-user-data'),
addEnvironmentFromPairingCodeMock: vi.fn(),
listEnvironmentsMock: vi.fn(),
spawnMock: vi.fn()
}))

vi.mock('./runtime-client', async () => {
const { createRuntimeClientModuleMock } = await import('./index-test-harness.js')
return createRuntimeClientModuleMock({
callMock,
runtimeClientConstructorMock,
serveOrcaAppMock,
getDefaultUserDataPathMock
})
})

vi.mock('./runtime/environments', () => ({
addEnvironmentFromPairingCode: addEnvironmentFromPairingCodeMock,
listEnvironments: listEnvironmentsMock,
removeEnvironment: vi.fn(),
resolveEnvironment: vi.fn()
}))

vi.mock('child_process', async () => {
const { createChildProcessModuleMock } = await import('./index-test-harness.js')
return createChildProcessModuleMock(spawnMock)
})

import { main } from './index'
import { buildWorktree, okFixture, queueFixtures, worktreeListFixture } from './test-fixtures'
import { useWorktreeAwarenessEnvironment } from './index-test-harness'

describe('orca worktree create --account', () => {
useWorktreeAwarenessEnvironment({
callMock,
serveOrcaAppMock,
getDefaultUserDataPathMock,
addEnvironmentFromPairingCodeMock,
listEnvironmentsMock,
spawnMock
})

const createArgs = ['worktree', 'create', '--repo', 'id:repo-1', '--name', 'pinned', '--json']

it('sends the account selector to a host that advertises support', async () => {
queueFixtures(
callMock,
okFixture('req_status', { capabilities: [CLAUDE_LAUNCH_ACCOUNT_RUNTIME_CAPABILITY] }),
worktreeListFixture([buildWorktree('/tmp/repo', 'main', 'abc', 'repo-1')]),
okFixture('req_create', {
worktree: buildWorktree('/tmp/repo/pinned', 'pinned', 'abc', 'repo-1')
})
)
vi.spyOn(console, 'log').mockImplementation(() => {})

await main([...createArgs, '--agent', 'claude', '--account', 'pinned@example.com'], '/tmp/repo')

expect(callMock).toHaveBeenNthCalledWith(1, 'status.get')
expect(callMock).toHaveBeenNthCalledWith(
3,
'worktree.create',
expect.objectContaining({
startupAgent: 'claude',
startupPrompt: '',
startupClaudeAccount: 'pinned@example.com'
})
)
})

it('refuses an older host instead of launching on its active account', async () => {
queueFixtures(callMock, okFixture('req_status', { capabilities: [] }))
vi.spyOn(console, 'error').mockImplementation(() => {})

await main([...createArgs, '--agent', 'claude', '--account', 'acct-b'], '/tmp/repo')

expect(process.exitCode).toBe(1)
expect(callMock).not.toHaveBeenCalledWith('worktree.create', expect.anything())
})

it('requires --agent claude', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})

await main([...createArgs, '--agent', 'codex', '--account', 'acct-b'], '/tmp/repo')

expect(process.exitCode).toBe(1)
expect(callMock).not.toHaveBeenCalled()
})
})
4 changes: 3 additions & 1 deletion src/cli/specs/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
path: ['worktree', 'create'],
summary: 'Create a new Orca-managed worktree',
usage:
'orca worktree create --name <name> [--repo <selector>|--project <id> [--host <host-id>]|--project-host-setup <id>] [--agent <id>] [--prompt <text>] [--setup run|skip|inherit] [--base-branch <ref>] [--issue <number>] [--linear-issue <identifier-or-url>] [--comment <text>] [--parent-worktree <selector>] [--no-parent] [--run-hooks] [--activate] [--json]',
'orca worktree create --name <name> [--repo <selector>|--project <id> [--host <host-id>]|--project-host-setup <id>] [--agent <id>] [--account <id|email>] [--prompt <text>] [--setup run|skip|inherit] [--base-branch <ref>] [--issue <number>] [--linear-issue <identifier-or-url>] [--comment <text>] [--parent-worktree <selector>] [--no-parent] [--run-hooks] [--activate] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'repo',
Expand All @@ -99,6 +99,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
'project-host-setup',
'name',
'agent',
'account',
'prompt',
'base-branch',
'issue',
Expand All @@ -121,6 +122,7 @@ export const CORE_COMMAND_SPECS: CommandSpec[] = [
'--no-parent only affects Orca lineage; omit --base-branch to use the repo default base, or pass the default base ref explicitly for independent top-level work.',
'By default this creates the worktree and its first terminal without switching the active Orca view.',
'Pass --agent to launch an agent in the first terminal; --prompt sends initial work to that agent.',
'--account <id|email> (with --agent claude) starts Claude on that managed account from `orca account list` without switching the host account. Local host workspaces only.',
'With --agent --json, read the new agent handle from result.agentTerminalHandle; older runtimes return only result.startupTerminal.handle, and may return neither for folder-based repos.',
'Repo-defined setup hooks follow the repository setup policy; pass --setup run to force them.',
'Pass --activate when the CLI caller intentionally wants to reveal the new worktree in the app.',
Expand Down
4 changes: 3 additions & 1 deletion src/cli/specs/orchestration-worker-specs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [
path: ['orchestration', 'worker-start'],
summary: 'Start one supervised worker on the Run home or a connected Orca server',
usage:
'orca orchestration worker-start (--task <task_id> | --spec <text>) [--on <saved-environment>] [--worktree <current|selector|new-child|new-top-level>] (--agent <agent> | --terminal <handle>) [--task-title <text>] [--deps <json_array>] [--parent <task_id>] [--model <id>] [--effort <level>] [--name <name>] [--repo <selector>] [--base-branch <ref>] [--display-name <text>] [--comment <text>] [--setup <run|skip|inherit>] [--retry-of <dispatch_id>] [--timeout-ms <n>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
'orca orchestration worker-start (--task <task_id> | --spec <text>) [--on <saved-environment>] [--worktree <current|selector|new-child|new-top-level>] (--agent <agent> | --terminal <handle>) [--task-title <text>] [--deps <json_array>] [--parent <task_id>] [--model <id>] [--effort <level>] [--account <id|email>] [--name <name>] [--repo <selector>] [--base-branch <ref>] [--display-name <text>] [--comment <text>] [--setup <run|skip|inherit>] [--retry-of <dispatch_id>] [--timeout-ms <n>] [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'task',
Expand All @@ -24,6 +24,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [
'agent',
'model',
'effort',
'account',
'terminal',
'retry-of',
'timeout-ms',
Expand All @@ -36,6 +37,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [
'When reusing --terminal, pass --worktree for that terminal; current means the coordinator worktree.',
'--agent takes an Orca agent id enabled on the worker server, such as claude, codex, cursor, antigravity, muse, opencode, or opencode2.',
'--model supports Claude, Codex, Cursor, Antigravity, and Muse opaque provider model ids; --effort requires --model. Neither can combine with --terminal. Other agents, including opencode, launch with the model from their own config.',
'--account <id|email> starts a Claude worker on that managed account from `orca account list` without switching the host account. Claude only, this host only (no --on), always a terminal worker, and not with --terminal.',
'New worktrees use agent-first creation and default --setup to run. Repository start-immediately runs setup beside the agent; wait-for-setup gates agent readiness and task input.',
'Creation flags (--name, --repo, --base-branch, --display-name, --comment, --setup) are rejected for current/existing worktrees. Use exact --repo on the selected server; project/host convenience routing remains on worktree create.',
"How the worker runs follows the user's own setting for new agent tabs; there is no flag for it and no caller needs to ask. A dispatch the setting cannot apply to still starts, so the placement, agent, and launch options passed here are always the ones honoured.",
Expand Down
9 changes: 8 additions & 1 deletion src/main/agent-launch/agent-launch-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ export type AgentLaunchModePlacement = {
* resolved — never accepted from a caller, which would let one route around this decision.
* Absent means the kind was never established, and is not read as any particular kind. */
workspaceKind?: WorkspaceLaunchKind
/** `--account`: a structured session has no way to run on a non-active account yet. */
claudeAccount?: string
/** A start directory other than the workspace root. It belongs here, unlike `model` or `effort`,
* because a structured session has no way to apply one — it runs in its workspace — so honouring
* it and honouring the chat preference are mutually exclusive rather than merely awkward. */
Expand All @@ -87,7 +89,9 @@ const DOWNGRADE_DETAIL: Record<Exclude<AgentLaunchModeReason, 'user_default'>, s
structured_support_unknown: 'the execution host has not established structured session support',
wsl_execution_runtime: 'this workspace runs under WSL',
codex_on_windows: 'Codex has no structured session on Windows',
structured_unsupported_on_host: 'the execution host cannot create one here'
structured_unsupported_on_host: 'the execution host cannot create one here',
pinned_claude_account:
'--account runs Claude on a non-active account, which only a terminal can do'
}

const BLOCKER_REASON: Record<
Expand Down Expand Up @@ -133,6 +137,9 @@ export function decideAgentLaunchMode(args: {
detail: `Started ${vocabulary.terminal}, the default for new agent tabs in your settings.`
}
}
if (placement.claudeAccount) {
return downgraded('pinned_claude_account', vocabulary)
}
Comment on lines +140 to +142

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.

The pinned_claude_account downgrade fires for any --account, including a selector that names the account already active on the host. The PR's resolution rules say an active-account selector runs the normal path unchanged, but this decision runs before resolution and only sees the raw selector, so a structured-default user gets a terminal worker (and the “non-active account” detail) for --account <active>. The same raw-selector assumption makes buildRuntimeAgentTeamsLaunchPlan force in-process teammates for the active account too.

Technical details
# `--account <active>` is treated as pinned in mode/Agent-Teams decisions

## Affected sites
- `src/main/agent-launch/agent-launch-mode.ts:140` — downgrades for any non-empty `placement.claudeAccount`.
- `src/main/runtime/rpc/methods/orchestration-worker-start-mode.ts:60` — passes the raw `params.account` as `claudeAccount`.
- `src/main/runtime/orca-runtime-agent-teams-launch-plan.ts:35` — forces `in-process` for any `claudeAccountId`.

## Required outcome
- Either only downgrade / force in-process when the resolved account is not the active host account (resolution already exists: `resolveClaudeLaunchAccount(...).isActiveOnHost`), or document that `--account` is selector-level terminal-only regardless of which account it names so the receipt and the Agent-Teams mode stop contradicting the resolution rules.

## Open questions for the human
- Is the active-account case worth special-casing, or is the selector-level behavior intentional and just under-documented?

// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: an unrecognized agent name is handled rather than trusted; isAgentSessionHandleProvider rejects it and the launch downgrades to a terminal.
const agent = placement.agent as TuiAgent
const support = resolveStructuredNativeChatSupport({
Expand Down
Loading
Loading