Skip to content

Commit 00713ca

Browse files
authored
fix(cli): honor selected port when tailing logs (#130513)
1 parent b54e677 commit 00713ca

5 files changed

Lines changed: 227 additions & 35 deletions

File tree

‎docs/cli/logs.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Tail Gateway file logs over RPC. Works in remote mode.
2525
## Shared Gateway RPC options
2626

2727
- `--url <url>`: Gateway WebSocket URL
28+
- `--port <port>`: select a local Gateway port, overriding the configured remote URL and `OPENCLAW_GATEWAY_URL`; cannot be combined with `--url`
2829
- `--token <token>`: Gateway token
2930
- `--timeout <ms>`: timeout in ms (default `30000`)
3031
- `--expect-final`: wait for a final response when the Gateway call is agent-backed
@@ -45,6 +46,7 @@ openclaw logs --plain
4546
openclaw logs --no-color
4647
openclaw logs --utc
4748
openclaw logs --follow --local-time
49+
openclaw logs --port 19083 --json
4850
openclaw logs --url ws://127.0.0.1:18789 --token "$OPENCLAW_GATEWAY_TOKEN"
4951
```
5052

@@ -60,6 +62,8 @@ profile uses `openclaw-YYYY-MM-DD.log`, while named profiles use
6062
- During `--follow`, transient disconnects (WebSocket close, timeout, connection drop) trigger automatic reconnection with exponential backoff: up to 8 retries, capped at 30s between attempts. A warning prints to stderr on each retry, and a `[logs] gateway reconnected` notice prints once a poll succeeds. In `--json` mode both are emitted as `{"type":"notice"}` records on stderr. Non-recoverable errors (auth failure, bad configuration) still exit immediately.
6163
- In `--follow --json` mode, log-source transitions are emitted as `{"type":"meta"}` records. Track cursors per `sourceKind`: a stream can move from Gateway file output (`sourceKind: "file"`) to local journal fallback (`sourceKind: "journal"`, `localFallback: true`, with `service.pid`/`service.unit`) and back to Gateway file output after recovery. Do not assume one stable source or cursor for the whole session, and tolerate overlapping lines when recovery replays the Gateway file cursor.
6264

65+
In `--json` mode, invalid `--port`, `--limit`, `--interval`, or `--max-bytes` values and conflicting `--url`/`--port` options produce the standard CLI failure envelope on stdout: `{"ok":false,"error":{"type":"cli_error","message":"..."}}`. Terminal log-fetch failures instead emit `{"type":"error",...}` on stderr. Both exit with status `1`.
66+
6367
## Related
6468

6569
- [Logging overview](/logging)

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Shared parser for CLI flags that select a local Gateway TCP port.
22
import { parseStrictPositiveInteger } from "@openclaw/normalization-core/number-coercion";
3+
import type { GatewayRpcOpts } from "./gateway-rpc.types.js";
34

45
const MAX_TCP_PORT = 65_535;
56

@@ -24,3 +25,13 @@ export function parseGatewayPortOption(raw: unknown, flagName = "--port"): numbe
2425
}
2526
return parsed;
2627
}
28+
29+
export function resolveGatewayLocalPortOverride(
30+
opts: Pick<GatewayRpcOpts, "port" | "url"> & { localPortOverride?: number },
31+
): number | undefined {
32+
const port = opts.localPortOverride ?? parseGatewayPortOption(opts.port);
33+
if (port !== undefined && typeof opts.url === "string" && opts.url.trim()) {
34+
throw new Error("Use either --url or --port, not both.");
35+
}
36+
return port;
37+
}

‎src/cli/gateway-rpc.runtime.ts‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
} from "../../packages/gateway-protocol/src/client-info.js";
66
import type { OpenClawConfig } from "../config/types.openclaw.js";
77
import { callGateway, isImplicitLocalGatewayTarget } from "../gateway/call.js";
8-
import { parseGatewayPortOption } from "./gateway-port-option.js";
8+
import { resolveGatewayLocalPortOverride } from "./gateway-port-option.js";
99
import type { GatewayRpcOpts } from "./gateway-rpc.types.js";
1010
import { parseTimeoutMsWithFallback } from "./parse-timeout.js";
1111
import { withProgress } from "./progress.js";
@@ -37,21 +37,13 @@ type GatewayCliTransportRpcOpts = Omit<GatewayRpcOpts, "timeout"> & {
3737

3838
const DEFAULT_GATEWAY_RPC_TIMEOUT_MS = 30_000;
3939

40-
function resolveLocalPortOverride(opts: GatewayCliTransportRpcOpts): number | undefined {
41-
const port = opts.localPortOverride ?? parseGatewayPortOption(opts.port);
42-
if (port !== undefined && typeof opts.url === "string" && opts.url.trim()) {
43-
throw new Error("Use either --url or --port, not both.");
44-
}
45-
return port;
46-
}
47-
4840
export async function isImplicitLocalGatewayTargetFromCliRuntime(
4941
opts: GatewayCliTransportRpcOpts,
5042
): Promise<boolean> {
5143
return await isImplicitLocalGatewayTarget({
5244
config: opts.config,
5345
url: opts.url,
54-
localPortOverride: resolveLocalPortOverride(opts),
46+
localPortOverride: resolveGatewayLocalPortOverride(opts),
5547
});
5648
}
5749

@@ -61,7 +53,7 @@ export async function callGatewayFromCliRuntime(
6153
params?: unknown,
6254
extra?: CallGatewayFromCliRuntimeExtra,
6355
) {
64-
const localPortOverride = resolveLocalPortOverride(opts);
56+
const localPortOverride = resolveGatewayLocalPortOverride(opts);
6557
// Progress is disabled for JSON output so stdout stays parseable.
6658
const showProgress = extra?.progress ?? opts.json !== true;
6759
const timeoutMs =

‎src/cli/logs-cli.port.test.ts‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
import { once } from "node:events";
2+
import type { AddressInfo } from "node:net";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { WebSocketServer } from "ws";
5+
import {
6+
buildMinimalGatewayHelloOkPayload,
7+
closeMinimalGatewayServer,
8+
parseMinimalGatewayRequestFrame,
9+
sendMinimalGatewayConnectChallenge,
10+
sendMinimalGatewayResponse,
11+
} from "../gateway/minimal-gateway.test-helpers.js";
12+
import { defaultRuntime, ExitError } from "../runtime.js";
13+
import { runRegisteredCli } from "../test-utils/command-runner.js";
14+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
15+
import { registerLogsCli } from "./logs-cli.js";
16+
17+
afterEach(() => vi.restoreAllMocks());
18+
19+
async function withLogsGateway(
20+
options: { source?: "config" | "environment"; denied?: boolean },
21+
run: (fixture: {
22+
port: string;
23+
requests: string[];
24+
stdout: string[];
25+
stderr: string[];
26+
}) => Promise<void>,
27+
) {
28+
await withOpenClawTestState(
29+
{
30+
label: "logs-port",
31+
env: {
32+
OPENCLAW_GATEWAY_URL:
33+
options.source === "environment" ? "ws://remote.example:19001" : undefined,
34+
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS: undefined,
35+
},
36+
},
37+
async (state) => {
38+
await state.writeConfig({
39+
gateway: {
40+
mode: options.source === "config" ? "remote" : "local",
41+
auth: { mode: "none" },
42+
...(options.source === "config" ? { remote: { url: "ws://remote.example:19001" } } : {}),
43+
},
44+
});
45+
const server = new WebSocketServer({ host: "127.0.0.1", port: 0 });
46+
const requests: string[] = [];
47+
server.on("connection", (socket) => {
48+
sendMinimalGatewayConnectChallenge(socket);
49+
socket.on("message", (data) => {
50+
const frame = parseMinimalGatewayRequestFrame(data);
51+
if (!frame.id || !frame.method) {
52+
return;
53+
}
54+
requests.push(frame.method);
55+
if (frame.method === "connect") {
56+
sendMinimalGatewayResponse(
57+
socket,
58+
frame.id,
59+
buildMinimalGatewayHelloOkPayload({ methods: ["logs.tail"] }),
60+
);
61+
} else if (options.denied) {
62+
socket.send(
63+
JSON.stringify({
64+
type: "res",
65+
id: frame.id,
66+
ok: false,
67+
error: { code: "INVALID_REQUEST", message: "logs unavailable for this client" },
68+
}),
69+
);
70+
} else {
71+
sendMinimalGatewayResponse(socket, frame.id, {
72+
file: "selected-gateway.log",
73+
cursor: 1,
74+
lines: ["selected local log"],
75+
});
76+
}
77+
});
78+
});
79+
await once(server, "listening");
80+
const port = String((server.address() as AddressInfo).port);
81+
const stdout: string[] = [];
82+
const stderr: string[] = [];
83+
vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
84+
stdout.push(String(chunk));
85+
return true;
86+
});
87+
vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
88+
stderr.push(String(chunk));
89+
return true;
90+
});
91+
vi.spyOn(defaultRuntime, "exit").mockImplementation((code) => {
92+
throw new ExitError(code);
93+
});
94+
try {
95+
await run({ port, requests, stdout, stderr });
96+
} finally {
97+
await closeMinimalGatewayServer(server);
98+
}
99+
},
100+
);
101+
}
102+
103+
async function runLogs(argv: string[]) {
104+
await runRegisteredCli({ register: registerLogsCli, argv: ["logs", ...argv] });
105+
}
106+
107+
describe("logs local port selection", () => {
108+
it.each(["config", "environment"] as const)(
109+
"tails the selected local port instead of validating the %s default URL",
110+
async (source) => {
111+
await withLogsGateway({ source }, async ({ port, requests, stdout }) => {
112+
await runLogs(["--port", port, "--json", "--timeout", "1500"]);
113+
expect(requests).toEqual(["connect", "logs.tail"]);
114+
expect(stdout.join("")).toContain("selected local log");
115+
});
116+
},
117+
);
118+
119+
it.each(["text", "json"])(
120+
"reports the selected port when the RPC fails in %s mode",
121+
async (mode) => {
122+
await withLogsGateway({ denied: true }, async ({ port, requests, stderr }) => {
123+
const args = [
124+
"--port",
125+
port,
126+
"--timeout",
127+
"1500",
128+
...(mode === "json" ? ["--json"] : ["--plain"]),
129+
];
130+
await expect(runLogs(args)).rejects.toBeInstanceOf(ExitError);
131+
expect(requests).toEqual(["connect", "logs.tail"]);
132+
const output = stderr.join("");
133+
if (mode === "json") {
134+
expect(JSON.parse(output)).toMatchObject({
135+
type: "error",
136+
details: { url: `ws://127.0.0.1:${port}` },
137+
});
138+
} else {
139+
expect(output).toContain(`Gateway target: ws://127.0.0.1:${port}`);
140+
}
141+
});
142+
},
143+
);
144+
145+
it("honors an explicit URL even with an unusable default URL", async () => {
146+
await withLogsGateway({ source: "config" }, async ({ port, requests, stdout }) => {
147+
await runLogs([
148+
"--url",
149+
`ws://127.0.0.1:${port}`,
150+
"--token",
151+
"fixture-token",
152+
"--json",
153+
"--timeout",
154+
"1500",
155+
]);
156+
expect(requests).toEqual(["connect", "logs.tail"]);
157+
expect(stdout.join("")).toContain("selected local log");
158+
});
159+
});
160+
161+
it.each(["config", "environment"] as const)(
162+
"still rejects an unsafe %s target without an override",
163+
async (source) => {
164+
await withLogsGateway({ source }, async ({ requests }) => {
165+
await expect(runLogs(["--json"])).rejects.toThrow(
166+
"uses plaintext ws:// to a non-loopback address",
167+
);
168+
expect(requests).toEqual([]);
169+
});
170+
},
171+
);
172+
173+
it.each([
174+
{ args: ["--port", "65536"], message: "--port must be an integer between 1 and 65535." },
175+
{
176+
args: ["--port", "19083", "--url", "ws://127.0.0.1:19083"],
177+
message: "Use either --url or --port, not both.",
178+
},
179+
])("keeps target validation for $args", async ({ args, message }) => {
180+
await withLogsGateway({}, async ({ requests }) => {
181+
await expect(runLogs(args)).rejects.toThrow(message);
182+
expect(requests).toEqual([]);
183+
});
184+
});
185+
});

0 commit comments

Comments
 (0)