fix: address review — forced rechecks, account pick, asleep-only mapping, no casts

This commit is contained in:
Neil
2026-11-08 20:21:53 -08:00
parent 9c6909eada
commit 024bbf8d5e
6 changed files with 126 additions and 39 deletions
+3 -4
View File
@@ -32,13 +32,12 @@ export function parseClaudeAuthStatusReport(stdout: string): ClaudeAuthStatusRep
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null
}
const record = parsed as Record<string, unknown>
const report: ClaudeAuthStatusReport = {}
if (typeof record.loggedIn === 'boolean') {
report.loggedIn = record.loggedIn
if ('loggedIn' in parsed && typeof parsed.loggedIn === 'boolean') {
report.loggedIn = parsed.loggedIn
}
for (const field of STRING_FIELDS) {
const value = record[field]
const value = Object.getOwnPropertyDescriptor(parsed, field)?.value
if (typeof value === 'string') {
report[field] = value
}
@@ -105,7 +105,7 @@ describe('HostAgentSignInStatusChecker', () => {
expect(runStatus).not.toHaveBeenCalled()
})
it('falls back to the CLI login when the selected Claude account has no login of its own', async () => {
it('reports a selected Claude account without a login as signed out, even when the CLI is signed in', async () => {
const accounts = emptyAccounts()
accounts.claude = {
accounts: [
@@ -125,7 +125,7 @@ describe('HostAgentSignInStatusChecker', () => {
findCommand: async (command) => ({ status: 'available', binary: `/bin/${command}` }),
runStatus: async (binary) =>
binary === '/bin/claude'
? { exitCode: 1, output: CLAUDE_SIGNED_OUT, timedOut: false }
? { exitCode: 0, output: CLAUDE_SUBSCRIPTION, timedOut: false }
: { exitCode: 1, output: 'Not logged in', timedOut: false },
readAccounts: () => accounts,
now: () => 5
@@ -136,4 +136,34 @@ describe('HostAgentSignInStatusChecker', () => {
{ agent: 'codex', state: 'signedOut' }
])
})
it('answers a forced recheck with a fresh check, not one begun before the sign-in', async () => {
let calls = 0
const firstCheck = Promise.withResolvers<void>()
const checker = new HostAgentSignInStatusChecker({
findCommand: async (command) =>
command === 'codex' ? { status: 'available', binary: '/bin/codex' } : { status: 'absent' },
runStatus: async () => {
// The first check started before the sign-in finished.
const signedIn = calls++ > 0
if (!signedIn) {
await firstCheck.promise
}
return signedIn
? { exitCode: 0, output: 'Logged in using ChatGPT', timedOut: false }
: { exitCode: 1, output: 'Not logged in', timedOut: false }
},
readAccounts: () => emptyAccounts(),
now: () => 1
})
const before = checker.read()
const after = checker.read(true)
firstCheck.resolve()
expect((await before).agents[1]).toEqual({ agent: 'codex', state: 'signedOut' })
expect((await after).agents[1]).toEqual({
agent: 'codex',
state: 'signedIn',
method: 'cliLogin'
})
})
})
@@ -49,18 +49,25 @@ function hostSelection(state: {
return state.activeAccountIdsByRuntime?.host ?? state.activeAccountId
}
/** Whether launches here already use a signed-in Orca account, so the CLI's own login is moot. */
function usesOrcaAccount(agent: HostAgentSignInAgent, accounts: Accounts | null): boolean {
/** The verdict a selected Orca account fixes for launches here; null leaves it to the CLI's own login. */
function orcaAccountVerdict(
agent: HostAgentSignInAgent,
accounts: Accounts | null
): 'signedIn' | 'signedOut' | null {
if (!accounts) {
return false
return null
}
if (agent === 'claude') {
const id = hostSelection(accounts.claude)
const account = accounts.claude.accounts.find((entry) => entry.id === id)
return Boolean(account && !account.needsSignIn && !account.runsOnSystemDefault)
if (!account || account.runsOnSystemDefault) {
return null
}
// Launches use the account's own folder, which holds no login yet.
return account.needsSignIn ? 'signedOut' : 'signedIn'
}
const id = hostSelection(accounts.codex)
return accounts.codex.accounts.some((entry) => entry.id === id)
return accounts.codex.accounts.some((entry) => entry.id === id) ? 'signedIn' : null
}
export function classifyAgentStatusOutput(
@@ -95,17 +102,32 @@ export function classifyAgentStatusOutput(
export class HostAgentSignInStatusChecker {
private report: HostAgentSignInReport | null = null
private inFlight: Promise<HostAgentSignInReport> | null = null
private queuedForce: Promise<HostAgentSignInReport> | null = null
constructor(private readonly deps: HostAgentSignInStatusDeps) {}
read(force = false): Promise<HostAgentSignInReport> {
if (this.inFlight) {
return this.inFlight
if (!force) {
return this.inFlight
}
// Why: a check begun before a sign-in finished can't answer a forced recheck after it.
this.queuedForce ??= this.inFlight
.catch(() => undefined)
.then(() => {
this.queuedForce = null
return this.start()
})
return this.queuedForce
}
const cached = this.report
if (!force && cached && this.deps.now() - cached.checkedAt < REPORT_TTL_MS) {
return Promise.resolve(cached)
}
return this.start()
}
private start(): Promise<HostAgentSignInReport> {
const run = this.check().finally(() => {
if (this.inFlight === run) {
this.inFlight = null
@@ -141,8 +163,11 @@ export class HostAgentSignInStatusChecker {
if (probe.status !== 'available') {
return { agent, state: 'unknown' }
}
if (usesOrcaAccount(agent, accounts)) {
return { agent, state: 'signedIn', method: 'orcaAccount' }
const verdict = orcaAccountVerdict(agent, accounts)
if (verdict) {
return verdict === 'signedIn'
? { agent, state: 'signedIn', method: 'orcaAccount' }
: { agent, state: 'signedOut' }
}
try {
return classifyAgentStatusOutput(
@@ -156,8 +181,8 @@ export class HostAgentSignInStatusChecker {
}
function errorField(error: unknown, field: string): unknown {
return typeof error === 'object' && error !== null && field in error
? (error as Record<string, unknown>)[field]
return typeof error === 'object' && error !== null
? Object.getOwnPropertyDescriptor(error, field)?.value
: undefined
}
@@ -176,7 +201,8 @@ export async function runAgentStatusCommand(
const stdout = errorField(error, 'stdout')
const stderr = errorField(error, 'stderr')
return {
exitCode: typeof code === 'number' ? code : null,
// Why: a throw carrying code 0 is truncated output, never a clean exit.
exitCode: typeof code === 'number' && code !== 0 ? code : null,
output: `${typeof stdout === 'string' ? stdout : ''}\n${typeof stderr === 'string' ? stderr : ''}`,
timedOut: code === 'ETIMEDOUT' || errorField(error, 'killed') === true
}
+1 -1
View File
@@ -22621,7 +22621,7 @@
"signIn": "Sign in",
"codexDeviceCodeHint": "Codex signs in with a device code. If it fails, turn on device code login in ChatGPT under Settings → Security, then try again.",
"title": "Sign in agents",
"description": "Each agent runs its own sign-in on {{host}}. Your login stays on {{host}}; Orca only passes along the link and code.",
"description": "Each agent signs in on {{host}}, and the login stays there. Orca only passes along the link and code.",
"apiKeyNote": "Using an API key instead? Set ANTHROPIC_API_KEY or OPENAI_API_KEY in that host’s shell profile.",
"recheck": "Check again",
"done": "Done",
@@ -58,8 +58,8 @@ describe('host agent sign-in status client', () => {
it('makes a new sign-in the host account only when none was chosen', async () => {
mocks.addClaude.mockResolvedValue({
accounts: [
{ id: 'old', createdAt: 1 },
{ id: 'new', createdAt: 2 }
{ id: 'new', createdAt: 1, lastAuthenticatedAt: 9 },
{ id: 'old', createdAt: 2, lastAuthenticatedAt: 2 }
],
activeAccountId: null,
activeAccountIdsByRuntime: { host: null, wsl: {} }
@@ -72,8 +72,8 @@ describe('host agent sign-in status client', () => {
mocks.addCodex.mockResolvedValue({
accounts: [
{ id: 'chosen', createdAt: 1 },
{ id: 'new', createdAt: 2 }
{ id: 'chosen', lastAuthenticatedAt: 1 },
{ id: 'new', lastAuthenticatedAt: 2 }
],
activeAccountId: 'chosen'
})
@@ -3,7 +3,7 @@ import type {
HostAgentSignInReport
} from '../../../../../shared/host-agent-sign-in-status'
import { HOST_AGENT_SIGN_IN_STATUS_RUNTIME_CAPABILITY } from '../../../../../shared/account-runtime-capabilities'
import { RECIPE_VM_REFUSAL_CODES } from '../../../../../shared/remote-runtime/recipe-vm-wake'
import { RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE } from '../../../../../shared/remote-runtime/recipe-vm-wake'
import { callRuntimeRpc } from '../../rpc/calls/runtime-rpc-call'
import { runtimeEnvironmentSupportsCapability } from '../../rpc/compatibility/runtime-capability-proof'
import {
@@ -28,9 +28,14 @@ export type HostAgentSignInView =
// Why: sign-in rarely changes on its own; views re-ask only after this or an explicit recheck.
const VIEW_TTL_MS = 5 * 60_000
const CALL_TIMEOUT_MS = 30_000
const RECIPE_VM_REFUSALS: ReadonlySet<string> = new Set(RECIPE_VM_REFUSAL_CODES)
type Entry = { view: HostAgentSignInView; settledAt: number; pending: Promise<void> | null }
type Entry = {
view: HostAgentSignInView
settledAt: number
pending: Promise<void> | null
pendingForced: boolean
queuedForce: Promise<void> | null
}
const IDLE: HostAgentSignInView = { phase: 'idle' }
const entries = new Map<string, Entry>()
@@ -47,7 +52,9 @@ function setView(environmentId: string, view: HostAgentSignInView, settled: bool
entries.set(environmentId, {
view,
settledAt: settled ? Date.now() : (entry?.settledAt ?? 0),
pending: entry?.pending ?? null
pending: entry?.pending ?? null,
pendingForced: entry?.pendingForced ?? false,
queuedForce: entry?.queuedForce ?? null
})
notify()
}
@@ -58,8 +65,12 @@ function lastReport(environmentId: string): HostAgentSignInReport | null {
}
function errorCode(error: unknown): string | undefined {
const code = typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined
return typeof code === 'string' ? code : undefined
return typeof error === 'object' &&
error !== null &&
'code' in error &&
typeof error.code === 'string'
? error.code
: undefined
}
async function fetchView(environmentId: string, force: boolean): Promise<HostAgentSignInView> {
@@ -81,7 +92,8 @@ async function fetchView(environmentId: string, force: boolean): Promise<HostAge
return { phase: 'ready', report }
} catch (error) {
const code = errorCode(error)
if (code && RECIPE_VM_REFUSALS.has(code)) {
// Waking or manually disconnected servers fall through to failed, which offers a retry.
if (code === RUNTIME_ENVIRONMENT_ASLEEP_ERROR_CODE) {
return { phase: 'asleep' }
}
if (code === 'method_not_found') {
@@ -105,21 +117,35 @@ export function refreshHostAgentSignInStatus(
environmentId: string,
options: { force?: boolean } = {}
): Promise<void> {
const running = entries.get(environmentId)?.pending
if (running) {
return running
const force = options.force === true
const running = entries.get(environmentId)
if (running?.pending) {
if (!force || running.pendingForced) {
return running.pending
}
// Why: a read begun before a sign-in finished can't answer a forced recheck after it.
running.queuedForce ??= running.pending.then(() => {
const entry = entries.get(environmentId)
if (entry) {
entry.queuedForce = null
}
return refreshHostAgentSignInStatus(environmentId, { force: true })
})
return running.queuedForce
}
setView(environmentId, { phase: 'checking', report: lastReport(environmentId) }, false)
const pending = fetchView(environmentId, options.force === true).then((view) => {
const pending = fetchView(environmentId, force).then((view) => {
setView(environmentId, view, true)
const entry = entries.get(environmentId)
if (entry) {
entry.pending = null
entry.pendingForced = false
}
})
const entry = entries.get(environmentId)
if (entry) {
entry.pending = pending
entry.pendingForced = force
}
return pending
}
@@ -142,19 +168,25 @@ export function ensureHostAgentSignInStatus(environmentId: string): void {
}
type HostAccountsState = {
accounts: { id: string; createdAt: number; managedAuthRuntime?: 'host' | 'wsl' }[]
accounts: {
id: string
lastAuthenticatedAt: number
managedAuthRuntime?: 'host' | 'wsl'
managedHomeRuntime?: 'host' | 'wsl'
}[]
activeAccountId: string | null
activeAccountIdsByRuntime?: { host: string | null }
}
function newestUnselectedHostAccount(state: HostAccountsState): string | null {
/** The host account this sign-in just authenticated, when the host has none chosen. */
function justSignedInUnselectedHostAccount(state: HostAccountsState): string | null {
if ((state.activeAccountIdsByRuntime?.host ?? state.activeAccountId) !== null) {
return null
}
const hostAccounts = state.accounts.filter(
(account) => (account.managedAuthRuntime ?? 'host') === 'host'
(account) => (account.managedAuthRuntime ?? account.managedHomeRuntime ?? 'host') === 'host'
)
hostAccounts.sort((a, b) => b.createdAt - a.createdAt)
hostAccounts.sort((a, b) => b.lastAuthenticatedAt - a.lastAuthenticatedAt)
return hostAccounts[0]?.id ?? null
}
@@ -167,12 +199,12 @@ export async function signInAgentOnHost(
const owner = { kind: 'environment', environmentId } as const
try {
if (agent === 'claude') {
const accountId = newestUnselectedHostAccount(await addClaudeAccountOnHost(owner))
const accountId = justSignedInUnselectedHostAccount(await addClaudeAccountOnHost(owner))
if (accountId) {
await selectClaudeProviderAccount(owner, { accountId, runtime: 'host' })
}
} else {
const accountId = newestUnselectedHostAccount(await addCodexAccountOnHost(owner))
const accountId = justSignedInUnselectedHostAccount(await addCodexAccountOnHost(owner))
if (accountId) {
await selectCodexProviderAccount(owner, { accountId, runtime: 'host' })
}