Skip to content

Commit 8e4213b

Browse files
fix(gateway): accept port for health and probe (#94687)
* fix(gateway): accept port for health and probe * fix(gateway): repair health port override * fix(gateway): repair health port override * fix(gateway): accept port for health and probe --------- Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com>
1 parent a0ab5c0 commit 8e4213b

14 files changed

Lines changed: 483 additions & 30 deletions

‎docs/cli/gateway.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,10 +165,15 @@ When you set `--url`, the CLI does not fall back to config or environment creden
165165

166166
```bash
167167
openclaw gateway health --url ws://127.0.0.1:18789
168+
openclaw gateway health --port 18789
168169
```
169170

170171
The HTTP `/healthz` endpoint is a liveness probe: it returns once the server can answer HTTP. The HTTP `/readyz` endpoint is stricter and stays red while startup plugin sidecars, channels, or configured hooks are still settling. Local or authenticated detailed readiness responses include an `eventLoop` diagnostic block with event-loop delay, event-loop utilization, CPU core ratio, and a `degraded` flag.
171172

173+
<ParamField path="--port <port>" type="number">
174+
Target a local loopback Gateway on this port. This overrides `OPENCLAW_GATEWAY_URL` and `OPENCLAW_GATEWAY_PORT` for the health call.
175+
</ParamField>
176+
172177
### `gateway usage-cost`
173178

174179
Fetch usage-cost summaries from session logs.
@@ -340,8 +345,13 @@ If multiple probe targets are reachable, it prints all of them. An SSH tunnel, T
340345
```bash
341346
openclaw gateway probe
342347
openclaw gateway probe --json
348+
openclaw gateway probe --port 18789
343349
```
344350

351+
<ParamField path="--port <port>" type="number">
352+
Use this port for the local loopback probe target and SSH tunnel remote port. Without `--url`, this selects the local loopback target instead of configured gateway environment URL, environment port, or remote targets.
353+
</ParamField>
354+
345355
<AccordionGroup>
346356
<Accordion title="Interpretation">
347357
- `Reachable: yes` means at least one target accepted a WebSocket connect.

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export type GatewayRpcOpts = {
1717
timeout?: string;
1818
expectFinal?: boolean;
1919
json?: boolean;
20+
localPortOverride?: number;
2021
};
2122

2223
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 10_000;
@@ -50,6 +51,7 @@ export const callGatewayCli = async (method: string, opts: GatewayRpcOpts, param
5051
params,
5152
expectFinal: Boolean(opts.expectFinal),
5253
timeoutMs,
54+
localPortOverride: opts.localPortOverride,
5355
clientName: GATEWAY_CLIENT_NAMES.CLI,
5456
mode: GATEWAY_CLIENT_MODES.CLI,
5557
}),

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

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
77
callGatewayCli: vi.fn(async (_method: string, _opts: unknown, _params?: unknown) => ({
88
ok: true,
99
})),
10+
emitReachableGatewayAuthDiagnostic: vi.fn(async (_params: unknown) => false),
1011
gatewayStatusCommand: vi.fn(async (_opts: unknown, _runtime: unknown) => {}),
1112
defaultRuntime: {
1213
log: vi.fn(),
@@ -17,7 +18,8 @@ const mocks = vi.hoisted(() => ({
1718
},
1819
}));
1920

20-
const { callGatewayCli, gatewayStatusCommand, defaultRuntime } = mocks;
21+
const { callGatewayCli, emitReachableGatewayAuthDiagnostic, gatewayStatusCommand, defaultRuntime } =
22+
mocks;
2123

