feat(remote): sign agents in from the VM build sheet, warn on a different account, pre-check hosts on connect

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Neil
2026-11-09 06:02:02 -08:00
co-authored by Claude
parent 8a7aad4e42
commit a9accd871c
28 changed files with 1297 additions and 96 deletions
@@ -97,5 +97,8 @@ export const deviceCode = shot(
{ agent: 'codex' }
)
)
export const signedOtherAccount = shot(
gate({ step: 'signed', email: 'nw@personal.dev', expectedEmail: 'nw@stably.ai' })
)
export const olderHost = shot(gate({ step: 'need' }, { codeOnly: true }))
export const noPrompt = shot(gate({ step: 'need' }, { prompt: null, hostLabel: 'feature-x' }))
@@ -1,4 +1,4 @@
import { CircleAlert, Copy, ExternalLink } from 'lucide-react'
import { CircleAlert, Copy, ExternalLink, TriangleAlert } from 'lucide-react'
import { useTranslate } from '@/i18n/use-translate'
import { AgentIcon } from '@/lib/agent-catalog'
import { Button } from '@/components/ui/button'
@@ -14,7 +14,8 @@ export type AgentSignInCardActions = {
openLink: (url: string) => void
copyText: (text: string) => void
cancel: () => void
skip: () => void
/** Absent where nothing waits to start, e.g. the VM build sheet. */
skip?: () => void
}
const AGENT_NAME = { claude: 'Claude', codex: 'Codex' } as const
@@ -37,10 +38,28 @@ function QueuedPrompt({
)
}
function ErrorLine({ title, detail }: { title: string; detail: string }): React.JSX.Element {
export function ErrorLine({
title,
detail,
tone = 'error'
}: {
title: string
detail: string
tone?: 'error' | 'warning'
}): React.JSX.Element {
const Icon = tone === 'warning' ? TriangleAlert : CircleAlert
return (
<div role="alert" className="flex items-start gap-2 text-xs leading-5">
<CircleAlert className="mt-0.5 size-3.5 shrink-0 text-destructive" />
<div
role={tone === 'warning' ? 'status' : 'alert'}
className="flex items-start gap-2 text-xs leading-5"
>
<Icon
className={
tone === 'warning'
? 'mt-0.5 size-3.5 shrink-0 text-status-warning'
: 'mt-0.5 size-3.5 shrink-0 text-destructive'
}
/>
<p className="min-w-0">
<span className="font-medium text-foreground">{title}</span>{' '}
<span className="text-muted-foreground">{detail}</span>
@@ -137,6 +156,18 @@ export function AgentSignInCard({
{view.step === 'error' ? <AgentSignInError gate={gate} view={view} /> : null}
{view.step === 'signed' && view.expectedEmail ? (
<ErrorLine
tone="warning"
title={t('agentSignIn.otherAccount', 'Not your usual account.')}
detail={t(
'agentSignIn.otherAccountDetail',
'This computer uses {{email}} for {{agent}}.',
{ email: view.expectedEmail, agent: name }
)}
/>
) : null}
{view.step === 'paste' ? (
<>
<div className="flex items-center gap-2">
@@ -265,7 +296,8 @@ export function AgentSignInCard({
</div>
)}
{view.step === 'need' || view.step === 'starting' || view.step === 'error' ? (
{(view.step === 'need' || view.step === 'starting' || view.step === 'error') &&
(!gate.codeOnly || actions.skip) ? (
<div className="-mx-4 -mb-1 flex items-center gap-1.5 border-t border-border px-2.5 pt-2 text-xs text-muted-foreground">
{gate.codeOnly ? null : (
<Button
@@ -279,15 +311,11 @@ export function AgentSignInCard({
</Button>
)}
<span className="flex-1" />
<Button
type="button"
variant="ghost"
size="xs"
onClick={actions.skip}
>
{t('agentSignIn.startAnyway', 'Start without signing in')}
</Button>
{actions.skip ? (
<Button type="button" variant="ghost" size="xs" onClick={actions.skip}>
{t('agentSignIn.startAnyway', 'Start without signing in')}
</Button>
) : null}
</div>
) : null}
</div>
@@ -0,0 +1,43 @@
import { useEffect } from 'react'
import { toast } from 'sonner'
import { defineFixture } from '../../component-fixtures/component-fixture'
import { Toaster } from '@/components/ui/sonner'
import { warnHostAgentOtherAccount } from '@/lib/agent-sign-in/host-agent-sign-out'
function OtherAccountToast(): React.JSX.Element {
useEffect(() => {
// After the Toaster mounts, which listens only from then on.
const timer = window.setTimeout(() => {
warnHostAgentOtherAccount(
{ key: 'fixture', environmentId: 'env-m4air', hostLabel: 'm4air', agent: 'claude' },
'nw@personal.dev',
'nw@stably.ai'
)
}, 50)
return () => {
window.clearTimeout(timer)
toast.dismiss('agent-sign-in-other-account:fixture')
}
}, [])
return (
<>
<div className="h-[900px] bg-background" />
<Toaster closeButton toastOptions={{ className: 'font-sans text-sm' }} />
</>
)
}
export const otherAccountToast = defineFixture({
width: 1280,
render: () => <OtherAccountToast />,
interact: async () => {
const deadline = performance.now() + 3000
while (
document.querySelector('[data-sonner-toast]')?.getAttribute('data-mounted') !== 'true' &&
performance.now() < deadline
) {
await new Promise((resolve) => setTimeout(resolve, 50))
}
await new Promise((resolve) => setTimeout(resolve, 400))
}
})
@@ -22,7 +22,7 @@ import { AgentSignInOverlay } from './AgentSignInOverlay'
const ABANDON_CHECK_MS = 1_000
const mountedPortals = new Map<string, number>()
function cardActions(key: string): AgentSignInCardActions {
export function agentSignInCardActions(key: string): AgentSignInCardActions {
return {
signIn: () => startAgentSignIn(key),
retry: () => void retryAgentSignIn(key),
@@ -65,7 +65,7 @@ function AgentSignInPanePortal({
}
return createPortal(
<AgentSignInOverlay>
<AgentSignInCard gate={gate} actions={cardActions(key)} />
<AgentSignInCard gate={gate} actions={agentSignInCardActions(key)} />
</AgentSignInOverlay>,
pane.container,
`agent-sign-in-${pane.id}`
@@ -1,6 +1,5 @@
import { useEffect, useState, useSyncExternalStore } from 'react'
import { LogOut } from 'lucide-react'
import { toast } from 'sonner'
import {
DropdownMenuItem,
DropdownMenuLabel,
@@ -17,54 +16,16 @@ import {
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { useTranslate } from '@/i18n/use-translate'
import { translate } from '@/i18n/i18n'
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
import {
readHostAgentSignInReport,
refreshHostAgentSignInReport,
rememberHostAgentSignInReport,
subscribeHostAgentSignInReports
} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client'
import type {
HostAgentSignInAgent,
HostAgentSignInReport
} from '../../../../../../shared/host-agent-sign-in-status'
import { signOutAgentOnHost } from '@/lib/agent-sign-in/host-agent-sign-out'
import type { HostAgentSignInAgent } from '../../../../../../shared/host-agent-sign-in-status'
const AGENT_NAME: Record<HostAgentSignInAgent, string> = { claude: 'Claude', codex: 'Codex' }
async function signOut(
environmentId: string,
hostLabel: string,
agent: HostAgentSignInAgent
): Promise<boolean> {
const name = AGENT_NAME[agent]
try {
const report = await callRuntimeRpc<HostAgentSignInReport>(
{ kind: 'environment', environmentId },
'accounts.agentSignOut',
{ agent },
{ timeoutMs: 30_000 }
)
rememberHostAgentSignInReport(environmentId, report)
toast.success(
translate('agentSignIn.signedOutToast', 'Signed out of {{agent}} on {{host}}', {
agent: name,
host: hostLabel
})
)
return true
} catch (error) {
toast.error(
error instanceof Error
? error.message
: translate('agentSignIn.signOutFailed', 'Could not sign out on {{host}}.', {
host: hostLabel
})
)
return false
}
}
/** "Sign out of Claude/Codex" for agents the host reports signed in; nothing otherwise. */
export function HostAgentSignOutMenuItems({
environmentId,
@@ -155,7 +116,7 @@ export function HostAgentSignOutDialog({
return
}
setBusy(true)
void signOut(environmentId, hostLabel, agent).finally(() => {
void signOutAgentOnHost(environmentId, hostLabel, agent).finally(() => {
setBusy(false)
onClose()
})
@@ -0,0 +1,256 @@
import React, { useEffect, useSyncExternalStore } from 'react'
import { Circle, CircleCheck, ExternalLink, Loader2 } from 'lucide-react'
import { useAppStore } from '@/store'
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '@/components/ui/button'
import {
precheckHostAgentSignIn,
readHostAgentSignInReport,
subscribeHostAgentSignInReports
} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client'
import {
HOST_AGENT_SIGN_IN_AGENTS,
type HostAgentSignInAgent,
type HostAgentSignInReport
} from '../../../../shared/host-agent-sign-in-status'
import {
openSignInPage,
useAgentSignInGate,
type AgentSignInGate
} from '@/lib/agent-sign-in/agent-sign-in-gate'
import {
cancelVmBuildAgentSignIn,
forgetVmBuildSignedInAgent,
startVmBuildAgentSignIn,
useVmBuildAgentSignIn,
vmBuildSignInKey,
type VmBuildAgentSignIn,
type VmBuildSignedInAgent
} from '@/lib/agent-sign-in/vm-build-agent-sign-in'
import { switchHostAgentAccount } from '@/lib/agent-sign-in/host-agent-sign-out'
import { AgentSignInCard, ErrorLine } from '../agent-sign-in/AgentSignInCard'
import { agentSignInCardActions } from '../agent-sign-in/AgentSignInPanePortals'
const AGENT_NAME: Record<HostAgentSignInAgent, string> = { claude: 'Claude', codex: 'Codex' }
export type VmBuildAgentSignInRowModel =
| { kind: 'idle'; agents: readonly HostAgentSignInAgent[] }
| {
kind: 'busy'
agent: HostAgentSignInAgent
next: readonly HostAgentSignInAgent[]
gate: AgentSignInGate | null
}
| { kind: 'done'; agents: readonly VmBuildSignedInAgent[] }
/** Hidden unless an agent on the VM is signed out, or the sheet already signed one in. */
export function deriveVmBuildAgentSignInRow(
report: HostAgentSignInReport | null,
run: VmBuildAgentSignIn | null,
gate: AgentSignInGate | null
): VmBuildAgentSignInRowModel | null {
if (run?.running && run.current) {
return { kind: 'busy', agent: run.current, next: run.next, gate }
}
// The host's re-check after a sign-in can land after the run ends; trust the sign-in meanwhile.
const signedOut = HOST_AGENT_SIGN_IN_AGENTS.filter(
(agent) =>
report?.agents.find((entry) => entry.agent === agent)?.state === 'signedOut' &&
!run?.signedIn.some((entry) => entry.agent === agent)
)
if (signedOut.length > 0) {
return { kind: 'idle', agents: signedOut }
}
return run && run.signedIn.length > 0 ? { kind: 'done', agents: run.signedIn } : null
}
export type VmBuildAgentSignInRowActions = {
signIn: (agents: readonly HostAgentSignInAgent[]) => void
cancel: () => void
switchAccount: (agent: HostAgentSignInAgent) => void
}
/** The build checklist's optional sign-in row; the workspace opens whether or not it is used. */
export function VmBuildAgentSignInRowView({
model,
gateKey,
actions
}: {
model: VmBuildAgentSignInRowModel
gateKey: string
actions: VmBuildAgentSignInRowActions
}): React.JSX.Element {
const t = useTranslate()
const view = model.kind === 'busy' ? model.gate?.view : undefined
// Steps that need more than one line (a code, an error) get the full sign-in card under the row.
const cardStep =
view && (view.step === 'paste' || view.step === 'device' || view.step === 'error')
const otherAccounts =
model.kind === 'done' ? model.agents.filter((entry) => entry.expectedEmail) : []
let icon: React.ReactNode
let tag: string | null = null
let detail: string | null = null
let meta: React.ReactNode = null
if (model.kind === 'idle') {
icon = <Circle aria-hidden className="size-3.5 shrink-0 text-muted-foreground/60" />
tag = t('vmBuildAgentSignIn.optional', 'optional')
detail = t('vmBuildAgentSignIn.idleDetail', 'Or sign in when you first start one.')
meta = (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => actions.signIn(model.agents)}
>
{model.agents.length > 1
? t('vmBuildAgentSignIn.signInBoth', 'Sign in {{first}} + {{second}}', {
first: AGENT_NAME[model.agents[0]],
second: AGENT_NAME[model.agents[1]]
})
: t('vmBuildAgentSignIn.signInOne', 'Sign in {{agent}}', {
agent: AGENT_NAME[model.agents[0]]
})}
</Button>
)
} else if (model.kind === 'busy') {
const name = AGENT_NAME[model.agent]
icon = <Loader2 aria-hidden className="size-3.5 shrink-0 animate-spin text-muted-foreground" />
tag =
model.next.length > 0
? t('vmBuildAgentSignIn.next', '{{agent}} next', { agent: AGENT_NAME[model.next[0]] })
: null
detail =
view?.step === 'waiting'
? t('vmBuildAgentSignIn.waiting', '{{agent}}: finish in your browser', { agent: name })
: view?.step === 'signed'
? t('vmBuildAgentSignIn.signed', '{{agent}}: signed in', { agent: name })
: cardStep
? null
: t('vmBuildAgentSignIn.starting', '{{agent}}: starting sign-in…', { agent: name })
// The card below carries its own Cancel.
meta = cardStep ? null : (
<>
{view?.step === 'waiting' ? (
<Button type="button" variant="ghost" size="xs" onClick={() => openSignInPage(view.url)}>
<ExternalLink />
{t('agentSignIn.openAgain', 'Open again')}
</Button>
) : null}
<Button
type="button"
variant="ghost"
size="xs"
className="text-muted-foreground"
onClick={actions.cancel}
>
{t('agentSignIn.cancel', 'Cancel')}
</Button>
</>
)
} else {
icon = <CircleCheck aria-hidden className="size-3.5 shrink-0 text-muted-foreground" />
meta = (
<span className="pr-2 text-xs text-muted-foreground">
{model.agents.map((entry) => AGENT_NAME[entry.agent]).join(', ')}
</span>
)
}
return (
<li className="flex flex-col gap-2 py-1.5" data-vm-build-agent-sign-in={model.kind}>
<div className="flex min-h-7 items-center gap-2.5">
{icon}
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate">
{t('vmBuildAgentSignIn.title', 'Agent sign-in')}
{tag ? <span className="text-xs text-muted-foreground"> · {tag}</span> : null}
</span>
{detail ? <span className="truncate text-xs text-muted-foreground">{detail}</span> : null}
</div>
<div className="flex shrink-0 items-center gap-1">{meta}</div>
</div>
{otherAccounts.map((entry) => (
<div key={entry.agent} className="flex items-start gap-2 pl-6">
<div className="min-w-0 flex-1">
<ErrorLine
tone="warning"
title={t('vmBuildAgentSignIn.otherAccount', '{{agent}} signed in as {{email}}.', {
agent: AGENT_NAME[entry.agent],
email: entry.email ?? ''
})}
detail={t(
'agentSignIn.otherAccountDetail',
'This computer uses {{email}} for {{agent}}.',
{ email: entry.expectedEmail ?? '', agent: AGENT_NAME[entry.agent] }
)}
/>
</div>
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => actions.switchAccount(entry.agent)}
>
{t('agentSignIn.switchAccount', 'Switch account')}
</Button>
</div>
))}
{cardStep && model.kind === 'busy' && model.gate ? (
<div className="pl-6">
<AgentSignInCard
gate={model.gate}
actions={{
...agentSignInCardActions(gateKey),
cancel: actions.cancel,
skip: undefined
}}
/>
</div>
) : null}
</li>
)
}
/** Live row for a VM create; asks the VM once which agents are signed in. */
export function VmBuildAgentSignInRow({
creationId,
environmentId
}: {
creationId: string
environmentId: string
}): React.JSX.Element | null {
const gateKey = vmBuildSignInKey(creationId)
const report = useSyncExternalStore(subscribeHostAgentSignInReports, () =>
readHostAgentSignInReport(environmentId)
)
const run = useVmBuildAgentSignIn(creationId)
const gate = useAgentSignInGate(gateKey)
const hostLabel = useAppStore(
(s) => s.runtimeEnvironments.find((environment) => environment.id === environmentId)?.name
)
useEffect(() => {
precheckHostAgentSignIn(environmentId)
}, [environmentId])
const model = deriveVmBuildAgentSignInRow(report, run, gate)
if (!model) {
return null
}
const label = hostLabel ?? environmentId
return (
<VmBuildAgentSignInRowView
model={model}
gateKey={gateKey}
actions={{
signIn: (agents) => void startVmBuildAgentSignIn(creationId, environmentId, label, agents),
cancel: () => cancelVmBuildAgentSignIn(creationId),
switchAccount: (agent) =>
void switchHostAgentAccount(environmentId, label, agent).then((switched) => {
if (switched) {
forgetVmBuildSignedInAgent(creationId, agent)
}
})
}}
/>
)
}
@@ -2,6 +2,8 @@ import React from 'react'
import { defineFixture } from '../../component-fixtures/component-fixture'
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
import { VmBuildSheet } from './VmBuildSheet'
import { VmBuildAgentSignInRowView, type VmBuildAgentSignInRowModel } from './VmBuildAgentSignInRow'
import type { AgentSignInGate } from '@/lib/agent-sign-in/agent-sign-in-gate'
const LOG = [
'Creating sandbox from snapshot snap_7f2c…',
@@ -29,7 +31,11 @@ function entry(patch: Partial<PendingWorktreeCreation>): PendingWorktreeCreation
}
}
function frame(value: PendingWorktreeCreation, error: string | null = null) {
function frame(
value: PendingWorktreeCreation,
error: string | null = null,
agentSignInRow?: React.ReactNode
) {
return defineFixture({
width: 760,
render: () => (
@@ -43,12 +49,98 @@ function frame(value: PendingWorktreeCreation, error: string | null = null) {
onRetry={() => {}}
onDismiss={() => {}}
onEditRecipe={() => {}}
agentSignInRow={agentSignInRow}
/>
</div>
)
})
}
const noop = (): void => {}
function signInRow(model: VmBuildAgentSignInRowModel): React.ReactNode {
return (
<VmBuildAgentSignInRowView
model={model}
gateKey="fixture"
actions={{ signIn: noop, cancel: noop, switchAccount: noop }}
/>
)
}
function vmGate(agent: AgentSignInGate['agent'], view: AgentSignInGate['view']): AgentSignInGate {
return {
key: 'fixture',
environmentId: 'env-vm',
hostLabel: 'fix-login',
agent,
prompt: null,
codeOnly: false,
view
}
}
const checkingVm = entry({
environmentCheck: { status: 'running' },
provisioningLog: ['Cloning repository…', 'Starting orca serve on :7420', 'Paired.'].join('\n')
})
export const signInIdle = frame(
checkingVm,
null,
signInRow({ kind: 'idle', agents: ['claude', 'codex'] })
)
export const signInWaiting = frame(
checkingVm,
null,
signInRow({
kind: 'busy',
agent: 'claude',
next: ['codex'],
gate: vmGate('claude', { step: 'waiting', url: 'https://claude.ai/oauth/authorize' })
})
)
export const signInDeviceCode = frame(
checkingVm,
null,
signInRow({
kind: 'busy',
agent: 'codex',
next: [],
gate: vmGate('codex', {
step: 'device',
url: 'https://auth.openai.com/codex/device',
userCode: 'K7PQ-2HXM'
})
})
)
export const signInDone = frame(
checkingVm,
null,
signInRow({
kind: 'done',
agents: [
{ agent: 'claude', email: 'nw@stably.ai' },
{ agent: 'codex', email: 'nw@stably.ai' }
]
})
)
export const signInOtherAccount = frame(
checkingVm,
null,
signInRow({
kind: 'done',
agents: [
{ agent: 'claude', email: 'nw@stably.ai' },
{ agent: 'codex', email: 'nw@personal.dev', expectedEmail: 'nw@stably.ai' }
]
})
)
export const provisioning = frame(
entry({ provisioningLog: LOG.split('\n').slice(0, 2).join('\n') })
)
@@ -11,6 +11,7 @@ import { StepIcon } from './WorktreeSetupSteps'
import type { WorktreeSetupStepState } from './worktree-setup-steps'
import { VmBuildLog } from './VmBuildLog'
import { VmBuildFailureCard, type VmBuildFailure } from './VmBuildFailureCard'
import { VmBuildAgentSignInRow } from './VmBuildAgentSignInRow'
type VmBuildStep = { id: 'provision' | 'checks' | 'create'; state: WorktreeSetupStepState }
@@ -72,7 +73,8 @@ export function VmBuildSheet({
onCancel,
onRetry,
onDismiss,
onEditRecipe
onEditRecipe,
agentSignInRow
}: {
creationId: string
entry: PendingWorktreeCreation
@@ -82,6 +84,8 @@ export function VmBuildSheet({
onRetry: () => void
onDismiss: () => void
onEditRecipe: () => void
/** Fixtures only: a fixed sign-in row in place of the live one. */
agentSignInRow?: React.ReactNode
}): React.JSX.Element {
const t = useTranslate()
const steps = deriveVmBuildSteps(entry)
@@ -174,6 +178,13 @@ export function VmBuildSheet({
</span>
</li>
))}
{agentSignInRow ??
(entry.vmEnvironmentId ? (
<VmBuildAgentSignInRow
creationId={creationId}
environmentId={entry.vmEnvironmentId}
/>
) : null)}
</ol>
<VmBuildFailureCard
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import type { HostAgentSignInReport } from '../../../../shared/host-agent-sign-in-status'
import { deriveVmBuildAgentSignInRow } from './VmBuildAgentSignInRow'
const report = (claude: string, codex: string): HostAgentSignInReport =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: states are the literal union.
({
checkedAt: 0,
agents: [
{ agent: 'claude', state: claude },
{ agent: 'codex', state: codex }
]
}) as HostAgentSignInReport
const run = (patch = {}) => ({
environmentId: 'env-vm',
running: false,
current: null,
next: [],
signedIn: [],
...patch
})
describe('VM build sheet sign-in row', () => {
it('stays hidden when nothing on the VM needs signing in', () => {
expect(deriveVmBuildAgentSignInRow(null, null, null)).toBeNull()
expect(deriveVmBuildAgentSignInRow(report('signedIn', 'notInstalled'), null, null)).toBeNull()
})
it('offers only the signed-out agents', () => {
expect(deriveVmBuildAgentSignInRow(report('signedIn', 'signedOut'), null, null)).toEqual({
kind: 'idle',
agents: ['codex']
})
})
it('shows the sheet’s sign-ins as done before the VM’s re-check lands', () => {
const signedIn = [
{ agent: 'claude' as const, email: 'me@example.com' },
{ agent: 'codex' as const, email: 'me@example.com' }
]
expect(
deriveVmBuildAgentSignInRow(report('signedOut', 'signedOut'), run({ signedIn }), null)
).toEqual({ kind: 'done', agents: signedIn })
})
})
@@ -1,5 +1,6 @@
import { observeJiraImageHostStatus } from '@/runtime/jira/runtime-jira-image-cache'
import { observeRuntimeHostStatusForPendingRemovals } from '@/store/repos/pending-runtime-repo-removal-replay'
import { observeRuntimeHostStatusForAgentSignInPrecheck } from '@/lib/agent-sign-in/host-agent-sign-in-precheck'
import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status'
import { getTabIdsAwaitingHostHydrationRemount } from '@/lib/parked-terminal-host-hydration'
import { emitAutomationsChangedWindowEvent } from '@/lib/automations-changed-window-event'
@@ -72,6 +73,7 @@ export function installAppLifetimeIpcEvents(): () => void {
observeRuntimeHostStatusForPendingRemovals(snapshot)
remoteRuntimeTerminalColorPush.observeStatusSnapshot(snapshot)
observeJiraImageHostStatus(snapshot)
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot)
}
let stopped = false
unsubs.push(statusApi.onStatusChanged(apply), () => {
@@ -0,0 +1,75 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
type Report = { checkedAt: number; agents: { agent: string; state: string }[] }
const signedOut: Report = { checkedAt: 0, agents: [{ agent: 'claude', state: 'signedOut' }] }
const signedIn: Report = { checkedAt: 0, agents: [{ agent: 'claude', state: 'signedIn' }] }
const status = vi.hoisted(() => ({
fresh: null as Report | null,
refresh: vi.fn<() => Promise<Report | null>>()
}))
vi.mock('@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client', () => ({
readHostAgentSignInReport: () => status.fresh,
readFreshHostAgentSignInReport: () => status.fresh,
refreshHostAgentSignInReport: status.refresh,
hostAgentSignInEntry: (value: Report | null, agent: string) =>
value?.agents.find((entry) => entry.agent === agent) ?? null
}))
vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({
runtimeEnvironmentSupportsCapability: async () => true
}))
const {
agentSignInGateEntry,
readAgentSignInGate,
releaseAgentSignInPane,
requireAgentSignIn,
settleAgentSignInGate
} = await import('./agent-sign-in-gate-store')
const request = (key: string, background = false) => ({
key,
environmentId: 'env-1',
hostLabel: 'devbox',
agent: 'claude' as const,
prompt: null,
background
})
describe('agent sign-in gate with a connect-time verdict', () => {
beforeEach(() => {
status.fresh = null
status.refresh.mockReset()
})
it('shows the card at once from a recent signed-out verdict, without waiting on the host', async () => {
status.fresh = signedOut
status.refresh.mockReturnValue(new Promise(() => {}))
const held = requireAgentSignIn(request('pane-a'))
await vi.waitFor(() => expect(readAgentSignInGate('pane-a')?.view.step).toBe('need'))
settleAgentSignInGate(agentSignInGateEntry('pane-a')!, 'cancel')
await expect(held).resolves.toBe('cancel')
})
it('lets the launch go when the host has since been signed in', async () => {
status.fresh = signedOut
status.refresh.mockResolvedValue(signedIn)
await expect(requireAgentSignIn(request('pane-b'))).resolves.toBe('proceed')
expect(readAgentSignInGate('pane-b')).toBeNull()
})
it('a waiter without a launch never keeps the sign-in alive for itself', async () => {
status.refresh.mockResolvedValue(signedOut)
const sheet = requireAgentSignIn(request('sheet', true))
await vi.waitFor(() => expect(readAgentSignInGate('sheet')).not.toBeNull())
const pane = requireAgentSignIn(request('pane-c'))
await vi.waitFor(() => expect(readAgentSignInGate('pane-c')).not.toBeNull())
// The launching pane leaves: nothing that would start an agent still waits.
expect(releaseAgentSignInPane('pane-c', 'cancel')).toBe(true)
await expect(pane).resolves.toBe('cancel')
settleAgentSignInGate(agentSignInGateEntry('sheet')!, 'cancel')
await expect(sheet).resolves.toBe('cancel')
})
})
@@ -4,6 +4,7 @@ vi.mock('@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client',
const report = { checkedAt: 0, agents: [{ agent: 'claude', state: 'signedOut' }] }
return {
readHostAgentSignInReport: () => null,
readFreshHostAgentSignInReport: () => null,
refreshHostAgentSignInReport: async () => report,
hostAgentSignInEntry: (value: typeof report | null, agent: string) =>
value?.agents.find((entry) => entry.agent === agent) ?? null
@@ -4,6 +4,7 @@ import { HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY } from '../../../../sh
import { runtimeEnvironmentSupportsCapability } from '@/runtime/rpc/compatibility/runtime-capability-proof'
import {
hostAgentSignInEntry,
readFreshHostAgentSignInReport,
readHostAgentSignInReport,
refreshHostAgentSignInReport
} from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client'
@@ -15,7 +16,12 @@ export type AgentSignInGateView =
| { step: 'waiting'; url: string }
| { step: 'paste'; url: string; submitting: boolean; refusal: string | null }
| { step: 'device'; url: string; userCode: string }
| { step: 'signed'; email: string | null }
| {
step: 'signed'
email: string | null
/** The account this computer uses for the agent, when the host signed in as another. */
expectedEmail?: string
}
| {
step: 'error'
kind: 'port_busy' | 'timeout' | 'declined' | 'offline' | 'failed'
@@ -38,6 +44,8 @@ export type AgentSignInGate = {
export type GateEntry = AgentSignInGate & {
/** Each held pane's launch, by pane key. */
waiters: Map<string, (outcome: 'proceed' | 'cancel') => void>
/** Waiters with no launch of their own (the VM build sheet); they never keep a sign-in alive. */
backgroundWaiters: Set<string>
/** Bumps on every new sign-in attempt so a late result of an abandoned one is ignored. */
attempt: number
forwardFlowId: string | null
@@ -60,7 +68,13 @@ function notify(): void {
}
function publicGate(entry: GateEntry): AgentSignInGate {
const { waiters: _waiters, attempt: _attempt, forwardFlowId: _flow, ...gate } = entry
const {
waiters: _waiters,
backgroundWaiters: _background,
attempt: _attempt,
forwardFlowId: _flow,
...gate
} = entry
return gate
}
@@ -96,38 +110,70 @@ export function setAgentSignInGateView(entry: GateEntry, view: AgentSignInGateVi
notify()
}
function subscribe(listener: () => void): () => void {
export function subscribeAgentSignInGates(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
export function useAgentSignInGate(paneKey: string): AgentSignInGate | null {
return useSyncExternalStore(subscribe, () => snapshotOf(agentSignInGateEntry(paneKey)))
return useSyncExternalStore(subscribeAgentSignInGates, () =>
snapshotOf(agentSignInGateEntry(paneKey))
)
}
export function readAgentSignInGate(paneKey: string): AgentSignInGate | null {
return snapshotOf(agentSignInGateEntry(paneKey))
}
type SignedOutVerdict = { signedOut: boolean; fromCache: boolean }
async function signedOutVerdict(
environmentId: string,
agent: HostAgentSignInAgent
): Promise<SignedOutVerdict> {
const cached = hostAgentSignInEntry(readHostAgentSignInReport(environmentId), agent)
const fresh = hostAgentSignInEntry(readFreshHostAgentSignInReport(environmentId), agent)
// Sign-in rarely changes by itself: a signed-in verdict of any age, or a recent signed-out
// one (usually the connect-time pre-check), answers at once; the host is re-asked quietly.
if ((cached && cached.state !== 'signedOut') || fresh) {
void refreshHostAgentSignInReport(environmentId)
return { signedOut: (fresh ?? cached)?.state === 'signedOut', fromCache: true }
}
const report = await Promise.race([
refreshHostAgentSignInReport(environmentId),
new Promise<null>((resolve) => setTimeout(() => resolve(null), FIRST_CHECK_BUDGET_MS))
])
return { signedOut: hostAgentSignInEntry(report, agent)?.state === 'signedOut', fromCache: false }
}
/** Whether `agent` is known signed out on the host; unknown answers count as signed in. */
export async function isAgentSignedOutOnHost(
environmentId: string,
agent: HostAgentSignInAgent
): Promise<boolean> {
const cached = hostAgentSignInEntry(readHostAgentSignInReport(environmentId), agent)
if (cached && cached.state !== 'signedOut') {
// Sign-in rarely changes by itself; refresh quietly for next time.
void refreshHostAgentSignInReport(environmentId)
return false
}
const report = await Promise.race([
refreshHostAgentSignInReport(environmentId),
new Promise<null>((resolve) => setTimeout(() => resolve(null), FIRST_CHECK_BUDGET_MS))
])
return hostAgentSignInEntry(report, agent)?.state === 'signedOut'
return (await signedOutVerdict(environmentId, agent)).signedOut
}
function waitOn(entry: GateEntry, paneKey: string): Promise<'proceed' | 'cancel'> {
/** A card raised from a cached verdict steps aside if the host's fresh answer says signed in. */
function releaseIfHostDisagrees(entry: GateEntry): void {
void refreshHostAgentSignInReport(entry.environmentId).then((report) => {
const state = hostAgentSignInEntry(report, entry.agent)?.state
if (report && state !== 'signedOut' && entry.view.step === 'need') {
settleAgentSignInGate(entry, 'proceed')
}
})
}
function waitOn(
entry: GateEntry,
paneKey: string,
background: boolean
): Promise<'proceed' | 'cancel'> {
if (background) {
entry.backgroundWaiters.add(paneKey)
} else {
entry.backgroundWaiters.delete(paneKey)
}
return new Promise((resolve) => {
const previous = entry.waiters.get(paneKey)
entry.waiters.set(paneKey, (outcome) => {
@@ -150,14 +196,17 @@ export async function requireAgentSignIn(request: {
hostLabel: string
agent: HostAgentSignInAgent
prompt: string | null
/** Waits without a launch of its own, so it never keeps the sign-in alive by itself. */
background?: boolean
}): Promise<'proceed' | 'cancel'> {
const { key: paneKey, ...gate } = request
const { key: paneKey, background = false, ...gate } = request
const key = gateKeyOf(gate.environmentId, gate.agent)
const running = gates.get(key)
if (running) {
return waitOn(running, paneKey)
return waitOn(running, paneKey, background)
}
if (!(await isAgentSignedOutOnHost(gate.environmentId, gate.agent))) {
const verdict = await signedOutVerdict(gate.environmentId, gate.agent)
if (!verdict.signedOut) {
return 'proceed'
}
const codeOnly = !(await runtimeEnvironmentSupportsCapability(
@@ -170,11 +219,17 @@ export async function requireAgentSignIn(request: {
codeOnly,
view: { step: 'need' as const },
waiters: new Map(),
backgroundWaiters: new Set<string>(),
attempt: 0,
forwardFlowId: null
}
const created = !gates.has(key)
gates.set(key, entry)
return waitOn(entry, paneKey)
const held = waitOn(entry, paneKey, background)
if (created && verdict.fromCache) {
releaseIfHostDisagrees(entry)
}
return held
}
/** Ends the gate for every pane waiting on it. */
@@ -186,6 +241,7 @@ export function settleAgentSignInGate(entry: GateEntry, outcome: 'proceed' | 'ca
gates.delete(entry.key)
const waiters = [...entry.waiters]
entry.waiters.clear()
entry.backgroundWaiters.clear()
for (const [paneKey] of waiters) {
gateKeyByPane.delete(paneKey)
}
@@ -195,7 +251,7 @@ export function settleAgentSignInGate(entry: GateEntry, outcome: 'proceed' | 'ca
}
}
/** Lets one pane go its own way; true when no other pane still waits on the gate. */
/** Lets one pane go its own way; true when no launching pane still waits on the gate. */
export function releaseAgentSignInPane(paneKey: string, outcome: 'proceed' | 'cancel'): boolean {
const entry = agentSignInGateEntry(paneKey)
const resolve = entry?.waiters.get(paneKey)
@@ -203,10 +259,11 @@ export function releaseAgentSignInPane(paneKey: string, outcome: 'proceed' | 'ca
return true
}
entry.waiters.delete(paneKey)
entry.backgroundWaiters.delete(paneKey)
gateKeyByPane.delete(paneKey)
notify()
resolve(outcome)
return entry.waiters.size === 0
return [...entry.waiters.keys()].every((key) => entry.backgroundWaiters.has(key))
}
export function closeAgentSignInForward(entry: GateEntry): void {
@@ -27,6 +27,8 @@ import {
type AgentSignInGateView,
type GateEntry
} from './agent-sign-in-gate-store'
import { differentAccountEmail, readDesktopAgentEmail } from './desktop-agent-account'
import { warnHostAgentOtherAccount } from './host-agent-sign-out'
export {
isAgentSignedOutOnHost,
@@ -38,6 +40,8 @@ export {
} from './agent-sign-in-gate-store'
const SIGNED_IN_HOLD_MS = 600
// Long enough to read the account line; the launch still goes ahead on its own.
const OTHER_ACCOUNT_HOLD_MS = 1_800
/** Sign-in pages open in the person's own browser, where they are already signed in. */
export function openSignInPage(url: string): void {
@@ -90,8 +94,25 @@ async function finishSignedIn(entry: GateEntry, status: HostAccountSignInStatus)
).catch(() => {})
}
void refreshHostAgentSignInReport(entry.environmentId, { force: true })
setAgentSignInGateView(entry, { step: 'signed', email: account?.email ?? null })
setTimeout(() => settleAgentSignInGate(entry, 'proceed'), SIGNED_IN_HOLD_MS)
const email = account?.email ?? null
const expectedEmail = differentAccountEmail(email, await readDesktopAgentEmail(entry.agent))
if (!isCurrentAgentSignInGate(entry)) {
return
}
setAgentSignInGateView(entry, {
step: 'signed',
email,
...(expectedEmail ? { expectedEmail } : {})
})
// The build sheet shows it inline with its own Switch account; a pane's card is gone in a moment.
const launching = [...entry.waiters.keys()].some((key) => !entry.backgroundWaiters.has(key))
if (email && expectedEmail && launching) {
warnHostAgentOtherAccount(entry, email, expectedEmail)
}
setTimeout(
() => settleAgentSignInGate(entry, 'proceed'),
expectedEmail ? OTHER_ACCOUNT_HOLD_MS : SIGNED_IN_HOLD_MS
)
}
/** Follows the host's sign-in and turns its prompts into card steps until it settles. */
@@ -0,0 +1,51 @@
import { describe, expect, it } from 'vitest'
import { differentAccountEmail, selectedAccountEmail } from './desktop-agent-account'
const account = (id: string, email: string) => ({
id,
email,
authMethod: 'subscription-oauth' as const,
createdAt: 0,
updatedAt: 0,
lastAuthenticatedAt: 0
})
describe('desktop agent account', () => {
it('uses the selected account, else the System default login', () => {
const accounts = [account('a', 'work@example.com'), account('b', 'home@example.com')]
expect(
selectedAccountEmail('claude', {
accounts,
activeAccountId: 'a',
activeAccountIdsByRuntime: { host: 'b', wsl: {} }
})
).toBe('home@example.com')
expect(
selectedAccountEmail('claude', {
accounts,
activeAccountId: null,
systemDefaultEmail: 'default@example.com'
})
).toBe('default@example.com')
expect(
selectedAccountEmail('codex', {
accounts: [],
activeAccountId: null,
systemDefault: {
hasAuth: true,
authKind: 'oauth',
email: 'codex@example.com',
providerAccountId: null,
workspaceLabel: null
}
})
).toBe('codex@example.com')
})
it('warns only when both accounts are known and differ', () => {
expect(differentAccountEmail('Me@Example.com', 'me@example.com ')).toBeNull()
expect(differentAccountEmail('other@example.com', null)).toBeNull()
expect(differentAccountEmail(null, 'me@example.com')).toBeNull()
expect(differentAccountEmail('other@example.com', 'me@example.com')).toBe('me@example.com')
})
})
@@ -0,0 +1,50 @@
import type {
ClaudeRateLimitAccountsState,
CodexRateLimitAccountsState
} from '../../../../shared/managed-account-types'
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import { isWebClientLocation } from '@/lib/web-client-location'
const READ_BUDGET_MS = 1_500
/** The email of the account a launch would use: the selected one, else System default's. */
export function selectedAccountEmail(
agent: HostAgentSignInAgent,
state: ClaudeRateLimitAccountsState | CodexRateLimitAccountsState | null | undefined
): string | null {
if (!state) {
return null
}
const selectedId = state.activeAccountIdsByRuntime?.host ?? state.activeAccountId
if (selectedId) {
return state.accounts.find((account) => account.id === selectedId)?.email ?? null
}
return agent === 'claude'
? ((state as ClaudeRateLimitAccountsState).systemDefaultEmail ?? null)
: ((state as CodexRateLimitAccountsState).systemDefault?.email ?? null)
}
/** The account this computer uses for `agent`; null in the web client, whose accounts live on its host. */
export async function readDesktopAgentEmail(agent: HostAgentSignInAgent): Promise<string | null> {
if (isWebClientLocation()) {
return null
}
const accounts = agent === 'claude' ? window.api.claudeAccounts : window.api.codexAccounts
// Only a hint for the signed-in card; never let a slow read hold the launch.
const state = await Promise.race([
accounts?.list().catch(() => null) ?? null,
new Promise<null>((resolve) => setTimeout(() => resolve(null), READ_BUDGET_MS))
])
return selectedAccountEmail(agent, state)
}
/** The account this computer uses when the host signed in as a different one; null otherwise. */
export function differentAccountEmail(
hostEmail: string | null,
desktopEmail: string | null
): string | null {
if (!hostEmail || !desktopEmail) {
return null
}
return hostEmail.trim().toLowerCase() === desktopEmail.trim().toLowerCase() ? null : desktopEmail
}
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from 'vitest'
import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-worktree-creation'
const signedOutOn = vi.hoisted(() => vi.fn<(environmentId: string) => Promise<boolean>>())
vi.mock('./agent-sign-in-gate-store', () => ({
isAgentSignedOutOnHost: (environmentId: string) => signedOutOn(environmentId)
}))
vi.mock('@/lib/workspace/creation/worktree-creation-host-agent-launch', () => ({
hostPlannableAgentLaunch: () => ({ agent: 'claude' })
}))
const { hostSignInCheck, signedInHostLaunch } = await import('./host-agent-launch-sign-in')
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only host and agent are read.
const onHost = (hostId: string | null) =>
({ agent: 'claude', executionHostId: hostId }) as WorktreeCreationRequest
describe('host-started agent launch on a new VM', () => {
it('asks the VM itself once it exists, since the early ask had no host', async () => {
signedOutOn.mockImplementation(async (environmentId) => environmentId === 'env-vm')
const before = onHost(null)
const early = hostSignInCheck(before)
await expect(early).resolves.toBe(false)
// Signed out on the VM: the pane plans the launch so it can show the sign-in card.
await expect(
signedInHostLaunch(onHost('runtime:env-vm'), early, before)
).resolves.toBeUndefined()
})
it('reuses the early answer when the host did not change', async () => {
signedOutOn.mockReset()
signedOutOn.mockResolvedValue(true)
const request = onHost('runtime:env-1')
await expect(signedInHostLaunch(request, Promise.resolve(false), request)).resolves.toEqual({
agent: 'claude'
})
expect(signedOutOn).not.toHaveBeenCalled()
})
})
@@ -4,23 +4,36 @@ import type { WorktreeCreationRequest } from '@/lib/workspace/creation/pending-w
import { hostPlannableAgentLaunch } from '@/lib/workspace/creation/worktree-creation-host-agent-launch'
import { isAgentSignedOutOnHost } from './agent-sign-in-gate-store'
/** Whether the creation's Claude/Codex is known signed out on its runtime host. */
export function hostSignInCheck(request: WorktreeCreationRequest): Promise<boolean> {
function creationRuntimeEnvironmentId(request: WorktreeCreationRequest): string | null {
const host = parseExecutionHostId(
request.workspaceRunContext?.hostId ?? request.executionHostId ?? null
)
return host?.kind === 'runtime' ? host.environmentId : null
}
/** Whether the creation's Claude/Codex is known signed out on its runtime host. */
export function hostSignInCheck(request: WorktreeCreationRequest): Promise<boolean> {
const environmentId = creationRuntimeEnvironmentId(request)
const agent = request.agent
if (host?.kind !== 'runtime' || (agent !== 'claude' && agent !== 'codex')) {
if (!environmentId || (agent !== 'claude' && agent !== 'codex')) {
return Promise.resolve(false)
}
return isAgentSignedOutOnHost(host.environmentId, agent)
return isAgentSignedOutOnHost(environmentId, agent)
}
/** A host-started agent can't show the sign-in card, so a signed-out host gets the pane-planned launch. */
export async function signedInHostLaunch(
request: WorktreeCreationRequest,
signedOut: Promise<boolean>
signedOut: Promise<boolean>,
askedFor?: WorktreeCreationRequest
): Promise<HostAgentLaunch | undefined> {
const launch = hostPlannableAgentLaunch(request)
return launch && (await signedOut) ? undefined : launch
if (!launch) {
return undefined
}
// A new VM has no host until it is provisioned, so the early answer was about no host at all.
const moved =
askedFor !== undefined &&
creationRuntimeEnvironmentId(askedFor) !== creationRuntimeEnvironmentId(request)
return (await (moved ? hostSignInCheck(request) : signedOut)) ? undefined : launch
}
@@ -0,0 +1,61 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status'
const precheck = vi.hoisted(() => vi.fn())
vi.mock('@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client', () => ({
precheckHostAgentSignIn: precheck
}))
const { observeRuntimeHostStatusForAgentSignInPrecheck, _resetAgentSignInPrecheckForTest } =
await import('./host-agent-sign-in-precheck')
function snapshot(patch: Partial<RuntimeHostStatusSnapshot>): RuntimeHostStatusSnapshot {
return {
environmentId: 'env-1',
pairingRevision: 1,
sequence: 1,
checkedAt: 0,
status: null,
verification: 'verified',
transport: 'ready',
...patch
}
}
describe('agent sign-in pre-check on host connect', () => {
beforeEach(() => {
vi.useFakeTimers()
precheck.mockReset()
_resetAgentSignInPrecheckForTest()
})
afterEach(() => vi.useRealTimers())
it('asks once per connection, after the connect settles', () => {
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({}))
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ sequence: 2 }))
expect(precheck).not.toHaveBeenCalled()
vi.advanceTimersByTime(3_000)
expect(precheck).toHaveBeenCalledTimes(1)
expect(precheck).toHaveBeenCalledWith('env-1')
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ transport: 'disconnected' }))
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ sequence: 3 }))
vi.advanceTimersByTime(3_000)
expect(precheck).toHaveBeenCalledTimes(2)
})
it('never asks a host that is not connected, such as a suspended VM', () => {
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ transport: 'disconnected' }))
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ verification: 'unavailable' }))
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ retired: true }))
vi.advanceTimersByTime(10_000)
expect(precheck).not.toHaveBeenCalled()
})
it('drops the ask when the host goes away before it fires', () => {
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({}))
observeRuntimeHostStatusForAgentSignInPrecheck(snapshot({ transport: 'connecting' }))
vi.advanceTimersByTime(3_000)
expect(precheck).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,40 @@
import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status'
import { precheckHostAgentSignIn } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client'
// Let the connect's own hydration go first; the check only needs to land before a launch.
const PRECHECK_DELAY_MS = 3_000
const connected = new Set<string>()
/** Answering and reachable now. A suspended VM has no live connection, so it never counts. */
function isLive(snapshot: RuntimeHostStatusSnapshot): boolean {
return snapshot.verification === 'verified' && snapshot.transport === 'ready' && !snapshot.retired
}
/**
* Asks a host once, in the background, which agents are signed in each time it connects, so the
* first Claude/Codex launch there reads a cached verdict instead of waiting on the host. The
* client skips the ask while an answer from the last few minutes is still at hand.
*/
export function observeRuntimeHostStatusForAgentSignInPrecheck(
snapshot: RuntimeHostStatusSnapshot
): void {
const { environmentId } = snapshot
if (!isLive(snapshot)) {
connected.delete(environmentId)
return
}
if (connected.has(environmentId)) {
return
}
connected.add(environmentId)
setTimeout(() => {
if (connected.has(environmentId)) {
precheckHostAgentSignIn(environmentId)
}
}, PRECHECK_DELAY_MS)
}
export function _resetAgentSignInPrecheckForTest(): void {
connected.clear()
}
@@ -0,0 +1,93 @@
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
import { rememberHostAgentSignInReport } from '@/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client'
import type {
HostAgentSignInAgent,
HostAgentSignInReport
} from '../../../../shared/host-agent-sign-in-status'
const AGENT_NAME: Record<HostAgentSignInAgent, string> = { claude: 'Claude', codex: 'Codex' }
/** Runs the agent's own logout on the host; resolves whether it worked. */
export async function signOutAgentOnHost(
environmentId: string,
hostLabel: string,
agent: HostAgentSignInAgent,
detail?: string
): Promise<boolean> {
const name = AGENT_NAME[agent]
try {
const report = await callRuntimeRpc<HostAgentSignInReport>(
{ kind: 'environment', environmentId },
'accounts.agentSignOut',
{ agent },
{ timeoutMs: 30_000 }
)
rememberHostAgentSignInReport(environmentId, report)
toast.success(
translate('agentSignIn.signedOutToast', 'Signed out of {{agent}} on {{host}}', {
agent: name,
host: hostLabel
}),
detail ? { description: detail } : undefined
)
return true
} catch (error) {
toast.error(
error instanceof Error
? error.message
: translate('agentSignIn.signOutFailed', 'Could not sign out on {{host}}.', {
host: hostLabel
})
)
return false
}
}
/** Signs the host's agent out so the next start signs in again, with the browser on the other account. */
export function switchHostAgentAccount(
environmentId: string,
hostLabel: string,
agent: HostAgentSignInAgent
): Promise<boolean> {
return signOutAgentOnHost(
environmentId,
hostLabel,
agent,
translate(
'agentSignIn.switchAccountDetail',
'Switch accounts in your browser, then start {{agent}} there again to sign in.',
{ agent: AGENT_NAME[agent] }
)
)
}
/** Not an error: the agent starts anyway, and the warning outlives the card so it can be acted on. */
export function warnHostAgentOtherAccount(
host: { key: string; environmentId: string; hostLabel: string; agent: HostAgentSignInAgent },
email: string,
expectedEmail: string
): void {
const agent = AGENT_NAME[host.agent]
toast.warning(
translate('agentSignIn.otherAccountToast', '{{agent}} on {{host}} is signed in as {{email}}', {
agent,
host: host.hostLabel,
email
}),
{
id: `agent-sign-in-other-account:${host.key}`,
duration: 20_000,
description: translate(
'agentSignIn.otherAccountDetail',
'This computer uses {{email}} for {{agent}}.',
{ email: expectedEmail, agent }
),
action: {
label: translate('agentSignIn.switchAccount', 'Switch account'),
onClick: () => void switchHostAgentAccount(host.environmentId, host.hostLabel, host.agent)
}
}
)
}
@@ -0,0 +1,178 @@
import { useSyncExternalStore } from 'react'
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import {
agentSignInGateEntry,
readAgentSignInGate,
requireAgentSignIn,
subscribeAgentSignInGates,
type AgentSignInGateView
} from './agent-sign-in-gate-store'
import { cancelAgentSignIn, startAgentSignIn } from './agent-sign-in-gate'
/** One agent the sheet signed in, and the account this computer uses when the host's differs. */
export type VmBuildSignedInAgent = {
agent: HostAgentSignInAgent
email: string | null
expectedEmail?: string
}
/** The build sheet's "Sign in Claude + Codex" run: one agent at a time, in the order given. */
export type VmBuildAgentSignIn = {
environmentId: string
running: boolean
current: HostAgentSignInAgent | null
next: readonly HostAgentSignInAgent[]
signedIn: readonly VmBuildSignedInAgent[]
}
const runs = new Map<string, VmBuildAgentSignIn>()
const stopped = new Set<string>()
const listeners = new Set<() => void>()
function notify(): void {
for (const listener of listeners) {
listener()
}
}
function update(creationId: string, patch: Partial<VmBuildAgentSignIn>): void {
const run = runs.get(creationId)
if (run) {
runs.set(creationId, { ...run, ...patch })
notify()
}
}
/** The gate key the sheet waits under; it has no pane, so it never holds a launch. */
export function vmBuildSignInKey(creationId: string): string {
return `vm-build-sheet:${creationId}`
}
/** Resolves once the sign-in for this key exists, or the wait ended without needing one. */
function gateOpened(key: string, held: Promise<unknown>): Promise<void> {
return new Promise((resolve) => {
let unsubscribe = (): void => {}
const done = (): void => {
unsubscribe()
resolve()
}
unsubscribe = subscribeAgentSignInGates(() => {
if (agentSignInGateEntry(key)) {
done()
}
})
if (agentSignInGateEntry(key)) {
done()
}
void held.finally(done)
})
}
async function signInOne(
creationId: string,
environmentId: string,
hostLabel: string,
agent: HostAgentSignInAgent
): Promise<'proceed' | 'cancel'> {
const key = vmBuildSignInKey(creationId)
let lastView: AgentSignInGateView | null = null
const unsubscribe = subscribeAgentSignInGates(() => {
lastView = readAgentSignInGate(key)?.view ?? lastView
})
try {
const held = requireAgentSignIn({
key,
environmentId,
hostLabel,
agent,
prompt: null,
background: true
})
await gateOpened(key, held)
if (stopped.has(creationId)) {
cancelAgentSignIn(key)
} else if (agentSignInGateEntry(key)?.view.step === 'need') {
// A pane may already be signing this agent in there; the sheet then only follows it.
startAgentSignIn(key)
}
const outcome = await held
const signed = lastView as AgentSignInGateView | null
if (outcome === 'proceed' && signed?.step === 'signed') {
const run = runs.get(creationId)
update(creationId, {
signedIn: [
...(run?.signedIn ?? []),
{
agent,
email: signed.email,
...(signed.expectedEmail ? { expectedEmail: signed.expectedEmail } : {})
}
]
})
}
return outcome
} finally {
unsubscribe()
}
}
/** Signs each agent in on the VM back to back: one browser approval, then the next. */
export async function startVmBuildAgentSignIn(
creationId: string,
environmentId: string,
hostLabel: string,
agents: readonly HostAgentSignInAgent[]
): Promise<void> {
if (runs.get(creationId)?.running || agents.length === 0) {
return
}
stopped.delete(creationId)
runs.set(creationId, {
environmentId,
running: true,
current: null,
next: agents,
signedIn: runs.get(creationId)?.signedIn ?? []
})
notify()
for (const [index, agent] of agents.entries()) {
if (stopped.has(creationId)) {
break
}
update(creationId, { current: agent, next: agents.slice(index + 1) })
if ((await signInOne(creationId, environmentId, hostLabel, agent)) === 'cancel') {
break
}
}
update(creationId, { running: false, current: null, next: [] })
}
/** Stops the run; a pane still waiting on the same sign-in keeps it. */
export function cancelVmBuildAgentSignIn(creationId: string): void {
stopped.add(creationId)
update(creationId, { next: [] })
cancelAgentSignIn(vmBuildSignInKey(creationId))
}
/** Forgets an agent the sheet signed in, e.g. after switching its account on the host. */
export function forgetVmBuildSignedInAgent(creationId: string, agent: HostAgentSignInAgent): void {
const run = runs.get(creationId)
if (run) {
update(creationId, { signedIn: run.signedIn.filter((entry) => entry.agent !== agent) })
}
}
function subscribe(listener: () => void): () => void {
listeners.add(listener)
return () => listeners.delete(listener)
}
export function useVmBuildAgentSignIn(creationId: string): VmBuildAgentSignIn | null {
return useSyncExternalStore(subscribe, () => runs.get(creationId) ?? null)
}
export function _resetVmBuildAgentSignInForTest(): void {
runs.clear()
stopped.clear()
listeners.clear()
}
@@ -80,6 +80,9 @@ async function prepareEphemeralVmRecipeRequest(
}
appendProvisioningWarnings(creationId, preparedTarget.warnings)
if (preparedTarget.environmentId) {
useAppStore
.getState()
.updatePendingWorktreeCreation(creationId, { vmEnvironmentId: preparedTarget.environmentId })
// Why: the VM's first connect may have just deployed this server; host badges and removal read it.
try {
useAppStore.getState().setRuntimeEnvironments(await window.api.runtimeEnvironments.list())
@@ -166,6 +166,8 @@ export type PendingWorktreeCreation = {
provisioningLog?: string
/** VM creates: the provisioned VM's environment checks, run before the workspace is created. */
environmentCheck?: PendingVmEnvironmentCheck
/** VM creates: the provisioned VM's runtime environment, known once it answers. */
vmEnvironmentId?: string
// Local git checkout meter; absent when git emits none or creation runs over SSH/runtime.
checkoutProgress?: WorktreeCheckoutProgress
/** Phases entered so far with their start times, so the chat checklist can time each step. */
@@ -58,7 +58,7 @@ export async function executeWorktreeCreation(
const creationHostId =
preparedRequest.workspaceRunContext?.hostId ?? preparedRequest.executionHostId
const onCreationHost = creationHostId ? { executionHostId: creationHostId } : {}
const hostAgentLaunch = await signedInHostLaunch(preparedRequest, signedOut)
const hostAgentLaunch = await signedInHostLaunch(preparedRequest, signedOut, request)
let result: CreatedWorktreeResult
try {
const provisionedRoot = getProvisionedRootCreateOptions(preparedRequest)
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const rpc = vi.hoisted(() => vi.fn())
vi.mock('../../rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc }))
vi.mock('../../rpc/compatibility/runtime-capability-proof', () => ({
runtimeEnvironmentSupportsCapability: async () => true
}))
const {
_resetHostAgentSignInReportsForTest,
precheckHostAgentSignIn,
readFreshHostAgentSignInReport,
refreshHostAgentSignInReport
} = await import('./host-agent-sign-in-status-client')
const report = { checkedAt: 1, agents: [{ agent: 'claude', state: 'signedOut' }] }
describe('host agent sign-in pre-check', () => {
beforeEach(() => {
vi.useFakeTimers()
rpc.mockReset()
rpc.mockResolvedValue(report)
_resetHostAgentSignInReportsForTest()
})
afterEach(() => vi.useRealTimers())
it('asks the host once and reuses the answer for five minutes', async () => {
precheckHostAgentSignIn('env-1')
precheckHostAgentSignIn('env-1')
await vi.waitFor(() => expect(readFreshHostAgentSignInReport('env-1')).toEqual(report))
expect(rpc).toHaveBeenCalledTimes(1)
precheckHostAgentSignIn('env-1')
expect(rpc).toHaveBeenCalledTimes(1)
vi.advanceTimersByTime(5 * 60_000)
expect(readFreshHostAgentSignInReport('env-1')).toBeNull()
precheckHostAgentSignIn('env-1')
await vi.waitFor(() => expect(rpc).toHaveBeenCalledTimes(2))
})
it('keeps the last answer when a later ask fails, without counting it as fresh', async () => {
await refreshHostAgentSignInReport('env-1')
vi.advanceTimersByTime(5 * 60_000)
rpc.mockRejectedValue(new Error('asleep'))
await refreshHostAgentSignInReport('env-1')
expect(readFreshHostAgentSignInReport('env-1')).toBeNull()
})
})
@@ -8,9 +8,13 @@ import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call'
import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof'
const CALL_TIMEOUT_MS = 30_000
// A verdict this young is trusted for a launch without asking again; launches still re-ask quietly.
const FRESH_REPORT_MS = 5 * 60_000
type Entry = {
report: HostAgentSignInReport | null
/** This client's clock when the report arrived; the host's checkedAt is on another clock. */
receivedAt: number
pending: Promise<HostAgentSignInReport | null> | null
}
@@ -53,6 +57,23 @@ export function readHostAgentSignInReport(environmentId: string): HostAgentSignI
return entries.get(environmentId)?.report ?? null
}
/** The last verdicts when they arrived recently enough to act on without waiting for the host. */
export function readFreshHostAgentSignInReport(
environmentId: string
): HostAgentSignInReport | null {
const entry = entries.get(environmentId)
return entry?.report && Date.now() - entry.receivedAt < FRESH_REPORT_MS ? entry.report : null
}
/** Asks once in the background unless a fresh answer or a request is already here. */
export function precheckHostAgentSignIn(environmentId: string): void {
const entry = entries.get(environmentId)
if (entry?.pending || readFreshHostAgentSignInReport(environmentId)) {
return
}
void refreshHostAgentSignInReport(environmentId)
}
export function hostAgentSignInEntry(
report: HostAgentSignInReport | null,
agent: HostAgentSignInAgent
@@ -70,19 +91,22 @@ export function refreshHostAgentSignInReport(
environmentId: string,
options: { force?: boolean } = {}
): Promise<HostAgentSignInReport | null> {
const entry = entries.get(environmentId) ?? { report: null, pending: null }
const entry = entries.get(environmentId) ?? { report: null, receivedAt: 0, pending: null }
if (entry.pending && !options.force) {
return entry.pending
}
const pending = fetchReport(environmentId, options.force === true).then((report) => {
const current = entries.get(environmentId)
if (current?.pending === pending) {
entries.set(environmentId, { report: report ?? current.report, pending: null })
entries.set(
environmentId,
report ? { report, receivedAt: Date.now(), pending: null } : { ...current, pending: null }
)
notify()
}
return report
})
entries.set(environmentId, { report: entry.report, pending })
entries.set(environmentId, { ...entry, pending })
return pending
}
@@ -91,7 +115,7 @@ export function rememberHostAgentSignInReport(
environmentId: string,
report: HostAgentSignInReport
): void {
entries.set(environmentId, { report, pending: null })
entries.set(environmentId, { report, receivedAt: Date.now(), pending: null })
notify()
}
@@ -180,6 +180,7 @@ export type WorktreeSlice = {
chatSessionOptions?: Readonly<Record<string, string>>
provisioningLog?: string
environmentCheck?: PendingWorktreeCreation['environmentCheck']
vmEnvironmentId?: string
checkoutProgress?: PendingWorktreeCreation['checkoutProgress']
worktreeId?: string
heldChatMessage?: string