diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx index 34e47519186..b3f28ab17bd 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.fixture.tsx @@ -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' })) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx index 8cb7b4494dc..6b45259948b 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInCard.tsx @@ -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 ( -
- +
+

{title}{' '} {detail} @@ -137,6 +156,18 @@ export function AgentSignInCard({ {view.step === 'error' ? : null} + {view.step === 'signed' && view.expectedEmail ? ( + + ) : null} + {view.step === 'paste' ? ( <>

@@ -265,7 +296,8 @@ export function AgentSignInCard({
)} - {view.step === 'need' || view.step === 'starting' || view.step === 'error' ? ( + {(view.step === 'need' || view.step === 'starting' || view.step === 'error') && + (!gate.codeOnly || actions.skip) ? (
{gate.codeOnly ? null : ( + {actions.skip ? ( + + ) : null}
) : null}
diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInOtherAccountToast.fixture.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInOtherAccountToast.fixture.tsx new file mode 100644 index 00000000000..a840c9f4406 --- /dev/null +++ b/src/renderer/src/components/agent-sign-in/AgentSignInOtherAccountToast.fixture.tsx @@ -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 ( + <> +
+ + + ) +} + +export const otherAccountToast = defineFixture({ + width: 1280, + render: () => , + 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)) + } +}) diff --git a/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx b/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx index 01e465b8259..3ae70abfacf 100644 --- a/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx +++ b/src/renderer/src/components/agent-sign-in/AgentSignInPanePortals.tsx @@ -22,7 +22,7 @@ import { AgentSignInOverlay } from './AgentSignInOverlay' const ABANDON_CHECK_MS = 1_000 const mountedPortals = new Map() -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( - + , pane.container, `agent-sign-in-${pane.id}` diff --git a/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx index 1cd292ade30..df36fa727da 100644 --- a/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/rows/HostAgentSignOutMenuItems.tsx @@ -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 = { claude: 'Claude', codex: 'Codex' } -async function signOut( - environmentId: string, - hostLabel: string, - agent: HostAgentSignInAgent -): Promise { - const name = AGENT_NAME[agent] - try { - const report = await callRuntimeRpc( - { kind: 'environment', environmentId }, - 'accounts.agentSignOut', - { agent }, - { timeoutMs: 30_000 } - ) - rememberHostAgentSignInReport(environmentId, report) - toast.success( - translate('agentSignIn.signedOutToast', 'Signed out of {{agent}} on {{host}}', { - agent: name, - host: hostLabel - }) - ) - 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() }) diff --git a/src/renderer/src/components/worktree-creation/VmBuildAgentSignInRow.tsx b/src/renderer/src/components/worktree-creation/VmBuildAgentSignInRow.tsx new file mode 100644 index 00000000000..b1ff87c0f21 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/VmBuildAgentSignInRow.tsx @@ -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 = { 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 = + tag = t('vmBuildAgentSignIn.optional', 'optional') + detail = t('vmBuildAgentSignIn.idleDetail', 'Or sign in when you first start one.') + meta = ( + + ) + } else if (model.kind === 'busy') { + const name = AGENT_NAME[model.agent] + icon = + 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' ? ( + + ) : null} + + + ) + } else { + icon = + meta = ( + + {model.agents.map((entry) => AGENT_NAME[entry.agent]).join(', ')} + + ) + } + + return ( +
  • +
    + {icon} +
    + + {t('vmBuildAgentSignIn.title', 'Agent sign-in')} + {tag ? · {tag} : null} + + {detail ? {detail} : null} +
    +
    {meta}
    +
    + {otherAccounts.map((entry) => ( +
    +
    + +
    + +
    + ))} + {cardStep && model.kind === 'busy' && model.gate ? ( +
    + +
    + ) : null} +
  • + ) +} + +/** 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 ( + void startVmBuildAgentSignIn(creationId, environmentId, label, agents), + cancel: () => cancelVmBuildAgentSignIn(creationId), + switchAccount: (agent) => + void switchHostAgentAccount(environmentId, label, agent).then((switched) => { + if (switched) { + forgetVmBuildSignedInAgent(creationId, agent) + } + }) + }} + /> + ) +} diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx index e7f699968f1..a253aabbae6 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.fixture.tsx @@ -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 } } -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} />
    ) }) } +const noop = (): void => {} + +function signInRow(model: VmBuildAgentSignInRowModel): React.ReactNode { + return ( + + ) +} + +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') }) ) diff --git a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx index 7c9f79b5e7d..082e4631e02 100644 --- a/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx +++ b/src/renderer/src/components/worktree-creation/VmBuildSheet.tsx @@ -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({ ))} + {agentSignInRow ?? + (entry.vmEnvironmentId ? ( + + ) : null)} + // 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 }) + }) +}) diff --git a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts index 80e83e8e5ad..e0b0d94cd93 100644 --- a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts @@ -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), () => { diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-cached-verdict.test.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-cached-verdict.test.ts new file mode 100644 index 00000000000..6cee9416bc0 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-cached-verdict.test.ts @@ -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>() +})) + +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') + }) +}) diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts index 20070434196..996d74c3c16 100644 --- a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.test.ts @@ -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 diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts index 7aae5638f28..2a6007e59ad 100644 --- a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate-store.ts @@ -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 void> + /** Waiters with no launch of their own (the VM build sheet); they never keep a sign-in alive. */ + backgroundWaiters: Set /** 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 { + 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((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 { - const cached = hostAgentSignInEntry(readHostAgentSignInReport(environmentId), agent) - if (cached && cached.state !== 'signedOut') { - // Sign-in rarely changes by itself; refresh quietly for next time. - void refreshHostAgentSignInReport(environmentId) - return false - } - const report = await Promise.race([ - refreshHostAgentSignInReport(environmentId), - new Promise((resolve) => setTimeout(() => resolve(null), FIRST_CHECK_BUDGET_MS)) - ]) - return hostAgentSignInEntry(report, agent)?.state === 'signedOut' + 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(), 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 { diff --git a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts index 993e8c26be5..02011222199 100644 --- a/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts +++ b/src/renderer/src/lib/agent-sign-in/agent-sign-in-gate.ts @@ -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. */ diff --git a/src/renderer/src/lib/agent-sign-in/desktop-agent-account.test.ts b/src/renderer/src/lib/agent-sign-in/desktop-agent-account.test.ts new file mode 100644 index 00000000000..29a4bbced7e --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/desktop-agent-account.test.ts @@ -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') + }) +}) diff --git a/src/renderer/src/lib/agent-sign-in/desktop-agent-account.ts b/src/renderer/src/lib/agent-sign-in/desktop-agent-account.ts new file mode 100644 index 00000000000..17c2b1a6843 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/desktop-agent-account.ts @@ -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 { + 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((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 +} diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.test.ts b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.test.ts new file mode 100644 index 00000000000..55d0bae8234 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.test.ts @@ -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>()) +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() + }) +}) diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts index 9428399ce1c..9904667c88f 100644 --- a/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts +++ b/src/renderer/src/lib/agent-sign-in/host-agent-launch-sign-in.ts @@ -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 { +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 { + 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 + signedOut: Promise, + askedFor?: WorktreeCreationRequest ): Promise { 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 } diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.test.ts b/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.test.ts new file mode 100644 index 00000000000..ffb4be14784 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.test.ts @@ -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 { + 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() + }) +}) diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.ts b/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.ts new file mode 100644 index 00000000000..3e77886ac82 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/host-agent-sign-in-precheck.ts @@ -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() + +/** 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() +} diff --git a/src/renderer/src/lib/agent-sign-in/host-agent-sign-out.ts b/src/renderer/src/lib/agent-sign-in/host-agent-sign-out.ts new file mode 100644 index 00000000000..b96d1ed9358 --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/host-agent-sign-out.ts @@ -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 = { 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 { + const name = AGENT_NAME[agent] + try { + const report = await callRuntimeRpc( + { kind: 'environment', environmentId }, + 'accounts.agentSignOut', + { agent }, + { timeoutMs: 30_000 } + ) + rememberHostAgentSignInReport(environmentId, report) + toast.success( + translate('agentSignIn.signedOutToast', 'Signed out of {{agent}} on {{host}}', { + agent: name, + host: hostLabel + }), + 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 { + 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) + } + } + ) +} diff --git a/src/renderer/src/lib/agent-sign-in/vm-build-agent-sign-in.ts b/src/renderer/src/lib/agent-sign-in/vm-build-agent-sign-in.ts new file mode 100644 index 00000000000..64379fb46bc --- /dev/null +++ b/src/renderer/src/lib/agent-sign-in/vm-build-agent-sign-in.ts @@ -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() +const stopped = new Set() +const listeners = new Set<() => void>() + +function notify(): void { + for (const listener of listeners) { + listener() + } +} + +function update(creationId: string, patch: Partial): 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): Promise { + 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 { + 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() +} diff --git a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts index 5347af12a6e..311ad718940 100644 --- a/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts +++ b/src/renderer/src/lib/ephemeral-vm-worktree-creation.ts @@ -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()) diff --git a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts index c30a0aedb3b..9ae8cf234ef 100644 --- a/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts +++ b/src/renderer/src/lib/workspace/creation/pending-worktree-creation.ts @@ -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. */ diff --git a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts index 289f32f54ca..625542d0636 100644 --- a/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/workspace/creation/worktree-creation-flow-execute.ts @@ -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) diff --git a/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts new file mode 100644 index 00000000000..24874e95ff3 --- /dev/null +++ b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.test.ts @@ -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() + }) +}) diff --git a/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts index b479c8f214e..2f34df5397b 100644 --- a/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts +++ b/src/renderer/src/runtime/provider-accounts/sign-in/host-agent-sign-in-status-client.ts @@ -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 | 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 { - 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() } diff --git a/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts b/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts index 31d8364fa04..0e9e7de7d0b 100644 --- a/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts +++ b/src/renderer/src/store/slices/worktrees/worktree-slice-contract.ts @@ -180,6 +180,7 @@ export type WorktreeSlice = { chatSessionOptions?: Readonly> provisioningLog?: string environmentCheck?: PendingWorktreeCreation['environmentCheck'] + vmEnvironmentId?: string checkoutProgress?: PendingWorktreeCreation['checkoutProgress'] worktreeId?: string heldChatMessage?: string