feat(remote): show agent sign-in on remote hosts and offer a Sign in agents step after VM create

This commit is contained in:
Neil
2026-11-08 19:50:34 -08:00
parent 72e5893944
commit 9c6909eada
22 changed files with 1386 additions and 36 deletions
@@ -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<string, unknown>
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
}
+8 -24
View File
@@ -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
}
@@ -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<ReturnType<HostAgentSignInStatusDeps['readAccounts']>> {
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<HostAgentSignInStatusDeps['runStatus']>()
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' }
])
})
})
@@ -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<LocalCommandProbe>
runStatus: (binary: string, args: string[]) => Promise<AgentStatusCommandResult>
/** This host's Orca account roster; null where it has none. */
readAccounts: () => {
claude: ClaudeRateLimitAccountsState
codex: CodexRateLimitAccountsState
} | null
now: () => number
}
type Accounts = NonNullable<ReturnType<HostAgentSignInStatusDeps['readAccounts']>>
const STATUS_ARGS: Record<HostAgentSignInAgent, string[]> = {
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<HostAgentSignInReport> | null = null
constructor(private readonly deps: HostAgentSignInStatusDeps) {}
read(force = false): Promise<HostAgentSignInReport> {
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<HostAgentSignInReport> {
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<HostAgentSignInEntry> {
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<string, unknown>)[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<AgentStatusCommandResult> {
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
})
}
@@ -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',
@@ -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<OrcaRuntimeService, HostAgentSignInStatusChecker>()
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)
})
+2
View File
@@ -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 {
<WorktreeBaseFallbackDialog />
<AgentWorkspaceTrustDecisionDialog />
<ClaudeAccountSwitchDialog />
<HostAgentSignInDialog />
<PinnedTabCloseDialog />
<RunningTerminalCloseDialog />
{/* Electron drag hit-testing follows DOM order, ignoring z-index; render controls last to keep them clickable. */}
@@ -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 (
<ServerListRow
sectionId={name}
name={name}
chips={<HostAgentSignInChipList view={view} onOpen={() => {}} onRetry={() => {}} />}
meta={<span>ws://10.0.0.4:6768 · v1.4.2</span>}
status={{ label: 'Connected', tone: 'success' }}
/>
)
}
export const serverRowChips = defineFixture({
width: 760,
render: () => (
<div className="divide-y divide-border rounded-lg border border-border bg-card">
<Row name="api-refactor VM" view={{ phase: 'ready', report: MIXED }} />
<Row name="build-box" view={{ phase: 'ready', report: SIGNED_OUT }} />
<Row name="staging VM" view={{ phase: 'failed', report: null }} />
<Row name="Older server" view={{ phase: 'unsupported' }} />
</div>
)
})
function Panel(props: {
view: HostAgentSignInView
errors?: { codex?: string; claude?: string }
}): React.JSX.Element {
return (
<div className="space-y-3 rounded-lg border border-border bg-background p-5">
<div className="text-lg font-semibold">Sign in agents</div>
<p className="text-sm text-muted-foreground">
Each agent signs in on api-refactor VM, and the login stays there. Orca only passes along
the link and code.
</p>
<HostAgentSignInRows
environmentId="vm"
hostLabel="api-refactor VM"
view={props.view}
runningAgent={null}
errors={props.errors ?? {}}
onSignIn={() => {}}
onRecheck={() => {}}
/>
</div>
)
}
export const signInStep = defineFixture({
width: 460,
render: () => <Panel view={{ phase: 'ready', report: MIXED }} />
})
export const codexSignInFailed = defineFixture({
width: 460,
render: () => (
<Panel
view={{ phase: 'ready', report: SIGNED_OUT }}
errors={{ codex: 'Codex could not start device code sign-in.' }}
/>
)
})
export const hostAsleep = defineFixture({
width: 460,
render: () => <Panel view={{ phase: 'asleep' }} />
})
@@ -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 (
<button type="button" className={CHIP_CLASS} onClick={onRetry}>
<AlertTriangle className="size-2.5 text-status-warning" />
{t('accounts.hostAgentSignIn.chipCheckFailed', 'Couldn’t check agents · Retry')}
</button>
)
}
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 key={entry.agent}>
<TooltipTrigger asChild>
<button type="button" className={CHIP_CLASS} onClick={onOpen}>
<AgentIcon agent={entry.agent} size={10} />
<span>{label}</span>
{signedIn ? (
<Check className="size-2.5" aria-hidden />
) : (
<span className={cn(entry.state === 'signedOut' && 'text-status-warning')}>
{entry.state === 'signedOut'
? t('accounts.hostAgentSignIn.chipSignIn', 'Sign in')
: t('accounts.hostAgentSignIn.chipUnknown', 'Unknown')}
</span>
)}
</button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
{tooltip}
</TooltipContent>
</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 (
<HostAgentSignInChipList
view={view}
onOpen={() => openHostAgentSignInDialog({ environmentId, hostLabel })}
onRetry={() => void refreshHostAgentSignInStatus(environmentId, { force: true })}
/>
)
}
@@ -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<Record<HostAgentSignInAgent, string>>
onSignIn: (agent: HostAgentSignInAgent) => void
onRecheck: () => void
}
function StatusText({ entry }: { entry: HostAgentSignInEntry }): React.JSX.Element {
const t = useTranslate()
if (entry.state === 'signedIn') {
return (
<span className="flex items-center gap-1 text-xs text-muted-foreground">
<Check className="size-3" aria-hidden />
{entry.method === 'apiKey'
? t('accounts.hostAgentSignIn.signedInApiKey', 'Signed in with an API key')
: t('accounts.hostAgentSignIn.signedIn', 'Signed in')}
</span>
)
}
return (
<span
className={cn(
'text-xs',
entry.state === 'signedOut' ? 'text-status-warning' : 'text-muted-foreground'
)}
>
{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')}
</span>
)
}
/** 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 (
<p className="text-sm text-muted-foreground">
{t(
'accounts.hostAgentSignIn.asleep',
'{{host}} is asleep. Open one of its workspaces to wake it, then check again.',
{ host: hostLabel }
)}
</p>
)
}
if (view.phase === 'unsupported') {
return (
<p className="text-sm text-muted-foreground">
{t(
'accounts.hostAgentSignIn.unsupported',
'Update Orca on {{host}} to sign in agents from here.',
{ host: hostLabel }
)}
</p>
)
}
const report = 'report' in view ? view.report : null
if (!report) {
return view.phase === 'failed' ? (
<div className="flex items-center justify-between gap-3">
<p role="alert" className="text-sm text-destructive">
{t('accounts.hostAgentSignIn.checkFailed', 'Couldn’t reach {{host}} to check agents.', {
host: hostLabel
})}
</p>
<Button type="button" variant="outline" size="xs" onClick={onRecheck}>
{t('accounts.hostAgentSignIn.retry', 'Try again')}
</Button>
</div>
) : (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<LoadingSpinner className="size-3" />
{t('accounts.hostAgentSignIn.checking', 'Checking agents on {{host}}…', {
host: hostLabel
})}
</p>
)
}
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 (
<div className="divide-y divide-border rounded-md border border-border">
{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 (
<div key={entry.agent} className="space-y-2 px-3 py-2.5">
<div className="flex items-center gap-3">
<AgentIcon agent={entry.agent} size={16} />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium">{label}</div>
<StatusText entry={entry} />
</div>
{canSignIn && !running ? (
<Button
type="button"
variant={entry.state === 'signedOut' ? 'default' : 'outline'}
size="xs"
disabled={runningAgent !== null}
onClick={() => onSignIn(entry.agent)}
>
<LogIn />
{error
? t('accounts.hostAgentSignIn.retry', 'Try again')
: t('accounts.hostAgentSignIn.signIn', 'Sign in')}
</Button>
) : null}
</div>
{running ? (
<HostAccountSignInPrompt owner={owner} provider={entry.agent} hostLabel={hostLabel} />
) : null}
{error && !running ? (
<div role="alert" className="space-y-1 text-xs">
<p className="text-destructive">{error}</p>
{entry.agent === 'codex' ? (
<p className="text-muted-foreground">
{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.'
)}
</p>
) : null}
</div>
) : null}
</div>
)
})}
</div>
)
}
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<Partial<Record<HostAgentSignInAgent, string>>>({})
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 (
<>
<DialogHeader>
<DialogTitle>{t('accounts.hostAgentSignIn.title', 'Sign in agents')}</DialogTitle>
<DialogDescription>
{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 }
)}
</DialogDescription>
</DialogHeader>
<HostAgentSignInRows
environmentId={environmentId}
hostLabel={hostLabel}
view={view}
runningAgent={runningAgent}
errors={errors}
onSignIn={signIn}
onRecheck={recheck}
/>
<p className="text-xs text-muted-foreground">
{t(
'accounts.hostAgentSignIn.apiKeyNote',
'Using an API key instead? Set ANTHROPIC_API_KEY or OPENAI_API_KEY in that host’s shell profile.'
)}
</p>
<DialogFooter>
<Button
type="button"
variant="ghost"
size="sm"
disabled={checking || runningAgent !== null}
onClick={recheck}
>
{checking ? <LoadingSpinner className="size-3" /> : <RefreshCw />}
{t('accounts.hostAgentSignIn.recheck', 'Check again')}
</Button>
<Button type="button" size="sm" onClick={() => closeAndCancel(target)}>
{t('accounts.hostAgentSignIn.done', 'Done')}
</Button>
</DialogFooter>
</>
)
}
/** 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 (
<Dialog
open
onOpenChange={(open) => {
if (!open) {
closeAndCancel(target)
}
}}
>
<DialogContent className="max-w-md">
<SignInDialogBody key={target.environmentId} target={target} />
</DialogContent>
</Dialog>
)
}
@@ -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)
}
@@ -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
}
@@ -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 (
<>
<ServerListRow
sectionId={environment.id}
name={
deployment
? (sshTargets.find((target) => 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')}
</ServerRowChip>
) : null}
<HostAgentSignInChips
environmentId={environment.id}
hostLabel={rowName}
reachable={row.isReachable}
/>
</>
}
meta={meta}
+30 -1
View File
@@ -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.",
@@ -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)
@@ -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<void> {
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 })
}
}
}
)
}
@@ -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()
)
})
})
@@ -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<string> = new Set(RECIPE_VM_REFUSAL_CODES)
type Entry = { view: HostAgentSignInView; settledAt: number; pending: Promise<void> | null }
const IDLE: HostAgentSignInView = { phase: 'idle' }
const entries = new Map<string, Entry>()
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<HostAgentSignInView> {
try {
if (
!(await runtimeEnvironmentSupportsCapability(
environmentId,
HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY
))
) {
return { phase: 'unsupported' }
}
const report = await callRuntimeRpc<HostAgentSignInReport>(
{ 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<void> {
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<void> {
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()
}
+5 -1
View File
@@ -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
+21
View File
@@ -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[]
}
@@ -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)
+2
View File
@@ -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,