Skip to content

Commit d6e1f01

Browse files
authored
fix(gateway/ui): record model auth unavailability reasons; gate composers only on actionable auth failures (#131697)
* fix(gateway): preserve model auth unavailability reasons Record missing credentials, unusable auth, and cooldown separately from unknown availability. Carry native runtime auth facts and retry times through the additive models.list projection without changing protocol versions. * fix(ui): gate composers only on actionable auth failures Read producer availability reasons in chat and new-session gates. Preserve Model Setup for missing credentials, keep accurate rejection copy, and allow sending during cooldown or unknown availability. Keep unavailable picker options disabled. * fix(gateway): distinguish permanent auth rejection from cooldown Keep permanently rejected profiles and inline credentials actionable without a retry timestamp. Use only viable transient profiles for the earliest recovery time, preserving explicit profile retry behavior. * test: isolate submit gates and native runtime availability fixtures Extract the existing submit-gate suite and shared draft fixture to stay within the file-size limit. Supply registered CLI metadata through the existing test boundary so availability checks do not cold-load executable plugin setup code. * chore(protocol): regenerate Swift gateway models for availability reasons * test(gateway): expect availability reasons in models.list projections
1 parent 2f3cd08 commit d6e1f01

30 files changed

Lines changed: 1277 additions & 546 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14541,6 +14541,8 @@ public struct ModelChoice: Codable, Sendable {
1454114541
public let alias: String?
1454214542
public let tags: [String]?
1454314543
public let available: Bool?
14544+
public let unavailablereason: AnyCodable?
14545+
public let unavailableuntil: Int?
1454414546
public let contextwindow: Int?
1454514547
public let contextwindows: [[String: AnyCodable]]?
1454614548
public let contextwindowdefault: String?
@@ -14559,6 +14561,8 @@ public struct ModelChoice: Codable, Sendable {
1455914561
alias: String? = nil,
1456014562
tags: [String]? = nil,
1456114563
available: Bool? = nil,
14564+
unavailablereason: AnyCodable? = nil,
14565+
unavailableuntil: Int? = nil,
1456214566
contextwindow: Int? = nil,
1456314567
contextwindows: [[String: AnyCodable]]? = nil,
1456414568
contextwindowdefault: String? = nil,
@@ -14576,6 +14580,8 @@ public struct ModelChoice: Codable, Sendable {
1457614580
self.alias = alias
1457714581
self.tags = tags
1457814582
self.available = available
14583+
self.unavailablereason = unavailablereason
14584+
self.unavailableuntil = unavailableuntil
1457914585
self.contextwindow = contextwindow
1458014586
self.contextwindows = contextwindows
1458114587
self.contextwindowdefault = contextwindowdefault
@@ -14595,6 +14601,8 @@ public struct ModelChoice: Codable, Sendable {
1459514601
case alias
1459614602
case tags
1459714603
case available
14604+
case unavailablereason = "unavailableReason"
14605+
case unavailableuntil = "unavailableUntil"
1459814606
case contextwindow = "contextWindow"
1459914607
case contextwindows = "contextWindows"
1460014608
case contextwindowdefault = "contextWindowDefault"

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,7 @@ Chat error banners, including cloud runner failures, keep a compact preview. Ope
584584
- If you send a message while a model picker change for the same session is still saving, the composer waits for that session patch before calling `chat.send` so the send uses the selected model.
585585
- Typing `/new` creates and switches to the same fresh dashboard session as New Chat, except when `session.dmScope: "main"` is configured and the current parent is the agent's main session; then it resets the main session in place. Typing `/reset` keeps the Gateway's explicit in-place reset for the current session.
586586
- The chat model picker requests the Gateway's configured model view. If `agents.defaults.modelPolicy.allow` is non-empty, that policy drives the picker, including `provider/*` entries that keep provider-scoped catalogs dynamic. Otherwise the picker shows configured entries plus providers with usable auth; aliases and settings under `agents.defaults.models` do not restrict it. The full catalog stays available through the debug `models.list` RPC with `view: "all"`.
587+
- Chat and New Session block sending when the Gateway reports missing provider credentials or a confirmed authentication failure. Missing credentials point to **Model Setup**; authentication failures ask you to review the credential or sign-in. Temporary credential cooldowns and unknown model availability do not block sending or show an authentication banner; run errors remain visible in the transcript. Unavailable model choices stay disabled in the picker.
587588
- When fresh Gateway session usage reports include current context tokens, the chat composer toolbar shows a small context usage ring with the used percentage. Open the ring for the current context window, latest-run token counts and estimated total cost, provider/model identity, and the latest provider response's input/output/cache cost breakdown when reported. The ring switches to warning styling at high context pressure. Stale token snapshots are hidden until the Gateway reports fresh usage again.
588589

589590
</Accordion>

‎packages/gateway-protocol/src/schema/agents-models-skills.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,24 @@ describe("Models auth params schemas", () => {
262262
});
263263

264264
describe("ModelsListResultSchema", () => {
265+
it("accepts closed unavailability reasons and epoch-millisecond retry times", () => {
266+
const model = { id: "test-model", name: "Test Model", provider: "custom", available: false };
267+
for (const unavailableReason of ["missing-auth", "auth-failed", "cooldown"]) {
268+
expectAccepted(ModelsListResultSchema, { models: [{ ...model, unavailableReason }] });
269+
}
270+
expectAccepted(ModelsListResultSchema, {
271+
models: [{ ...model, unavailableReason: "cooldown", unavailableUntil: 2_000_000_000_000 }],
272+
});
273+
expectRejected(ModelsListResultSchema, {
274+
models: [{ ...model, unavailableReason: "unknown" }],
275+
});
276+
for (const unavailableUntil of [-1, 1.5, "2033-05-18T03:33:20.000Z"]) {
277+
expectRejected(ModelsListResultSchema, {
278+
models: [{ ...model, unavailableReason: "cooldown", unavailableUntil }],
279+
});
280+
}
281+
});
282+
265283
it("accepts stable public input capabilities", () => {
266284
const model = {
267285
id: "gpt-image",

‎packages/gateway-protocol/src/schema/agents-models-skills.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ export const ModelChoiceSchema = closedObject({
6161
alias: Type.Optional(NonEmptyString),
6262
tags: Type.Optional(Type.Array(NonEmptyString)),
6363
available: Type.Optional(Type.Boolean()),
64+
unavailableReason: Type.Optional(
65+
Type.Union([
66+
Type.Literal("missing-auth"),
67+
Type.Literal("auth-failed"),
68+
Type.Literal("cooldown"),
69+
]),
70+
),
71+
/** Earliest known retry time in epoch milliseconds, only for unavailable models. */
72+
unavailableUntil: Type.Optional(Type.Integer({ minimum: 0 })),
6473
contextWindow: Type.Optional(Type.Integer({ minimum: 1 })),
6574
contextWindows: Type.Optional(Type.Array(GatewayContextWindowOptionSchema)),
6675
contextWindowDefault: Type.Optional(NonEmptyString),
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import { describe, expect, it } from "vitest";
2+
import { createModelAuthAvailabilityResolver } from "./model-auth-availability.js";
3+
import {
4+
authStore,
5+
dualRoutes,
6+
evaluate,
7+
routeResolverFactory,
8+
} from "./model-auth-availability.test-support.js";
9+
10+
describe("model auth unavailability reasons", () => {
11+
it.each(["openai", "anthropic"])(
12+
"distinguishes missing, failed, unknown, and ready credentials for %s",
13+
(provider) => {
14+
const cases = [
15+
{ label: "no evidence", profiles: {}, reason: "missing-auth" },
16+
{
17+
label: "expired without refresh",
18+
profiles: { test: { type: "token", provider, token: "expired-token", expires: 1 } },
19+
reason: "auth-failed",
20+
},
21+
{
22+
label: "invalid reference",
23+
profiles: {
24+
test: {
25+
type: "api_key",
26+
provider,
27+
keyRef: { source: "file", provider: "absent", id: "key" },
28+
},
29+
},
30+
reason: "auth-failed",
31+
},
32+
{
33+
label: "unread reference",
34+
profiles: {
35+
test: {
36+
type: "api_key",
37+
provider,
38+
keyRef: { source: "env", provider: "default", id: "UNREAD_KEY" },
39+
},
40+
},
41+
reason: undefined,
42+
},
43+
{
44+
label: "ready",
45+
profiles: { test: { type: "api_key", provider, key: "test-key" } },
46+
reason: undefined,
47+
},
48+
];
49+
for (const { label, profiles, reason } of cases) {
50+
const result = createModelAuthAvailabilityResolver({
51+
cfg: {},
52+
authStore: authStore(profiles),
53+
env: {},
54+
routeResolverFactory: routeResolverFactory(dualRoutes),
55+
}).evaluateModelAuth(provider);
56+
expect.soft(result.unavailableReason, label).toBe(reason);
57+
expect.soft(result.unavailableUntil, label).toBeUndefined();
58+
}
59+
},
60+
);
61+
62+
it("reports the earliest retry among viable cooling profiles, excluding invalid or permanently rejected profiles", () => {
63+
const until = Date.now() + 60_000;
64+
const store = authStore({
65+
first: { type: "api_key", provider: "openai", key: "first-key" },
66+
second: { type: "api_key", provider: "openai", key: "second-key" },
67+
invalid: { type: "token", provider: "openai", token: "expired-token", expires: 1 },
68+
rejected: { type: "api_key", provider: "openai", key: "rejected-key" },
69+
});
70+
store.usageStats = {
71+
first: { cooldownUntil: until + 60_000 },
72+
second: { cooldownUntil: until },
73+
invalid: { cooldownUntil: until - 30_000 },
74+
rejected: { disabledUntil: until - 45_000, disabledReason: "auth_permanent" },
75+
};
76+
expect(evaluate({ store, ref: { preferredProfileId: "first" } })).toMatchObject({
77+
availability: false,
78+
unavailableReason: "cooldown",
79+
unavailableUntil: until,
80+
});
81+
expect(evaluate({ store, ref: { lockedProfileId: "invalid" } })).toMatchObject({
82+
availability: false,
83+
unavailableReason: "auth-failed",
84+
});
85+
});
86+
87+
it.each(["openai", "anthropic"])(
88+
"reports permanent auth rejection for %s without removing explicit profile retry",
89+
(provider) => {
90+
const store = authStore({ bound: { type: "api_key", provider, key: "rejected-key" } });
91+
store.usageStats = {
92+
bound: { disabledUntil: Date.now() + 60_000, disabledReason: "auth_permanent" },
93+
};
94+
const resolver = createModelAuthAvailabilityResolver({
95+
cfg: {},
96+
authStore: store,
97+
env: {},
98+
routeResolverFactory: routeResolverFactory(dualRoutes),
99+
});
100+
const result = resolver.evaluateModelAuth(provider);
101+
expect(result).toMatchObject({ availability: false, unavailableReason: "auth-failed" });
102+
expect(result.unavailableUntil).toBeUndefined();
103+
const locked = resolver.evaluateModelAuth(provider, { lockedProfileId: "bound" });
104+
expect(locked.availability).toBe(true);
105+
expect(locked.unavailableReason).toBeUndefined();
106+
},
107+
);
108+
109+
it.each(["profile", "inline"] as const)(
110+
"distinguishes %s permanent auth rejection from active retry windows",
111+
(source) => {
112+
const until = Date.now() + 60_000;
113+
const cases = [
114+
{ stats: { cooldownUntil: until }, reason: "cooldown", retryAt: until },
115+
{
116+
stats: { disabledUntil: until, disabledReason: "auth_permanent" },
117+
reason: "auth-failed",
118+
retryAt: undefined,
119+
},
120+
{
121+
stats: { disabledUntil: 1, disabledReason: "auth_permanent", cooldownUntil: until },
122+
reason: "cooldown",
123+
retryAt: until,
124+
},
125+
{
126+
stats: { disabledUntil: until, disabledReason: "billing" },
127+
reason: "cooldown",
128+
retryAt: until,
129+
},
130+
] as const;
131+
for (const { stats, reason, retryAt } of cases) {
132+
const store = authStore({
133+
bound: { type: "api_key", provider: "anthropic", key: "test-key" },
134+
});
135+
store.usageStats = {
136+
[source === "profile" ? "bound" : "inline-api-key:anthropic"]: stats,
137+
};
138+
const result = createModelAuthAvailabilityResolver({
139+
cfg: {
140+
models: {
141+
providers: {
142+
anthropic: {
143+
auth: "api-key",
144+
apiKey: source === "profile" ? "bound" : "inline-key",
145+
baseUrl: "https://api.anthropic.com",
146+
models: [],
147+
},
148+
},
149+
},
150+
},
151+
authStore: store,
152+
env: {},
153+
}).evaluateModelAuth("anthropic");
154+
expect.soft(result, JSON.stringify(stats)).toMatchObject({
155+
availability: false,
156+
unavailableReason: reason,
157+
});
158+
expect.soft(result.unavailableUntil, JSON.stringify(stats)).toBe(retryAt);
159+
}
160+
},
161+
);
162+
});
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import type { OpenClawConfig } from "../config/types.openclaw.js";
2+
import type {
3+
ProviderModelRouteCandidate,
4+
ProviderModelRouteResolution,
5+
} from "../plugin-sdk/provider-model-types.js";
6+
import type { PreparedAgentCredentialModes } from "./agent-auth-credential-modes.js";
7+
import type { RuntimeAuthMaterialization } from "./auth-profiles/runtime-materializations.js";
8+
import type { AuthProfileStore } from "./auth-profiles/types.js";
9+
import {
10+
createModelAuthAvailabilityResolver,
11+
type ModelAuthAvailabilityRef,
12+
} from "./model-auth-availability.js";
13+
import type { createOpenAIModelRoutesResolver } from "./openai-model-routes.js";
14+
15+
export const platformRoute = {
16+
api: "openai-responses",
17+
baseUrl: "https://api.openai.com/v1",
18+
authRequirement: "api-key",
19+
requestTransportOverrides: "none",
20+
runtimePolicy: { compatibleIds: ["openclaw", "codex"] },
21+
} satisfies ProviderModelRouteCandidate;
22+
23+
export const subscriptionRoute = {
24+
api: "openai-chatgpt-responses",
25+
baseUrl: "https://chatgpt.com/backend-api/codex",
26+
authRequirement: "subscription",
27+
requestTransportOverrides: "none",
28+
runtimePolicy: { compatibleIds: ["openclaw", "codex"] },
29+
} satisfies ProviderModelRouteCandidate;
30+
31+
export const dualRoutes = {
32+
kind: "routes",
33+
defaultRuntimeId: "codex",
34+
routes: [platformRoute, subscriptionRoute],
35+
} satisfies ProviderModelRouteResolution;
36+
37+
export function routeResolverFactory(resolution: ProviderModelRouteResolution | null) {
38+
return (() => () => resolution) as typeof createOpenAIModelRoutesResolver;
39+
}
40+
41+
export function authStore(
42+
profiles: Record<string, unknown> = {},
43+
order?: AuthProfileStore["order"],
44+
): AuthProfileStore {
45+
return {
46+
version: 1,
47+
profiles: profiles as AuthProfileStore["profiles"],
48+
...(order ? { order } : {}),
49+
};
50+
}
51+
52+
export function evaluate(params: {
53+
cfg?: OpenClawConfig | Record<string, unknown>;
54+
env?: NodeJS.ProcessEnv;
55+
ref?: ModelAuthAvailabilityRef;
56+
resolution?: ProviderModelRouteResolution | null;
57+
store?: AuthProfileStore;
58+
preparedRuntimeAuthStore?: AuthProfileStore;
59+
syntheticAuthProviderRefs?: readonly string[];
60+
preparedRuntimeAuthModes?: PreparedAgentCredentialModes;
61+
preparedRuntimeAuthMaterializations?: readonly RuntimeAuthMaterialization[];
62+
}) {
63+
return createModelAuthAvailabilityResolver({
64+
cfg: (params.cfg ?? {}) as OpenClawConfig,
65+
authStore: params.store ?? authStore(),
66+
env: params.env ?? {},
67+
routeResolverFactory: routeResolverFactory(params.resolution ?? dualRoutes),
68+
syntheticAuthProviderRefs: params.syntheticAuthProviderRefs,
69+
preparedRuntimeAuthModes: params.preparedRuntimeAuthModes,
70+
preparedRuntimeAuthStore: params.preparedRuntimeAuthStore,
71+
preparedRuntimeAuthMaterializations: params.preparedRuntimeAuthMaterializations,
72+
}).evaluateModelAuth("openai", params.ref);
73+
}

0 commit comments

Comments
 (0)