File size: 14,641 Bytes
f778c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Register service command tests cover daemon service subcommand registration.
import { Command } from "commander";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { isVerbose, setVerbose } from "../../globals.js";
import { captureEnv, deleteTestEnvValue, setTestEnvValue } from "../../test-utils/env.js";
import { mockProcessPlatform } from "../../test-utils/vitest-spies.js";
import { withConsoleLogsRoutedToStderrForJson } from "../json-output-mode.js";
import { ensureConfigReady } from "../program/config-guard.js";
import { registerPreActionHooks } from "../program/preaction.js";
import { addGatewayServiceCommands } from "./register-service-commands.js";
import { registerDaemonCli } from "./register.js";

const runDaemonInstall = vi.fn(async (_opts: unknown) => {});
const runDaemonRestart = vi.fn(async (_opts: unknown) => {});
const runDaemonStart = vi.fn(async (_opts: unknown) => {});
const runDaemonStatus = vi.fn(async (_opts: unknown) => {});
const runDaemonStop = vi.fn(async (_opts: unknown) => {});
const runDaemonUninstall = vi.fn(async (_opts: unknown) => {});

vi.mock("../program/config-guard.js", () => ({ ensureConfigReady: vi.fn(async () => {}) }));

const RESTART_ROUTE_ENV_KEYS = [
  "OPENCLAW_SERVICE_MARKER",
  "OPENCLAW_SERVICE_KIND",
  "OPENCLAW_SUPERVISOR_MODE",
];

const gatewayServiceEnv = {
  OPENCLAW_SERVICE_MARKER: "openclaw",
  OPENCLAW_SERVICE_KIND: "gateway",
};

vi.mock("./install.runtime.js", () => ({
  runDaemonInstall: (opts: unknown) => runDaemonInstall(opts),
}));

vi.mock("./status.runtime.js", () => ({
  runDaemonStatus: (opts: unknown) => runDaemonStatus(opts),
}));

vi.mock("./lifecycle.runtime.js", () => ({
  runDaemonRestart: (opts: unknown) => runDaemonRestart(opts),
  runDaemonStart: (opts: unknown) => runDaemonStart(opts),
  runDaemonStop: (opts: unknown) => runDaemonStop(opts),
  runDaemonUninstall: (opts: unknown) => runDaemonUninstall(opts),
}));

function createGatewayParentLikeCommand(program?: Command) {
  const gateway = program ? program.command("gateway") : new Command().name("gateway");
  // Mirror overlapping root gateway options that conflict with service subcommand options.
  gateway.option("--port <port>", "Port for the gateway WebSocket");
  gateway.option("--token <token>", "Gateway token");
  gateway.option("--password <password>", "Gateway password");
  gateway.option("--force", "Gateway run --force", false);
  gateway.option("--allow-unconfigured", "Gateway run without local mode", false);
  addGatewayServiceCommands(gateway);
  return gateway;
}

function expectSingleDaemonCall(mockFn: ReturnType<typeof vi.fn>) {
  expect(mockFn).toHaveBeenCalledTimes(1);
  const opts = mockFn.mock.calls[0]?.[0] as Record<string, unknown> | undefined;
  if (opts === undefined) {
    throw new Error("expected daemon call options");
  }
  return opts;
}

function setRestartRouteEnv(env: Record<string, string | undefined>) {
  for (const key of RESTART_ROUTE_ENV_KEYS) {
    const value = env[key];
    if (value === undefined) {
      deleteTestEnvValue(key);
    } else {
      setTestEnvValue(key, value);
    }
  }
}

