File size: 21,083 Bytes
d197cf3 | 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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | // Daemon inspect tests cover service inspection and diagnostic output.
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
import {
detectMarkerLineWithGateway,
findExtraGatewayServices,
renderGatewayServiceCleanupHints,
} from "./inspect.js";
const { execSchtasksMock } = vi.hoisted(() => ({
execSchtasksMock: vi.fn(),
}));
vi.mock("./schtasks-exec.js", () => ({
execSchtasks: (...args: unknown[]) => execSchtasksMock(...args),
}));
// File-scope cleanup cannot prevent the nested platform-restoration hooks from running.
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
// Real content from the openclaw-gateway.service unit file (the canonical gateway unit).
const GATEWAY_SERVICE_CONTENTS = `\
[Unit]
Description=OpenClaw Gateway
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/node /home/openclaw/.npm-global/lib/node_modules/openclaw/dist/entry.js gateway --port 18789
Restart=always
Environment=OPENCLAW_SERVICE_MARKER=openclaw
Environment=OPENCLAW_SERVICE_KIND=gateway
[Install]
WantedBy=default.target
`;
// Real content from the openclaw-test.service unit file (a non-gateway openclaw service).
const TEST_SERVICE_CONTENTS = `\
[Unit]
Description=OpenClaw test service
After=default.target
[Service]
Type=simple
ExecStart=/bin/sh -c 'while true; do sleep 60; done'
Restart=on-failure
[Install]
WantedBy=default.target
`;
const CLAWDBOT_GATEWAY_CONTENTS = `\
[Unit]
Description=Clawdbot Gateway
[Service]
ExecStart=/usr/bin/node /opt/clawdbot/dist/entry.js gateway --port 18789
Environment=HOME=/home/clawdbot
`;
const COMPANION_SERVICE_CONTENTS = `\
[Unit]
Description=OpenClaw companion worker
After=openclaw-gateway.service
Requires=openclaw-gateway.service
[Service]
ExecStart=/usr/bin/node /opt/openclaw-worker/dist/index.js worker
`;
const CUSTOM_OPENCLAW_GATEWAY_CONTENTS = `\
[Unit]
Description=Custom OpenClaw gateway
[Service]
ExecStart=/usr/bin/node /opt/openclaw/dist/entry.js gateway --port 18888
`;
describe("detectMarkerLineWithGateway", () => {
it("returns null for openclaw-test.service (openclaw only in description, no gateway on same line)", () => {
expect(detectMarkerLineWithGateway(TEST_SERVICE_CONTENTS)).toBeNull();
});
it("returns openclaw for the canonical gateway unit (ExecStart has both openclaw and gateway)", () => {
expect(detectMarkerLineWithGateway(GATEWAY_SERVICE_CONTENTS)).toBe("openclaw");
});
it("returns clawdbot for a clawdbot gateway unit", () => {
expect(detectMarkerLineWithGateway(CLAWDBOT_GATEWAY_CONTENTS)).toBe("clawdbot");
});
it.each([
"ExecStart=/usr/bin/openclaw \\\n gateway",
"# comment \\\nExecStart=/usr/bin/openclaw gateway",
"; comment \\\nExecStart=/usr/bin/openclaw gateway",
"ExecStart=/usr/bin/openclaw \\\n# comment\n gateway",
])("detects commands through native comments and continuations: %s", (command) => {
expect(detectMarkerLineWithGateway(`[Service]\n${command}\n`)).toBe("openclaw");
});
it.each(["After", "Requires", "Description", "Environment"])(
"ignores gateway mentions in %s instead of an executable directive",
(key) => {
expect(detectMarkerLineWithGateway(`${key}=openclaw gateway\n`)).toBeNull();
},
);
it("ignores dependency-only references to the gateway unit", () => {
expect(detectMarkerLineWithGateway(COMPANION_SERVICE_CONTENTS)).toBeNull();
});
it("ignores non-gateway ExecStart commands that only pass gateway-named options", () => {
const contents = `[Service]\nExecStart=/usr/bin/openclaw-helper --gateway-url http://127.0.0.1:18789 sync\n`;
expect(detectMarkerLineWithGateway(contents)).toBeNull();
});
});
describe("renderGatewayServiceCleanupHints", () => {
it("does not suggest removing a gateway when no extra service was detected", () => {
expect(renderGatewayServiceCleanupHints([])).toEqual([]);
});
it.each([
{
title: "targets the detected macOS LaunchAgent instead of the active gateway",
platform: "darwin",
serviceName: "com.example.openclaw-gateway",
source: "plist: /Users/test/Library/LaunchAgents/com.example.openclaw-gateway.plist",
scope: "user",
firstHint: "launchctl bootout gui/$UID/com.example.openclaw-gateway",
secondHint: "rm /Users/test/Library/LaunchAgents/com.example.openclaw-gateway.plist",
},
{
title: "uses the system domain for a detected macOS LaunchDaemon",
platform: "darwin",
serviceName: "com.example.openclaw-gateway",
source: "plist: /Library/LaunchDaemons/com.example.openclaw-gateway.plist",
scope: "system",
firstHint: "sudo launchctl bootout system/com.example.openclaw-gateway",
secondHint: "sudo rm /Library/LaunchDaemons/com.example.openclaw-gateway.plist",
},
{
title: "keeps global macOS LaunchAgents in the GUI domain",
platform: "darwin",
serviceName: "com.example.openclaw-gateway",
source: "plist: /Library/LaunchAgents/com.example.openclaw-gateway.plist",
scope: "system",
firstHint: "launchctl bootout gui/$UID/com.example.openclaw-gateway",
secondHint: "sudo rm /Library/LaunchAgents/com.example.openclaw-gateway.plist",
},
{
title: "inspects the detected user-level systemd unit without removing it",
platform: "linux",
serviceName: "custom-gateway.service",
source: "unit: /home/test/.config/systemd/user/custom-gateway.service",
scope: "user",
firstHint: "systemctl --user status -- custom-gateway.service",
secondHint: "systemctl --user cat -- custom-gateway.service",
},
{
title: "inspects the detected system-level systemd unit without removing it",
platform: "linux",
serviceName: "custom-gateway.service",
source: "unit: /etc/systemd/system/custom-gateway.service",
scope: "system",
firstHint: "systemctl --system status -- custom-gateway.service",
secondHint: "systemctl --system cat -- custom-gateway.service",
},
{
title: "terminates systemctl options before a detected unit that begins with a dash",
platform: "linux",
serviceName: "-custom-gateway.service",
source: "unit: /home/test/.config/systemd/user/-custom-gateway.service",
scope: "user",
firstHint: "systemctl --user status -- -custom-gateway.service",
secondHint: "systemctl --user cat -- -custom-gateway.service",
},
{
title: "shell-quotes detected POSIX service labels and paths",
platform: "darwin",
serviceName: "com.example.gateway; touch injected",
source: "plist: /Users/test/Launch Agents/example's gateway.plist",
scope: "user",
firstHint: "launchctl bootout gui/$UID/'com.example.gateway; touch injected'",
secondHint: "rm '/Users/test/Launch Agents/example'\\''s gateway.plist'",
},
] as const)("$title", ({ platform, serviceName, source, scope, firstHint, secondHint }) => {
expect(
renderGatewayServiceCleanupHints([
{
platform,
label: serviceName,
detail: source,
scope,
},
]),
).toEqual([firstHint, secondHint]);
});
it("targets the detected Windows scheduled task", () => {
expect(
renderGatewayServiceCleanupHints([
{
platform: "win32",
label: "\\OpenClaw Gateway Backup",
detail: "task: \\OpenClaw Gateway Backup",
scope: "system",
},
]),
).toEqual(['schtasks /Delete /TN "\\OpenClaw Gateway Backup" /F']);
});
it.each(["$(Start-Process calc)", "%OPENCLAW_GATEWAY_TASK%", "unsafe&task", "task`name"])(
"does not render a Windows task name expandable by cmd.exe or PowerShell: %s",
(label) => {
expect(
renderGatewayServiceCleanupHints([
{
platform: "win32",
label,
detail: `task: ${label}`,
scope: "system",
},
]),
).toEqual([]);
},
);
it("does not invent a removal path when service metadata omits it", () => {
expect(
renderGatewayServiceCleanupHints([
{
platform: "darwin",
label: "com.example.openclaw-gateway",
detail: "loaded",
scope: "user",
},
]),
).toEqual(["launchctl bootout gui/$UID/com.example.openclaw-gateway"]);
});
});
describe("findExtraGatewayServices (linux / scanSystemdDir) — real filesystem", () => {
// These tests write real .service files to a temp dir and call findExtraGatewayServices
// with that dir as HOME. No platform mocking or fs mocking needed.
const isLinux = process.platform === "linux";
it.skipIf(!isLinux)("does not report openclaw-test.service as a gateway service", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(path.join(systemdDir, "openclaw-test.service"), TEST_SERVICE_CONTENTS);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
});
it.skipIf(!isLinux)(
"does not report the canonical openclaw-gateway.service as an extra service",
async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(
path.join(systemdDir, "openclaw-gateway.service"),
GATEWAY_SERVICE_CONTENTS,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
},
);
it.skipIf(!isLinux)(
"reports a legacy clawdbot-gateway service as an extra gateway service",
async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
const unitPath = path.join(systemdDir, "clawdbot-gateway.service");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(unitPath, CLAWDBOT_GATEWAY_CONTENTS);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toEqual([
{
platform: "linux",
label: "clawdbot-gateway.service",
detail: `unit: ${unitPath}`,
scope: "user",
marker: "clawdbot",
legacy: true,
},
]);
},
);
it.skipIf(!isLinux)("reports an orphaned legacy systemd backup", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
const backupPath = path.join(systemdDir, "clawdbot-gateway.service.bak");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(backupPath, CLAWDBOT_GATEWAY_CONTENTS);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toEqual([
{
platform: "linux",
label: "clawdbot-gateway.service",
detail: `unit backup: ${backupPath}`,
scope: "user",
marker: "clawdbot",
legacy: true,
},
]);
});
it.skipIf(!isLinux)("reports a legacy systemd unit and its backup once", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
const unitPath = path.join(systemdDir, "clawdbot-gateway.service");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(unitPath, CLAWDBOT_GATEWAY_CONTENTS);
await fs.writeFile(`${unitPath}.bak`, CLAWDBOT_GATEWAY_CONTENTS);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toEqual([
{
platform: "linux",
label: "clawdbot-gateway.service",
detail: `unit: ${unitPath}`,
scope: "user",
marker: "clawdbot",
legacy: true,
},
]);
});
it.skipIf(!isLinux)(
"does not report companion units that only depend on the gateway",
async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(
path.join(systemdDir, "openclaw-companion.service"),
COMPANION_SERVICE_CONTENTS,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
},
);
it.skipIf(!isLinux).each(["", "# comment \\\n", "; comment \\\n"])(
"reports custom-named gateway units after a physical comment: %j",
async (comment) => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const systemdDir = path.join(tmpHome, ".config", "systemd", "user");
const unitPath = path.join(systemdDir, "custom-openclaw.service");
await fs.mkdir(systemdDir, { recursive: true });
await fs.writeFile(
unitPath,
CUSTOM_OPENCLAW_GATEWAY_CONTENTS.replace("ExecStart=", `${comment}ExecStart=`),
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toEqual([
{
platform: "linux",
label: "custom-openclaw.service",
detail: `unit: ${unitPath}`,
scope: "user",
marker: "openclaw",
legacy: false,
},
]);
},
);
});
describe("findExtraGatewayServices (darwin / scanLaunchdDir) — real filesystem", () => {
const originalPlatform = process.platform;
beforeEach(() => {
Object.defineProperty(process, "platform", {
configurable: true,
value: "darwin",
});
});
afterEach(() => {
Object.defineProperty(process, "platform", {
configurable: true,
value: originalPlatform,
});
});
it("does not report LaunchAgent companions that only mention the gateway label", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const launchdDir = path.join(tmpHome, "Library", "LaunchAgents");
await fs.mkdir(launchdDir, { recursive: true });
await fs.writeFile(
path.join(launchdDir, "com.example.companion.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>Label</key><string>com.example.companion</string>
<key>KeepAlive</key><dict><key>OtherJobEnabled</key><dict><key>ai.openclaw.gateway</key><true/></dict></dict>
<key>ProgramArguments</key><array><string>/usr/local/bin/openclaw-helper</string><string>sync</string></array>
</dict></plist>`,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
});
it("does not report LaunchAgent companions that only pass gateway-named options", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const launchdDir = path.join(tmpHome, "Library", "LaunchAgents");
await fs.mkdir(launchdDir, { recursive: true });
await fs.writeFile(
path.join(launchdDir, "com.example.companion-options.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>Label</key><string>com.example.companion-options</string>
<key>ProgramArguments</key><array><string>/usr/local/bin/openclaw-helper</string><string>--gateway-url</string><string>http://127.0.0.1:18789</string><string>sync</string></array>
</dict></plist>`,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
});
it("does not report non-gateway LaunchAgents that mention clawdbot in environment values", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const launchdDir = path.join(tmpHome, "Library", "LaunchAgents");
await fs.mkdir(launchdDir, { recursive: true });
await fs.writeFile(
path.join(launchdDir, "com.github.facebook.watchman.plist"),
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>Label</key><string>com.github.facebook.watchman</string>
<key>EnvironmentVariables</key><dict><key>PATH</key><string>/Users/test/Projects/clawdbot2/node_modules/.bin:/opt/homebrew/bin</string></dict>
<key>ProgramArguments</key><array><string>/opt/homebrew/bin/watchman</string><string>--foreground</string></array>
</dict></plist>`,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toStrictEqual([]);
});
it("reports custom LaunchAgents that execute openclaw gateway", async () => {
const tmpHome = tempDirs.make("openclaw-test-", os.tmpdir());
const launchdDir = path.join(tmpHome, "Library", "LaunchAgents");
const plistPath = path.join(launchdDir, "com.example.openclaw-gateway.plist");
await fs.mkdir(launchdDir, { recursive: true });
await fs.writeFile(
plistPath,
`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>Label</key><string>com.example.openclaw-gateway</string>
<key>ProgramArguments</key><array><string>/usr/local/bin/openclaw</string><string>gateway</string><string>--port</string><string>18888</string></array>
</dict></plist>`,
);
const result = await findExtraGatewayServices({ HOME: tmpHome });
expect(result).toEqual([
{
platform: "darwin",
label: "com.example.openclaw-gateway",
detail: `plist: ${plistPath}`,
scope: "user",
marker: "openclaw",
legacy: false,
},
]);
expect(renderGatewayServiceCleanupHints(result)).toEqual([
"launchctl bootout gui/$UID/com.example.openclaw-gateway",
`rm ${plistPath}`,
]);
});
});
describe("findExtraGatewayServices (win32)", () => {
const originalPlatform = process.platform;
beforeEach(() => {
Object.defineProperty(process, "platform", {
configurable: true,
value: "win32",
});
execSchtasksMock.mockReset();
});
afterEach(() => {
Object.defineProperty(process, "platform", {
configurable: true,
value: originalPlatform,
});
});
it("skips schtasks queries unless deep mode is enabled", async () => {
const result = await findExtraGatewayServices({});
expect(result).toStrictEqual([]);
expect(execSchtasksMock).not.toHaveBeenCalled();
});
it("returns empty results when schtasks query fails", async () => {
execSchtasksMock.mockResolvedValueOnce({
code: 1,
stdout: "",
stderr: "error",
});
const result = await findExtraGatewayServices({}, { deep: true });
expect(result).toStrictEqual([]);
});
it("collects only non-openclaw marker tasks from schtasks output", async () => {
// Real schtasks /Query /FO LIST /V output prefixes root-folder task
// names with a backslash (e.g. TaskName:\OpenClaw Gateway).
execSchtasksMock.mockResolvedValueOnce({
code: 0,
stdout: [
"TaskName:\\OpenClaw Gateway",
"Task To Run: C:\\Program Files\\OpenClaw\\openclaw.exe gateway run",
"",
"TaskName: Clawdbot Legacy",
"Task To Run: C:\\clawdbot\\clawdbot.exe run",
"",
"TaskName: Other Task",
"Task To Run: C:\\tools\\helper.exe",
"",
].join("\n"),
stderr: "",
});
const result = await findExtraGatewayServices({}, { deep: true });
// The \OpenClaw Gateway task is the live launcher — it must be skipped.
// Only the unrelated clawdbot task should be flagged.
expect(result).toEqual([
{
platform: "win32",
label: "Clawdbot Legacy",
detail: "task: Clawdbot Legacy, run: C:\\clawdbot\\clawdbot.exe run",
scope: "system",
marker: "clawdbot",
legacy: true,
},
]);
});
it("reports duplicate root tasks that only share the gateway task prefix", async () => {
execSchtasksMock.mockResolvedValueOnce({
code: 0,
stdout: [
"TaskName:\\OpenClaw Gateway",
"Task To Run: C:\\Program Files\\OpenClaw\\openclaw.exe gateway run",
"",
"TaskName:\\OpenClaw Gateway (dev)",
"Task To Run: C:\\Program Files\\OpenClaw\\openclaw.exe gateway run --profile dev",
"",
"TaskName:\\OpenClaw Gateway Backup",
"Task To Run: C:\\Program Files\\OpenClaw\\openclaw.exe gateway run",
"",
].join("\n"),
stderr: "",
});
const result = await findExtraGatewayServices({}, { deep: true });
expect(result).toEqual([
{
platform: "win32",
label: "\\OpenClaw Gateway Backup",
detail:
"task: \\OpenClaw Gateway Backup, run: C:\\Program Files\\OpenClaw\\openclaw.exe gateway run",
scope: "system",
marker: "openclaw",
legacy: false,
},
]);
});
});
|