2224
vi.mock("../cli-utils.js", () => ({
2325
runCommandWithRuntime: async (
@@ -59,6 +61,7 @@ vi.mock("./call.js", () => ({
5961
vi.mock("./run-command.js", () => ({
6062
addGatewayRunCommand: (cmd: Command) =>
6163
cmd
64+
.option("--port <port>", "Port for the gateway WebSocket")
6265
.option("--token <token>", "Gateway token")
6366
.option("--password <password>", "Gateway password"),
6467
}));
@@ -68,6 +71,8 @@ vi.mock("../daemon-cli/register-service-commands.js", () => ({
6871
}));
6972

7073
vi.mock("../../commands/health.js", () => ({
74+
emitReachableGatewayAuthDiagnostic: (params: unknown) =>
75+
mocks.emitReachableGatewayAuthDiagnostic(params),
7176
formatHealthChannelLines: () => [],
7277
}));
7378

@@ -141,6 +146,7 @@ describe("gateway register option collisions", () => {
141146

142147
beforeEach(() => {
143148
callGatewayCli.mockClear();
149+
emitReachableGatewayAuthDiagnostic.mockClear();
144150
gatewayStatusCommand.mockClear();
145151
defaultRuntime.log.mockClear();
146152
defaultRuntime.error.mockClear();
@@ -171,6 +177,58 @@ describe("gateway register option collisions", () => {
171177
expect(runtime).toBe(defaultRuntime);
172178
},
173179
},
180+
{
181+
name: "forwards --port to gateway probe",
182+
argv: ["gateway", "probe", "--port", "19080", "--json"],
183+
assert: () => {
184+
expect(gatewayStatusCommand).toHaveBeenCalledTimes(1);
185+
const [opts] = firstGatewayStatusCall();
186+
expect((opts as { port?: string } | undefined)?.port).toBe("19080");
187+
},
188+
},
189+
{
190+
name: "inherits parent --port for gateway probe",
191+
argv: ["gateway", "--port", "19082", "probe", "--json"],
192+
assert: () => {
193+
expect(gatewayStatusCommand).toHaveBeenCalledTimes(1);
194+
const [opts] = firstGatewayStatusCall();
195+
expect((opts as { port?: string } | undefined)?.port).toBe("19082");
196+
},
197+
},
198+
{
199+
name: "projects gateway health --port into local config",
200+
argv: ["gateway", "health", "--port", "19081", "--json"],
201+
assert: () => {
202+
expect(defaultRuntime.error.mock.calls).toEqual([]);
203+
expect(callGatewayCli).toHaveBeenCalledTimes(1);
204+
const [method, opts] = firstGatewayCall();
205+
expect(method).toBe("health");
206+
const gatewayOpts = opts as
207+
| { config?: { gateway?: { port?: number } }; localPortOverride?: number }
208+
| undefined;
209+
expect(gatewayOpts?.localPortOverride).toBe(19081);
210+
expect(gatewayOpts?.config).toEqual({
211+
gateway: { mode: "local", port: 19081 },
212+
});
213+
},
214+
},
215+
{
216+
name: "inherits parent --port for gateway health",
217+
argv: ["gateway", "--port", "19083", "health", "--json"],
218+
assert: () => {
219+
expect(defaultRuntime.error.mock.calls).toEqual([]);
220+
expect(callGatewayCli).toHaveBeenCalledTimes(1);
221+
const [method, opts] = firstGatewayCall();
222+
expect(method).toBe("health");
223+
const gatewayOpts = opts as
224+
| { config?: { gateway?: { port?: number } }; localPortOverride?: number }
225+
| undefined;
226+
expect(gatewayOpts?.localPortOverride).toBe(19083);
227+
expect(gatewayOpts?.config).toEqual({
228+
gateway: { mode: "local", port: 19083 },
229+
});
230+
},
231+
},
174232
{
175233
name: "passes decimal usage-cost --days values",
176234
argv: ["gateway", "usage-cost", "--days", "7", "--json"],
@@ -195,4 +253,28 @@ describe("gateway register option collisions", () => {
195253
await sharedProgram.parseAsync(argv, { from: "user" });
196254
assert();
197255
});
256+
257+
it("uses the effective local port config for gateway health auth diagnostics", async () => {
258+
const authError = new Error("gateway auth required");
259+
callGatewayCli.mockRejectedValueOnce(authError);
260+
emitReachableGatewayAuthDiagnostic.mockResolvedValueOnce(true);
261+
262+
await sharedProgram.parseAsync(["gateway", "health", "--port", "19081", "--json"], {
263+
from: "user",
264+
});
265+
266+
expect(emitReachableGatewayAuthDiagnostic).toHaveBeenCalledTimes(1);
267+
expect(emitReachableGatewayAuthDiagnostic).toHaveBeenCalledWith({
268+
error: authError,
269+
config: {
270+
gateway: { mode: "local", port: 19081 },
271+
},
272+
runtime: defaultRuntime,
273+
timeoutMs: 10000,
274+
token: undefined,
275+
password: undefined,
276+
localPortOverride: 19081,
277+
json: true,
278+
});
279+
});
198280
});

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

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { defaultRuntime } from "../../runtime.js";
1818
import { createLazyImportLoader } from "../../shared/lazy-promise.js";
1919
import { inheritOptionFromParent } from "../command-options.js";
2020
import { addGatewayServiceCommands } from "../daemon-cli/register-service-commands.js";
21+
import { parseGatewayPortOption } from "../gateway-port-option.js";
2122
import { formatHelpExamples } from "../help-format.js";
2223
import type { GatewayRpcOpts } from "./call.js";
2324
import type { GatewayDiscoverOpts } from "./discover.js";
@@ -168,6 +169,34 @@ function resolveGatewayRpcOptions<T extends { token?: string; password?: string
168169
};
169170
}
170171

172+
async function resolveGatewayRpcOptionsWithLocalPort(
173+
opts: GatewayRpcOpts & { port?: unknown },
174+
command?: Command,
175+
): Promise<GatewayRpcOpts> {
176+
const rpcOpts = resolveGatewayRpcOptions(opts, command);
177+
const port = parseGatewayPortOption(opts.port ?? inheritOptionFromParent(command, "port"));
178+
if (port === undefined) {
179+
return rpcOpts;
180+
}
181+
if (typeof opts.url === "string" && opts.url.trim()) {
182+
throw new Error("Use either --url or --port, not both.");
183+
}
184+
const { readBestEffortConfig } = await loadConfigModule();
185+
const config = await readBestEffortConfig();
186+
return {
187+
...rpcOpts,
188+
localPortOverride: port,
189+
config: {
190+
...config,
191+
gateway: {
192+
...config.gateway,
193+
mode: "local",
194+
port,
195+
},
196+
},
197+
};
198+
}
199+
171200
async function renderCostUsageSummaryAsync(
172201
summary: CostUsageSummary,
173202
days: number,
@@ -553,10 +582,11 @@ export function registerGatewayCli(program: Command) {
553582
gateway
554583
.command("health")
555584
.description("Fetch Gateway health")
585+
.option("--port <port>", "Local Gateway port")
556586
.action(async (opts, command) => {
557587
await runGatewayCommand(
558588
async () => {
559-
const rpcOpts = resolveGatewayRpcOptions(opts, command);
589+
const rpcOpts = await resolveGatewayRpcOptionsWithLocalPort(opts, command);
560590
const [
561591
{ emitReachableGatewayAuthDiagnostic, formatHealthChannelLines },
562592
{ styleHealthChannelLine },
@@ -568,11 +598,12 @@ export function registerGatewayCli(program: Command) {
568598
const { readBestEffortConfig } = await loadConfigModule();
569599
const handled = await emitReachableGatewayAuthDiagnostic({
570600
error,
571-
config: await readBestEffortConfig(),
601+
config: rpcOpts.config ?? (await readBestEffortConfig()),
572602
runtime: defaultRuntime,
573603
timeoutMs: parseGatewayRpcTimeoutOption(rpcOpts.timeout),
574604
token: rpcOpts.token,
575605
password: rpcOpts.password,
606+
localPortOverride: rpcOpts.localPortOverride,
576607
json: Boolean(rpcOpts.json),
577608
});
578609
if (handled) {
@@ -728,6 +759,7 @@ export function registerGatewayCli(program: Command) {
728759
"Show gateway reachability, auth capability, and read-probe summary (local + remote)",
729760
)
730761
.option("--url <url>", "Explicit Gateway WebSocket URL (still probes localhost)")
762+
.option("--port <port>", "Local Gateway port")
731763
.option("--ssh <target>", "SSH target for remote gateway tunnel (user@host or user@host:port)")
732764
.option("--ssh-identity <path>", "SSH identity file path")
733765
.option("--ssh-auto", "Try to derive an SSH target from Bonjour discovery", false)
@@ -739,7 +771,13 @@ export function registerGatewayCli(program: Command) {
739771
await runGatewayCommand(async () => {
740772
const rpcOpts = resolveGatewayRpcOptions(opts, command);
741773
const { gatewayStatusCommand } = await loadGatewayStatusModule();
742-
await gatewayStatusCommand(rpcOpts, defaultRuntime);
774+
await gatewayStatusCommand(
775+
{
776+
...rpcOpts,
777+
port: opts.port ?? inheritOptionFromParent(command, "port"),
778+
},
779+
defaultRuntime,
780+
);
743781
});
744782
});
745783

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Gateway port option tests cover strict CLI validation before transports open.
2+
import { describe, expect, it } from "vitest";
3+
import { parseGatewayPortOption } from "./gateway-port-option.js";
4+
5+
describe("parseGatewayPortOption", () => {
6+
it("accepts TCP port values", () => {
7+
expect(parseGatewayPortOption("18789")).toBe(18789);
8+
expect(parseGatewayPortOption(65_535)).toBe(65_535);
9+
});
10+
11+
it("treats absent values as no override", () => {
12+
expect(parseGatewayPortOption(undefined)).toBeUndefined();
13+
expect(parseGatewayPortOption("")).toBeUndefined();
14+
});
15+
16+
it.each(["0", "65536", "1e4", "18789ms"])("rejects invalid port value %s", (value) => {
17+
expect(() => parseGatewayPortOption(value)).toThrow(
18+
"--port must be an integer between 1 and 65535.",
19+
);
20+
});
21+
});

‎src/cli/gateway-port-option.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Shared parser for CLI flags that select a local Gateway TCP port.
2+
import { parseStrictPositiveInteger } from "../infra/parse-finite-number.js";
3+
4+
const MAX_TCP_PORT = 65_535;
5+
6+
export function parseGatewayPortOption(raw: unknown, flagName = "--port"): number | undefined {
7+
if (raw === undefined || raw === null) {
8+
return undefined;
9+
}
10+
11+
const value =
12+
typeof raw === "string"
13+
? raw.trim()
14+
: typeof raw === "number" || typeof raw === "bigint"
15+
? String(raw)
16+
: "";
17+
if (!value) {
18+
return undefined;
19+
}
20+
21+
const parsed = parseStrictPositiveInteger(value);
22+
if (parsed === undefined || parsed > MAX_TCP_PORT) {
23+
throw new Error(`${flagName} must be an integer between 1 and ${MAX_TCP_PORT}.`);
24+
}
25+
return parsed;
26+
}

0 commit comments

Comments
 (0)