Skip to content

Commit 06c0b29

Browse files
committed
fix(daemon): preserve uncertain service probe outcomes
1 parent 3f5c7f7 commit 06c0b29

8 files changed

Lines changed: 293 additions & 179 deletions

‎src/commands/doctor-gateway-services.test.ts‎

Lines changed: 107 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs/promises";
22
import os from "node:os";
33
import path from "node:path";
4+
import { err, ok, type Result } from "@openclaw/normalization-core/result";
45
// Doctor gateway service tests cover service audit diagnostics and duplicate gateway service reporting.
56
import { createRequireRecord } from "openclaw/plugin-sdk/test-fixtures";
67
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -49,7 +50,9 @@ const mocks = vi.hoisted(() => ({
4950
needsNodeRuntimeMigration: vi.fn(() => false),
5051
renderSystemNodeWarning: vi.fn().mockReturnValue(undefined),
5152
resolveSystemNodeInfo: vi.fn().mockResolvedValue(null),
52-
isSystemdUnitActive: vi.fn().mockResolvedValue(false),
53+
isSystemdUnitActive: vi
54+
.fn<typeof import("../daemon/systemd-exec.js").isSystemdUnitActive>()
55+
.mockResolvedValue({ ok: true, value: false }),
5356
uninstallLegacySystemdUnits: vi.fn().mockResolvedValue([]),
5457
readWindowsProcessArgsSync: vi.fn(),
5558
readWindowsStartupFallbackRuntimeForUpdate: vi.fn(),
@@ -433,7 +436,7 @@ describe("maybeRepairGatewayServiceConfig", () => {
433436
mocks.needsNodeRuntimeMigration.mockReturnValue(false);
434437
mocks.renderSystemNodeWarning.mockReturnValue(undefined);
435438
mocks.resolveSystemNodeInfo.mockResolvedValue(null);
436-
mocks.isSystemdUnitActive.mockResolvedValue(false);
439+
mocks.isSystemdUnitActive.mockResolvedValue(ok(false));
437440
mocks.readWindowsProcessArgsSync.mockReturnValue(["node", "openclaw.mjs", "update"]);
438441
mocks.resolveGatewayAuthTokenForService.mockImplementation(async (cfg: OpenClawConfig, env) => {
439442
const configToken =
@@ -1053,7 +1056,7 @@ describe("maybeRepairGatewayServiceConfig", () => {
10531056
...createGatewayCommand("/opt/new-openclaw/dist/index.js"),
10541057
workingDirectory: "/tmp",
10551058
});
1056-
mocks.isSystemdUnitActive.mockResolvedValue(true);
1059+
mocks.isSystemdUnitActive.mockResolvedValue(ok(true));
10571060

10581061
await runRepair({ gateway: {} });
10591062

@@ -1144,7 +1147,7 @@ describe("maybeRepairGatewayServiceConfig", () => {
11441147
...createGatewayCommand("/opt/new-openclaw/dist/index.js"),
11451148
workingDirectory: "/tmp",
11461149
});
1147-
mocks.isSystemdUnitActive.mockResolvedValue(false);
1150+
mocks.isSystemdUnitActive.mockResolvedValue(ok(false));
11481151

11491152
await runRepair({ gateway: {} });
11501153

@@ -1157,46 +1160,69 @@ describe("maybeRepairGatewayServiceConfig", () => {
11571160
expect(mocks.stage).not.toHaveBeenCalled();
11581161
});
11591162

1160-
it("leaves all service metadata unchanged when an active unit has command drift plus other issues", async () => {
1161-
mockProcessPlatform("linux");
1162-
mocks.readCommand.mockResolvedValue({
1163-
programArguments: ["/usr/bin/openclaw", "run"],
1164-
environment: {},
1165-
sourcePath: "/home/test/.config/systemd/user/openclaw-gateway.service",
1166-
});
1167-
mocks.auditGatewayServiceConfig.mockResolvedValue({
1168-
ok: false,
1169-
issues: [
1170-
{
1171-
code: "gateway-command-missing",
1172-
message: "Service command does not include the gateway subcommand",
1173-
level: "aggressive",
1174-
},
1175-
{
1176-
code: "gateway-port-mismatch",
1177-
message: "Gateway service port does not match current gateway config.",
1178-
detail: "18789 -> 18888",
1179-
level: "recommended",
1180-
},
1181-
],
1182-
});
1183-
mocks.buildGatewayInstallPlan.mockResolvedValue({
1184-
programArguments: gatewayProgramArguments,
1185-
workingDirectory: "/tmp",
1186-
environment: {},
1187-
});
1188-
mocks.isSystemdUnitActive.mockResolvedValue(true);
1163+
it.each([
1164+
["active", ok(true)],
1165+
["bus query failed", err("Failed to connect to bus: Permission denied")],
1166+
["timed out", err("Command timed out")],
1167+
] satisfies [string, Result<boolean, string>][])(
1168+
"leaves service metadata unchanged when unit activity is %s and command drift accompanies other issues",
1169+
async (_, active) => {
1170+
mockProcessPlatform("linux");
1171+
mocks.readCommand.mockResolvedValue({
1172+
programArguments: ["/usr/bin/openclaw", "run"],
1173+
environment: {},
1174+
sourcePath: "/home/test/.config/systemd/user/openclaw-gateway.service",
1175+
});
1176+
mocks.auditGatewayServiceConfig.mockResolvedValue({
1177+
ok: false,
1178+
issues: [
1179+
{
1180+
code: "gateway-command-missing",
1181+
message: "Service command does not include the gateway subcommand",
1182+
level: "aggressive",
1183+
},
1184+
{
1185+
code: "gateway-port-mismatch",
1186+
message: "Gateway service port does not match current gateway config.",
1187+
detail: "18789 -> 18888",
1188+
level: "recommended",
1189+
},
1190+
],
1191+
});
1192+
mocks.buildGatewayInstallPlan.mockResolvedValue({
1193+
programArguments: gatewayProgramArguments,
1194+
workingDirectory: "/tmp",
1195+
environment: {},
1196+
});
1197+
mocks.isSystemdUnitActive.mockResolvedValue(active);
11891198

1190-
await runRepair({ gateway: { port: 18888 } });
1199+
await runRepair({ gateway: { port: 18888 } });
11911200

1192-
expectNoteContaining(
1193-
"Gateway service port does not match current gateway config.",
1194-
"Gateway service config",
1195-
);
1196-
expectNoteContaining("leaving supervisor metadata unchanged", "Gateway service config");
1197-
expect(mocks.install).not.toHaveBeenCalled();
1198-
expect(mocks.stage).not.toHaveBeenCalled();
1199-
});
1201+
expectNoteContaining(
1202+
"Gateway service port does not match current gateway config.",
1203+
"Gateway service config",
1204+
);
1205+
expectNoteContaining("supervisor metadata unchanged", "Gateway service config");
1206+
if (active.ok) {
1207+
expectNoteContaining(
1208+
"is running; skipped command/entrypoint rewrites",
1209+
"Gateway service config",
1210+
);
1211+
expectNoNoteContaining("Service command does not include", "Gateway service config");
1212+
} else {
1213+
expectNoteContaining("Service command does not include", "Gateway service config");
1214+
expectNoteContaining(active.error, "Gateway service config");
1215+
expectNoteContaining(
1216+
"systemctl --user status openclaw-gateway.service",
1217+
"Gateway service config",
1218+
);
1219+
expectNoNoteContaining("is running;", "Gateway service config");
1220+
}
1221+
expect(mocks.replaceConfigFile).not.toHaveBeenCalled();
1222+
expect(mocks.install).not.toHaveBeenCalled();
1223+
expect(mocks.stage).not.toHaveBeenCalled();
1224+
},
1225+
);
12001226

12011227
it("skips entrypoint rewrite in non-interactive fix mode", async () => {
12021228
setupGatewayEntrypointRepairScenario({
@@ -1944,7 +1970,7 @@ describe("maybeScanExtraGatewayServices", () => {
19441970
mocks.isContainerEnvironment.mockReturnValue(false);
19451971
mocks.findExtraGatewayServices.mockResolvedValue([]);
19461972
mocks.renderGatewayServiceCleanupHints.mockReturnValue([]);
1947-
mocks.isSystemdUnitActive.mockResolvedValue(false);
1973+
mocks.isSystemdUnitActive.mockResolvedValue(ok(false));
19481974
mocks.uninstallLegacySystemdUnits.mockResolvedValue([]);
19491975
mocks.execLaunchctl.mockReset().mockResolvedValue(launchctlResult());
19501976
});
@@ -1954,51 +1980,45 @@ describe("maybeScanExtraGatewayServices", () => {
19541980
mockProcessPlatform(originalPlatform);
19551981
});
19561982

1957-
it("ignores inactive non-legacy Linux gateway-like services", async () => {
1958-
mockProcessPlatform("linux");
1959-
mocks.findExtraGatewayServices.mockResolvedValue([
1960-
{
1961-
platform: "linux",
1962-
label: "custom-gateway.service",
1963-
detail: "unit: /home/test/.config/systemd/user/custom-gateway.service",
1964-
scope: "user",
1965-
legacy: false,
1966-
},
1967-
]);
1968-
mocks.isSystemdUnitActive.mockResolvedValue(false);
1969-
1970-
await maybeScanExtraGatewayServices({ deep: false }, makeDoctorIo(), makeDoctorPrompts());
1971-
1972-
expect(mocks.isSystemdUnitActive).toHaveBeenCalledWith(
1973-
process.env,
1974-
"custom-gateway.service",
1975-
"user",
1976-
);
1977-
expectNoNoteContaining("custom-gateway.service", "Other gateway-like services detected");
1978-
});
1979-
1980-
it("reports active non-legacy Linux gateway-like services", async () => {
1981-
mockProcessPlatform("linux");
1982-
mocks.findExtraGatewayServices.mockResolvedValue([
1983-
{
1984-
platform: "linux",
1983+
it.each([
1984+
["inactive", ok(false), "user", false],
1985+
["active", ok(true), "system", true],
1986+
["unknown", err("Failed to connect to bus: Permission denied"), "system", true],
1987+
] satisfies [string, Result<boolean, string>, "user" | "system", boolean][])(
1988+
"reports non-legacy Linux gateway-like services with %s activity only when appropriate",
1989+
async (_, active, scope, reported) => {
1990+
mockProcessPlatform("linux");
1991+
const { renderGatewayServiceCleanupHints } =
1992+
await vi.importActual<typeof import("../daemon/inspect.js")>("../daemon/inspect.js");
1993+
mocks.renderGatewayServiceCleanupHints.mockImplementation(renderGatewayServiceCleanupHints);
1994+
const unitPath = `${scope === "user" ? "/home/test/.config/systemd/user" : "/etc/systemd/system"}/custom-gateway.service`;
1995+
const service = {
1996+
platform: "linux" as const,
19851997
label: "custom-gateway.service",
1986-
detail: "unit: /etc/systemd/system/custom-gateway.service",
1987-
scope: "system",
1998+
detail: `unit: ${unitPath}`,
1999+
scope,
19882000
legacy: false,
1989-
},
1990-
]);
1991-
mocks.isSystemdUnitActive.mockResolvedValue(true);
2001+
};
2002+
mocks.findExtraGatewayServices.mockResolvedValue([service]);
2003+
mocks.isSystemdUnitActive.mockResolvedValue(active);
19922004

1993-
await maybeScanExtraGatewayServices({ deep: true }, makeDoctorIo(), makeDoctorPrompts());
2005+
await maybeScanExtraGatewayServices({ deep: false }, makeDoctorIo(), makeDoctorPrompts());
19942006

1995-
expect(mocks.isSystemdUnitActive).toHaveBeenCalledWith(
1996-
process.env,
1997-
"custom-gateway.service",
1998-
"system",
1999-
);
2000-
expectNoteContaining("custom-gateway.service", "Other gateway-like services detected");
2001-
});
2007+
expect(mocks.isSystemdUnitActive).toHaveBeenCalledWith(
2008+
process.env,
2009+
"custom-gateway.service",
2010+
scope,
2011+
);
2012+
if (reported) {
2013+
expectNoteContaining("custom-gateway.service", "Other gateway-like services detected");
2014+
expect(mocks.renderGatewayServiceCleanupHints).toHaveBeenCalledWith([service]);
2015+
expectNoteContaining(`${scope === "system" ? "sudo " : ""}rm ${unitPath}`, "Cleanup hints");
2016+
} else {
2017+
expectNoNoteContaining("custom-gateway.service", "Other gateway-like services detected");
2018+
}
2019+
expect(mocks.uninstallLegacySystemdUnits).not.toHaveBeenCalled();
2020+
},
2021+
);
20022022

20032023
it("renders cleanup hints only for the detected extra macOS gateway", async () => {
20042024
mockProcessPlatform("darwin");
@@ -2504,7 +2524,9 @@ describe("maybeResolveDuelingSystemdGatewayScopes", () => {
25042524
expect(prompter.confirmRuntimeRepair).not.toHaveBeenCalled();
25052525
expect(mocks.uninstallUserSystemdGatewayUnit).not.toHaveBeenCalled();
25062526
expect(mocks.note).toHaveBeenCalledWith(
2507-
expect.stringContaining("not both running and enabled at boot"),
2527+
expect.stringContaining(
2528+
"Could not verify the system-scope unit is both running and enabled at boot",
2529+
),
25082530
"Gateway cleanup needs an owner decision",
25092531
);
25102532
});

‎src/commands/doctor-gateway-services.ts‎

Lines changed: 24 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -271,34 +271,24 @@ async function readWindowsGatewayRuntimeForUpdateRepair(params: {
271271
return await params.service.readRuntime(params.env).catch(() => null);
272272
}
273273

274-
async function suppressRunningSystemdExecStartRepairs(params: {
275-
command: GatewayServiceCommandConfig;
276-
issues: { code: string }[];
277-
}): Promise<boolean> {
278-
if (process.platform !== "linux") {
279-
return false;
274+
async function resolveSystemdServiceRewriteBlock(
275+
command: GatewayServiceCommandConfig,
276+
issues: { code: string }[],
277+
): Promise<string | undefined> {
278+
if (process.platform !== "linux" || !issues.some(isExecStartRepairIssue)) {
279+
return undefined;
280280
}
281-
if (!params.issues.some(isExecStartRepairIssue)) {
282-
return false;
281+
const unitName = resolveSystemdUnitNameFromServicePath(command.sourcePath);
282+
const scope = resolveSystemdScopeFromServicePath(command.sourcePath);
283+
const active = await isSystemdUnitActive(process.env, unitName, scope);
284+
if (!active.ok) {
285+
return `Could not determine whether gateway service ${unitName} is active: ${active.error}. Leaving supervisor metadata unchanged. Check \`systemctl${scope === "user" ? " --user" : ""} status ${unitName}\` and rerun doctor.`;
283286
}
284-
const unitName = resolveSystemdUnitNameFromServicePath(params.command.sourcePath);
285-
const scope = resolveSystemdScopeFromServicePath(params.command.sourcePath);
286-
if (!(await isSystemdUnitActive(process.env, unitName, scope))) {
287-
return false;
287+
if (!active.value) {
288+
return undefined;
288289
}
289-
const before = params.issues.length;
290-
params.issues.splice(
291-
0,
292-
params.issues.length,
293-
...params.issues.filter((issue) => !isExecStartRepairIssue(issue)),
294-
);
295-
if (params.issues.length !== before) {
296-
note(
297-
`Gateway service ${unitName} is running; skipped command/entrypoint rewrites for this doctor pass.`,
298-
"Gateway service config",
299-
);
300-
}
301-
return true;
290+
issues.splice(0, issues.length, ...issues.filter((issue) => !isExecStartRepairIssue(issue)));
291+
return `Gateway service ${unitName} is running; skipped command/entrypoint rewrites and leaving supervisor metadata unchanged. Stop the service first or use \`openclaw gateway install --force\` when you want to replace the active launcher.`;
302292
}
303293

304294
async function filterInactiveExtraGatewayServices(
@@ -313,7 +303,8 @@ async function filterInactiveExtraGatewayServices(
313303
activeOrLegacy.push(svc);
314304
continue;
315305
}
316-
if (await isSystemdUnitActive(process.env, svc.label, svc.scope)) {
306+
const active = await isSystemdUnitActive(process.env, svc.label, svc.scope);
307+
if (!active.ok || active.value) {
317308
activeOrLegacy.push(svc);
318309
}
319310
}
@@ -655,10 +646,10 @@ export async function maybeRepairGatewayServiceConfig(
655646
});
656647
}
657648

658-
const serviceRewriteBlocked = await suppressRunningSystemdExecStartRepairs({
659-
command,
660-
issues: audit.issues,
661-
});
649+
const serviceRewriteBlock = await resolveSystemdServiceRewriteBlock(command, audit.issues);
650+
if (serviceRewriteBlock) {
651+
note(serviceRewriteBlock, "Gateway service config");
652+
}
662653

663654
const hasEntrypointMismatch = audit.issues.some(
664655
(issue) => issue.code === SERVICE_AUDIT_CODES.gatewayEntrypointMismatch,
@@ -704,11 +695,7 @@ export async function maybeRepairGatewayServiceConfig(
704695
return cfg;
705696
}
706697

707-
if (serviceRewriteBlocked) {
708-
note(
709-
"Gateway service is running; leaving supervisor metadata unchanged. Stop the service first or use `openclaw gateway install --force` when you want to replace the active launcher.",
710-
"Gateway service config",
711-
);
698+
if (serviceRewriteBlock) {
712699
return cfg;
713700
}
714701

@@ -1067,7 +1054,7 @@ export async function maybeResolveDuelingSystemdGatewayScopes(
10671054
if (!systemOwnsGateway) {
10681055
note(
10691056
[
1070-
"The system-scope unit is not both running and enabled at boot, so the",
1057+
"Could not verify the system-scope unit is both running and enabled at boot, so the",
10711058
"user-scope unit may be your working gateway. Not removing anything",
10721059
"automatically.",
10731060
"If the system-scope unit is the one you want, activate it and re-run doctor:",
@@ -1081,7 +1068,7 @@ export async function maybeResolveDuelingSystemdGatewayScopes(
10811068
}
10821069
note(
10831070
[
1084-
"The system-scope unit is the active or boot-enabled supervisor and is",
1071+
"The system-scope unit is the active and boot-enabled supervisor and is",
10851072
"treated as authoritative; the user-scope unit is the redundant leftover.",
10861073
].join("\n"),
10871074
"System-scope unit owns the gateway",

0 commit comments

Comments
 (0)