Skip to content

Commit 0022cd2

Browse files
authored
fix(cli): render models refresh JSON failures (#128981)
1 parent f3defc7 commit 0022cd2

3 files changed

Lines changed: 227 additions & 29 deletions

File tree

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

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { ExpectedCliError } from "../../cli/failure-output.js";
23

34
const mocks = vi.hoisted(() => ({ refresh: vi.fn(), getConfig: vi.fn(() => ({})) }));
45
vi.mock("../../config/config.js", () => ({ getRuntimeConfig: mocks.getConfig }));
@@ -21,7 +22,7 @@ function runtime() {
2122
beforeEach(() => mocks.refresh.mockReset());
2223

2324
describe("models refresh", () => {
24-
it("prints updated, fresh, disabled, error, and JSON results", async () => {
25+
it("prints updated, fresh, and disabled human results", async () => {
2526
const updatedRuntime = runtime();
2627
mocks.refresh.mockResolvedValueOnce({
2728
status: "updated",
@@ -50,38 +51,64 @@ describe("models refresh", () => {
5051
expect(disabledRuntime.log).toHaveBeenCalledWith(
5152
"Remote catalog refresh is disabled (models.catalogRefresh.enabled=false)",
5253
);
54+
});
5355

54-
const errorRuntime = runtime();
56+
it.each([
57+
{ name: "human", options: {} },
58+
{ name: "JSON", options: { json: true } },
59+
])("delegates $name refresh failures to the canonical CLI error owner", async ({ options }) => {
60+
const commandRuntime = runtime();
5561
mocks.refresh.mockResolvedValueOnce({
5662
status: "error",
5763
providers: 0,
5864
models: 0,
5965
error: "boom",
6066
});
61-
await modelsRefreshCommand({}, errorRuntime);
62-
expect(errorRuntime.error).toHaveBeenCalledWith("Remote catalog refresh failed: boom");
63-
expect(errorRuntime.exit).toHaveBeenCalledWith(1);
6467

65-
const jsonRuntime = runtime();
66-
mocks.refresh.mockResolvedValueOnce({ status: "disabled", providers: 0, models: 0 });
67-
await modelsRefreshCommand({ json: true }, jsonRuntime);
68-
expect(jsonRuntime.writeJson).toHaveBeenCalledWith(
69-
{ status: "disabled", providers: 0, models: 0 },
70-
0,
71-
);
72-
expect(jsonRuntime.log).not.toHaveBeenCalled();
68+
const execution = modelsRefreshCommand(options, commandRuntime);
69+
70+
await expect(execution).rejects.toBeInstanceOf(ExpectedCliError);
71+
await expect(execution).rejects.toMatchObject({
72+
message: "Remote catalog refresh failed: boom",
73+
humanOutput: "Remote catalog refresh failed: boom",
74+
machineOutput: "Remote catalog refresh failed: boom",
75+
});
76+
expect(commandRuntime.writeJson).not.toHaveBeenCalled();
77+
expect(commandRuntime.log).not.toHaveBeenCalled();
78+
expect(commandRuntime.error).not.toHaveBeenCalled();
79+
expect(commandRuntime.exit).not.toHaveBeenCalled();
7380
});
7481

75-
it("writes refresh errors to structured stdout before exiting in JSON mode", async () => {
76-
const jsonRuntime = runtime();
77-
const result = { status: "error", providers: 0, models: 0, error: "boom" };
82+
it.each([
83+
{
84+
status: "updated",
85+
providers: 2,
86+
models: 3,
87+
generatedAt: 1_753_500_000_000,
88+
},
89+
{
90+
status: "unchanged",
91+
providers: 2,
92+
models: 3,
93+
generatedAt: 1_753_500_000_000,
94+
},
95+
{
96+
status: "fresh",
97+
providers: 2,
98+
models: 3,
99+
generatedAt: 1_753_500_000_000,
100+
nextCheckInMs: 1_000,
101+
},
102+
{ status: "disabled", providers: 0, models: 0 },
103+
])("preserves the $status JSON domain payload", async (result) => {
104+
const commandRuntime = runtime();
78105
mocks.refresh.mockResolvedValueOnce(result);
79106

80-
await modelsRefreshCommand({ json: true }, jsonRuntime);
107+
await modelsRefreshCommand({ json: true }, commandRuntime);
81108

82-
expect(jsonRuntime.writeJson).toHaveBeenCalledWith(result, 0);
83-
expect(jsonRuntime.exit).toHaveBeenCalledWith(1);
84-
expect(jsonRuntime.log).not.toHaveBeenCalled();
85-
expect(jsonRuntime.error).not.toHaveBeenCalled();
109+
expect(commandRuntime.writeJson).toHaveBeenCalledWith(result, 0);
110+
expect(commandRuntime.log).not.toHaveBeenCalled();
111+
expect(commandRuntime.error).not.toHaveBeenCalled();
112+
expect(commandRuntime.exit).not.toHaveBeenCalled();
86113
});
87114
});

‎src/commands/models/refresh.ts‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ExpectedCliError } from "../../cli/failure-output.js";
12
import { getRuntimeConfig } from "../../config/config.js";
23
import { refreshRemoteModelCatalog } from "../../model-catalog/remote-refresh.js";
34
import { type RuntimeEnv, writeRuntimeJson } from "../../runtime.js";
@@ -7,22 +8,18 @@ export async function modelsRefreshCommand(
78
runtime: RuntimeEnv,
89
): Promise<void> {
910
const result = await refreshRemoteModelCatalog({ config: getRuntimeConfig(), force: true });
11+
if (result.status === "error") {
12+
const message = `Remote catalog refresh failed: ${result.error}`;
13+
throw new ExpectedCliError({ message, humanOutput: message, machineOutput: message });
14+
}
1015
if (options.json) {
1116
writeRuntimeJson(runtime, result, 0);
12-
if (result.status === "error") {
13-
runtime.exit(1);
14-
}
1517
return;
1618
}
1719
if (result.status === "disabled") {
1820
runtime.log("Remote catalog refresh is disabled (models.catalogRefresh.enabled=false)");
1921
return;
2022
}
21-
if (result.status === "error") {
22-
runtime.error(`Remote catalog refresh failed: ${result.error}`);
23-
runtime.exit(1);
24-
return;
25-
}
2623
runtime.log(
2724
`Remote catalog refresh: ${result.status} (${result.providers} providers, ${result.models} models; generated ${new Date(result.generatedAt).toISOString()})`,
2825
);

‎test/cli-json-stdout.e2e.test.ts‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { spawnSync } from "node:child_process";
33
import fs from "node:fs/promises";
44
import path from "node:path";
5+
import { DatabaseSync } from "node:sqlite";
56
import { withTempHome } from "openclaw/plugin-sdk/test-env";
67
import { describe, expect, it } from "vitest";
78

@@ -229,6 +230,179 @@ describe("cli json stdout contract", () => {
229230
);
230231
});
231232

233+
it.each([
234+
{ name: "leaf JSON", args: ["models", "refresh", "--json"] },
235+
{ name: "parent JSON", args: ["models", "--json", "refresh"] },
236+
{ name: "human output", args: ["models", "refresh"], human: true },
237+
{
238+
name: "forced Commander JSON",
239+
args: ["models", "refresh", "--json"],
240+
commander: true,
241+
},
242+
{
243+
name: "dual-TTY JSON",
244+
args: ["models", "refresh", "--json"],
245+
tty: true,
246+
},
247+
])("renders model catalog refresh failures canonically for $name", async (testCase) => {
248+
await withTempHome(
249+
async (tempHome) => {
250+
const preload = Buffer.from(
251+
[
252+
'import net from "node:net";',
253+
'net.Socket.prototype.connect = function () { throw new Error("AUTOQA_NETWORK_FORBIDDEN"); };',
254+
'globalThis.fetch = async () => { throw new Error("offline fixture"); };',
255+
"globalThis.fetch.mock = {};",
256+
...("tty" in testCase
257+
? [
258+
'Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });',
259+
'Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });',
260+
]
261+
: []),
262+
].join("\n"),
263+
).toString("base64");
264+
const result = runBuiltCli(tempHome, testCase.args, {
265+
NODE_OPTIONS: `--import=data:text/javascript;base64,${preload}`,
266+
OPENCLAW_CONFIG_PATH: path.join(tempHome, "missing-openclaw.json"),
267+
OPENCLAW_STATE_DIR: path.join(tempHome, "isolated-state"),
268+
...("commander" in testCase ? { OPENCLAW_DISABLE_ROUTE_FIRST: "1" } : {}),
269+
...("tty" in testCase ? { FORCE_COLOR: "1" } : {}),
270+
});
271+
const message = "Remote catalog refresh failed: Error: offline fixture";
272+
273+
expect(result.status, result.stderr).toBe(1);
274+
expect(result.stdout, result.stderr).not.toMatch(/[\u001B\u0007]/u);
275+
if ("human" in testCase) {
276+
expect(result.stdout).toBe("");
277+
} else {
278+
expect(JSON.parse(result.stdout)).toEqual({
279+
ok: false,
280+
error: { type: "cli_error", message },
281+
});
282+
}
283+
expect(result.stderr).toContain(message);
284+
expect(result.stderr.split(message)).toHaveLength(2);
285+
expect(result.stderr).not.toContain("AUTOQA_NETWORK_FORBIDDEN");
286+
if ("tty" in testCase) {
287+
expect(result.stderr).toContain("\u001B[?25h");
288+
}
289+
},
290+
{ prefix: "openclaw-models-refresh-json-failure-e2e-" },
291+
);
292+
});
293+
294+
it("preserves model catalog refresh success payloads and persisted rows", async () => {
295+
await withTempHome(
296+
async (tempHome) => {
297+
const stateDir = path.join(tempHome, "isolated-state");
298+
const configPath = path.join(tempHome, "openclaw.json");
299+
const databasePath = path.join(stateDir, "state", "openclaw.sqlite");
300+
const generatedAt = Date.now() + 60_000;
301+
const bundle = {
302+
schemaVersion: 1,
303+
generatedAt,
304+
sourceCommit: "autoqa-model-catalog-fixture",
305+
providers: { openai: { models: [{ id: "gpt-5.6-luna" }] } },
306+
};
307+
const updatedBundle = { ...bundle, generatedAt: generatedAt + 1_000 };
308+
const preloadFor = (response: "initial" | "updated" | "unchanged" | "failure") => {
309+
const fixture = response === "initial" ? bundle : updatedBundle;
310+
const fetchResponse =
311+
response === "failure"
312+
? 'throw new Error("offline fixture");'
313+
: response === "unchanged"
314+
? "return new Response(null, { status: 304 });"
315+
: `return new Response(JSON.stringify(${JSON.stringify(fixture)}), { headers: { etag: '\"fixture\"' } });`;
316+
return Buffer.from(
317+
[
318+
'import net from "node:net";',
319+
'import module from "node:module";',
320+
'net.Socket.prototype.connect = function () { throw new Error("AUTOQA_NETWORK_FORBIDDEN"); };',
321+
"const createRequire = module.createRequire;",
322+
'module.createRequire = (...args) => new Proxy(createRequire(...args), { apply(target, receiver, request) { return String(request[0]).endsWith("/build-info.json") ? { builtAt: "2020-01-01T00:00:00.000Z" } : Reflect.apply(target, receiver, request); } });',
323+
"module.syncBuiltinESMExports();",
324+
`globalThis.fetch = async () => { ${fetchResponse} };`,
325+
"globalThis.fetch.mock = {};",
326+
].join("\n"),
327+
).toString("base64");
328+
};
329+
const runRefresh = (
330+
args: string[],
331+
response: "initial" | "updated" | "unchanged" | "failure",
332+
) =>
333+
runBuiltCli(tempHome, ["models", ...args], {
334+
NODE_OPTIONS: `--import=data:text/javascript;base64,${preloadFor(response)}`,
335+
OPENCLAW_CONFIG_PATH: configPath,
336+
OPENCLAW_STATE_DIR: stateDir,
337+
});
338+
const readCatalogRow = () => {
339+
const database = new DatabaseSync(databasePath, { readOnly: true });
340+
try {
341+
return database.prepare("SELECT * FROM model_catalog_remote WHERE id = 1").get();
342+
} finally {
343+
database.close();
344+
}
345+
};
346+
347+
const human = runRefresh(["refresh"], "initial");
348+
expect(human.status, human.stderr).toBe(0);
349+
expect(human.stdout).toContain("Remote catalog refresh: updated (1 providers, 1 models;");
350+
expect(human.stdout).toContain(
351+
"A running Gateway applies the updated catalog after its next restart.",
352+
);
353+
354+
const updated = runRefresh(["refresh", "--json"], "updated");
355+
expect(updated.status, updated.stderr).toBe(0);
356+
expect(JSON.parse(updated.stdout)).toEqual({
357+
status: "updated",
358+
generatedAt: updatedBundle.generatedAt,
359+
providers: 1,
360+
models: 1,
361+
});
362+
363+
const unchanged = runRefresh(["--json", "refresh"], "unchanged");
364+
expect(unchanged.status, unchanged.stderr).toBe(0);
365+
expect(JSON.parse(unchanged.stdout)).toEqual({
366+
status: "unchanged",
367+
generatedAt: updatedBundle.generatedAt,
368+
providers: 1,
369+
models: 1,
370+
});
371+
const persistedRow = readCatalogRow();
372+
expect(persistedRow).toMatchObject({
373+
generated_at: updatedBundle.generatedAt,
374+
bundle_json: JSON.stringify(updatedBundle),
375+
});
376+
377+
const failure = runRefresh(["refresh", "--json"], "failure");
378+
expect(failure.status, failure.stderr).toBe(1);
379+
expect(JSON.parse(failure.stdout)).toEqual({
380+
ok: false,
381+
error: {
382+
type: "cli_error",
383+
message: "Remote catalog refresh failed: Error: offline fixture",
384+
},
385+
});
386+
expect(readCatalogRow()).toEqual(persistedRow);
387+
388+
await fs.writeFile(
389+
configPath,
390+
`${JSON.stringify({ models: { catalogRefresh: { enabled: false } } })}\n`,
391+
"utf8",
392+
);
393+
const disabled = runRefresh(["refresh", "--json"], "failure");
394+
expect(disabled.status, disabled.stderr).toBe(0);
395+
expect(JSON.parse(disabled.stdout)).toEqual({
396+
status: "disabled",
397+
providers: 0,
398+
models: 0,
399+
});
400+
expect(readCatalogRow()).toEqual(persistedRow);
401+
},
402+
{ prefix: "openclaw-models-refresh-persistence-e2e-" },
403+
);
404+
});
405+
232406
it.each([
233407
{
234408
name: "add without an interactive terminal in human mode",

0 commit comments

Comments
 (0)