describe("addGatewayServiceCommands", () => {
  let restartRouteEnvSnapshot: ReturnType<typeof captureEnv>;

  beforeEach(() => {
    restartRouteEnvSnapshot = captureEnv(RESTART_ROUTE_ENV_KEYS);
    setRestartRouteEnv({});
    runDaemonInstall.mockClear();
    runDaemonRestart.mockClear();
    runDaemonStart.mockClear();
    runDaemonStatus.mockClear();
    runDaemonStop.mockClear();
    runDaemonUninstall.mockClear();
    vi.mocked(ensureConfigReady).mockClear();
  });

  afterEach(() => {
    restartRouteEnvSnapshot.restore();
    vi.restoreAllMocks();
  });

  it.each(
    ["gateway", "daemon"].flatMap((parent) =>
      ["install", "restart", "stop"].map((action) => ({ parent, action })),
    ),
  )(
    "probes $parent $action update custody without startup mutation or invoking the action",
    async ({ parent, action }) => {
      const program = new Command().name("openclaw").enablePositionalOptions();
      addGatewayServiceCommands(program.command(parent));
      registerPreActionHooks(program, "9.9.9-test");
      const previousArgv = process.argv;
      const previousTitle = process.title;
      const previousVerbose = isVerbose();
      const startupEnv = captureEnv(["NODE_NO_WARNINGS"]);
      process.argv = ["node", "openclaw", parent, action, "--update-executor", "check"];
      const output = vi.spyOn(process.stdout, "write").mockReturnValue(true);
      try {
        await withConsoleLogsRoutedToStderrForJson(
          process.argv,
          () => program.parseAsync(process.argv),
          { restoreChanges: true },
        );
      } finally {
        process.argv = previousArgv;
        process.title = previousTitle;
        setVerbose(previousVerbose);
        startupEnv.restore();
      }
      expect(output.mock.calls.map(([chunk]) => String(chunk)).join("")).toBe(
        JSON.stringify({ updateExecutor: "root-spawner-v1", targetRootBinding: true }),
      );
      expect(ensureConfigReady).not.toHaveBeenCalled();
      expect(runDaemonInstall).not.toHaveBeenCalled();
      expect(runDaemonRestart).not.toHaveBeenCalled();
      expect(runDaemonStop).not.toHaveBeenCalled();
    },
  );

  it.each([
    {
      name: "forwards install option collisions from parent gateway command",
      argv: ["install", "--force", "--port", "19000", "--token", "tok_test", "--runtime", "bun"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonInstall);
        expect(opts.force).toBe(true);
        expect(opts.port).toBe("19000");
        expect(opts.token).toBe("tok_test");
        expect(opts.runtime).toBe("bun");
      },
    },
    {
      name: "preserves an omitted service start-mode override during updater reinstall",
      argv: ["install", "--force", "--json"],
      assert: () => {
        expect(expectSingleDaemonCall(runDaemonInstall)).toMatchObject({
          force: true,
          json: true,
          allowUnconfigured: undefined,
        });
      },
    },
    {
      name: "forwards an explicit service start-mode override",
      argv: ["install", "--allow-unconfigured"],
      assert: () => {
        expect(expectSingleDaemonCall(runDaemonInstall).allowUnconfigured).toBe(true);
      },
    },
    {
      name: "inherits the parent service start-mode override",
      argv: ["--allow-unconfigured", "install"],
      assert: () => {
        expect(expectSingleDaemonCall(runDaemonInstall).allowUnconfigured).toBe(true);
      },
    },
    {
      name: "forwards restart force and wait controls",
      argv: ["restart", "--wait", "30s"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonRestart);
        expect(opts.wait).toBe("30s");
      },
    },
    {
      name: "forwards restart safe control",
      argv: ["restart", "--safe"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonRestart);
        expect(opts.safe).toBe(true);
      },
    },
    {
      name: "forwards restart force control",
      argv: ["restart", "--force"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonRestart);
        expect(opts.force).toBe(true);
      },
    },
    {
      name: "forwards stop force control",
      argv: ["stop", "--force"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonStop);
        expect(opts.force).toBe(true);
      },
    },
    {
      name: "forwards status auth collisions from parent gateway command",
      argv: ["status", "--token", "tok_status", "--password", "pw_status"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonStatus);
        const rpc = opts.rpc as { token?: unknown; password?: unknown } | undefined;
        expect(rpc?.token).toBe("tok_status");
        expect(rpc?.password).toBe("pw_status"); // pragma: allowlist secret
      },
    },
    {
      name: "forwards require-rpc for status",
      argv: ["status", "--require-rpc"],
      assert: () => {
        const opts = expectSingleDaemonCall(runDaemonStatus);
        expect(opts.requireRpc).toBe(true);
      },
    },
  ])("$name", async ({ argv, assert }) => {
    const gateway = createGatewayParentLikeCommand();
    await gateway.parseAsync(argv, { from: "user" });
    assert();
  });

  it.each([
    {
      name: "uses safe restart for a plain Windows Gateway service restart",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["restart", "--json"],
      expected: { safe: true, json: true },
    },
    {
      name: "keeps a plain restart non-safe outside a service process",
      platform: "win32" as const,
      env: {},
      argv: ["restart"],
      expected: { safe: false },
    },
    {
      name: "keeps a plain restart non-safe inside a node service",
      platform: "win32" as const,
      env: { OPENCLAW_SERVICE_MARKER: "openclaw", OPENCLAW_SERVICE_KIND: "node" },
      argv: ["restart"],
      expected: { safe: false },
    },
    {
      name: "keeps a plain Gateway service restart non-safe outside Windows",
      platform: "linux" as const,
      env: gatewayServiceEnv,
      argv: ["restart"],
      expected: { safe: false },
    },
    {
      name: "keeps an externally supervised plain restart non-safe",
      platform: "win32" as const,
      env: { ...gatewayServiceEnv, OPENCLAW_SUPERVISOR_MODE: "external" },
      argv: ["restart"],
      expected: { safe: false },
    },
    {
      name: "honors normalized external supervisor mode before routing",
      platform: "win32" as const,
      env: { ...gatewayServiceEnv, OPENCLAW_SUPERVISOR_MODE: "  ExTeRnAl  " },
      argv: ["restart"],
      expected: { safe: false },
    },
    {
      name: "preserves explicit safe restart under external supervision",
      platform: "win32" as const,
      env: { ...gatewayServiceEnv, OPENCLAW_SUPERVISOR_MODE: "external" },
      argv: ["restart", "--safe"],
      expected: { safe: true },
    },
    {
      name: "preserves leaf force instead of adding implicit safe mode",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["restart", "--force"],
      expected: { safe: false, force: true },
    },
    {
      name: "preserves inherited force instead of adding implicit safe mode",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["--force", "restart"],
      expected: { safe: false, force: true },
    },
    {
      name: "preserves wait instead of adding implicit safe mode",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["restart", "--wait", "30s"],
      expected: { safe: false, wait: "30s" },
    },
    {
      name: "preserves definition control instead of adding implicit safe mode",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["restart", "--preserve-definition"],
      expected: { safe: false, preserveDefinition: true },
    },
    {
      name: "preserves skip-deferral validation instead of adding implicit safe mode",
      platform: "win32" as const,
      env: gatewayServiceEnv,
      argv: ["restart", "--skip-deferral"],
      expected: { safe: false, skipDeferral: true },
    },
  ])("$name", async ({ platform, env, argv, expected }) => {
    mockProcessPlatform(platform);
    setRestartRouteEnv(env);
    const gateway = createGatewayParentLikeCommand().enablePositionalOptions();

    await gateway.parseAsync(argv, { from: "user" });

    expect(expectSingleDaemonCall(runDaemonRestart)).toMatchObject(expected);
  });

  it.each(["gateway", "daemon"])("parses preservation only on %s restart", async (name) => {
    const program = new Command()
      .enablePositionalOptions()
      .exitOverride()
      .configureOutput({ writeErr: () => {} });
    if (name === "daemon") {
      registerDaemonCli(program);
    } else {
      createGatewayParentLikeCommand(program);
    }
    await program.parseAsync([name, "restart", "--preserve-definition", "--json"], {
      from: "user",
    });
    expect(expectSingleDaemonCall(runDaemonRestart)).toMatchObject({
      preserveDefinition: true,
      json: true,
    });
    for (const verb of ["install", "start", "stop", "uninstall"]) {
      await expect(
        program.parseAsync([name, verb, "--preserve-definition"], { from: "user" }),
      ).rejects.toMatchObject({ code: "commander.unknownOption" });
    }
    expect(runDaemonInstall).not.toHaveBeenCalled();
    expect(runDaemonStart).not.toHaveBeenCalled();
    expect(runDaemonStop).not.toHaveBeenCalled();
    expect(runDaemonUninstall).not.toHaveBeenCalled();
  });

  it.each(
    [
      { leaf: "status", runner: runDaemonStatus },
      { leaf: "install", runner: runDaemonInstall },
      { leaf: "uninstall", runner: runDaemonUninstall },
      { leaf: "start", runner: runDaemonStart },
      { leaf: "stop", runner: runDaemonStop },
      { leaf: "restart", runner: runDaemonRestart },
    ].flatMap(({ leaf, runner }) => [
      { name: `daemon --json ${leaf}`, argv: ["daemon", "--json", leaf], runner },
      { name: `daemon ${leaf} --json`, argv: ["daemon", leaf, "--json"], runner },
    ]),
  )("forwards JSON mode for $name", async ({ argv, runner }) => {
    const program = new Command().enablePositionalOptions().exitOverride();
    registerDaemonCli(program);

    await program.parseAsync(argv, { from: "user" });

    expect(expectSingleDaemonCall(runner).json).toBe(true);
  });

  it("inherits an explicit parent port instead of a status leaf default", async () => {
    const gateway = createGatewayParentLikeCommand().enablePositionalOptions();
    const status = gateway.commands.find((command) => command.name() === "status")!;
    status.setOptionValueWithSource("port", "19003", "default");

    await gateway.parseAsync(["--port", "19002", "status"], { from: "user" });

    expect(expectSingleDaemonCall(runDaemonStatus).rpc).toMatchObject({
      port: "19002",
      localPortOverride: 19002,
    });
  });

  it.each([
    { argv: ["status", "--port", "0"], error: "--port must be an integer between 1 and 65535." },
    {
      argv: ["--port", "19002", "status", "--url", "ws://localhost:19002"],
      error: "Use either --url or --port, not both.",
    },
  ])("rejects invalid status options $argv", async ({ argv, error }) => {
    const gateway = createGatewayParentLikeCommand().enablePositionalOptions().exitOverride();

    await expect(gateway.parseAsync(argv, { from: "user" })).rejects.toThrow(error);
    expect(runDaemonStatus).not.toHaveBeenCalled();
  });
});