fix(cloud): Claude "Set up once" completes: paste the code from Claude's sign-in page (SETUP-PASTE, P0)

claude setup-token prints only its manual-redirect link (redirect_uri platform.claude.com/oauth/code/callback), which Orca opens from "Open again" and which ends on Anthropic's "Authentication code - Paste this into Claude Code" page. The CLI waits at a masked "Paste code here if prompted >" in Orca's hidden PTY, and nothing could type into it, so setup spun until its 10-minute timeout.

- Runner: the setup-token process can be written to; once the sign-in link shows, a submitter types the code then Enter. A refused code ("That code wasn't accepted") starts over in the same run (Enter, new link, new submitter).
- claude-setup-run.ts (extracted from the service): one run's link, code prompt and outcome. A run that ends without a token after its link showed is expired (failed/timed_out); "Open again" then starts a fresh run.
- IPC orcaCloudAgents:submitClaudeCode: a bare code or the whole callback URL, trimmed (setup-tokens and other sites refused), never logged or stored; progress on the 'browser' phase (acceptsCode, code: checking | rejected).
- UI (design-squad copy): [Paste code] [Finish setup] [Open again] on the pane strip (terminal and chat UI, which mounts the same strip) and Settings > Agent accounts (also the sign-in sheet the new-workspace row and host panel open). Masked, cleared once sent, auto-submitted when a whole code is pasted; one rejection message; expired shows "Open again". The build sheet row is display only and points to Settings.
This commit is contained in:
Neil
2026-11-11 17:30:18 -08:00
parent 1d9a62814f
commit 74dcb98527
22 changed files with 763 additions and 85 deletions
@@ -0,0 +1,230 @@
// P0 "Set up once": Claude's setup-token ends on Anthropic's "Authentication code — Paste this into
// Claude Code" page. The code comes back through Orca (strip, Settings, chat UI) into the waiting CLI.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { OrcaCloudAgentSetups } from '../../shared/orca-cloud-agents/orca-cloud-agents-wire'
import type { AgentCredentialsClient } from './agent-credentials-client'
import { normalizeClaudeSetupCode } from './claude-setup-code'
import {
runClaudeSetupToken,
type SetupTokenProcess,
type SubmitSetupCode
} from './claude-setup-token-runner'
import { createOrcaCloudAgentsService } from './orca-cloud-agents-service'
const TOKEN = `sk-ant-oat01-${'Qq7_'.repeat(25)}`
// What setup-token 2.1.319 prints (manual redirect: Anthropic's code page).
const AUTHORIZE =
'https://claude.com/cai/oauth/authorize?code=true&client_id=c&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=s1'
const PROMPT = 'Paste code here if prompted > '
// A recorded-shape fake: never a real code.
const CODE = 'FAKEcode0123456789abcdef#FAKEstate0123456789'
const REJECTED =
"OAuth error: That code wasn't accepted. It may be incomplete, expired, already used, or from an earlier sign-in attempt.\n Press Enter to retry.\n"
function fakeChild() {
let onData: (chunk: string) => void = () => {}
let onExit: (code: number | null) => void = () => {}
const writes: string[] = []
const child: SetupTokenProcess & { emit(c: string): void; exit(): void; writes: string[] } = {
writes,
onData: (l) => {
onData = l
},
onExit: (l) => {
onExit = l
},
kill: vi.fn(),
write: (data) => void writes.push(data),
emit: (c) => onData(c),
exit: () => onExit(0)
}
return child
}
const tick = async (): Promise<void> => {
for (let i = 0; i < 10; i++) {
await Promise.resolve()
}
}
describe('normalizeClaudeSetupCode', () => {
it('takes the bare code, trimmed', () => {
expect(normalizeClaudeSetupCode(` ${CODE}\n`)).toBe(CODE)
})
it("takes the whole callback URL from the browser's address bar", () => {
expect(
normalizeClaudeSetupCode(
'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef&state=FAKEstate0123456789'
)
).toBe(CODE)
})
it('refuses anything else, including another site', () => {
expect(normalizeClaudeSetupCode('hello world')).toBeNull()
expect(
normalizeClaudeSetupCode('https://evil.test/cb?code=FAKEcode0123456789&state=x1234567')
).toBeNull()
expect(normalizeClaudeSetupCode(TOKEN)).toBeNull()
})
})
describe('runClaudeSetupToken with a pasted code', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
async function started() {
const child = fakeChild()
const submits: SubmitSetupCode[] = []
const onCodeRejected = vi.fn()
const outcome = runClaudeSetupToken({
spawn: async () => child,
signal: new AbortController().signal,
timeoutMs: 600_000,
onAcceptsCode: (submit) => void submits.push(submit),
onCodeRejected
})
await tick()
return { child, submits, onCodeRejected, outcome }
}
it('types the code, then Enter, into the waiting CLI and captures the token it prints', async () => {
const { child, submits, outcome } = await started()
expect(submits).toHaveLength(0)
child.emit(`Browser didn't open? Use the url below to sign in\n${AUTHORIZE}\n${PROMPT}`)
expect(submits).toHaveLength(1)
expect(submits[0]!(CODE)).toBe(true)
// One code at a time until the CLI answers.
expect(submits[0]!(CODE)).toBe(false)
expect(child.writes).toEqual([CODE])
await vi.advanceTimersByTimeAsync(200)
expect(child.writes).toEqual([CODE, '\r'])
child.emit(`Your OAuth token (valid for 1 year):\n\n${TOKEN}\n\nStore this token`)
await vi.advanceTimersByTimeAsync(1_100)
await expect(outcome).resolves.toEqual({ ok: true, token: TOKEN })
})
it('on a refused code starts over in the same run: Enter for a new link, which takes a new code', async () => {
const { child, submits, onCodeRejected } = await started()
child.emit(`${AUTHORIZE}\n${PROMPT}`)
submits[0]!(CODE)
await vi.advanceTimersByTimeAsync(200)
child.emit(REJECTED)
expect(onCodeRejected).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(600)
expect(child.writes).toEqual([CODE, '\r', '\r'])
// The spent submitter refuses; the new link brings a new one.
expect(submits[0]!(CODE)).toBe(false)
child.emit(`${AUTHORIZE.replace('state=s1', 'state=s2')}\n${PROMPT}`)
expect(submits).toHaveLength(2)
expect(submits[1]!(CODE)).toBe(true)
})
})
describe('service: the code from the strip, Settings or the chat UI', () => {
const logged: unknown[][] = []
beforeEach(() => {
logged.length = 0
for (const level of ['log', 'info', 'warn', 'error', 'debug'] as const) {
vi.spyOn(console, level).mockImplementation((...args: unknown[]) => void logged.push(args))
}
})
afterEach(() => vi.restoreAllMocks())
function setup() {
const children: ReturnType<typeof fakeChild>[] = []
const broadcasts: OrcaCloudAgentSetups[] = []
const client = {
putClaude: vi.fn(async () => ({})),
credentials: vi.fn(),
sources: vi.fn()
} as unknown as AgentCredentialsClient
const service = createOrcaCloudAgentsService({
client,
spawnSetupToken: async () => {
const child = fakeChild()
children.push(child)
return child
},
readClaudeEmail: () => null,
openExternal: vi.fn(async () => {}),
broadcast: (setups) => broadcasts.push(setups),
identity: () => 'p1:u1'
})
return { service, children, broadcasts, client }
}
it('shows the code field once the CLI waits for it, checks it, and saves the token; the code is never echoed', async () => {
const { service, children, broadcasts, client } = setup()
service.start('claude')
await tick()
expect(service.setups().claude).toMatchObject({ phase: 'browser' })
expect(service.submitClaudeCode(CODE)).toEqual({ ok: false, error: 'unavailable' })
children[0]!.emit(`${AUTHORIZE}\n${PROMPT}`)
expect(service.setups().claude).toMatchObject({
phase: 'browser',
acceptsCode: true,
canReopen: true
})
expect(service.submitClaudeCode('not a code')).toEqual({ ok: false, error: 'invalid_code' })
expect(service.submitClaudeCode(` ${CODE} `)).toEqual({ ok: true, value: true })
expect(service.setups().claude).toMatchObject({ phase: 'browser', code: 'checking' })
expect(children[0]!.writes[0]).toBe(CODE)
children[0]!.emit(`Your OAuth token:\n\n${TOKEN}\n\n`)
children[0]!.exit()
await tick()
expect(client.putClaude).toHaveBeenCalledWith(TOKEN, undefined)
expect(service.setups().claude).toEqual({ phase: 'saved' })
for (const surface of [broadcasts, logged]) {
expect(JSON.stringify(surface)).not.toContain('FAKEcode')
expect(JSON.stringify(surface)).not.toContain('sk-ant-oat01')
}
})
it('a refused code shows "rejected" and the field again for the next code', async () => {
vi.useFakeTimers()
try {
const { service, children } = setup()
service.start('claude')
await tick()
children[0]!.emit(`${AUTHORIZE}\n${PROMPT}`)
service.submitClaudeCode(CODE)
children[0]!.emit(REJECTED)
expect(service.setups().claude).toMatchObject({ phase: 'browser', code: 'rejected' })
expect(service.submitClaudeCode(CODE)).toEqual({ ok: false, error: 'unavailable' })
await vi.advanceTimersByTimeAsync(600)
children[0]!.emit(`${AUTHORIZE}\n${PROMPT}`)
expect(service.setups().claude).toMatchObject({ phase: 'browser', acceptsCode: true })
expect(service.submitClaudeCode(CODE)).toEqual({ ok: true, value: true })
} finally {
vi.useRealTimers()
}
})
it('a sign-in whose CLI goes away shows expired, and "Open again" starts a fresh run with a new link', async () => {
const { service, children } = setup()
service.start('claude')
await tick()
children[0]!.emit(`${AUTHORIZE}\n${PROMPT}`)
children[0]!.exit()
await tick()
expect(service.setups().claude).toEqual({ phase: 'failed', error: 'timed_out' })
expect(await service.reopen('claude')).toBe(true)
await tick()
expect(children).toHaveLength(2)
expect(service.setups().claude).toMatchObject({ phase: 'browser', canReopen: false })
})
it('the 10-minute timeout also ends as expired, not a silent spin', async () => {
vi.useFakeTimers()
try {
const { service, children } = setup()
service.start('claude')
await tick()
children[0]!.emit(`${AUTHORIZE}\n${PROMPT}`)
await vi.advanceTimersByTimeAsync(600_001)
await tick()
expect(service.setups().claude).toEqual({ phase: 'failed', error: 'timed_out' })
} finally {
vi.useRealTimers()
}
})
})
@@ -0,0 +1,40 @@
// The code Claude's sign-in page shows ("Authentication code — Paste this into Claude Code"), as the
// person pastes it into Orca: the bare `code#state`, or the whole callback URL copied from the address
// bar. Normalized here before it is typed into the waiting `claude setup-token`; never logged or kept.
// Anthropic's codes and states are URL-safe base64 joined by '#'.
const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}(?:#[A-Za-z0-9_-]{8,512})?$/
const CALLBACK_HOSTS = new Set([
'platform.claude.com',
'console.anthropic.com',
'claude.ai',
'claude.com'
])
/** The code the CLI expects, or null when the paste isn't one (the caller says so, without echoing it). */
export function normalizeClaudeSetupCode(raw: string): string | null {
const value = raw.trim()
// A setup-token or API key pasted here is not a sign-in code; it never goes to the CLI's prompt.
if (/^sk-ant-/i.test(value)) {
return null
}
if (/^https:\/\//i.test(value)) {
let url: URL
try {
url = new URL(value)
} catch {
return null
}
if (!CALLBACK_HOSTS.has(url.hostname)) {
return null
}
const code = url.searchParams.get('code')
const state = url.searchParams.get('state')
if (!code) {
return null
}
const joined = state ? `${code}#${state}` : code
return CODE_SHAPE.test(joined) ? joined : null
}
return CODE_SHAPE.test(value) ? value : null
}
@@ -0,0 +1,115 @@
// One Claude "Set up once" run: `claude setup-token` in main, the sign-in link it shows, and the code
// Claude's sign-in page hands back (pasted into Orca, typed into the waiting CLI). It reports setup
// states only; the token goes to `onToken` and nowhere else, and a pasted code is never kept.
import type { OrcaCloudAgentSetup } from '../../shared/orca-cloud-agents/orca-cloud-agents-wire'
import {
runClaudeSetupToken,
type SpawnSetupToken,
type SubmitSetupCode
} from './claude-setup-token-runner'
export type ClaudeSetupRun = {
/** The sign-in link for "Open again", while the CLI is waiting on it. */
url: () => string | null
/** Types a (normalized) code into the waiting CLI; false when it can't take one now. */
submit: (code: string) => boolean
/** Abandons the run (cancel, sign-out, paste instead); nothing it reports afterwards lands. */
stop: () => void
}
export function startClaudeSetupRun(args: {
spawn: SpawnSetupToken
now: () => number
isSignInUrl: (url: string) => boolean
onSetup: (setup: OrcaCloudAgentSetup) => void
onToken: (token: string) => Promise<void>
/** The run is over (any outcome); the caller drops its handle. */
onDone: () => void
}): ClaudeSetupRun {
const controller = new AbortController()
let live = true
let url: string | null = null
let submitter: SubmitSetupCode | null = null
// The CLI showed its sign-in link: a run that ends without a token after that has expired.
let linkShown = false
const startedAt = args.now()
const browser = (extra: { code?: 'checking' | 'rejected' } = {}): void =>
args.onSetup({
phase: 'browser',
startedAt,
canReopen: url !== null,
...(submitter ? { acceptsCode: true } : {}),
...extra
})
browser()
void runClaudeSetupToken({
spawn: args.spawn,
signal: controller.signal,
onAuthorizeUrl: (link) => {
if (live && args.isSignInUrl(link)) {
url = link
linkShown = true
browser()
}
},
onAcceptsCode: (submit) => {
if (live) {
submitter = submit
browser()
}
},
onCodeRejected: () => {
if (live) {
// The CLI starts over: the old link and its code are spent until the new link shows.
url = null
submitter = null
browser({ code: 'rejected' })
}
}
}).then(async (outcome) => {
if (!live) {
return
}
live = false
url = null
submitter = null
args.onDone()
if (outcome.ok) {
await args.onToken(outcome.token)
return
}
if (outcome.error === 'capture_failed' && linkShown) {
// The sign-in was underway and the CLI went away: say it expired; "Open again" starts over.
args.onSetup({ phase: 'failed', error: 'timed_out' })
return
}
switch (outcome.error) {
case 'cancelled':
args.onSetup({ phase: 'idle' })
return
case 'no_cli':
case 'capture_failed':
args.onSetup({ phase: 'paste', reason: outcome.error })
return
case 'denied':
case 'timed_out':
args.onSetup({ phase: 'failed', error: outcome.error })
}
})
return {
url: () => (live ? url : null),
submit: (code) => {
if (!live || !submitter || !submitter(code)) {
return false
}
browser({ code: 'checking' })
return true
},
stop: () => {
live = false
url = null
submitter = null
controller.abort()
}
}
}
@@ -69,7 +69,8 @@ export const spawnClaudeSetupTokenPty: SpawnSetupToken = async () => {
onExit: (listener) => {
child.onExit(({ exitCode }) => listener(exitCode))
},
kill: () => child.kill()
kill: () => child.kill(),
write: (data) => child.write(data)
}
return handle
}
@@ -30,6 +30,7 @@ function fakeChild(): FakeChild {
kill: () => {
child.killed = true
},
write: () => {},
emit: (chunk) => onData(chunk),
exit: (code) => onExit(code)
}
@@ -8,8 +8,13 @@ export type SetupTokenProcess = {
onData(listener: (chunk: string) => void): void
onExit(listener: (exitCode: number | null) => void): void
kill(): void
/** Types into the CLI, like a user at its prompt (the pasted sign-in code). */
write(data: string): void
}
/** Hands the CLI the code from Claude's "Paste this into Claude Code" page. False when it can't take one now. */
export type SubmitSetupCode = (code: string) => boolean
/** Rejects with `{ code: 'ENOENT' }` when there is no `claude` to run. */
export type SpawnSetupToken = () => Promise<SetupTokenProcess>
@@ -46,6 +51,12 @@ const DENIED =
/\baccess_denied\b|authorization (?:request )?(?:was )?denied|sign-?in (?:was )?denied|login (?:was )?denied/i
const AUTHORIZE_HOSTS = new Set(['claude.ai', 'claude.com', 'console.anthropic.com'])
const LINK = /https:\/\/[^\s"'<>]+(?=\s)/g
// The CLI's answer to a pasted code it could not exchange; it then waits for Enter to start over.
const CODE_REJECTED = /code wasn.t accepted|Invalid authorization code|OAuth error/i
// Ink reads a chunk ending in Enter as a paste; the code and the Enter go in separately.
const ENTER_AFTER_CODE_MS = 150
// Long enough to read the rejection; then Enter starts a fresh sign-in (new link, new code).
const RETRY_AFTER_REJECT_MS = 500
function plainText(raw: string): string {
return raw.replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n')
@@ -93,8 +104,12 @@ export function runClaudeSetupToken(options: {
signal: AbortSignal
timeoutMs?: number
onAuthorizeUrl?: (url: string) => void
/** The CLI is waiting at its sign-in prompt: from here a pasted code can finish it. */
onAcceptsCode?: (submit: SubmitSetupCode) => void
/** The CLI refused the pasted code and started over; a new link (onAuthorizeUrl) follows. */
onCodeRejected?: () => void
}): Promise<ClaudeSetupTokenOutcome> {
const { spawn, signal, onAuthorizeUrl } = options
const { spawn, signal, onAuthorizeUrl, onAcceptsCode, onCodeRejected } = options
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
return new Promise((resolve) => {
if (signal.aborted) {
@@ -106,6 +121,8 @@ export function runClaudeSetupToken(options: {
let exited = false
let scanned = ''
let linkSeen = false
// A code was typed in and the CLI hasn't answered yet (token, or a rejection).
let codePending = false
let best: string | null = null
let timer: ReturnType<typeof setTimeout> | null = null
let settleTimer: ReturnType<typeof setTimeout> | null = null
@@ -184,11 +201,39 @@ export function runClaudeSetupToken(options: {
finish({ ok: false, error: 'denied' }, 'kill')
return
}
if (codePending && CODE_REJECTED.test(plainText(scanned))) {
// Start over in the same run: Enter gets a fresh link; the old code page is spent.
codePending = false
linkSeen = false
scanned = ''
onCodeRejected?.()
const retry = setTimeout(() => {
if (!settled && !exited) {
process.write('\r')
}
}, RETRY_AFTER_REJECT_MS)
retry.unref?.()
return
}
if (!linkSeen) {
const url = findAuthorizeUrl(scanned)
if (url) {
linkSeen = true
onAuthorizeUrl?.(url)
onAcceptsCode?.((code) => {
if (settled || exited || !linkSeen || codePending) {
return false
}
codePending = true
process.write(code)
const enter = setTimeout(() => {
if (!settled && !exited) {
process.write('\r')
}
}, ENTER_AFTER_CODE_MS)
enter.unref?.()
return true
})
}
}
})
@@ -25,6 +25,8 @@ const Agent = z.enum(ORCA_CLOUD_ACCOUNT_AGENTS)
const AgentRequest = z.object({ agent: Agent })
// Bounded well above a real token; the service checks the exact shape.
const PasteRequest = z.object({ token: z.string().min(1).max(1024) })
// The code (or callback URL) from Claude's sign-in page; main normalizes it.
const CodeRequest = z.object({ code: z.string().min(1).max(2048) })
const SourceRequest = z.object({ agent: Agent, source: z.enum(['sign-in', 'key']).nullable() })
// A runtime environment, never a raw sandbox id: main resolves only sandboxes this desktop made.
const RuntimeEnvironment = z.string().min(1).max(256)
@@ -32,6 +34,7 @@ const WorkspaceRequest = z.object({ runtimeEnvironmentId: RuntimeEnvironment })
const WorkspaceSourceRequest = SourceRequest.extend({ runtimeEnvironmentId: RuntimeEnvironment })
const CHANNELS = [
'orcaCloudAgents:submitClaudeCode',
'orcaCloudAgents:status',
'orcaCloudAgents:setups',
'orcaCloudAgents:start',
@@ -135,6 +138,10 @@ export function registerOrcaCloudAgentsHandlers(userDataPath: string): void {
return request.success ? service.reopen(request.data.agent) : false
})
ipcMain.handle('orcaCloudAgents:usePaste', () => service.usePaste())
ipcMain.handle('orcaCloudAgents:submitClaudeCode', (_event, raw: unknown) => {
const request = CodeRequest.safeParse(raw)
return request.success ? service.submitClaudeCode(request.data.code) : invalid
})
ipcMain.handle('orcaCloudAgents:pasteClaudeToken', (_event, raw: unknown) => {
const request = PasteRequest.safeParse(raw)
return request.success ? service.pasteClaudeToken(request.data.token) : invalid
@@ -27,6 +27,7 @@ function fakeChild() {
onExit = l
},
kill: vi.fn(),
write: vi.fn(),
emit: (c) => onData(c),
exit: () => onExit(0)
}
@@ -17,7 +17,9 @@ import {
agentCredentialsFailureCode,
type AgentCredentialsClient
} from './agent-credentials-client'
import { runClaudeSetupToken, type SpawnSetupToken } from './claude-setup-token-runner'
import type { SpawnSetupToken } from './claude-setup-token-runner'
import { normalizeClaudeSetupCode } from './claude-setup-code'
import { startClaudeSetupRun, type ClaudeSetupRun } from './claude-setup-run'
import {
isCodexSignInUrl,
startCodexBrokerSession,
@@ -64,8 +66,7 @@ export function isProviderSignInUrl(agent: OrcaCloudAccountAgent, value: string)
export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
const now = deps.now ?? Date.now
let setups: OrcaCloudAgentSetups = { ...IDLE_ORCA_CLOUD_AGENT_SETUPS }
let claudeRun: AbortController | null = null
let claudeUrl: string | null = null
let claudeRun: ClaudeSetupRun | null = null
let codexSession: CodexBrokerSession | null = null
let codexRun: { live: boolean } | null = null
// A captured or pasted token is being stored: it can't be cancelled or raced by another one.
@@ -83,9 +84,8 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
}
function stopClaudeRun(): void {
claudeRun?.abort()
claudeRun?.stop()
claudeRun = null
claudeUrl = null
}
function stopCodexRun(): CodexBrokerSession | null {
@@ -155,43 +155,21 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
return
}
const owner = identity()
const controller = new AbortController()
claudeRun = controller
claudeUrl = null
const startedAt = now()
update('claude', { phase: 'browser', startedAt, canReopen: false })
void runClaudeSetupToken({
const run: ClaudeSetupRun = startClaudeSetupRun({
spawn: deps.spawnSetupToken,
signal: controller.signal,
onAuthorizeUrl: (url) => {
if (claudeRun === controller && isProviderSignInUrl('claude', url)) {
claudeUrl = url
update('claude', { phase: 'browser', startedAt, canReopen: true })
now,
isSignInUrl: (url) => isProviderSignInUrl('claude', url),
onSetup: (setup) => update('claude', setup),
onToken: async (token) => {
await storeClaude(token, deps.readClaudeEmail(), owner)
},
onDone: () => {
if (claudeRun === run) {
claudeRun = null
}
}
}).then(async (outcome) => {
if (claudeRun !== controller) {
return
}
claudeRun = null
claudeUrl = null
if (outcome.ok) {
await storeClaude(outcome.token, deps.readClaudeEmail(), owner)
return
}
switch (outcome.error) {
case 'cancelled':
update('claude', { phase: 'idle' })
return
case 'no_cli':
case 'capture_failed':
update('claude', { phase: 'paste', reason: outcome.error })
return
case 'denied':
case 'timed_out':
update('claude', { phase: 'failed', error: outcome.error })
}
})
claudeRun = run
}
function startCodex(): void {
@@ -271,8 +249,18 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
/** "Open again" (Claude) / "Open page" (Codex): the provider's page, never anything else. */
reopen: async (agent: OrcaCloudAccountAgent): Promise<boolean> => {
const current = setups[agent]
if (agent === 'claude' && !claudeRun && !claudeSaving && current.phase === 'failed') {
// Expired (timed out, or the CLI went away): a fresh setup-token run with a new link.
followIdentity()
startClaude()
return true
}
const url =
agent === 'claude' ? claudeUrl : current.phase === 'device' ? current.verificationUrl : null
agent === 'claude'
? (claudeRun?.url() ?? null)
: current.phase === 'device'
? current.verificationUrl
: null
if (!url || !isProviderSignInUrl(agent, url)) {
return false
}
@@ -280,6 +268,20 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
return true
},
/**
* The code from Claude's sign-in page, typed into the waiting setup-token. The reply is a code
* only; the value is never logged, stored or echoed. The CLI's answer arrives as a setup update.
*/
submitClaudeCode: (raw: string): OrcaCloudAgentsResult<true> => {
const code = normalizeClaudeSetupCode(raw)
if (!code) {
return { ok: false, error: 'invalid_code' }
}
return claudeRun?.submit(code)
? { ok: true, value: true }
: { ok: false, error: 'unavailable' }
},
/** "Paste the token instead": stop setup-token and show the masked field. */
usePaste: (): void => {
if (claudeSaving) {
@@ -17,6 +17,8 @@ export type OrcaCloudAgentsApi = {
cancel: (request: { agent: OrcaCloudAccountAgent }) => Promise<void>
reopen: (request: { agent: OrcaCloudAccountAgent }) => Promise<boolean>
usePaste: () => Promise<void>
/** The code from Claude's sign-in page, typed into the waiting setup; the reply is a code only. */
submitClaudeCode: (request: { code: string }) => Promise<OrcaCloudAgentsResult<true>>
/** The pasted value goes to main once; the reply is a code only. */
pasteClaudeToken: (request: { token: string }) => Promise<OrcaCloudAgentsResult<true>>
acknowledge: (request: { agent: OrcaCloudAccountAgent }) => Promise<void>
@@ -47,6 +49,7 @@ export const orcaCloudAgentsApi: OrcaCloudAgentsApi = {
cancel: (request) => ipcRenderer.invoke('orcaCloudAgents:cancel', request),
reopen: (request) => ipcRenderer.invoke('orcaCloudAgents:reopen', request),
usePaste: () => ipcRenderer.invoke('orcaCloudAgents:usePaste'),
submitClaudeCode: (request) => ipcRenderer.invoke('orcaCloudAgents:submitClaudeCode', request),
pasteClaudeToken: (request) => ipcRenderer.invoke('orcaCloudAgents:pasteClaudeToken', request),
acknowledge: (request) => ipcRenderer.invoke('orcaCloudAgents:acknowledge', request),
remove: (request) => ipcRenderer.invoke('orcaCloudAgents:remove', request),
@@ -15,7 +15,7 @@ import {
} from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { CloudStripPasteForm } from './CloudStripPasteForm'
import {
DropdownMenu,
DropdownMenuContent,
@@ -88,6 +88,8 @@ export function CloudStripLayer({ children }: { children: React.ReactNode }): Re
export type CloudStripActions = {
primary: (action: CloudStripPrimary) => void
submitCode: (code: string) => void
/** The code from Claude's sign-in page, for the waiting setup-token (Set up once). */
submitSetupCode?: (code: string) => void
useCode: () => void
/** From a device code to pasting a code (the gate's code fallback). */
pasteCode: () => void
@@ -155,7 +157,6 @@ export function CloudAgentSignInStrip({
const t = useTranslate()
const titleId = React.useId()
const detailId = React.useId()
const [code, setCode] = useState('')
const primary = model.primary
return (
<section
@@ -236,36 +237,11 @@ export function CloudAgentSignInStrip({
</code>
) : null}
{model.paste ? (
<form
className="flex min-w-0 items-center gap-1.5"
onSubmit={(event) => {
event.preventDefault()
if (code.trim()) {
actions.submitCode(code.trim())
}
}}
>
<Input
aria-label={
model.paste.secretLabel ?? t('agentSignInStrip.pasteLabel', 'Code from claude.ai')
}
type={model.paste.secretLabel ? 'password' : undefined}
autoComplete={model.paste.secretLabel ? 'off' : undefined}
aria-invalid={model.paste.refusal ? true : undefined}
value={code}
onChange={(event) => setCode(event.target.value)}
variant="code"
className="h-7 min-w-0"
/>
<Button
type="submit"
size="xs"
aria-busy={model.paste.submitting || undefined}
aria-disabled={model.paste.submitting || undefined}
>
{t('agentSignInStrip.continue', 'Continue')}
</Button>
</form>
<CloudStripPasteForm
paste={model.paste}
onSubmitCode={actions.submitCode}
onSubmitSetupCode={actions.submitSetupCode}
/>
) : null}
{primary ? (
<Button
@@ -0,0 +1,91 @@
// The strip's paste input: a claude.ai code (RA-11), a setup-token (PC-3b), or the code Claude's
// sign-in page shows for the waiting setup-token (Set up once). Secrets are masked; a setup code is
// cleared as soon as it's sent and goes on its own when a whole one is pasted.
import React, { useEffect, useRef, useState } from 'react'
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import type { CloudStripModel } from './cloud-agent-strip-model'
/** A pasted value that is a whole code (`code#state`) or the callback URL carrying one. */
export function looksLikeWholeSetupCode(value: string): boolean {
const text = value.trim()
return /^https:\/\/\S+[?&]code=/.test(text) || /^[A-Za-z0-9_-]{8,}#[A-Za-z0-9_-]{8,}$/.test(text)
}
export function CloudStripPasteForm({
paste,
onSubmitCode,
onSubmitSetupCode
}: {
paste: NonNullable<CloudStripModel['paste']>
onSubmitCode: (code: string) => void
onSubmitSetupCode?: (code: string) => void
}): React.JSX.Element {
const t = useTranslate()
const [code, setCode] = useState('')
const inputRef = useRef<HTMLInputElement | null>(null)
const setupCode = paste.setupCode
const busy = paste.submitting
// A refused code: the field is already empty; keep the person's place in it.
useEffect(() => {
if (paste.refusal) {
inputRef.current?.focus()
}
}, [paste.refusal])
const send = (value: string): void => {
const trimmed = value.trim()
if (!trimmed || busy) {
return
}
if (setupCode && onSubmitSetupCode) {
// Never kept on screen or in state once it's on its way.
setCode('')
onSubmitSetupCode(trimmed)
return
}
onSubmitCode(trimmed)
}
return (
<form
className="flex min-w-0 items-center gap-1.5"
onSubmit={(event) => {
event.preventDefault()
send(code)
}}
>
<Input
ref={inputRef}
aria-label={paste.secretLabel ?? t('agentSignInStrip.pasteLabel', 'Code from claude.ai')}
placeholder={setupCode?.placeholder}
type={paste.secretLabel ? 'password' : undefined}
autoComplete={paste.secretLabel ? 'off' : undefined}
aria-invalid={paste.refusal ? true : undefined}
disabled={setupCode ? busy : undefined}
value={code}
onChange={(event) => setCode(event.target.value)}
onPaste={(event) => {
if (!setupCode) {
return
}
const pasted = event.clipboardData.getData('text')
if (looksLikeWholeSetupCode(pasted)) {
event.preventDefault()
send(pasted)
}
}}
variant="code"
className="h-7 min-w-0"
/>
<Button
type="submit"
size="xs"
disabled={setupCode ? busy || !code.trim() : undefined}
aria-busy={busy || undefined}
aria-disabled={busy || undefined}
>
{setupCode ? setupCode.submitLabel : t('agentSignInStrip.continue', 'Continue')}
</Button>
</form>
)
}
@@ -27,6 +27,34 @@ function base(agent: string, t: Translate): CloudStripModel {
}
}
export function setupCodePaste(
agent: HostAgentSignInAgent,
code: 'checking' | 'rejected' | undefined,
t: Translate
): NonNullable<CloudStripModel['paste']> {
const name = HOST_AGENT_SIGN_IN_AGENT_NAME[agent]
return {
submitting: code === 'checking',
refusal:
code === 'rejected'
? t(
'agentSignInStrip.setupCodeRejected',
'That code didn’t work. Paste the newest code from the sign-in page, or open it again.'
)
: null,
secretLabel: t('agentSignInStrip.setupCodeLabel', 'Code from {{agent}}’s sign-in page', {
agent: name
}),
setupCode: {
placeholder: t('agentSignInStrip.setupCodePlaceholder', 'Paste code'),
submitLabel:
code === 'checking'
? t('agentSignInStrip.setupCodeChecking', 'Checking the code…')
: t('agentSignInStrip.finishSetup', 'Finish setup')
}
}
}
export function cloudAgentSetupStripModel(args: {
agent: HostAgentSignInAgent
setup: OrcaCloudAgentSetup
@@ -67,7 +95,14 @@ export function cloudAgentSetupStripModel(args: {
return {
...need,
status: 'busy',
detail: t('agentSignInStrip.finishInBrowser', 'Finish in your browser'),
detail: setup.acceptsCode
? t(
'agentSignInStrip.finishInBrowserPaste',
'Finish in your browser, then paste the code here.'
)
: t('agentSignInStrip.finishInBrowser', 'Finish in your browser'),
// Claude's page shows a code to bring back: [Paste code] [Finish setup] [Open again].
paste: setup.acceptsCode ? setupCodePaste(args.agent, setup.code, t) : null,
primary: setup.canReopen
? {
label: t('agentSignInStrip.openAgain', 'Open again'),
@@ -135,10 +170,14 @@ export function cloudAgentSetupStripModel(args: {
status: 'error',
title: copy.title,
detail: copy.detail ?? need.detail,
primary: {
label: t('agentSignInStrip.tryAgain', 'Try again'),
action: { kind: 'setUpOnce' }
},
// An expired sign-in: "Open again" starts a fresh one with a new link (main restarts it).
primary:
setup.error === 'timed_out'
? {
label: t('agentSignInStrip.openAgain', 'Open again'),
action: { kind: 'reopenSetup' }
}
: { label: t('agentSignInStrip.tryAgain', 'Try again'), action: { kind: 'setUpOnce' } },
announcement: copy.title
}
}
@@ -43,6 +43,11 @@ export type CloudStripModel = {
refusal: string | null
/** PC-3b: a setup-token is a secret: masked, with this label (default: the claude.ai code). */
secretLabel?: string
/**
* The code Claude's sign-in page shows, for the waiting setup-token (Set up once): masked, cleared
* once sent, and sent on its own when a whole code is pasted.
*/
setupCode?: { placeholder: string; submitLabel: string }
} | null
/** "Other ways" under ⋯: the code fallback and the key path. */
otherWays: boolean
@@ -0,0 +1,74 @@
// P0 "Set up once": the strip (terminal pane and chat UI) takes the code Claude's sign-in page shows.
import { describe, expect, it } from 'vitest'
import type { Translate } from '@/i18n/use-translate'
import { cloudAgentSetupStripModel } from './cloud-agent-setup-strip-model'
import { looksLikeWholeSetupCode } from './CloudStripPasteForm'
const t: Translate = (_key, fallback, options) =>
fallback.replace(/\{\{(\w+)\}\}/g, (_m, name: string) => String(options?.[name] ?? ''))
const model = (setup: Parameters<typeof cloudAgentSetupStripModel>[0]['setup']) =>
cloudAgentSetupStripModel({ agent: 'claude', setup, ready: false, t })
describe('the setup strip with a code to paste back', () => {
it('before the CLI waits for a code: no field, the plain browser detail', () => {
const strip = model({ phase: 'browser', startedAt: 1, canReopen: false })
expect(strip.paste).toBeNull()
expect(strip.detail).toBe('Finish in your browser')
})
it('[Paste code] [Finish setup] [Open again], masked, with the paste hint', () => {
const strip = model({ phase: 'browser', startedAt: 1, canReopen: true, acceptsCode: true })
expect(strip.detail).toBe('Finish in your browser, then paste the code here.')
expect(strip.paste).toMatchObject({
submitting: false,
refusal: null,
secretLabel: 'Code from Claude’s sign-in page',
setupCode: { placeholder: 'Paste code', submitLabel: 'Finish setup' }
})
expect(strip.primary).toMatchObject({ label: 'Open again', action: { kind: 'reopenSetup' } })
})
it('checking, then a refused code keeps the field with one message', () => {
const checking = model({
phase: 'browser',
startedAt: 1,
canReopen: true,
acceptsCode: true,
code: 'checking'
})
expect(checking.paste).toMatchObject({
submitting: true,
setupCode: { submitLabel: 'Checking the code…' }
})
const refused = model({
phase: 'browser',
startedAt: 1,
canReopen: false,
acceptsCode: true,
code: 'rejected'
})
expect(refused.paste?.refusal).toBe(
'That code didn’t work. Paste the newest code from the sign-in page, or open it again.'
)
})
it('an expired sign-in stops spinning and offers "Open again" (a fresh run)', () => {
const expired = model({ phase: 'failed', error: 'timed_out' })
expect(expired.status).toBe('error')
expect(expired.primary).toMatchObject({ label: 'Open again', action: { kind: 'reopenSetup' } })
})
})
describe('looksLikeWholeSetupCode (auto-submit on paste)', () => {
it('takes a whole code or the callback URL, not a fragment', () => {
expect(looksLikeWholeSetupCode(' FAKEcode0123456789#FAKEstate0123 ')).toBe(true)
expect(
looksLikeWholeSetupCode(
'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123&state=s'
)
).toBe(true)
expect(looksLikeWholeSetupCode('FAKEcode0123456789')).toBe(false)
expect(looksLikeWholeSetupCode('FAKE#x')).toBe(false)
})
})
@@ -42,6 +42,10 @@ export function cloudSetupStripActions(args: {
.then(() => reloadOrcaCloudAgentAccounts())
.catch(() => undefined)
},
submitSetupCode: (code) => {
// The CLI's answer comes back as a setup update (checking, then saved or rejected).
void api?.submitClaudeCode({ code }).catch(() => undefined)
},
useCode: () => undefined,
pasteCode: () => void api?.usePaste(),
useApiKey: args.useApiKey,
@@ -17,6 +17,7 @@ const ACTIONS: OrcaCloudAccountsActions = {
cancel: noop,
reopen: noop,
usePaste: noop,
submitSetupCode: noop,
pasteToken: async () => null,
remove: async () => null,
setSource: async () => null,
@@ -41,6 +41,7 @@ export function OrcaCloudAccountsSection({
start: (agent) => void api?.start({ agent }),
cancel: (agent) => void api?.cancel({ agent }),
reopen: (agent) => void api?.reopen({ agent }),
submitSetupCode: (code) => void api?.submitClaudeCode({ code }).catch(() => undefined),
usePaste: () => void api?.usePaste(),
pasteToken: async (token) => {
if (!api) {
@@ -12,6 +12,8 @@ import type {
import { SecretValueInput } from '../cloud-secrets/SecretValueInput'
import { ElapsedSuffix, RowShell } from './orca-cloud-account-row-shell'
import { setupFailureCopy } from './orca-cloud-accounts-copy'
import { CloudStripPasteForm } from '@/components/agent-sign-in-strip/CloudStripPasteForm'
import { setupCodePaste } from '@/components/agent-sign-in-strip/cloud-agent-setup-strip-model'
import type { OrcaCloudAccountsActions } from './orca-cloud-accounts-types'
function PasteTokenForm({
@@ -151,12 +153,33 @@ export function SetupRow({
<ElapsedSuffix startedAt={setup.startedAt} now={now} />
</>
}
detail={t(
'orcaCloudAccounts.settingUpClaudeDetail',
'Orca runs claude setup-token on this computer, then saves the result to your Orca account.'
)}
detail={
setup.code === 'rejected'
? t(
'agentSignInStrip.setupCodeRejected',
'That code didn’t work. Paste the newest code from the sign-in page, or open it again.'
)
: setup.acceptsCode
? t(
'agentSignInStrip.finishInBrowserPaste',
'Finish in your browser, then paste the code here.'
)
: t(
'orcaCloudAccounts.settingUpClaudeDetail',
'Orca runs claude setup-token on this computer, then saves the result to your Orca account.'
)
}
detailTone={setup.code === 'rejected' ? 'warning' : undefined}
actions={
<>
{/* Same order on every surface: [Paste code] [Finish setup] [Open again]. */}
{setup.acceptsCode ? (
<CloudStripPasteForm
paste={setupCodePaste(agent, setup.code, t)}
onSubmitCode={() => undefined}
onSubmitSetupCode={(code) => actions.submitSetupCode?.(code)}
/>
) : null}
{setup.canReopen ? (
<Button
type="button"
@@ -11,6 +11,8 @@ export type OrcaCloudAccountsActions = {
cancel: (agent: OrcaCloudAccountAgent) => void
reopen: (agent: OrcaCloudAccountAgent) => void
usePaste: () => void
/** The code from Claude's sign-in page, for the waiting setup-token; the answer is a setup update. */
submitSetupCode?: (code: string) => void
/** Resolves with a code when the token wasn't stored; the value is never echoed back. */
pasteToken: (token: string) => Promise<OrcaCloudAgentsErrorCode | null>
remove: (agent: OrcaCloudAccountAgent) => Promise<OrcaCloudAgentsErrorCode | null>
@@ -69,7 +69,13 @@ function setupText(
return {
title,
tag,
detail: t('vmBuildAgents.finishInBrowser', 'Finish in your browser')
// This row has no field: the code goes in where setup has one (the pane, Settings).
detail: model.setup.acceptsCode
? t(
'vmBuildAgents.finishInBrowserPaste',
'Finish in your browser, then paste the code in Settings → Agent accounts.'
)
: t('vmBuildAgents.finishInBrowser', 'Finish in your browser')
}
case 'preparing':
return {
@@ -109,6 +109,8 @@ export const ORCA_CLOUD_AGENTS_ERROR_CODES = [
/** The provider's flag is off or its kill switch is on (404 from the credential routes). */
'not_enabled',
'invalid_token',
/** A pasted sign-in code that isn't one (Claude's "Paste this into Claude Code" page). */
'invalid_code',
'not_found',
'broker_in_progress',
'rate_limited',
@@ -145,8 +147,17 @@ export type OrcaCloudAgentSetupFailure =
/** The one setup step running on this computer for an agent (spec §5 state 6). */
export type OrcaCloudAgentSetup =
| { phase: 'idle' }
/** Claude: setup-token is running and the browser is open ("Finish in your browser"). */
| { phase: 'browser'; startedAt: number; canReopen: boolean }
/**
* Claude: setup-token is running and the browser is open ("Finish in your browser"). `acceptsCode`:
* the CLI is waiting for the code Claude's sign-in page shows; `code` is the pasted one's progress.
*/
| {
phase: 'browser'
startedAt: number
canReopen: boolean
acceptsCode?: boolean
code?: 'checking' | 'rejected'
}
/** Codex: the broker is starting. */
| { phase: 'preparing'; startedAt: number }
/** Codex: enter the code on the provider's page. The code is meant to be shown; it isn't a secret. */