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..0de38b333d9 --- /dev/null +++ b/src/main/claude/claude-auth-status-report.ts @@ -0,0 +1,47 @@ +/** 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 record = parsed as Record + const report: ClaudeAuthStatusReport = {} + if (typeof record.loggedIn === 'boolean') { + report.loggedIn = record.loggedIn + } + for (const field of STRING_FIELDS) { + const value = record[field] + if (typeof value === 'string') { + report[field] = value + } + } + return report +} diff --git a/src/main/claude/claude-real-cli-test-gate.ts b/src/main/claude/claude-real-cli-test-gate.ts index 745ede2733b..b47bfd01e87 100644 --- a/src/main/claude/claude-real-cli-test-gate.ts +++ b/src/main/claude/claude-real-cli-test-gate.ts @@ -1,3 +1,5 @@ +import { parseClaudeAuthStatusReport } from './claude-auth-status-report' + /** Opt-in for tests that drive the real `claude` CLI on this machine's signed-in account. */ export const REAL_CLAUDE_CLI_TEST_ENV = 'ORCA_REAL_CLAUDE_CLI_TEST' @@ -12,34 +14,16 @@ export type RealClaudeCliGate = { } function parseAuthStatus(stdout: string): RealClaudeAuthStatus | 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)) { + const report = parseClaudeAuthStatusReport(stdout) + if (!report) { return null } const status: RealClaudeAuthStatus = {} - if ('loggedIn' in parsed && typeof parsed.loggedIn === 'boolean') { - status.loggedIn = parsed.loggedIn + if (report.loggedIn !== undefined) { + status.loggedIn = report.loggedIn } - if ('projectsDirectory' in parsed && typeof parsed.projectsDirectory === 'string') { - status.projectsDirectory = parsed.projectsDirectory + if (report.projectsDirectory !== undefined) { + status.projectsDirectory = report.projectsDirectory } return status } 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..6cda1ab9063 --- /dev/null +++ b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.test.ts @@ -0,0 +1,139 @@ +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('falls back to the CLI login when the selected Claude account has no login of its own', 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: 1, output: CLAUDE_SIGNED_OUT, 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' } + ]) + }) +}) 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..90c6965533a --- /dev/null +++ b/src/main/runtime/agent-session/environment/host-agent-sign-in-status.ts @@ -0,0 +1,195 @@ +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'] +} + +function hostSelection(state: { + activeAccountId: string | null + activeAccountIdsByRuntime?: { host: string | null } +}): string | null { + return state.activeAccountIdsByRuntime?.host ?? state.activeAccountId +} + +/** Whether launches here already use a signed-in Orca account, so the CLI's own login is moot. */ +function usesOrcaAccount(agent: HostAgentSignInAgent, accounts: Accounts | null): boolean { + if (!accounts) { + return false + } + if (agent === 'claude') { + const id = hostSelection(accounts.claude) + const account = accounts.claude.accounts.find((entry) => entry.id === id) + return Boolean(account && !account.needsSignIn && !account.runsOnSystemDefault) + } + const id = hostSelection(accounts.codex) + return accounts.codex.accounts.some((entry) => entry.id === id) +} + +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 + + constructor(private readonly deps: HostAgentSignInStatusDeps) {} + + read(force = false): Promise { + if (this.inFlight) { + return this.inFlight + } + const cached = this.report + if (!force && cached && this.deps.now() - cached.checkedAt < REPORT_TTL_MS) { + return Promise.resolve(cached) + } + 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' } + } + if (usesOrcaAccount(agent, accounts)) { + return { agent, state: 'signedIn', method: 'orcaAccount' } + } + 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 && field in error + ? (error as Record)[field] + : 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 { + exitCode: typeof code === 'number' ? code : null, + output: `${typeof stdout === 'string' ? stdout : ''}\n${typeof stderr === 'string' ? stderr : ''}`, + timedOut: code === 'ETIMEDOUT' || errorField(error, 'killed') === true + } + } +} + +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..e77449ac619 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 { AGENT_SIGN_IN_STATUS_METHOD } from './agent-sign-in-status-method' import { AddDataAccountParams, SelectDataAccountParams, @@ -217,6 +218,7 @@ const ACCOUNT_METHOD_DEFINITIONS = [ }) } }), + AGENT_SIGN_IN_STATUS_METHOD, // Credentials stay on this host; the caller opens the page and relays its code (#20009). defineMethod({ name: 'accounts.hostSignInStart', diff --git a/src/main/runtime/rpc/methods/accounts/agent-sign-in-status-method.ts b/src/main/runtime/rpc/methods/accounts/agent-sign-in-status-method.ts new file mode 100644 index 00000000000..fa898e2be44 --- /dev/null +++ b/src/main/runtime/rpc/methods/accounts/agent-sign-in-status-method.ts @@ -0,0 +1,25 @@ +import { defineMethod } from '../../core' +import { + createHostAgentSignInStatusChecker, + type HostAgentSignInStatusChecker +} from '../../../agent-session/environment/host-agent-sign-in-status' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { HostAgentSignInStatusParams } 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 +} + +// Verdicts only: CLI output and credentials stay on this host. +export const AGENT_SIGN_IN_STATUS_METHOD = defineMethod({ + name: 'accounts.agentSignInStatus', + permission: 'workspace', + params: HostAgentSignInStatusParams, + handler: async ({ force }, { runtime }) => checkerFor(runtime).read(force === true) +}) diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index ec6963440dd..8d807af9cb4 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -13,6 +13,7 @@ import RunningTerminalCloseDialog from './components/terminal-pane/layout/close/ import WorktreeBaseFallbackDialog from './components/WorktreeBaseFallbackDialog' import AgentWorkspaceTrustDecisionDialog from './components/agent-workspace-trust/AgentWorkspaceTrustDecisionDialog' import ClaudeAccountSwitchDialog from './components/ClaudeAccountSwitchDialog' +import HostAgentSignInDialog from './components/settings/accounts/sign-in/host-agents/HostAgentSignInDialog' import { useUnreadDockBadge } from './hooks/useUnreadDockBadge' import { AppBackgroundServices } from './app-shell/AppBackgroundServices' import { AppRootSurfaces } from './app-shell/AppRootSurfaces' @@ -130,6 +131,7 @@ function App(): React.JSX.Element { + {/* Electron drag hit-testing follows DOM order, ignoring z-index; render controls last to keep them clickable. */} diff --git a/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignIn.fixture.tsx b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignIn.fixture.tsx new file mode 100644 index 00000000000..e00d71bc497 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignIn.fixture.tsx @@ -0,0 +1,89 @@ +import type { HostAgentSignInReport } from '../../../../../../../shared/host-agent-sign-in-status' +import { defineFixture } from '../../../../../component-fixtures/component-fixture' +import type { HostAgentSignInView } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { ServerListRow } from '../../../host-rows/ServerListRow' +import { HostAgentSignInChipList } from './HostAgentSignInChips' +import { HostAgentSignInRows } from './HostAgentSignInDialog' + +const MIXED: HostAgentSignInReport = { + checkedAt: 1, + agents: [ + { agent: 'claude', state: 'signedIn', method: 'cliLogin' }, + { agent: 'codex', state: 'signedOut' } + ] +} +const SIGNED_OUT: HostAgentSignInReport = { + checkedAt: 1, + agents: [ + { agent: 'claude', state: 'signedOut' }, + { agent: 'codex', state: 'signedOut' } + ] +} + +function Row({ name, view }: { name: string; view: HostAgentSignInView }): React.JSX.Element { + return ( + {}} onRetry={() => {}} />} + meta={ws://10.0.0.4:6768 · v1.4.2} + status={{ label: 'Connected', tone: 'success' }} + /> + ) +} + +export const serverRowChips = defineFixture({ + width: 760, + render: () => ( +
+ + + + +
+ ) +}) + +function Panel(props: { + view: HostAgentSignInView + errors?: { codex?: string; claude?: string } +}): React.JSX.Element { + return ( +
+
Sign in agents
+

+ Each agent signs in on api-refactor VM, and the login stays there. Orca only passes along + the link and code. +

+ {}} + onRecheck={() => {}} + /> +
+ ) +} + +export const signInStep = defineFixture({ + width: 460, + render: () => +}) + +export const codexSignInFailed = defineFixture({ + width: 460, + render: () => ( + + ) +}) + +export const hostAsleep = defineFixture({ + width: 460, + render: () => +}) diff --git a/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInChips.tsx b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInChips.tsx new file mode 100644 index 00000000000..9ed83183c00 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInChips.tsx @@ -0,0 +1,107 @@ +import { AlertTriangle, Check } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { AgentIcon, getAgentLabel } from '@/lib/agent-catalog' +import { cn } from '@/lib/utils' +import type { HostAgentSignInView } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { refreshHostAgentSignInStatus } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { Tooltip, TooltipContent, TooltipTrigger } from '../../../../ui/tooltip' +import { openHostAgentSignInDialog } from './host-agent-sign-in-dialog-state' +import { useHostAgentSignInView } from './use-host-agent-sign-in-view' + +const CHIP_CLASS = + 'flex shrink-0 items-center gap-1 rounded border border-border bg-accent px-1.5 py-px text-3xs leading-4 text-muted-foreground hover:bg-accent/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring' + +/** One chip per installed agent; any chip opens the sign-in step. Nothing shows until the host answers. */ +export function HostAgentSignInChipList({ + view, + onOpen, + onRetry +}: { + view: HostAgentSignInView + onOpen: () => void + onRetry: () => void +}): React.JSX.Element | null { + const t = useTranslate() + if (view.phase === 'failed' && !view.report) { + return ( + + ) + } + const report = 'report' in view ? view.report : null + const agents = report?.agents.filter((entry) => entry.state !== 'notInstalled') ?? [] + if (agents.length === 0) { + return null + } + return ( + <> + {agents.map((entry) => { + const label = getAgentLabel(entry.agent) + const signedIn = entry.state === 'signedIn' + const tooltip = signedIn + ? entry.method === 'apiKey' + ? t('accounts.hostAgentSignIn.chipApiKeyTooltip', '{{agent}} uses an API key here.', { + agent: label + }) + : t('accounts.hostAgentSignIn.chipSignedInTooltip', '{{agent}} is signed in here.', { + agent: label + }) + : entry.state === 'signedOut' + ? t( + 'accounts.hostAgentSignIn.chipSignedOutTooltip', + '{{agent}} isn’t signed in here. Click to sign in.', + { agent: label } + ) + : t( + 'accounts.hostAgentSignIn.chipUnknownTooltip', + 'Couldn’t tell if {{agent}} is signed in here.', + { agent: label } + ) + return ( + + + + + + {tooltip} + + + ) + })} + + ) +} + +/** Sign-in chips for a paired host; asks only while it is reachable, so a sleeping VM stays asleep. */ +export function HostAgentSignInChips({ + environmentId, + hostLabel, + reachable +}: { + environmentId: string + hostLabel: string + reachable: boolean +}): React.JSX.Element | null { + const view = useHostAgentSignInView(environmentId, reachable) + return ( + openHostAgentSignInDialog({ environmentId, hostLabel })} + onRetry={() => void refreshHostAgentSignInStatus(environmentId, { force: true })} + /> + ) +} diff --git a/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInDialog.tsx b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInDialog.tsx new file mode 100644 index 00000000000..af19900f2b7 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/sign-in/host-agents/HostAgentSignInDialog.tsx @@ -0,0 +1,309 @@ +import { useState, useSyncExternalStore } from 'react' +import { Check, LogIn, RefreshCw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { useTranslate } from '@/i18n/use-translate' +import { AgentIcon, getAgentLabel } from '@/lib/agent-catalog' +import { cn } from '@/lib/utils' +import { + refreshHostAgentSignInStatus, + signInAgentOnHost, + type HostAgentSignInView +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { + cancelHostAccountSignIn, + runningHostAccountSignInOwner, + subscribeHostAccountSignIns +} from '@/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client' +import { CODEX_LOGIN_CANCELLED_MESSAGE } from '../../../../../../../shared/codex-auth-errors' +import { + HOST_AGENT_SIGN_IN_AGENTS, + type HostAgentSignInAgent, + type HostAgentSignInEntry +} from '../../../../../../../shared/host-agent-sign-in-status' +import { LoadingSpinner } from '../../../../LoadingSpinner' +import { HostAccountSignInPrompt } from '../HostAccountSignInPrompt' +import { + closeHostAgentSignInDialog, + readHostAgentSignInDialogTarget, + subscribeHostAgentSignInDialog, + type HostAgentSignInDialogTarget +} from './host-agent-sign-in-dialog-state' +import { useHostAgentSignInView } from './use-host-agent-sign-in-view' + +const CANCELLED_MESSAGES = new Set(['Claude sign-in was cancelled.', CODEX_LOGIN_CANCELLED_MESSAGE]) + +export type HostAgentSignInRowsProps = { + environmentId: string + hostLabel: string + view: HostAgentSignInView + /** The agent whose sign-in runs on this host, if any. */ + runningAgent: HostAgentSignInAgent | null + errors: Partial> + onSignIn: (agent: HostAgentSignInAgent) => void + onRecheck: () => void +} + +function StatusText({ entry }: { entry: HostAgentSignInEntry }): React.JSX.Element { + const t = useTranslate() + if (entry.state === 'signedIn') { + return ( + + + {entry.method === 'apiKey' + ? t('accounts.hostAgentSignIn.signedInApiKey', 'Signed in with an API key') + : t('accounts.hostAgentSignIn.signedIn', 'Signed in')} + + ) + } + return ( + + {entry.state === 'signedOut' + ? t('accounts.hostAgentSignIn.signedOut', 'Not signed in') + : entry.state === 'notInstalled' + ? t('accounts.hostAgentSignIn.notInstalled', 'Not installed on this host') + : t('accounts.hostAgentSignIn.unknown', 'Couldn’t check')} + + ) +} + +/** The agents' rows: status, one Sign in per agent, and the relayed prompt while it runs. */ +export function HostAgentSignInRows({ + environmentId, + hostLabel, + view, + runningAgent, + errors, + onSignIn, + onRecheck +}: HostAgentSignInRowsProps): React.JSX.Element { + const t = useTranslate() + if (view.phase === 'asleep') { + return ( +

+ {t( + 'accounts.hostAgentSignIn.asleep', + '{{host}} is asleep. Open one of its workspaces to wake it, then check again.', + { host: hostLabel } + )} +

+ ) + } + if (view.phase === 'unsupported') { + return ( +

+ {t( + 'accounts.hostAgentSignIn.unsupported', + 'Update Orca on {{host}} to sign in agents from here.', + { host: hostLabel } + )} +

+ ) + } + const report = 'report' in view ? view.report : null + if (!report) { + return view.phase === 'failed' ? ( +
+

+ {t('accounts.hostAgentSignIn.checkFailed', 'Couldn’t reach {{host}} to check agents.', { + host: hostLabel + })} +

+ +
+ ) : ( +

+ + {t('accounts.hostAgentSignIn.checking', 'Checking agents on {{host}}…', { + host: hostLabel + })} +

+ ) + } + const owner = { kind: 'environment', environmentId } as const + const entries = HOST_AGENT_SIGN_IN_AGENTS.map( + (agent) => + report.agents.find((entry) => entry.agent === agent) ?? { + agent, + state: 'unknown' as const + } + ) + return ( +
+ {entries.map((entry) => { + const label = getAgentLabel(entry.agent) + const error = errors[entry.agent] + const running = runningAgent === entry.agent + const canSignIn = entry.state === 'signedOut' || entry.state === 'unknown' + return ( +
+
+ +
+
{label}
+ +
+ {canSignIn && !running ? ( + + ) : null} +
+ {running ? ( + + ) : null} + {error && !running ? ( +
+

{error}

+ {entry.agent === 'codex' ? ( +

+ {t( + 'accounts.hostAgentSignIn.codexDeviceCodeHint', + 'Codex signs in with a device code. If it fails, turn on device code login in ChatGPT under Settings → Security, then try again.' + )} +

+ ) : null} +
+ ) : null} +
+ ) + })} +
+ ) +} + +function useRunningAgent(environmentId: string): HostAgentSignInAgent | null { + const read = (): HostAgentSignInAgent | null => { + for (const agent of HOST_AGENT_SIGN_IN_AGENTS) { + const owner = runningHostAccountSignInOwner(agent) + if (owner?.environmentId === environmentId) { + return agent + } + } + return null + } + return useSyncExternalStore(subscribeHostAccountSignIns, read, read) +} + +function SignInDialogBody({ target }: { target: HostAgentSignInDialogTarget }): React.JSX.Element { + const t = useTranslate() + const { environmentId, hostLabel } = target + const view = useHostAgentSignInView(environmentId, true) + const runningAgent = useRunningAgent(environmentId) + const [errors, setErrors] = useState>>({}) + const checking = view.phase === 'checking' + const signIn = (agent: HostAgentSignInAgent): void => { + setErrors((current) => ({ ...current, [agent]: undefined })) + void signInAgentOnHost(environmentId, agent).catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error) + if (!CANCELLED_MESSAGES.has(message)) { + setErrors((current) => ({ ...current, [agent]: message })) + } + }) + } + const recheck = (): void => void refreshHostAgentSignInStatus(environmentId, { force: true }) + return ( + <> + + {t('accounts.hostAgentSignIn.title', 'Sign in agents')} + + {t( + 'accounts.hostAgentSignIn.description', + 'Each agent signs in on {{host}}, and the login stays there. Orca only passes along the link and code.', + { host: hostLabel } + )} + + + +

+ {t( + 'accounts.hostAgentSignIn.apiKeyNote', + 'Using an API key instead? Set ANTHROPIC_API_KEY or OPENAI_API_KEY in that host’s shell profile.' + )} +

+ + + + + + ) +} + +/** Closing mid-sign-in cancels it, so no login is left waiting on the host for a code. */ +function closeAndCancel(target: HostAgentSignInDialogTarget): void { + const owner = { kind: 'environment', environmentId: target.environmentId } as const + for (const agent of HOST_AGENT_SIGN_IN_AGENTS) { + if (runningHostAccountSignInOwner(agent)?.environmentId === target.environmentId) { + void cancelHostAccountSignIn(owner, agent).catch(() => {}) + } + } + closeHostAgentSignInDialog() +} + +/** App-wide host for the "Sign in agents" step. */ +export default function HostAgentSignInDialog(): React.JSX.Element | null { + const target = useSyncExternalStore( + subscribeHostAgentSignInDialog, + readHostAgentSignInDialogTarget, + readHostAgentSignInDialogTarget + ) + if (!target) { + return null + } + return ( + { + if (!open) { + closeAndCancel(target) + } + }} + > + + + + + ) +} diff --git a/src/renderer/src/components/settings/accounts/sign-in/host-agents/host-agent-sign-in-dialog-state.ts b/src/renderer/src/components/settings/accounts/sign-in/host-agents/host-agent-sign-in-dialog-state.ts new file mode 100644 index 00000000000..c048b2206b5 --- /dev/null +++ b/src/renderer/src/components/settings/accounts/sign-in/host-agents/host-agent-sign-in-dialog-state.ts @@ -0,0 +1,28 @@ +export type HostAgentSignInDialogTarget = { environmentId: string; hostLabel: string } + +let target: HostAgentSignInDialogTarget | null = null +const listeners = new Set<() => void>() + +function publish(next: HostAgentSignInDialogTarget | null): void { + target = next + for (const listener of listeners) { + listener() + } +} + +export function openHostAgentSignInDialog(next: HostAgentSignInDialogTarget): void { + publish(next) +} + +export function closeHostAgentSignInDialog(): void { + publish(null) +} + +export function readHostAgentSignInDialogTarget(): HostAgentSignInDialogTarget | null { + return target +} + +export function subscribeHostAgentSignInDialog(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} diff --git a/src/renderer/src/components/settings/accounts/sign-in/host-agents/use-host-agent-sign-in-view.ts b/src/renderer/src/components/settings/accounts/sign-in/host-agents/use-host-agent-sign-in-view.ts new file mode 100644 index 00000000000..a1d8b7b59de --- /dev/null +++ b/src/renderer/src/components/settings/accounts/sign-in/host-agents/use-host-agent-sign-in-view.ts @@ -0,0 +1,24 @@ +import { useCallback, useEffect, useSyncExternalStore } from 'react' +import { + ensureHostAgentSignInStatus, + readHostAgentSignInStatus, + subscribeHostAgentSignInStatus, + type HostAgentSignInView +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' + +const IDLE: HostAgentSignInView = { phase: 'idle' } + +/** The host's agent sign-in, asked once per TTL while `enabled` (the host is reachable and awake). */ +export function useHostAgentSignInView( + environmentId: string, + enabled: boolean +): HostAgentSignInView { + const read = useCallback(() => readHostAgentSignInStatus(environmentId), [environmentId]) + const view = useSyncExternalStore(subscribeHostAgentSignInStatus, read, read) + useEffect(() => { + if (enabled) { + ensureHostAgentSignInStatus(environmentId) + } + }, [enabled, environmentId]) + return enabled ? view : IDLE +} diff --git a/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row.tsx b/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row.tsx index d636925097d..e9328278578 100644 --- a/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row.tsx +++ b/src/renderer/src/components/settings/runtime-environments/server-rows/runtime-server-row.tsx @@ -31,6 +31,7 @@ import { ServerRowDetailsToggle, type ServerRowStatus } from '../../host-rows/ServerListRow' +import { HostAgentSignInChips } from '../../accounts/sign-in/host-agents/HostAgentSignInChips' import { RuntimeSshAccessControl } from '../ssh-access/RuntimeSshAccessControl' import { RuntimeSshAccessDialog } from '../ssh-access/runtime-ssh-access-dialog' import { @@ -298,16 +299,15 @@ export function RuntimeServerRow({ ) : null + const rowName = deployment + ? (sshTargets.find((target) => target.id === deployment.sshTargetId)?.label ?? environment.name) + : row.title + return ( <> target.id === deployment.sshTargetId)?.label ?? - environment.name) - : row.title - } + name={rowName} descriptor={row.hostDescriptorText} chips={ <> @@ -321,6 +321,11 @@ export function RuntimeServerRow({ {t('auto.components.settings.serverList.sshTunnelChip', 'SSH tunnel')} ) : null} + } meta={meta} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 0dd9cc0f4bb..a35fb12dbec 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -22599,7 +22599,36 @@ "failed": "Sign-in failed. Try again." } }, - "remoteScopeAccountsAddHere": "Showing accounts managed by {{value0}}. New accounts sign in there; you finish in this device’s browser." + "remoteScopeAccountsAddHere": "Showing accounts managed by {{value0}}. New accounts sign in there; you finish in this device’s browser.", + "hostAgentSignIn": { + "chipCheckFailed": "Couldn’t check agents · Retry", + "chipApiKeyTooltip": "{{agent}} uses an API key here.", + "chipSignedInTooltip": "{{agent}} is signed in here.", + "chipSignedOutTooltip": "{{agent}} isn’t signed in here. Click to sign in.", + "chipUnknownTooltip": "Couldn’t tell if {{agent}} is signed in here.", + "chipSignIn": "Sign in", + "chipUnknown": "Unknown", + "signedInApiKey": "Signed in with an API key", + "signedIn": "Signed in", + "signedOut": "Not signed in", + "notInstalled": "Not installed on this host", + "unknown": "Couldn’t check", + "asleep": "{{host}} is asleep. Open one of its workspaces to wake it, then check again.", + "unsupported": "Update Orca on {{host}} to sign in agents from here.", + "checkFailed": "Couldn’t reach {{host}} to check agents.", + "retry": "Try again", + "checking": "Checking agents on {{host}}…", + "signIn": "Sign in", + "codexDeviceCodeHint": "Codex signs in with a device code. If it fails, turn on device code login in ChatGPT under Settings → Security, then try again.", + "title": "Sign in agents", + "description": "Each agent runs its own sign-in on {{host}}. Your login stays on {{host}}; Orca only passes along the link and code.", + "apiKeyNote": "Using an API key instead? Set ANTHROPIC_API_KEY or OPENAI_API_KEY in that host’s shell profile.", + "recheck": "Check again", + "done": "Done", + "toastTitle": "Sign in agents on {{host}}", + "toastDescriptionOne": "{{agent}} isn’t signed in on this VM yet.", + "toastDescriptionMany": "{{agents}} aren’t signed in on this VM yet." + } }, "fileSearch": { "failed": "Search failed. Try again.", diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 0d731d8efd2..899870d675f 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -6,6 +6,7 @@ import { getProjectIdentityKey } from '../../../shared/project-host-setup-projec import type { Repo } from '../../../shared/repo-types' import { translate } from '@/i18n/i18n' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' +import { offerAgentSignInForNewVm } from '@/lib/vm-agent-sign-in-prompt' import { appendProvisioningLog, appendProvisioningWarnings @@ -154,10 +155,14 @@ export async function attachEphemeralVmRuntimeToWorkspace( runtimeId: request.ephemeralVmRuntimeId, workspaceId }) - if (request.ephemeralVmRuntimeEnvironmentId) { - void useAppStore - .getState() - .refreshRuntimeEnvironmentStatus(request.ephemeralVmRuntimeEnvironmentId) + const environmentId = request.ephemeralVmRuntimeEnvironmentId + if (environmentId) { + const store = useAppStore.getState() + void store.refreshRuntimeEnvironmentStatus(environmentId) + const hostLabel = + store.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name ?? + request.name + void offerAgentSignInForNewVm(environmentId, hostLabel).catch(() => {}) } } catch (error) { console.error('Failed to attach ephemeral VM runtime to workspace:', error) diff --git a/src/renderer/src/lib/vm-agent-sign-in-prompt.ts b/src/renderer/src/lib/vm-agent-sign-in-prompt.ts new file mode 100644 index 00000000000..151205e6e96 --- /dev/null +++ b/src/renderer/src/lib/vm-agent-sign-in-prompt.ts @@ -0,0 +1,54 @@ +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { getAgentLabel } from '@/lib/agent-catalog' +import { + readHostAgentSignInStatus, + refreshHostAgentSignInStatus +} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client' +import { openHostAgentSignInDialog } from '@/components/settings/accounts/sign-in/host-agents/host-agent-sign-in-dialog-state' + +/** After a VM workspace is created, offer the "Sign in agents" step when an agent there is signed out. */ +export async function offerAgentSignInForNewVm( + environmentId: string, + hostLabel: string +): Promise { + await refreshHostAgentSignInStatus(environmentId, { force: true }) + const view = readHostAgentSignInStatus(environmentId) + if (view.phase !== 'ready') { + return + } + const signedOut = view.report.agents.filter((entry) => entry.state === 'signedOut') + if (signedOut.length === 0) { + return + } + const agents = signedOut.map((entry) => getAgentLabel(entry.agent)).join(', ') + const toastId = `vm-agent-sign-in:${environmentId}` + toast( + translate('accounts.hostAgentSignIn.toastTitle', 'Sign in agents on {{host}}', { + host: hostLabel + }), + { + id: toastId, + description: + signedOut.length === 1 + ? translate( + 'accounts.hostAgentSignIn.toastDescriptionOne', + '{{agent}} isn’t signed in on this VM yet.', + { agent: agents } + ) + : translate( + 'accounts.hostAgentSignIn.toastDescriptionMany', + '{{agents}} aren’t signed in on this VM yet.', + { agents } + ), + duration: 20_000, + action: { + label: translate('accounts.hostAgentSignIn.signIn', 'Sign in'), + onClick: () => { + toast.dismiss(toastId) + openHostAgentSignInDialog({ environmentId, hostLabel }) + } + } + } + ) +} diff --git a/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts new file mode 100644 index 00000000000..6090e920c44 --- /dev/null +++ b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts @@ -0,0 +1,89 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE } from '../../../../../shared/remote-runtime/recipe-vm-wake' + +const mocks = vi.hoisted(() => ({ + supported: true, + call: vi.fn(), + addClaude: vi.fn(), + addCodex: vi.fn(), + selectClaude: vi.fn(), + selectCodex: vi.fn() +})) + +vi.mock('../../rpc/compatibility/runtime-capability-proof', () => ({ + runtimeEnvironmentSupportsCapability: vi.fn(async () => mocks.supported) +})) +vi.mock('../../rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: mocks.call })) +vi.mock('./runtime-host-account-sign-in-client', () => ({ + addClaudeAccountOnHost: mocks.addClaude, + addCodexAccountOnHost: mocks.addCodex +})) +vi.mock('../observations/runtime-provider-accounts-client', () => ({ + selectClaudeProviderAccount: mocks.selectClaude, + selectCodexProviderAccount: mocks.selectCodex +})) + +import { + _resetHostAgentSignInStatusForTest, + readHostAgentSignInStatus, + refreshHostAgentSignInStatus, + signInAgentOnHost +} from './host-agent-sign-in-status-client' + +const REPORT = { checkedAt: 1, agents: [{ agent: 'claude', state: 'signedOut' }] } + +beforeEach(() => { + _resetHostAgentSignInStatusForTest() + vi.clearAllMocks() + mocks.supported = true + mocks.call.mockResolvedValue(REPORT) +}) + +describe('host agent sign-in status client', () => { + it('shows a sleeping VM as asleep, not as a failed check', async () => { + mocks.call.mockRejectedValue( + Object.assign(new Error('asleep'), { code: RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE }) + ) + await refreshHostAgentSignInStatus('vm') + expect(readHostAgentSignInStatus('vm')).toEqual({ phase: 'asleep' }) + }) + + it('shows nothing for a host whose Orca predates the check', async () => { + mocks.supported = false + await refreshHostAgentSignInStatus('old') + expect(readHostAgentSignInStatus('old')).toEqual({ phase: 'unsupported' }) + expect(mocks.call).not.toHaveBeenCalled() + }) + + it('makes a new sign-in the host account only when none was chosen', async () => { + mocks.addClaude.mockResolvedValue({ + accounts: [ + { id: 'old', createdAt: 1 }, + { id: 'new', createdAt: 2 } + ], + activeAccountId: null, + activeAccountIdsByRuntime: { host: null, wsl: {} } + }) + await signInAgentOnHost('vm', 'claude') + expect(mocks.selectClaude).toHaveBeenCalledWith( + { kind: 'environment', environmentId: 'vm' }, + { accountId: 'new', runtime: 'host' } + ) + + mocks.addCodex.mockResolvedValue({ + accounts: [ + { id: 'chosen', createdAt: 1 }, + { id: 'new', createdAt: 2 } + ], + activeAccountId: 'chosen' + }) + await signInAgentOnHost('vm', 'codex') + expect(mocks.selectCodex).not.toHaveBeenCalled() + expect(mocks.call).toHaveBeenLastCalledWith( + { kind: 'environment', environmentId: 'vm' }, + 'accounts.agentSignInStatus', + { force: true }, + expect.anything() + ) + }) +}) 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..958f904a842 --- /dev/null +++ b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts @@ -0,0 +1,188 @@ +import type { + HostAgentSignInAgent, + HostAgentSignInReport +} from '../../../../../shared/host-agent-sign-in-status' +import { HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY } from '../../../../../shared/account-runtime-capabilities' +import { RECIPE_VM_REFUSAL_CODES } from '../../../../../shared/remote-runtime/recipe-vm-wake' +import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call' +import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof' +import { + selectClaudeProviderAccount, + selectCodexProviderAccount +} from '../observations/runtime-provider-accounts-client' +import { + addClaudeAccountOnHost, + addCodexAccountOnHost +} from './runtime-host-account-sign-in-client' + +export type HostAgentSignInView = + | { phase: 'idle' } + | { phase: 'checking'; report: HostAgentSignInReport | null } + | { phase: 'ready'; report: HostAgentSignInReport } + /** The host's Orca predates the check; show nothing rather than a guess. */ + | { phase: 'unsupported' } + /** A suspended VM: Orca does not wake it to ask. */ + | { phase: 'asleep' } + | { phase: 'failed'; report: HostAgentSignInReport | null } + +// Why: sign-in rarely changes on its own; views re-ask only after this or an explicit recheck. +const VIEW_TTL_MS = 5 * 60_000 +const CALL_TIMEOUT_MS = 30_000 +const RECIPE_VM_REFUSALS: ReadonlySet = new Set(RECIPE_VM_REFUSAL_CODES) + +type Entry = { view: HostAgentSignInView; settledAt: number; pending: Promise | null } + +const IDLE: HostAgentSignInView = { phase: 'idle' } +const entries = new Map() +const listeners = new Set<() => void>() + +function notify(): void { + for (const listener of listeners) { + listener() + } +} + +function setView(environmentId: string, view: HostAgentSignInView, settled: boolean): void { + const entry = entries.get(environmentId) + entries.set(environmentId, { + view, + settledAt: settled ? Date.now() : (entry?.settledAt ?? 0), + pending: entry?.pending ?? null + }) + notify() +} + +function lastReport(environmentId: string): HostAgentSignInReport | null { + const view = entries.get(environmentId)?.view + return view && 'report' in view ? view.report : null +} + +function errorCode(error: unknown): string | undefined { + const code = typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined + return typeof code === 'string' ? code : undefined +} + +async function fetchView(environmentId: string, force: boolean): Promise { + try { + if ( + !(await runtimeEnvironmentSupportsCapability( + environmentId, + HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY + )) + ) { + return { phase: 'unsupported' } + } + const report = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'accounts.agentSignInStatus', + force ? { force: true } : {}, + { timeoutMs: CALL_TIMEOUT_MS } + ) + return { phase: 'ready', report } + } catch (error) { + const code = errorCode(error) + if (code && RECIPE_VM_REFUSALS.has(code)) { + return { phase: 'asleep' } + } + if (code === 'method_not_found') { + return { phase: 'unsupported' } + } + return { phase: 'failed', report: lastReport(environmentId) } + } +} + +export function readHostAgentSignInStatus(environmentId: string): HostAgentSignInView { + return entries.get(environmentId)?.view ?? IDLE +} + +export function subscribeHostAgentSignInStatus(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +/** Asks the host again; concurrent callers share one request. `force` skips the host's cache. */ +export function refreshHostAgentSignInStatus( + environmentId: string, + options: { force?: boolean } = {} +): Promise { + const running = entries.get(environmentId)?.pending + if (running) { + return running + } + setView(environmentId, { phase: 'checking', report: lastReport(environmentId) }, false) + const pending = fetchView(environmentId, options.force === true).then((view) => { + setView(environmentId, view, true) + const entry = entries.get(environmentId) + if (entry) { + entry.pending = null + } + }) + const entry = entries.get(environmentId) + if (entry) { + entry.pending = pending + } + return pending +} + +/** Checks once per TTL for a reachable host; callers gate on reachability so a sleeping VM is never asked. */ +export function ensureHostAgentSignInStatus(environmentId: string): void { + const entry = entries.get(environmentId) + if (entry?.pending) { + return + } + const stale = + !entry || + entry.view.phase === 'idle' || + // A woken VM must not keep showing asleep until the TTL passes. + entry.view.phase === 'asleep' || + Date.now() - entry.settledAt >= VIEW_TTL_MS + if (stale) { + void refreshHostAgentSignInStatus(environmentId) + } +} + +type HostAccountsState = { + accounts: { id: string; createdAt: number; managedAuthRuntime?: 'host' | 'wsl' }[] + activeAccountId: string | null + activeAccountIdsByRuntime?: { host: string | null } +} + +function newestUnselectedHostAccount(state: HostAccountsState): string | null { + if ((state.activeAccountIdsByRuntime?.host ?? state.activeAccountId) !== null) { + return null + } + const hostAccounts = state.accounts.filter( + (account) => (account.managedAuthRuntime ?? 'host') === 'host' + ) + hostAccounts.sort((a, b) => b.createdAt - a.createdAt) + return hostAccounts[0]?.id ?? null +} + +/** Runs the agent's own login on the host (tokens stay there), then makes it the host's account + * when none was chosen, so the next agent started there is signed in. */ +export async function signInAgentOnHost( + environmentId: string, + agent: HostAgentSignInAgent +): Promise { + const owner = { kind: 'environment', environmentId } as const + try { + if (agent === 'claude') { + const accountId = newestUnselectedHostAccount(await addClaudeAccountOnHost(owner)) + if (accountId) { + await selectClaudeProviderAccount(owner, { accountId, runtime: 'host' }) + } + } else { + const accountId = newestUnselectedHostAccount(await addCodexAccountOnHost(owner)) + if (accountId) { + await selectCodexProviderAccount(owner, { accountId, runtime: 'host' }) + } + } + } finally { + await refreshHostAgentSignInStatus(environmentId, { force: true }) + } +} + +export function _resetHostAgentSignInStatusForTest(): void { + entries.clear() + listeners.clear() +} diff --git a/src/shared/account-runtime-capabilities.ts b/src/shared/account-runtime-capabilities.ts index ee423cae7cc..a283f999197 100644 --- a/src/shared/account-runtime-capabilities.ts +++ b/src/shared/account-runtime-capabilities.ts @@ -13,6 +13,9 @@ 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 agent sign-in check, so their rows show no sign-in chips. +export const HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY = + 'accounts.agent-sign-in-status.v1' as const export const ACCOUNT_RUNTIME_CAPABILITIES = [ ACCOUNT_IMPORT_RUNTIME_CAPABILITY, @@ -23,5 +26,6 @@ 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 ] as const 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..de253302773 100644 --- a/src/shared/rpc-contract/accounts-params.ts +++ b/src/shared/rpc-contract/accounts-params.ts @@ -113,6 +113,8 @@ export const FinishClaudeSignInParams = z export const HostAccountSignInStartParams = z.object({ provider: z.enum(['claude', 'codex']) }) +export const HostAgentSignInStatusParams = z.object({ force: z.boolean().optional() }) + export const HostAccountSignInWaitParams = z.object({ flowId: z.string().min(1).max(64), afterRevision: z.number().int().nonnegative().default(0) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 7a3d4daf21b..280af13c295 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -60,6 +60,7 @@ import { HostAccountSignInFlowParams, HostAccountSignInStartParams, HostAccountSignInWaitParams, + HostAgentSignInStatusParams, ListAccountsParams, RemoveAccountParams, RemoveDataAccountParams, @@ -770,6 +771,7 @@ export const RPC_PARAMS_BY_METHOD = { 'accounts.addClaudeFromConfigDir': AddClaudeFromConfigDirParams, 'accounts.addCodexFromHome': AddCodexFromHomeParams, 'accounts.addDataFromHome': AddDataAccountParams, + 'accounts.agentSignInStatus': HostAgentSignInStatusParams, 'accounts.antigravityAddCurrent': AntigravityAccountTargetParams, 'accounts.antigravityChatAuthApply': AntigravityChatAuthConfigSchema, 'accounts.antigravityChatAuthGet': null,