Skip to content

Commit 22d4279

Browse files
P5inaobviyus
andauthored
fix(tui): surface provider auth failures (#125677)
Make local TUI auth failures actionable while preserving the foreground child lifecycle, provider picker routing, and built-in token masking under custom redaction patterns. Co-authored-by: Timur Turatbekov <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 968945a commit 22d4279

7 files changed

Lines changed: 223 additions & 37 deletions

File tree

‎src/commands/models/auth.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ const mocks = vi.hoisted(() => ({
4949
resolveAgentDir: vi.fn(),
5050
resolveAgentWorkspaceDir: vi.fn(),
5151
resolveDefaultAgentWorkspaceDir: vi.fn(),
52+
isCliProvider: vi.fn(),
5253
upsertAuthProfile: vi.fn(),
5354
upsertAuthProfileAfterLoginWithLock: vi.fn(),
5455
upsertAuthProfileWithLock: vi.fn(),
@@ -126,6 +127,10 @@ vi.mock("../../agents/workspace.js", () => ({
126127
resolveDefaultAgentWorkspaceDir: mocks.resolveDefaultAgentWorkspaceDir,
127128
}));
128129

130+
vi.mock("../../agents/model-selection-cli.js", () => ({
131+
isCliProvider: mocks.isCliProvider,
132+
}));
133+
129134
vi.mock("../../plugins/providers.runtime.js", () => ({
130135
resolvePluginProvidersCore: mocks.resolvePluginProvidersCore,
131136
}));
@@ -372,6 +377,7 @@ describe("modelsAuthLoginCommand", () => {
372377
mocks.resolveAgentWorkspaceDir.mockReturnValue("/tmp/openclaw/workspace");
373378
mocks.resolveDefaultAgentWorkspaceDir.mockReturnValue("/tmp/openclaw/workspace");
374379
mocks.isRemoteEnvironment.mockReturnValue(false);
380+
mocks.isCliProvider.mockReturnValue(false);
375381
mocks.resolvePluginSetupProviderCore.mockReturnValue(undefined);
376382
mocks.resolvePluginSetupRegistry.mockReturnValue({
377383
providers: [],
@@ -1242,6 +1248,44 @@ describe("modelsAuthLoginCommand", () => {
12421248
);
12431249
});
12441250

1251+
it("opens the provider picker when a CLI backend has no provider auth method", async () => {
1252+
const runtime = createRuntime();
1253+
const prompter = {
1254+
note: vi.fn(async () => {}),
1255+
select: vi.fn(async () => "openai"),
1256+
};
1257+
mocks.createClackPrompter.mockReturnValue(prompter);
1258+
mocks.isCliProvider.mockImplementation((provider: string) => provider === "claude-cli");
1259+
const openaiProvider = createProvider({
1260+
id: "openai",
1261+
label: "OpenAI Codex",
1262+
run: runProviderAuth as ProviderPlugin["auth"][number]["run"],
1263+
});
1264+
mocks.resolvePluginProvidersCore.mockImplementation(
1265+
(params: ResolvePluginProvidersCall | undefined) =>
1266+
params?.providerRefs?.includes("claude-cli") ? [] : [openaiProvider],
1267+
);
1268+
1269+
await modelsAuthLoginCommand({ provider: "claude-cli" }, runtime);
1270+
1271+
expect(prompter.note).toHaveBeenCalledWith(
1272+
'Provider "claude-cli" uses its own CLI login. Select a provider with an OpenClaw auth flow.',
1273+
"Provider auth",
1274+
);
1275+
expect(prompter.select).toHaveBeenCalledWith(
1276+
expect.objectContaining({ message: "Select a provider" }),
1277+
);
1278+
expect(runProviderAuth).toHaveBeenCalledOnce();
1279+
expect(mocks.resolvePluginProvidersCore).toHaveBeenNthCalledWith(
1280+
1,
1281+
expect.objectContaining({ providerRefs: ["claude-cli"], activate: true }),
1282+
);
1283+
expect(mocks.resolvePluginProvidersCore).toHaveBeenNthCalledWith(
1284+
2,
1285+
expect.not.objectContaining({ providerRefs: expect.anything() }),
1286+
);
1287+
});
1288+
12451289
it.each(["openai-codex", "codex-cli"])(
12461290
"rejects retired manual auth provider %s",
12471291
async (provider) => {

‎src/commands/models/auth.ts‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
} from "../../agents/auth-profiles/profiles.js";
2626
import type { AuthProfileCredential } from "../../agents/auth-profiles/types.js";
2727
import { normalizeProviderId } from "../../agents/model-ref-shared.js";
28+
import { isCliProvider } from "../../agents/model-selection-cli.js";
2829
import { resolveProviderIdForAuth } from "../../agents/provider-auth-aliases.js";
2930
import { resolveDefaultAgentWorkspaceDir } from "../../agents/workspace.js";
3031
import { formatCliCommand } from "../../cli/command-format.js";
@@ -950,23 +951,43 @@ function maybeLogOpenAICodexNativeSearchTip(runtime: RuntimeEnv, providerId: str
950951
export async function runModelsAuthLoginFlowCore(
951952
opts: ModelsAuthLoginFlowOptions,
952953
): Promise<ModelsAuthLoginFlowResult> {
953-
const { config, agentId, agentDir, workspaceDir, providers } = await resolveModelsAuthContext({
954-
requestedProvider: opts.provider,
954+
const requestedProviderId = opts.provider
955+
? normalizeManualAuthProvider(opts.provider)
956+
: undefined;
957+
let context = await resolveModelsAuthContext({
958+
requestedProvider: requestedProviderId,
955959
rawAgentId: opts.agent,
956960
config: opts.config,
957961
});
958962
const prompter = opts.prompter;
959-
const authProviders = listProvidersWithAuthMethods(providers);
963+
let authProviders = listProvidersWithAuthMethods(context.providers);
964+
let requestedProvider = requestedProviderId
965+
? resolveProviderMatch(authProviders, requestedProviderId)
966+
: null;
967+
const useProviderPicker =
968+
requestedProviderId !== undefined &&
969+
requestedProvider === null &&
970+
isCliProvider(requestedProviderId, context.config);
971+
if (useProviderPicker) {
972+
context = await resolveModelsAuthContext({
973+
rawAgentId: opts.agent,
974+
config: context.config,
975+
});
976+
authProviders = listProvidersWithAuthMethods(context.providers);
977+
}
960978
if (authProviders.length === 0) {
961979
throw new Error(
962980
`No provider plugins found. Install one via \`${formatCliCommand("openclaw plugins install")}\`.`,
963981
);
964982
}
965-
966-
const requestedProvider = resolveRequestedLoginProviderOrThrow(
967-
authProviders,
968-
opts.provider ? normalizeManualAuthProvider(opts.provider) : undefined,
969-
);
983+
if (useProviderPicker) {
984+
await prompter.note(
985+
`Provider "${requestedProviderId}" uses its own CLI login. Select a provider with an OpenClaw auth flow.`,
986+
"Provider auth",
987+
);
988+
} else if (requestedProviderId && !requestedProvider) {
989+
requestedProvider = resolveRequestedLoginProviderOrThrow(authProviders, requestedProviderId);
990+
}
970991
const selectedProvider =
971992
requestedProvider ??
972993
(await prompter
@@ -1010,7 +1031,7 @@ export async function runModelsAuthLoginFlowCore(
10101031
try {
10111032
const clearedStore = await removeProviderAuthProfilesWithLock({
10121033
provider: selectedProvider.id,
1013-
agentDir,
1034+
agentDir: context.agentDir,
10141035
});
10151036
if (!clearedStore) {
10161037
throw new Error("profile store update failed");
@@ -1028,10 +1049,10 @@ export async function runModelsAuthLoginFlowCore(
10281049
}
10291050

10301051
const { result, profiles } = await runProviderAuthMethod({
1031-
config,
1032-
agentId,
1033-
agentDir,
1034-
workspaceDir,
1052+
config: context.config,
1053+
agentId: context.agentId,
1054+
agentDir: context.agentDir,
1055+
workspaceDir: context.workspaceDir,
10351056
provider: selectedProvider,
10361057
method: chosenMethod,
10371058
runtime: opts.runtime,

‎src/tui/tui-auth-child-pty.e2e.test.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const STARTUP_TIMEOUT_MS = 60_000;
1212
const EXIT_TIMEOUT_MS = 4_000;
1313
const tempDirs: string[] = [];
1414

15-
async function createCodexFixture(exitMs?: number) {
15+
async function createCodexFixture(exitMs?: number, exitCode = 0) {
1616
const dir = await mkdtemp(path.join(tmpdir(), "openclaw-tui-auth-"));
1717
tempDirs.push(dir);
1818
const scriptPath = path.join(dir, "codex-fixture.cjs");
@@ -22,7 +22,7 @@ async function createCodexFixture(exitMs?: number) {
2222
'console.log("AUTH_CHILD_STARTED:" + process.pid);',
2323
exitMs === undefined
2424
? "setInterval(() => {}, 1000);"
25-
: `setTimeout(() => process.exit(0), ${String(exitMs)});`,
25+
: `setTimeout(() => process.exit(${String(exitCode)}), ${String(exitMs)});`,
2626
].join("\n"),
2727
"utf8",
2828
);
@@ -104,4 +104,24 @@ describe.sequential("TUI auth child lifecycle", () => {
104104
},
105105
STARTUP_TIMEOUT_MS * 2,
106106
);
107+
108+
it(
109+
"keeps a failed auth command visible after the TUI resumes",
110+
async () => {
111+
const auth = await createCodexFixture(50, 1);
112+
const fixture = await startTuiFixture({
113+
env: {
114+
PATH: auth.pathEnv,
115+
},
116+
});
117+
await fixture.run.waitForOutput("local ready", STARTUP_TIMEOUT_MS);
118+
await fixture.run.write("/auth openai\r", { delay: false });
119+
await fixture.run.waitForOutput("auth flow failed (exit 1)", STARTUP_TIMEOUT_MS);
120+
await fixture.run.waitForOutput(
121+
"in a regular terminal to see its output",
122+
STARTUP_TIMEOUT_MS,
123+
);
124+
},
125+
STARTUP_TIMEOUT_MS * 2,
126+
);
107127
});

‎src/tui/tui-command-handlers.test.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,11 @@ function createHarness(params?: {
191191
const runAuthFlow: RunAuthFlow | undefined =
192192
params?.runAuthFlow ??
193193
(params?.opts?.local
194-
? (vi.fn().mockResolvedValue({ exitCode: 0, signal: null }) as unknown as RunAuthFlow)
194+
? (vi.fn().mockResolvedValue({
195+
exitCode: 0,
196+
signal: null,
197+
commandArgv: '["codex","login"]',
198+
}) as unknown as RunAuthFlow)
195199
: undefined);
196200
const state = {
197201
agentDefaultId: params?.agentDefaultId ?? "main",
@@ -3130,7 +3134,11 @@ describe("tui command handlers", () => {
31303134

31313135
it("runs /auth through the local auth flow and refreshes session info", async () => {
31323136
const refreshSessionInfo = vi.fn().mockResolvedValue(undefined);
3133-
const runAuthFlow = vi.fn().mockResolvedValue({ exitCode: 0, signal: null });
3137+
const runAuthFlow = vi.fn().mockResolvedValue({
3138+
exitCode: 0,
3139+
signal: null,
3140+
commandArgv: '["codex","login"]',
3141+
});
31343142
const { handleCommand, addSystem, setActivityStatus } = createHarness({
31353143
opts: { local: true },
31363144
refreshSessionInfo,
@@ -3148,6 +3156,25 @@ describe("tui command handlers", () => {
31483156
expect(setActivityStatus).toHaveBeenLastCalledWith("idle");
31493157
});
31503158

3159+
it("shows the failed auth command and a safe terminal retry", async () => {
3160+
const runAuthFlow = vi.fn().mockResolvedValue({
3161+
exitCode: 1,
3162+
signal: null,
3163+
commandArgv: '["codex","login"]',
3164+
});
3165+
const { handleCommand, addSystem, setActivityStatus } = createHarness({
3166+
opts: { local: true },
3167+
runAuthFlow,
3168+
});
3169+
3170+
await handleCommand("/auth openai");
3171+
3172+
expect(addSystem).toHaveBeenCalledWith(
3173+
'auth flow failed (exit 1) — command argv: ["codex","login"]; retry provider login in a regular terminal to see its output',
3174+
);
3175+
expect(setActivityStatus).toHaveBeenLastCalledWith("error");
3176+
});
3177+
31513178
it("rejects /auth in non-local mode", async () => {
31523179
const { handleCommand, addSystem } = createHarness();
31533180

@@ -3157,7 +3184,11 @@ describe("tui command handlers", () => {
31573184
});
31583185

31593186
it("blocks /auth while an optimistic run is still pending", async () => {
3160-
const runAuthFlow = vi.fn().mockResolvedValue({ exitCode: 0, signal: null });
3187+
const runAuthFlow = vi.fn().mockResolvedValue({
3188+
exitCode: 0,
3189+
signal: null,
3190+
commandArgv: '["codex","login"]',
3191+
});
31613192
const { handleCommand, addSystem } = createHarness({
31623193
opts: { local: true },
31633194
pendingSubmit: {

‎src/tui/tui-command-handlers.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,11 @@ type CommandHandlerContext = {
9393
consumeCompletedRunForPendingSend?: (runId: string) => boolean;
9494
isRunObserved?: (runId: string) => boolean;
9595
flushPendingHistoryRefreshIfIdle?: () => void;
96-
runAuthFlow?: (params: {
97-
provider?: string;
98-
}) => Promise<{ exitCode: number | null; signal: NodeJS.Signals | null }>;
96+
runAuthFlow?: (params: { provider?: string }) => Promise<{
97+
exitCode: number | null;
98+
signal: NodeJS.Signals | null;
99+
commandArgv: string;
100+
}>;
99101
requestExit: (result?: Partial<TuiResult>) => void;
100102
};
101103

@@ -500,7 +502,9 @@ export function createCommandHandlers(context: CommandHandlerContext) {
500502
: typeof result.exitCode === "number"
501503
? ` (exit ${String(result.exitCode)})`
502504
: "";
503-
chatLog.addSystem(`auth flow failed${failureSuffix}`);
505+
chatLog.addSystem(
506+
`auth flow failed${failureSuffix} — command argv: ${result.commandArgv}; retry provider login in a regular terminal to see its output`,
507+
);
504508
setActivityStatus("error");
505509
}
506510
} catch (err) {

‎src/tui/tui.local-auth.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,47 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
13
import { describe, expect, it } from "vitest";
2-
import { resolveCodexCliBin, resolveLocalAuthSpawnInvocation } from "./tui.js";
4+
import { withEnv } from "../test-utils/env.js";
5+
import { withTempDir } from "../test-utils/temp-dir.js";
6+
import {
7+
formatTuiAuthCommandArgv,
8+
resolveCodexCliBin,
9+
resolveLocalAuthSpawnInvocation,
10+
} from "./tui.js";
11+
12+
describe("formatTuiAuthCommandArgv", () => {
13+
it("renders bounded redacted argv without shell semantics", () => {
14+
const rendered = formatTuiAuthCommandArgv("C:\\Users\\%USERNAME%\\codex.exe\n", ["login"]);
15+
expect(rendered).toContain("%USERNAME%");
16+
expect(rendered).toContain("\\n");
17+
expect(rendered).not.toContain("\n");
18+
19+
const secret = "sk-proof-only-1234567890";
20+
expect(formatTuiAuthCommandArgv("codex", ["login", secret])).not.toContain(secret);
21+
expect(
22+
formatTuiAuthCommandArgv("/tmp/" + "x".repeat(400), ["login"]).length,
23+
).toBeLessThanOrEqual(320);
24+
});
25+
26+
it("keeps built-in masking when custom log patterns are configured", async () => {
27+
await withTempDir("openclaw-tui-auth-redaction-", async (dir) => {
28+
const configPath = path.join(dir, "openclaw.json");
29+
await fs.writeFile(
30+
configPath,
31+
JSON.stringify({ logging: { redactPatterns: ["project-secret-\\d+"] } }),
32+
);
33+
const token = "sk-proof-only-1234567890";
34+
const customSecret = "project-secret-12345";
35+
36+
const rendered = withEnv({ OPENCLAW_CONFIG_PATH: configPath }, () =>
37+
formatTuiAuthCommandArgv("codex", ["login", token, customSecret]),
38+
);
39+
40+
expect(rendered).not.toContain(token);
41+
expect(rendered).not.toContain(customSecret);
42+
});
43+
});
44+
});
345

446
describe("resolveCodexCliBin", () => {
547
it("returns null or a valid Codex executable path", async () => {

0 commit comments

Comments
 (0)