Skip to content

Commit 73a95d3

Browse files
MarvintheboredPeetiegonzalezclaudevincentkoc
authored
fix(gateway): read-only persisted fast path for models.list catalog (#76406)
* fix(gateway): read-only fast path for models.list catalog loading The gateway model catalog refresh calls loadModelCatalog without readOnly, triggering ensureOpenClawModelsJson (60-70s), full PI SDK registry instantiation, auth storage discovery, and live provider plugin augmentation on every Control UI list/refresh. None of this is needed for a read-only UI listing. Three changes: 1. Gateway catalog refresh now passes readOnly: true to loadModelCatalog. 2. In readOnly mode, skip augmentModelCatalogWithProviderPlugins — live provider discovery is explicit admin/background work, not a UI list operation. 3. Add a persisted models.json fast path: when readOnly is true, first try reading the existing models.json directly and converting providers.<provider>.models[] to catalog rows. Falls back to the full PI registry path if the file is missing or unreadable. Observed improvement on a production install: loadGatewayModelCatalog: 967 entries / 4651ms → 89 entries / 8ms Live models.list during startup: ~18s → ~2s Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(gateway): preserve full model catalog view * fix(agents): preserve read-only catalog defaults * fix(agents): preserve provider catalog defaults --------- Co-authored-by: Marvinthebored <[email protected]> Co-authored-by: Claude Opus 4.6 <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
1 parent de24a05 commit 73a95d3

8 files changed

Lines changed: 371 additions & 50 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Docs: https://docs.openclaw.ai
2929
- CLI/plugins: reject missing plugin ids before config writes in `plugins enable` and `plugins disable` so a typo no longer persists a stale config entry. (#73554) Thanks @ai-hpc.
3030
- Agents/sessions: preserve delivered trailing assistant replies during session-file repair so Telegram/WebChat history is not rewritten to drop already-delivered responses. Fixes #76329. Thanks @obviyus.
3131
- Gateway/chat history: preserve oversized transcript turns as explicit omitted-message placeholders while avoiding large JSONL parse stalls. Thanks @Marvinthebored and @vincentkoc.
32+
- Gateway/models: keep read-only model-list responses on registry-compatible fallbacks and metadata defaults, so empty or minimal persisted model files do not hide built-ins or custom model capabilities. Thanks @Marvinthebored.
3233
- Gateway: preserve stack diagnostics when `chat.send` or agent attachment parsing/staging fails, improving image-send failure triage. Refs #63432. (#75135) Thanks @keen0206.
3334
- Heartbeats/Codex: stop sending the legacy `HEARTBEAT_OK` prompt instruction when heartbeat turns have the structured `heartbeat_respond` tool, while keeping the text sentinel for legacy automatic heartbeat replies. Thanks @pashpashpash.
3435
- Agent runtimes: fail explicit plugin runtime selections honestly when the requested harness is unavailable instead of silently falling back to the embedded PI runtime. Thanks @pashpashpash.

‎src/agents/model-catalog.test.ts‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ let augmentCatalogMock: ReturnType<typeof vi.fn>;
1515
let ensureOpenClawModelsJsonMock: ReturnType<typeof vi.fn>;
1616
let currentPluginMetadataSnapshotMock: ReturnType<typeof vi.fn>;
1717
let loadPluginMetadataSnapshotMock: ReturnType<typeof vi.fn>;
18+
let readFileMock: ReturnType<typeof vi.fn>;
1819

1920
vi.mock("./model-suppression.runtime.js", () => ({
2021
shouldSuppressBuiltInModel: (params: { provider?: string; id?: string }) =>
@@ -70,6 +71,11 @@ function mockSingleOpenAiCatalogModel() {
7071

7172
describe("loadModelCatalog", () => {
7273
beforeAll(async () => {
74+
readFileMock = vi.fn();
75+
vi.doMock("node:fs/promises", async (importOriginal) => ({
76+
...(await importOriginal<typeof import("node:fs/promises")>()),
77+
readFile: readFileMock,
78+
}));
7379
ensureOpenClawModelsJsonMock = vi.fn().mockResolvedValue({ agentDir: "/tmp", wrote: false });
7480
vi.doMock("./models-config.js", () => ({
7581
ensureOpenClawModelsJson: ensureOpenClawModelsJsonMock,
@@ -104,6 +110,10 @@ describe("loadModelCatalog", () => {
104110

105111
beforeEach(() => {
106112
resetModelCatalogCacheForTest();
113+
readFileMock.mockReset();
114+
readFileMock.mockRejectedValue(
115+
Object.assign(new Error("models.json missing"), { code: "ENOENT" }),
116+
);
107117
ensureOpenClawModelsJsonMock.mockClear();
108118
augmentCatalogMock.mockClear();
109119
currentPluginMetadataSnapshotMock.mockReset();
@@ -117,6 +127,7 @@ describe("loadModelCatalog", () => {
117127
});
118128

119129
afterAll(() => {
130+
vi.doUnmock("node:fs/promises");
120131
vi.doUnmock("./models-config.js");
121132
vi.doUnmock("./agent-paths.js");
122133
vi.doUnmock("../plugins/provider-runtime.runtime.js");
@@ -217,6 +228,163 @@ describe("loadModelCatalog", () => {
217228
expect(discoverAuthStorage).toHaveBeenCalledWith("/tmp/openclaw", { readOnly: true });
218229
});
219230

231+
it("filters suppressed built-ins from persisted read-only catalog rows", async () => {
232+
readFileMock.mockResolvedValueOnce(
233+
JSON.stringify({
234+
providers: {
235+
"openai-codex": {
236+
models: [
237+
{
238+
id: "gpt-5.3-codex-spark",
239+
name: "GPT-5.3 Codex Spark",
240+
reasoning: true,
241+
contextWindow: 128000,
242+
input: ["text"],
243+
},
244+
{
245+
id: "gpt-5.4",
246+
name: "GPT-5.4",
247+
reasoning: true,
248+
contextWindow: 272000,
249+
input: ["text", "image"],
250+
},
251+
],
252+
},
253+
openai: {
254+
models: [
255+
{
256+
id: "gpt-5.3-codex-spark",
257+
name: "GPT-5.3 Codex Spark",
258+
},
259+
],
260+
},
261+
},
262+
}),
263+
);
264+
265+
const result = await loadModelCatalog({ config: {} as OpenClawConfig, readOnly: true });
266+
267+
expect(result).toEqual([
268+
{
269+
provider: "openai-codex",
270+
id: "gpt-5.4",
271+
name: "GPT-5.4",
272+
reasoning: true,
273+
contextWindow: 272000,
274+
input: ["text", "image"],
275+
compat: undefined,
276+
},
277+
]);
278+
expect(ensureOpenClawModelsJsonMock).not.toHaveBeenCalled();
279+
expect(augmentCatalogMock).not.toHaveBeenCalled();
280+
});
281+
282+
it("falls back to the registry when persisted read-only catalog has no model rows", async () => {
283+
readFileMock.mockResolvedValueOnce(
284+
JSON.stringify({
285+
providers: {
286+
openai: {
287+
modelOverrides: {
288+
"gpt-4.1": {
289+
contextWindow: 128000,
290+
},
291+
},
292+
},
293+
},
294+
}),
295+
);
296+
const discoverAuthStorage = vi.fn(() => ({
297+
getOAuthProviders: () => [],
298+
}));
299+
__setModelCatalogImportForTest(
300+
async () =>
301+
({
302+
discoverAuthStorage,
303+
AuthStorage: function AuthStorage() {},
304+
ModelRegistry: class {
305+
getAll() {
306+
return [{ id: "gpt-4.1", name: "GPT-4.1", provider: "openai" }];
307+
}
308+
},
309+
}) as unknown as PiSdkModule,
310+
);
311+
312+
const result = await loadModelCatalog({ config: {} as OpenClawConfig, readOnly: true });
313+
314+
expect(result).toEqual([{ id: "gpt-4.1", name: "GPT-4.1", provider: "openai" }]);
315+
expect(ensureOpenClawModelsJsonMock).not.toHaveBeenCalled();
316+
expect(discoverAuthStorage).toHaveBeenCalledWith("/tmp/openclaw", { readOnly: true });
317+
});
318+
319+
it("preserves registry defaults for minimal persisted read-only catalog rows", async () => {
320+
readFileMock.mockResolvedValueOnce(
321+
JSON.stringify({
322+
providers: {
323+
custom: {
324+
models: [{ id: "local-tiny" }],
325+
},
326+
},
327+
}),
328+
);
329+
330+
const result = await loadModelCatalog({ config: {} as OpenClawConfig, readOnly: true });
331+
332+
expect(result).toEqual([
333+
{
334+
provider: "custom",
335+
id: "local-tiny",
336+
name: "local-tiny",
337+
reasoning: false,
338+
contextWindow: 128000,
339+
input: ["text"],
340+
compat: undefined,
341+
},
342+
]);
343+
expect(ensureOpenClawModelsJsonMock).not.toHaveBeenCalled();
344+
expect(augmentCatalogMock).not.toHaveBeenCalled();
345+
});
346+
347+
it("preserves provider context defaults for persisted read-only catalog rows", async () => {
348+
readFileMock.mockResolvedValueOnce(
349+
JSON.stringify({
350+
providers: {
351+
custom: {
352+
contextWindow: 262144,
353+
models: [
354+
{ id: "inherits-provider-context" },
355+
{ id: "overrides-context", contextWindow: 65536 },
356+
],
357+
},
358+
},
359+
}),
360+
);
361+
362+
const result = await loadModelCatalog({ config: {} as OpenClawConfig, readOnly: true });
363+
364+
expect(result).toEqual([
365+
{
366+
provider: "custom",
367+
id: "inherits-provider-context",
368+
name: "inherits-provider-context",
369+
reasoning: false,
370+
contextWindow: 262144,
371+
input: ["text"],
372+
compat: undefined,
373+
},
374+
{
375+
provider: "custom",
376+
id: "overrides-context",
377+
name: "overrides-context",
378+
reasoning: false,
379+
contextWindow: 65536,
380+
input: ["text"],
381+
compat: undefined,
382+
},
383+
]);
384+
expect(ensureOpenClawModelsJsonMock).not.toHaveBeenCalled();
385+
expect(augmentCatalogMock).not.toHaveBeenCalled();
386+
});
387+
220388
it("does not synthesize stale openai-codex/gpt-5.3-codex-spark entries from gpt-5.4", async () => {
221389
mockPiDiscoveryModels([
222390
{

‎src/agents/model-catalog.ts‎

Lines changed: 109 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { readFile } from "node:fs/promises";
12
import { join } from "node:path";
23
import { getRuntimeConfig } from "../config/config.js";
34
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -20,6 +21,7 @@ import { ensureOpenClawModelsJson } from "./models-config.js";
2021
import { normalizeProviderId } from "./provider-id.js";
2122

2223
const log = createSubsystemLogger("model-catalog");
24+
const PI_CUSTOM_MODEL_DEFAULT_CONTEXT_WINDOW = 128_000;
2325

2426
export type { ModelCatalogEntry, ModelInputType } from "./model-catalog.types.js";
2527
export {
@@ -161,12 +163,106 @@ export function loadManifestModelCatalog(params: {
161163
});
162164
}
163165

166+
function sortModelCatalogEntries(entries: ModelCatalogEntry[]): ModelCatalogEntry[] {
167+
return entries.toSorted((a, b) => {
168+
const p = a.provider.localeCompare(b.provider);
169+
if (p !== 0) {
170+
return p;
171+
}
172+
return a.name.localeCompare(b.name);
173+
});
174+
}
175+
176+
function normalizePersistedModelCatalogEntry(
177+
providerRaw: string,
178+
entry: Record<string, unknown>,
179+
defaults?: {
180+
contextWindow?: number;
181+
},
182+
): ModelCatalogEntry | undefined {
183+
const id = normalizeOptionalString(entry.id) ?? "";
184+
if (!id) {
185+
return undefined;
186+
}
187+
const provider = normalizeProviderId(providerRaw);
188+
if (!provider) {
189+
return undefined;
190+
}
191+
const name = normalizeOptionalString(entry.name ?? id) || id;
192+
const contextWindow =
193+
typeof entry?.contextWindow === "number" && entry.contextWindow > 0
194+
? entry.contextWindow
195+
: defaults?.contextWindow !== undefined
196+
? defaults.contextWindow
197+
: PI_CUSTOM_MODEL_DEFAULT_CONTEXT_WINDOW;
198+
const reasoning = typeof entry?.reasoning === "boolean" ? entry.reasoning : false;
199+
const parsedInput = Array.isArray(entry?.input)
200+
? entry.input.filter((value): value is ModelInputType =>
201+
["text", "image", "audio", "video", "document"].includes(String(value)),
202+
)
203+
: undefined;
204+
const input: ModelInputType[] = parsedInput?.length ? parsedInput : ["text"];
205+
const compat =
206+
entry?.compat && typeof entry.compat === "object"
207+
? (entry.compat as ModelCatalogEntry["compat"])
208+
: undefined;
209+
return { id, name, provider, contextWindow, reasoning, input, compat };
210+
}
211+
212+
async function loadReadOnlyPersistedModelCatalog(params?: {
213+
config?: OpenClawConfig;
214+
}): Promise<ModelCatalogEntry[]> {
215+
const cfg = params?.config ?? getRuntimeConfig();
216+
const agentDir = resolveOpenClawAgentDir();
217+
const raw = await readFile(join(agentDir, "models.json"), "utf8");
218+
const parsed = JSON.parse(raw) as Record<string, unknown>;
219+
const models: ModelCatalogEntry[] = [];
220+
const { buildShouldSuppressBuiltInModel } = await loadModelSuppression();
221+
const shouldSuppressBuiltInModel = buildShouldSuppressBuiltInModel({ config: cfg });
222+
const providers =
223+
parsed?.providers && typeof parsed.providers === "object"
224+
? (parsed.providers as Record<string, Record<string, unknown>>)
225+
: {};
226+
for (const [providerRaw, providerConfig] of Object.entries(providers)) {
227+
if (!Array.isArray(providerConfig?.models)) {
228+
continue;
229+
}
230+
const providerContextWindow =
231+
typeof providerConfig?.contextWindow === "number" && providerConfig.contextWindow > 0
232+
? providerConfig.contextWindow
233+
: undefined;
234+
for (const entry of providerConfig.models as Record<string, unknown>[]) {
235+
const normalized = normalizePersistedModelCatalogEntry(providerRaw, entry, {
236+
contextWindow: providerContextWindow,
237+
});
238+
if (normalized && !shouldSuppressBuiltInModel(normalized)) {
239+
models.push(normalized);
240+
}
241+
}
242+
}
243+
if (models.length === 0) {
244+
throw new Error("persisted model catalog has no usable model rows");
245+
}
246+
const configuredModels = buildConfiguredModelCatalog({ cfg });
247+
if (configuredModels.length > 0) {
248+
appendCatalogEntriesIfAbsent(models, configuredModels);
249+
}
250+
return sortModelCatalogEntries(models);
251+
}
252+
164253
export async function loadModelCatalog(params?: {
165254
config?: OpenClawConfig;
166255
useCache?: boolean;
167256
readOnly?: boolean;
168257
}): Promise<ModelCatalogEntry[]> {
169258
const readOnly = params?.readOnly === true;
259+
if (readOnly) {
260+
try {
261+
return await loadReadOnlyPersistedModelCatalog(params);
262+
} catch {
263+
// fall through to full catalog path
264+
}
265+
}
170266
if (!readOnly && params?.useCache === false) {
171267
modelCatalogPromise = null;
172268
}
@@ -185,14 +281,7 @@ export async function loadModelCatalog(params?: {
185281
const suffix = extra ? ` ${extra}` : "";
186282
log.info(`model-catalog stage=${stage} elapsedMs=${Date.now() - startMs}${suffix}`);
187283
};
188-
const sortModels = (entries: ModelCatalogEntry[]) =>
189-
entries.sort((a, b) => {
190-
const p = a.provider.localeCompare(b.provider);
191-
if (p !== 0) {
192-
return p;
193-
}
194-
return a.name.localeCompare(b.name);
195-
});
284+
const sortModels = sortModelCatalogEntries;
196285
try {
197286
const cfg = params?.config ?? getRuntimeConfig();
198287
if (!readOnly) {
@@ -247,18 +336,20 @@ export async function loadModelCatalog(params?: {
247336
const compat = entry?.compat && typeof entry.compat === "object" ? entry.compat : undefined;
248337
models.push({ id, name, provider, contextWindow, reasoning, input, compat });
249338
}
250-
const supplemental = await augmentModelCatalogWithProviderPlugins({
251-
config: cfg,
252-
env: process.env,
253-
context: {
339+
if (!readOnly) {
340+
const supplemental = await augmentModelCatalogWithProviderPlugins({
254341
config: cfg,
255-
agentDir,
256342
env: process.env,
257-
entries: [...models],
258-
},
259-
});
260-
if (supplemental.length > 0) {
261-
appendCatalogEntriesIfAbsent(models, supplemental);
343+
context: {
344+
config: cfg,
345+
agentDir,
346+
env: process.env,
347+
entries: [...models],
348+
},
349+
});
350+
if (supplemental.length > 0) {
351+
appendCatalogEntriesIfAbsent(models, supplemental);
352+
}
262353
}
263354
logStage("plugin-models-merged", `entries=${models.length}`);
264355

0 commit comments

Comments
 (0)