diff --git a/src/main/orca-cloud-agents/claude-setup-code.test.ts b/src/main/orca-cloud-agents/claude-setup-code.test.ts new file mode 100644 index 00000000000..6eadb4bfbe8 --- /dev/null +++ b/src/main/orca-cloud-agents/claude-setup-code.test.ts @@ -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 => { + 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[] = [] + 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() + } + }) +}) diff --git a/src/main/orca-cloud-agents/claude-setup-code.ts b/src/main/orca-cloud-agents/claude-setup-code.ts new file mode 100644 index 00000000000..a3a41c06f08 --- /dev/null +++ b/src/main/orca-cloud-agents/claude-setup-code.ts @@ -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 +} diff --git a/src/main/orca-cloud-agents/claude-setup-run.ts b/src/main/orca-cloud-agents/claude-setup-run.ts new file mode 100644 index 00000000000..bc6819025f7 --- /dev/null +++ b/src/main/orca-cloud-agents/claude-setup-run.ts @@ -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 + /** 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() + } + } +} diff --git a/src/main/orca-cloud-agents/claude-setup-token-pty.ts b/src/main/orca-cloud-agents/claude-setup-token-pty.ts index 8657255a2ff..78a729bdd85 100644 --- a/src/main/orca-cloud-agents/claude-setup-token-pty.ts +++ b/src/main/orca-cloud-agents/claude-setup-token-pty.ts @@ -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 } diff --git a/src/main/orca-cloud-agents/claude-setup-token-runner.test.ts b/src/main/orca-cloud-agents/claude-setup-token-runner.test.ts index 2d6de9c7c02..52878d4dc12 100644 --- a/src/main/orca-cloud-agents/claude-setup-token-runner.test.ts +++ b/src/main/orca-cloud-agents/claude-setup-token-runner.test.ts @@ -30,6 +30,7 @@ function fakeChild(): FakeChild { kill: () => { child.killed = true }, + write: () => {}, emit: (chunk) => onData(chunk), exit: (code) => onExit(code) } diff --git a/src/main/orca-cloud-agents/claude-setup-token-runner.ts b/src/main/orca-cloud-agents/claude-setup-token-runner.ts index 1f24ce5761a..1cb3901a860 100644 --- a/src/main/orca-cloud-agents/claude-setup-token-runner.ts +++ b/src/main/orca-cloud-agents/claude-setup-token-runner.ts @@ -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 @@ -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 { - 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 | null = null let settleTimer: ReturnType | 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 + }) } } }) diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts index 8051f811b90..f9b680c6c4d 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-ipc.ts @@ -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 diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts index fda0ea62b67..fc62da9d9bb 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.test.ts @@ -27,6 +27,7 @@ function fakeChild() { onExit = l }, kill: vi.fn(), + write: vi.fn(), emit: (c) => onData(c), exit: () => onExit(0) } diff --git a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts index 5b0922cd54d..2c8f9073388 100644 --- a/src/main/orca-cloud-agents/orca-cloud-agents-service.ts +++ b/src/main/orca-cloud-agents/orca-cloud-agents-service.ts @@ -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 => { 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 => { + 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) { diff --git a/src/preload/api/orca-cloud-agents-bridge.ts b/src/preload/api/orca-cloud-agents-bridge.ts index 046b04a2c00..ce88eaa8d7c 100644 --- a/src/preload/api/orca-cloud-agents-bridge.ts +++ b/src/preload/api/orca-cloud-agents-bridge.ts @@ -17,6 +17,8 @@ export type OrcaCloudAgentsApi = { cancel: (request: { agent: OrcaCloudAccountAgent }) => Promise reopen: (request: { agent: OrcaCloudAccountAgent }) => Promise usePaste: () => Promise + /** The code from Claude's sign-in page, typed into the waiting setup; the reply is a code only. */ + submitClaudeCode: (request: { code: string }) => Promise> /** The pasted value goes to main once; the reply is a code only. */ pasteClaudeToken: (request: { token: string }) => Promise> acknowledge: (request: { agent: OrcaCloudAccountAgent }) => Promise @@ -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), diff --git a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx index 3a7fe13d653..b75344763d7 100644 --- a/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx +++ b/src/renderer/src/components/agent-sign-in-strip/CloudAgentSignInStrip.tsx @@ -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 (
) : null} {model.paste ? ( -
{ - event.preventDefault() - if (code.trim()) { - actions.submitCode(code.trim()) - } - }} - > - setCode(event.target.value)} - variant="code" - className="h-7 min-w-0" - /> - -
+ ) : null} {primary ? ( + + ) +} diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts index fbdda7fc86b..554057261b3 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-setup-strip-model.ts @@ -27,6 +27,34 @@ function base(agent: string, t: Translate): CloudStripModel { } } +export function setupCodePaste( + agent: HostAgentSignInAgent, + code: 'checking' | 'rejected' | undefined, + t: Translate +): NonNullable { + 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 } } diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts index 9d0ea1964ef..44add7d3bf2 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-agent-strip-model.ts @@ -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 diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-code-strip.test.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-code-strip.test.ts new file mode 100644 index 00000000000..9294ce82b11 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-code-strip.test.ts @@ -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[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) + }) +}) diff --git a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts index 336c3009840..78a4d6439bb 100644 --- a/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts +++ b/src/renderer/src/components/agent-sign-in-strip/cloud-setup-strip-actions.ts @@ -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, diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx index 7e366be90d8..681a2688dea 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccounts.fixture.tsx @@ -17,6 +17,7 @@ const ACTIONS: OrcaCloudAccountsActions = { cancel: noop, reopen: noop, usePaste: noop, + submitSetupCode: noop, pasteToken: async () => null, remove: async () => null, setSource: async () => null, diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx index 5f837a0efee..8b708933393 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudAccountsSection.tsx @@ -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) { diff --git a/src/renderer/src/components/settings/agent-accounts/OrcaCloudSetupRow.tsx b/src/renderer/src/components/settings/agent-accounts/OrcaCloudSetupRow.tsx index 5a381a4019f..e3660cec484 100644 --- a/src/renderer/src/components/settings/agent-accounts/OrcaCloudSetupRow.tsx +++ b/src/renderer/src/components/settings/agent-accounts/OrcaCloudSetupRow.tsx @@ -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({ } - 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 ? ( + undefined} + onSubmitSetupCode={(code) => actions.submitSetupCode?.(code)} + /> + ) : null} {setup.canReopen ? (