Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(codex): stop showing Codex ready with a keyring login sessions cannot use (CHOO-3856) (#1083)

Christian McDermotte87604250833
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b18bf3ba..1e798a2ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -200,6 +200,13 @@ version of their own to them without also giving them a release of their own.
Existing duplicates are left as they are and can be reached by id.
#### Fixed
+- **An agent is told why a machine's CLI cannot be used.** When
+ `create_agent` or `update_agent_detail` was refused because a provider was
+ not logged in, it said the owner needed to log in, even when the machine had
+ reported a login its agents could not use, which logging in does not fix
+ (a Codex login in the OS keyring, say). The refusal now gives what the
+ machine said instead, and `list_machines` shows it as each provider's
+ `problem`.
- **The agent HTTP API answers a refused or malformed request with a 4xx, not
a 500.** Inviting an agent to a room the caller may not change answered 500
instead of 403, and so did looking up a room the agent is not in. A room
@@ -2112,6 +2119,31 @@ version of their own to them without also giving them a release of their own.
A host reading another host's ownership ticket while that host replaced or
deleted it got `EPERM` from Windows and exited. It now tries the read again
for a few seconds, as it already did for its own writes.
+- **Codex is no longer shown as ready with a login sessions cannot use.** A
+ ChatGPT login kept in the OS keyring passed Console's sign-in check, so
+ Codex showed as signed in while every session failed: a session takes that
+ login only from `auth.json`. The check now reports a login sessions cannot
+ reach as not signed in, and says why: a ChatGPT login or a Bedrock key
+ Codex keeps in the keyring, an `auth.json` Codex ignores because it is set
+ to use the keyring, and an API key in the keyring that Codex will not hand
+ over or that an administrator's Codex configuration stops Switch handing to
+ sessions. It gives the switch to file storage where that helps and names
+ the Codex home it checked (from `~` when it is under your home folder), and
+ when it cannot tell, it says so and why.
+ Otherwise an API key in the keyring still counts as signed in, since
+ sessions are handed it. The provider status card and the warning beside an
+ agent now show what the check said when a provider is not signed in,
+ instead of a generic line.
+- **Console stops offering a sign-in that cannot help.** When a provider's
+ check says signing in would not fix it (an administrator pinning where
+ Codex keeps logins, or a check that could not finish, say), the status
+ card, Settings → Agent providers and switch-buddy say it can't be used yet
+ and why, instead of "Not signed in" with the login command or a Sign in
+ button.
+- **A relative `CODEX_HOME` is refused.** Codex reads one from whichever
+ directory it starts in, which differed between Console's check and
+ Switch's sessions, so the two could look at different Codex homes. Both
+ now say to set an absolute path, and a session will not start with one.
- **Settings → Agent providers keeps this computer's report current.** It
prefers the report from the server Console is on, rereads it while open and
after the controller reports again, and the install section says so when
@@ -4113,6 +4145,10 @@ tags; see RELEASING.md.
### [Unreleased]
#### Added
+- **A provider report says when signing in would not help.** A provider
+ whose check says its login command would not fix the problem is reported
+ with `login_helps: false` beside `auth_problem`, so Console does not offer
+ the command. Absent otherwise, as before.
- **Provider logins given to the machine, on demand.** The controller makes an
X25519 keypair at enrollment (or on its next run, for one enrolled before)
and registers the public half. When its owner gives the machine a login
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts
index a7150d113..fd3c36df8 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.test.ts
@@ -77,7 +77,16 @@ describe('ProviderPrecheck', () => {
const file = JSON.stringify({
providers: [
{ status: { provider: 'claude', installed: true, auth: 'ok', checked_at: at(500) } },
- { status: { provider: 'codex', installed: true, auth: 'missing', checked_at: at(600) } },
+ {
+ status: {
+ provider: 'codex',
+ installed: true,
+ auth: 'missing',
+ checked_at: at(600),
+ auth_problem: 'An administrator pins where Codex keeps logins.',
+ login_helps: false,
+ },
+ },
{
status: {
provider: 'cursor',
@@ -92,8 +101,14 @@ describe('ProviderPrecheck', () => {
expect(await service.results()).toBeNull();
service.start();
expect(await service.results()).toEqual([
- { provider: 'claude', installed: true, auth: 'ok', problem: null },
- { provider: 'codex', installed: true, auth: 'missing', problem: null },
+ { provider: 'claude', installed: true, auth: 'ok', problem: null, loginHelps: true },
+ {
+ provider: 'codex',
+ installed: true,
+ auth: 'missing',
+ problem: 'An administrator pins where Codex keeps logins.',
+ loginHelps: false,
+ },
]);
advance(10 * 60 * 1000 + 1_000);
expect(await service.results()).toEqual([]);
diff --git a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts
index 7756a5921..277edcb20 100644
--- a/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts
+++ b/console/apps/switch-console-desktop/src/main/core/embedded-controller/provider-precheck.ts
@@ -1,3 +1,8 @@
+import {
+ type ControllerProviderReport,
+ providerReport,
+} from '@main/core/switch-servers/controller-provider-report';
+
/**
* Checks this computer's providers as onboarding opens, before it is enrolled
* as a machine anywhere, with the controller's own `precheck`: the same
@@ -23,13 +28,7 @@ export type ProviderPrecheckDeps = {
};
/** A provider as the precheck found it, in the terms a controller reports it to Switch. */
-export type PrecheckedProvider = {
- provider: string;
- installed: boolean;
- auth: 'ok' | 'expired' | 'missing' | 'unknown';
- /** Why its login does not work, in the controller's words; null when it said nothing. */
- problem: string | null;
-};
+export type PrecheckedProvider = ControllerProviderReport;
/** A check older than this is made again when asked; the controller takes none older either. */
const FRESH_MS = 10 * 60 * 1000;
@@ -102,21 +101,13 @@ export class ProviderPrecheck {
if (!Array.isArray(entries)) return [];
return entries.flatMap((entry): PrecheckedProvider[] => {
const status = (entry as { status?: Record<string, unknown> }).status;
- if (!status) return [];
- const { provider, installed, auth, checked_at: checkedAt, auth_problem: said } = status;
- if (
- typeof provider !== 'string' ||
- typeof installed !== 'boolean' ||
- (auth !== 'ok' && auth !== 'expired' && auth !== 'missing' && auth !== 'unknown') ||
- typeof checkedAt !== 'string'
- )
- return [];
+ const report = providerReport(status);
+ const checkedAt = status?.checked_at;
+ if (!report || typeof checkedAt !== 'string') return [];
// Checked before this session's start: a file left from an earlier one.
const at = Date.parse(checkedAt);
if (!(at >= this.startedAt! - 1000) || this.deps.now() - at >= FRESH_MS) return [];
- return [
- { provider, installed, auth, problem: typeof said === 'string' && said ? said : null },
- ];
+ return [report];
});
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
index 7375bbf52..09562f190 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.test.ts
@@ -27,23 +27,31 @@ function controller(patch: Partial<ManagementController> & { id: string }): Mana
describe('machineProvider', () => {
it('is ready only when installed and logged in', () => {
expect(
- machineProvider({ provider: 'claude', installed: true, auth: 'ok', problem: null })
+ machineProvider({
+ provider: 'claude',
+ installed: true,
+ auth: 'ok',
+ problem: null,
+ loginHelps: true,
+ })
).toEqual({
provider: 'claude',
ready: true,
problem: null,
detail: null,
+ loginHelps: true,
});
});
it('says why a provider is not ready', () => {
const problem = (installed: boolean, auth: 'ok' | 'expired' | 'missing' | 'unknown') =>
- machineProvider({ provider: 'codex', installed, auth, problem: null });
+ machineProvider({ provider: 'codex', installed, auth, problem: null, loginHelps: true });
expect(problem(false, 'ok')).toEqual({
provider: 'codex',
ready: false,
problem: 'not installed',
detail: null,
+ loginHelps: true,
});
expect(problem(true, 'missing').problem).toBe('not logged in');
expect(problem(true, 'expired').problem).toBe('login expired');
@@ -52,6 +60,7 @@ describe('machineProvider', () => {
ready: false,
problem: 'login not checked yet',
detail: null,
+ loginHelps: true,
});
});
@@ -62,14 +71,28 @@ describe('machineProvider', () => {
installed: true,
auth: 'unknown',
problem: 'Claude Code did not say whether it is signed in. It may be too old.',
+ loginHelps: true,
})
).toEqual({
provider: 'claude',
ready: false,
problem: 'login could not be checked',
detail: 'Claude Code did not say whether it is signed in. It may be too old.',
+ loginHelps: true,
});
});
+
+ it('passes on that signing in would not make a provider ready', () => {
+ expect(
+ machineProvider({
+ provider: 'codex',
+ installed: true,
+ auth: 'missing',
+ problem: 'An administrator pins where Codex keeps logins.',
+ loginHelps: false,
+ })
+ ).toMatchObject({ ready: false, problem: 'not logged in', loginHelps: false });
+ });
});
describe('ownedMachines', () => {
@@ -79,7 +102,9 @@ describe('ownedMachines', () => {
controller({
id: 'laptop',
kind: 'console',
- providers: [{ provider: 'claude', installed: true, auth: 'ok', problem: null }],
+ providers: [
+ { provider: 'claude', installed: true, auth: 'ok', problem: null, loginHelps: true },
+ ],
workspacesDir: '/data/workspaces',
os: null,
}),
@@ -95,7 +120,9 @@ describe('ownedMachines', () => {
name: 'laptop',
kind: 'console',
state: 'online',
- providers: [{ provider: 'claude', ready: true, problem: null, detail: null }],
+ providers: [
+ { provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true },
+ ],
workspacesDir: '/data/workspaces',
os: null,
local: { kind: 'this-computer' },
@@ -139,7 +166,7 @@ describe('ownedMachines', () => {
});
describe('thisComputerReport', () => {
- const claude = { provider: 'claude', ready: true, problem: null, detail: null };
+ const claude = { provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true };
function machine(patch: Partial<OwnedMachine>): OwnedMachine {
return {
id: 'mac',
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
index e5a925925..533151f5c 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/owned-machines.ts
@@ -1,7 +1,5 @@
-import type {
- ControllerProviderReport,
- ManagementController,
-} from '@main/core/switch-servers/gateway-client';
+import type { ControllerProviderReport } from '@main/core/switch-servers/controller-provider-report';
+import type { ManagementController } from '@main/core/switch-servers/gateway-client';
import {
isCloudMachine,
type MachineProvider,
@@ -33,6 +31,7 @@ export function machineProvider(report: ControllerProviderReport): MachineProvid
ready: problem === null,
problem,
detail: problem === null ? null : report.problem,
+ loginHelps: report.loginHelps,
};
}
diff --git a/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
index 7b270624b..f458b3cdb 100644
--- a/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/providers/add-a-provider.test.ts
@@ -101,7 +101,9 @@ describe('a provider added as a plugin and a runtime', () => {
name: 'Build box',
kind: 'linux',
state: 'online',
- providers: [{ provider: 'dummy', ready: true, problem: null, detail: null }],
+ providers: [
+ { provider: 'dummy', ready: true, problem: null, detail: null, loginHelps: true },
+ ],
acceptsLogins: false,
cloud: false,
workspacesDir: null,
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.test.ts
new file mode 100644
index 000000000..39e6c05f7
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { providerReport } from './controller-provider-report';
+
+describe('providerReport', () => {
+ const entry = { provider: 'codex', installed: true, auth: 'missing' };
+
+ it('reads whether signing in would help, offering it unless the controller says not', () => {
+ expect(providerReport({ ...entry, login_helps: false })?.loginHelps).toBe(false);
+ expect(providerReport(entry)?.loginHelps).toBe(true);
+ expect(providerReport({ ...entry, login_helps: 'no' })?.loginHelps).toBe(true);
+ });
+
+ it('keeps what the controller said, and reads a login state it does not know as unknown', () => {
+ expect(providerReport({ ...entry, auth: 'later', auth_problem: 'In the keyring.' })).toEqual({
+ provider: 'codex',
+ installed: true,
+ auth: 'unknown',
+ problem: 'In the keyring.',
+ loginHelps: true,
+ });
+ });
+
+ it('leaves out an entry that does not say which provider, or whether it is installed', () => {
+ expect(providerReport({ installed: true, auth: 'ok' })).toBeNull();
+ expect(providerReport({ provider: 'codex', auth: 'ok' })).toBeNull();
+ expect(providerReport(null)).toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.ts
new file mode 100644
index 000000000..11a0c6628
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller-provider-report.ts
@@ -0,0 +1,34 @@
+/** A provider as a controller reports it: installed, and whether its login works. */
+export type ControllerProviderReport = {
+ /** The Switch definition provider id (`claude`, `codex`, …). */
+ provider: string;
+ installed: boolean;
+ auth: 'ok' | 'expired' | 'missing' | 'unknown';
+ /** Why its login does not work, in the controller's words; null when it said nothing. */
+ problem: string | null;
+ /** False when signing in with the provider's login command would not fix `problem`. */
+ loginHelps: boolean;
+};
+
+const PROVIDER_AUTH_STATES: readonly ControllerProviderReport['auth'][] = [
+ 'ok',
+ 'expired',
+ 'missing',
+ 'unknown',
+];
+
+/** One provider status as a controller reports it, or null when it does not say which, or whether it is installed. */
+export function providerReport(entry: unknown): ControllerProviderReport | null {
+ if (!entry || typeof entry !== 'object') return null;
+ const { provider, installed, auth, auth_problem, login_helps } = entry as Record<string, unknown>;
+ if (typeof provider !== 'string' || typeof installed !== 'boolean') return null;
+ const known = PROVIDER_AUTH_STATES.find((state) => state === auth);
+ return {
+ provider,
+ installed,
+ auth: known ?? 'unknown',
+ problem: typeof auth_problem === 'string' && auth_problem ? auth_problem : null,
+ // A controller that does not send the field leaves the login command on offer.
+ loginHelps: login_helps !== false,
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
index c8244e326..c49bfb437 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -3057,6 +3057,13 @@ describe('agent management calls', () => {
},
{ provider: 'codex', installed: true, auth: 'something-new' },
{ provider: 'opencode', installed: false, auth: 'unknown' },
+ {
+ provider: 'cursor',
+ installed: true,
+ auth: 'missing',
+ auth_problem: 'Signing in again will not help.',
+ login_helps: false,
+ },
{ installed: true, auth: 'ok' },
'garbage',
],
@@ -3073,9 +3080,22 @@ describe('agent management calls', () => {
[
'reported',
[
- { provider: 'claude', installed: true, auth: 'ok', problem: null },
- { provider: 'codex', installed: true, auth: 'unknown', problem: null },
- { provider: 'opencode', installed: false, auth: 'unknown', problem: null },
+ { provider: 'claude', installed: true, auth: 'ok', problem: null, loginHelps: true },
+ { provider: 'codex', installed: true, auth: 'unknown', problem: null, loginHelps: true },
+ {
+ provider: 'opencode',
+ installed: false,
+ auth: 'unknown',
+ problem: null,
+ loginHelps: true,
+ },
+ {
+ provider: 'cursor',
+ installed: true,
+ auth: 'missing',
+ problem: 'Signing in again will not help.',
+ loginHelps: false,
+ },
],
],
['silent', []],
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 44234748c..ddc4d7dad 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -7,6 +7,10 @@ import {
managedServerStoppedPhase,
noteManagedServerUnanswered,
} from '@main/core/managed-switch-server/managed-server-status';
+import {
+ type ControllerProviderReport,
+ providerReport,
+} from '@main/core/switch-servers/controller-provider-report';
import { rememberBridgePlatforms } from '@main/core/telemetry/bridge-platform';
import { assertedTenant } from '@main/core/workspaces/asserted-tenant';
import { type CloudMachine, cloudMachineSchema } from '@shared/core/cloud-agents/cloud-agents';
@@ -3739,16 +3743,6 @@ export type ManagementController = {
sealingKey: { key: string; keyId: string } | null;
};
-/** A provider as a controller reports it: installed, and whether its login works. */
-export type ControllerProviderReport = {
- /** The Switch definition provider id (`claude`, `codex`, …). */
- provider: string;
- installed: boolean;
- auth: 'ok' | 'expired' | 'missing' | 'unknown';
- /** Why its login does not work, in the controller's words; null when it said nothing. */
- problem: string | null;
-};
-
/** A managed agent as the owner's list shows it. */
export type ManagedAgent = {
agentId: string;
@@ -3960,13 +3954,6 @@ export async function fetchMachineOperation(
return { state: found.state, error: found.result?.error ?? null };
}
-const PROVIDER_AUTH_STATES: readonly ControllerProviderReport['auth'][] = [
- 'ok',
- 'expired',
- 'missing',
- 'unknown',
-];
-
/**
* The providers in a controller's last status report. An entry that does not
* say which provider it is, or whether it is installed, is left out; a login
@@ -3976,19 +3963,9 @@ function providerReports(status: unknown): ControllerProviderReport[] {
if (!status || typeof status !== 'object') return [];
const providers = (status as { providers?: unknown }).providers;
if (!Array.isArray(providers)) return [];
- return providers.flatMap((entry: unknown): ControllerProviderReport[] => {
- if (!entry || typeof entry !== 'object') return [];
- const { provider, installed, auth, auth_problem } = entry as Record<string, unknown>;
- if (typeof provider !== 'string' || typeof installed !== 'boolean') return [];
- const known = PROVIDER_AUTH_STATES.find((state) => state === auth);
- return [
- {
- provider,
- installed,
- auth: known ?? 'unknown',
- problem: typeof auth_problem === 'string' && auth_problem ? auth_problem : null,
- },
- ];
+ return providers.flatMap((entry: unknown) => {
+ const report = providerReport(entry);
+ return report ? [report] : [];
});
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.test.ts
index e0e573544..be1916e63 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.test.ts
@@ -60,6 +60,11 @@ describe('local Codex subscription detection', () => {
await writeFile(localProviderAuthPath('codex'), JSON.stringify(value));
await expect(localSignIn('codex')).rejects.toThrow('Sign in to Codex with ChatGPT');
});
+ it('refuses a relative CODEX_HOME, as sessions and the sign-in check do', () => {
+ vi.stubEnv('CODEX_HOME', '.codex-work');
+ expect(() => localProviderAuthPath('codex')).toThrow('Set CODEX_HOME to an absolute path.');
+ });
+
it('rejects oversized files before reading their contents', async () => {
await writeFile(localProviderAuthPath('codex'), 'x'.repeat(16385));
await expect(localSignIn('codex')).rejects.toThrow('smaller than 16 KiB');
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.ts
index a6e98e800..7431eb07d 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/local-provider-sign-in.ts
@@ -2,6 +2,7 @@ import { open } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
+import { codexSourceHome } from '@switch-console/agent-providers';
import { z } from 'zod';
import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';
import { localOpenCodeDatabasePath, readOpenCodeConsole } from './local-opencode-sign-in';
@@ -21,7 +22,7 @@ export type LocalSignInProvider = 'codex' | 'opencode' | 'antigravity';
export function localProviderAuthPath(provider: LocalSignInProvider): string {
switch (provider) {
case 'codex':
- return join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'auth.json');
+ return join(codexSourceHome(process.env), 'auth.json');
case 'opencode':
return join(
process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share'),
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
index 9f959e9ba..bb7e90ed1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.test.ts
@@ -82,7 +82,7 @@ describe('managedAgentState', () => {
const LAPTOP: OwnedMachine = {
...AGENT.machine!,
local: { kind: 'this-computer' },
- providers: [{ provider: 'claude', ready: true, problem: null, detail: null }],
+ providers: [{ provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true }],
acceptsLogins: false,
cloud: false,
workspacesDir: null,
@@ -137,11 +137,36 @@ describe('machineProblem', () => {
expect(
machineProblem(AGENT, {
...LAPTOP,
- providers: [{ provider: 'claude', ready: false, problem: 'not logged in', detail: null }],
+ providers: [
+ {
+ provider: 'claude',
+ ready: false,
+ problem: 'not logged in',
+ detail: null,
+ loginHelps: true,
+ },
+ ],
})
).toBe('Claude Code is not ready on laptop: not logged in.');
});
+ it('says what the machine said about a provider that is not ready', () => {
+ expect(
+ machineProblem(AGENT, {
+ ...LAPTOP,
+ providers: [
+ {
+ provider: 'claude',
+ ready: false,
+ problem: 'not logged in',
+ detail: 'Its login is in the OS keyring.',
+ loginHelps: true,
+ },
+ ],
+ })
+ ).toBe('Claude Code is not ready on laptop: not logged in. Its login is in the OS keyring.');
+ });
+
it('is quiet, not alarming, while the agent is stopped', () => {
const stopped = { ...AGENT, desiredState: 'stopped' as const, status: null };
expect(machineProblem(stopped, LAPTOP)).toBeNull();
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.ts
index b8e290411..aca33bfb2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-state.ts
@@ -80,7 +80,7 @@ export function machineProblem(
const provider = machine?.providers.find((entry) => entry.provider === agent.definition.provider);
if (provider && !provider.ready) {
const label = providerDisplayName(provider.provider) ?? provider.provider;
- return `${label} is not ready on ${name}${provider.problem ? `: ${provider.problem}` : ''}.`;
+ return `${label} is not ready on ${name}${provider.problem ? `: ${provider.problem}` : ''}.${provider.detail ? ` ${provider.detail}` : ''}`;
}
return null;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.test.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.test.ts
new file mode 100644
index 000000000..4e832e207
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.test.ts
@@ -0,0 +1,57 @@
+import type * as ReactQuery from '@tanstack/react-query';
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { beforeEach, expect, it, vi } from 'vitest';
+import type { MachineProvider } from '@shared/core/managed-agents/managed-agents';
+
+const report = vi.hoisted(() => ({ provider: null as MachineProvider | null }));
+vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+vi.mock('@renderer/lib/stores/use-this-computer-report', () => ({
+ useThisComputerReport: () => ({
+ isPending: false,
+ data: { serverId: 'server', providers: report.provider ? [report.provider] : [] },
+ }),
+ recheckThisComputer: async () => {},
+}));
+vi.mock('@tanstack/react-query', async (actual) => ({
+ ...(await actual<typeof ReactQuery>()),
+ useQueryClient: () => ({}),
+ useMutation: () => ({ isPending: false, mutate: () => {} }),
+}));
+vi.mock('@shared/core/providers/agent-provider-registry', () => ({
+ getProvider: () => ({ name: 'Codex', loginCommand: 'codex login' }),
+}));
+
+const { ThisComputerProviderStatus } = await import('./this-computer-provider-status');
+
+const render = () =>
+ renderToStaticMarkup(React.createElement(ThisComputerProviderStatus, { providerId: 'codex' }));
+
+const notSignedIn = (patch: Partial<MachineProvider>): MachineProvider => ({
+ provider: 'codex',
+ ready: false,
+ problem: 'not logged in',
+ detail: null,
+ loginHelps: true,
+ ...patch,
+});
+
+beforeEach(() => {
+ report.provider = null;
+});
+
+it('suggests the login command for a provider that is not signed in', () => {
+ report.provider = notSignedIn({});
+ expect(render()).toContain('codex login');
+});
+
+it('does not suggest it when the controller says signing in would not help', () => {
+ report.provider = notSignedIn({
+ detail: 'An administrator pins where Codex keeps logins.',
+ loginHelps: false,
+ });
+ const html = render();
+ expect(html).toContain('An administrator pins where Codex keeps logins.');
+ expect(html).toContain('Can’t be used yet');
+ expect(html).not.toContain('codex login');
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx
index b9824a7cf..c5c678370 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-provider-status.tsx
@@ -76,6 +76,7 @@ export function ThisComputerProviderStatus({
)}
{!recheck.isPending &&
!reported.ready &&
+ reported.loginHelps &&
provider &&
reported.problem !== 'not installed' && (
<p className="mt-2 text-foreground-muted">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts
index ffd22dffd..ef28fa038 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.test.ts
@@ -8,7 +8,14 @@ import {
} from './this-computer-status';
function reported(patch: Partial<MachineProvider>): MachineProvider {
- return { provider: 'claude', ready: false, problem: null, detail: null, ...patch };
+ return {
+ provider: 'claude',
+ ready: false,
+ problem: null,
+ detail: null,
+ loginHelps: true,
+ ...patch,
+ };
}
describe('Settings → Agent providers on this computer', () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts
index 629ec93aa..8438a1f1c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/this-computer-status.ts
@@ -47,7 +47,7 @@ export function reportedHeadline(reported: MachineProvider): string {
case 'not installed':
return 'CLI not installed';
case 'not logged in':
- return 'Not signed in';
+ return reported.loginHelps ? 'Not signed in' : 'Can’t be used yet';
case 'login expired':
return 'Sign-in expired';
case 'login not checked yet':
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
index e18acbbbe..84c15449d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.test.ts
@@ -30,10 +30,28 @@ describe('buddyProviders', () => {
const states = buddyProviders(
PROVIDERS,
machine([
- { provider: 'claude', ready: true, problem: null, detail: null },
- { provider: 'codex', ready: false, problem: 'not logged in', detail: null },
- { provider: 'opencode', ready: false, problem: 'not installed', detail: null },
- { provider: 'cursor', ready: false, problem: 'login not checked yet', detail: null },
+ { provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true },
+ {
+ provider: 'codex',
+ ready: false,
+ problem: 'not logged in',
+ detail: null,
+ loginHelps: true,
+ },
+ {
+ provider: 'opencode',
+ ready: false,
+ problem: 'not installed',
+ detail: null,
+ loginHelps: true,
+ },
+ {
+ provider: 'cursor',
+ ready: false,
+ problem: 'login not checked yet',
+ detail: null,
+ loginHelps: true,
+ },
])
);
expect(states.map((p) => [p.id, p.state])).toEqual([
@@ -54,12 +72,29 @@ describe('buddyProviders', () => {
ready: false,
problem: 'login could not be checked',
detail: 'It may be too old.',
+ loginHelps: true,
},
])
);
expect(claude).toMatchObject({ id: 'claude', state: 'sign-in', detail: 'It may be too old.' });
});
+ it('passes on that signing in would not make a provider ready', () => {
+ const [, codex] = buddyProviders(
+ PROVIDERS,
+ machine([
+ {
+ provider: 'codex',
+ ready: false,
+ problem: 'not logged in',
+ detail: 'An administrator pins where Codex keeps logins.',
+ loginHelps: false,
+ },
+ ])
+ );
+ expect(codex).toMatchObject({ id: 'codex', state: 'sign-in', loginHelps: false });
+ });
+
it('is still checking everything before this computer reports', () => {
expect(buddyProviders(PROVIDERS, null).every((p) => p.state === 'checking')).toBe(true);
});
@@ -71,6 +106,7 @@ describe('startButtons', () => {
...provider,
state: entries[provider.id] ?? 'checking',
detail: null,
+ loginHelps: true,
}));
const ids = (buttons: BuddyProvider[] | null) => buttons?.map((provider) => provider.id) ?? null;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
index 17c72bd7f..f9ba7f4c8 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-providers.ts
@@ -17,6 +17,8 @@ export type BuddyProvider = {
state: BuddyProviderState;
/** What the machine said about its login, when it is not ready; null when nothing. */
detail: string | null;
+ /** False when signing in would not make it ready: `detail` says what would. */
+ loginHelps: boolean;
};
export function buddyProviders(
@@ -34,7 +36,13 @@ export function buddyProviders(
: reported.problem === 'login not checked yet'
? 'checking'
: 'sign-in';
- return { id: provider.id, name: provider.name, state, detail: reported?.detail ?? null };
+ return {
+ id: provider.id,
+ name: provider.name,
+ state,
+ detail: reported?.detail ?? null,
+ loginHelps: reported?.loginHelps ?? true,
+ };
});
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx
index 5dda6de52..c96e9b3a4 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/provider-cards.tsx
@@ -74,7 +74,9 @@ export function ProviderCard({
)}
>
{provider.state === 'checking' && <Spinner className="size-3" />}
- {TAG[provider.state]}
+ {provider.state === 'sign-in' && !provider.loginHelps
+ ? 'Can’t be used yet'
+ : TAG[provider.state]}
</span>
</span>
</button>
@@ -145,6 +147,27 @@ export function SelectedPanel({
);
case 'sign-in': {
const running = login !== null && login.ended === null;
+ // A sign-in already under way stays, with its Cancel, whatever the report says now.
+ if (!provider.loginHelps && !running)
+ return (
+ <>
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-foreground">
+ {provider.name} can’t be used on this computer yet
+ </p>
+ {provider.detail && (
+ <p className="text-xs text-foreground-warning">{provider.detail}</p>
+ )}
+ </div>
+ <div>
+ <Button variant="ghost" onClick={onCheckAgain} disabled={busy !== null}>
+ {busy === 'check' && <Spinner className="size-3.5" />}
+ Check again
+ </Button>
+ </div>
+ {checked && <p className="text-xs text-foreground-muted">{checked}</p>}
+ </>
+ );
const links = login ? linksIn(login.lines) : [];
return (
<>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.test.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.test.ts
index 86444b64d..8dbeaa2d5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.test.ts
@@ -19,7 +19,7 @@ function machine(overrides: Partial<OwnedMachine>): OwnedMachine {
name: 'laptop',
kind: 'console',
state: 'online',
- providers: [{ provider: 'claude', ready: true, problem: null, detail: null }],
+ providers: [{ provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true }],
acceptsLogins: true,
cloud: false,
workspacesDir: '/home/me/.switch/agents',
@@ -75,7 +75,9 @@ describe('machineFor', () => {
const coder = machine({
id: 'm4',
name: 'cluster',
- providers: [{ provider: 'codex', ready: true, problem: null, detail: null }],
+ providers: [
+ { provider: 'codex', ready: true, problem: null, detail: null, loginHelps: true },
+ ],
});
// "local" or an SSH host is this Console's idea: the server's $first stands in.
expect(machineFor([BOX, coder, LAPTOP], 'local', 'claude', true)).toBe(LAPTOP);
@@ -96,12 +98,37 @@ describe('machineProblem', () => {
expect(
machineProblem(
machine({
- providers: [{ provider: 'claude', ready: false, problem: 'not logged in', detail: null }],
+ providers: [
+ {
+ provider: 'claude',
+ ready: false,
+ problem: 'not logged in',
+ detail: null,
+ loginHelps: true,
+ },
+ ],
}),
'claude',
'a'
)
).toBe('claude on laptop is not ready: not logged in.');
+ expect(
+ machineProblem(
+ machine({
+ providers: [
+ {
+ provider: 'claude',
+ ready: false,
+ problem: 'not logged in',
+ detail: 'Its login is in the OS keyring.',
+ loginHelps: true,
+ },
+ ],
+ }),
+ 'claude',
+ 'a'
+ )
+ ).toBe('claude on laptop is not ready: not logged in. Its login is in the OS keyring.');
expect(machineProblem(LAPTOP, 'claude', 'a')).toBeNull();
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.ts
index 83622c972..7ba4f3fda 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/managed-run.ts
@@ -80,7 +80,7 @@ export function machineProblem(
const entry = machine.providers.find((p) => p.provider === provider);
if (!entry) return `${provider} is not installed on ${machine.name}.`;
if (!entry.ready)
- return `${provider} on ${machine.name} is not ready${entry.problem ? `: ${entry.problem}` : ''}.`;
+ return `${provider} on ${machine.name} is not ready${entry.problem ? `: ${entry.problem}` : ''}.${entry.detail ? ` ${entry.detail}` : ''}`;
return null;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.test.ts
index 0acd2e8ee..b99b85280 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.test.ts
@@ -60,6 +60,32 @@ it('suggests signing in when the CLI says it is signed out', () => {
expect(render(false)).toContain('claude auth login');
});
+it('does not suggest signing in when the check says it would not help', () => {
+ const pinned = 'An administrator pins where Codex keeps logins.';
+ query.data = {
+ installed: true,
+ status: 'unauthenticated',
+ message: pinned,
+ models: [],
+ loginHelps: false,
+ };
+
+ const html = render(false);
+
+ expect(html).toContain(pinned);
+ expect(html).toContain('Can’t be used yet');
+ expect(html).not.toContain('Not signed in');
+ expect(html).not.toContain('claude auth login');
+});
+
+it('says why a sign-in sessions cannot use counts as signed out', () => {
+ const keyring = 'The login is in the OS keyring, which sessions cannot use.';
+ query.data = { installed: true, status: 'unauthenticated', message: keyring, models: [] };
+
+ expect(render(false)).toContain(keyring);
+ expect(render(true)).toContain(`title="${keyring}"`);
+});
+
it('gives no reason when signed in', () => {
query.data = { installed: true, status: 'authenticated', message: 'ok', models: [] };
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
index 0fa5a158a..1e7b83e05 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
@@ -50,10 +50,11 @@ export function useProviderReadiness(
/** What is wrong with a provider on a machine, in a few words, or null when nothing is known to be. */
export function providerProblem(
- data: { installed: boolean | null; status: string } | undefined
+ data: { installed: boolean | null; status: string; loginHelps?: boolean } | undefined
): string | null {
if (!data) return null;
if (data.installed === false) return 'CLI not installed';
+ if (data.status === 'unauthenticated' && data.loginHelps === false) return 'Can’t be used yet';
if (data.status === 'unauthenticated') return 'Not signed in';
if (data.status === 'unconfigured') return 'No backend configured';
return null;
@@ -86,7 +87,9 @@ export function ProviderConnectionStatus({
: missing
? 'CLI not installed'
: data?.status === 'unauthenticated'
- ? 'Not signed in'
+ ? data.loginHelps === false
+ ? 'Can’t be used yet'
+ : 'Not signed in'
: data?.status === 'unconfigured'
? 'No backend configured'
: ready
@@ -99,13 +102,14 @@ export function ProviderConnectionStatus({
? null
: query.error
? 'Could not reach this host. Check the connection and try again.'
- : data?.status === 'unauthenticated'
- ? 'Sign in to use this provider.'
- : (data?.message ?? null);
+ : (data?.message ?? null);
// Only a CLI that answered "signed out" (or "no backend") is fixed by its
- // login command. An unknown status means the check itself could not run,
- // and the reason says what to do instead.
- const loginMayHelp = data?.status === 'unauthenticated' || data?.status === 'unconfigured';
+ // login command, and not when the check says signing in would not help. An
+ // unknown status means the check itself could not run, and the reason says
+ // what to do instead.
+ const loginMayHelp =
+ (data?.status === 'unauthenticated' || data?.status === 'unconfigured') &&
+ data.loginHelps !== false;
const Icon = checking ? Loader2 : ready ? CheckCircle2 : CircleAlert;
const tone = checking || ready ? 'text-foreground-muted' : 'text-foreground-warning';
if (compact)
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts
index dd6d546c7..eb0af2461 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts
@@ -4,6 +4,14 @@ import { beforeEach, expect, it, vi } from 'vitest';
const readiness = vi.hoisted(() => ({ data: undefined as unknown, enabled: [] as boolean[] }));
vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+// Rendered in place, so the tooltip's text is in the markup.
+vi.mock('@renderer/lib/ui/tooltip', () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) =>
+ React.createElement(React.Fragment, null, children),
+ TooltipTrigger: ({ render }: { render: React.ReactNode }) => render,
+ TooltipContent: ({ children }: { children: React.ReactNode }) =>
+ React.createElement('span', null, children),
+}));
vi.mock('./provider-connection-status', async (importOriginal) => ({
...(await importOriginal<object>()),
useProviderReadiness: (_p: string, _h: string | null, _d: string, enabled: boolean) => {
@@ -37,6 +45,15 @@ it('warns when the provider is not signed in or not installed', () => {
expect(render()).toContain('CLI not installed on box');
});
+it("gives the check's own reason a provider is not signed in", () => {
+ readiness.data = {
+ installed: true,
+ status: 'unauthenticated',
+ message: 'The login is in the OS keyring, which sessions cannot use.',
+ };
+ expect(render()).toContain('The login is in the OS keyring, which sessions cannot use.');
+});
+
it('shows nothing when the provider is ready or the check could not tell', () => {
readiness.data = { installed: true, status: 'authenticated', message: null };
expect(render()).toBe('');
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx
index 30ee8acff..6281674b0 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx
@@ -26,12 +26,7 @@ export function ProviderIssueIndicator({
const provider = getProvider(providerId);
const name = provider?.name ?? providerId;
const where = sshHost ? `on ${sshHost}` : 'on this computer';
- const fix =
- data?.installed === false
- ? `Install the ${name} CLI ${where}.`
- : data?.status === 'unauthenticated' && provider
- ? `Run \`${provider.loginCommand}\` ${where}.`
- : data?.message;
+ const fix = data?.installed === false ? `Install the ${name} CLI ${where}.` : data?.message;
return (
<Tooltip>
<TooltipTrigger
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
index 4a9c36c86..412def2e8 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-agent-page.test.tsx
@@ -105,7 +105,7 @@ const AGENT: ManagedAgentView = {
const LAPTOP: OwnedMachine = {
...AGENT.machine!,
local: { kind: 'this-computer' },
- providers: [{ provider: 'claude', ready: true, problem: null, detail: null }],
+ providers: [{ provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true }],
acceptsLogins: false,
cloud: false,
workspacesDir: '/home/me/workspaces',
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
index fd9c9b646..571474fba 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/new-agent-managed-machine.test.tsx
@@ -319,9 +319,15 @@ const BOX: OwnedMachine = {
workspacesDir: null,
os: null,
providers: [
- { provider: 'claude', ready: true, problem: null, detail: null },
- { provider: 'codex', ready: false, problem: 'not logged in', detail: null },
- { provider: 'opencode', ready: false, problem: 'not installed', detail: null },
+ { provider: 'claude', ready: true, problem: null, detail: null, loginHelps: true },
+ { provider: 'codex', ready: false, problem: 'not logged in', detail: null, loginHelps: true },
+ {
+ provider: 'opencode',
+ ready: false,
+ problem: 'not installed',
+ detail: null,
+ loginHelps: true,
+ },
],
};
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
index ee6ee41b3..241aafc71 100644
--- a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
@@ -80,6 +80,8 @@ export type MachineProvider = {
problem: string | null;
/** What the machine said about it, when it said more than `problem` does. */
detail: string | null;
+ /** False when signing in with the provider's login command would not make it ready. */
+ loginHelps: boolean;
};
/**
diff --git a/console/packages/agent-controller/src/schemas.ts b/console/packages/agent-controller/src/schemas.ts
index fa807a5a1..ee5801531 100644
--- a/console/packages/agent-controller/src/schemas.ts
+++ b/console/packages/agent-controller/src/schemas.ts
@@ -211,6 +211,8 @@ export const providerStatusSchema = z.object({
version_problem: z.string().max(300).optional(),
/** Why the provider's login does not work, or a login given to the machine is not used, in so many words. */
auth_problem: z.string().max(300).optional(),
+ /** False when signing in with the provider's login command would not fix what `auth_problem` says. */
+ login_helps: z.boolean().optional(),
});
export type ProviderStatus = z.infer<typeof providerStatusSchema>;
diff --git a/console/packages/agent-controller/src/status.test.ts b/console/packages/agent-controller/src/status.test.ts
index 5c4bd5872..3b34ea1ef 100644
--- a/console/packages/agent-controller/src/status.test.ts
+++ b/console/packages/agent-controller/src/status.test.ts
@@ -230,6 +230,26 @@ describe('providerStatusFrom', () => {
models: [],
});
+ it('says when signing in would not fix the login, and only then', () => {
+ const pinned = {
+ status: 'unauthenticated' as const,
+ message: 'An administrator pins where Codex keeps logins.',
+ models: [],
+ loginHelps: false,
+ };
+ expect(providerStatusFrom('codex', located, pinned, at)).toMatchObject({
+ auth: 'missing',
+ auth_problem: 'An administrator pins where Codex keeps logins.',
+ login_helps: false,
+ });
+ expect(
+ providerStatusFrom('codex', located, readiness('unauthenticated'), at)
+ ).not.toHaveProperty('login_helps');
+ expect(
+ providerStatusFrom('codex', located, { ...pinned, status: 'unknown' as const }, at)
+ ).toMatchObject({ auth: 'unknown', login_helps: false });
+ });
+
it('maps a missing CLI and each readiness answer', () => {
expect(providerStatusFrom('claude', null, null, at)).toMatchObject({
installed: false,
@@ -531,6 +551,42 @@ describe('ProviderStatuses with logins given to the machine', () => {
expect(runtime.loginProbes).toEqual([]);
});
+ it('keeps "signing in would not help" only beside the message it was said of', async () => {
+ const pinned = {
+ status: 'unauthenticated' as const,
+ message: 'An administrator pins where Codex keeps logins.',
+ models: [],
+ loginHelps: false,
+ };
+ const signsIn = new FakeRuntime();
+ signsIn.readiness = pinned;
+ answer = sealedAnswer('sk-given', 1, 'setup-token', 'codex');
+ const given = await build(signsIn).check('codex');
+ expect(given).toMatchObject({ auth: 'ok', auth_source: 'sealed' });
+ expect(given).not.toHaveProperty('login_helps');
+ // The machine's own login is not the one agents use now.
+ expect(given).not.toHaveProperty('auth_problem');
+
+ const refused = new FakeRuntime();
+ refused.readiness = pinned;
+ refused.loginReadiness = { status: 'unauthenticated', message: 'Expired.', models: [] };
+ expect(await build(refused).check('codex')).not.toHaveProperty('login_helps');
+
+ // The machine's own login is still the one in use, and signing in still would not fix it.
+ const unopened = new FakeRuntime();
+ unopened.readiness = pinned;
+ answer = sealedAnswer(vertexCredentialFixture(), 1, 'vertex', 'codex');
+ const status = await build(unopened).check('codex');
+ expect(status.auth_problem).toContain('Only Claude signs in through Vertex AI.');
+ expect(status).toMatchObject({ auth: 'missing', login_helps: false });
+
+ const none = new FakeRuntime();
+ none.readiness = pinned;
+ answer = null;
+ reachable = false;
+ expect(await build(none).check('codex')).toMatchObject({ login_helps: false });
+ });
+
it('says why a given login is not used', async () => {
const runtime = new FakeRuntime();
runtime.readiness = { status: 'unauthenticated', message: '', models: [] };
diff --git a/console/packages/agent-controller/src/status.ts b/console/packages/agent-controller/src/status.ts
index 9329f2f60..cacf92621 100644
--- a/console/packages/agent-controller/src/status.ts
+++ b/console/packages/agent-controller/src/status.ts
@@ -215,9 +215,16 @@ export function providerStatusFrom(
auth_source: null,
reason: 'provider_login_missing',
...said,
+ ...(readiness.loginHelps === false ? { login_helps: false } : {}),
};
case 'unknown':
- return { ...base, auth: 'unknown', auth_source: null, ...said };
+ return {
+ ...base,
+ auth: 'unknown',
+ auth_source: null,
+ ...said,
+ ...(readiness.loginHelps === false ? { login_helps: false } : {}),
+ };
}
}
@@ -343,7 +350,14 @@ export class ProviderStatuses {
const signedIn = await this.probe(provider, located.path, given.login);
if (signedIn?.status === 'authenticated') {
login = given.login;
- status = { ...status, auth: 'ok', auth_source: 'sealed', reason: undefined };
+ // What the machine's own check said is not about the login agents use now.
+ status = {
+ ...status,
+ auth: 'ok',
+ auth_source: 'sealed',
+ reason: undefined,
+ auth_problem: undefined,
+ };
} else {
problem = {
code: 'provider_login_expired',
@@ -375,6 +389,9 @@ export class ProviderStatuses {
}
}
if (status.reason === undefined) delete status.reason;
+ if (status.auth_problem === undefined) delete status.auth_problem;
+ // Said of the machine's own login, which a given login now stands in for.
+ if (status.auth_source === 'sealed') delete status.login_helps;
const previous = this.entries.get(provider);
// A check that started before the one already recorded knows less.
if (previous && previous.sequence > sequence) return previous.status;
@@ -513,6 +530,7 @@ function fingerprintProvider(status: ProviderStatus): string {
status.auth,
status.reason ?? null,
status.auth_problem ?? null,
+ status.login_helps ?? null,
]);
}
@@ -729,6 +747,7 @@ export function statusFingerprint(report: Omit<StatusReport, 'seq'>): string {
p.auth,
p.reason,
p.auth_problem,
+ p.login_helps,
]),
tools: report.tools.map((t) => [t.tool, t.state, t.reason]),
agents: report.agents.map((a) => [
diff --git a/console/packages/agent-providers/src/codex/codex-adapter.ts b/console/packages/agent-providers/src/codex/codex-adapter.ts
index 80379ec77..cc5544c90 100644
--- a/console/packages/agent-providers/src/codex/codex-adapter.ts
+++ b/console/packages/agent-providers/src/codex/codex-adapter.ts
@@ -36,7 +36,12 @@ import {
import { CumulativeUsage, mergeUsage, type UsageCounts } from '../usage';
import { featureArgs, mcpServerConfigArgs, tomlString } from './config-args';
import { mapCodexItem } from './item-mapping';
-import { CODEX_KEYRING_READ_TIMEOUT_MS, readCodexKeyringApiKey } from './keyring-login';
+import {
+ CODEX_EPHEMERAL_LOGIN_ARGS,
+ CODEX_KEYRING_READ_TIMEOUT_MS,
+ readCodexCredentialStore,
+ readCodexKeyringApiKey,
+} from './keyring-login';
import {
CODEX_CLIENT_METHODS,
CODEX_CLIENT_NOTIFICATIONS,
@@ -82,14 +87,6 @@ export const CODEX_KEYRING_SIGN_IN_REQUIRED =
'the login it keeps in the OS keyring: the keychain may be locked, or access to its ' +
'"Codex Auth" item may have been denied.';
-/**
- * Where a session that is handed a keyring login keeps it: in the memory of
- * its own Codex process, never in a file or the keyring. Given on the command
- * line, it outranks the user's and the project's configuration, and survives
- * Codex falling back to its defaults over a configuration it cannot read.
- */
-const EPHEMERAL_LOGIN_ARGS = ['-c', 'cli_auth_credentials_store="ephemeral"'];
-
const accountSchema = z.object({
account: z.unknown().nullable(),
requiresOpenaiAuth: z.boolean(),
@@ -442,7 +439,7 @@ export class CodexAdapter implements ProviderAdapter {
}
const client = new StdioJsonRpcClient({
command: this.binaryPath,
- args: handOver ? [...args, ...EPHEMERAL_LOGIN_ARGS] : args,
+ args: handOver ? [...args, ...CODEX_EPHEMERAL_LOGIN_ARGS] : args,
cwd: input.cwd,
env,
logger: this.logger,
@@ -825,10 +822,7 @@ export class CodexAdapter implements ProviderAdapter {
cwd: string,
login: CodexKeyringLogin
): Promise<void> {
- const { config } = z
- .object({ config: z.object({ cli_auth_credentials_store: z.unknown() }) })
- .parse(await client.request('config/read', { cwd }));
- const store = config.cli_auth_credentials_store;
+ const store = await readCodexCredentialStore(client, cwd);
if (store !== 'ephemeral')
throw new Error(
`Codex's configuration on the execution machine sets cli_auth_credentials_store to ${JSON.stringify(store ?? null)} for this session where Switch asked for "ephemeral" (an administrator's managed configuration or requirements can do this), so Switch did not hand the session the API key from the OS keyring: Codex would have saved another copy of it.`
diff --git a/console/packages/agent-providers/src/codex/home.test.ts b/console/packages/agent-providers/src/codex/home.test.ts
index 3e396401f..cc2468002 100644
--- a/console/packages/agent-providers/src/codex/home.test.ts
+++ b/console/packages/agent-providers/src/codex/home.test.ts
@@ -1,9 +1,14 @@
import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
+import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import { parse } from 'smol-toml';
import { afterEach, describe, expect, it } from 'vitest';
-import { prepareCodexSessionHome, withManagedCodexSandbox } from './home';
+import {
+ codexHomeNotAbsolute,
+ codexSourceHome,
+ prepareCodexSessionHome,
+ withManagedCodexSandbox,
+} from './home';
const roots: string[] = [];
afterEach(async () => {
@@ -104,6 +109,20 @@ it('links the user’s own Codex skills into a session home that has no skills f
expect(await readFile(join(home, 'skills', '.system', 'SKILL.md'), 'utf8')).toBe('system skill');
});
+describe('codexSourceHome', () => {
+ it('takes CODEX_HOME, else ~/.codex', () => {
+ expect(codexSourceHome({ CODEX_HOME: '/srv/codex' })).toBe('/srv/codex');
+ expect(codexSourceHome({})).toBe(join(homedir(), '.codex'));
+ });
+
+ it('refuses a relative CODEX_HOME rather than guess which directory it is from', () => {
+ expect(() => codexSourceHome({ CODEX_HOME: '.codex-work' })).toThrow(
+ codexHomeNotAbsolute('.codex-work')
+ );
+ expect(() => codexSourceHome({ CODEX_HOME: '~/.codex' })).toThrow('absolute path');
+ });
+});
+
describe('withManagedCodexSandbox', () => {
it('lets a managed agent write in its workspace, or anywhere when it bypasses permissions', () => {
expect(parse(withManagedCodexSandbox('web_search = true\n', 'approval-required'))).toEqual({
diff --git a/console/packages/agent-providers/src/codex/home.ts b/console/packages/agent-providers/src/codex/home.ts
index 67f761f3b..768914a2f 100644
--- a/console/packages/agent-providers/src/codex/home.ts
+++ b/console/packages/agent-providers/src/codex/home.ts
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from 'node:crypto';
import { chmod, copyFile, lstat, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
-import { join } from 'node:path';
+import { homedir } from 'node:os';
+import { isAbsolute, join } from 'node:path';
import { parse, stringify } from 'smol-toml';
import type { RuntimeMode } from '../adapter';
import { linkHomeAsset, linkSkills, optionalText } from '../host/provider-home';
@@ -38,7 +39,7 @@ export async function prepareCodexSessionHome(input: {
const home = join(input.root, key);
await mkdir(home, { recursive: true, mode: 0o700 });
await chmod(home, 0o700);
- const keyringLogin = !(await isFile(join(input.sourceHome, 'auth.json')));
+ const keyringLogin = !(await hasCodexAuthFile(input.sourceHome));
if (!keyringLogin) await copyCodexAuthenticationOnce(home, input.sourceHome);
const sourceConfig = await optionalText(join(input.sourceHome, 'config.toml'));
const config = { ...(sourceConfig ? parse(sourceConfig) : {}), ...parse(input.config) };
@@ -61,9 +62,27 @@ export async function prepareCodexSessionHome(input: {
return { home, keyringLogin };
}
-async function isFile(path: string): Promise<boolean> {
+export const codexHomeNotAbsolute = (home: string) =>
+ `Set CODEX_HOME to an absolute path. It is ${JSON.stringify(home)}, which Codex reads from whichever directory it starts in, so Switch cannot tell which Codex home its sessions would use.`;
+
+/**
+ * The Codex home a session takes its login and configuration from; sign-in
+ * checks look here too. A relative CODEX_HOME is refused rather than
+ * resolved: Codex reads one from whichever directory it starts in, and
+ * Console, the agent controller, a session's host and the Codex a check runs
+ * each start in a different one, so no one resolution would be the home both
+ * sessions and the check mean.
+ */
+export function codexSourceHome(env: Readonly<Record<string, string | undefined>>): string {
+ const configured = env.CODEX_HOME;
+ if (configured && !isAbsolute(configured)) throw new Error(codexHomeNotAbsolute(configured));
+ return configured || join(homedir(), '.codex');
+}
+
+/** Whether a Codex home keeps its login in auth.json, the only form a session copies. */
+export async function hasCodexAuthFile(home: string): Promise<boolean> {
try {
- return (await stat(path)).isFile();
+ return (await stat(join(home, 'auth.json'))).isFile();
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw new Error('Could not load the execution-host Codex login.', { cause: error });
diff --git a/console/packages/agent-providers/src/codex/keyring-login.test.ts b/console/packages/agent-providers/src/codex/keyring-login.test.ts
index 4d7e299ac..f1be2bbc5 100644
--- a/console/packages/agent-providers/src/codex/keyring-login.test.ts
+++ b/console/packages/agent-providers/src/codex/keyring-login.test.ts
@@ -290,6 +290,14 @@ describe('a Codex session with no login of its own', () => {
expect(methods(sessionServer())).not.toContain('account/login/start');
});
+ it('recognises a missing getAuthStatus as Codex reports it', async () => {
+ source.authStatus = {
+ error: { code: -32600, message: 'Invalid request: unknown variant `getAuthStatus`' },
+ };
+ const result = await start();
+ expect(result.error?.message).toContain('no longer answers getAuthStatus');
+ });
+
it('passes on what Codex said when it fails to report its login', async () => {
source.crash = 'fixture: keyring backend unavailable';
const result = await start();
diff --git a/console/packages/agent-providers/src/codex/keyring-login.ts b/console/packages/agent-providers/src/codex/keyring-login.ts
index 3f9f34a0b..39d6747a3 100644
--- a/console/packages/agent-providers/src/codex/keyring-login.ts
+++ b/console/packages/agent-providers/src/codex/keyring-login.ts
@@ -10,18 +10,51 @@ import { JsonRpcError, noopLogger, StdioJsonRpcClient } from '../transport/stdio
export const CODEX_KEYRING_READ_TIMEOUT_MS = 30_000;
const METHOD_NOT_FOUND = -32601;
+const INVALID_REQUEST = -32600;
+
+/**
+ * Whether Codex refused `method` because it does not have it. Codex answers
+ * that with -32600 naming the method as an unknown variant, not JSON-RPC's
+ * -32601; the same words about a parameter's value name the value instead.
+ */
+export function isUnknownCodexMethod(error: unknown, method: string): boolean {
+ return (
+ error instanceof JsonRpcError &&
+ (error.code === METHOD_NOT_FOUND ||
+ (error.code === INVALID_REQUEST && error.message.includes(`unknown variant \`${method}\``)))
+ );
+}
export const CODEX_FILE_STORE_WORKAROUND =
'Unless your organization enforces the keyring, set cli_auth_credentials_store = "file" in the ' +
'Codex config.toml on the execution machine, which keeps the login in plaintext, then run codex ' +
'login again and start a new session.';
+/**
+ * Where a session that is handed a keyring login keeps it: in the memory of
+ * its own Codex process, never in a file or the keyring. Given on the command
+ * line, it outranks the user's and the project's configuration, and survives
+ * Codex falling back to its defaults over a configuration it cannot read.
+ */
+export const CODEX_EPHEMERAL_LOGIN_ARGS = ['-c', 'cli_auth_credentials_store="ephemeral"'];
+
+/** Where the Codex behind `client` keeps logins, as its configuration for `cwd` resolves it. */
+export async function readCodexCredentialStore(
+ client: StdioJsonRpcClient,
+ cwd: string
+): Promise<unknown> {
+ const { config } = z
+ .object({ config: z.object({ cli_auth_credentials_store: z.unknown() }) })
+ .parse(await client.request('config/read', { cwd }));
+ return config.cli_auth_credentials_store;
+}
+
const accountSchema = z.object({
account: z.object({ type: z.string() }).nullable(),
requiresOpenaiAuth: z.boolean(),
});
-const authStatusSchema = z.object({
+export const codexAuthStatusSchema = z.object({
authMethod: z.string().nullable(),
authToken: z.string().nullish(),
});
@@ -115,13 +148,13 @@ async function readApiKey(client: StdioJsonRpcClient): Promise<string | null> {
throw new KeyringLoginError(
`Codex on the execution machine is signed in with ${loginKind(account.type)} and has no auth.json, so its login is likely in the OS keyring (cli_auth_credentials_store = "keyring" or "auto"). A Switch session can take a login from the keyring only when it is an API key. ${CODEX_FILE_STORE_WORKAROUND}`
);
- let status: z.infer<typeof authStatusSchema>;
+ let status: z.infer<typeof codexAuthStatusSchema>;
try {
- status = authStatusSchema.parse(
+ status = codexAuthStatusSchema.parse(
await client.request('getAuthStatus', { includeToken: true, refreshToken: false })
);
} catch (error) {
- if (error instanceof JsonRpcError && error.code === METHOD_NOT_FOUND)
+ if (isUnknownCodexMethod(error, 'getAuthStatus'))
throw new KeyringLoginError(
`This version of Codex cannot hand Switch the API key it keeps in the OS keyring: it no longer answers getAuthStatus. ${CODEX_FILE_STORE_WORKAROUND}`,
{ cause: error }
diff --git a/console/packages/agent-providers/src/codex/sign-in.test.ts b/console/packages/agent-providers/src/codex/sign-in.test.ts
new file mode 100644
index 000000000..756723a70
--- /dev/null
+++ b/console/packages/agent-providers/src/codex/sign-in.test.ts
@@ -0,0 +1,352 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, sep } from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type * as Protocol from '../transport/stdio-json-rpc';
+import { JsonRpcError } from '../transport/stdio-json-rpc';
+import { codexHomeNotAbsolute } from './home';
+import {
+ checkCodexSignIn,
+ codexKeyringApiKeyWithheld,
+ codexKeyringIgnoresAuthFile,
+ codexKeyringLoginUnusable,
+ codexKeyringStorePinned,
+} from './sign-in';
+
+/** How Codex answers a method it does not have. */
+const unknownMethod = (method: string) =>
+ new JsonRpcError(-32600, `Invalid request: unknown variant \`${method}\`, expected one of ...`);
+
+/**
+ * A Codex app-server per spawn: the home `initialize` reports, what
+ * `account/read` and `getAuthStatus` answer, and where `config/read` says
+ * logins are kept, for a plain spawn and for one asked to keep them in memory.
+ */
+const codex = vi.hoisted(() => ({
+ codexHome: undefined as string | null | undefined,
+ /** How long each method takes to answer; a Codex stopped first fails as an exit. */
+ delayMs: {} as Record<string, number>,
+ disposeError: null as Error | null,
+ account: null as unknown,
+ requiresOpenaiAuth: true,
+ authStatus: { authMethod: 'apikey', authToken: null } as unknown,
+ authStatusError: null as Error | null,
+ store: 'file' as unknown,
+ ephemeralStore: 'ephemeral' as unknown,
+ configReadError: null as Error | null,
+ events: [] as string[],
+}));
+vi.mock('../transport/stdio-json-rpc', async (original) => ({
+ ...(await original<typeof Protocol>()),
+ StdioJsonRpcClient: class {
+ private readonly name: string;
+ constructor(options: { args: string[] }) {
+ this.name = options.args.includes('cli_auth_credentials_store="ephemeral"')
+ ? 'ephemeral'
+ : 'plain';
+ codex.events.push(`start ${this.name}`);
+ }
+ private stopped: (() => void) | null = null;
+ private disposed = false;
+ async request(method: string) {
+ // As the real client does once its Codex is stopped.
+ if (this.disposed) throw new Error('Provider input is closed; command was not written.');
+ const delay = codex.delayMs[method];
+ if (delay)
+ await new Promise<void>((resolve, reject) => {
+ setTimeout(resolve, delay);
+ this.stopped = () => reject(new Error('provider process exited (signal SIGTERM)'));
+ });
+ if (method === 'initialize')
+ return codex.codexHome === undefined ? {} : { codexHome: codex.codexHome };
+ if (method === 'account/read')
+ return { account: codex.account, requiresOpenaiAuth: codex.requiresOpenaiAuth };
+ if (method === 'getAuthStatus') {
+ if (codex.authStatusError) throw codex.authStatusError;
+ return codex.authStatus;
+ }
+ if (method === 'config/read') {
+ if (codex.configReadError) throw codex.configReadError;
+ const store = this.name === 'ephemeral' ? codex.ephemeralStore : codex.store;
+ return { config: { cli_auth_credentials_store: store } };
+ }
+ throw unknownMethod(method);
+ }
+ notify() {}
+ async dispose() {
+ this.disposed = true;
+ codex.events.push(`stop ${this.name}`);
+ this.stopped?.();
+ if (codex.disposeError) throw codex.disposeError;
+ }
+ },
+}));
+
+let root: string;
+let home: string;
+
+beforeEach(async () => {
+ Object.assign(codex, {
+ codexHome: undefined,
+ delayMs: {},
+ disposeError: null,
+ account: null,
+ requiresOpenaiAuth: true,
+ authStatus: { authMethod: 'apikey', authToken: null },
+ authStatusError: null,
+ store: 'file',
+ ephemeralStore: 'ephemeral',
+ configReadError: null,
+ events: [],
+ });
+ root = await mkdtemp(join(tmpdir(), 'codex-sign-in-'));
+ home = join(root, 'codex-home');
+ await mkdir(home);
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+ await rm(root, { recursive: true, force: true });
+});
+
+const CHATGPT = { type: 'chatgpt', email: null, planType: 'plus' };
+const API_KEY = { type: 'apiKey' };
+const authFile = (dir = home) => writeFile(join(dir, 'auth.json'), '{}');
+const check = (env: Record<string, string> = { CODEX_HOME: home }) =>
+ checkCodexSignIn({ binaryPath: 'codex', cwd: root, env });
+
+it('reports a ChatGPT login with no auth.json behind it as unusable by sessions', async () => {
+ codex.account = CHATGPT;
+ expect(await check()).toEqual({
+ status: 'unauthenticated',
+ message: codexKeyringLoginUnusable(home),
+ models: [],
+ });
+});
+
+it('reports a ChatGPT login kept in auth.json as signed in', async () => {
+ await authFile();
+ codex.account = CHATGPT;
+ expect((await check()).status).toBe('authenticated');
+});
+
+it('reports an auth.json that Codex is set to ignore for the keyring as unusable', async () => {
+ await authFile();
+ codex.account = CHATGPT;
+ codex.store = 'keyring';
+ expect(await check()).toEqual({
+ status: 'unauthenticated',
+ message: codexKeyringIgnoresAuthFile(home),
+ models: [],
+ });
+});
+
+it('reads a Codex too old for config/read from the config.toml sessions inherit', async () => {
+ await authFile();
+ codex.account = CHATGPT;
+ codex.configReadError = unknownMethod('config/read');
+ expect((await check()).status).toBe('authenticated');
+ await writeFile(join(home, 'config.toml'), 'cli_auth_credentials_store = "keyring"\n');
+ expect((await check()).message).toBe(codexKeyringIgnoresAuthFile(home));
+});
+
+it('does not take a refused parameter for a missing method', async () => {
+ codex.account = API_KEY;
+ codex.authStatusError = new JsonRpcError(
+ -32600,
+ 'Invalid request: unknown variant `includeSecrets`, expected one of `includeToken`'
+ );
+ const result = await check();
+ expect(result.status).toBe('unknown');
+ expect(result.message).toContain('unknown variant `includeSecrets`');
+});
+
+it('reports an API key in the keyring as signed in when sessions can be handed it', async () => {
+ codex.account = API_KEY;
+ expect((await check()).status).toBe('authenticated');
+ // The second Codex starts only once the first has stopped.
+ expect(codex.events).toEqual(['start plain', 'stop plain', 'start ephemeral', 'stop ephemeral']);
+});
+
+it('reports an API key in the keyring as unusable when the session store is pinned', async () => {
+ codex.account = API_KEY;
+ codex.ephemeralStore = 'keyring';
+ expect(await check()).toEqual({
+ status: 'unauthenticated',
+ message: codexKeyringStorePinned(home, 'keyring'),
+ models: [],
+ // No sign-in changes what an administrator pinned.
+ loginHelps: false,
+ });
+});
+
+it('refuses a relative CODEX_HOME before starting Codex, as sessions do', async () => {
+ expect(await check({ CODEX_HOME: '.codex-work' })).toEqual({
+ status: 'unauthenticated',
+ message: codexHomeNotAbsolute('.codex-work'),
+ models: [],
+ loginHelps: false,
+ });
+ expect(codex.events).toEqual([]);
+});
+
+it('leaves signing in on offer where it is the last step of the fix', async () => {
+ codex.account = CHATGPT;
+ expect(await check()).not.toHaveProperty('loginHelps');
+});
+
+it('names a missing store as null rather than guessing at one', async () => {
+ codex.account = API_KEY;
+ codex.ephemeralStore = undefined;
+ expect((await check()).message).toBe(codexKeyringStorePinned(home, undefined));
+ expect(codexKeyringStorePinned(home, undefined)).toContain('to null for a session');
+});
+
+it('reports an API key in the keyring as unusable when Codex will not hand it over', async () => {
+ codex.account = API_KEY;
+ codex.authStatusError = unknownMethod('getAuthStatus');
+ expect((await check()).message).toBe(codexKeyringApiKeyWithheld(home));
+ codex.authStatusError = null;
+ codex.authStatus = { authMethod: 'chatgpt', authToken: null };
+ expect((await check()).message).toBe(codexKeyringApiKeyWithheld(home));
+});
+
+it('gives the cause when the hand-over cannot be checked', async () => {
+ codex.account = API_KEY;
+ codex.authStatusError = new JsonRpcError(-32603, 'keychain is locked');
+ const result = await check();
+ expect(result).toMatchObject({ status: 'unknown', loginHelps: false });
+ expect(result.message).toContain('keychain is locked');
+});
+
+it('reports a Bedrock key Codex keeps in the keyring as unusable', async () => {
+ codex.account = { type: 'amazonBedrock', usesCodexManagedCredentials: true };
+ codex.requiresOpenaiAuth = false;
+ expect((await check()).message).toBe(codexKeyringLoginUnusable(home));
+});
+
+it('says it cannot tell when Codex does not say what a Bedrock login runs on', async () => {
+ codex.account = { type: 'amazonBedrock' };
+ codex.requiresOpenaiAuth = false;
+ const result = await check();
+ expect(result.status).toBe('unknown');
+ expect(result.message).toContain('runs on AWS credentials or on a key Codex keeps');
+ codex.account = { type: 'amazonBedrock', usesCodexManagedCredentials: false };
+ expect((await check()).status).toBe('authenticated');
+});
+
+// A file where the home should be reads as ENOENT on Windows, not ENOTDIR.
+it.skipIf(process.platform === 'win32')(
+ 'says what went wrong when the Codex home cannot be checked',
+ async () => {
+ await rm(home, { recursive: true });
+ await writeFile(home, 'not a directory');
+ codex.account = CHATGPT;
+ const result = await check();
+ expect(result.status).toBe('unknown');
+ expect(result.message).toContain('ENOTDIR');
+ }
+);
+
+it('looks in the home Codex reports reading the login from', async () => {
+ const reported = join(root, 'reported-home');
+ await mkdir(reported);
+ await authFile(reported);
+ codex.codexHome = reported;
+ codex.account = CHATGPT;
+ expect((await check()).status).toBe('authenticated');
+});
+
+it('looks for auth.json in ~/.codex when Codex does not say and CODEX_HOME is not set', async () => {
+ vi.stubEnv('HOME', root);
+ vi.stubEnv('USERPROFILE', root);
+ codex.account = CHATGPT;
+ expect((await check({})).status).toBe('unauthenticated');
+ await mkdir(join(root, '.codex'));
+ await authFile(join(root, '.codex'));
+ expect((await check({})).status).toBe('authenticated');
+});
+
+it('falls back to CODEX_HOME when Codex reports its home as null', async () => {
+ await authFile();
+ codex.codexHome = null;
+ codex.account = CHATGPT;
+ expect((await check()).status).toBe('authenticated');
+});
+
+it('keeps what it read when a Codex will not stop afterwards', async () => {
+ await authFile();
+ codex.account = CHATGPT;
+ codex.disposeError = new Error('Provider process did not exit after termination.');
+ expect((await check()).status).toBe('authenticated');
+});
+
+it('says the check ran out of time rather than that Codex crashed', async () => {
+ vi.useFakeTimers();
+ codex.account = CHATGPT;
+ codex.delayMs = { 'account/read': 60_000 };
+ const result = check();
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(await result).toEqual({
+ status: 'unknown',
+ message: "Could not check Codex's sign-in: the check ran out of its 20 seconds.",
+ models: [],
+ loginHelps: false,
+ });
+});
+
+it.each([
+ ['config/read', CHATGPT, true],
+ ['getAuthStatus', API_KEY, false],
+] as const)(
+ 'says the check ran out of time when it stops Codex during %s',
+ async (method, account, withAuthFile) => {
+ if (withAuthFile) await authFile();
+ vi.useFakeTimers();
+ codex.account = account;
+ codex.delayMs = { 'account/read': 15_000, [method]: 30_000 };
+ const result = check();
+ await vi.advanceTimersByTimeAsync(20_000);
+ const answer = await result;
+ expect(answer.message).toContain('ran out of its 20 seconds');
+ expect(answer.message).not.toContain('exited');
+ }
+);
+
+it('does not start a second Codex with too little of the deadline left', async () => {
+ vi.useFakeTimers();
+ codex.account = API_KEY;
+ codex.delayMs = { 'account/read': 19_000 };
+ const result = check();
+ await vi.advanceTimersByTimeAsync(19_000);
+ expect((await result).message).toContain('ran out of its 20 seconds');
+ expect(codex.events).toEqual(['start plain', 'stop plain']);
+});
+
+it('pays no mind to a leftover login on a backend that needs no OpenAI login', async () => {
+ codex.account = CHATGPT;
+ codex.requiresOpenaiAuth = false;
+ expect((await check()).status).toBe('authenticated');
+});
+
+it('says it cannot tell when Codex does not say what kind of login it has', async () => {
+ codex.account = {};
+ expect(await check()).toMatchObject({ status: 'unknown', loginHelps: false });
+ expect((await check()).message).toContain('did not say what kind of login');
+});
+
+it('reports a keyring API key as unusable when Codex cannot say where a session keeps it', async () => {
+ codex.account = API_KEY;
+ codex.configReadError = unknownMethod('config/read');
+ expect((await check()).message).toBe(codexKeyringApiKeyWithheld(home));
+});
+
+it('names a home under the user’s own from ~, so relayed reasons carry no user name', async () => {
+ vi.stubEnv('HOME', root);
+ vi.stubEnv('USERPROFILE', root);
+ codex.account = CHATGPT;
+ const { message } = await check({});
+ expect(message).toContain(`(Codex home: ~${join('/', '.codex').replace('/', sep)})`);
+ expect(message).not.toContain(root);
+});
diff --git a/console/packages/agent-providers/src/codex/sign-in.ts b/console/packages/agent-providers/src/codex/sign-in.ts
index 557ca8a9f..87497f340 100644
--- a/console/packages/agent-providers/src/codex/sign-in.ts
+++ b/console/packages/agent-providers/src/codex/sign-in.ts
@@ -1,36 +1,279 @@
+import { homedir } from 'node:os';
+import { join, sep } from 'node:path';
+import { parse } from 'smol-toml';
import { z } from 'zod';
-import { readiness, signInWith, type ProviderReadiness, type SignInCheckInput } from '../readiness';
+import { optionalText } from '../host/provider-home';
+import {
+ loginWontHelp,
+ readiness,
+ signInWith,
+ type ProviderReadiness,
+ type SignInCheckInput,
+} from '../readiness';
import { noopLogger, StdioJsonRpcClient } from '../transport/stdio-json-rpc';
+import { codexSourceHome, hasCodexAuthFile } from './home';
+import {
+ CODEX_EPHEMERAL_LOGIN_ARGS,
+ codexAuthStatusSchema,
+ isUnknownCodexMethod,
+ readCodexCredentialStore,
+} from './keyring-login';
export const CODEX_LOGIN = 'codex login';
+/** How long the whole check may take, across every Codex it starts. */
+const CHECK_TIMEOUT_MS = 20_000;
+
+/** Less than this left of the deadline, and a second Codex is not started at all. */
+const START_BUDGET_MS = 2_000;
+
+/**
+ * Shorter than `CODEX_FILE_STORE_WORKAROUND`: the controller keeps only 300
+ * characters of what a check says, so the instruction comes before the home.
+ */
+const FILE_STORE_WORKAROUND =
+ 'Unless your organization enforces the keyring, set cli_auth_credentials_store = "file" in its ' +
+ 'config.toml (it then keeps the login in plaintext) and run codex login again.';
+
+/**
+ * The home as a message names it: from `~` when it is under the user's own
+ * home directory, so a reason relayed to agents and rooms does not carry the
+ * user's name.
+ */
+function shown(home: string): string {
+ const user = homedir();
+ return home === user || home.startsWith(user + sep) ? `~${home.slice(user.length)}` : home;
+}
+
+const inHome = (home: string) => `(Codex home: ${shown(home)})`;
+
+export const codexKeyringLoginUnusable = (home: string) =>
+ `Codex keeps this login in the OS keyring, where sessions can use only an OpenAI API key. ${FILE_STORE_WORKAROUND} ${inHome(home)}`;
+
+export const codexKeyringIgnoresAuthFile = (home: string) =>
+ `Codex is set to use the OS keyring, so sessions ignore its auth.json. ${FILE_STORE_WORKAROUND} ${inHome(home)}`;
+
+export const codexKeyringApiKeyWithheld = (home: string) =>
+ `Codex keeps this API key in the OS keyring, but this version of Codex will not hand it to Switch. ${FILE_STORE_WORKAROUND} ${inHome(home)}`;
+
+export const codexKeyringStorePinned = (home: string, store: unknown) =>
+ `Codex keeps this API key in the OS keyring, but sets cli_auth_credentials_store to ${JSON.stringify(store ?? null)} for a session where Switch asks for "ephemeral" (an administrator's managed configuration can do this), so Switch cannot hand the key over. ${inHome(home)}`;
+
+export const codexSessionLoginUnchecked = (home: string, cause: string) =>
+ `Codex is signed in, but whether sessions can use its login could not be checked: ${cause} ${inHome(home)}`;
+
+const BEDROCK_UNSAID =
+ 'Codex did not say whether this Amazon Bedrock login runs on AWS credentials or on a key Codex keeps, so whether sessions can use it is not known.';
+
+const KIND_UNSAID =
+ 'Codex did not say what kind of login this is, so whether sessions can use it is not known.';
+
+/** A Codex the check's deadline stopped before it answered. */
+class CheckTimeout extends Error {
+ constructor() {
+ super(`the check ran out of its ${CHECK_TIMEOUT_MS / 1000} seconds.`);
+ }
+}
+
+const accountSchema = z.object({
+ account: z
+ .object({ type: z.string().optional(), usesCodexManagedCredentials: z.boolean().optional() })
+ .nullable(),
+ requiresOpenaiAuth: z.boolean(),
+});
+
+/** An API key in the keyring, still to be checked against a Codex started as a session's is. */
+type HandOver = { handOver: string };
+
export async function checkCodexSignIn(input: SignInCheckInput): Promise<ProviderReadiness> {
+ let sourceHome: string;
+ try {
+ sourceHome = codexSourceHome(input.env);
+ } catch (error) {
+ // Sessions refuse it the same way, and no sign-in changes it.
+ return loginWontHelp(readiness('unauthenticated', describe(error)));
+ }
+ const deadline = Date.now() + CHECK_TIMEOUT_MS;
+ let found: ProviderReadiness | HandOver;
+ try {
+ // The home this Codex read the login from, as Codex resolved it, when it says.
+ found = await withAppServer(input, [], deadline, (client, codexHome) =>
+ machineLogin(input, client, codexHome ?? sourceHome, deadline)
+ );
+ } catch (error) {
+ if (error instanceof CheckTimeout)
+ return loginWontHelp(
+ readiness('unknown', `Could not check Codex's sign-in: ${error.message}`)
+ );
+ throw error;
+ }
+ // Asked only once the first Codex has stopped, within the same deadline.
+ return 'handOver' in found ? handOverStore(input, deadline, found.handOver) : found;
+}
+
+/**
+ * Whether sessions can use the login Codex reports. A session copies only
+ * auth.json from the Codex home, and its Codex ignores that file when set to
+ * use the keyring. Without the file, only an API key is handed over from the
+ * keyring (`readCodexKeyringApiKey`), and only into a session whose Codex
+ * keeps it in memory (`CodexAdapter.signInFromKeyring`).
+ */
+async function machineLogin(
+ input: SignInCheckInput,
+ client: StdioJsonRpcClient,
+ home: string,
+ deadline: number
+): Promise<ProviderReadiness | HandOver> {
+ const { account, requiresOpenaiAuth } = accountSchema.parse(
+ await client.request('account/read', { refreshToken: false })
+ );
+ if (!account && requiresOpenaiAuth) return readiness('unauthenticated', signInWith(CODEX_LOGIN));
+ if (!account) return readiness('unknown', 'This Codex backend does not require OpenAI sign-in.');
+ // Bedrock on AWS's own credentials keeps nothing in Codex's login store.
+ if (account.type === 'amazonBedrock' && account.usesCodexManagedCredentials === false)
+ return readiness('authenticated', 'Signed in.');
+ // Sessions on a backend that needs no OpenAI login never use one, so a
+ // leftover login does not matter; Bedrock's key in Codex's store does.
+ if (!requiresOpenaiAuth && account.type !== 'amazonBedrock')
+ return readiness('authenticated', 'Signed in.');
+ let inFile: boolean;
+ try {
+ inFile = await hasCodexAuthFile(home);
+ } catch (error) {
+ return unchecked(home, failure(error, deadline));
+ }
+ if (inFile) {
+ let store: unknown;
+ try {
+ store = await credentialStore(client, input.cwd, home);
+ } catch (error) {
+ return unchecked(home, failure(error, deadline));
+ }
+ return store === 'keyring'
+ ? readiness('unauthenticated', codexKeyringIgnoresAuthFile(home))
+ : readiness('authenticated', 'Signed in.');
+ }
+ if (account.type === undefined)
+ return loginWontHelp(readiness('unknown', `${KIND_UNSAID} ${inHome(home)}`));
+ if (account.type === 'amazonBedrock' && account.usesCodexManagedCredentials === undefined)
+ return loginWontHelp(readiness('unknown', `${BEDROCK_UNSAID} ${inHome(home)}`));
+ if (account.type !== 'apiKey')
+ return readiness('unauthenticated', codexKeyringLoginUnusable(home));
+ let authMethod: string | null;
+ try {
+ ({ authMethod } = codexAuthStatusSchema.parse(
+ await client.request('getAuthStatus', { includeToken: false, refreshToken: false })
+ ));
+ } catch (error) {
+ return isUnknownCodexMethod(error, 'getAuthStatus')
+ ? readiness('unauthenticated', codexKeyringApiKeyWithheld(home))
+ : unchecked(home, failure(error, deadline));
+ }
+ if (authMethod !== 'apikey')
+ return readiness('unauthenticated', codexKeyringApiKeyWithheld(home));
+ return { handOver: home };
+}
+
+/** A check that could not finish: no sign-in changes that, so it is not offered. */
+function unchecked(home: string, cause: string): ProviderReadiness {
+ return loginWontHelp(readiness('unknown', codexSessionLoginUnchecked(home, cause)));
+}
+
+/** Why a request failed: a Codex the deadline stopped fails as an exit, so say what stopped it. */
+function failure(error: unknown, deadline: number): string {
+ return Date.now() >= deadline ? new CheckTimeout().message : describe(error);
+}
+
+/**
+ * Where Codex keeps logins for `cwd`. A Codex too old to answer config/read
+ * is read from the home's own config.toml instead, which a session inherits;
+ * an administrator's managed configuration is then not seen.
+ */
+async function credentialStore(
+ client: StdioJsonRpcClient,
+ cwd: string,
+ home: string
+): Promise<unknown> {
+ try {
+ return await readCodexCredentialStore(client, cwd);
+ } catch (error) {
+ if (!isUnknownCodexMethod(error, 'config/read')) throw error;
+ }
+ const text = await optionalText(join(home, 'config.toml'));
+ return text === null ? null : parse(text).cli_auth_credentials_store;
+}
+
+async function handOverStore(
+ input: SignInCheckInput,
+ deadline: number,
+ home: string
+): Promise<ProviderReadiness> {
+ if (deadline - Date.now() < START_BUDGET_MS) return unchecked(home, new CheckTimeout().message);
+ let store: unknown;
+ try {
+ store = await withAppServer(input, CODEX_EPHEMERAL_LOGIN_ARGS, deadline, (session) =>
+ readCodexCredentialStore(session, input.cwd)
+ );
+ } catch (error) {
+ // The session asks the same, so a Codex that cannot answer fails it too.
+ if (isUnknownCodexMethod(error, 'config/read'))
+ return readiness('unauthenticated', codexKeyringApiKeyWithheld(home));
+ return unchecked(home, describe(error));
+ }
+ return store === 'ephemeral'
+ ? readiness('authenticated', 'Signed in.')
+ : loginWontHelp(readiness('unauthenticated', codexKeyringStorePinned(home, store)));
+}
+
+function describe(error: unknown): string {
+ const cause = error instanceof Error && error.cause !== undefined ? error.cause : error;
+ return cause instanceof Error ? cause.message : String(cause);
+}
+
+async function withAppServer<T>(
+ input: SignInCheckInput,
+ args: string[],
+ deadline: number,
+ read: (client: StdioJsonRpcClient, codexHome: string | null) => Promise<T>
+): Promise<T> {
const client = new StdioJsonRpcClient({
command: input.binaryPath,
- args: ['app-server'],
+ args: ['app-server', ...args],
cwd: input.cwd,
env: input.env,
logger: noopLogger,
onExit: () => {},
});
- const timer = setTimeout(() => {
- void client.dispose().catch(() => console.warn('Provider readiness process cleanup failed.'));
- }, 20000);
+ let timedOut = false;
+ const timer = setTimeout(
+ () => {
+ timedOut = true;
+ void client.dispose().catch(() => console.warn('Provider readiness process cleanup failed.'));
+ },
+ Math.max(0, deadline - Date.now())
+ );
try {
- await client.request('initialize', {
- clientInfo: { name: 'switch-console', version: '0.1.0' },
- });
+ const { codexHome } = z.object({ codexHome: z.string().nullish() }).parse(
+ await client.request('initialize', {
+ clientInfo: { name: 'switch-console', version: '0.1.0' },
+ })
+ );
client.notify('initialized', null);
- const account = z
- .object({ account: z.unknown().nullable(), requiresOpenaiAuth: z.boolean() })
- .parse(await client.request('account/read', { refreshToken: false }));
- if (!account.account && account.requiresOpenaiAuth)
- return readiness('unauthenticated', signInWith(CODEX_LOGIN));
- return account.account
- ? readiness('authenticated', 'Signed in.')
- : readiness('unknown', 'This Codex backend does not require OpenAI sign-in.');
+ return await read(client, codexHome ?? null);
+ } catch (error) {
+ // Stopped by the deadline, it fails as an exit; say what stopped it.
+ if (timedOut) throw new CheckTimeout();
+ throw error;
} finally {
clearTimeout(timer);
- await client.dispose();
+ // What was read, or went wrong, is the answer: a Codex that will not stop
+ // is reported, not put in its place.
+ await client
+ .dispose()
+ .catch((error: unknown) =>
+ console.warn(
+ `The Codex that checked a sign-in did not stop: ${error instanceof Error ? error.message : String(error)}`
+ )
+ );
}
}
diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.ts
index 28a6b16ce..44564f744 100644
--- a/console/packages/agent-providers/src/host/shared-config.test.ts
+++ b/console/packages/agent-providers/src/host/shared-config.test.ts
@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { codexHomeNotAbsolute } from '../codex/home';
import {
executionEnvironment,
prepareSharedConfig,
@@ -211,6 +212,19 @@ it('gives Codex the Switch skill as instructions, like the other providers', asy
}
});
+it('refuses to start a Codex session whose CODEX_HOME is relative', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));
+ try {
+ const config = await codexHostConfig(root);
+ config.start.input.env.CODEX_HOME = 'codex-source';
+ await expect(
+ prepareSharedConfig(root, config, CODEX_RUNTIME, NO_SERVICES, null, {}, NO_REDACTIONS)
+ ).rejects.toThrow(codexHomeNotAbsolute('codex-source'));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
it('hands a Codex session the keyring login of a home with no auth.json, with only what reading it needs', async () => {
vi.stubEnv('DBUS_SESSION_BUS_ADDRESS', 'unix:path=/run/user/1000/bus');
vi.stubEnv('XDG_RUNTIME_DIR', '/run/user/1000');
diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.ts
index 527e974cb..c8d03fc92 100644
--- a/console/packages/agent-providers/src/host/shared-config.ts
+++ b/console/packages/agent-providers/src/host/shared-config.ts
@@ -1,13 +1,12 @@
import { execFile } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
-import { homedir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { join } from 'node:path';
import { promisify } from 'node:util';
import { sessionSchema } from '@switch-console/shared/session-v1';
import { z } from 'zod';
import type { CodexKeyringLogin, HttpMcpServerSpec, ProviderSessionStartInput } from '../adapter';
-import { prepareCodexSessionHome } from '../codex/home';
+import { codexSourceHome, prepareCodexSessionHome } from '../codex/home';
import { codexKeyringReaderEnvironment } from './agent-env';
import { agentHasOwnUser } from './host-permissions';
import { type HostedCredential, hostedCredentialSchema } from './provider-login';
@@ -161,7 +160,7 @@ export async function prepareSharedConfig(
);
input.env = { ...inherited, ...input.env };
if (config.start.provider === 'codex') {
- const sourceHome = resolve(input.env.CODEX_HOME || join(homedir(), '.codex'));
+ const sourceHome = codexSourceHome(input.env);
const prepared = await prepareCodexSessionHome({
root: join(root, 'provider-home'),
sessionId: config.session.sessionId,
diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.ts
index 8b3cc1aca..d37d84df5 100644
--- a/console/packages/agent-providers/src/index.ts
+++ b/console/packages/agent-providers/src/index.ts
@@ -162,7 +162,7 @@ export {
watcherHealthSchema,
} from './host/watcher-tools';
-export { prepareCodexSessionHome, withManagedCodexSandbox } from './codex/home';
+export { codexSourceHome, prepareCodexSessionHome, withManagedCodexSandbox } from './codex/home';
export { readSharedCredentials, sharedConfigSchema } from './host/shared-config';
export type { SharedHostConfig } from './host/shared-config';
diff --git a/console/packages/agent-providers/src/readiness.ts b/console/packages/agent-providers/src/readiness.ts
index f65e0139f..3d6e7d8e5 100644
--- a/console/packages/agent-providers/src/readiness.ts
+++ b/console/packages/agent-providers/src/readiness.ts
@@ -4,6 +4,12 @@ export const providerReadinessSchema = z.object({
status: z.enum(['authenticated', 'unauthenticated', 'unconfigured', 'unknown']),
message: z.string(),
models: z.array(z.object({ id: z.string(), name: z.string() })),
+ /**
+ * False when signing in with the provider's login command would not fix
+ * what `message` says, so Console does not offer it. Absent from a check
+ * older than this field, and wherever signing in may help.
+ */
+ loginHelps: z.boolean().optional(),
});
export type ProviderReadiness = z.infer<typeof providerReadinessSchema>;
@@ -18,6 +24,11 @@ export function readiness(status: ProviderReadiness['status'], message: string):
return { status, message, models: [] };
}
+/** `result`, marked as something the provider's login command cannot fix. */
+export function loginWontHelp(result: ProviderReadiness): ProviderReadiness {
+ return { ...result, loginHelps: false };
+}
+
export function signInWith(loginCommand: string): string {
return `Sign in on the execution machine with ${loginCommand}.`;
}
diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.md
index d5d7528d3..aebf41918 100644
--- a/console/packages/plugins/src/switch-skill/SKILL.md
+++ b/console/packages/plugins/src/switch-skill/SKILL.md
@@ -797,8 +797,9 @@ does not manage agents, so say so rather than looking for another way.
- **`list_machines`** — your owner's machines: `id`, `name`, `description`,
`state` (`online`, `offline`, or `unknown` if it never connected), the
- providers each has (`installed`, `auth`) and how many agents it is running.
- Removed machines are left out.
+ providers each has (`installed`, `auth`, and `problem`: why its login does
+ not work, in the machine's words, when it said) and how many agents it is
+ running. Removed machines are left out.
- **`get_advanced_config`** — the advanced settings a provider's agents can
carry (the "Advanced configuration" Switch Console shows): each field's
`key`, `label`, `type` (`text`, `textarea`, `number`, `boolean`, `list` of
diff --git a/core/switch_core/bridges/agent/operations/agent_management.py b/core/switch_core/bridges/agent/operations/agent_management.py
index 262287098..a90281de5 100644
--- a/core/switch_core/bridges/agent/operations/agent_management.py
+++ b/core/switch_core/bridges/agent/operations/agent_management.py
@@ -137,8 +137,10 @@ async def list_machines() -> list[dict[str, Any]]:
now), "offline" (was connected, and is not now: stopped, asleep, off
or disconnected) or "unknown" (has never connected).
`providers` lists the agent CLIs the machine last reported, each
- {provider, installed, version, auth}, `auth` being "ok", "missing",
- "expired" or "unknown". `agents_running` counts the managed agents
+ {provider, installed, version, auth, problem}, `auth` being "ok",
+ "missing", "expired" or "unknown", and `problem` why its login does
+ not work, in the machine's words, or null when it said nothing.
+ `agents_running` counts the managed agents
whose process the machine last reported as running, null before it
has reported. Pass a machine's `id` or exact `name` to `create_agent`.
"""
diff --git a/core/switch_core/management/agent_operations.py b/core/switch_core/management/agent_operations.py
index b16a660e5..5fb38cd05 100644
--- a/core/switch_core/management/agent_operations.py
+++ b/core/switch_core/management/agent_operations.py
@@ -61,9 +61,18 @@ def _validation_message(exc: ValidationError) -> str:
return "; ".join(parts) or "invalid request"
-def _placement_sentence(code: str, machine: str, provider: str) -> str | None:
+def _placement_sentence(
+ code: str, machine: str, provider: str, problem: str | None
+) -> str | None:
"""Why the machine cannot take the agent, in a person's terms, for the
- placement reason codes; None for any other code."""
+ placement reason codes; None for any other code. `problem` is what the
+ machine said about the provider's login: a CLI that is signed in in a way
+ its agents cannot use is not fixed by logging in, and that says so."""
+ if code == reason_codes.PROVIDER_LOGIN_MISSING and problem:
+ return (
+ f"{provider} cannot be used on machine '{machine}'; your owner "
+ f"needs to fix this there: {problem}"
+ )
sentences = {
reason_codes.CONTROLLER_REVOKED: (
f"machine '{machine}' has been removed from Switch; pick another machine"
@@ -105,19 +114,48 @@ def _agents_running(controller: AgentController) -> int | None:
)
-def _providers(controller: AgentController) -> list[dict[str, Any]]:
- if controller.status is None:
+def _provider_entries(controller: AgentController | None) -> list[dict[str, Any]]:
+ if controller is None or controller.status is None:
return []
providers = controller.status.get("providers")
+ return [
+ entry
+ for entry in (providers if isinstance(providers, list) else [])
+ if isinstance(entry, dict)
+ ]
+
+
+def _login_problem(entry: dict[str, Any]) -> str | None:
+ """What the machine said about the provider's login, if anything."""
+ problem = entry.get("auth_problem")
+ return problem if isinstance(problem, str) and problem else None
+
+
+def _provider_problem(controller: AgentController | None, provider: str) -> str | None:
+ return next(
+ (
+ _login_problem(entry)
+ for entry in _provider_entries(controller)
+ if entry.get("provider") == provider
+ ),
+ None,
+ )
+
+
+def _providers(controller: AgentController) -> list[dict[str, Any]]:
return [
{
"provider": entry.get("provider"),
"installed": entry.get("installed") is True,
"version": entry.get("version"),
"auth": provider_auth(entry),
+ # A login that works has nothing wrong with it, whatever else
+ # the machine said along the way.
+ "problem": (
+ _login_problem(entry) if provider_auth(entry) != "ok" else None
+ ),
}
- for entry in (providers if isinstance(providers, list) else [])
- if isinstance(entry, dict)
+ for entry in _provider_entries(controller)
]
@@ -238,7 +276,9 @@ class ManagementAgentOperations:
def _refusal(
exc: ManagementError, controller: AgentController, provider: str
) -> AgentManagementRefused:
- sentence = _placement_sentence(exc.code, controller.name, provider)
+ sentence = _placement_sentence(
+ exc.code, controller.name, provider, _provider_problem(controller, provider)
+ )
return AgentManagementRefused(
exc.code,
f"{NOTHING_CREATED}: {sentence or exc.message} ({exc.code}).",
@@ -451,7 +491,9 @@ class ManagementAgentOperations:
)
except ManagementError as exc:
machine = controller.name if controller is not None else "(none)"
- sentence = _placement_sentence(exc.code, machine, provider)
+ sentence = _placement_sentence(
+ exc.code, machine, provider, _provider_problem(controller, provider)
+ )
raise AgentManagementRefused(
exc.code,
f"{NOTHING_CHANGED}: {sentence or exc.message} ({exc.code}).",
diff --git a/core/tests/switch_core/management/harness.py b/core/tests/switch_core/management/harness.py
index a3cf646bf..c3eaa0adc 100644
--- a/core/tests/switch_core/management/harness.py
+++ b/core/tests/switch_core/management/harness.py
@@ -372,7 +372,13 @@ def status_report(
return report
-def provider(name: str, *, installed: bool = True, auth: str = "ok") -> dict[str, Any]:
+def provider(
+ name: str,
+ *,
+ installed: bool = True,
+ auth: str = "ok",
+ auth_problem: str | None = None,
+) -> dict[str, Any]:
return {
"provider": name,
"installed": installed,
@@ -380,6 +386,7 @@ def provider(name: str, *, installed: bool = True, auth: str = "ok") -> dict[str
"auth": auth,
"auth_source": "local" if installed else None,
"checked_at": "2026-01-01T00:00:00Z",
+ **({"auth_problem": auth_problem} if auth_problem else {}),
}
diff --git a/core/tests/switch_core/management/test_agent_operations.py b/core/tests/switch_core/management/test_agent_operations.py
index d07b225ea..24978613d 100644
--- a/core/tests/switch_core/management/test_agent_operations.py
+++ b/core/tests/switch_core/management/test_agent_operations.py
@@ -322,8 +322,8 @@ class TestListMachines:
client,
laptop,
providers=[
- provider("claude"),
- provider("codex", auth="missing"),
+ provider("claude", auth_problem="Said before a given login worked."),
+ provider("codex", auth="missing", auth_problem="In the OS keyring."),
provider("cursor", installed=False),
],
agents=[
@@ -351,18 +351,21 @@ class TestListMachines:
"installed": True,
"version": "1.0.0",
"auth": "ok",
+ "problem": None,
},
{
"provider": "codex",
"installed": True,
"version": "1.0.0",
"auth": "missing",
+ "problem": "In the OS keyring.",
},
{
"provider": "cursor",
"installed": False,
"version": None,
"auth": "ok",
+ "problem": None,
},
],
"agents_running": 2,
@@ -586,6 +589,18 @@ class TestCreateAgent:
"provider_login_expired",
"the claude login on machine 'laptop' has expired",
),
+ (
+ [
+ provider(
+ "claude",
+ auth="missing",
+ auth_problem="An administrator pins where it keeps logins.",
+ )
+ ],
+ "provider_login_missing",
+ "claude cannot be used on machine 'laptop'; your owner needs to fix "
+ "this there: An administrator pins where it keeps logins.",
+ ),
],
)
async def test_placement_refusals_are_relayable_and_leave_nothing(