Skip to content

Commit 6335d97

Browse files
authored
fix(cli): render Gateway validation JSON failures (#129043)
1 parent 4e8e22f commit 6335d97

4 files changed

Lines changed: 188 additions & 20 deletions

File tree

‎src/cli/gateway-cli.coverage.test.ts‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import path from "node:path";
55
import { Command } from "commander";
66
import { beforeEach, describe, expect, it, vi } from "vitest";
77
import { withEnvOverride } from "../config/test-helpers.js";
8+
import { ExpectedCliError } from "./failure-output.js";
89
import { registerGatewayCli } from "./gateway-cli.js";
910

1011
type GatewayCliDependencies = Parameters<typeof registerGatewayCli>[1];
@@ -156,7 +157,11 @@ describe("gateway-cli coverage", () => {
156157
await expectGatewayExit(["gateway", "call", "health", "--timeout", "1000ms", "--json"]);
157158

158159
expect(callGateway).not.toHaveBeenCalled();
159-
expect(runtimeErrors.join("\n")).toContain("Gateway call failed: Invalid --timeout");
160+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
161+
ok: false,
162+
error: { type: "cli_error", message: expect.stringContaining("Invalid --timeout") },
163+
});
164+
expect(runtimeErrors).toHaveLength(0);
160165
});
161166

162167
it("renders gateway request failures without the client error class in human mode", async () => {
@@ -311,7 +316,29 @@ describe("gateway-cli coverage", () => {
311316
]);
312317

313318
expect(callGateway).not.toHaveBeenCalled();
314-
expect(runtimeErrors.join("\n")).toContain("Use --agent or --all-agents, not both");
319+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
320+
ok: false,
321+
error: { type: "cli_error", message: "Use --agent or --all-agents, not both" },
322+
});
323+
expect(runtimeErrors).toHaveLength(0);
324+
});
325+
326+
it("preserves expected CLI machine output for ordinary Gateway command failures", async () => {
327+
callGateway.mockRejectedValueOnce(
328+
new ExpectedCliError({
329+
message: "validation failed",
330+
humanOutput: "human recovery guidance",
331+
machineOutput: "machine recovery guidance\n",
332+
}),
333+
);
334+
335+
await expectGatewayExit(["gateway", "call", "health", "--json"]);
336+
337+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
338+
ok: false,
339+
error: { type: "cli_error", message: "machine recovery guidance" },
340+
});
341+
expect(runtimeErrors).toHaveLength(0);
315342
});
316343

317344
it("writes JSON for gateway health transport failures in JSON mode", async () => {
@@ -585,7 +612,11 @@ describe("gateway-cli coverage", () => {
585612

586613
await expectGatewayExit(["gateway", "diagnostics", "export", flag, value, "--json"]);
587614

588-
expect(runtimeErrors.join("\n")).toContain(`${flag} must be a positive integer`);
615+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
616+
ok: false,
617+
error: { type: "cli_error", message: `${flag} must be a positive integer.` },
618+
});
619+
expect(runtimeErrors).toHaveLength(0);
589620
expect(callGateway).not.toHaveBeenCalled();
590621
});
591622

@@ -663,11 +694,33 @@ describe("gateway-cli coverage", () => {
663694
expect(runtimeErrors.join("\n")).toContain("--params must be valid JSON.");
664695
});
665696

697+
it("renders invalid gateway call params as JSON before calling Gateway", async () => {
698+
await expectGatewayExit([
699+
"gateway",
700+
"call",
701+
"system-presence",
702+
"--params",
703+
"not-json",
704+
"--json",
705+
]);
706+
707+
expect(callGateway).not.toHaveBeenCalled();
708+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
709+
ok: false,
710+
error: { type: "cli_error", message: "--params must be valid JSON." },
711+
});
712+
expect(runtimeErrors).toHaveLength(0);
713+
});
714+
666715
it("validates gateway call timeout before opening a transport", async () => {
667716
callGateway.mockClear();
668717
await expectGatewayExit(["gateway", "call", "health", "--timeout", "nope", "--json"]);
669718

670719
expect(callGateway).not.toHaveBeenCalled();
671-
expect(runtimeErrors.join("\n")).toContain("Invalid --timeout");
720+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
721+
ok: false,
722+
error: { type: "cli_error", message: expect.stringContaining("Invalid --timeout") },
723+
});
724+
expect(runtimeErrors).toHaveLength(0);
672725
});
673726
});

