Skip to content

Commit 92b6c17

Browse files
authored
fix(usage): keep healthy provider usage after auth failures (#124367)
* fix(usage): isolate provider auth failures * fix(usage): preserve direct auth failures
1 parent a73249c commit 92b6c17

5 files changed

Lines changed: 143 additions & 78 deletions

‎src/infra/provider-usage-plugin-runtime.test-mocks.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ const resolveProviderUsageSnapshotWithPluginMock = vi.hoisted(() =>
66
async () => null,
77
),
88
);
9+
const resolveProviderUsageAuthWithPluginMock = vi.hoisted(() =>
10+
vi.fn<typeof import("../plugins/provider-runtime.js").resolveProviderUsageAuthWithPlugin>(
11+
async () => undefined,
12+
),
13+
);
914

1015
vi.mock("../config/config.js", () => ({
1116
getRuntimeConfig: () => ({}),
@@ -17,16 +22,23 @@ vi.mock("../plugins/provider-runtime.js", async () => {
1722
);
1823
return {
1924
...actual,
25+
resolveProviderUsageAuthWithPlugin: resolveProviderUsageAuthWithPluginMock,
2026
resolveProviderUsageSnapshotWithPlugin: resolveProviderUsageSnapshotWithPluginMock,
2127
};
2228
});
2329

2430
/** Resets the plugin-backed provider usage mock to the default no-snapshot behavior. */
2531
export function resetProviderUsageSnapshotWithPluginMock() {
32+
resolveProviderUsageAuthWithPluginMock.mockReset();
33+
resolveProviderUsageAuthWithPluginMock.mockResolvedValue(undefined);
2634
resolveProviderUsageSnapshotWithPluginMock.mockReset();
2735
resolveProviderUsageSnapshotWithPluginMock.mockResolvedValue(null);
2836
}
2937

3038
export function getProviderUsageSnapshotWithPluginMock() {
3139
return resolveProviderUsageSnapshotWithPluginMock;
3240
}
41+
42+
export function getProviderUsageAuthWithPluginMock() {
43+
return resolveProviderUsageAuthWithPluginMock;
44+
}

‎src/infra/provider-usage.auth.plugin.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,17 @@ describe("resolveProviderAuths plugin boundary", () => {
152152
expect(ensureAuthProfileStoreMock).not.toHaveBeenCalled();
153153
});
154154

155+
it("preserves exact plugin auth failures for direct callers", async () => {
156+
const authError = new Error("plugin auth failed");
157+
resolveProviderUsageAuthWithPluginMock.mockRejectedValueOnce(authError);
158+
159+
await expect(
160+
resolveProviderAuthsForTest({
161+
providers: ["anthropic"],
162+
}),
163+
).rejects.toBe(authError);
164+
});
165+
155166
it("resolves SecretRef-backed profiles before provider credential classification", async () => {
156167
const store = {
157168
profiles: {

‎src/infra/provider-usage.auth.ts‎

Lines changed: 69 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,7 @@ export async function resolveProviderAuths(params: {
481481
config?: OpenClawConfig;
482482
env?: NodeJS.ProcessEnv;
483483
skipPluginAuthWithoutCredentialSource?: boolean;
484+
onError?: (provider: UsageProviderId, error: unknown) => void;
484485
}): Promise<ProviderAuth[]> {
485486
if (params.auth) {
486487
return params.auth;
@@ -501,80 +502,87 @@ export async function resolveProviderAuths(params: {
501502
const auths: ProviderAuth[] = [];
502503

503504
for (const provider of params.providers) {
504-
if (!params.skipPluginAuthWithoutCredentialSource) {
505-
const pluginAuth = await resolveProviderUsageAuthViaPlugin({
506-
state: authProfileSourceState,
507-
provider,
508-
});
509-
if (pluginAuth.auth) {
510-
auths.push(pluginAuth.auth);
511-
continue;
512-
}
513-
if (pluginAuth.handled) {
505+
try {
506+
if (!params.skipPluginAuthWithoutCredentialSource) {
507+
const pluginAuth = await resolveProviderUsageAuthViaPlugin({
508+
state: authProfileSourceState,
509+
provider,
510+
});
511+
if (pluginAuth.auth) {
512+
auths.push(pluginAuth.auth);
513+
continue;
514+
}
515+
if (pluginAuth.handled) {
516+
continue;
517+
}
518+
const fallbackAuth = await resolveProviderUsageAuthFallback({
519+
state: authProfileSourceState,
520+
provider,
521+
});
522+
if (fallbackAuth) {
523+
auths.push(fallbackAuth);
524+
}
514525
continue;
515526
}
516-
const fallbackAuth = await resolveProviderUsageAuthFallback({
517-
state: authProfileSourceState,
527+
528+
const directCredentialState = { ...stateBase, allowAuthProfileStore: false };
529+
const credentialProviderIds = resolveUsageCredentialProviderIds({
530+
state: directCredentialState,
518531
provider,
519532
});
520-
if (fallbackAuth) {
521-
auths.push(fallbackAuth);
522-
}
523-
continue;
524-
}
525-
526-
const directCredentialState = { ...stateBase, allowAuthProfileStore: false };
527-
const credentialProviderIds = resolveUsageCredentialProviderIds({
528-
state: directCredentialState,
529-
provider,
530-
});
531-
const hasDirectCredentialSource =
532-
Boolean(
533-
resolveProviderApiKeyFromConfig({
533+
const hasDirectCredentialSource =
534+
Boolean(
535+
resolveProviderApiKeyFromConfig({
536+
state: directCredentialState,
537+
providerIds: credentialProviderIds,
538+
}),
539+
) ||
540+
hasProviderAuthEnvCredentialSource({
534541
state: directCredentialState,
535542
providerIds: credentialProviderIds,
536-
}),
537-
) ||
538-
hasProviderAuthEnvCredentialSource({
539-
state: directCredentialState,
540-
providerIds: credentialProviderIds,
541-
}) ||
542-
hasProviderUsageAuthEnvCredentialSource({
543-
state: directCredentialState,
544-
providerIds: credentialProviderIds,
545-
});
546-
const allowAuthProfileStore =
547-
hasDirectCredentialSource ||
548-
(hasAuthProfileStoreSource &&
549-
hasAuthProfileCredentialSource({
550-
state: authProfileSourceState,
543+
}) ||
544+
hasProviderUsageAuthEnvCredentialSource({
545+
state: directCredentialState,
551546
providerIds: credentialProviderIds,
552-
}));
553-
const state: UsageAuthState = {
554-
...stateBase,
555-
allowAuthProfileStore,
556-
};
557-
const hasPluginCredentialSource = hasDirectCredentialSource || allowAuthProfileStore;
547+
});
548+
const allowAuthProfileStore =
549+
hasDirectCredentialSource ||
550+
(hasAuthProfileStoreSource &&
551+
hasAuthProfileCredentialSource({
552+
state: authProfileSourceState,
553+
providerIds: credentialProviderIds,
554+
}));
555+
const state: UsageAuthState = {
556+
...stateBase,
557+
allowAuthProfileStore,
558+
};
559+
const hasPluginCredentialSource = hasDirectCredentialSource || allowAuthProfileStore;
558560

559-
if (hasPluginCredentialSource) {
560-
const pluginAuth = await resolveProviderUsageAuthViaPlugin({
561+
if (hasPluginCredentialSource) {
562+
const pluginAuth = await resolveProviderUsageAuthViaPlugin({
563+
state,
564+
provider,
565+
});
566+
if (pluginAuth.auth) {
567+
auths.push(pluginAuth.auth);
568+
continue;
569+
}
570+
if (pluginAuth.handled) {
571+
continue;
572+
}
573+
}
574+
const fallbackAuth = await resolveProviderUsageAuthFallback({
561575
state,
562576
provider,
563577
});
564-
if (pluginAuth.auth) {
565-
auths.push(pluginAuth.auth);
566-
continue;
578+
if (fallbackAuth) {
579+
auths.push(fallbackAuth);
567580
}
568-
if (pluginAuth.handled) {
569-
continue;
581+
} catch (error) {
582+
if (!params.onError) {
583+
throw error;
570584
}
571-
}
572-
const fallbackAuth = await resolveProviderUsageAuthFallback({
573-
state,
574-
provider,
575-
});
576-
if (fallbackAuth) {
577-
auths.push(fallbackAuth);
585+
params.onError(provider, error);
578586
}
579587
}
580588

‎src/infra/provider-usage.load.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import { createProviderUsageFetch, makeResponse } from "../test-utils/provider-usage-fetch.js";
44
import {
5+
getProviderUsageAuthWithPluginMock,
56
getProviderUsageSnapshotWithPluginMock,
67
resetProviderUsageSnapshotWithPluginMock,
78
} from "./provider-usage-plugin-runtime.test-mocks.js";
@@ -16,6 +17,7 @@ import type { ProviderUsageSnapshot } from "./provider-usage.types.js";
1617

1718
type ProviderAuth = ProviderUsageAuth<typeof loadProviderUsageSummary>;
1819
const googleGeminiCliProvider = "google-gemini-cli" as unknown as ProviderAuth["provider"];
20+
const resolveProviderUsageAuthWithPluginMock = getProviderUsageAuthWithPluginMock();
1921
const resolveProviderUsageSnapshotWithPluginMock = getProviderUsageSnapshotWithPluginMock();
2022

2123
describe("provider-usage.load", () => {
@@ -214,6 +216,35 @@ describe("provider-usage.load", () => {
214216
]);
215217
});
216218

219+
it("keeps successful provider usage when a sibling auth hook rejects", async () => {
220+
resolveProviderUsageAuthWithPluginMock.mockImplementation(async ({ provider }) => {
221+
if (provider === "anthropic") {
222+
throw new Error("auth failed");
223+
}
224+
return { token: `${provider}-token` };
225+
});
226+
resolveProviderUsageSnapshotWithPluginMock.mockImplementation(async ({ provider }) => ({
227+
provider,
228+
displayName: provider,
229+
windows: [{ label: "5h", usedPercent: 12 }],
230+
}));
231+
232+
const summary = await loadProviderUsageSummary({
233+
providers: ["anthropic", "openai"],
234+
config: {},
235+
env: {},
236+
});
237+
238+
expect(summary.providers).toEqual([
239+
{ provider: "anthropic", displayName: "Claude", windows: [], error: "auth failed" },
240+
{
241+
provider: "openai",
242+
displayName: "openai",
243+
windows: [{ label: "5h", usedPercent: 12 }],
244+
},
245+
]);
246+
});
247+
217248
it("throws when fetch is unavailable", async () => {
218249
const previousFetch = globalThis.fetch;
219250
vi.stubGlobal("fetch", undefined);

‎src/infra/provider-usage.load.ts‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -122,26 +122,31 @@ export async function loadProviderUsageSummary(
122122
const displayNames = new Map(
123123
descriptors.map((descriptor) => [descriptor.provider, descriptor.displayName]),
124124
);
125+
const providerOrder = new Map(descriptors.map(({ provider }, index) => [provider, index]));
126+
const failureSnapshot = (provider: UsageProviderId, error: string): ProviderUsageSnapshot => ({
127+
provider,
128+
displayName: displayNames.get(provider) ?? providerUsageLabel(provider) ?? provider,
129+
windows: [],
130+
error,
131+
});
132+
const authFailures: ProviderUsageSnapshot[] = [];
125133
const auths = await resolveProviderAuths({
126134
providers: descriptors.map((descriptor) => descriptor.provider),
127135
auth: opts.auth,
128136
agentDir: opts.agentDir,
129137
config,
130138
env,
131139
skipPluginAuthWithoutCredentialSource: opts.skipPluginAuthWithoutCredentialSource,
140+
onError: (provider, error) => {
141+
const message = error instanceof Error ? error.message : String(error);
142+
authFailures.push(failureSnapshot(provider, message.trim() || "Auth failed"));
143+
},
132144
});
133-
if (auths.length === 0) {
145+
if (auths.length === 0 && authFailures.length === 0) {
134146
return { updatedAt: now, providers: [] };
135147
}
136148

137149
const tasks = auths.map((auth) => {
138-
const failureSnapshot = (error: string): ProviderUsageSnapshot => ({
139-
provider: auth.provider,
140-
displayName:
141-
displayNames.get(auth.provider) ?? providerUsageLabel(auth.provider) ?? auth.provider,
142-
windows: [],
143-
error,
144-
});
145150
return raceUsageTimeout(
146151
fetchProviderUsageSnapshot({
147152
auth,
@@ -153,20 +158,18 @@ export async function loadProviderUsageSummary(
153158
fetchFn,
154159
}),
155160
timeoutMs + 1000,
156-
{
157-
provider: auth.provider,
158-
displayName:
159-
displayNames.get(auth.provider) ?? providerUsageLabel(auth.provider) ?? auth.provider,
160-
windows: [],
161-
error: "Timeout",
162-
},
161+
failureSnapshot(auth.provider, "Timeout"),
163162
).catch((error: unknown) => {
164163
const message = error instanceof Error ? error.message : String(error);
165-
return failureSnapshot(message.trim() || "Fetch failed");
164+
return failureSnapshot(auth.provider, message.trim() || "Fetch failed");
166165
});
167166
});
168167

169-
const snapshots = await Promise.all(tasks);
168+
const snapshots = [...(await Promise.all(tasks)), ...authFailures].toSorted(
169+
(left, right) =>
170+
(providerOrder.get(left.provider) ?? Number.MAX_SAFE_INTEGER) -
171+
(providerOrder.get(right.provider) ?? Number.MAX_SAFE_INTEGER),
172+
);
170173
const providers = snapshots.filter((entry) => {
171174
if (entry.windows.length > 0) {
172175
return true;

0 commit comments

Comments
 (0)