Skip to content

Commit 21e9634

Browse files
SunnyShu0925claudePatrick-Erichsen
authored
fix(node-cli): warn when systemd user lingering is disabled after install (#118430)
* [AI] fix(node-cli): warn when systemd user lingering is disabled after install openclaw node install now detects when systemd user lingering is off and warns the operator (text + JSON) to run 'sudo loginctl enable-linger <user>'. Without lingering, the user-level node service is torn down when the last SSH session ends, so the node silently goes offline after logout. The check is read-only and never auto-enables lingering, matching the operator-consent policy used elsewhere. It runs only on the verified-success path: an optional onVerified hook is added to installDaemonServiceAndEmit that fires after service.isLoaded() confirms the service is loaded and before the success payload is emitted. The linger diagnostic runs there, so a failed install or verification failure never carries a linger warning (avoids misdirecting the operator to fix lingering for a service that was not successfully installed). The already-installed short-circuit warns separately. Skipped on non-Linux and when systemd user service is unavailable. Adds unit tests for both paths, the linger=yes no-op, the install-failure isolation, the verification-failure no-warn regression, and the systemd-unavailable skip, plus response.test.ts cases covering onVerified running on success and failing safely when it throws. The readSystemdUserLingerStatus mock is typed with the full linger union to satisfy tsgo. Documents the linger step in docs/cli/node.md and docs/nodes/troubleshooting.md. Real-behavior evidence captured on a Linux host by toggling loginctl disable-linger/enable-linger and running the real install flow: linger=no emits the warning on successful install (text + JSON) and on the already-installed path; linger=yes emits nothing; a failed install or verification failure emits no warning. Fixes #107033 Co-Authored-By: deepseek-v4-flash <[email protected]> * fix(node-cli): align linger user with service owner * docs(node): narrow crash-loop claim to gateway units The duplicate-scope guard that raises on two managers running the same unit name is enforced for gateway units (two supervisors on the same port SIGTERM each other in a restart loop); assertNoSystemGatewayOwnership returns early for node services, so claiming node services crash-loop misattributes gateway behavior. Qualify the troubleshooting note accordingly. Addresses ClawSweeper P3 finding on PR #118430. * fix(systemd): align linger checks with service owner * test(doctor): align linger status mock contract * style(doctor): format linger mock * test(wizard): mock systemd service account --------- Co-authored-by: deepseek-v4-flash <[email protected]> Co-authored-by: Patrick Erichsen <[email protected]>
1 parent 7ddc65d commit 21e9634

14 files changed

Lines changed: 508 additions & 18 deletions

‎docs/cli/node.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,12 @@ Options:
126126
- `--runtime <runtime>`: Service runtime (`node`)
127127
- `--force`: Reinstall/overwrite if already installed
128128

129+
> **Linux (systemd user service):** Run `sudo loginctl enable-linger <user>` after
130+
> install. Without lingering, `systemd --user` tears down the node service when
131+
> your last SSH session ends, so the node silently goes offline after logout.
132+
> `openclaw node install` prints this warning when it detects lingering is
133+
> disabled.
134+
129135
Manage the service:
130136

131137
```bash

‎docs/nodes/troubleshooting.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,42 @@ title: "Node troubleshooting"
88

99
Use this page when a node is visible in status but node tools fail.
1010

11+
## Node goes offline after SSH logout (Linux)
12+
13+
On Linux, `openclaw node install` creates a **user-level** systemd service. The
14+
`systemd --user` instance is torn down when your last login session ends, so the
15+
node service stops the moment you log out — even though it looked healthy
16+
(`enabled` + `running`) while you were connected.
17+
18+
Check lingering:
19+
20+
```bash
21+
loginctl show-user "$USER" -p Linger
22+
```
23+
24+
If it reads `Linger=no`, enable it (may require sudo):
25+
26+
```bash
27+
sudo loginctl enable-linger "$USER"
28+
```
29+
30+
Then restart the node service and verify it survives logout:
31+
32+
```bash
33+
openclaw node restart
34+
# log out, then from another machine:
35+
openclaw nodes status
36+
```
37+
38+
`openclaw node install` prints a warning with this recovery command when it
39+
detects lingering is disabled. Don't mix a user-level service with a
40+
system-level one for the same node. The duplicate-scope guard that prevents
41+
two managers from running the same unit name is enforced for gateway units
42+
(two supervisors on the same port SIGTERM each other in a restart loop); for
43+
node services the installer does not raise this guard, so a leftover unit in
44+
the other scope can leave the node in an ambiguous state. Fully remove one
45+
before switching.
46+
1147
## Command ladder
1248

1349
```bash

‎src/cli/daemon-cli/response.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ describe("daemon action JSON hints", () => {
5555
});
5656

5757
describe("daemon install verification", () => {
58-
function createInstallParams(isLoaded: GatewayService["isLoaded"]) {
58+
function createInstallParams(
59+
isLoaded: GatewayService["isLoaded"],
60+
onVerified?: () => Promise<void>,
61+
) {
5962
const service = {
6063
label: "systemd user",
6164
loadedText: "enabled",
@@ -69,6 +72,7 @@ describe("daemon install verification", () => {
6972
emit: vi.fn(),
7073
fail: vi.fn(),
7174
install: vi.fn(async () => {}),
75+
onVerified,
7276
};
7377
}
7478

@@ -113,4 +117,36 @@ describe("daemon install verification", () => {
113117
}),
114118
);
115119
});
120+
121+
it("runs onVerified after verification succeeds and before the success emit", async () => {
122+
const onVerified = vi.fn(async () => {});
123+
const params = createInstallParams(
124+
vi.fn(async () => true),
125+
onVerified,
126+
);
127+
128+
await installDaemonServiceAndEmit(params);
129+
130+
expect(onVerified).toHaveBeenCalledTimes(1);
131+
expect(params.fail).not.toHaveBeenCalled();
132+
expect(params.emit).toHaveBeenCalledWith(
133+
expect.objectContaining({ ok: true, result: "installed" }),
134+
);
135+
});
136+
137+
it("fails with no success emit when onVerified throws", async () => {
138+
const params = createInstallParams(
139+
vi.fn(async () => true),
140+
async () => {
141+
throw new Error("post-check boom");
142+
},
143+
);
144+
145+
await installDaemonServiceAndEmit(params);
146+
147+
expect(params.fail).toHaveBeenCalledWith(
148+
"Gateway post-install check failed: Error: post-check boom",
149+
);
150+
expect(params.emit).not.toHaveBeenCalled();
151+
});
116152
});

‎src/cli/daemon-cli/response.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,13 @@ export async function installDaemonServiceAndEmit(params: {
230230
emit: (payload: Omit<DaemonActionResponse, "action">) => void;
231231
fail: (message: string, hints?: string[]) => void;
232232
install: () => Promise<void>;
233+
/**
234+
* Runs only after the service has been written AND verified as loaded, but
235+
* before the success payload is emitted. Use this for post-success
236+
* diagnostics (e.g. linger warnings) so they never accompany a failed
237+
* install or a verification failure. Throwing here surfaces as a failure.
238+
*/
239+
onVerified?: () => Promise<void>;
233240
}) {
234241
try {
235242
await params.install();
@@ -257,6 +264,16 @@ export async function installDaemonServiceAndEmit(params: {
257264
);
258265
return;
259266
}
267+
// Post-success diagnostics run only on the verified-success path, so a
268+
// failed install or verification never carries their warnings.
269+
if (params.onVerified) {
270+
try {
271+
await params.onVerified();
272+
} catch (err) {
273+
params.fail(`${params.serviceNoun} post-install check failed: ${String(err)}`);
274+
return;
275+
}
276+
}
260277
params.emit({
261278
ok: true,
262279
result: "installed",

‎src/cli/node-cli/daemon.test.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ const mocks = vi.hoisted(() => {
3232
environmentValueSources: {},
3333
})),
3434
loadNodeHostConfig: vi.fn(),
35+
isSystemdUserServiceAvailable: vi.fn(async () => true),
36+
resolveSystemdUserServiceAccount: vi.fn(() => "pi"),
37+
readSystemdUserLingerStatus: vi.fn(
38+
async (): Promise<{ user: string; linger: "yes" | "no" }> => ({
39+
user: "pi",
40+
linger: "no",
41+
}),
42+
),
3543
};
3644
});
3745

@@ -59,6 +67,17 @@ vi.mock("../../daemon/runtime-hints.js", () => ({
5967
buildPlatformServiceStartHints: () => ["openclaw node install", "openclaw node start"],
6068
}));
6169

70+
vi.mock("../../daemon/systemd.js", async () => {
71+
const actual =
72+
await vi.importActual<typeof import("../../daemon/systemd.js")>("../../daemon/systemd.js");
73+
return {
74+
...actual,
75+
isSystemdUserServiceAvailable: mocks.isSystemdUserServiceAvailable,
76+
resolveSystemdUserServiceAccount: mocks.resolveSystemdUserServiceAccount,
77+
readSystemdUserLingerStatus: mocks.readSystemdUserLingerStatus,
78+
};
79+
});
80+
6281
vi.mock("../../../packages/terminal-core/src/theme.js", async () => {
6382
const actual = await vi.importActual<
6483
typeof import("../../../packages/terminal-core/src/theme.js")
@@ -111,6 +130,12 @@ describe("runNodeDaemonInstall", () => {
111130
tlsFingerprint: "saved-fingerprint",
112131
},
113132
});
133+
mocks.isSystemdUserServiceAvailable.mockReset().mockResolvedValue(true);
134+
mocks.resolveSystemdUserServiceAccount.mockReset().mockReturnValue("pi");
135+
mocks.readSystemdUserLingerStatus.mockReset().mockResolvedValue({
136+
user: "pi",
137+
linger: "no",
138+
});
114139
});
115140

