@devries-cameron20 / t3code-1 / commits / 99224f098d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): launcher repoints the unit the systemd manager loads (#35966)

Julius Marminge committed Nov 12, 2026 at 20:39 UTC 99224f098d5d4d223ab1d04f02935288fe2651cc
4 files changed +124 -21
apps/server/src/cloud/bootService.ts
+6 -13
@@ -45,6 +45,7 @@ import {
45 parseServiceState,
46 serviceStateActiveVersion,
47 serviceStateHasPendingUpdate,
48 + systemdUnitDirectoryOf,
49 type ServiceState,
50 } from "./serviceProtocol.ts";
51
@@ -550,7 +551,7 @@ const decodeSystemdUnitPaths = Schema.decodeUnknownEffect(
551
552 // The manager may not share the installer's environment; JSON preserves spaces in its paths.
553 const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit_directory")(
553 - function* (runner: ProcessRunner.ProcessRunner["Service"], path: Path.Path) {
554 + function* (runner: ProcessRunner.ProcessRunner["Service"]) {
555 const result = yield* runner.run({
556 command: "busctl",
557 args: [
@@ -566,14 +567,7 @@ const readSystemdUnitDirectory = Effect.fn("cloud.boot_service.read_systemd_unit
567 });
568 if (result.code !== 0) return undefined;
569 const { data } = yield* decodeSystemdUnitPaths(result.stdout);
569 - // The persistent control directory identifies the manager's config root despite UnitPath overrides.
570 - const controlDirectory = data.find(
571 - (directory) =>
572 - path.isAbsolute(directory) &&
573 - directory.endsWith("/systemd/user.control") &&
574 - data.includes(directory.slice(0, -".control".length)),
575 - );
576 - return controlDirectory?.slice(0, -".control".length);
570 + return systemdUnitDirectoryOf(data);
571 },
572 Effect.orElseSucceed(() => undefined),
573 );
@@ -591,7 +585,7 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun
585 }
586 if (platform !== "linux") return undefined;
587 const unitDir =
594 - (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ??
588 + (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner)) ??
589 defaultSystemdUnitDir(path, homeDir, (yield* HostProcess.Environment).XDG_CONFIG_HOME ?? "");
590 return path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
591 });
@@ -972,8 +966,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
966 };
967 return { manager, unitPath, plan };
968 };
975 - let systemdUnitDir =
976 - platform === "linux" ? yield* readSystemdUnitDirectory(runner, path) : undefined;
969 + let systemdUnitDir = platform === "linux" ? yield* readSystemdUnitDirectory(runner) : undefined;
970 let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir);
971 const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
972 const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE);
@@ -1205,7 +1198,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1198 // Without a session the manager was unreachable at construction, and the one lingering
1199 // started may use another config root than this shell's XDG_CONFIG_HOME.
1200 if (systemdUnitDir === undefined) {
1208 - systemdUnitDir = yield* readSystemdUnitDirectory(runner, path);
1201 + systemdUnitDir = yield* readSystemdUnitDirectory(runner);
1202 ({ manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir));
1203 manager = yield* requireManager;
1204 yield* refuseOtherBaseDir;
apps/server/src/cloud/serviceProtocol.ts
+14
@@ -63,6 +63,20 @@ export function serviceUnitBaseDirOf(contents: string): string | undefined {
63 return task === undefined ? undefined : unquoteWindowsArgument(task);
64 }
65
66 +/**
67 + * The user unit directory a systemd manager reads, from its UnitPath property. The persistent
68 + * control directory identifies the manager's config root despite UnitPath overrides.
69 + */
70 +export function systemdUnitDirectoryOf(unitPath: ReadonlyArray<string>): string | undefined {
71 + const controlDirectory = unitPath.find(
72 + (directory) =>
73 + directory.startsWith("/") &&
74 + directory.endsWith("/systemd/user.control") &&
75 + unitPath.includes(directory.slice(0, -".control".length)),
76 + );
77 + return controlDirectory?.slice(0, -".control".length);
78 +}
79 +
80 /** The file systemd or launchd appends the service's output to. */
81 export function serviceUnitLogPathOf(contents: string): string | undefined {
82 const systemd = /^StandardOutput=append:(.*)$/m.exec(contents)?.[1];
apps/server/src/serviceLauncher.test.ts
+64
@@ -318,6 +318,70 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
318 }),
319 );
320
321 + it.effect(
322 + "repoints the systemd unit the manager loads when environment.d moves XDG_CONFIG_HOME",
323 + () =>
324 + Effect.gen(function* () {
325 + const fs = yield* FileSystem.FileSystem;
326 + const path = yield* Path.Path;
327 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-xdg-" });
328 + const home = path.join(root, "home");
329 + const managerUnitDir = path.join(home, ".config", "systemd", "user");
330 + const unitPath = path.join(managerUnitDir, "t3code.service");
331 + const render = (version: string) =>
332 + renderBootServiceUnit({ ...unitPlan(root, version), unitPath });
333 + yield* fs.makeDirectory(managerUnitDir, { recursive: true });
334 + yield* fs.writeFileString(unitPath, render("1.0.0"));
335 + // Fake manager: busctl reports the unit search path, systemctl reloads.
336 + const bin = path.join(root, "bin");
337 + yield* fs.makeDirectory(bin, { recursive: true });
338 + const unitPathJson = JSON.stringify({
339 + type: "as",
340 + data: [`${managerUnitDir}.control`, managerUnitDir, "/usr/lib/systemd/user"],
341 + });
342 + yield* fs.writeFileString(
343 + path.join(bin, "busctl"),
344 + `#!/bin/sh\nprintf '%s\\n' '${unitPathJson}'\n`,
345 + );
346 + yield* fs.writeFileString(
347 + path.join(bin, "systemctl"),
348 + `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`,
349 + );
350 + yield* fs.chmod(path.join(bin, "busctl"), 0o755);
351 + yield* fs.chmod(path.join(bin, "systemctl"), 0o755);
352 + yield* writeFakeRuntime(
353 + fs,
354 + path,
355 + path.join(root, "runtime", "versions", "1.1.0"),
356 + "process.exit(0);\n",
357 + );
358 + yield* Effect.promise(() =>
359 + writeServiceState(path.join(root, "runtime", "service-state.json"), {
360 + protocol: SERVICE_LAUNCHER_PROTOCOL,
361 + activeVersion: "1.1.0",
362 + update: {
363 + id: "update-1",
364 + fromVersion: "1.0.0",
365 + targetVersion: "1.1.0",
366 + status: "committed",
367 + },
368 + }),
369 + );
370 + vi.stubEnv("PATH", bin);
371 + vi.stubEnv("HOME", home);
372 + // environment.d changes what services inherit, not where the manager reads units.
373 + vi.stubEnv("XDG_CONFIG_HOME", path.join(home, "service-config"));
374 + vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.service");
375 +
376 + yield* Effect.promise(() =>
377 + expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
378 + );
379 +
380 + assert.equal(yield* fs.readFileString(unitPath), render("1.1.0"));
381 + assert.equal(yield* fs.readFileString(path.join(root, "reloads")), "reload\n");
382 + }),
383 + );
384 +
385 it.effect("keeps the service manager's append log bounded when it starts", () =>
386 Effect.gen(function* () {
387 const fs = yield* FileSystem.FileSystem;
apps/server/src/serviceLauncher.ts
+40 -8
@@ -35,6 +35,7 @@ import {
35 SERVICE_RESTART_PENDING_FILE,
36 SERVICE_STOP_MARKER_FILE,
37 SERVICE_UNIT_ENV,
38 + systemdUnitDirectoryOf,
39 } from "./cloud/serviceProtocol.ts";
40 import {
41 legacyOwnerStartedBeforeRecord,
@@ -123,7 +124,34 @@ export async function registerServiceTask(
124 }
125 }
126
126 -function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined {
127 +// The manager's environment can differ from the one it gives services (environment.d).
128 +async function readSystemdUnitDirectory(): Promise<string | undefined> {
129 + try {
130 + const { stdout } = await NodeUtil.promisify(NodeChildProcess.execFile)(
131 + "busctl",
132 + [
133 + "--user",
134 + "--json=short",
135 + "get-property",
136 + "org.freedesktop.systemd1",
137 + "/org/freedesktop/systemd1",
138 + "org.freedesktop.systemd1.Manager",
139 + "UnitPath",
140 + ],
141 + { timeout: 5_000 },
142 + );
143 + const { data } = JSON.parse(stdout) as { readonly data?: unknown };
144 + return Array.isArray(data) && data.every((entry) => typeof entry === "string")
145 + ? systemdUnitDirectoryOf(data)
146 + : undefined;
147 + } catch {
148 + return undefined;
149 + }
150 +}
151 +
152 +async function serviceUnitFromEnvironment(
153 + env: NodeJS.ProcessEnv = process.env,
154 +): Promise<ServiceUnit | undefined> {
155 const unitName = env[SERVICE_UNIT_ENV]?.trim();
156 if (!unitName) return undefined;
157 if (unitName.endsWith(".xml")) {
@@ -141,14 +169,18 @@ function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): Servi
169 reload: () => Promise.resolve(),
170 };
171 }
144 - // The manager's own environment, which decides where it reads user units.
172 const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
146 - const configHome =
147 - xdgConfigHome && NodePath.isAbsolute(xdgConfigHome)
148 - ? xdgConfigHome
149 - : NodePath.join(home, ".config");
173 + const unitDir =
174 + (await readSystemdUnitDirectory()) ??
175 + NodePath.join(
176 + xdgConfigHome && NodePath.isAbsolute(xdgConfigHome)
177 + ? xdgConfigHome
178 + : NodePath.join(home, ".config"),
179 + "systemd",
180 + "user",
181 + );
182 return {
151 - path: NodePath.join(configHome, "systemd", "user", unitName),
183 + path: NodePath.join(unitDir, unitName),
184 reload: () =>
185 new Promise((resolve, reject) => {
186 NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], {
@@ -1403,7 +1435,7 @@ export async function main(options: LauncherOptions = {}): Promise<void> {
1435 throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`);
1436 }
1437 }
1406 - const serviceUnit = serviceUnitFromEnvironment(managerEnvironment);
1438 + const serviceUnit = await serviceUnitFromEnvironment(managerEnvironment);
1439 const logPath = await serviceLogPath(options, serviceUnit);
1440 if (logPath !== undefined) {
1441 await boundServiceLog(logPath);