The best way to control Claude Code, Codex and more from any computer or phone
fix(server): t3 service install works on Linux hosts without a login session (#29923)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 11, 2026 at 11:57 UTC
546036ec0ceee44c57a554770dbe4a7057060366
2 files changed
+256
-45
apps/server/src/cloud/bootService.test.ts
+164
-6
@@ -3,6 +3,7 @@ import * as NodeChildProcess from "node:child_process";
3
import * as NodeServices from "@effect/platform-node/NodeServices";
4
import { expect, it } from "@effect/vitest";
5
import * as HostProcess from "@t3tools/shared/HostProcess";
6
+import * as Clock from "effect/Clock";
7
import * as ConfigProvider from "effect/ConfigProvider";
8
import * as Duration from "effect/Duration";
9
import * as Effect from "effect/Effect";
@@ -139,12 +140,20 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
140
const control: {
141
failCommand: string | undefined;
142
stateAfterStop?: string;
142
- linger: string;
143
+ /** `undefined` makes `loginctl show-user` fail, as when logind does not know the user. */
144
+ linger: string | undefined;
145
+ managerReachable: boolean;
146
+ /** The user bus is found only through `XDG_RUNTIME_DIR`, as without a login session. */
147
+ busNeedsRuntimeDir: boolean;
148
+ lingerStartsManager: boolean;
149
enabled: boolean;
150
active: boolean;
151
} = {
152
failCommand: undefined,
153
linger: "yes",
154
+ managerReachable: true,
155
+ busNeedsRuntimeDir: false,
156
+ lingerStartsManager: true,
157
enabled: true,
158
active: true,
159
};
@@ -157,10 +166,16 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
166
invocations.push(input);
167
timeouts.set(command, input.timeout);
168
const failed = command === control.failCommand;
160
- if (!failed && command === "loginctl enable-linger --no-ask-password 501")
169
+ if (!failed && command.startsWith("loginctl enable-linger --no-ask-password ")) {
170
control.linger = "yes";
171
+ control.managerReachable ||= control.lingerStartsManager;
172
+ }
173
if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
174
if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
175
+ // The manager loads units only from its own unit directory.
176
+ const unitOutsideManager =
177
+ command === "systemctl --user enable t3code.service" &&
178
+ !(yield* fs.exists(path.join(managerUnitDir, "t3code.service")));
179
// A timed-out stop may still stop the service.
180
if (command === "systemctl --user stop t3code.service") control.active = false;
181
if (
@@ -168,7 +183,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
183
(command === "systemctl --user stop t3code.service" ||
184
command.startsWith("launchctl bootout --wait "))
185
) {
171
- yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
186
+ yield* fs.writeFileString(statePath, control.stateAfterStop);
187
}
188
return {
189
stdout:
@@ -186,7 +201,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
201
: input.args[0] === "--version"
202
? `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
203
: input.command === "loginctl" && input.args[0] === "show-user"
189
- ? `${control.linger}\n`
204
+ ? `${control.linger ?? ""}\n`
205
: input.args[1] === "is-enabled"
206
? control.enabled
207
? "enabled\n"
@@ -195,6 +210,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
210
stderr: "",
211
code: ChildProcessSpawner.ExitCode(
212
failed ||
213
+ unitOutsideManager ||
214
+ ((command === "systemctl --user show-environment" || input.command === "busctl") &&
215
+ (!control.managerReachable ||
216
+ (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) ||
217
+ (input.command === "loginctl" &&
218
+ input.args[0] === "show-user" &&
219
+ control.linger === undefined) ||
220
(input.args[1] === "is-active" && !control.active) ||
221
(input.args[1] === "is-enabled" && !control.enabled)
222
? 1
@@ -206,7 +228,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
228
stdoutInvalidUtf8: false,
229
stderrInvalidUtf8: false,
230
};
209
- }),
231
+ }, Effect.orDie),
232
});
233
const makeService = (
234
environmentPath: string | undefined = installerPath,
@@ -214,6 +236,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
236
serviceBaseDir = baseDir,
237
insideService = false,
238
hostExecPath = "/usr/bin/t3",
239
+ underSudo = false,
240
) =>
241
Effect.gen(function* () {
242
const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
@@ -231,7 +254,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
254
Effect.provide(
255
Layer.mergeAll(
256
Layer.succeed(HostProcess.Platform, platform),
234
- Layer.succeed(HostProcess.UserId, 501),
257
+ Layer.succeed(HostProcess.UserId, underSudo ? 0 : 501),
258
Layer.succeed(HostProcess.ExecutablePath, hostExecPath),
259
Layer.succeed(
260
HttpClient.HttpClient,
@@ -246,6 +269,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
269
? {}
270
: { PATH: environmentPath }),
271
...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
272
+ ...(underSudo ? { SUDO_USER: "julius" } : {}),
273
},
274
}),
275
),
@@ -345,6 +369,140 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
369
}),
370
);
371
372
+ // regression: #29881
373
+ it.effect.each([
374
+ { logind: "has lingering disabled", linger: "no" },
375
+ { logind: "does not know the user", linger: undefined },
376
+ ])(
377
+ "enables lingering to bring up an unreachable user manager when logind $logind",
378
+ ({ linger }) =>
379
+ Effect.gen(function* () {
380
+ const { service, commands, control } = yield* makeHarness();
381
+ control.linger = linger;
382
+ control.managerReachable = false;
383
+
384
+ yield* service.install();
385
+
386
+ expect(commands).toContain("loginctl enable-linger --no-ask-password 501");
387
+ expect((yield* service.status).current).toBe(true);
388
+ }),
389
+ );
390
+
391
+ it.effect("does not reach a running root user manager under sudo", () =>
392
+ Effect.gen(function* () {
393
+ const { makeService, commands, control } = yield* makeHarness();
394
+ control.busNeedsRuntimeDir = true;
395
+ const service = yield* makeService(undefined, "1.2.3", undefined, false, undefined, true);
396
+
397
+ expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
398
+ _tag: "BootServicePrerequisiteError",
399
+ problem: "user-manager-unavailable",
400
+ });
401
+ expect(commands).not.toContain("systemctl --user enable t3code.service");
402
+ }),
403
+ );
404
+
405
+ it.effect("does not enable lingering for root under sudo", () =>
406
+ Effect.gen(function* () {
407
+ const { makeService, commands, control } = yield* makeHarness();
408
+ control.linger = undefined;
409
+ control.managerReachable = false;
410
+ const service = yield* makeService(undefined, "1.2.3", undefined, false, undefined, true);
411
+
412
+ expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
413
+ _tag: "BootServicePrerequisiteError",
414
+ problem: "user-manager-unavailable",
415
+ });
416
+ expect(commands.filter((command) => command.includes("enable-linger"))).toEqual([]);
417
+ }),
418
+ );
419
+
420
+ // regression: #29881
421
+ it.effect("installs into the unit directory of the user manager that lingering starts", () =>
422
+ Effect.gen(function* () {
423
+ const path = yield* Path.Path;
424
+ const fs = yield* FileSystem.FileSystem;
425
+ const shellConfigHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-xdg-config-" });
426
+ const { makeService, home, control } = yield* makeHarness(
427
+ "linux",
428
+ undefined,
429
+ shellConfigHome,
430
+ "",
431
+ );
432
+ control.linger = "no";
433
+ control.managerReachable = false;
434
+ const service = yield* makeService();
435
+
436
+ const plan = yield* service.install();
437
+
438
+ const unitPath = path.join(home, ".config", "systemd", "user", "t3code.service");
439
+ expect(plan.unitPath).toBe(unitPath);
440
+ expect(yield* service.status).toMatchObject({ current: true, unitPath });
441
+ }),
442
+ );
443
+
444
+ // regression: #29881
445
+ it.effect.each([
446
+ { manager: "starts after three probes", upAfterPauses: 3, pauses: 3 },
447
+ { manager: "never starts", upAfterPauses: undefined, pauses: 10 },
448
+ ])(
449
+ "waits a bounded time for the user manager lingering starts when it $manager",
450
+ ({ upAfterPauses, pauses }) =>
451
+ Effect.gen(function* () {
452
+ const { service, fs, control } = yield* makeHarness();
453
+ const { unitPath } = yield* service.status;
454
+ control.linger = "no";
455
+ control.managerReachable = false;
456
+ control.lingerStartsManager = false;
457
+ const clock = yield* Clock.Clock;
458
+ const waited: number[] = [];
459
+
460
+ const result = yield* service.install().pipe(
461
+ Effect.provideService(Clock.Clock, {
462
+ ...clock,
463
+ sleep: (duration) =>
464
+ Effect.sync(() => {
465
+ if (waited.push(Duration.toMillis(duration)) === upAfterPauses) {
466
+ control.managerReachable = true;
467
+ }
468
+ }),
469
+ }),
470
+ Effect.result,
471
+ );
472
+
473
+ expect(waited).toEqual(Array.from({ length: pauses }, () => 500));
474
+ if (upAfterPauses === undefined) {
475
+ expect(result).toMatchObject({
476
+ failure: { _tag: "BootServicePrerequisiteError", problem: "user-manager-unavailable" },
477
+ });
478
+ expect(yield* fs.exists(unitPath)).toBe(false);
479
+ } else {
480
+ expect(result._tag).toBe("Success");
481
+ expect((yield* service.status).current).toBe(true);
482
+ }
483
+ }),
484
+ );
485
+
486
+ // regression: #29881
487
+ it.effect("points systemd user commands at the user's runtime directory when none is set", () =>
488
+ Effect.gen(function* () {
489
+ const { service, invocations, makeService } = yield* makeHarness();
490
+ yield* service.install();
491
+ const inside = yield* makeService(undefined, "1.2.4", undefined, true);
492
+ yield* inside.install({ allowDowngrade: true });
493
+
494
+ const systemdCalls = invocations.filter(({ command }) =>
495
+ ["systemctl", "busctl", "systemd-run", "loginctl"].includes(command),
496
+ );
497
+ expect(new Set(systemdCalls.map(({ command }) => command)).size).toBe(4);
498
+ expect(
499
+ systemdCalls
500
+ .filter(({ env }) => env?.XDG_RUNTIME_DIR !== "/run/user/501")
501
+ .map(({ command, args }) => `${command} ${args.join(" ")}`),
502
+ ).toEqual([]);
503
+ }),
504
+ );
505
+
506
it.effect.each([
507
{ command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
508
{ command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
apps/server/src/cloud/bootService.ts
+92
-39
@@ -9,6 +9,7 @@ import * as FileSystem from "effect/FileSystem";
9
import * as Layer from "effect/Layer";
10
import * as Option from "effect/Option";
11
import * as Path from "effect/Path";
12
+import * as Schedule from "effect/Schedule";
13
import { CliError } from "effect/cli";
14
import { HttpClient } from "effect/http";
15
import * as Schema from "effect/Schema";
@@ -374,9 +375,7 @@ const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
375
376
// The manager may not share the installer's environment; JSON preserves spaces in its paths.
377
const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
377
- function* () {
378
- const runner = yield* ProcessRunner.ProcessRunner;
379
- const path = yield* Path.Path;
378
+ function* (runner: ProcessRunner.ProcessRunner["Service"], path: Path.Path) {
379
const result = yield* runner.run({
380
command: "busctl",
381
args: [
@@ -589,12 +588,29 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
588
const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
589
const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
590
const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
591
+ const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault(""));
592
+ // Root under sudo must not reach or start a separate root service.
593
+ const rootUnderSudo =
594
+ uid === 0 && (yield* Config.String("SUDO_USER").pipe(Config.withDefault(""))) !== "";
595
const runningInsideService =
596
(yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
597
BOOT_SERVICE_UNIT_FILE;
598
const fs = yield* FileSystem.FileSystem;
599
const path = yield* Path.Path;
597
- const runner = yield* ProcessRunner.ProcessRunner;
600
+ const processRunner = yield* ProcessRunner.ProcessRunner;
601
+ // Without a login session nothing sets this, so `--user` commands cannot find the user bus.
602
+ // The directory only appears once lingering starts the manager, so it need not exist yet.
603
+ const userManagerEnv =
604
+ platform === "linux" && xdgRuntimeDir === "" && uid !== undefined && !rootUnderSudo
605
+ ? { XDG_RUNTIME_DIR: `/run/user/${uid}` }
606
+ : undefined;
607
+ const runner: ProcessRunner.ProcessRunner["Service"] =
608
+ userManagerEnv === undefined
609
+ ? processRunner
610
+ : {
611
+ run: (request) =>
612
+ processRunner.run({ ...request, env: { ...userManagerEnv, ...request.env } }),
613
+ };
614
const host = input.host ?? { execPath: hostExecPath };
615
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion, platform);
616
const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir);
@@ -625,18 +641,29 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
641
),
642
).join(":");
643
628
- const systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory() : undefined;
629
- const detectedManager = selectBootServiceManager({
630
- platform,
631
- homeDir,
632
- xdgConfigHome,
633
- systemdUnitDir,
634
- uid,
635
- path,
636
- environmentPath,
637
- });
638
- const unitPath = detectedManager?.unitPath ?? "";
644
const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
645
+ const resolveTarget = (systemdUnitDir: string | undefined) => {
646
+ const manager = selectBootServiceManager({
647
+ platform,
648
+ homeDir,
649
+ xdgConfigHome,
650
+ systemdUnitDir,
651
+ uid,
652
+ path,
653
+ environmentPath,
654
+ });
655
+ const unitPath = manager?.unitPath ?? "";
656
+ const plan: BootServicePlan = {
657
+ program: [runtimePaths.entryPath, "__service-launcher"],
658
+ baseDir: input.baseDir,
659
+ logPath,
660
+ unitPath,
661
+ };
662
+ return { manager, unitPath, plan };
663
+ };
664
+ let systemdUnitDir =
665
+ platform === "linux" ? yield* readSystemdUnitDirectory(runner, path) : undefined;
666
+ let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir);
667
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
668
const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
669
const otherBaseDirOf = (unit: string) => {
@@ -665,13 +692,6 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
692
);
693
}),
694
).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
668
- const plan: BootServicePlan = {
669
- program: [runtimePaths.entryPath, "__service-launcher"],
670
- baseDir: input.baseDir,
671
- logPath,
672
- unitPath,
673
- };
674
-
695
const requireManager = Effect.suspend(() =>
696
detectedManager === undefined
697
? new BootServiceUnsupportedError({ platform })
@@ -767,19 +787,37 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
787
788
const requireSystemdPrerequisites = Effect.gen(function* () {
789
const problems = yield* readSystemdProblems(false);
770
- const unavailable = problems.find((problem) => problem !== "linger-disabled");
771
- if (unavailable) return yield* new BootServicePrerequisiteError({ problem: unavailable });
772
- if (!problems.includes("linger-disabled")) return;
790
+ const firstProblem = problems[0];
791
+ if (firstProblem === undefined) return;
792
+ // Logind reports a user without a session, whose manager is not running yet, as linger-unavailable.
793
+ const withoutSession =
794
+ problems.includes("linger-unavailable") && problems.includes("user-manager-unavailable");
795
+ const lingerDisabled = problems.includes("linger-disabled");
796
+ if (rootUnderSudo || (!lingerDisabled && !withoutSession)) {
797
+ return yield* new BootServicePrerequisiteError({ problem: firstProblem });
798
+ }
799
yield* runStep("enabling lingering for this user", "loginctl", [
800
"enable-linger",
801
"--no-ask-password",
802
...(uid === undefined ? [] : [String(uid)]),
803
]).pipe(
804
Effect.mapError(
779
- (cause) => new BootServicePrerequisiteError({ problem: "linger-disabled", cause }),
805
+ // Without a session this also fails on hosts that do not run systemd at all.
806
+ (cause) =>
807
+ new BootServicePrerequisiteError({
808
+ problem: lingerDisabled ? "linger-disabled" : firstProblem,
809
+ cause,
810
+ }),
811
),
812
);
782
- const remaining = yield* readSystemdProblems(false);
813
+ // Lingering starts the user manager asynchronously.
814
+ const remaining = yield* readSystemdProblems(false).pipe(
815
+ Effect.repeat({
816
+ schedule: Schedule.spaced("500 millis"),
817
+ times: 10,
818
+ while: (current) => current.includes("user-manager-unavailable"),
819
+ }),
820
+ );
821
if (remaining[0]) return yield* new BootServicePrerequisiteError({ problem: remaining[0] });
822
});
823
@@ -797,22 +835,36 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
835
readonly allowDowngrade?: boolean;
836
readonly start?: boolean;
837
}) {
800
- const manager = yield* requireManager;
838
+ let manager = yield* requireManager;
839
// The unit is per user. Rewriting one that serves another home moves the
840
// service onto this home's data, which looks like every thread vanished.
803
- const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
804
- const installedBaseDir = Option.isSome(existingUnit)
805
- ? otherBaseDirOf(existingUnit.value)
806
- : undefined;
807
- if (installedBaseDir !== undefined) {
808
- return yield* new BootServiceOtherBaseDirError({ installedBaseDir, baseDir: input.baseDir });
809
- }
841
+ const refuseOtherBaseDir = Effect.gen(function* () {
842
+ const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
843
+ const installedBaseDir = Option.isSome(existingUnit)
844
+ ? otherBaseDirOf(existingUnit.value)
845
+ : undefined;
846
+ if (installedBaseDir !== undefined) {
847
+ return yield* new BootServiceOtherBaseDirError({
848
+ installedBaseDir,
849
+ baseDir: input.baseDir,
850
+ });
851
+ }
852
+ });
853
+ yield* refuseOtherBaseDir;
854
yield* fs
855
.makeDirectory(input.logsDir, { recursive: true })
856
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
857
858
if (manager.kind === "systemd") {
859
yield* requireSystemdPrerequisites.pipe(Effect.tapError(logFailure));
860
+ // Without a session the manager was unreachable at construction, and the one lingering
861
+ // started may use another config root than this shell's XDG_CONFIG_HOME.
862
+ if (systemdUnitDir === undefined) {
863
+ systemdUnitDir = yield* readSystemdUnitDirectory(runner, path);
864
+ ({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir));
865
+ manager = yield* requireManager;
866
+ yield* refuseOtherBaseDir;
867
+ }
868
}
869
870
yield* ensurePinnedRuntimeInstalled({
@@ -1081,7 +1133,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1133
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
1134
1135
const status: BootService["Service"]["status"] = Effect.gen(function* () {
1084
- if (detectedManager === undefined) {
1136
+ const manager = detectedManager;
1137
+ if (manager === undefined) {
1138
return { supported: false, installed: false, current: false, unitPath, logPath };
1139
}
1140
if (!(yield* fs.exists(unitPath))) {
@@ -1100,11 +1153,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1153
const installedBaseDir = bootServiceBaseDirOf(unit);
1154
const otherBaseDir = otherBaseDirOf(unit);
1155
const normalizeUnit = (contents: string) =>
1103
- detectedManager.kind === "launchd"
1156
+ manager.kind === "launchd"
1157
? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1158
: contents;
1159
const problems: BootServiceProblem[] =
1107
- detectedManager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1160
+ manager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1161
if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1162
return {
1163
supported: true,
@@ -1115,7 +1168,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1168
problems,
1169
current:
1170
problems.length === 0 &&
1118
- normalizeUnit(unit) === normalizeUnit(detectedManager.render(plan)) &&
1171
+ normalizeUnit(unit) === normalizeUnit(manager.render(plan)) &&
1172
runtimeEntryExists &&
1173
Option.isSome(runtimeSentinel) &&
1174
runtimeSentinel.value.trim() === input.cliVersion &&