116141
it.each([
@@ -179,6 +204,109 @@ describe("runNodeDaemonInstall", () => {
179204
expect.stringContaining("--no-tls cannot be combined with --tls-fingerprint"),
180205
);
181206
});
207+
208+
it("warns about disabled systemd lingering after a fresh install (text mode)", async () => {
209+
// isLoaded=true so the service-load verification passes and the linger
210+
// diagnostic runs on the verified-success path.
211+
mocks.service.isLoaded.mockResolvedValue(true);
212+
await runNodeDaemonInstall({ force: true });
213+
214+
expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalled();
215+
expect(mocks.runtime.log).toHaveBeenCalledWith(
216+
expect.stringContaining("sudo loginctl enable-linger pi"),
217+
);
218+
});
219+
220+
it("checks lingering for the same sudo target user as the systemd service", async () => {
221+
mocks.service.isLoaded.mockResolvedValue(true);
222+
mocks.resolveSystemdUserServiceAccount.mockReturnValue("debian");
223+
mocks.readSystemdUserLingerStatus.mockResolvedValue({ user: "debian", linger: "no" });
224+
225+
await runNodeDaemonInstall({ force: true });
226+
227+
expect(mocks.resolveSystemdUserServiceAccount).toHaveBeenCalledWith(process.env);
228+
expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalledWith({
229+
env: process.env,
230+
user: "debian",
231+
});
232+
expect(mocks.runtime.log).toHaveBeenCalledWith(
233+
expect.stringContaining("sudo loginctl enable-linger debian"),
234+
);
235+
});
236+
237+
it("includes the linger warning in JSON warnings after a fresh install", async () => {
238+
mocks.service.isLoaded.mockResolvedValue(true);
239+
await runNodeDaemonInstall({ force: true, json: true });
240+
241+
expect(mocks.runtime.writeJson).toHaveBeenCalledWith(
242+
expect.objectContaining({
243+
warnings: expect.arrayContaining([expect.stringContaining("enable-linger pi")]),
244+
}),
245+
);
246+
});
247+
248+
it("warns about disabled lingering on the already-installed short-circuit path", async () => {
249+
mocks.service.isLoaded.mockResolvedValue(true);
250+
await runNodeDaemonInstall({ force: false });
251+
252+
expect(mocks.readSystemdUserLingerStatus).toHaveBeenCalled();
253+
expect(mocks.runtime.log).toHaveBeenCalledWith(
254+
expect.stringContaining("sudo loginctl enable-linger pi"),
255+
);
256+
});
257+
258+
it("does not warn when systemd lingering is already enabled", async () => {
259+
mocks.service.isLoaded.mockResolvedValue(true);
260+
mocks.readSystemdUserLingerStatus.mockResolvedValue({ user: "pi", linger: "yes" });
261+
await runNodeDaemonInstall({ force: true });
262+
263+
expect(mocks.runtime.log).not.toHaveBeenCalledWith(expect.stringContaining("enable-linger"));
264+
});
265+
266+
it("does not pollute the failure output when service.install throws", async () => {
267+
mocks.service.isLoaded.mockResolvedValue(true);
268+
mocks.service.install.mockRejectedValue(new Error("disk full"));
269+
await runNodeDaemonInstall({ force: true, json: true });
270+
271+
// install() threw before verification, so onVerified never runs and no
272+
// linger warning accompanies the install-failure payload.
273+
const calls = mocks.runtime.writeJson.mock.calls;
274+
const failurePayload = calls
275+
.map(([payload]) => payload as { ok?: boolean; error?: string; warnings?: string[] })
276+
.find((payload) => payload.ok === false);
277+
expect(failurePayload).toBeDefined();
278+
expect(failurePayload?.error).toContain("install failed");
279+
expect(failurePayload?.warnings ?? []).toEqual(
280+
expect.not.arrayContaining([expect.stringContaining("enable-linger")]),
281+
);
282+
});
283+
284+
it("does not warn when service-load verification fails (regression for #107033 review)", async () => {
285+
// install() succeeded but the service is not loaded: the linger diagnostic
286+
// must NOT run, so a failed verification never tells the operator to fix
287+
// lingering for a service that was not successfully installed.
288+
mocks.service.isLoaded.mockResolvedValue(false);
289+
await runNodeDaemonInstall({ force: true, json: true });
290+
291+
expect(mocks.readSystemdUserLingerStatus).not.toHaveBeenCalled();
292+
const calls = mocks.runtime.writeJson.mock.calls;
293+
const failurePayload = calls
294+
.map(([payload]) => payload as { ok?: boolean; error?: string; warnings?: string[] })
295+
.find((payload) => payload.ok === false);
296+
expect(failurePayload).toBeDefined();
297+
expect(failurePayload?.error).toContain("verification failed");
298+
expect(failurePayload?.warnings ?? []).toEqual(
299+
expect.not.arrayContaining([expect.stringContaining("enable-linger")]),
300+
);
301+
});
302+
303+
it("skips the linger check when systemd user services are unavailable", async () => {
304+
mocks.service.isLoaded.mockResolvedValue(true);
305+
mocks.isSystemdUserServiceAvailable.mockResolvedValue(false);
306+
await runNodeDaemonInstall({ force: true });
307+
308+
expect(mocks.readSystemdUserLingerStatus).not.toHaveBeenCalled();
309+
});
182310
});
183311

