Skip to content

Commit deb0ffd

Browse files
mushuiyu886openclaw-clownfish[bot]steipete
authored
fix #94040: [Bug]: nodes approve failed: GatewayClientRequestError: unknown requestId (#94452)
* fix(nodes): explain unknown approval request ids * fix(nodes): keep stale request handling CI-clean * fix(nodes): point stale approve hint at pending command * fix(nodes): explain stale approval request ids * fix(nodes): make stale approval guidance reliable * fix(nodes): preserve stale approval error context --------- Co-authored-by: openclaw-clownfish[bot] <280122609+openclaw-clownfish[bot]@users.noreply.github.com> Co-authored-by: Peter Steinberger <[email protected]>
1 parent a846b87 commit deb0ffd

5 files changed

Lines changed: 168 additions & 36 deletions

File tree

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

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type NodeInvokeCall = {
1515

1616
let lastNodeInvokeCall: NodeInvokeCall | null = null;
1717

18-
const callGateway = vi.fn(async (opts: NodeInvokeCall) => {
18+
const callGateway = vi.fn(async (opts: NodeInvokeCall): Promise<unknown> => {
1919
if (opts.method === "node.list") {
2020
return {
2121
nodes: [
@@ -123,6 +123,82 @@ describe("nodes-cli coverage", () => {
123123
});
124124
});
125125

126+
it("explains unknown nodes approve request ids with the current pending requests", async () => {
127+
callGateway.mockResolvedValueOnce({
128+
pending: [{ requestId: "current-request", nodeId: "n1", ts: Date.now() }],
129+
paired: [],
130+
});
131+
132+
await expect(
133+
sharedProgram.parseAsync(
134+
[
135+
"nodes",
136+
"approve",
137+
"stale-request",
138+
"--url",
139+
"wss://gateway.example.test",
140+
"--token",
141+
"secret-token",
142+
],
143+
{ from: "user" },
144+
),
145+
).rejects.toThrow("__exit__:1");
146+
147+
const output = runtimeErrors.join("\n");
148+
expect(output).toContain("Unknown node pairing requestId: stale-request");
149+
expect(output).toContain("Pending requestIds: current-request");
150+
expect(output).toContain("openclaw nodes pending");
151+
expect(output).toContain("Reuse the same connection options when rerunning: --url, --token.");
152+
expect(output).not.toContain("gateway.example.test");
153+
expect(output).not.toContain("secret-token");
154+
expect(output).not.toContain("nodes approve failed: Error:");
155+
expect(output).not.toContain("GatewayClientRequestError: unknown requestId");
156+
expect(callGateway.mock.calls.map(([call]) => call.method)).toEqual(["node.pair.list"]);
157+
});
158+
159+
it("explains when a nodes approve request disappears after the preflight", async () => {
160+
callGateway
161+
.mockResolvedValueOnce({
162+
pending: [{ requestId: "expired-request", nodeId: "n1", ts: Date.now() }],
163+
paired: [],
164+
})
165+
.mockRejectedValueOnce(
166+
Object.assign(new Error("unknown requestId"), {
167+
name: "GatewayClientRequestError",
168+
gatewayCode: "INVALID_REQUEST",
169+
}),
170+
);
171+
172+
await expect(
173+
sharedProgram.parseAsync(["nodes", "approve", "expired-request"], { from: "user" }),
174+
).rejects.toThrow("__exit__:1");
175+
176+
const output = runtimeErrors.join("\n");
177+
expect(output).toContain("Unknown node pairing requestId: expired-request");
178+
expect(output).not.toContain("No pending node pairing requests are currently visible.");
179+
expect(output).not.toContain("Pending requestIds:");
180+
expect(output).toContain("openclaw nodes pending");
181+
expect(output).not.toContain("GatewayClientRequestError: unknown requestId");
182+
expect(callGateway.mock.calls.map(([call]) => call.method)).toEqual([
183+
"node.pair.list",
184+
"node.pair.approve",
185+
]);
186+
});
187+
188+
it("still approves when the pairing preflight is unavailable", async () => {
189+
callGateway
190+
.mockRejectedValueOnce(new Error("pairing list unavailable"))
191+
.mockResolvedValueOnce({ approved: true });
192+
193+
await sharedProgram.parseAsync(["nodes", "approve", "request-1"], { from: "user" });
194+
195+
expect(callGateway.mock.calls.map(([call]) => call.method)).toEqual([
196+
"node.pair.list",
197+
"node.pair.approve",
198+
]);
199+
expect(defaultRuntime.writeJson).toHaveBeenCalledWith({ approved: true });
200+
});
201+
126202
it("blocks system.run on nodes invoke", async () => {
127203
await expect(
128204
sharedProgram.parseAsync(["nodes", "invoke", "--node", "mac-1", "--command", "system.run"], {

‎src/cli/nodes-cli/cli-utils.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
// Node CLI runtime helpers: terminal theme adaptation and standard error handling.
2+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
23
import { isRich, theme } from "../../../packages/terminal-core/src/theme.js";
4+
import { formatErrorMessage } from "../../infra/errors.js";
35
import { defaultRuntime } from "../../runtime.js";
46
import { runCommandWithRuntime } from "../cli-utils.js";
57
import { unauthorizedHintForMessage } from "./rpc.js";
8+
import type { NodesRpcOpts } from "./types.js";
69

710
/** Return color helpers that degrade to plain text in non-rich terminals. */
811
export function getNodesTheme() {
@@ -18,10 +21,20 @@ export function getNodesTheme() {
1821
};
1922
}
2023

24+
export function formatConnectionFlagReminder(opts: NodesRpcOpts): string | null {
25+
const flags = [
26+
normalizeOptionalString(opts.url) ? "--url" : null,
27+
normalizeOptionalString(opts.token) ? "--token" : null,
28+
].filter((flag) => flag !== null);
29+
return flags.length > 0
30+
? `Reuse the same connection option${flags.length === 1 ? "" : "s"} when rerunning: ${flags.join(", ")}.`
31+
: null;
32+
}
33+
2134
/** Run a node CLI action with standard failure text and authorization hints. */
2235
export function runNodesCommand(label: string, action: () => Promise<void>) {
2336
return runCommandWithRuntime(defaultRuntime, action, (err) => {
24-
const message = String(err);
37+
const message = formatErrorMessage(err);
2538
const { error, warn } = getNodesTheme();
2639
defaultRuntime.error(error(`nodes ${label} failed: ${message}`));
2740
const hint = unauthorizedHintForMessage(message);

‎src/cli/nodes-cli/register.pairing.ts‎

Lines changed: 75 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { OperatorScope } from "../../gateway/method-scopes.js";
66
import { resolveNodePairApprovalScopes } from "../../infra/node-pairing-authz.js";
77
import { defaultRuntime } from "../../runtime.js";
88
import { formatCliCommand } from "../command-format.js";
9-
import { getNodesTheme, runNodesCommand } from "./cli-utils.js";
9+
import { formatConnectionFlagReminder, getNodesTheme, runNodesCommand } from "./cli-utils.js";
1010
import { parsePairingList } from "./format.js";
1111
import { renderPendingPairingRequestsTable } from "./pairing-render.js";
1212
import {
@@ -44,25 +44,67 @@ function normalizeNodePairApproveScopes(scopes: unknown): OperatorScope[] {
4444
async function resolveApproveScopesForRequest(
4545
opts: NodesRpcOpts,
4646
requestId: string,
47-
): Promise<OperatorScope[]> {
47+
): Promise<{ scopes: OperatorScope[] }> {
48+
let pending: PendingRequest[];
4849
try {
4950
const result = await callNodePairApprovalGatewayCli(
5051
"node.pair.list",
5152
opts,
5253
{},
5354
{ scopes: DEFAULT_NODE_PAIR_APPROVE_SCOPES },
5455
);
55-
const { pending } = parsePairingList(result);
56-
const request = pending.find((candidate: PendingRequest) => candidate.requestId === requestId);
57-
const scopes = normalizeNodePairApproveScopes(request?.requiredApproveScopes);
58-
if (scopes.length > DEFAULT_NODE_PAIR_APPROVE_SCOPES.length) {
59-
return scopes;
60-
}
61-
// Older pending requests only list requested commands; derive approval scopes from them.
62-
return resolveNodePairApprovalScopes(request?.commands) as OperatorScope[];
56+
pending = parsePairingList(result).pending;
6357
} catch {
64-
return [...DEFAULT_NODE_PAIR_APPROVE_SCOPES];
58+
return { scopes: [...DEFAULT_NODE_PAIR_APPROVE_SCOPES] };
59+
}
60+
const pendingRequestIds = pending
61+
.map((request) => request.requestId)
62+
.filter((id): id is string => typeof id === "string" && id.length > 0);
63+
const request = pending.find((candidate) => candidate.requestId === requestId);
64+
if (!request) {
65+
throw new Error(buildUnknownNodePairRequestIdMessage(requestId, opts, pendingRequestIds));
6566
}
67+
const declaredScopes = normalizeNodePairApproveScopes(request.requiredApproveScopes);
68+
if (declaredScopes.length > DEFAULT_NODE_PAIR_APPROVE_SCOPES.length) {
69+
return { scopes: declaredScopes };
70+
}
71+
// Older pending requests only list requested commands; derive approval scopes from them.
72+
return {
73+
scopes: resolveNodePairApprovalScopes(request.commands) as OperatorScope[],
74+
};
75+
}
76+
77+
function isUnknownNodePairRequestIdError(
78+
error: unknown,
79+
): error is Error & { gatewayCode: "INVALID_REQUEST" } {
80+
const requestError = error as (Error & { gatewayCode?: unknown }) | undefined;
81+
return (
82+
requestError instanceof Error &&
83+
requestError.name === "GatewayClientRequestError" &&
84+
requestError.gatewayCode === "INVALID_REQUEST" &&
85+
requestError.message === "unknown requestId"
86+
);
87+
}
88+
89+
function buildUnknownNodePairRequestIdMessage(
90+
requestId: string,
91+
opts: NodesRpcOpts,
92+
pendingRequestIds?: string[],
93+
): string {
94+
const lines = [`Unknown node pairing requestId: ${requestId}`];
95+
if (pendingRequestIds !== undefined) {
96+
if (pendingRequestIds.length > 0) {
97+
lines.push(`Pending requestIds: ${pendingRequestIds.join(", ")}`);
98+
} else {
99+
lines.push("No pending node pairing requests are currently visible.");
100+
}
101+
}
102+
lines.push(`Run ${formatCliCommand("openclaw nodes pending")} to inspect current requests.`);
103+
const connectionReminder = formatConnectionFlagReminder(opts);
104+
if (connectionReminder) {
105+
lines.push(connectionReminder);
106+
}
107+
return lines.join("\n");
66108
}
67109

68110
/** Register node pairing management commands. */
@@ -106,17 +148,28 @@ export function registerNodesPairingCommands(nodes: Command) {
106148
.argument("<requestId>", "Pending request id")
107149
.action(async (requestId: string, opts: NodesRpcOpts) => {
108150
await runNodesCommand("approve", async () => {
109-
const scopes = await resolveApproveScopesForRequest(opts, requestId);
110-
const result = await callNodePairApprovalGatewayCli(
111-
"node.pair.approve",
112-
opts,
113-
{
114-
requestId,
115-
},
116-
{
117-
scopes,
118-
},
119-
);
151+
const { scopes } = await resolveApproveScopesForRequest(opts, requestId);
152+
let result: unknown;
153+
try {
154+
result = await callNodePairApprovalGatewayCli(
155+
"node.pair.approve",
156+
opts,
157+
{
158+
requestId,
159+
},
160+
{
161+
scopes,
162+
},
163+
);
164+
} catch (error) {
165+
if (!isUnknownNodePairRequestIdError(error)) {
166+
throw error;
167+
}
168+
// Reuse the gateway error so generic formatting does not append its raw cause.
169+
error.name = "Error";
170+
error.message = buildUnknownNodePairRequestIdMessage(requestId, opts);
171+
throw error;
172+
}
120173
defaultRuntime.writeJson(result);
121174
});
122175
}),

‎src/cli/nodes-cli/register.status.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import { shortenHomeInString } from "../../utils.js";
1414
import { formatCliCommand } from "../command-format.js";
1515
import { parseDurationMs } from "../parse-duration.js";
1616
import { quoteCliArg } from "../quote-cli-arg.js";
17-
import { getNodesTheme, runNodesCommand } from "./cli-utils.js";
17+
import { formatConnectionFlagReminder, getNodesTheme, runNodesCommand } from "./cli-utils.js";
1818
import { formatPermissions, parseNodeList, parsePairingList } from "./format.js";
1919
import { renderPendingPairingRequestsTable } from "./pairing-render.js";
2020
import {
@@ -146,16 +146,6 @@ function formatPendingApprovalCommand(raw: unknown, opts: NodesRpcOpts): string
146146
return formatCliCommand(args.map(quoteCliArg).join(" "));
147147
}
148148

149-
function formatConnectionFlagReminder(opts: NodesRpcOpts): string | null {
150-
const flags = [
151-
normalizeOptionalString(opts.url) ? "--url" : null,
152-
normalizeOptionalString(opts.token) ? "--token" : null,
153-
].filter((flag) => flag !== null);
154-
return flags.length > 0
155-
? `Reuse the same ${flags.join("/")} option${flags.length === 1 ? "" : "s"} when rerunning.`
156-
: null;
157-
}
158-
159149
function parseSinceMs(raw: unknown, label: string): number | undefined {
160150
if (raw === undefined || raw === null) {
161151
return undefined;

‎src/cli/program.nodes-basic.e2e.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,7 @@ describe("cli program (nodes basics)", () => {
562562

563563
const output = getRuntimeOutput();
564564
expect(output).toContain("openclaw nodes approve request-reapproval --timeout 3000");
565-
expect(output).toContain("Reuse the same --url/--token options when rerunning.");
565+
expect(output).toContain("Reuse the same connection options when rerunning: --url, --token.");
566566
expect(output).not.toContain("gateway-user");
567567
expect(output).not.toContain("url-secret");
568568
expect(output).not.toContain("gateway.example");

0 commit comments

Comments
 (0)