From 700cfcb3964555a41eac7defdbb1458719be6c35 Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 9 Nov 2026 00:07:34 -0800 Subject: [PATCH] feat(remote): sign agents in from the pane with one browser approval on the host Starting Claude or Codex on a runtime host where it isn't signed in holds the launch behind an inline card. Sign in with browser runs the unmodified CLI login on the host; this computer forwards the browser's localhost callback to it over a narrowly scoped tunnel, so the token never leaves the host. Adds a verdict-only host check, agent sign-out in the host menu, and paste/device-code fallbacks. --- config/direct-link-open-baseline.txt | 9 +- .../claude-pasted-code-login.ts | 94 ++++- .../claude-accounts/claude-sign-in-browser.ts | 2 +- src/main/claude/claude-auth-status-report.ts | 46 +++ .../codex-accounts/codex-login-session.ts | 4 +- .../codex-remote-browser-login.ts | 21 + src/main/codex-accounts/service.ts | 12 +- .../auth-callback-forward.ts | 299 +++++++++++++++ .../runtime-environment-handler-channels.ts | 4 +- .../runtime-environments.ts | 2 + .../host-account-sign-in-flows.test.ts | 22 ++ .../environment/host-account-sign-in-flows.ts | 36 +- .../host-agent-sign-in-status.test.ts | 169 +++++++++ .../environment/host-agent-sign-in-status.ts | 239 ++++++++++++ .../runtime/rpc/methods/accounts/accounts.ts | 6 +- .../methods/accounts/agent-sign-in-methods.ts | 73 ++++ .../accounts/auth-callback-tunnel.test.ts | 49 +++ .../methods/accounts/auth-callback-tunnel.ts | 181 +++++++++ src/preload/api/runtime-api.ts | 11 + .../api/runtime-environments-bridge.ts | 11 + .../agent-sign-in/AgentSignInCard.fixture.tsx | 101 +++++ .../agent-sign-in/AgentSignInCard.tsx | 359 ++++++++++++++++++ .../agent-sign-in/AgentSignInOverlay.tsx | 11 + .../agent-sign-in/AgentSignInPanePortals.tsx | 89 +++++ .../AgentSignInPasteCodeForm.tsx | 58 +++ .../HostAgentSignOutMenuItems.fixture.tsx | 44 +++ .../rows/HostAgentSignOutMenuItems.tsx | 107 ++++++ .../rows/HostSectionHeaderMenu.tsx | 8 + .../controller/TerminalPaneSurface.tsx | 2 + .../spawn/agent-sign-in-spawn-gate.ts | 106 ++++++ .../pty-connection/spawn/fresh-spawn-start.ts | 2 + src/renderer/src/i18n/locales/en.json | 49 +++ .../agent-sign-in-gate-store.test.ts | 51 +++ .../agent-sign-in/agent-sign-in-gate-store.ts | 222 +++++++++++ .../lib/agent-sign-in/agent-sign-in-gate.ts | 306 +++++++++++++++ .../host-agent-launch-sign-in.ts | 26 ++ .../worktree-creation-flow-execute.ts | 5 +- .../host-agent-sign-in-status-client.ts | 101 +++++ .../runtime-host-account-sign-in-client.ts | 30 +- src/shared/account-runtime-capabilities.ts | 10 +- src/shared/auth-callback-forward.ts | 15 + src/shared/host-account-sign-in-types.ts | 25 ++ src/shared/host-agent-sign-in-status.ts | 21 + src/shared/rpc-contract/accounts-params.ts | 12 +- .../rpc-params-catalog.generated.ts | 6 + tests/e2e/agent-host-sign-in.spec.ts | 179 +++++++++ .../e2e/helpers/agent-sign-in-fake-claude.ts | 86 +++++ tests/e2e/helpers/agent-sign-in-fake-codex.ts | 75 ++++ 48 files changed, 3364 insertions(+), 32 deletions(-) create mode 100644 src/main/claude/claude-auth-status-report.ts create mode 100644 src/main/codex-accounts/codex-remote-browser-login.ts create mode 100644 src/main/ipc/runtime-environments/auth-callback-forward.ts create mode 100644 src/main/runtime/agent-session/environment/host-agent-sign-in-status.test.ts create mode 100644 src/main/runtime/agent-session/environment/host-agent-sign-in-status.ts create mode 100644 src/main/runtime/rpc/methods/accounts/agent-sign-in-methods.ts create mode 100644 src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.test.ts create mode 100644 src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.ts create mode 100644 src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx create mode 100644 src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx create mode 100644 src/renderer/src/components/agent-sign-in/AgentSignInOverlay.tsx create mode 100644 src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx create mode 100644 src/renderer/src/components/agent-sign-in/AgentSignInPasteCodeForm.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.fixture.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx create mode 100644 src/renderer/src/components/terminal-pane/pty-connection/spawn/agent-sign-in-spawn-gate.ts create mode 100644 src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts create mode 100644 src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts create mode 100644 src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts create mode 100644 src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts create mode 100644 src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts create mode 100644 src/shared/auth-callback-forward.ts create mode 100644 src/shared/host-agent-sign-in-status.ts create mode 100644 tests/e2e/agent-host-sign-in.spec.ts create mode 100644 tests/e2e/helpers/agent-sign-in-fake-claude.ts create mode 100644 tests/e2e/helpers/agent-sign-in-fake-codex.ts diff --git a/config/direct-link-open-baseline.txt b/config/direct-link-open-baseline.txt index 2676e9c9328..8c0d8c0bdb3 100644 --- a/config/direct-link-open-baseline.txt +++ b/config/direct-link-open-baseline.txt @@ -16,6 +16,8 @@ 2 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-context-menu.tsx 1 src/renderer/src/components/browser-pane/stream-remote/remote-browser-page-viewport.tsx 1 src/renderer/src/components/dashboard-popout/preview-terminal-links.ts +1 src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx +1 src/renderer/src/components/integrations/source-control/bitbucket-integration-card.tsx 1 src/renderer/src/components/jira-connect-credential-guide.tsx 2 src/renderer/src/components/linear-api-key-dialog.tsx 1 src/renderer/src/components/native-chat/media/images/NativeChatMarkdownImage.tsx @@ -23,14 +25,13 @@ 1 src/renderer/src/components/right-sidebar/ssh-forwarded-ports-section.tsx 1 src/renderer/src/components/right-sidebar/ssh-ports-panel.tsx 1 src/renderer/src/components/settings/accounts/codex/CodexLoginLinkNotice.tsx -1 src/renderer/src/components/settings/general/GeneralSupportSection.tsx 1 src/renderer/src/components/settings/accounts/sign-in/HostAccountSignInPrompt.tsx +1 src/renderer/src/components/settings/general/GeneralSupportSection.tsx 1 src/renderer/src/components/settings/updates/ReleaseChannelSection.tsx -1 src/renderer/src/components/integrations/source-control/bitbucket-credentials-dialog.tsx -1 src/renderer/src/components/integrations/source-control/bitbucket-integration-card.tsx -1 src/renderer/src/components/stats/ShareUsageButton.tsx 1 src/renderer/src/components/star-nag/StarNagToastHost.tsx +1 src/renderer/src/components/stats/ShareUsageButton.tsx 1 src/renderer/src/components/tab-bar/BrowserTab.tsx +1 src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts 1 src/renderer/src/lib/browser/navigation/http-link-routing.ts 1 src/renderer/src/lib/workspace-ports/workspace-port-actions.ts 1 src/renderer/src/runtime/provider-accounts/sign-in/antigravity-chat-sign-in-status.ts diff --git a/src/main/claude-accounts/claude-pasted-code-login.ts b/src/main/claude-accounts/claude-pasted-code-login.ts index 08e84cde607..c4a7db7c2ee 100644 --- a/src/main/claude-accounts/claude-pasted-code-login.ts +++ b/src/main/claude-accounts/claude-pasted-code-login.ts @@ -1,11 +1,18 @@ +import { setTimeout as delay } from 'node:timers/promises' import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences' -import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' +import { + signInCallbackPort, + type HostAccountSignInChannel, + type HostAccountSignInPrompt +} from '../../shared/host-account-sign-in-types' import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process' import { isClaudeLocalSignInLink, prepareClaudeSignInBrowser } from './claude-sign-in-browser' // Match the desktop login window and allow time to sign in on another device. const LOGIN_TIMEOUT_MS = 600_000 const MAX_SCAN_CHARS = 8_000 +// Claude prints its paste-code page right after handing BROWSER the callback link. +const PASTE_LINK_GRACE_MS = 2_000 const CLAUDE_AUTHORIZE_HOSTS = new Set(['claude.com', 'claude.ai']) const CLAUDE_SIGN_IN_CANCELLED_MESSAGE = 'Claude sign-in was cancelled.' export const CLAUDE_PASTED_CODE_REJECTED_MESSAGE = @@ -51,6 +58,7 @@ export async function runClaudePastedCodeLogin( throw new Error(CLAUDE_SIGN_IN_CANCELLED_MESSAGE) } const controller = new AbortController() + const linkWatch = new AbortController() const abort = (): boolean => { if (controller.signal.aborted) { return false @@ -60,14 +68,43 @@ export async function runClaudePastedCodeLogin( } setCancel(abort) channel.signal.addEventListener('abort', abort, { once: true }) + controller.signal.addEventListener('abort', () => linkWatch.abort(), { once: true }) let scanned = '' let prompted = false + let pasteUrl: string | null = null + // Set once the BROWSER link turned out unforwardable; the paste page is then the prompt. + let pasteOnly = !channel.callback let sendToClaude: ((text: string) => void) | null = null let codeSent = false let browser: Awaited> | null = null + const publish = (prompt: HostAccountSignInPrompt): void => { + if (prompted) { + return + } + prompted = true + channel.onPrompt(prompt) + void channel.nextCode().then( + (code) => { + codeSent = true + sendToClaude?.(`${code}\n`) + }, + () => {} + ) + } try { // Suppress browser opening on the unattended execution host. browser = await prepareClaudeSignInBrowser(folder) + if (channel.callback) { + void publishCallbackLink( + browser, + linkWatch.signal, + () => pasteUrl, + publish, + () => { + pasteOnly = true + } + ) + } await runCommand(['auth', 'login', '--claudeai'], folder, LOGIN_TIMEOUT_MS, { signal: controller.signal, keepStdinOpen: true, @@ -76,7 +113,7 @@ export async function runClaudePastedCodeLogin( sendToClaude = send }, onStdout: (text) => { - if (prompted) { + if (prompted || pasteUrl) { return } scanned = `${scanned}${text}`.slice(-MAX_SCAN_CHARS) @@ -84,15 +121,10 @@ export async function runClaudePastedCodeLogin( if (!url) { return } - prompted = true - channel.onPrompt({ url, userCode: null, needsCode: true }) - void channel.nextCode().then( - (code) => { - codeSent = true - sendToClaude?.(`${code}\n`) - }, - () => {} - ) + pasteUrl = url + if (pasteOnly) { + publish({ url, userCode: null, needsCode: true }) + } } }) } catch (error) { @@ -102,6 +134,7 @@ export async function runClaudePastedCodeLogin( ? new Error(CLAUDE_PASTED_CODE_REJECTED_MESSAGE, { cause: error }) : error } finally { + linkWatch.abort() channel.signal.removeEventListener('abort', abort) setCancel(null) await browser?.dispose().catch((error: unknown) => { @@ -109,3 +142,42 @@ export async function runClaudePastedCodeLogin( }) } } + +/** Publishes the callback link Claude handed BROWSER, with its paste-code page as a fallback. */ +async function publishCallbackLink( + browser: Awaited>, + signal: AbortSignal, + pasteUrl: () => string | null, + publish: (prompt: HostAccountSignInPrompt) => void, + fallBackToPaste: () => void +): Promise { + const link = await browser.nextLink(signal) + const callbackPort = link ? signInCallbackPort(link) : null + if (!link || callbackPort === null) { + if (signal.aborted) { + return + } + // No forwardable callback: the paste-code page signs in, now or whenever Claude prints it. + fallBackToPaste() + const url = pasteUrl() + if (url) { + publish({ url, userCode: null, needsCode: true }) + } + return + } + const deadline = Date.now() + PASTE_LINK_GRACE_MS + while (!pasteUrl() && !signal.aborted && Date.now() < deadline) { + await delay(100, undefined, { signal }).catch(() => {}) + } + if (signal.aborted) { + return + } + const url = pasteUrl() + publish({ + url: link, + userCode: null, + needsCode: true, + callbackPort, + ...(url ? { pasteUrl: url } : {}) + }) +} diff --git a/src/main/claude-accounts/claude-sign-in-browser.ts b/src/main/claude-accounts/claude-sign-in-browser.ts index ff4da747af6..403ce18a885 100644 --- a/src/main/claude-accounts/claude-sign-in-browser.ts +++ b/src/main/claude-accounts/claude-sign-in-browser.ts @@ -6,6 +6,7 @@ import { canCopyClaudeSignInLink } from '../../shared/claude-sign-in-link' import type { ClaudeCommandConfig } from './claude-command-process' +import { LOCAL_CALLBACK_HOSTS } from '../../shared/host-account-sign-in-types' const HELPER_NAME = '.orca-sign-in-browser' const LINK_SUFFIX = '.link' @@ -14,7 +15,6 @@ const LINK_WAIT_MS = 60_000 // Claude discards BROWSER stdout; its printed link uses a different pasted-code flow. const HELPER_SCRIPT = `#!/bin/sh\nprintf '%s' "$1" > "$0.tmp" && mv "$0.tmp" "$0${LINK_SUFFIX}"\n` const CLAUDE_AUTHORIZE_HOSTS = new Set(['claude.com', 'claude.ai']) -const LOCAL_CALLBACK_HOSTS = new Set(['localhost', '127.0.0.1']) export type ClaudeSignInBrowser = { /** BROWSER as the Claude process sees it. */ diff --git a/src/main/claude/claude-auth-status-report.ts b/src/main/claude/claude-auth-status-report.ts new file mode 100644 index 00000000000..bcabb3a875a --- /dev/null +++ b/src/main/claude/claude-auth-status-report.ts @@ -0,0 +1,46 @@ +/** Fields of `claude auth status --json` Orca reads; tokens are never part of it. */ +export type ClaudeAuthStatusReport = { + loggedIn?: boolean + authMethod?: string + apiKeySource?: string + projectsDirectory?: string +} + +const STRING_FIELDS = ['authMethod', 'apiKeySource', 'projectsDirectory'] as const + +/** Parses `claude auth status --json`; null when the output is not one JSON object. */ +export function parseClaudeAuthStatusReport(stdout: string): ClaudeAuthStatusReport | null { + const start = stdout.search(/[[{]/) + if (start === -1) { + return null + } + // CLI warnings may precede the report, but another JSON value makes it ambiguous. + for (const line of stdout.slice(0, start).split('\n')) { + try { + JSON.parse(line) + return null + } catch { + continue + } + } + let parsed: unknown + try { + parsed = JSON.parse(stdout.slice(start)) + } catch { + return null + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return null + } + const report: ClaudeAuthStatusReport = {} + if ('loggedIn' in parsed && typeof parsed.loggedIn === 'boolean') { + report.loggedIn = parsed.loggedIn + } + for (const field of STRING_FIELDS) { + const value = Object.getOwnPropertyDescriptor(parsed, field)?.value + if (typeof value === 'string') { + report[field] = value + } + } + return report +} diff --git a/src/main/codex-accounts/codex-login-session.ts b/src/main/codex-accounts/codex-login-session.ts index 630305fe782..12ac3c81555 100644 --- a/src/main/codex-accounts/codex-login-session.ts +++ b/src/main/codex-accounts/codex-login-session.ts @@ -63,6 +63,7 @@ type CodexLoginSessionDependencies = { openWslAuthUrl?: ((url: string) => void) | null /** Runs `codex login --device-auth` on a Linux/macOS host for a person on another device. */ deviceAuth?: { onPrompt: (prompt: { url: string; userCode: string }) => void } + remoteBrowser?: true } type LoginCancellation = { @@ -100,7 +101,8 @@ async function runCodexLoginProcess( ): Promise { const wslInfo = parseWslUncPath(managedHomePath) const deviceAuth = dependencies.deviceAuth ?? null - const loginTimeoutMs = deviceAuth ? DEVICE_AUTH_TIMEOUT_MS : LOGIN_TIMEOUT_MS + const loginTimeoutMs = + deviceAuth || dependencies.remoteBrowser ? DEVICE_AUTH_TIMEOUT_MS : LOGIN_TIMEOUT_MS if (wslInfo) { await assertWslCodexCliAvailable(wslInfo) } diff --git a/src/main/codex-accounts/codex-remote-browser-login.ts b/src/main/codex-accounts/codex-remote-browser-login.ts new file mode 100644 index 00000000000..e9f8e1564d3 --- /dev/null +++ b/src/main/codex-accounts/codex-remote-browser-login.ts @@ -0,0 +1,21 @@ +import { + signInCallbackPort, + type HostAccountSignInChannel +} from '../../shared/host-account-sign-in-types' + +/** Publishes codex's browser link with its localhost callback port for a remote person to forward. */ +export function publishCodexCallbackPrompt(channel: HostAccountSignInChannel, url: string): void { + const callbackPort = signInCallbackPort(url) + channel.onPrompt({ + url, + userCode: null, + needsCode: false, + ...(callbackPort === null ? {} : { callbackPort }) + }) +} + +/** The page opens on the remote person's device. Linux honors BROWSER, so `true` keeps codex from + * opening one here; macOS hosts have no such switch and may also open the page locally. */ +export function withoutHostBrowser(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return process.platform === 'linux' ? { ...env, BROWSER: 'true' } : env +} diff --git a/src/main/codex-accounts/service.ts b/src/main/codex-accounts/service.ts index feab44c10a3..953e8a5678f 100644 --- a/src/main/codex-accounts/service.ts +++ b/src/main/codex-accounts/service.ts @@ -31,6 +31,7 @@ import type { import { toCodexManagedAccountSummary } from './codex-account-service-types' import { CODEX_LOGIN_CANCELLED_MESSAGE } from '../../shared/codex-auth-errors' import type { HostAccountSignInChannel } from '../../shared/host-account-sign-in-types' +import { publishCodexCallbackPrompt, withoutHostBrowser } from './codex-remote-browser-login' export type { CodexAccountAddTarget, CodexAccountReauthenticateOptions, @@ -302,7 +303,7 @@ export class CodexAccountService { stdio, // Hide the outer wrapper; the dedicated login console remains visible. windowsHide: true, - env + env: deviceChannel?.callback ? withoutHostBrowser(env) : env }) }, killProcessTree: killLoginProcessTree, @@ -310,9 +311,14 @@ export class CodexAccountService { this.cancelPendingCodexLogin = cancel cancelThisLogin = cancel }, - onAuthUrl: (url) => this.setPendingLoginUrl(url), + // A remote person's sign-in link is theirs; this host's Orca windows don't offer it. + onAuthUrl: (url) => + deviceChannel?.callback + ? publishCodexCallbackPrompt(deviceChannel, url) + : this.setPendingLoginUrl(url), openWslAuthUrl: this.openWslLoginUrl, - ...(deviceChannel + ...(deviceChannel?.callback ? { remoteBrowser: true as const } : {}), + ...(deviceChannel && !deviceChannel.callback ? { deviceAuth: { onPrompt: ({ url, userCode }) => diff --git a/src/main/ipc/runtime-environments/auth-callback-forward.ts b/src/main/ipc/runtime-environments/auth-callback-forward.ts new file mode 100644 index 00000000000..9c33d6ecd9f --- /dev/null +++ b/src/main/ipc/runtime-environments/auth-callback-forward.ts @@ -0,0 +1,299 @@ +import { createServer, type Server, type Socket } from 'node:net' +import { ipcMain } from 'electron' +import '../../../shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RemoteRuntimeTransportSubscription } from '../../../shared/remote-runtime/requests/remote-runtime-subscription-contract' +import { resolveEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-store' +import { getPreferredPairedRuntimeConnection } from '../../../shared/remote-runtime/host-catalog/runtime-environments' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../shared/electron-remote-runtime-client-capabilities' +import { HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY } from '../../../shared/account-runtime-capabilities' +import { BrowserNetworkTunnelEvent } from '../../../shared/browser/client-hosting/browser-client-host-protocol' +import { + AUTH_CALLBACK_FORWARD_MAX_BYTES as MAX_BYTES, + AUTH_CALLBACK_FORWARD_MAX_STREAMS as MAX_CONNECTIONS, + AUTH_CALLBACK_FORWARD_TTL_MS as TTL_MS, + type AuthCallbackForwardRequest, + type AuthCallbackForwardResult +} from '../../../shared/auth-callback-forward' +import { BrowserNetworkTunnelClient } from '../../browser/network/tunnels/browser-network-tunnel-client' +import { BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL } from '../../browser/network/tunnels/browser-network-tunnel-stream-state' +import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel' + +const ATTACH_TIMEOUT_MS = 20_000 + +type Tunnel = { client: BrowserNetworkTunnelClient; close: () => void } + +/** Opens the host end: a tunnel that reaches only this flow's callback port there. */ +async function openHostTunnel( + userDataPath: string, + request: AuthCallbackForwardRequest, + onClosed: () => void +): Promise { + await ensureOrcadManagedTunnel(userDataPath, request.environmentId) + const connection = getPreferredPairedRuntimeConnection( + resolveEnvironment(userDataPath, request.environmentId) + ) + const ready = Promise.withResolvers() + let client: BrowserNetworkTunnelClient | null = null + let subscription: RemoteRuntimeTransportSubscription | null = null + const fail = (error: Error): void => { + ready.reject(error) + onClosed() + } + subscription = await subscribeRemoteRuntimeTransport( + connection, + 'network.authCallbackTunnel', + { flowId: request.flowId }, + ATTACH_TIMEOUT_MS, + { + onResponse: (response) => { + if (!response.ok) { + fail(new Error(response.error.message)) + return + } + const event = BrowserNetworkTunnelEvent.safeParse(response.result) + if (!event.success || event.data.type === 'closed') { + fail(new Error('The sign-in tunnel closed.')) + return + } + if (!client) { + client = new BrowserNetworkTunnelClient({ + tunnelGeneration: event.data.tunnelGeneration, + sendBinary: (bytes) => subscription?.sendBinary(bytes) ?? false, + flowControl: BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL, + onClosed: () => onClosed() + }) + ready.resolve(client) + } + }, + onBinary: (bytes) => client?.handleBinary(bytes), + onError: (error) => fail(error), + onClose: () => fail(new Error('The sign-in tunnel closed.')) + }, + { + perMessageDeflate: false, + outboundQueue: { + softCapBytes: MAX_BYTES, + maxQueuedBytes: 2 * MAX_BYTES, + maxQueuedFrames: 256, + maxDrainFramesPerTurn: 4 + }, + clientCapabilities: [ + ...ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, + HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY + ] + } + ) + const timeout = setTimeout( + () => ready.reject(new Error('The sign-in tunnel did not open.')), + ATTACH_TIMEOUT_MS + ) + try { + const opened = await ready.promise + return { + client: opened, + close: () => { + opened.close(new Error('Sign-in finished.')) + subscription?.close() + } + } + } catch (error) { + subscription.close() + throw error + } finally { + clearTimeout(timeout) + } +} + +function listen(server: Server, port: number, host: string): Promise { + return new Promise((resolve, reject) => { + server.once('error', reject) + server.listen({ port, host, exclusive: true }, () => { + server.off('error', reject) + resolve() + }) + }) +} + +/** Listens on this computer's loopback callback port for one sign-in and carries each connection to the host. */ +export class AuthCallbackForward { + private readonly servers: Server[] = [] + private readonly sockets = new Set() + private tunnel: Tunnel | null = null + private connections = 0 + private bytes = 0 + private closed = false + private readonly ttl: ReturnType + + constructor( + readonly request: AuthCallbackForwardRequest, + private readonly onClosed: () => void + ) { + this.ttl = setTimeout(() => this.close(), TTL_MS) + } + + async start(userDataPath: string): Promise { + const v4 = createServer((socket) => this.accept(socket)) + try { + await listen(v4, this.request.port, '127.0.0.1') + } catch (error) { + this.close() + const busy = error instanceof Error && 'code' in error && error.code === 'EADDRINUSE' + return { + ok: false, + code: busy ? 'port_busy' : 'listen_failed', + message: busy + ? `Port ${this.request.port} is busy on this computer.` + : 'Orca could not listen for the sign-in on this computer.' + } + } + this.servers.push(v4) + // Browsers may resolve localhost to ::1 first; a missing IPv6 loopback is fine. + const v6 = createServer((socket) => this.accept(socket)) + await listen(v6, this.request.port, '::1').then( + () => this.servers.push(v6), + () => v6.close() + ) + try { + this.tunnel = await openHostTunnel(userDataPath, this.request, () => this.close()) + } catch (error) { + this.close() + return { + ok: false, + code: 'tunnel_failed', + message: error instanceof Error ? error.message : String(error) + } + } + if (this.closed) { + this.tunnel.close() + return { ok: false, code: 'tunnel_failed', message: 'The sign-in ended.' } + } + console.info(`[auth-callback-forward] listening on port ${this.request.port}`) + return { ok: true } + } + + private accept(socket: Socket): void { + this.connections += 1 + if (this.closed || !this.tunnel || this.connections > MAX_CONNECTIONS) { + socket.destroy() + return + } + this.sockets.add(socket) + socket.on('close', () => this.sockets.delete(socket)) + const count = (chunk: Buffer): void => { + this.bytes += chunk.byteLength + if (this.bytes > MAX_BYTES) { + this.close() + } + } + socket.pause() + this.tunnel.client.open({ host: '127.0.0.1', port: this.request.port }).then( + (remote) => { + if (socket.destroyed) { + remote.destroy() + return + } + socket.on('data', count) + remote.on('data', count) + socket.pipe(remote) + remote.pipe(socket) + socket.on('error', () => remote.destroy()) + remote.on('error', () => socket.destroy()) + socket.on('close', () => remote.destroy()) + remote.on('close', () => socket.destroy()) + socket.resume() + }, + () => socket.destroy() + ) + } + + close(): void { + if (this.closed) { + return + } + this.closed = true + clearTimeout(this.ttl) + for (const server of this.servers) { + server.close() + } + for (const socket of this.sockets) { + socket.destroy() + } + this.tunnel?.close() + this.onClosed() + console.info(`[auth-callback-forward] closed port ${this.request.port}`) + } +} + +const forwards = new Map() +const keyOf = (request: Pick): string => + `${request.environmentId}\u0000${request.flowId}` + +function field(value: unknown, name: string): unknown { + return value && typeof value === 'object' + ? Object.getOwnPropertyDescriptor(value, name)?.value + : undefined +} + +function flowOf( + value: unknown +): Pick | null { + const environmentId = field(value, 'environmentId') + const flowId = field(value, 'flowId') + return typeof environmentId === 'string' && typeof flowId === 'string' + ? { environmentId, flowId } + : null +} + +function requestOf(value: unknown): AuthCallbackForwardRequest | null { + const flow = flowOf(value) + const port = field(value, 'port') + return flow && + typeof port === 'number' && + Number.isInteger(port) && + port >= 1024 && + port <= 65_535 + ? { ...flow, port } + : null +} + +export function closeAuthCallbackForward( + request: Pick +): void { + forwards.get(keyOf(request))?.close() +} + +export async function openAuthCallbackForward( + userDataPath: string, + request: AuthCallbackForwardRequest +): Promise { + // A retried sign-in replaces this computer's earlier listener on the same port. + for (const existing of forwards.values()) { + if (existing.request.port === request.port) { + existing.close() + } + } + const key = keyOf(request) + const forward = new AuthCallbackForward(request, () => { + if (forwards.get(key) === forward) { + forwards.delete(key) + } + }) + forwards.set(key, forward) + return forward.start(userDataPath) +} + +export function registerAuthCallbackForwardHandlers(getUserDataPath: () => string): void { + ipcMain.handle('runtimeEnvironments:openAuthCallbackForward', (_event, value: unknown) => { + const request = requestOf(value) + return request + ? openAuthCallbackForward(getUserDataPath(), request) + : { ok: false, code: 'listen_failed', message: 'Invalid sign-in forward.' } + }) + ipcMain.handle('runtimeEnvironments:closeAuthCallbackForward', (_event, value: unknown) => { + const flow = flowOf(value) + if (flow) { + closeAuthCallbackForward(flow) + } + }) +} diff --git a/src/main/ipc/runtime-environments/runtime-environment-handler-channels.ts b/src/main/ipc/runtime-environments/runtime-environment-handler-channels.ts index bb23c2da45c..c01c66f3310 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-handler-channels.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-handler-channels.ts @@ -31,5 +31,7 @@ export const RUNTIME_ENVIRONMENT_HANDLER_CHANNELS = [ 'runtimeEnvironments:previewOrcadDeltaMove', 'runtimeEnvironments:moveOrcadDelta', 'runtimeEnvironments:keepOrcadServerVersion', - 'runtimeEnvironments:allowOrcadMoveLeavingBehind' + 'runtimeEnvironments:allowOrcadMoveLeavingBehind', + 'runtimeEnvironments:openAuthCallbackForward', + 'runtimeEnvironments:closeAuthCallbackForward' ] as const diff --git a/src/main/ipc/runtime-environments/runtime-environments.ts b/src/main/ipc/runtime-environments/runtime-environments.ts index fb21fb8e798..94f98b22bb0 100644 --- a/src/main/ipc/runtime-environments/runtime-environments.ts +++ b/src/main/ipc/runtime-environments/runtime-environments.ts @@ -32,6 +32,7 @@ import { registerRuntimeEnvironmentRepairHandler } from './runtime-environment-r import { advanceRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' import { resetSharedControlSupport } from './runtime-environment-shared-control-support' import { RUNTIME_ENVIRONMENT_HANDLER_CHANNELS } from './runtime-environment-handler-channels' +import { registerAuthCallbackForwardHandlers } from './auth-callback-forward' import { registerOrcadRuntimeLifecycleHandlers } from './orcad-runtime-lifecycle-handlers' import { registerOrcadRuntimeConversionHandlers } from './orcad-runtime-conversion-handlers' import { registerOrcadDeltaMoveHandlers } from './orcad-delta-move-handlers' @@ -150,6 +151,7 @@ export function registerRuntimeEnvironmentHandlers(store: Store): void { getSettings: () => store.getSettings() }) registerRuntimeEnvironmentRecoveryHandler() + registerAuthCallbackForwardHandlers(getUserDataPath) registerRuntimeEnvironmentRepairHandler({ getUserDataPath, invalidateTransport: invalidateRuntimeEnvironmentTransport diff --git a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts b/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts index d88e0aa256b..ec7d522fb80 100644 --- a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts +++ b/src/main/runtime/agent-session/environment/host-account-sign-in-flows.test.ts @@ -32,6 +32,28 @@ afterEach(() => { }) describe('HostAccountSignInFlows', () => { + it('grants the callback port only to the owner of a browser sign-in while it waits', async () => { + const runner = controllableRunner() + const flows = new HostAccountSignInFlows(runner.run, 'linux') + const { flowId } = flows.start('device-a', 'claude', { callback: true }) + expect(runner.channel().callback).toBe(true) + expect(flows.callbackTarget('device-a', flowId)).toBeNull() + runner.channel().onPrompt({ + url: 'https://claude.ai/oauth/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A54121%2Fcallback', + userCode: null, + needsCode: true, + callbackPort: 54121 + }) + expect(flows.callbackTarget('device-a', flowId)?.port).toBe(54121) + expect(flows.callbackTarget('device-b', flowId)).toBeNull() + expect(flows.callbackTarget('device-a', 'other-flow')).toBeNull() + const grant = flows.callbackTarget('device-a', flowId) + runner.finish.resolve() + await flows.wait('device-a', flowId, 2) + expect(grant?.ended.aborted).toBe(true) + expect(flows.callbackTarget('device-a', flowId)).toBeNull() + }) + it('keeps one client from reading, answering or cancelling another client’s sign-in', async () => { const runner = controllableRunner() const flows = new HostAccountSignInFlows(runner.run, 'linux') diff --git a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.ts b/src/main/runtime/agent-session/environment/host-account-sign-in-flows.ts index 9423379b035..36ab785f158 100644 --- a/src/main/runtime/agent-session/environment/host-account-sign-in-flows.ts +++ b/src/main/runtime/agent-session/environment/host-account-sign-in-flows.ts @@ -32,6 +32,7 @@ export type HostAccountSignInRunner = ( type Flow = { owner: string + callback: boolean status: HostAccountSignInStatus ended: AbortController stop: 'cancelled' | 'silent' | null @@ -55,7 +56,11 @@ export class HostAccountSignInFlows { private readonly platform: NodeJS.Platform = process.platform ) {} - start(owner: string, provider: HostAccountSignInProvider): HostAccountSignInStatus { + start( + owner: string, + provider: HostAccountSignInProvider, + options: { callback?: boolean } = {} + ): HostAccountSignInStatus { if (this.platform === 'win32') { throw new Error( 'Adding accounts from another device is not available on Windows hosts yet. Run `orca account add` in a terminal on that host.' @@ -63,7 +68,12 @@ export class HostAccountSignInFlows { } const current = this.active if (current) { - if (current.owner === owner && current.status.provider === provider && !current.stop) { + if ( + current.owner === owner && + current.status.provider === provider && + current.callback === (options.callback === true) && + !current.stop + ) { this.touch(current) return current.status } @@ -78,6 +88,7 @@ export class HostAccountSignInFlows { code.promise.catch(() => {}) const flow: Flow = { owner, + callback: options.callback === true, status: { flowId: randomUUID(), provider, revision: 1, phase: 'starting' }, ended: new AbortController(), stop: null, @@ -106,7 +117,8 @@ export class HostAccountSignInFlows { this.update(flow, { phase: 'waiting', prompt }) } }, - nextCode: () => flow.code.promise + nextCode: () => flow.code.promise, + ...(flow.callback ? { callback: true } : {}) } try { const result = await this.run(flow.status.provider, channel) @@ -152,6 +164,24 @@ export class HostAccountSignInFlows { return flow.status } + /** The callback port `owner` may reach on this host: only its own flow, only while it waits in the browser. */ + callbackTarget(owner: string, flowId: string): { port: number; ended: AbortSignal } | null { + const flow = this.latest.get(owner) + const port = flow?.status.prompt?.callbackPort + if ( + !flow || + flow !== this.active || + flow.status.flowId !== flowId || + flow.status.phase !== 'waiting' || + flow.stop || + port === undefined + ) { + return null + } + this.touch(flow) + return { port, ended: flow.ended.signal } + } + submitCode(owner: string, flowId: string, code: string): HostAccountSignInStatus { const flow = this.own(owner, flowId) this.touch(flow) diff --git a/src/main/runtime/agent-session/environment/host-agent-sign-in-status.test.ts b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.test.ts new file mode 100644 index 00000000000..0c1827917f0 --- /dev/null +++ b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it, vi } from 'vitest' +import { + classifyAgentStatusOutput, + HostAgentSignInStatusChecker, + type HostAgentSignInStatusDeps +} from './host-agent-sign-in-status' + +const CLAUDE_SIGNED_OUT = '{\n "loggedIn": false,\n "authMethod": "none"\n}\n' +const CLAUDE_API_KEY = + '{\n "loggedIn": true,\n "authMethod": "api_key",\n "apiKeySource": "ANTHROPIC_API_KEY"\n}\n' +const CLAUDE_SUBSCRIPTION = '{ "loggedIn": true, "authMethod": "claude.ai" }' + +function emptyAccounts(): NonNullable> { + return { + claude: { accounts: [], activeAccountId: null }, + codex: { accounts: [], activeAccountId: null } + } +} + +describe('classifyAgentStatusOutput', () => { + it('reads claude auth status, which exits 1 with its JSON when signed out', () => { + expect( + classifyAgentStatusOutput('claude', { + exitCode: 1, + output: CLAUDE_SIGNED_OUT, + timedOut: false + }) + ).toEqual({ agent: 'claude', state: 'signedOut' }) + expect( + classifyAgentStatusOutput('claude', { exitCode: 0, output: CLAUDE_API_KEY, timedOut: false }) + ).toEqual({ agent: 'claude', state: 'signedIn', method: 'apiKey' }) + expect( + classifyAgentStatusOutput('claude', { + exitCode: 0, + output: CLAUDE_SUBSCRIPTION, + timedOut: false + }) + ).toEqual({ agent: 'claude', state: 'signedIn', method: 'cliLogin' }) + }) + + it('reports an old claude without --json as unknown rather than signed out', () => { + expect( + classifyAgentStatusOutput('claude', { + exitCode: 1, + output: "error: unknown option '--json'", + timedOut: false + }) + ).toEqual({ agent: 'claude', state: 'unknown' }) + }) + + it('reads codex login status by exit code', () => { + expect( + classifyAgentStatusOutput('codex', { + exitCode: 0, + output: '\nLogged in using ChatGPT', + timedOut: false + }) + ).toEqual({ agent: 'codex', state: 'signedIn', method: 'cliLogin' }) + expect( + classifyAgentStatusOutput('codex', { + exitCode: 0, + output: 'Logged in using an API key - sk-***', + timedOut: false + }) + ).toEqual({ agent: 'codex', state: 'signedIn', method: 'apiKey' }) + expect( + classifyAgentStatusOutput('codex', { exitCode: 1, output: 'Not logged in', timedOut: false }) + ).toEqual({ agent: 'codex', state: 'signedOut' }) + expect( + classifyAgentStatusOutput('codex', { exitCode: null, output: '', timedOut: true }) + ).toEqual({ agent: 'codex', state: 'unknown' }) + }) +}) + +describe('HostAgentSignInStatusChecker', () => { + it('reports a selected Orca account as signed in and a missing CLI as not installed', async () => { + const accounts = emptyAccounts() + accounts.codex = { + accounts: [ + { + id: 'codex-1', + email: 'a@example.com', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + ], + activeAccountId: 'codex-1' + } + const runStatus = vi.fn() + const checker = new HostAgentSignInStatusChecker({ + findCommand: async (command) => + command === 'codex' ? { status: 'available', binary: '/bin/codex' } : { status: 'absent' }, + runStatus, + readAccounts: () => accounts, + now: () => 1_000 + }) + await expect(checker.read()).resolves.toEqual({ + checkedAt: 1_000, + agents: [ + { agent: 'claude', state: 'notInstalled' }, + { agent: 'codex', state: 'signedIn', method: 'orcaAccount' } + ] + }) + expect(runStatus).not.toHaveBeenCalled() + }) + + it('reports a selected Claude account without a login as signed out, even when the CLI is signed in', async () => { + const accounts = emptyAccounts() + accounts.claude = { + accounts: [ + { + id: 'claude-1', + email: 'a@example.com', + authMethod: 'subscription-oauth', + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1, + needsSignIn: true + } + ], + activeAccountId: 'claude-1' + } + const checker = new HostAgentSignInStatusChecker({ + findCommand: async (command) => ({ status: 'available', binary: `/bin/${command}` }), + runStatus: async (binary) => + binary === '/bin/claude' + ? { exitCode: 0, output: CLAUDE_SUBSCRIPTION, timedOut: false } + : { exitCode: 1, output: 'Not logged in', timedOut: false }, + readAccounts: () => accounts, + now: () => 5 + }) + const report = await checker.read() + expect(report.agents).toEqual([ + { agent: 'claude', state: 'signedOut' }, + { agent: 'codex', state: 'signedOut' } + ]) + }) + + it('answers a forced recheck with a fresh check, not one begun before the sign-in', async () => { + let calls = 0 + const firstCheck = Promise.withResolvers() + const checker = new HostAgentSignInStatusChecker({ + findCommand: async (command) => + command === 'codex' ? { status: 'available', binary: '/bin/codex' } : { status: 'absent' }, + runStatus: async () => { + // The first check started before the sign-in finished. + const signedIn = calls++ > 0 + if (!signedIn) { + await firstCheck.promise + } + return signedIn + ? { exitCode: 0, output: 'Logged in using ChatGPT', timedOut: false } + : { exitCode: 1, output: 'Not logged in', timedOut: false } + }, + readAccounts: () => emptyAccounts(), + now: () => 1 + }) + const before = checker.read() + const after = checker.read(true) + firstCheck.resolve() + expect((await before).agents[1]).toEqual({ agent: 'codex', state: 'signedOut' }) + expect((await after).agents[1]).toEqual({ + agent: 'codex', + state: 'signedIn', + method: 'cliLogin' + }) + }) +}) diff --git a/src/main/runtime/agent-session/environment/host-agent-sign-in-status.ts b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.ts new file mode 100644 index 00000000000..4e5d8efa524 --- /dev/null +++ b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.ts @@ -0,0 +1,239 @@ +import type { + ClaudeRateLimitAccountsState, + CodexRateLimitAccountsState +} from '../../../../shared/managed-account-types' +import type { + HostAgentSignInAgent, + HostAgentSignInEntry, + HostAgentSignInReport +} from '../../../../shared/host-agent-sign-in-status' +import { parseClaudeAuthStatusReport } from '../../../claude/claude-auth-status-report' +import { + execLocalPreflightCommandOrThrow, + findRunnableLocalCommand, + type LocalCommandProbe +} from '../../../ipc/preflight-command-exec' + +// Why: clients ask on open and after a sign-in; one minute keeps reopened views from respawning CLIs. +const REPORT_TTL_MS = 60_000 +const STATUS_TIMEOUT_MS = 10_000 + +export type AgentStatusCommandResult = { + exitCode: number | null + output: string + timedOut: boolean +} + +export type HostAgentSignInStatusDeps = { + findCommand: (command: string) => Promise + runStatus: (binary: string, args: string[]) => Promise + /** This host's Orca account roster; null where it has none. */ + readAccounts: () => { + claude: ClaudeRateLimitAccountsState + codex: CodexRateLimitAccountsState + } | null + now: () => number +} + +type Accounts = NonNullable> + +const STATUS_ARGS: Record = { + claude: ['auth', 'status', '--json'], + codex: ['login', 'status'] +} + +export function hostSelection(state: { + activeAccountId: string | null + activeAccountIdsByRuntime?: { host: string | null } +}): string | null { + return state.activeAccountIdsByRuntime?.host ?? state.activeAccountId +} + +/** The verdict a selected Orca account fixes for launches here; null leaves it to the CLI's own login. */ +function orcaAccountVerdict( + agent: HostAgentSignInAgent, + accounts: Accounts | null +): 'signedIn' | 'signedOut' | null { + if (!accounts) { + return null + } + if (agent === 'claude') { + const id = hostSelection(accounts.claude) + const account = accounts.claude.accounts.find((entry) => entry.id === id) + if (!account || account.runsOnSystemDefault) { + return null + } + // Launches use the account's own folder, which holds no login yet. + return account.needsSignIn ? 'signedOut' : 'signedIn' + } + const id = hostSelection(accounts.codex) + return accounts.codex.accounts.some((entry) => entry.id === id) ? 'signedIn' : null +} + +export function classifyAgentStatusOutput( + agent: HostAgentSignInAgent, + result: AgentStatusCommandResult +): HostAgentSignInEntry { + if (result.timedOut) { + return { agent, state: 'unknown' } + } + if (agent === 'claude') { + // Signed out exits 1 with the same JSON report. + const report = parseClaudeAuthStatusReport(result.output) + if (report?.loggedIn === true) { + const apiKey = report.authMethod === 'api_key' || report.apiKeySource !== undefined + return { agent, state: 'signedIn', method: apiKey ? 'apiKey' : 'cliLogin' } + } + return { agent, state: report?.loggedIn === false ? 'signedOut' : 'unknown' } + } + // Codex prints its verdict to stderr on some versions; the exit code is the contract. + if (result.exitCode === 0) { + return { + agent, + state: 'signedIn', + method: /api key/i.test(result.output) ? 'apiKey' : 'cliLogin' + } + } + return { agent, state: /not logged in/i.test(result.output) ? 'signedOut' : 'unknown' } +} + +/** Checks, on this host, whether each agent CLI would start signed in. Results are cached and + * concurrent asks share one check, so opening many views never fans out CLI spawns. */ +export class HostAgentSignInStatusChecker { + private report: HostAgentSignInReport | null = null + private inFlight: Promise | null = null + private queuedForce: Promise | null = null + + constructor(private readonly deps: HostAgentSignInStatusDeps) {} + + read(force = false): Promise { + if (this.inFlight) { + if (!force) { + return this.inFlight + } + // Why: a check begun before a sign-in finished can't answer a forced recheck after it. + this.queuedForce ??= this.inFlight + .catch(() => undefined) + .then(() => { + this.queuedForce = null + return this.start() + }) + return this.queuedForce + } + const cached = this.report + if (!force && cached && this.deps.now() - cached.checkedAt < REPORT_TTL_MS) { + return Promise.resolve(cached) + } + return this.start() + } + + private start(): Promise { + const run = this.check().finally(() => { + if (this.inFlight === run) { + this.inFlight = null + } + }) + this.inFlight = run + return run + } + + private async check(): Promise { + let accounts: Accounts | null = null + try { + accounts = this.deps.readAccounts() + } catch { + // An unreadable roster leaves the CLI's own login to decide. + } + const agents = await Promise.all( + (['claude', 'codex'] as const).map((agent) => this.checkAgent(agent, accounts)) + ) + const report = { checkedAt: this.deps.now(), agents } + this.report = report + return report + } + + private async checkAgent( + agent: HostAgentSignInAgent, + accounts: Accounts | null + ): Promise { + const probe = await this.deps.findCommand(agent) + if (probe.status === 'absent') { + return { agent, state: 'notInstalled' } + } + if (probe.status !== 'available') { + return { agent, state: 'unknown' } + } + const verdict = orcaAccountVerdict(agent, accounts) + if (verdict) { + return verdict === 'signedIn' + ? { agent, state: 'signedIn', method: 'orcaAccount' } + : { agent, state: 'signedOut' } + } + try { + return classifyAgentStatusOutput( + agent, + await this.deps.runStatus(probe.binary, STATUS_ARGS[agent]) + ) + } catch { + return { agent, state: 'unknown' } + } + } +} + +function errorField(error: unknown, field: string): unknown { + return typeof error === 'object' && error !== null + ? Object.getOwnPropertyDescriptor(error, field)?.value + : undefined +} + +/** Runs a status verb; its output is classified here and never leaves the host. */ +export async function runAgentStatusCommand( + binary: string, + args: string[] +): Promise { + try { + const { stdout, stderr } = await execLocalPreflightCommandOrThrow(binary, args, { + timeoutMs: STATUS_TIMEOUT_MS + }) + return { exitCode: 0, output: `${stdout}\n${stderr}`, timedOut: false } + } catch (error) { + const code = errorField(error, 'code') + const stdout = errorField(error, 'stdout') + const stderr = errorField(error, 'stderr') + return { + // Why: a throw carrying code 0 is truncated output, never a clean exit. + exitCode: typeof code === 'number' && code !== 0 ? code : null, + output: `${typeof stdout === 'string' ? stdout : ''}\n${typeof stderr === 'string' ? stderr : ''}`, + timedOut: code === 'ETIMEDOUT' || errorField(error, 'killed') === true + } + } +} + +const LOGOUT_ARGS: Record = { + claude: ['auth', 'logout'], + codex: ['logout'] +} + +/** Signs the CLI's own login on this host out; the CLI deletes its credentials itself. */ +export async function runAgentLogoutCommand(agent: HostAgentSignInAgent): Promise { + const name = agent === 'claude' ? 'Claude' : 'Codex' + const probe = await findRunnableLocalCommand(agent) + if (probe.status !== 'available') { + throw new Error(`${name} is not installed on this host.`) + } + const result = await runAgentStatusCommand(probe.binary, LOGOUT_ARGS[agent]) + if (result.exitCode !== 0) { + throw new Error(`${name} could not sign out on this host.`) + } +} + +export function createHostAgentSignInStatusChecker( + readAccounts: HostAgentSignInStatusDeps['readAccounts'] +): HostAgentSignInStatusChecker { + return new HostAgentSignInStatusChecker({ + findCommand: findRunnableLocalCommand, + runStatus: runAgentStatusCommand, + readAccounts, + now: Date.now + }) +} diff --git a/src/main/runtime/rpc/methods/accounts/accounts.ts b/src/main/runtime/rpc/methods/accounts/accounts.ts index 33c9fdc4879..8ca981bc7c8 100644 --- a/src/main/runtime/rpc/methods/accounts/accounts.ts +++ b/src/main/runtime/rpc/methods/accounts/accounts.ts @@ -3,6 +3,7 @@ import type { OrcadFeature } from '../../orcad-feature-readiness' import { rpcCallerOperationKey } from '../../rpc-caller-identity' import { HostAccountSignInFlows } from '../../../agent-session/environment/host-account-sign-in-flows' import type { OrcaRuntimeService } from '../../../orca-runtime' +import { agentSignInMethods } from './agent-sign-in-methods' import { AddDataAccountParams, SelectDataAccountParams, @@ -222,9 +223,10 @@ const ACCOUNT_METHOD_DEFINITIONS = [ name: 'accounts.hostSignInStart', permission: 'accounts-admin', params: HostAccountSignInStartParams, - handler: async ({ provider }, ctx) => - hostSignInFlows(ctx.runtime).start(signInOwner(ctx), provider) + handler: async ({ provider, callback }, ctx) => + hostSignInFlows(ctx.runtime).start(signInOwner(ctx), provider, { callback }) }), + ...agentSignInMethods(hostSignInFlows, signInOwner), defineMethod({ name: 'accounts.hostSignInWait', permission: 'accounts-admin', diff --git a/src/main/runtime/rpc/methods/accounts/agent-sign-in-methods.ts b/src/main/runtime/rpc/methods/accounts/agent-sign-in-methods.ts new file mode 100644 index 00000000000..535e6207aed --- /dev/null +++ b/src/main/runtime/rpc/methods/accounts/agent-sign-in-methods.ts @@ -0,0 +1,73 @@ +import { defineMethod, type RpcContext } from '../../core' +import type { HostAccountSignInFlows } from '../../../agent-session/environment/host-account-sign-in-flows' +import { createAuthCallbackTunnelMethod } from './auth-callback-tunnel' +import { + createHostAgentSignInStatusChecker, + hostSelection, + runAgentLogoutCommand, + type HostAgentSignInStatusChecker +} from '../../../agent-session/environment/host-agent-sign-in-status' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { + HostAgentSignInStatusParams, + HostAgentSignOutParams +} from '../../../../../shared/rpc-contract/accounts-params' + +const checkers = new WeakMap() +function checkerFor(runtime: OrcaRuntimeService): HostAgentSignInStatusChecker { + let checker = checkers.get(runtime) + if (!checker) { + checker = createHostAgentSignInStatusChecker(() => runtime.getAccountsSnapshot()) + checkers.set(runtime, checker) + } + return checker +} + +function selectedHostAccountId( + runtime: OrcaRuntimeService, + agent: 'claude' | 'codex' +): string | null { + try { + const state = runtime.getAccountsSnapshot()[agent] + const id = hostSelection(state) + const account = state.accounts.find((entry) => entry.id === id) + // An account riding the system-default login has none of its own; the CLI's is what signs in. + return account && !('runsOnSystemDefault' in account && account.runsOnSystemDefault) + ? account.id + : null + } catch { + // No account services here: the CLI's own login is the only one. + return null + } +} + +// Verdicts only: CLI output and credentials stay on this host. +export const agentSignInMethods = ( + flowsFor: (runtime: OrcaRuntimeService) => HostAccountSignInFlows, + ownerOf: (ctx: Pick) => string +) => [ + defineMethod({ + name: 'accounts.agentSignInStatus', + permission: 'workspace', + params: HostAgentSignInStatusParams, + handler: async ({ force }, { runtime }) => checkerFor(runtime).read(force === true) + }), + // Signs out the login launches here use: the selected Orca account, else the CLI's own. + defineMethod({ + name: 'accounts.agentSignOut', + permission: 'accounts-admin', + params: HostAgentSignOutParams, + handler: async ({ agent }, { runtime }) => { + const accountId = selectedHostAccountId(runtime, agent) + if (accountId) { + await (agent === 'claude' + ? runtime.removeClaudeAccount(accountId) + : runtime.removeCodexAccount(accountId)) + } else { + await runAgentLogoutCommand(agent) + } + return checkerFor(runtime).read(true) + } + }), + createAuthCallbackTunnelMethod(flowsFor, ownerOf) +] diff --git a/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.test.ts b/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.test.ts new file mode 100644 index 00000000000..c23fd649374 --- /dev/null +++ b/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.test.ts @@ -0,0 +1,49 @@ +import { EventEmitter } from 'node:events' +import type { Socket } from 'node:net' +import { describe, expect, it, vi } from 'vitest' +import { + AUTH_CALLBACK_FORWARD_MAX_BYTES as AUTH_CALLBACK_TUNNEL_MAX_BYTES, + AUTH_CALLBACK_FORWARD_MAX_STREAMS as AUTH_CALLBACK_TUNNEL_MAX_STREAMS +} from '../../../../../shared/auth-callback-forward' +import { createAuthCallbackDialer } from './auth-callback-tunnel' + +function fakeSocket(): Socket { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test double; only the members the dialer calls are set. + const socket = new EventEmitter() as EventEmitter & Record + socket.destroyed = false + socket.destroy = vi.fn(() => { + socket.destroyed = true + }) + socket.write = vi.fn(() => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test double; only the members the dialer calls are set. + return socket as unknown as Socket +} + +describe('createAuthCallbackDialer', () => { + it('dials only the granted loopback port', () => { + const dial = vi.fn(() => fakeSocket()) + const connect = createAuthCallbackDialer(54121, () => {}, dial) + expect(() => connect({ host: '127.0.0.1', port: 22 })).toThrow( + 'auth_callback_destination_refused' + ) + expect(() => connect({ host: '10.0.0.5', port: 54121 })).toThrow( + 'auth_callback_destination_refused' + ) + connect({ host: '127.0.0.1', port: 54121 }) + expect(dial).toHaveBeenCalledExactlyOnceWith(54121) + }) + + it('closes the tunnel past the stream and byte caps', () => { + const onExceeded = vi.fn() + const socket = fakeSocket() + const connect = createAuthCallbackDialer(54121, onExceeded, () => socket) + const stream = connect({ host: '127.0.0.1', port: 54121 }) + stream.write(new Uint8Array(AUTH_CALLBACK_TUNNEL_MAX_BYTES + 1)) + expect(socket.destroy).toHaveBeenCalled() + expect(onExceeded).toHaveBeenCalledOnce() + for (let index = 1; index < AUTH_CALLBACK_TUNNEL_MAX_STREAMS; index += 1) { + connect({ host: '127.0.0.1', port: 54121 }) + } + expect(() => connect({ host: '127.0.0.1', port: 54121 })).toThrow('auth_callback_stream_limit') + }) +}) diff --git a/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.ts b/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.ts new file mode 100644 index 00000000000..57210bc4c07 --- /dev/null +++ b/src/main/runtime/rpc/methods/accounts/auth-callback-tunnel.ts @@ -0,0 +1,181 @@ +import { connect as netConnect, type Socket } from 'node:net' +import { BrowserNetworkTunnelSession } from '../../../../browser/network/tunnels/browser-network-tunnel-session' +import { BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL } from '../../../../browser/network/tunnels/browser-network-tunnel-stream-state' +import type { BrowserNetworkTunnelSocket } from '../../../../browser/network/tunnels/browser-network-tunnel-stream-state' +import { + AUTH_CALLBACK_FORWARD_MAX_BYTES as AUTH_CALLBACK_TUNNEL_MAX_BYTES, + AUTH_CALLBACK_FORWARD_MAX_STREAMS as AUTH_CALLBACK_TUNNEL_MAX_STREAMS, + AUTH_CALLBACK_FORWARD_TTL_MS as AUTH_CALLBACK_TUNNEL_TTL_MS +} from '../../../../../shared/auth-callback-forward' +import { AuthCallbackTunnelParams } from '../../../../../shared/rpc-contract/accounts-params' +import { HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY } from '../../../../../shared/account-runtime-capabilities' +import { defineStreamingMethod, type RpcContext } from '../../core' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { HostAccountSignInFlows } from '../../../agent-session/environment/host-account-sign-in-flows' + +// Tunnel generations only need to be positive; each subscription is its own session. +const TUNNEL_GENERATION = 1 + +/** Dials only the flow's own callback port on loopback, counting streams and bytes against the caps. */ +export function createAuthCallbackDialer( + port: number, + onExceeded: () => void, + dial: (port: number) => Socket = (target) => + netConnect({ host: 'localhost', port: target, autoSelectFamily: true, allowHalfOpen: true }) +): (target: { host: string; port: number }) => BrowserNetworkTunnelSocket { + let streams = 0 + let bytes = 0 + const count = (socket: Socket, byteLength: number): void => { + bytes += byteLength + if (bytes > AUTH_CALLBACK_TUNNEL_MAX_BYTES) { + socket.destroy() + onExceeded() + } + } + return (target) => { + if (target.port !== port || (target.host !== '127.0.0.1' && target.host !== 'localhost')) { + throw new Error('auth_callback_destination_refused') + } + if (streams >= AUTH_CALLBACK_TUNNEL_MAX_STREAMS) { + onExceeded() + throw new Error('auth_callback_stream_limit') + } + streams += 1 + const socket = dial(port) + const wrapper: BrowserNetworkTunnelSocket = { + get destroyed() { + return socket.destroyed + }, + setNoDelay: (noDelay) => { + socket.setNoDelay(noDelay) + return wrapper + }, + pause: () => { + socket.pause() + return wrapper + }, + resume: () => { + socket.resume() + return wrapper + }, + write: (chunk, callback) => { + count(socket, chunk.byteLength) + return socket.write(chunk, callback) + }, + end: () => { + socket.end() + return wrapper + }, + destroy: () => { + socket.destroy() + return wrapper + }, + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: one implementation serves every overload of `on`. + on: ((event: string, listener: (...args: never[]) => void) => { + if (event === 'data') { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the 'data' overload's listener takes the chunk. + const onData = listener as (chunk: Uint8Array) => void + socket.on('data', (chunk: Uint8Array) => { + count(socket, chunk.byteLength) + onData(chunk) + }) + } else { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: forwarded unchanged to the socket's own event of that name. + socket.on(event, listener as (...args: unknown[]) => void) + } + return wrapper + }) as BrowserNetworkTunnelSocket['on'] + } + return wrapper + } +} + +/** Carries a desktop browser's redirect to the localhost callback of a sign-in this caller started here. */ +export function createAuthCallbackTunnelMethod( + flowsFor: (runtime: OrcaRuntimeService) => HostAccountSignInFlows, + ownerOf: (ctx: Pick) => string +) { + return defineStreamingMethod({ + name: 'network.authCallbackTunnel', + permission: 'accounts-admin', + params: AuthCallbackTunnelParams, + handler: async (params, ctx, emit) => { + const { + runtime, + connectionId, + clientKind, + clientCapabilities, + sendBinary, + registerBinaryMessageHandler, + signal + } = ctx + if ( + clientKind !== 'runtime' || + !connectionId || + !sendBinary || + !registerBinaryMessageHandler + ) { + throw new Error('authenticated_binary_auth_callback_tunnel_required') + } + if (!clientCapabilities?.includes(HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY)) { + throw new Error('auth_callback_tunnel_capability_required') + } + const grant = flowsFor(runtime).callbackTarget(ownerOf(ctx), params.flowId) + if (!grant) { + throw new Error('auth_callback_not_waiting') + } + if (signal?.aborted) { + return + } + const closed = Promise.withResolvers() + let session: BrowserNetworkTunnelSession | null = null + let unregisterBinary = (): void => {} + const close = (): void => session?.close() + const ttl = setTimeout(close, AUTH_CALLBACK_TUNNEL_TTL_MS) + const subscriptionId = JSON.stringify(['auth-callback-tunnel', connectionId, params.flowId]) + let cleaned = false + const cleanup = (): void => { + if (cleaned) { + return + } + cleaned = true + clearTimeout(ttl) + grant.ended.removeEventListener('abort', close) + signal?.removeEventListener('abort', close) + unregisterBinary() + close() + closed.resolve() + } + session = new BrowserNetworkTunnelSession({ + tunnelGeneration: TUNNEL_GENERATION, + connect: createAuthCallbackDialer(grant.port, close), + sendBinary: (bytes) => sendBinary(bytes) !== false, + flowControl: BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL, + onClose: () => { + try { + emit({ type: 'closed', tunnelGeneration: TUNNEL_GENERATION }) + } finally { + cleanup() + } + } + }) + console.info(`[auth-callback-tunnel] opened for port ${grant.port}`) + unregisterBinary = registerBinaryMessageHandler((bytes) => session?.handleBinary(bytes)) + runtime.registerSubscriptionCleanup(subscriptionId, cleanup, connectionId) + // The grant ends with the login: success, failure, cancel or the owner going silent. + grant.ended.addEventListener('abort', close, { once: true }) + signal?.addEventListener('abort', close, { once: true }) + if (grant.ended.aborted || signal?.aborted) { + close() + } else { + emit({ type: 'ready', tunnelGeneration: TUNNEL_GENERATION }) + } + try { + await closed.promise + } finally { + cleanup() + console.info(`[auth-callback-tunnel] closed for port ${grant.port}`) + } + } + }) +} diff --git a/src/preload/api/runtime-api.ts b/src/preload/api/runtime-api.ts index cd257b576ef..09dbbee177c 100644 --- a/src/preload/api/runtime-api.ts +++ b/src/preload/api/runtime-api.ts @@ -1,3 +1,7 @@ +import type { + AuthCallbackForwardRequest, + AuthCallbackForwardResult +} from '../../shared/auth-callback-forward' import type { CrewSubscriptionAttemptArgs, CrewSubscriptionAttemptCallbacks, @@ -92,6 +96,13 @@ export type RuntimeApi = { } runtimeEnvironments: { desktopCreatedChatIds?: () => Promise + // Absent in the web client, which cannot listen on this computer's loopback. + openAuthCallbackForward?: ( + request: AuthCallbackForwardRequest + ) => Promise + closeAuthCallbackForward?: ( + request: Pick + ) => Promise getStatusSnapshots: () => Promise onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void // Absent in the web client, whose catalog lives in the browser rather than a CLI-editable file. diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime-environments-bridge.ts index 715605b216f..7621b9c477a 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime-environments-bridge.ts @@ -24,12 +24,23 @@ import { type RuntimeEnvironmentSubscriptionHandle } from '../runtime-environment-subscriptions' import type { PreloadApi } from '../api-types' +import type { + AuthCallbackForwardRequest, + AuthCallbackForwardResult +} from '../../shared/auth-callback-forward' import { managedOrcadApi } from './managed-orcad-api' import { getWslHostsApi } from './wsl-hosts-api' export const runtimeEnvironmentsApi = { desktopCreatedChatIds: (): Promise => ipcRenderer.invoke('runtimeEnvironments:desktopCreatedChatIds'), + openAuthCallbackForward: ( + request: AuthCallbackForwardRequest + ): Promise => + ipcRenderer.invoke('runtimeEnvironments:openAuthCallbackForward', request), + closeAuthCallbackForward: ( + request: Pick + ): Promise => ipcRenderer.invoke('runtimeEnvironments:closeAuthCallbackForward', request), getStatusSnapshots: (): Promise => ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'), onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => { diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx new file mode 100644 index 00000000000..34e47519186 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx @@ -0,0 +1,101 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import type { AgentSignInGate, AgentSignInGateView } from '@/lib/agent-sign-in/agent-sign-in-gate' +import { AgentSignInCard, type AgentSignInCardActions } from './AgentSignInCard' +import { AgentSignInOverlay } from './AgentSignInOverlay' + +const actions: AgentSignInCardActions = { + signIn: () => {}, + retry: () => {}, + useCode: () => {}, + submitCode: () => {}, + openLink: () => {}, + copyText: () => {}, + cancel: () => {}, + skip: () => {} +} + +const PROMPT = 'Fix the flaky retry test in api/client.test.ts and explain the root cause' + +function gate( + view: AgentSignInGateView, + overrides: Partial = {} +): AgentSignInGate { + return { + key: 'fixture', + environmentId: 'env-m4air', + hostLabel: 'm4air', + agent: 'claude', + prompt: PROMPT, + codeOnly: false, + view, + ...overrides + } +} + +function Pane({ children }: { children: React.ReactNode }): React.JSX.Element { + return ( +
+
nw@m4air ~/src/api (fix/flaky-retry) $
+ {children} +
+ ) +} + +const shot = (g: AgentSignInGate) => + defineFixture({ + width: 640, + render: () => ( + + + + ) + }) + +export const need = shot(gate({ step: 'need' })) +export const needCodex = shot(gate({ step: 'need' }, { agent: 'codex' })) +export const starting = shot(gate({ step: 'starting' })) +export const waiting = shot(gate({ step: 'waiting', url: 'https://claude.ai/oauth/authorize' })) +export const waitingCodex = shot( + gate({ step: 'waiting', url: 'https://auth.openai.com/oauth/authorize' }, { agent: 'codex' }) +) +export const signedIn = shot(gate({ step: 'signed', email: 'nw@stably.ai' })) +export const portBusy = shot( + gate( + { step: 'error', kind: 'port_busy', message: 'Port 1455 is busy.', port: 1455 }, + { agent: 'codex' } + ) +) +export const timedOut = shot(gate({ step: 'error', kind: 'timeout', message: 'timed out' })) +export const declined = shot(gate({ step: 'error', kind: 'declined', message: 'access_denied' })) +export const offline = shot(gate({ step: 'error', kind: 'offline', message: 'transport lost' })) +export const failed = shot( + gate({ + step: 'error', + kind: 'failed', + message: 'Claude command failed: OAuth error: invalid_grant' + }) +) +export const pasteCode = shot( + gate({ + step: 'paste', + url: 'https://claude.ai/oauth/authorize?code=true', + submitting: false, + refusal: null + }) +) +export const pasteRefused = shot( + gate({ + step: 'paste', + url: 'https://claude.ai/oauth/authorize?code=true', + submitting: false, + refusal: 'Claude did not accept that code. Start the sign-in again.' + }) +) +export const deviceCode = shot( + gate( + { step: 'device', url: 'https://auth.openai.com/codex/device', userCode: 'K7PQ-2HXM' }, + { agent: 'codex' } + ) +) +export const olderHost = shot(gate({ step: 'need' }, { codeOnly: true })) +export const noPrompt = shot(gate({ step: 'need' }, { prompt: null, hostLabel: 'feature-x' })) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx new file mode 100644 index 00000000000..8cb7b4494dc --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx @@ -0,0 +1,359 @@ +import { CircleAlert, Copy, ExternalLink } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { AgentIcon } from '@/lib/agent-catalog' +import { Button } from '@/components/ui/button' +import { LoadingSpinner } from '@/components/LoadingSpinner' +import { PasteCodeForm } from './AgentSignInPasteCodeForm' +import type { AgentSignInGate } from '@/lib/agent-sign-in/agent-sign-in-gate' + +export type AgentSignInCardActions = { + signIn: () => void + retry: () => void + useCode: () => void + submitCode: (code: string) => void + openLink: (url: string) => void + copyText: (text: string) => void + cancel: () => void + skip: () => void +} + +const AGENT_NAME = { claude: 'Claude', codex: 'Codex' } as const +const SIGN_IN_SITE = { claude: 'claude.ai', codex: 'chatgpt.com' } as const + +function QueuedPrompt({ + prompt, + label +}: { + prompt: string + label: React.ReactNode +}): React.JSX.Element { + return ( +
+ {label} + + {prompt} + +
+ ) +} + +function ErrorLine({ title, detail }: { title: string; detail: string }): React.JSX.Element { + return ( +
+ +

+ {title}{' '} + {detail} +

+
+ ) +} + +/** Inline sign-in for an agent about to start on a host where it isn't signed in. */ +export function AgentSignInCard({ + gate, + actions +}: { + gate: AgentSignInGate + actions: AgentSignInCardActions +}): React.JSX.Element { + const t = useTranslate() + const name = AGENT_NAME[gate.agent] + const host = gate.hostLabel + const view = gate.view + const title = + view.step === 'waiting' + ? t('agentSignIn.waitingTitle', 'Finish in your browser') + : view.step === 'signed' + ? t('agentSignIn.signedTitle', 'Signed in to {{agent}} on {{host}}', { agent: name, host }) + : t('agentSignIn.title', 'Sign in to {{agent}} on {{host}}', { agent: name, host }) + const busy = view.step === 'starting' + const cancel = ( + + ) + const codeLabel = + gate.agent === 'claude' + ? t('agentSignIn.pasteInstead', 'Paste a code instead') + : t('agentSignIn.deviceInstead', 'Use a device code instead') + + let body: React.ReactNode = null + if (view.step === 'need' || view.step === 'starting') { + body = gate.codeOnly + ? t( + 'agentSignIn.codeOnlyBody', + '{{host}} runs an older Orca, so sign-in needs a code. The sign-in is saved on {{host}}, not here.', + { host } + ) + : t( + 'agentSignIn.needBody', + 'Approve once in your browser. The sign-in is saved on {{host}}, not here.', + { host } + ) + } else if (view.step === 'waiting') { + body = ( + + + {gate.agent === 'claude' + ? t('agentSignIn.waitingClaude', 'Click Authorize on {{site}}.', { + site: SIGN_IN_SITE.claude + }) + : t('agentSignIn.waitingCodex', 'Click Continue on {{site}}.', { + site: SIGN_IN_SITE.codex + })} + + ) + } else if (view.step === 'signed') { + body = view.email ? t('agentSignIn.signedAs', 'as {{email}}', { email: view.email }) : null + } else if (view.step === 'paste') { + body = t('agentSignIn.pasteBody', 'Sign in on the page, then paste the code it shows.') + } else if (view.step === 'device') { + body = t('agentSignIn.deviceBody', 'Open the page and enter this code.') + } + + return ( +
{ + if (event.key === 'Escape') { + event.stopPropagation() + actions.cancel() + } + }} + > +
+
+ +
+
+
{title}
+ {body ?
{body}
: null} +
+
+ + {view.step === 'error' ? : null} + + {view.step === 'paste' ? ( + <> +
+ + +
+ + + ) : null} + + {view.step === 'device' ? ( +
+ + {view.userCode} + + + + +
+ ) : null} + + {gate.prompt ? ( + + + {t('agentSignIn.sending', 'Starting {{agent}} and sending', { agent: name })} + + ) : ( + t('agentSignIn.queued', 'Sends after sign-in') + ) + } + /> + ) : null} + + {view.step === 'signed' ? null : view.step === 'waiting' ? ( +
+ + + + {cancel} +
+ ) : ( +
+ {cancel} + {view.step === 'error' && view.kind === 'port_busy' && !gate.codeOnly ? ( + + ) : null} + {view.step === 'need' || view.step === 'starting' ? ( + + ) : view.step === 'error' ? ( + + ) : null} +
+ )} + + {view.step === 'need' || view.step === 'starting' || view.step === 'error' ? ( +
+ {gate.codeOnly ? null : ( + + )} + + +
+ ) : null} +
+ ) +} + +function AgentSignInError({ + gate, + view +}: { + gate: AgentSignInGate + view: Extract +}): React.JSX.Element { + const t = useTranslate() + const name = AGENT_NAME[gate.agent] + switch (view.kind) { + case 'port_busy': + return ( + + ) + case 'timeout': + return ( + + ) + case 'declined': + return ( + + ) + case 'offline': + return ( + + ) + case 'failed': + return ( + + ) + } +} diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInOverlay.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInOverlay.tsx new file mode 100644 index 00000000000..6c9ac37ade6 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInOverlay.tsx @@ -0,0 +1,11 @@ +/** The pane-covering scrim the sign-in card sits on, matching the sleeping-pane overlay. */ +export function AgentSignInOverlay({ children }: { children: React.ReactNode }): React.JSX.Element { + return ( +
+ {children} +
+ ) +} diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx new file mode 100644 index 00000000000..01e465b8259 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx @@ -0,0 +1,89 @@ +import { useEffect } from 'react' +import { createPortal } from 'react-dom' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types' +import { + abandonAgentSignIn, + openSignInPage, + cancelAgentSignIn, + readAgentSignInGate, + retryAgentSignIn, + skipAgentSignIn, + startAgentSignIn, + submitAgentSignInCode, + switchToCodeSignIn, + useAgentSignInGate +} from '@/lib/agent-sign-in/agent-sign-in-gate' +import type { TerminalPaneController } from '../terminal-pane/controller/use-terminal-pane-controller' +import { AgentSignInCard, type AgentSignInCardActions } from './AgentSignInCard' +import { AgentSignInOverlay } from './AgentSignInOverlay' + +// Why a delay: remounts unmount the portal too; only a pane that stays gone abandons its sign-in. +const ABANDON_CHECK_MS = 1_000 +const mountedPortals = new Map() + +function cardActions(key: string): AgentSignInCardActions { + return { + signIn: () => startAgentSignIn(key), + retry: () => void retryAgentSignIn(key), + useCode: () => void switchToCodeSignIn(key), + submitCode: (code) => void submitAgentSignInCode(key, code), + openLink: openSignInPage, + copyText: (text) => void window.api.ui.writeClipboardText(text), + cancel: () => cancelAgentSignIn(key), + skip: () => skipAgentSignIn(key) + } +} + +function AgentSignInPanePortal({ + pane, + tabId +}: { + pane: ManagedPane + tabId: string +}): React.JSX.Element | null { + const key = makePaneKey(tabId, pane.leafId) + const gate = useAgentSignInGate(key) + const held = gate !== null + useEffect(() => { + if (!held) { + return + } + mountedPortals.set(key, (mountedPortals.get(key) ?? 0) + 1) + return () => { + mountedPortals.set(key, (mountedPortals.get(key) ?? 1) - 1) + setTimeout(() => { + if ((mountedPortals.get(key) ?? 0) <= 0 && readAgentSignInGate(key)) { + mountedPortals.delete(key) + abandonAgentSignIn(key) + } + }, ABANDON_CHECK_MS) + } + }, [held, key]) + if (!gate) { + return null + } + return createPortal( + + + , + pane.container, + `agent-sign-in-${pane.id}` + ) +} + +/** Each pane whose agent launch waits for sign-in on its host shows the card instead of a terminal. */ +export function AgentSignInPanePortals({ + controller +}: { + controller: TerminalPaneController +}): React.JSX.Element { + const { managedPanes, tabId } = controller + return ( + <> + {managedPanes.map((pane) => ( + + ))} + + ) +} diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInPasteCodeForm.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInPasteCodeForm.tsx new file mode 100644 index 00000000000..55d1a08eb30 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInPasteCodeForm.tsx @@ -0,0 +1,58 @@ +import { useId, useState } from 'react' +import { useTranslate } from '@/i18n/use-translate' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' + +/** The code Claude's sign-in page shows, sent back to the login on the host. */ +export function PasteCodeForm({ + submitting, + refusal, + onSubmit +}: { + submitting: boolean + refusal: string | null + onSubmit: (code: string) => void +}): React.JSX.Element { + const t = useTranslate() + const [code, setCode] = useState('') + const labelId = useId() + const trimmed = code.trim() + return ( +
{ + event.preventDefault() + if (trimmed && !submitting) { + onSubmit(trimmed) + } + }} + > +
+ setCode(event.target.value)} + /> + +
+ + {t('agentSignIn.pasteCodeLabel', 'Code from the sign-in page')} + + {refusal ? ( +

+ {refusal} +

+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.fixture.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.fixture.tsx new file mode 100644 index 00000000000..1f8006d3a2c --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.fixture.tsx @@ -0,0 +1,44 @@ +import { Pencil, RefreshCw } from 'lucide-react' +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { rememberHostAgentSignInReport } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { HostAgentSignOutMenuItems } from './HostAgentSignOutMenuItems' + +export const signedIn = defineFixture({ + width: 320, + setup: () => + rememberHostAgentSignInReport('env-m4air', { + checkedAt: 0, + agents: [ + { agent: 'claude', state: 'signedIn', method: 'orcaAccount' }, + { agent: 'codex', state: 'signedIn', method: 'cliLogin' } + ] + }), + render: () => ( +
+ + m4air + + + m4air + + + + Rename… + + + + Check connection + + + + +
+ ) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx new file mode 100644 index 00000000000..b7d967d8543 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx @@ -0,0 +1,107 @@ +import { useEffect, useSyncExternalStore } from 'react' +import { LogOut } from 'lucide-react' +import { toast } from 'sonner' +import { + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator +} from '@/components/ui/dropdown-menu' +import { useTranslate } from '@/i18n/use-translate' +import { translate } from '@/i18n/i18n' +import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' +import { + readHostAgentSignInReport, + refreshHostAgentSignInReport, + rememberHostAgentSignInReport, + subscribeHostAgentSignInReports +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import type { + HostAgentSignInAgent, + HostAgentSignInReport +} from '../../../../../../shared/host-agent-sign-in-status' + +const AGENT_NAME: Record = { claude: 'Claude', codex: 'Codex' } + +async function signOut( + environmentId: string, + hostLabel: string, + agent: HostAgentSignInAgent +): Promise { + const name = AGENT_NAME[agent] + try { + const report = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'accounts.agentSignOut', + { agent }, + { timeoutMs: 30_000 } + ) + rememberHostAgentSignInReport(environmentId, report) + toast.success( + translate('agentSignIn.signedOutToast', 'Signed out of {{agent}} on {{host}}', { + agent: name, + host: hostLabel + }), + { + description: translate( + 'agentSignIn.signedOutDetail', + 'The next {{agent}} you start there asks to sign in.', + { agent: name } + ) + } + ) + } catch (error) { + toast.error( + error instanceof Error + ? error.message + : translate('agentSignIn.signOutFailed', 'Could not sign out on {{host}}.', { + host: hostLabel + }) + ) + } +} + +/** "Sign out of Claude/Codex" for agents the host reports signed in; nothing otherwise. */ +export function HostAgentSignOutMenuItems({ + environmentId, + hostLabel, + open +}: { + environmentId: string + hostLabel: string + open: boolean +}): React.JSX.Element | null { + const t = useTranslate() + const report = useSyncExternalStore(subscribeHostAgentSignInReports, () => + readHostAgentSignInReport(environmentId) + ) + useEffect(() => { + if (open) { + // Asked only when the menu opens; the host answers from its own one-minute cache. + void refreshHostAgentSignInReport(environmentId) + } + }, [environmentId, open]) + // API-key logins live in the host's own environment, which Orca does not manage. + const signedIn = (report?.agents ?? []).filter( + (entry) => entry.state === 'signedIn' && entry.method !== 'apiKey' + ) + if (signedIn.length === 0) { + return null + } + return ( + <> + + + {t('agentSignIn.menuLabel', 'Agents on {{host}}', { host: hostLabel })} + + {signedIn.map((entry) => ( + void signOut(environmentId, hostLabel, entry.agent)} + > + + {t('agentSignIn.signOutOf', 'Sign out of {{agent}}', { agent: AGENT_NAME[entry.agent] })} + + ))} + + ) +} diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/HostSectionHeaderMenu.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/HostSectionHeaderMenu.tsx index 85c73e17ded..fbc0f3a3f5c 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/HostSectionHeaderMenu.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/HostSectionHeaderMenu.tsx @@ -43,6 +43,7 @@ import { HostRenameDialog } from '../../HostRenameDialog' import { HostRemoveDialog } from '../../HostRemoveDialog' import { RuntimeRepairDialog } from '../../../runtime-access/RuntimeRepairDialog' import { resolveHostRemoval } from '../../host-rename-remove' +import { HostAgentSignOutMenuItems } from './HostAgentSignOutMenuItems' function blockedTitle( reason: 'client-too-old' | 'server-too-old', @@ -297,6 +298,13 @@ export function HostSectionHeaderMenu({ row }: { row: HostHeaderRow }): React.JS {t('auto.components.sidebar.HostSectionHeaderMenu.2d3e4f5a6b', 'Check connection')} )} + {runtimeEnvironmentId && row.health !== 'blocked' && ( + + )} diff --git a/src/renderer/src/components/terminal-pane/controller/TerminalPaneSurface.tsx b/src/renderer/src/components/terminal-pane/controller/TerminalPaneSurface.tsx index e324b6c0eb4..715d644d9f3 100644 --- a/src/renderer/src/components/terminal-pane/controller/TerminalPaneSurface.tsx +++ b/src/renderer/src/components/terminal-pane/controller/TerminalPaneSurface.tsx @@ -21,6 +21,7 @@ import { handleInternalTerminalFileDrop } from '../input/file-drop/terminal-drop import { TerminalQuickCommandEditorDialog } from '../quick-commands/TerminalQuickCommandEditorDialog' import { TerminalPaneNativeChatPortal } from '../chat/TerminalPaneNativeChatPortal' import { TerminalPaneSleepingPortals } from '../session-restore/spawn-deferral/TerminalPaneSleepingPortals' +import { AgentSignInPanePortals } from '../../agent-sign-in/AgentSignInPanePortals' import { TerminalPaneCodexRestartPortals } from './TerminalPaneCodexRestartPortals' import { TerminalPaneMobileDriverPortals } from '../mobile-driver/TerminalPaneMobileDriverPortals' import { TerminalPaneProcessExitPortals } from '../process-exit/TerminalPaneProcessExitPortals' @@ -389,6 +390,7 @@ export function TerminalPaneSurface({ /> + [0] + +/** A fresh Claude/Codex launch on a runtime host; resumes and plain shells are never held. */ +export function agentSignInGateRequest( + session: ConnectPanePtySession, + startupOverride: PendingStartupCommand | null | undefined +): GateRequest | null { + const environmentId = session.runtimeEnvironmentId + const startup = session.paneStartup + if (startupOverride !== undefined || !environmentId || !startup) { + return null + } + // Fresh launches also carry launchConfig (for a later resume); only resume facts mark a resume. + if (startup.resumeSource || startup.resumeProviderSession) { + return null + } + const agent = startup.launchAgent ?? startup.agentLaunch?.launch.agent + if (agent !== 'claude' && agent !== 'codex') { + return null + } + const prompt = + startup.freshAgentLaunch?.prompt ?? + startup.agentLaunch?.launch.prompt ?? + startup.draftPrompt ?? + startup.initialAgentStatus?.prompt ?? + agentLaunchPanePrompt(session.deps.tabId) + const hostLabel = + useAppStore + .getState() + .runtimeEnvironments.find((environment) => environment.id === environmentId)?.name ?? + environmentId + return { + key: session.cacheKey, + environmentId, + hostLabel, + agent, + prompt: prompt?.trim() || null + } +} + +function noteCancelledLaunch(prompt: string | null): void { + toast( + translate('agentSignIn.cancelledToast', 'Sign-in cancelled. The agent did not start.'), + prompt + ? { + action: { + label: translate('agentSignIn.copyPrompt', 'Copy prompt'), + onClick: () => void window.api.ui.writeClipboardText(prompt) + } + } + : undefined + ) +} + +/** + * Holds the pane's first spawn until its agent is signed in on the host. The held spawn is + * registered as pending so a remount waits for it instead of starting a second agent. + */ +export function gateFreshSpawnOnAgentSignIn( + session: ConnectPanePtySession, + request: GateRequest, + spawn: (startupOverride?: null) => Promise +): Promise { + const held = requireAgentSignIn(request).then((outcome) => { + if (session.disposed) { + return null + } + if (outcome === 'cancel') { + // Only this pane's agent is dropped; the pane opens a plain shell like a new terminal. + noteCancelledLaunch(request.prompt) + return spawn(null) + } + return spawn() + }) + const tracked = held.finally(() => { + if (pendingSpawnByPaneKey.get(session.pendingSpawnKey) === tracked) { + pendingSpawnByPaneKey.delete(session.pendingSpawnKey) + pendingSpawnGenerationByPaneKey.delete(session.pendingSpawnKey) + } + }) + pendingSpawnByPaneKey.set(session.pendingSpawnKey, tracked) + pendingSpawnGenerationByPaneKey.set(session.pendingSpawnKey, session.tabGeneration) + return tracked +} + +/** A first Claude/Codex launch on a signed-out host waits for its inline sign-in. */ +export function installAgentSignInSpawnGate(session: ConnectPanePtySession): void { + const start = session.startFreshSpawn + session.startFreshSpawn = (startupOverride, options) => { + const request = agentSignInGateRequest(session, startupOverride) + return request + ? gateFreshSpawnOnAgentSignIn(session, request, (override = startupOverride) => + start(override, options) + ) + : start(startupOverride, options) + } +} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/spawn/fresh-spawn-start.ts b/src/renderer/src/components/terminal-pane/pty-connection/spawn/fresh-spawn-start.ts index c27987c850a..cb5a69392e7 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/spawn/fresh-spawn-start.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/spawn/fresh-spawn-start.ts @@ -20,6 +20,7 @@ import type { import type { ConnectPanePtySession } from '../connect-pane-pty-session' import { findTerminalTabForPane } from '../terminal-tab-id' +import { installAgentSignInSpawnGate } from './agent-sign-in-spawn-gate' export function releaseDeferredCwdFence(session: ConnectPanePtySession): void { if (!session.transport.getPtyId()) { @@ -320,4 +321,5 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void { pendingSpawnGenerationByPaneKey.set(session.pendingSpawnKey, session.tabGeneration) return trackedPromise } + installAgentSignInSpawnGate(session) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b192f42c6f7..9184fb3104b 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -24486,5 +24486,54 @@ "stopped": "{{host}} stopped controlling browser tabs until Orca restarts.", "disallowed": "{{host}} can no longer control browser tabs. Turn it back on in Settings > SSH.", "failed": "Couldn’t stop {{host}}. Turn off its browser control in Settings > SSH." + }, + "agentSignIn": { + "pasteCodePlaceholder": "Paste code", + "continue": "Continue", + "pasteCodeLabel": "Code from the sign-in page", + "waitingTitle": "Finish in your browser", + "signedTitle": "Signed in to {{agent}} on {{host}}", + "title": "Sign in to {{agent}} on {{host}}", + "cancel": "Cancel", + "pasteInstead": "Paste a code instead", + "deviceInstead": "Use a device code instead", + "codeOnlyBody": "{{host}} runs an older Orca, so sign-in needs a code. The sign-in is saved on {{host}}, not here.", + "needBody": "Approve once in your browser. The sign-in is saved on {{host}}, not here.", + "waitingClaude": "Click Authorize on {{site}}.", + "waitingCodex": "Click Continue on {{site}}.", + "signedAs": "as {{email}}", + "pasteBody": "Sign in on the page, then paste the code it shows.", + "deviceBody": "Open the page and enter this code.", + "openPage": "Open sign-in page", + "copyLink": "Copy link", + "copyCode": "Copy code", + "openPageShort": "Open page", + "sending": "Starting {{agent}} and sending", + "queued": "Sends after sign-in", + "openAgain": "Open again", + "pasteShort": "Paste a code", + "deviceShort": "Use a device code", + "signInCode": "Sign in", + "signIn": "Sign in with browser", + "tryAgain": "Try again", + "startAnyway": "Start without signing in", + "errors": { + "portBusy": "Port {{port}} is busy on this computer.", + "portBusyDetail": "Another {{agent}} sign-in is probably open. Close it and try again.", + "timeout": "Sign-in timed out.", + "timeoutDetail": "Nothing came back from the browser in time.", + "declined": "Not authorized.", + "declinedDetail": "{{site}} reported that the sign-in was declined.", + "offline": "Can't reach {{host}}.", + "offlineDetail": "Your prompt stays here until it reconnects.", + "failed": "Sign-in failed." + }, + "cancelledToast": "Sign-in cancelled. The agent did not start.", + "copyPrompt": "Copy prompt", + "signedOutToast": "Signed out of {{agent}} on {{host}}", + "signedOutDetail": "The next {{agent}} you start there asks to sign in.", + "signOutFailed": "Could not sign out on {{host}}.", + "menuLabel": "Agents on {{host}}", + "signOutOf": "Sign out of {{agent}}" } } diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts new file mode 100644 index 00000000000..20070434196 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client', () => { + const report = { checkedAt: 0, agents: [{ agent: 'claude', state: 'signedOut' }] } + return { + readHostAgentSignInReport: () => null, + refreshHostAgentSignInReport: async () => report, + hostAgentSignInEntry: (value: typeof report | null, agent: string) => + value?.agents.find((entry) => entry.agent === agent) ?? null + } +}) +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ + runtimeEnvironmentSupportsCapability: async () => true +})) + +const { + agentSignInGateEntry, + readAgentSignInGate, + releaseAgentSignInPane, + requireAgentSignIn, + settleAgentSignInGate +} = await import('./agent-sign-in-gate-store') + +const request = (key: string) => ({ + key, + environmentId: 'env-1', + hostLabel: 'devbox', + agent: 'claude' as const, + prompt: null +}) + +describe('agent sign-in gate', () => { + it('holds every pane launching the agent on that host behind one sign-in', async () => { + const first = requireAgentSignIn(request('pane-a')) + await vi.waitFor(() => expect(readAgentSignInGate('pane-a')).not.toBeNull()) + const second = requireAgentSignIn(request('pane-b')) + await vi.waitFor(() => expect(readAgentSignInGate('pane-b')).not.toBeNull()) + const entry = agentSignInGateEntry('pane-a') + expect(agentSignInGateEntry('pane-b')).toBe(entry) + + // One pane leaving keeps the sign-in for the other. + expect(releaseAgentSignInPane('pane-a', 'cancel')).toBe(false) + await expect(first).resolves.toBe('cancel') + expect(readAgentSignInGate('pane-a')).toBeNull() + expect(readAgentSignInGate('pane-b')).not.toBeNull() + + settleAgentSignInGate(entry!, 'proceed') + await expect(second).resolves.toBe('proceed') + expect(readAgentSignInGate('pane-b')).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts new file mode 100644 index 00000000000..7aae5638f28 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts @@ -0,0 +1,222 @@ +import { useSyncExternalStore } from 'react' +import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status' +import { HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY } from '../../../../shared/account-runtime-capabilities' +import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof' +import { + hostAgentSignInEntry, + readHostAgentSignInReport, + refreshHostAgentSignInReport +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' + +/** What the sign-in card shows; one step at a time, in the order the person meets them. */ +export type AgentSignInGateView = + | { step: 'need' } + | { step: 'starting' } + | { step: 'waiting'; url: string } + | { step: 'paste'; url: string; submitting: boolean; refusal: string | null } + | { step: 'device'; url: string; userCode: string } + | { step: 'signed'; email: string | null } + | { + step: 'error' + kind: 'port_busy' | 'timeout' | 'declined' | 'offline' | 'failed' + message: string + port?: number + } + +export type AgentSignInGate = { + /** One gate per host and agent; every pane launching that agent there waits on it. */ + key: string + environmentId: string + hostLabel: string + agent: HostAgentSignInAgent + prompt: string | null + /** The host predates browser sign-in, so its sign-in pastes a code or uses a device code. */ + codeOnly: boolean + view: AgentSignInGateView +} + +export type GateEntry = AgentSignInGate & { + /** Each held pane's launch, by pane key. */ + waiters: Map void> + /** Bumps on every new sign-in attempt so a late result of an abandoned one is ignored. */ + attempt: number + forwardFlowId: string | null +} + +// A first check on a host may spawn its CLIs; past this the launch proceeds unheld. +const FIRST_CHECK_BUDGET_MS = 4_000 + +const gates = new Map() +const gateKeyByPane = new Map() +const listeners = new Set<() => void>() + +const gateKeyOf = (environmentId: string, agent: HostAgentSignInAgent): string => + `${environmentId}\u0000${agent}` + +function notify(): void { + for (const listener of listeners) { + listener() + } +} + +function publicGate(entry: GateEntry): AgentSignInGate { + const { waiters: _waiters, attempt: _attempt, forwardFlowId: _flow, ...gate } = entry + return gate +} + +const snapshots = new WeakMap() +function snapshotOf(entry: GateEntry | undefined): AgentSignInGate | null { + if (!entry) { + return null + } + const cached = snapshots.get(entry) + if (cached && cached.view === entry.view) { + return cached.gate + } + const gate = publicGate(entry) + snapshots.set(entry, { view: entry.view, gate }) + return gate +} + +/** The gate the pane's launch waits on. */ +export function agentSignInGateEntry(paneKey: string): GateEntry | undefined { + const key = gateKeyByPane.get(paneKey) + return key === undefined ? undefined : gates.get(key) +} + +export function isCurrentAgentSignInGate(entry: GateEntry): boolean { + return gates.get(entry.key) === entry +} + +export function setAgentSignInGateView(entry: GateEntry, view: AgentSignInGateView): void { + if (!isCurrentAgentSignInGate(entry)) { + return + } + entry.view = view + notify() +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function useAgentSignInGate(paneKey: string): AgentSignInGate | null { + return useSyncExternalStore(subscribe, () => snapshotOf(agentSignInGateEntry(paneKey))) +} + +export function readAgentSignInGate(paneKey: string): AgentSignInGate | null { + return snapshotOf(agentSignInGateEntry(paneKey)) +} + +/** Whether `agent` is known signed out on the host; unknown answers count as signed in. */ +export async function isAgentSignedOutOnHost( + environmentId: string, + agent: HostAgentSignInAgent +): Promise { + const cached = hostAgentSignInEntry(readHostAgentSignInReport(environmentId), agent) + if (cached && cached.state !== 'signedOut') { + // Sign-in rarely changes by itself; refresh quietly for next time. + void refreshHostAgentSignInReport(environmentId) + return false + } + const report = await Promise.race([ + refreshHostAgentSignInReport(environmentId), + new Promise((resolve) => setTimeout(() => resolve(null), FIRST_CHECK_BUDGET_MS)) + ]) + return hostAgentSignInEntry(report, agent)?.state === 'signedOut' +} + +function waitOn(entry: GateEntry, paneKey: string): Promise<'proceed' | 'cancel'> { + return new Promise((resolve) => { + const previous = entry.waiters.get(paneKey) + entry.waiters.set(paneKey, (outcome) => { + previous?.(outcome) + resolve(outcome) + }) + gateKeyByPane.set(paneKey, entry.key) + notify() + }) +} + +/** + * Holds an agent launch on a runtime host until its agent is signed in there. Resolves `proceed` + * at once when the host reports it signed in, cannot tell, or predates the check. Panes launching + * the same agent on the same host share one sign-in. + */ +export async function requireAgentSignIn(request: { + key: string + environmentId: string + hostLabel: string + agent: HostAgentSignInAgent + prompt: string | null +}): Promise<'proceed' | 'cancel'> { + const { key: paneKey, ...gate } = request + const key = gateKeyOf(gate.environmentId, gate.agent) + const running = gates.get(key) + if (running) { + return waitOn(running, paneKey) + } + if (!(await isAgentSignedOutOnHost(gate.environmentId, gate.agent))) { + return 'proceed' + } + const codeOnly = !(await runtimeEnvironmentSupportsCapability( + gate.environmentId, + HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY + ).catch(() => false)) + const entry = gates.get(key) ?? { + ...gate, + key, + codeOnly, + view: { step: 'need' as const }, + waiters: new Map(), + attempt: 0, + forwardFlowId: null + } + gates.set(key, entry) + return waitOn(entry, paneKey) +} + +/** Ends the gate for every pane waiting on it. */ +export function settleAgentSignInGate(entry: GateEntry, outcome: 'proceed' | 'cancel'): void { + if (!isCurrentAgentSignInGate(entry)) { + return + } + closeAgentSignInForward(entry) + gates.delete(entry.key) + const waiters = [...entry.waiters] + entry.waiters.clear() + for (const [paneKey] of waiters) { + gateKeyByPane.delete(paneKey) + } + notify() + for (const [, resolve] of waiters) { + resolve(outcome) + } +} + +/** Lets one pane go its own way; true when no other pane still waits on the gate. */ +export function releaseAgentSignInPane(paneKey: string, outcome: 'proceed' | 'cancel'): boolean { + const entry = agentSignInGateEntry(paneKey) + const resolve = entry?.waiters.get(paneKey) + if (!entry || !resolve) { + return true + } + entry.waiters.delete(paneKey) + gateKeyByPane.delete(paneKey) + notify() + resolve(outcome) + return entry.waiters.size === 0 +} + +export function closeAgentSignInForward(entry: GateEntry): void { + const flowId = entry.forwardFlowId + if (!flowId) { + return + } + entry.forwardFlowId = null + void window.api.runtimeEnvironments.closeAuthCallbackForward?.({ + environmentId: entry.environmentId, + flowId + }) +} diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts new file mode 100644 index 00000000000..993e8c26be5 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts @@ -0,0 +1,306 @@ +import type { + ClaudeRateLimitAccountsState, + CodexRateLimitAccountsState +} from '../../../../shared/managed-account-types' +import type { HostAccountSignInStatus } from '../../../../shared/host-account-sign-in-types' +import { refreshHostAgentSignInReport } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { + cancelHostAccountSignIn, + hostAccountSignInEnded, + isLostHostAnswer, + readHostAccountSignIn, + signInAgentOnHost, + submitHostAccountSignInCode, + subscribeHostAccountSignIns +} from '@/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client' +import { + selectClaudeProviderAccount, + selectCodexProviderAccount +} from '@/runtime/provider-accounts/observations/runtime-provider-accounts-client' +import { + agentSignInGateEntry, + closeAgentSignInForward, + isCurrentAgentSignInGate, + releaseAgentSignInPane, + setAgentSignInGateView, + settleAgentSignInGate, + type AgentSignInGateView, + type GateEntry +} from './agent-sign-in-gate-store' + +export { + isAgentSignedOutOnHost, + readAgentSignInGate, + requireAgentSignIn, + useAgentSignInGate, + type AgentSignInGate, + type AgentSignInGateView +} from './agent-sign-in-gate-store' + +const SIGNED_IN_HOLD_MS = 600 + +/** Sign-in pages open in the person's own browser, where they are already signed in. */ +export function openSignInPage(url: string): void { + void window.api.shell.openUrl(url) +} + +function classifyFailure(error: unknown): Extract { + const message = error instanceof Error ? error.message : String(error) + if (isLostHostAnswer(error)) { + return { step: 'error', kind: 'offline', message } + } + if (/took too long|timed out/i.test(message)) { + return { step: 'error', kind: 'timeout', message } + } + if (/access_denied|denied|declined/i.test(message)) { + return { step: 'error', kind: 'declined', message } + } + return { step: 'error', kind: 'failed', message } +} + +type HostAccounts = ClaudeRateLimitAccountsState | CodexRateLimitAccountsState + +/** The account the sign-in just added on the host: the most recently authenticated one there. */ +type HostAccountSummary = { + id: string + email: string + lastAuthenticatedAt: number + managedAuthRuntime?: 'host' | 'wsl' + managedHomeRuntime?: 'host' | 'wsl' +} + +function newestHostAccount(state: HostAccounts | undefined): { id: string; email: string } | null { + const accounts: readonly HostAccountSummary[] = state?.accounts ?? [] + const onHost = accounts.filter( + (account) => (account.managedAuthRuntime ?? account.managedHomeRuntime ?? 'host') === 'host' + ) + onHost.sort((a, b) => b.lastAuthenticatedAt - a.lastAuthenticatedAt) + return onHost[0] ?? null +} + +async function finishSignedIn(entry: GateEntry, status: HostAccountSignInStatus): Promise { + const owner = { kind: 'environment', environmentId: entry.environmentId } as const + const account = newestHostAccount(entry.agent === 'claude' ? status.claude : status.codex) + // Launches use the host's selected account; the one just signed in is the one wanted there. + if (account) { + await ( + entry.agent === 'claude' + ? selectClaudeProviderAccount(owner, { accountId: account.id, runtime: 'host' }) + : selectCodexProviderAccount(owner, { accountId: account.id, runtime: 'host' }) + ).catch(() => {}) + } + void refreshHostAgentSignInReport(entry.environmentId, { force: true }) + setAgentSignInGateView(entry, { step: 'signed', email: account?.email ?? null }) + setTimeout(() => settleAgentSignInGate(entry, 'proceed'), SIGNED_IN_HOLD_MS) +} + +/** Follows the host's sign-in and turns its prompts into card steps until it settles. */ +function follow(entry: GateEntry, attempt: number, callback: boolean): void { + const owner = { kind: 'environment', environmentId: entry.environmentId } as const + const current = (): boolean => isCurrentAgentSignInGate(entry) && entry.attempt === attempt + let handledFlowId: string | null = null + const onStatus = (): void => { + if (!current()) { + return + } + const status = readHostAccountSignIn(owner, entry.agent) + const prompt = status?.phase === 'waiting' ? status.prompt : undefined + if (!status || !prompt || handledFlowId === status.flowId) { + return + } + handledFlowId = status.flowId + if (prompt.userCode) { + setAgentSignInGateView(entry, { step: 'device', url: prompt.url, userCode: prompt.userCode }) + return + } + if (!callback || prompt.callbackPort === undefined) { + setAgentSignInGateView(entry, { + step: 'paste', + url: prompt.url, + submitting: false, + refusal: null + }) + return + } + void openBrowserSignIn(entry, attempt, status.flowId, prompt.callbackPort, prompt) + } + const unsubscribe = subscribeHostAccountSignIns(onStatus) + signInAgentOnHost(owner, entry.agent, { callback }) + .then( + async (status) => { + if (current()) { + await finishSignedIn(entry, status) + } + }, + (error: unknown) => { + if (current()) { + closeAgentSignInForward(entry) + setAgentSignInGateView(entry, classifyFailure(error)) + } + } + ) + .finally(unsubscribe) +} + +async function openBrowserSignIn( + entry: GateEntry, + attempt: number, + flowId: string, + port: number, + prompt: NonNullable +): Promise { + // The web client can't listen on this computer, so it goes straight to the code fallback. + const open = window.api.runtimeEnvironments.openAuthCallbackForward + const result = open + ? await open({ environmentId: entry.environmentId, flowId, port }).catch(() => null) + : null + if (!isCurrentAgentSignInGate(entry) || entry.attempt !== attempt) { + if (result?.ok) { + void window.api.runtimeEnvironments.closeAuthCallbackForward?.({ + environmentId: entry.environmentId, + flowId + }) + } + return + } + if (result?.ok) { + entry.forwardFlowId = flowId + openSignInPage(prompt.url) + setAgentSignInGateView(entry, { step: 'waiting', url: prompt.url }) + return + } + if (result?.ok === false && result.code === 'port_busy') { + entry.attempt += 1 + setAgentSignInGateView(entry, { + step: 'error', + kind: 'port_busy', + message: result.message, + port + }) + void cancelHostAccountSignIn( + { kind: 'environment', environmentId: entry.environmentId }, + entry.agent + ).catch(() => {}) + return + } + // No forward: Claude's paste page still signs in; Codex falls back to its device code. + if (prompt.pasteUrl) { + setAgentSignInGateView(entry, { + step: 'paste', + url: prompt.pasteUrl, + submitting: false, + refusal: null + }) + return + } + void switchToCodeSignIn(entry.key) +} + +/** Cancels this client's run on the host and waits for it to end, so a new start can't join it. */ +async function stopHostSignIn(entry: GateEntry): Promise { + const owner = { kind: 'environment', environmentId: entry.environmentId } as const + await cancelHostAccountSignIn(owner, entry.agent).catch(() => {}) + await hostAccountSignInEnded(owner, entry.agent) +} + +function startAttempt(entry: GateEntry, callback: boolean): void { + entry.attempt += 1 + closeAgentSignInForward(entry) + setAgentSignInGateView(entry, { step: 'starting' }) + follow(entry, entry.attempt, callback) +} + +/** Primary action: browser sign-in (or the code flow on hosts that predate it). */ +export function startAgentSignIn(key: string): void { + const entry = agentSignInGateEntry(key) + if (entry) { + startAttempt(entry, !entry.codeOnly) + } +} + +/** Retries after an error, cancelling whatever the host still runs for this agent first. */ +export async function retryAgentSignIn(key: string): Promise { + const entry = agentSignInGateEntry(key) + if (!entry) { + return + } + entry.attempt += 1 + setAgentSignInGateView(entry, { step: 'starting' }) + await stopHostSignIn(entry) + startAttempt(entry, !entry.codeOnly) +} + +/** Fallback without a forwarded callback: Claude's paste page, or Codex's device code. */ +export async function switchToCodeSignIn(key: string): Promise { + const entry = agentSignInGateEntry(key) + if (!entry) { + return + } + const owner = { kind: 'environment', environmentId: entry.environmentId } as const + const pasteUrl = readHostAccountSignIn(owner, entry.agent)?.prompt?.pasteUrl + if (entry.agent === 'claude' && pasteUrl) { + // The same Claude login accepts its pasted code; keep the callback open too. + setAgentSignInGateView(entry, { + step: 'paste', + url: pasteUrl, + submitting: false, + refusal: null + }) + return + } + entry.attempt += 1 + setAgentSignInGateView(entry, { step: 'starting' }) + await stopHostSignIn(entry) + startAttempt(entry, false) +} + +export async function submitAgentSignInCode(key: string, code: string): Promise { + const entry = agentSignInGateEntry(key) + if (!entry || entry.view.step !== 'paste') { + return + } + const paste = entry.view + setAgentSignInGateView(entry, { ...paste, submitting: true, refusal: null }) + try { + await submitHostAccountSignInCode( + { kind: 'environment', environmentId: entry.environmentId }, + entry.agent, + code + ) + } catch (error) { + setAgentSignInGateView(entry, { + ...paste, + submitting: false, + refusal: error instanceof Error ? error.message : String(error) + }) + } +} + +/** Lets one pane leave; the host sign-in stops once no pane waits on it. */ +function leave(paneKey: string, outcome: 'proceed' | 'cancel'): void { + const entry = agentSignInGateEntry(paneKey) + if (!entry || !releaseAgentSignInPane(paneKey, outcome)) { + return + } + entry.attempt += 1 + void cancelHostAccountSignIn( + { kind: 'environment', environmentId: entry.environmentId }, + entry.agent + ).catch(() => {}) + settleAgentSignInGate(entry, outcome) +} + +/** Cancel: the pane starts a plain shell instead of the agent. */ +export function cancelAgentSignIn(paneKey: string): void { + leave(paneKey, 'cancel') +} + +/** Starts the agent without signing in, for hosts whose own setup the check cannot see. */ +export function skipAgentSignIn(paneKey: string): void { + leave(paneKey, 'proceed') +} + +/** Drops a pane that went away; the host sign-in stops if nothing else waits on it. */ +export function abandonAgentSignIn(paneKey: string): void { + leave(paneKey, 'cancel') +} diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts new file mode 100644 index 00000000000..9428399ce1c --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts @@ -0,0 +1,26 @@ +import { parseExecutionHostId } from '../../../../shared/execution-host' +import type { HostAgentLaunch } from '@/store/slices/worktrees/create/worktree-create-payload' +import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation' +import { hostPlannableAgentLaunch } from '@/lib/workspace/creation/worktree-creation-host-agent-launch' +import { isAgentSignedOutOnHost } from './agent-sign-in-gate-store' + +/** Whether the creation's Claude/Codex is known signed out on its runtime host. */ +export function hostSignInCheck(request: WorktreeCreationRequest): Promise { + const host = parseExecutionHostId( + request.workspaceRunContext?.hostId ?? request.executionHostId ?? null + ) + const agent = request.agent + if (host?.kind !== 'runtime' || (agent !== 'claude' && agent !== 'codex')) { + return Promise.resolve(false) + } + return isAgentSignedOutOnHost(host.environmentId, agent) +} + +/** A host-started agent can't show the sign-in card, so a signed-out host gets the pane-planned launch. */ +export async function signedInHostLaunch( + request: WorktreeCreationRequest, + signedOut: Promise +): Promise { + const launch = hostPlannableAgentLaunch(request) + return launch && (await signedOut) ? undefined : launch +} diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts index 27c6a317683..289f32f54ca 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts @@ -20,7 +20,6 @@ import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-w import { resolveBackendDraftStartup } from '@/lib/workspace/creation/worktree-draft-startup-view-mode' import { recoverWorktreeLegacyPreparation, - hostPlannableAgentLaunch, worktreeCreationAgentLaunchOptions, windowStartupAfterCreate } from '@/lib/workspace/creation/worktree-creation-host-agent-launch' @@ -38,12 +37,14 @@ import { } from '@/lib/workspace/creation/worktree-creation-surface' import { prepareCreatedWorktreeActivation } from '@/lib/workspace/creation/worktree-creation-initial-tabs' import type { UISlice } from '@/store/slices/ui/ui-slice-contract' +import { hostSignInCheck, signedInHostLaunch } from '@/lib/agent-sign-in/host-agent-launch-sign-in' export async function executeWorktreeCreation( creationId: string, request: WorktreeCreationRequest, originView: UISlice['activeView'] = 'terminal' ): Promise { + const signedOut = hostSignInCheck(request) // asked while the request is prepared const trustedRequest = request.hookPreparation ? await prepareWorktreeCreationHooks(creationId, request) : request @@ -57,7 +58,7 @@ export async function executeWorktreeCreation( const creationHostId = preparedRequest.workspaceRunContext?.hostId ?? preparedRequest.executionHostId const onCreationHost = creationHostId ? { executionHostId: creationHostId } : {} - const hostAgentLaunch = hostPlannableAgentLaunch(preparedRequest) + const hostAgentLaunch = await signedInHostLaunch(preparedRequest, signedOut) let result: CreatedWorktreeResult try { const provisionedRoot = getProvisionedRootCreateOptions(preparedRequest) diff --git a/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts new file mode 100644 index 00000000000..b479c8f214e --- /dev/null +++ b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts @@ -0,0 +1,101 @@ +import type { + HostAgentSignInAgent, + HostAgentSignInEntry, + HostAgentSignInReport +} from '../../../../../shared/host-agent-sign-in-status' +import { HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY } from '../../../../../shared/account-runtime-capabilities' +import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' +import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof' + +const CALL_TIMEOUT_MS = 30_000 + +type Entry = { + report: HostAgentSignInReport | null + pending: Promise | null +} + +const entries = new Map() +const listeners = new Set<() => void>() + +function notify(): void { + for (const listener of listeners) { + listener() + } +} + +async function fetchReport( + environmentId: string, + force: boolean +): Promise { + try { + if ( + !(await runtimeEnvironmentSupportsCapability( + environmentId, + HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY + )) + ) { + return null + } + return await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'accounts.agentSignInStatus', + force ? { force: true } : {}, + { timeoutMs: CALL_TIMEOUT_MS } + ) + } catch { + // An older, asleep or unreachable host answers nothing; launches there proceed as before. + return null + } +} + +/** The host's last verdicts, without asking. */ +export function readHostAgentSignInReport(environmentId: string): HostAgentSignInReport | null { + return entries.get(environmentId)?.report ?? null +} + +export function hostAgentSignInEntry( + report: HostAgentSignInReport | null, + agent: HostAgentSignInAgent +): HostAgentSignInEntry | null { + return report?.agents.find((entry) => entry.agent === agent) ?? null +} + +export function subscribeHostAgentSignInReports(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +/** Asks the host; concurrent callers share one request. `force` skips the host's own cache. */ +export function refreshHostAgentSignInReport( + environmentId: string, + options: { force?: boolean } = {} +): Promise { + const entry = entries.get(environmentId) ?? { report: null, pending: null } + if (entry.pending && !options.force) { + return entry.pending + } + const pending = fetchReport(environmentId, options.force === true).then((report) => { + const current = entries.get(environmentId) + if (current?.pending === pending) { + entries.set(environmentId, { report: report ?? current.report, pending: null }) + notify() + } + return report + }) + entries.set(environmentId, { report: entry.report, pending }) + return pending +} + +/** Records a verdict the host returned from another call (sign-out answers with a fresh report). */ +export function rememberHostAgentSignInReport( + environmentId: string, + report: HostAgentSignInReport +): void { + entries.set(environmentId, { report, pending: null }) + notify() +} + +export function _resetHostAgentSignInReportsForTest(): void { + entries.clear() + listeners.clear() +} diff --git a/src/renderer/src/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client.ts b/src/renderer/src/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client.ts index 0d7193958b3..4f336b381e9 100644 --- a/src/renderer/src/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client.ts +++ b/src/renderer/src/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client.ts @@ -38,6 +38,8 @@ type Attempt = { provider: HostAccountSignInProvider pairingRevision: number | undefined stage: 'checking' | 'starting' | 'following' + /** Browser sign-in whose localhost callback this client forwards to the host. */ + callback: boolean cancelRequested: boolean /** The host acknowledged the cancel (its flow is stopping or settled). */ cancelDelivered: boolean @@ -127,7 +129,10 @@ async function follow(attempt: Attempt): Promise { advance( attempt, await retryLostAnswers(() => - call(attempt, 'accounts.hostSignInStart', { provider: attempt.provider }) + call(attempt, 'accounts.hostSignInStart', { + provider: attempt.provider, + ...(attempt.callback ? { callback: true } : {}) + }) ) ) attempt.stage = 'following' @@ -191,7 +196,8 @@ function settle(attempt: Attempt): HostAccountSignInStatus { /** Starts a sign-in on `owner`, or joins the one this client already runs there. */ function runHostAccountSignIn( owner: EnvironmentTarget, - provider: HostAccountSignInProvider + provider: HostAccountSignInProvider, + options: { callback?: boolean } = {} ): Promise { const key = keyOf(owner, provider) const running = attempts.get(key) @@ -211,6 +217,7 @@ function runHostAccountSignIn( provider, pairingRevision: captureRuntimeEnvironmentRequestRevision(owner.environmentId), stage: 'checking', + callback: options.callback === true, cancelRequested: false, cancelDelivered: false, status: null, @@ -289,6 +296,25 @@ export async function addCodexAccountOnHost( return status.codex } +/** Signs `provider` in on `owner` for an agent about to start there; `callback` uses the browser + * sign-in whose localhost redirect this client forwards (hosts with the callback capability only). */ +export function signInAgentOnHost( + owner: EnvironmentTarget, + provider: HostAccountSignInProvider, + options: { callback: boolean } +): Promise { + return runHostAccountSignIn(owner, provider, options) +} + +/** Resolves once this client's run for `provider` on `owner` has ended, however it ended. */ +export async function hostAccountSignInEnded( + owner: RuntimeClientTarget, + provider: HostAccountSignInProvider +): Promise { + const attempt = owner.kind === 'environment' ? attempts.get(keyOf(owner, provider)) : undefined + await attempt?.done?.catch(() => {}) +} + export async function submitHostAccountSignInCode( owner: RuntimeClientTarget, provider: HostAccountSignInProvider, diff --git a/src/shared/account-runtime-capabilities.ts b/src/shared/account-runtime-capabilities.ts index ee423cae7cc..503f7607298 100644 --- a/src/shared/account-runtime-capabilities.ts +++ b/src/shared/account-runtime-capabilities.ts @@ -13,6 +13,12 @@ export const DATA_ACCOUNT_RUNTIME_CAPABILITY = 'accounts.managed-data-profiles.v export const USAGE_CREDENTIALS_RUNTIME_CAPABILITY = 'accounts.usage-credentials.v1' as const // Why: a paired client adds a Claude/Codex account whose login runs on this host (#20009). export const HOST_ACCOUNT_SIGN_IN_RUNTIME_CAPABILITY = 'accounts.host-sign-in.v1' as const +// Why: older hosts lack the verdict-only check, so launches there are never held for sign-in. +export const HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY = + 'accounts.agent-sign-in-status.v1' as const +// Why: browser sign-in whose localhost callback the client forwards here, plus agent sign-out. +export const HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY = + 'accounts.host-sign-in-callback.v1' as const export const ACCOUNT_RUNTIME_CAPABILITIES = [ ACCOUNT_IMPORT_RUNTIME_CAPABILITY, @@ -23,5 +29,7 @@ export const ACCOUNT_RUNTIME_CAPABILITIES = [ DATA_ACCOUNT_RUNTIME_CAPABILITY, CODEX_RESET_CREDIT_RUNTIME_CAPABILITY, USAGE_CREDENTIALS_RUNTIME_CAPABILITY, - HOST_ACCOUNT_SIGN_IN_RUNTIME_CAPABILITY + HOST_ACCOUNT_SIGN_IN_RUNTIME_CAPABILITY, + HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY, + HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY ] as const diff --git a/src/shared/auth-callback-forward.ts b/src/shared/auth-callback-forward.ts new file mode 100644 index 00000000000..4977301ffe5 --- /dev/null +++ b/src/shared/auth-callback-forward.ts @@ -0,0 +1,15 @@ +/** A host sign-in whose localhost callback this computer listens for and carries to the host. */ +export type AuthCallbackForwardRequest = { + environmentId: string + flowId: string + port: number +} + +export type AuthCallbackForwardResult = + | { ok: true } + | { ok: false; code: 'port_busy' | 'listen_failed' | 'tunnel_failed'; message: string } + +// A browser callback is one redirect plus a success page; both ends hold the forward to this. +export const AUTH_CALLBACK_FORWARD_MAX_STREAMS = 8 +export const AUTH_CALLBACK_FORWARD_MAX_BYTES = 1024 * 1024 +export const AUTH_CALLBACK_FORWARD_TTL_MS = 10 * 60_000 diff --git a/src/shared/host-account-sign-in-types.ts b/src/shared/host-account-sign-in-types.ts index a8c7f5b4451..456e9e94a40 100644 --- a/src/shared/host-account-sign-in-types.ts +++ b/src/shared/host-account-sign-in-types.ts @@ -20,6 +20,10 @@ export type HostAccountSignInPrompt = { userCode: string | null /** Claude shows a code after sign-in that has to come back to the host. */ needsCode: boolean + /** Browser sign-in: the host login's localhost callback port, which the client forwards here. */ + callbackPort?: number + /** Browser sign-in: Claude's paste-code page, a fallback that needs no forwarded callback. */ + pasteUrl?: string } /** How a login running on the host reaches the person signing in elsewhere. */ @@ -28,6 +32,8 @@ export type HostAccountSignInChannel = { onPrompt: (prompt: HostAccountSignInPrompt) => void /** The code the person pasted back; rejects if the flow ends first. */ nextCode: () => Promise + /** Run the login's browser flow and publish its localhost callback instead of a code-only flow. */ + callback?: boolean } /** One sign-in as the host reports it to the client that started it. */ @@ -74,3 +80,22 @@ export function isHostAccountSignInPage(provider: HostAccountSignInProvider, url return false } } + +export const LOCAL_CALLBACK_HOSTS: ReadonlySet = new Set(['localhost', '127.0.0.1']) + +/** The loopback port a sign-in page redirects back to, or null when it is not a localhost callback. */ +export function signInCallbackPort(url: string): number | null { + try { + const redirect = new URL(new URL(url).searchParams.get('redirect_uri') ?? '') + const port = Number(redirect.port) + return redirect.protocol === 'http:' && + LOCAL_CALLBACK_HOSTS.has(redirect.hostname) && + Number.isInteger(port) && + port >= 1024 && + port <= 65_535 + ? port + : null + } catch { + return null + } +} diff --git a/src/shared/host-agent-sign-in-status.ts b/src/shared/host-agent-sign-in-status.ts new file mode 100644 index 00000000000..2e9d83deac3 --- /dev/null +++ b/src/shared/host-agent-sign-in-status.ts @@ -0,0 +1,21 @@ +/** Agents whose sign-in a host can check and relay; matches HostAccountSignInProvider. */ +export type HostAgentSignInAgent = 'claude' | 'codex' + +export const HOST_AGENT_SIGN_IN_AGENTS: readonly HostAgentSignInAgent[] = ['claude', 'codex'] + +export type HostAgentSignInState = 'signedIn' | 'signedOut' | 'notInstalled' | 'unknown' + +/** How a signed-in agent authenticates; never the credential itself. */ +export type HostAgentSignInMethod = 'orcaAccount' | 'cliLogin' | 'apiKey' + +export type HostAgentSignInEntry = { + agent: HostAgentSignInAgent + state: HostAgentSignInState + method?: HostAgentSignInMethod +} + +/** What a host reports about its agents' sign-in. Carries verdicts only, never tokens or CLI output. */ +export type HostAgentSignInReport = { + checkedAt: number + agents: HostAgentSignInEntry[] +} diff --git a/src/shared/rpc-contract/accounts-params.ts b/src/shared/rpc-contract/accounts-params.ts index 30b95bfe712..c9682878de7 100644 --- a/src/shared/rpc-contract/accounts-params.ts +++ b/src/shared/rpc-contract/accounts-params.ts @@ -111,7 +111,17 @@ export const FinishClaudeSignInParams = z .object({ accountId: z.string().min(1), ...ClaudeSignInTarget }) .strict() -export const HostAccountSignInStartParams = z.object({ provider: z.enum(['claude', 'codex']) }) +export const HostAccountSignInStartParams = z.object({ + provider: z.enum(['claude', 'codex']), + // Clients send it only to hosts advertising accounts.host-sign-in-callback.v1. + callback: z.boolean().optional() +}) + +export const HostAgentSignInStatusParams = z.object({ force: z.boolean().optional() }) + +export const HostAgentSignOutParams = z.object({ agent: z.enum(['claude', 'codex']) }) + +export const AuthCallbackTunnelParams = z.object({ flowId: z.string().min(1).max(64) }) export const HostAccountSignInWaitParams = z.object({ flowId: z.string().min(1).max(64), diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 8e5fdeaa8e1..118074de86d 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -53,6 +53,7 @@ import { AddClaudeFromConfigDirParams, AddCodexFromHomeParams, AddDataAccountParams, + AuthCallbackTunnelParams, BeginClaudeSignInParams, ConsumeCodexResetCreditParams, FinishClaudeSignInParams, @@ -60,6 +61,8 @@ import { HostAccountSignInFlowParams, HostAccountSignInStartParams, HostAccountSignInWaitParams, + HostAgentSignInStatusParams, + HostAgentSignOutParams, ListAccountsParams, RemoveAccountParams, RemoveDataAccountParams, @@ -772,6 +775,8 @@ export const RPC_PARAMS_BY_METHOD = { 'accounts.addClaudeFromConfigDir': AddClaudeFromConfigDirParams, 'accounts.addCodexFromHome': AddCodexFromHomeParams, 'accounts.addDataFromHome': AddDataAccountParams, + 'accounts.agentSignInStatus': HostAgentSignInStatusParams, + 'accounts.agentSignOut': HostAgentSignOutParams, 'accounts.antigravityAddCurrent': AntigravityAccountTargetParams, 'accounts.antigravityChatAuthApply': AntigravityChatAuthConfigSchema, 'accounts.antigravityChatAuthGet': null, @@ -1319,6 +1324,7 @@ export const RPC_PARAMS_BY_METHOD = { 'nativeChat.readSession': NativeChatSession, 'nativeChat.subscribe': NativeChatSession, 'nativeChat.unsubscribe': NativeChatUnsubscribe, + 'network.authCallbackTunnel': AuthCallbackTunnelParams, 'network.browserTunnel': BrowserNetworkTunnelAttachParams, 'notifications.getMissedSince': NotificationGetMissedSinceParams, 'notifications.registerPush': NotificationRegisterPushParams, diff --git a/tests/e2e/agent-host-sign-in.spec.ts b/tests/e2e/agent-host-sign-in.spec.ts new file mode 100644 index 00000000000..b385ddebbb4 --- /dev/null +++ b/tests/e2e/agent-host-sign-in.spec.ts @@ -0,0 +1,179 @@ +// A first Claude launch on a signed-out paired host holds its prompt behind the inline sign-in card; +// the browser's localhost redirect reaches the host's login through the client's callback forward. +import { existsSync, readFileSync, rmSync } from 'node:fs' +import { createServer, type AddressInfo } from 'node:net' +import type { Page } from '@stablyai/playwright-test' +import { expect, test } from './helpers/orca-app' +import { TEST_REPO_PATH_FILE } from './global-setup' +import { launchPairedElectronClient } from './helpers/paired-electron-client' +import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import { writeAgentSignInFakeClaude } from './helpers/agent-sign-in-fake-claude' +import { writeAgentSignInFakeCodex } from './helpers/agent-sign-in-fake-codex' + +const PROMPT = 'Fix the flaky retry test in api/client.test.ts' +// A recorded run holds each step long enough to read; plain runs don't wait. +const RECORDING = process.env.ORCA_E2E_RECORD_VIDEO === '1' + +async function proofStep(page: Page, outputDir: string | null, name: string): Promise { + if (RECORDING && outputDir) { + // ast-grep-ignore: test-no-real-time-wait -- holds a settled frame so the recorded video can be read; plain runs skip it. + await page.waitForTimeout(1_500) + await page.screenshot({ path: `${outputDir}/${name}.png` }) + } +} + +async function freePort(): Promise { + const probe = createServer() + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a TCP server bound to a port reports AddressInfo. + const { port } = probe.address() as AddressInfo + await new Promise((resolve) => probe.close(() => resolve())) + return port +} + +async function callRuntime( + page: Page, + environmentId: string, + method: string, + params: unknown +): Promise { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test-only RPC result shape. + return page.evaluate( + async ({ environmentId, method, params }) => { + const response = await window.api.runtimeEnvironments.call({ + selector: environmentId, + method, + params + }) + if (!response.ok) { + throw new Error(`${response.error.code}: ${response.error.message}`) + } + return response.result + }, + { environmentId, method, params } + ) as Promise +} + +const AGENTS = [ + { agent: 'claude', site: 'claude.ai', callbackPath: '/callback', proof: true }, + { agent: 'codex', site: 'auth.openai.com', callbackPath: '/auth/callback', proof: false } +] as const + +for (const { agent, site, callbackPath, proof } of AGENTS) { + test(`a signed-out host holds the ${agent} launch until the browser sign-in finishes`, async (// oxlint-disable-next-line no-empty-pattern -- This test owns its host launch. + {}, testInfo) => { + test.skip(process.platform === 'win32', 'host sign-in runs on macOS and Linux hosts') + // Two Electron apps (host and client) start per run. + test.setTimeout(240_000) + const repoPath = existsSync(TEST_REPO_PATH_FILE) + ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() + : '' + test.skip(!repoPath, 'Global setup did not produce a seeded test repo') + const fakeDir = writeAgentSignInFakeClaude() + writeAgentSignInFakeCodex(fakeDir) + const callbackPort = await freePort() + const host = await launchHeadlessPairedRuntimeHost({ + extraEnv: { + PATH: `${fakeDir}:${process.env.PATH ?? ''}`, + FAKE_CLAUDE_CALLBACK_PORT: String(callbackPort), + FAKE_CODEX_CALLBACK_PORT: String(callbackPort) + } + }) + try { + const client = await launchPairedElectronClient(host.offer, testInfo, 'agent-host-sign-in') + try { + const { page, environmentId } = client + // The system browser stands in as this list; the test plays its redirect below. + await client.app.evaluate(({ shell }) => { + const opened: string[] = [] + Object.assign(globalThis, { __openedUrls: opened }) + shell.openExternal = async (url: string) => { + opened.push(url) + } + }) + const added = await callRuntime<{ repo: { id: string } }>(page, environmentId, 'repo.add', { + path: repoPath, + kind: 'git' + }) + const findWorktreeId = (): Promise => + page.evaluate( + (repoId) => + window.__store + ?.getState() + .allWorktrees() + .find((worktree) => worktree.repoId === repoId)?.id ?? null, + added.repo.id + ) + await expect.poll(findWorktreeId, { timeout: 60_000 }).not.toBeNull() + const worktreeId = (await findWorktreeId()) ?? '' + const tabId = await page.evaluate( + ({ worktreeId, prompt, agent }) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('store unavailable') + } + state.setActiveView('terminal') + state.setActiveWorktree(worktreeId) + const tab = state.createTab(worktreeId, undefined, undefined, { launchAgent: agent }) + state.queueTabStartupCommand(tab.id, { + command: `${agent} ${JSON.stringify(prompt)}`, + launchAgent: agent, + initialAgentStatus: { agent, prompt } + }) + state.setActiveTab(tab.id) + return tab.id + }, + { worktreeId, prompt: PROMPT, agent } + ) + + const card = page.locator('[data-agent-sign-in]') + await expect(card).toHaveAttribute('data-agent-sign-in', 'need', { timeout: 60_000 }) + await expect(card).toContainText(PROMPT) + // Workspace activation may seed its own shell tab after ours; bring the agent's back. + await page.evaluate((id) => window.__store?.getState().setActiveTab(id), tabId) + await proofStep(page, proof ? testInfo.outputDir : null, '1-needs-sign-in') + await card.getByRole('button', { name: 'Sign in with browser' }).click() + await expect(card).toHaveAttribute('data-agent-sign-in', 'waiting', { timeout: 60_000 }) + await proofStep(page, proof ? testInfo.outputDir : null, '2-waiting-for-browser') + + const opened = await client.app.evaluate(() => { + const urls: unknown = Object.getOwnPropertyDescriptor(globalThis, '__openedUrls')?.value + return Array.isArray(urls) ? urls.map(String) : [] + }) + const signInUrl = new URL(opened.at(-1) ?? '') + expect(signInUrl.hostname).toBe(site) + expect(new URL(signInUrl.searchParams.get('redirect_uri') ?? '').port).toBe( + String(callbackPort) + ) + + // The browser's redirect lands on this computer and must reach the host's login. + const redirect = await fetch( + `http://127.0.0.1:${callbackPort}${callbackPath}?code=fake&state=fake`, + { + redirect: 'manual' + } + ) + expect(redirect.status).toBe(302) + + if (RECORDING && proof) { + await expect(card).toHaveAttribute('data-agent-sign-in', 'signed', { timeout: 60_000 }) + await page.screenshot({ path: `${testInfo.outputDir}/3-signed-in.png` }) + } + await expect(card).toHaveCount(0, { timeout: 60_000 }) + await proofStep(page, proof ? testInfo.outputDir : null, '4-agent-running') + const report = await callRuntime<{ agents: { agent: string; state: string }[] }>( + page, + environmentId, + 'accounts.agentSignInStatus', + { force: true } + ) + expect(report.agents.find((entry) => entry.agent === agent)?.state).toBe('signedIn') + } finally { + await client.dispose() + } + } finally { + await host.dispose() + rmSync(fakeDir, { recursive: true, force: true }) + } + }) +} diff --git a/tests/e2e/helpers/agent-sign-in-fake-claude.ts b/tests/e2e/helpers/agent-sign-in-fake-claude.ts new file mode 100644 index 00000000000..8e30334e9e4 --- /dev/null +++ b/tests/e2e/helpers/agent-sign-in-fake-claude.ts @@ -0,0 +1,86 @@ +// A scripted `claude` whose browser sign-in answers on a localhost callback, like the real CLI. +import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +const FAKE_CLAUDE_SOURCE = `#!/usr/bin/env node +const fs = require('node:fs') +const http = require('node:http') +const path = require('node:path') +const os = require('node:os') +const { spawn } = require('node:child_process') +const args = process.argv.slice(2) +const stateFile = path.join(process.env.CLAUDE_CONFIG_DIR || os.homedir(), '.claude.json') +const email = process.env.FAKE_CLAUDE_EMAIL || 'demo@example.com' +const loggedIn = () => { + try { return Boolean(JSON.parse(fs.readFileSync(stateFile, 'utf8')).oauthAccount) } catch { return false } +} +const signIn = () => { + fs.mkdirSync(path.dirname(stateFile), { recursive: true }) + fs.writeFileSync(stateFile, JSON.stringify({ oauthAccount: { emailAddress: email } })) +} +if (args[0] === '--version') { + console.log('2.1.319 (Claude Code)') + process.exit(0) +} +if (args[0] === 'auth' && args[1] === 'status') { + console.log(JSON.stringify({ loggedIn: loggedIn(), authMethod: loggedIn() ? 'claude.ai' : 'none' })) + process.exit(loggedIn() ? 0 : 1) +} +if (args[0] === 'auth' && args[1] === 'logout') { + fs.rmSync(stateFile, { force: true }) + process.exit(0) +} +if (args[0] === 'auth' && args[1] === 'login') { + const port = Number(process.env.FAKE_CLAUDE_CALLBACK_PORT || 54545) + const server = http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost') + if (url.pathname === '/callback' && url.searchParams.get('code')) { + signIn() + res.writeHead(302, { Location: 'https://claude.ai/oauth/code/success?app=claude-code' }) + res.end() + setTimeout(() => { + console.log('Login successful.') + process.exit(0) + }, 100) + return + } + res.writeHead(404) + res.end() + }) + // Why [::1]: the paired client on the same machine owns 127.0.0.1 for the forwarded callback. + server.listen(port, process.env.FAKE_CLAUDE_CALLBACK_HOST || '::1', () => { + const redirect = encodeURIComponent('http://localhost:' + port + '/callback') + const browserLink = 'https://claude.ai/oauth/authorize?client_id=fake&response_type=code&redirect_uri=' + redirect + '&state=fake' + const pasteLink = 'https://claude.ai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=' + encodeURIComponent('https://platform.claude.com/oauth/code/callback') + '&state=fake' + if (process.env.BROWSER) { + spawn(process.env.BROWSER, [browserLink], { stdio: 'ignore' }) + } + process.stdout.write("Browser didn't open? Use the url below to sign in\\n\\n" + pasteLink + '\\n\\nPaste code here if prompted > ') + }) + process.stdin.on('data', (chunk) => { + if (chunk.toString().trim()) { + signIn() + console.log('Login successful.') + process.exit(0) + } + }) + return +} +// An interactive session: echo the prompt like Claude's first turn. +const prompt = args.filter((arg, index) => !arg.startsWith('-') && args[index - 1] !== '--plugin-dir').join(' ') +process.stdout.write('\\x1b[38;5;173m✻ Claude Code\\x1b[0m · ' + process.cwd() + ' · ' + (loggedIn() ? email : 'not signed in') + '\\r\\n\\r\\n') +if (prompt) { + process.stdout.write('> ' + prompt + '\\r\\n\\r\\n\\x1b[38;5;173m⏺\\x1b[0m Working on it…\\r\\n') +} +process.stdin.resume() +` + +/** Writes the fake `claude` into a fresh directory to put first on the host's PATH. */ +export function writeAgentSignInFakeClaude(): string { + const dir = mkdtempSync(path.join(os.tmpdir(), 'orca-fake-claude-')) + const file = path.join(dir, 'claude') + writeFileSync(file, FAKE_CLAUDE_SOURCE) + chmodSync(file, 0o755) + return dir +} diff --git a/tests/e2e/helpers/agent-sign-in-fake-codex.ts b/tests/e2e/helpers/agent-sign-in-fake-codex.ts new file mode 100644 index 00000000000..8699b14aff4 --- /dev/null +++ b/tests/e2e/helpers/agent-sign-in-fake-codex.ts @@ -0,0 +1,75 @@ +// A scripted `codex` whose browser login answers on a localhost callback, like `codex login`. +import { chmodSync, writeFileSync } from 'node:fs' +import path from 'node:path' + +const FAKE_CODEX_SOURCE = `#!/usr/bin/env node +const fs = require('node:fs') +const http = require('node:http') +const path = require('node:path') +const os = require('node:os') +const args = process.argv.slice(2) +const home = process.env.CODEX_HOME || path.join(os.homedir(), '.codex') +const authFile = path.join(home, 'auth.json') +const email = process.env.FAKE_CLAUDE_EMAIL || 'demo@example.com' +const b64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64url') +const signIn = () => { + const claims = { email, 'https://api.openai.com/auth': { chatgpt_account_id: 'acct-demo', chatgpt_plan_type: 'pro' } } + const idToken = b64({ alg: 'none' }) + '.' + b64(claims) + '.sig' + fs.mkdirSync(home, { recursive: true }) + fs.writeFileSync(authFile, JSON.stringify({ + tokens: { id_token: idToken, access_token: 'a', refresh_token: 'r', account_id: 'acct-demo' }, + last_refresh: new Date().toISOString() + })) +} +if (args[0] === '--version') { + console.log('codex-cli 0.167.0') + process.exit(0) +} +if (args[0] === 'login' && args[1] === 'status') { + const loggedIn = fs.existsSync(authFile) + console.error(loggedIn ? 'Logged in using ChatGPT' : 'Not logged in') + process.exit(loggedIn ? 0 : 1) +} +if (args[0] === 'logout') { + fs.rmSync(authFile, { force: true }) + process.exit(0) +} +if (args[0] === 'login') { + const port = Number(process.env.FAKE_CODEX_CALLBACK_PORT || 1455) + const server = http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost') + if (url.pathname === '/auth/callback' && url.searchParams.get('code')) { + signIn() + res.writeHead(302, { Location: 'http://localhost:' + port + '/success' }) + res.end() + setTimeout(() => { + console.error('Successfully logged in') + process.exit(0) + }, 100) + return + } + res.writeHead(404) + res.end() + }) + // Why [::1]: the paired client on the same machine owns 127.0.0.1 for the forwarded callback. + server.listen(port, '::1', () => { + const redirect = encodeURIComponent('http://localhost:' + port + '/auth/callback') + const url = 'https://auth.openai.com/oauth/authorize?response_type=code&client_id=fake&redirect_uri=' + redirect + '&state=fake' + console.error('If your browser did not open, navigate to this URL to authenticate:\\n\\n' + url + '\\n') + }) + return +} +const prompt = args.filter((arg) => !arg.startsWith('-')).join(' ') +process.stdout.write('>_ OpenAI Codex (fake) · ' + (fs.existsSync(authFile) ? email : 'not signed in') + '\\r\\n') +if (prompt) { + process.stdout.write('› ' + prompt + '\\r\\n') +} +process.stdin.resume() +` + +/** Adds the fake `codex` beside the fake `claude` in `dir`. */ +export function writeAgentSignInFakeCodex(dir: string): void { + const file = path.join(dir, 'codex') + writeFileSync(file, FAKE_CODEX_SOURCE) + chmodSync(file, 0o755) +}