184312
describe("runNodeDaemonStatus", () => {

‎src/cli/node-cli/daemon.ts‎

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ import {
1616
buildPlatformServiceStartHints,
1717
} from "../../daemon/runtime-hints.js";
1818
import type { GatewayServiceRuntime } from "../../daemon/service-runtime.js";
19+
import {
20+
isSystemdUserServiceAvailable,
21+
readSystemdUserLingerStatus,
22+
resolveSystemdUserServiceAccount,
23+
} from "../../daemon/systemd.js";
1924
import { loadNodeHostConfig } from "../../node-host/config.js";
2025
import { defaultRuntime } from "../../runtime.js";
2126
import { formatCliCommand } from "../command-format.js";
@@ -77,6 +82,32 @@ function buildNodeRuntimeHints(env: NodeJS.ProcessEnv = process.env): string[] {
7782
});
7883
}
7984

85+
/**
86+
* Warns (does NOT auto-enable) when systemd user lingering is disabled.
87+
* The installed user-level node service stops when the last SSH session ends
88+
* unless `loginctl enable-linger <user>` has been run. Read-only: this never
89+
* changes host state, matching the operator-consent policy used elsewhere.
90+
*/
91+
async function warnIfSystemdUserLingerDisabled(warn: (message: string) => void): Promise<void> {
92+
if (process.platform !== "linux") {
93+
return;
94+
}
95+
if (!(await isSystemdUserServiceAvailable())) {
96+
return;
97+
}
98+
const user = resolveSystemdUserServiceAccount(process.env);
99+
if (!user) {
100+
return;
101+
}
102+
const status = await readSystemdUserLingerStatus({ env: process.env, user });
103+
if (!status || status.linger === "yes") {
104+
return;
105+
}
106+
warn(
107+
`Systemd lingering is disabled for ${status.user}. The node service will stop when you log out. Run: sudo loginctl enable-linger ${status.user}`,
108+
);
109+
}
110+
80111
export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
81112
const { json, stdout, warnings, emit, fail } = createDaemonInstallActionContext(opts.json);
82113
if (failIfNixDaemonInstallMode(fail)) {
@@ -105,6 +136,13 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
105136
}
106137