‎src/cli/gateway-cli/register.option-collisions.test.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -372,28 +372,27 @@ describe("gateway register option collisions", () => {
372372
{
373373
name: "call",
374374
args: ["call", "health"],
375-
failure: "Gateway call failed",
376375
},
377376
{
378377
name: "usage-cost",
379378
args: ["usage-cost"],
380-
failure: "Gateway usage cost failed",
381379
},
382380
{
383381
name: "live stability",
384382
args: ["stability"],
385-
failure: "Gateway stability failed",
386383
},
387-
])("rejects combining --url and --port for gateway $name", async ({ args, failure }) => {
384+
])("rejects combining --url and --port for gateway $name", async ({ args }) => {
388385
await sharedProgram.parseAsync(
389386
["gateway", ...args, "--url", "ws://127.0.0.1:19084", "--port", "19084", "--json"],
390387
{ from: "user" },
391388
);
392389

393390
expect(callGatewayCli).not.toHaveBeenCalled();
394-
expect(defaultRuntime.error).toHaveBeenCalledWith(
395-
`${failure}: Use either --url or --port, not both.`,
396-
);
391+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({
392+
ok: false,
393+
error: { type: "cli_error", message: "Use either --url or --port, not both." },
394+
});
395+
expect(defaultRuntime.error).not.toHaveBeenCalled();
397396
expect(defaultRuntime.exit).toHaveBeenCalledWith(1);
398397
});
399398

‎src/cli/gateway-cli/register.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { defaultRuntime } from "../../runtime.js";
2020
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
2121
import { inheritOptionFromParent } from "../command-options.js";
2222
import { addGatewayServiceCommands } from "../daemon-cli/register-service-commands.js";
23-
import { rethrowExpectedCliError } from "../failure-output.js";
23+
import { formatCliJsonFailure, rethrowExpectedCliError } from "../failure-output.js";
2424
import { parseGatewayPortOption } from "../gateway-port-option.js";
2525
import { addGatewayClientOptions, callGatewayFromCliWithTransport } from "../gateway-rpc.js";
2626
import { formatHelpExamples } from "../help-format.js";
@@ -146,15 +146,14 @@ async function runGatewayCommand(
146146
formatGatewayClientRequestErrorJson,
147147
formatGatewayTransportErrorJson,
148148
} = await import("../../gateway/call.js");
149-
const payload =
149+
defaultRuntime.writeJson(
150150
formatGatewayAuthErrorJson(err) ??
151-
formatGatewayClientRequestErrorJson(err) ??
152-
formatGatewayTransportErrorJson(err);
153-
if (payload) {
154-
defaultRuntime.writeJson(payload);
155-
defaultRuntime.exit(1);
156-
return;
157-
}
151+
formatGatewayClientRequestErrorJson(err) ??
152+
formatGatewayTransportErrorJson(err) ??
153+
formatCliJsonFailure(err),
154+
);
155+
defaultRuntime.exit(1);
156+
return;
158157
}
159158
const message = formatErrorMessage(err);
160159
defaultRuntime.error(label ? `${label}: ${message}` : message);

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

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,123 @@ describe("cli json stdout contract", () => {
164164
);
165165
});
166166

