forked from NVIDIA/NemoClaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-global-oclif-adapters.test.ts
More file actions
387 lines (348 loc) · 14.9 KB
/
Copy pathsimple-global-oclif-adapters.test.ts
File metadata and controls
387 lines (348 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { testTimeoutOptions } from "../../test/helpers/timeouts";
const mocks = vi.hoisted(() => {
class GatewayTokenCommandError extends Error {
lines: readonly string[];
exitCode: number;
constructor(lines: string | readonly string[], exitCode = 1) {
const normalized = Array.isArray(lines) ? lines : [lines];
super(normalized.join("\n"));
this.lines = normalized;
this.exitCode = exitCode;
}
}
class DashboardUrlCommandError extends Error {
lines: readonly string[];
exitCode: number;
constructor(lines: string | readonly string[], exitCode = 1) {
const normalized = Array.isArray(lines) ? lines : [lines];
super(normalized.join("\n"));
this.lines = normalized;
this.exitCode = exitCode;
}
}
return {
buildVersionedUninstallUrl: vi.fn(
(version: string) => `https://example.test/${version}/uninstall.sh`,
),
fetchGatewayAuthTokenFromSandbox: vi.fn(() => "token"),
getVersion: vi.fn(() => "1.2.3"),
captureOpenshellCommand: vi.fn(() => ({ status: 0, output: "alpha\n" })),
listSandboxes: vi.fn(() => ({ sandboxes: [] })),
resolveOpenshell: vi.fn(() => "/usr/bin/openshell"),
runDebugCommandWithOptions: vi.fn(),
runDeployAction: vi.fn().mockResolvedValue(undefined),
runDashboardUrlCommand: vi.fn(() => undefined),
runGatewayTokenCommand: vi.fn(() => undefined),
runStartCommand: vi.fn().mockResolvedValue(undefined),
runStopCommand: vi.fn(),
runUninstallCommand: vi.fn(),
resolveDefaultSandboxName: vi.fn(() => "resolved-sandbox"),
assertHermesPortableCommandUnavailable: vi.fn(),
withMcpLifecycleLock: vi.fn(async (_sandboxName: string, operation: () => unknown) =>
operation(),
),
showRootHelp: vi.fn(),
showStatus: vi.fn(),
showVersion: vi.fn(),
spawnSync: vi.fn(),
startAll: vi.fn(),
stopAll: vi.fn(),
DashboardUrlCommandError,
GatewayTokenCommandError,
};
});
vi.mock("node:child_process", () => ({ spawnSync: mocks.spawnSync }));
vi.mock("../lib/diagnostics/debug", () => ({ runDebug: vi.fn() }));
vi.mock("../lib/diagnostics/debug-command", () => ({
runDebugCommandWithOptions: mocks.runDebugCommandWithOptions,
}));
vi.mock("../lib/gateway-token-command", () => ({
GatewayTokenCommandError: mocks.GatewayTokenCommandError,
runGatewayTokenCommand: mocks.runGatewayTokenCommand,
}));
vi.mock("../lib/dashboard-url-command", () => ({
DashboardUrlCommandError: mocks.DashboardUrlCommandError,
runDashboardUrlCommand: mocks.runDashboardUrlCommand,
}));
vi.mock("../lib/actions/global", () => ({
runDeployAction: mocks.runDeployAction,
showRootHelp: mocks.showRootHelp,
showVersion: mocks.showVersion,
}));
vi.mock("../lib/adapters/openshell/client", () => ({
captureOpenshellCommand: mocks.captureOpenshellCommand,
}));
vi.mock("../lib/state/registry", () => ({ listSandboxes: mocks.listSandboxes }));
vi.mock("../lib/adapters/openshell/resolve", () => ({ resolveOpenshell: mocks.resolveOpenshell }));
vi.mock("../lib/tunnel/services", () => ({
showStatus: mocks.showStatus,
startAll: mocks.startAll,
stopAll: mocks.stopAll,
}));
vi.mock("../lib/tunnel/service-command", () => ({
resolveDefaultSandboxName: mocks.resolveDefaultSandboxName,
runStartCommand: mocks.runStartCommand,
runStopCommand: mocks.runStopCommand,
}));
vi.mock("../lib/uninstall-command", () => ({
buildVersionedUninstallUrl: mocks.buildVersionedUninstallUrl,
runUninstallCommand: mocks.runUninstallCommand,
}));
vi.mock("../lib/core/version", () => ({ getVersion: mocks.getVersion }));
vi.mock("../lib/onboard/experimental/portable-agent-lifecycle", async (importOriginal) => ({
...(await importOriginal()),
assertHermesPortableCommandUnavailable: mocks.assertHermesPortableCommandUnavailable,
}));
vi.mock("../lib/state/mcp-lifecycle-lock-acquisition", async (importOriginal) => ({
...(await importOriginal()),
withMcpLifecycleLock: mocks.withMcpLifecycleLock,
}));
import { log } from "../lib/cli/logger";
import DebugCliCommand from "./debug";
import DeployCliCommand from "./deploy";
import RootHelpCommand from "./root/help";
import VersionCommand from "./root/version";
import DashboardUrlCliCommand, {
setDashboardUrlRuntimeBridgeFactoryForTest,
} from "./sandbox/dashboard-url";
import GatewayTokenCliCommand, {
setGatewayTokenRuntimeBridgeFactoryForTest,
} from "./sandbox/gateway/token";
import DeprecatedStartCommand from "./start";
import DeprecatedStopCommand from "./stop";
import TunnelStartCommand from "./tunnel/start";
import TunnelStatusCommand from "./tunnel/status";
import TunnelStopCommand from "./tunnel/stop";
import UninstallCliCommand from "./uninstall";
const rootDir = process.cwd();
describe("simple global oclif adapters", testTimeoutOptions(30_000), () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it("maps debug and deploy parser output to actions", async () => {
await DebugCliCommand.run(
["--quick", "--output", "/tmp/debug.tar.gz", "--sandbox", "alpha"],
rootDir,
);
await DeployCliCommand.run(["gpu-alpha"], rootDir);
expect(mocks.runDebugCommandWithOptions).toHaveBeenCalledWith(
{ quick: true, output: "/tmp/debug.tar.gz", sandboxName: "alpha" },
expect.objectContaining({
getDefaultSandbox: expect.any(Function),
runDebug: expect.any(Function),
}),
);
expect(mocks.runDeployAction).toHaveBeenCalledWith("gpu-alpha");
});
it("keeps debug -q scoped to quick diagnostics instead of global quiet mode", async () => {
const configure = vi.spyOn(log, "configure").mockImplementation(() => undefined);
await DebugCliCommand.run(["-q"], rootDir);
expect(mocks.runDebugCommandWithOptions).toHaveBeenCalledWith(
{ quick: true },
expect.objectContaining({ runDebug: expect.any(Function) }),
);
expect(configure).toHaveBeenCalledWith({ debug: false, quiet: false });
expect(configure).not.toHaveBeenCalledWith({ debug: false, quiet: true });
});
it("builds debug defaults from the sandbox registry and OpenShell liveness", async () => {
mocks.listSandboxes.mockReturnValue({
defaultSandbox: "alpha",
sandboxes: [{ name: "alpha" }],
} as never);
await DebugCliCommand.run(["--quick"], rootDir);
const deps = mocks.runDebugCommandWithOptions.mock.calls[0][1];
expect(deps.getDefaultSandbox()).toBe("alpha");
expect(mocks.captureOpenshellCommand).toHaveBeenCalledWith(
"/usr/bin/openshell",
["sandbox", "list"],
expect.objectContaining({ cwd: rootDir, ignoreError: true }),
);
});
it("maps gateway-token flags to the gateway token action", async () => {
const getSandboxAgent = vi.fn(() => "openclaw");
const fetchToken = mocks.fetchGatewayAuthTokenFromSandbox;
const agentExposesToken = vi.fn(() => true);
setGatewayTokenRuntimeBridgeFactoryForTest(() => ({
fetchToken,
getSandboxAgent,
agentExposesToken,
}));
await GatewayTokenCliCommand.run(["alpha", "--quiet"], rootDir);
expect(mocks.runGatewayTokenCommand).toHaveBeenCalledWith(
"alpha",
{ quiet: true },
{ fetchToken, getSandboxAgent, agentExposesToken },
);
expect(mocks.withMcpLifecycleLock).toHaveBeenCalledWith("alpha", expect.any(Function));
});
it("rejects schema-5 gateway-token before fetching or printing credentials (#9203)", async () => {
const fetchToken = vi.fn(() => "must-not-print");
setGatewayTokenRuntimeBridgeFactoryForTest(() => ({
fetchToken,
getSandboxAgent: () => "hermes",
agentExposesToken: () => true,
}));
mocks.assertHermesPortableCommandUnavailable.mockImplementationOnce(() => {
throw new Error("schema-5 token rejected");
});
await expect(GatewayTokenCliCommand.run(["alpha", "--quiet"], rootDir)).rejects.toThrow(
"schema-5 token rejected",
);
expect(fetchToken).not.toHaveBeenCalled();
expect(mocks.runGatewayTokenCommand).not.toHaveBeenCalled();
});
it("maps dashboard-url flags to the dashboard URL action", async () => {
const getSandbox = vi.fn(() => ({ agent: "openclaw", dashboardPort: 18789 }));
const getAccessUrl = vi.fn(() => "http://127.0.0.1:18789");
setDashboardUrlRuntimeBridgeFactoryForTest(() => ({
fetchGatewayAuthTokenFromSandbox: mocks.fetchGatewayAuthTokenFromSandbox,
getSandbox,
getAccessUrl,
}));
await DashboardUrlCliCommand.run(["alpha", "--quiet"], rootDir);
expect(mocks.runDashboardUrlCommand).toHaveBeenCalledWith(
"alpha",
{ quiet: true },
expect.objectContaining({
fetchToken: mocks.fetchGatewayAuthTokenFromSandbox,
getSandbox,
getAccessUrl,
}),
);
});
it("uses process.exitCode (no @oclif/core ExitError) when the gateway-token action fails", async () => {
// NCQ #3180: legacy dispatch did not catch the @oclif/core ExitError
// thrown by this.exit(1), surfacing a raw JS stack trace to the user.
// The adapter must signal failure via process.exitCode instead.
mocks.runGatewayTokenCommand.mockImplementationOnce(() => {
throw new mocks.GatewayTokenCommandError("not applicable");
});
setGatewayTokenRuntimeBridgeFactoryForTest(() => ({
fetchToken: mocks.fetchGatewayAuthTokenFromSandbox,
getSandboxAgent: () => "hermes",
agentExposesToken: () => false,
}));
const previousExitCode = process.exitCode;
process.exitCode = undefined;
try {
await expect(GatewayTokenCliCommand.run(["hermes"], rootDir)).resolves.toBeUndefined();
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = previousExitCode;
}
});
it("renders every line of a multi-line Hermes diagnostic to stderr without leaking an oclif stack trace", async () => {
// PRA-T3 on #5252: when the helper throws a multi-line
// GatewayTokenCommandError for a Hermes sandbox, the wrapper must
// (a) write every line via console.error, (b) signal failure via
// process.exitCode, and (c) leak no @oclif/core ExitError stack trace.
const hermesLines = [
" gateway-token is not applicable for sandbox 'hermes': it uses the 'hermes' agent, which does not expose a gateway auth token. This command only supports the OpenClaw agent.",
" For Hermes dashboard access, run: nemohermes hermes dashboard-url",
" Hermes dashboard auth is read from the in-sandbox config (~/.hermes/config.yaml), not a gateway token.",
];
mocks.runGatewayTokenCommand.mockImplementationOnce(() => {
throw new mocks.GatewayTokenCommandError(hermesLines, 1);
});
setGatewayTokenRuntimeBridgeFactoryForTest(() => ({
fetchToken: mocks.fetchGatewayAuthTokenFromSandbox,
getSandboxAgent: () => "hermes",
agentExposesToken: () => false,
}));
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const previousExitCode = process.exitCode;
process.exitCode = undefined;
try {
await expect(GatewayTokenCliCommand.run(["hermes"], rootDir)).resolves.toBeUndefined();
expect(process.exitCode).toBe(1);
hermesLines.forEach((line) => {
expect(errorSpy).toHaveBeenCalledWith(line);
});
const combined = errorSpy.mock.calls.map((args) => args.join(" ")).join("\n");
expect(combined).not.toMatch(/ExitError|@oclif\/core|at Object\.exit/);
} finally {
process.exitCode = previousExitCode;
errorSpy.mockRestore();
}
});
it("clears a stale non-zero process.exitCode on a successful gateway-token run", async () => {
// CodeRabbit #3182: if a prior run() left process.exitCode = 1, a later
// successful invocation must still report success. Always overwrite.
mocks.runGatewayTokenCommand.mockReturnValueOnce(undefined);
setGatewayTokenRuntimeBridgeFactoryForTest(() => ({
fetchToken: mocks.fetchGatewayAuthTokenFromSandbox,
getSandboxAgent: () => "openclaw",
agentExposesToken: () => true,
}));
const previousExitCode = process.exitCode;
process.exitCode = 1;
try {
await GatewayTokenCliCommand.run(["alpha", "--quiet"], rootDir);
expect(process.exitCode).toBe(0);
} finally {
process.exitCode = previousExitCode;
}
});
it("runs hidden root help and version adapters", async () => {
await RootHelpCommand.run([], rootDir);
await VersionCommand.run([], rootDir);
expect(mocks.showRootHelp).toHaveBeenCalledWith();
expect(mocks.showVersion).toHaveBeenCalledWith();
});
it("maps tunnel and deprecated service commands to service actions", async () => {
await TunnelStartCommand.run([], rootDir);
expect(mocks.runStartCommand).toHaveBeenCalledTimes(1);
await TunnelStopCommand.run([], rootDir);
await TunnelStatusCommand.run([], rootDir);
await DeprecatedStartCommand.run([], rootDir);
expect(mocks.runStartCommand).toHaveBeenCalledTimes(1);
await DeprecatedStopCommand.run([], rootDir);
expect(mocks.runStopCommand).toHaveBeenCalledTimes(2);
expect(mocks.runStartCommand).toHaveBeenCalledWith(
expect.objectContaining({ listSandboxes: expect.any(Function), startAll: mocks.startAll }),
);
expect(mocks.resolveDefaultSandboxName).toHaveBeenCalledWith(expect.any(Function));
expect(mocks.showStatus).toHaveBeenCalledWith({ sandboxName: "resolved-sandbox" });
expect(mocks.runStopCommand).toHaveBeenCalledWith(
expect.objectContaining({ listSandboxes: expect.any(Function), stopAll: mocks.stopAll }),
);
expect(mocks.runStopCommand.mock.calls).toEqual(
expect.arrayContaining([
[expect.not.objectContaining({ releaseGatewayPort: true })],
[expect.objectContaining({ releaseGatewayPort: true })],
]),
);
});
it("passes uninstall runtime dependencies to the uninstall action", async () => {
const originalEnv = process.env;
await UninstallCliCommand.run(["--yes"], rootDir);
expect(mocks.buildVersionedUninstallUrl).toHaveBeenCalledWith("1.2.3");
expect(mocks.runUninstallCommand).toHaveBeenCalledWith(
expect.objectContaining({
args: ["--yes"],
rootDir,
remoteScriptUrl: "https://example.test/1.2.3/uninstall.sh",
env: originalEnv,
spawnSyncImpl: mocks.spawnSync,
log: console.log,
error: console.error,
exit: expect.any(Function),
}),
);
});
it("forwards uninstall flags without assigning host logging semantics", async () => {
const configure = vi.spyOn(log, "configure").mockImplementation(() => undefined);
await UninstallCliCommand.run(["--yes", "--debug"], rootDir);
expect(mocks.runUninstallCommand).toHaveBeenCalledWith(
expect.objectContaining({ args: ["--yes", "--debug"] }),
);
expect(configure).toHaveBeenCalledWith({ debug: false, quiet: false });
expect(configure).not.toHaveBeenCalledWith({ debug: true, quiet: false });
});
});