107138
const service = resolveNodeService();
139+
const warn = (message: string) => {
140+
if (json) {
141+
warnings.push(message);
142+
} else {
143+
defaultRuntime.log(message);
144+
}
145+
};
108146
let loaded;
109147
try {
110148
loaded = await service.isLoaded({ env: process.env });
@@ -113,6 +151,7 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
113151
return;
114152
}
115153
if (loaded && !opts.force) {
154+
await warnIfSystemdUserLingerDisabled(warn);
116155
emit({
117156
ok: true,
118157
result: "already-installed",
@@ -147,13 +186,6 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
147186
}
148187
},
149188
});
150-
const warn = (message: string) => {
151-
if (json) {
152-
warnings.push(message);
153-
} else {
154-
defaultRuntime.log(message);
155-
}
156-
};
157189

158190
await installDaemonServiceAndEmit({
159191
serviceNoun: "Node",
@@ -173,6 +205,14 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
173205
description,
174206
});
175207
},
208+
// Run the linger diagnostic only on the verified-success path: placing it
209+
// in `install` (before service-load verification) would let a linger
210+
// warning accompany a failed install or verification, misdirecting the
211+
// operator (see #107033 review). The already-installed short-circuit
212+
// above warns separately.
213+
onVerified: async () => {
214+
await warnIfSystemdUserLingerDisabled(warn);
215+
},
176216
});
177217
}
178218

0 commit comments

Comments
 (0)