167+
it.each([
168+
{
169+
name: "invalid call params in JSON mode",
170+
args: ["gateway", "call", "system-presence", "--params", "not-json", "--json"],
171+
message: "--params must be valid JSON.",
172+
},
173+
{
174+
name: "invalid call params in human mode",
175+
args: ["gateway", "call", "system-presence", "--params", "not-json"],
176+
message: "--params must be valid JSON.",
177+
human: true,
178+
},
179+
{
180+
name: "invalid call params through forced Commander",
181+
args: ["gateway", "call", "system-presence", "--params", "not-json", "--json"],
182+
message: "--params must be valid JSON.",
183+
commander: true,
184+
},
185+
{
186+
name: "invalid call params with dual TTYs",
187+
args: ["gateway", "call", "system-presence", "--params", "not-json", "--json"],
188+
message: "--params must be valid JSON.",
189+
tty: true,
190+
},
191+
{
192+
name: "contradictory usage options in JSON mode",
193+
args: ["gateway", "usage-cost", "--agent", "alpha", "--all-agents", "--json"],
194+
message: "Use --agent or --all-agents, not both",
195+
},
196+
{
197+
name: "contradictory usage options in human mode",
198+
args: ["gateway", "usage-cost", "--agent", "alpha", "--all-agents"],
199+
message: "Use --agent or --all-agents, not both",
200+
human: true,
201+
},
202+
{
203+
name: "contradictory usage options through forced Commander",
204+
args: ["gateway", "usage-cost", "--agent", "alpha", "--all-agents", "--json"],
205+
message: "Use --agent or --all-agents, not both",
206+
commander: true,
207+
},
208+
{
209+
name: "contradictory usage options with dual TTYs",
210+
args: ["gateway", "usage-cost", "--agent", "alpha", "--all-agents", "--json"],
211+
message: "Use --agent or --all-agents, not both",
212+
tty: true,
213+
},
214+
{
215+
name: "specialized explicit Gateway authentication failure",
216+
args: ["gateway", "call", "system-presence", "--url", "ws://127.0.0.1:29793", "--json"],
217+
specializedAuth: true,
218+
},
219+
])("renders Gateway query failures through the Gateway owner for $name", async (testCase) => {
220+
await withTempHome(
221+
async (tempHome) => {
222+
const configPath = path.join(tempHome, "missing-openclaw.json");
223+
const stateDir = path.join(tempHome, "isolated-state");
224+
const gatewayError = "AUTOQA_INJECTED_GATEWAY_FAILURE";
225+
const preload = Buffer.from(
226+
[
227+
'import net from "node:net";',
228+
`net.Socket.prototype.connect = function () { throw new Error(${JSON.stringify(gatewayError)}); };`,
229+
...("tty" in testCase
230+
? [
231+
'Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });',
232+
'Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });',
233+
]
234+
: []),
235+
].join("\n"),
236+
).toString("base64");
237+
const result = runBuiltCli(tempHome, testCase.args, {
238+
NODE_OPTIONS: `--import=data:text/javascript;base64,${preload}`,
239+
OPENCLAW_CONFIG_PATH: configPath,
240+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
241+
OPENCLAW_STATE_DIR: stateDir,
242+
...("commander" in testCase ? { OPENCLAW_DISABLE_ROUTE_FIRST: "1" } : {}),
243+
...("tty" in testCase ? { FORCE_COLOR: "1", NO_COLOR: undefined } : {}),
244+
});
245+
246+
expect(result.status, result.stderr).toBe(1);
247+
expect(result.stdout, result.stderr).not.toMatch(/[\u001B\u0007]/u);
248+
expect(result.stdout).not.toContain(gatewayError);
249+
expect(result.stderr).not.toContain(gatewayError);
250+
if ("human" in testCase) {
251+
expect(result.stdout).toBe("");
252+
expect(result.stderr).toContain(testCase.message);
253+
} else if ("specializedAuth" in testCase) {
254+
expect(JSON.parse(result.stdout)).toEqual({
255+
ok: false,
256+
error: {
257+
type: "gateway_credentials_required",
258+
message: [
259+
"gateway url override requires explicit credentials",
260+
"Fix: pass --token or --password with --url (or gatewayToken in tools).",
261+
"For the default local or SSH-tunneled Gateway, remove --url to use the configured target.",
262+
`Config: ${configPath}`,
263+
].join("\n"),
264+
},
265+
});
266+
expect(result.stderr).toBe("");
267+
} else {
268+
expect(JSON.parse(result.stdout)).toEqual({
269+
ok: false,
270+
error: { type: "cli_error", message: testCase.message },
271+
});
272+
expect(result.stderr).not.toContain(testCase.message);
273+
}
274+
if ("tty" in testCase) {
275+
expect(result.stderr).toContain("\u001B[?25h");
276+
}
277+
await expect(fs.stat(stateDir)).rejects.toMatchObject({ code: "ENOENT" });
278+
await expect(fs.stat(configPath)).rejects.toMatchObject({ code: "ENOENT" });
279+
},
280+
{ prefix: "openclaw-gateway-query-json-failure-e2e-" },
281+
);
282+
});
283+
167284
it.each([
168285
{
169286
name: "bare report with parent JSON",

0 commit comments

Comments
 (0)