Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { expect, it } from "@effect/vitest";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import { CliError } from "effect/cli";
14import { HttpClient } from "effect/http";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import { vi } from "vite-plus/test";
17
18import * as ProcessRunner from "../processRunner.ts";
19import * as BootService from "./bootService.ts";
20import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
21import {
22 parseServiceState,
23 SERVICE_ENV_FILE,
24 SERVICE_LAUNCHER_PROTOCOL,
25 SERVICE_RESTART_PENDING_FILE,
26 serviceStateHasPendingUpdate,
27} from "./serviceProtocol.ts";
28
29const leaseObserver = vi.hoisted(() => ({ contended: (_destination: string) => {} }));
30vi.mock("node:fs", async (importOriginal) => {
31 const actual = await importOriginal<typeof import("node:fs")>();
32 return {
33 ...actual,
34 renameSync: (...args: Parameters<typeof actual.renameSync>) => {
35 try {
36 return actual.renameSync(...args);
37 } catch (error) {
38 if (["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) {
39 leaseObserver.contended(String(args[1]));
40 }
41 throw error;
42 }
43 },
44 };
45});
46
47it("reads the served T3 home back out of a rendered unit or plist", () => {
48 const plan = (baseDir: string) => ({
49 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
50 baseDir,
51 logPath: `${baseDir}/userdata/logs/boot-service.log`,
52 unitPath: "/home/theo/.config/systemd/user/t3code.service",
53 });
54
55 expect(
56 BootService.bootServiceBaseDirOf(BootService.renderBootServiceUnit(plan("/home/theo/.t3"))),
57 ).toBe("/home/theo/.t3");
58 expect(
59 BootService.bootServiceBaseDirOf(
60 BootService.renderBootServiceUnit(plan("/home/theo/T3 Data/100%")),
61 ),
62 ).toBe("/home/theo/T3 Data/100%");
63 expect(
64 BootService.bootServiceBaseDirOf(
65 BootService.renderBootServicePlist(plan("/Users/theo/a&b"), {
66 homeDir: "/Users/theo",
67 environmentPath: "/usr/bin",
68 }),
69 ),
70 ).toBe("/Users/theo/a&b");
71 expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
72});
73
74it("protects the server unit from agents under CPU and memory pressure", () => {
75 const unit = BootService.renderBootServiceUnit({
76 program: ["/home/theo/.t3/runtime/versions/1.2.3/t3", "__service-launcher"],
77 baseDir: "/home/theo/.t3",
78 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
79 unitPath: "/home/theo/.config/systemd/user/t3code.service",
80 });
81 const service = unit.slice(unit.indexOf("[Service]"), unit.indexOf("[Install]"));
82 for (const line of [
83 "CPUWeight=1000",
84 "IOWeight=1000",
85 "MemoryLow=1536M",
86 "OOMScoreAdjust=100",
87 "OOMPolicy=continue",
88 ]) {
89 expect(service.split("\n")).toContain(line);
90 }
91});
92
93it.each([
94 ["a unit", '/home/theo/T3 "Data"/100%\\x', BootService.renderBootServiceUnit],
95 [
96 "a plist",
97 "/Users/theo/a&b <c>",
98 (plan: BootService.BootServicePlan) =>
99 BootService.renderBootServicePlist(plan, { homeDir: "/Users/theo", environmentPath: "" }),
100 ],
101] as const)("reads the launcher back out of %s", (_, baseDir, render) => {
102 const program = `${baseDir}/runtime/versions/1.2.3/t3`;
103 expect(
104 BootService.bootServiceProgramOf(
105 render({ program: [program, "__service-launcher"], baseDir, logPath: "/log", unitPath: "" }),
106 ),
107 ).toBe(program);
108});
109
110const macInstallerPath =
111 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
112
113const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
114 platform: NodeJS.Platform = "linux",
115 installerPath = macInstallerPath,
116 xdgConfigHome?: string,
117 managerXdgConfigHome = xdgConfigHome,
118) {
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
122 const managerUnitDir = path.join(
123 managerXdgConfigHome !== undefined && path.isAbsolute(managerXdgConfigHome)
124 ? managerXdgConfigHome
125 : path.join(home, ".config"),
126 "systemd",
127 "user",
128 );
129 const baseDir = path.join(home, ".t3");
130 const statePath = path.join(baseDir, "runtime", "service-state.json");
131 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3", platform);
132 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
133 yield* fs.writeFileString(runtime.entryPath, "#!/bin/sh\n");
134 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
135
136 const commands: string[] = [];
137 const invocations: ProcessRunner.ProcessRunInput[] = [];
138 const timeouts = new Map<string, unknown>();
139 const control: {
140 failCommand: string | undefined;
141 stateAfterStop?: string;
142 linger: string;
143 enabled: boolean;
144 active: boolean;
145 } = {
146 failCommand: undefined,
147 linger: "yes",
148 enabled: true,
149 active: true,
150 };
151 const runner = ProcessRunner.ProcessRunner.of({
152 run: Effect.fn("test.run_boot_service_command")(function* (
153 input: ProcessRunner.ProcessRunInput,
154 ) {
155 const command = `${input.command} ${input.args.join(" ")}`;
156 commands.push(command);
157 invocations.push(input);
158 timeouts.set(command, input.timeout);
159 const failed = command === control.failCommand;
160 if (!failed && command === "loginctl enable-linger --no-ask-password 501")
161 control.linger = "yes";
162 if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
163 if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
164 // A timed-out stop may still stop the service.
165 if (command === "systemctl --user stop t3code.service") control.active = false;
166 if (
167 control.stateAfterStop !== undefined &&
168 (command === "systemctl --user stop t3code.service" ||
169 command.startsWith("launchctl bootout --wait "))
170 ) {
171 yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
172 }
173 return {
174 stdout:
175 input.command === "busctl"
176 ? JSON.stringify({
177 type: "as",
178 data: [
179 "/usr/lib/systemd/user",
180 `${managerUnitDir}.control`,
181 "/run/user/501/systemd/transient",
182 managerUnitDir,
183 "/etc/systemd/user",
184 ],
185 })
186 : input.args[0] === "--version"
187 ? `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
188 : input.command === "loginctl" && input.args[0] === "show-user"
189 ? `${control.linger}\n`
190 : input.args[1] === "is-enabled"
191 ? control.enabled
192 ? "enabled\n"
193 : "disabled\n"
194 : "",
195 stderr: "",
196 code: ChildProcessSpawner.ExitCode(
197 failed ||
198 (input.args[1] === "is-active" && !control.active) ||
199 (input.args[1] === "is-enabled" && !control.enabled)
200 ? 1
201 : 0,
202 ),
203 timedOut: false,
204 stdoutTruncated: false,
205 stderrTruncated: false,
206 stdoutInvalidUtf8: false,
207 stderrInvalidUtf8: false,
208 };
209 }),
210 });
211 const makeService = (
212 environmentPath: string | undefined = installerPath,
213 cliVersion = "1.2.3",
214 serviceBaseDir = baseDir,
215 insideService = false,
216 hostExecPath = "/usr/bin/t3",
217 ) =>
218 Effect.gen(function* () {
219 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
220 yield* fs.makeDirectory(path.dirname(paths.entryPath), { recursive: true });
221 yield* fs.writeFileString(paths.entryPath, "#!/bin/sh\n");
222 yield* fs.writeFileString(paths.sentinelPath, `${cliVersion}\n`);
223 return yield* BootService.make({
224 baseDir: serviceBaseDir,
225 logsDir: path.join(serviceBaseDir, "userdata", "logs"),
226 cliVersion,
227 host: { execPath: hostExecPath },
228 });
229 }).pipe(
230 Effect.provideService(ProcessRunner.ProcessRunner, runner),
231 Effect.provide(
232 Layer.mergeAll(
233 Layer.succeed(HostProcess.Platform, platform),
234 Layer.succeed(HostProcess.UserId, 501),
235 Layer.succeed(HostProcess.ExecutablePath, hostExecPath),
236 Layer.succeed(
237 HttpClient.HttpClient,
238 HttpClient.make(() => Effect.die("no release download expected")),
239 ),
240 ConfigProvider.layer(
241 ConfigProvider.fromEnv({
242 env: {
243 HOME: home,
244 ...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }),
245 ...(environmentPath === undefined || environmentPath === ""
246 ? {}
247 : { PATH: environmentPath }),
248 ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
249 },
250 }),
251 ),
252 ),
253 ),
254 );
255 const service = yield* makeService();
256 return {
257 service,
258 makeService,
259 fs,
260 home,
261 baseDir,
262 statePath,
263 commands,
264 invocations,
265 timeouts,
266 control,
267 runtime,
268 };
269});
270
271it.layer(NodeServices.layer)("boot service install", (it) => {
272 it.effect(
273 "fails before installing files or validating a runtime when lingering needs an administrator",
274 () =>
275 Effect.gen(function* () {
276 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
277 const before = yield* service.status;
278 control.linger = "no";
279 control.failCommand = "loginctl enable-linger --no-ask-password 501";
280 yield* fs.remove(runtime.sentinelPath);
281
282 const error = yield* service.install().pipe(Effect.flip);
283
284 expect(error).toMatchObject({
285 _tag: "BootServicePrerequisiteError",
286 problem: "linger-disabled",
287 });
288 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
289 expect(error.message).toContain("last login session ends");
290 expect(yield* fs.exists(before.unitPath)).toBe(false);
291 expect(yield* fs.exists(statePath)).toBe(false);
292 expect(commands.some((command) => command.includes("--version"))).toBe(false);
293 expect(
294 commands.some(
295 (command) => command.includes("daemon-reload") || command.includes("restart"),
296 ),
297 ).toBe(false);
298 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
299 }),
300 );
301
302 it.effect(
303 "detects a partial install and preserves the running service when repair lacks permission",
304 () =>
305 Effect.gen(function* () {
306 const { service, fs, statePath, commands, control } = yield* makeHarness();
307 const plan = yield* service.install();
308 const before = yield* fs.readFileString(statePath);
309 const unit = yield* fs.readFileString(plan.unitPath);
310 control.linger = "no";
311 control.failCommand = "loginctl enable-linger --no-ask-password 501";
312
313 expect(yield* service.status).toMatchObject({
314 current: false,
315 problems: ["linger-disabled"],
316 });
317 commands.length = 0;
318 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
319 "BootServicePrerequisiteError",
320 );
321 expect(yield* fs.readFileString(statePath)).toBe(before);
322 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
323 expect(commands).not.toContain("systemctl --user stop t3code.service");
324 }),
325 );
326
327 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
328 Effect.gen(function* () {
329 const { service, commands, control } = yield* makeHarness();
330 control.linger = "no";
331 yield* service.install();
332 expect(control.linger).toBe("yes");
333 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
334 commands.indexOf("systemctl --user daemon-reload"),
335 );
336
337 control.enabled = false;
338 control.active = false;
339 expect(yield* service.status).toMatchObject({
340 current: false,
341 problems: ["service-disabled", "service-stopped"],
342 });
343 yield* service.install();
344 expect((yield* service.status).current).toBe(true);
345 }),
346 );
347
348 it.effect.each([
349 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
350 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
351 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
352 Effect.gen(function* () {
353 const { service, fs, statePath, control } = yield* makeHarness();
354 control.failCommand = command;
355 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
356 _tag: "BootServicePrerequisiteError",
357 problem,
358 });
359 expect(yield* fs.exists(statePath)).toBe(false);
360 }),
361 );
362
363 it.effect.each([
364 "unset",
365 "empty",
366 "relative",
367 "relocated",
368 "shell-only",
369 "manager-only",
370 "manager-unavailable",
371 ] as const)("installs, discovers, restarts, and uninstalls with $XDG_CONFIG_HOME %s", (setting) =>
372 Effect.gen(function* () {
373 const path = yield* Path.Path;
374 const fs = yield* FileSystem.FileSystem;
375 const configRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-xdg-config-" });
376 const xdgConfigHome = {
377 unset: undefined,
378 empty: "",
379 relative: "relative-config",
380 relocated: path.join(configRoot, "config root"),
381 "shell-only": path.join(configRoot, "config root"),
382 "manager-only": undefined,
383 "manager-unavailable": path.join(configRoot, "config root"),
384 }[setting];
385 const managerXdgConfigHome =
386 setting === "shell-only"
387 ? ""
388 : setting === "manager-only"
389 ? path.join(configRoot, "config root")
390 : undefined;
391 const { service, makeService, home, statePath, timeouts, runtime, control } =
392 yield* makeHarness("linux", undefined, xdgConfigHome, managerXdgConfigHome);
393 const unitPath = path.join(
394 setting === "relocated" || setting === "manager-only" || setting === "manager-unavailable"
395 ? path.join(configRoot, "config root")
396 : path.join(home, ".config"),
397 "systemd",
398 "user",
399 "t3code.service",
400 );
401 expect(yield* service.status).toMatchObject({ installed: false, unitPath });
402 const plan = yield* service.install();
403 expect(plan.unitPath).toBe(unitPath);
404 if (setting === "manager-unavailable") {
405 control.failCommand =
406 "busctl --user --json=short get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager UnitPath";
407 }
408 const discoveredService = yield* makeService();
409
410 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
411 protocol: SERVICE_LAUNCHER_PROTOCOL,
412 activeVersion: "1.2.3",
413 });
414 expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
415 expect(yield* fs.readFileString(plan.unitPath)).toContain(
416 `ExecStart=${runtime.entryPath} __service-launcher`,
417 );
418 expect(yield* service.status).toMatchObject({
419 current: true,
420 installedVersion: "1.2.3",
421 });
422 expect(yield* discoveredService.status).toMatchObject({
423 installed: true,
424 current: true,
425 unitPath,
426 });
427 expect(yield* discoveredService.restart).toBe("restarted");
428 const pendingState = JSON.stringify({
429 protocol: SERVICE_LAUNCHER_PROTOCOL,
430 activeVersion: "1.2.3",
431 update: {
432 id: "u",
433 fromVersion: "1.2.3",
434 targetVersion: "1.2.4",
435 dbPath: "/tmp/state.sqlite",
436 status: "pending",
437 },
438 });
439 yield* fs.writeFileString(statePath, pendingState);
440 expect((yield* service.status).current).toBe(false);
441 expect(yield* discoveredService.uninstall).toBe(true);
442 expect(yield* fs.exists(unitPath)).toBe(false);
443 expect((yield* discoveredService.status).installed).toBe(false);
444 // systemd can take 90s to stop, exceeding the runner's 60s default.
445 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
446 Duration.seconds(120),
447 );
448 }),
449 );
450
451 it.effect.each(["linux", "darwin"] as const)(
452 "reports the installed version across launcher protocols on %s",
453 (platform) =>
454 Effect.gen(function* () {
455 const { service, fs, statePath } = yield* makeHarness(platform);
456 yield* service.install();
457
458 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
459 yield* fs.writeFileString(
460 statePath,
461 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
462 );
463 expect(yield* service.status).toMatchObject({
464 current: false,
465 installedVersion: "1.2.4-nightly.1",
466 });
467 yield* service.install({ allowDowngrade: true });
468 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
469 protocol: SERVICE_LAUNCHER_PROTOCOL,
470 activeVersion: "1.2.3",
471 });
472 }
473 }),
474 );
475
476 // regression: #5302 prevent accidental service downgrades
477 it.effect("reports an unknown version for invalid service state", () =>
478 Effect.gen(function* () {
479 const { service, fs, statePath } = yield* makeHarness();
480 yield* service.install();
481
482 for (const stateText of [
483 "{",
484 '{"activeVersion":"latest"}',
485 '{"activeVersion":"1.2"}',
486 '{"activeVersion":123}',
487 ]) {
488 yield* fs.writeFileString(statePath, stateText);
489 const status = yield* service.status;
490 expect(status.current).toBe(false);
491 expect(status.installedVersion).toBeUndefined();
492 }
493 }),
494 );
495
496 it.effect.each(["linux", "darwin"] as const)(
497 "preserves a newer version that finishes updating during stop on %s",
498 (platform) =>
499 Effect.gen(function* () {
500 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
501 const plan = yield* service.install();
502 const unit = yield* fs.readFileString(plan.unitPath);
503 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
504 commands.length = 0;
505
506 const error = yield* service.install().pipe(Effect.flip);
507
508 expect(error).toMatchObject({
509 _tag: "BootServiceDowngradeRefusedError",
510 installedVersion: "1.2.4",
511 targetVersion: "1.2.3",
512 });
513 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
514 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
515 expect(
516 commands.filter(
517 (command) =>
518 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
519 !command.includes("show-environment"),
520 ),
521 ).toEqual(
522 platform === "linux"
523 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
524 : [
525 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
526 `launchctl bootstrap gui/501 ${plan.unitPath}`,
527 ],
528 );
529 }),
530 );
531
532 // regression: #5302 prevent accidental service downgrades
533 it.effect("allows an explicit downgrade", () =>
534 Effect.gen(function* () {
535 const { service, fs, statePath } = yield* makeHarness();
536 yield* service.install();
537 yield* fs.writeFileString(
538 statePath,
539 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
540 );
541
542 yield* service.install({ allowDowngrade: true });
543
544 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
545 expect((yield* service.status).current).toBe(true);
546 }),
547 );
548
549 it.effect("repairs versions with equal SemVer precedence without an override", () =>
550 Effect.gen(function* () {
551 const { service, fs, statePath } = yield* makeHarness();
552 yield* service.install();
553 yield* fs.writeFileString(
554 statePath,
555 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
556 );
557
558 yield* service.install();
559
560 expect((yield* service.status).current).toBe(true);
561 }),
562 );
563
564 it.effect.each(["linux", "darwin"] as const)(
565 "install with start=false rewrites files, preserves service.env, and marks a restart pending on %s",
566 (platform) =>
567 Effect.gen(function* () {
568 const { service, fs, baseDir, statePath, commands, makeService } =
569 yield* makeHarness(platform);
570 const path = yield* Path.Path;
571 const envPath = path.join(baseDir, SERVICE_ENV_FILE);
572 const envBytes = new TextEncoder().encode(
573 '# user configuration\r\nT3CODE_TOKEN="literal $HOME # token"',
574 );
575 yield* fs.writeFile(envPath, envBytes);
576 yield* service.install();
577 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
578 yield* service.install();
579 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
580 commands.length = 0;
581
582 const newer = yield* makeService(undefined, "1.2.4");
583 const plan = yield* newer.install({ start: false });
584 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
585
586 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
587 protocol: SERVICE_LAUNCHER_PROTOCOL,
588 activeVersion: "1.2.4",
589 });
590 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
591 expect(
592 commands.filter(
593 (command) =>
594 /^(systemctl|launchctl) /.test(command) && !command.includes("show-environment"),
595 ),
596 ).toEqual([]);
597 const status = yield* newer.status;
598 expect(status.current).toBe(false);
599 expect(status.problems).toContain("restart-pending");
600
601 commands.length = 0;
602 expect(yield* newer.restart).toBe("restarted");
603 expect((yield* newer.status).problems).not.toContain("restart-pending");
604 expect((yield* newer.status).current).toBe(true);
605
606 const latest = yield* makeService(undefined, "1.2.5");
607 yield* latest.install({ start: true });
608 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
609 protocol: SERVICE_LAUNCHER_PROTOCOL,
610 activeVersion: "1.2.5",
611 });
612 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.5/t3");
613 expect((yield* latest.status).current).toBe(true);
614 expect(
615 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
616 ).toBe(false);
617 }),
618 );
619
620 it.effect(
621 "serializes a local install with another process reconciling an older unit snapshot",
622 () =>
623 Effect.gen(function* () {
624 const { service, fs, statePath, makeService, runtime } = yield* makeHarness();
625 const path = yield* Path.Path;
626 const plan = yield* service.install();
627 const unit = yield* fs.readFileString(plan.unitPath);
628 yield* fs.writeFileString(
629 plan.unitPath,
630 unit.replace("versions/1.2.3/t3", "versions/1.2.2/t3"),
631 );
632 yield* fs.writeFileString(
633 statePath,
634 JSON.stringify({
635 protocol: SERVICE_LAUNCHER_PROTOCOL,
636 activeVersion: "1.2.3",
637 update: {
638 id: "committed",
639 fromVersion: "1.2.2",
640 targetVersion: "1.2.3",
641 status: "committed",
642 },
643 }),
644 );
645 const rejection = path.join(plan.baseDir, "rejected-update");
646 const databasePath = path.join(plan.baseDir, "state.sqlite");
647 yield* fs.writeFileString(databasePath, "database");
648 yield* fs.writeFileString(
649 runtime.entryPath,
650 `#!${process.execPath}
651import { writeFileSync } from "node:fs";
652process.on("message", message => {
653 if (message === "request-update") process.send({ type: "request-update", targetVersion: "1.2.5", dbPath: ${JSON.stringify(databasePath)} });
654 if (message.type === "update-rejected") {
655 writeFileSync(${JSON.stringify(rejection)}, message.reason);
656 process.exit(0);
657 }
658});
659`,
660 );
661 yield* fs.chmod(runtime.entryPath, 0o755);
662 const newer = yield* makeService(undefined, "1.2.4");
663 yield* makeService(undefined, "1.2.5");
664 const snapshot = Promise.withResolvers<void>();
665 const milestone = Promise.withResolvers<void>();
666 const script = path.join(plan.baseDir, "launcher-contention.mjs");
667 yield* fs.writeFileString(
668 script,
669 `
670import fs from "node:fs/promises";
671import cp from "node:child_process";
672import { syncBuiltinESMExports } from "node:module";
673const server = Promise.withResolvers();
674const originalSpawn = cp.spawn;
675cp.spawn = (...args) => { const child = originalSpawn(...args); server.resolve(child); return child; };
676process.on("message", async message => {
677 if (message === "installed") (await server.promise).send("request-update");
678});
679const originalRead = fs.readFile;
680fs.readFile = async (...args) => {
681 const contents = await originalRead(...args);
682 if (args[0] === ${JSON.stringify(plan.unitPath)}) {
683 fs.readFile = originalRead;
684 syncBuiltinESMExports();
685 const resume = new Promise(resolve => process.once("message", resolve));
686 process.send("snapshot");
687 await resume;
688 }
689 return contents;
690};
691syncBuiltinESMExports();
692const { Launcher, readServiceState } = await import(${JSON.stringify(import.meta.resolve("../serviceLauncher.ts"))});
693const launcher = new Launcher(${JSON.stringify(plan.baseDir)}, await readServiceState(${JSON.stringify(statePath)}), {
694 serviceUnit: { path: ${JSON.stringify(plan.unitPath)}, reload: async () => {} },
695});
696try { await launcher.run(); throw Error("unexpected completion"); }
697catch (error) {
698 if (!error.message.includes("Active child exited unexpectedly (0)")) throw error;
699}
700const { acquireServiceSelectionLock } = await import(${JSON.stringify(import.meta.resolve("./serviceSelectionLock.ts"))});
701// Exit owning the real lease, as a crashed process would.
702await acquireServiceSelectionLock(${JSON.stringify(plan.unitPath)});
703process.disconnect();
704`,
705 );
706 const child = yield* Effect.acquireRelease(
707 Effect.sync(() =>
708 NodeChildProcess.fork(script, [], {
709 execArgv: [],
710 stdio: ["ignore", "inherit", "inherit", "ipc"],
711 }),
712 ),
713 (child) =>
714 Effect.sync(() => {
715 if (child.exitCode === null && child.signalCode === null) child.kill();
716 }),
717 );
718 const exited = new Promise<void>((resolve, reject) => {
719 child.once("error", reject);
720 child.once("exit", (code) =>
721 code === 0 ? resolve() : reject(new Error(`launcher exited ${code}`)),
722 );
723 });
724 child.on("message", (message) => {
725 if (message === "snapshot") snapshot.resolve();
726 });
727 yield* Effect.promise(() =>
728 Promise.race([
729 snapshot.promise,
730 exited.then(() => {
731 throw new Error("launcher exited before snapshot");
732 }),
733 ]),
734 );
735 leaseObserver.contended = (destination) => {
736 if (destination === plan.unitPath + ".selection-lock") milestone.resolve();
737 };
738 yield* Effect.addFinalizer(() =>
739 Effect.sync(() => {
740 leaseObserver.contended = () => {};
741 }),
742 );
743 const installing = yield* newer
744 .install({ start: false })
745 .pipe(Effect.ensuring(Effect.sync(() => milestone.resolve())), Effect.forkChild);
746 // Resume the launcher once the installer contends for the unit lease, or once an
747 // uncoordinated installer has finished, which makes the stale snapshot win.
748 yield* Effect.promise(() => milestone.promise);
749 child.send("resume");
750 yield* Fiber.join(installing);
751 child.send("installed");
752 yield* Effect.promise(() => exited);
753 expect(yield* fs.readFileString(rejection)).toContain("Service selection changed");
754 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
755 protocol: SERVICE_LAUNCHER_PROTOCOL,
756 activeVersion: "1.2.4",
757 });
758 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
759 expect(
760 yield* fs.readFileString(
761 path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE),
762 ),
763 ).toBe("1.2.4\n");
764 // The next installer reclaims the dead owner and releases its own lease.
765 yield* newer.install({ start: false });
766 expect(yield* fs.exists(plan.unitPath + ".selection-lock")).toBe(false);
767 }),
768 );
769
770 it.effect("install with start=false keeps the marker when a later write fails", () =>
771 Effect.gen(function* () {
772 const { service, fs, statePath, makeService } = yield* makeHarness();
773 const path = yield* Path.Path;
774 yield* service.install();
775 const newer = yield* makeService(undefined, "1.2.4");
776 const unitPath = (yield* service.status).unitPath;
777 yield* fs.remove(unitPath);
778 yield* fs.makeDirectory(unitPath);
779 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
780
781 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
782 expect(error._tag).toBe("BootServiceInstallError");
783 expect(
784 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
785 ).toBe(true);
786 }),
787 );
788
789 it.effect("install with start=false refuses while a remote update is pending", () =>
790 Effect.gen(function* () {
791 const { service, fs, statePath } = yield* makeHarness();
792 yield* service.install();
793 const pendingState = JSON.stringify({
794 protocol: SERVICE_LAUNCHER_PROTOCOL,
795 activeVersion: "1.2.3",
796 update: {
797 id: "u",
798 fromVersion: "1.2.3",
799 targetVersion: "1.2.4",
800 dbPath: "/tmp/state.sqlite",
801 status: "pending",
802 },
803 });
804 yield* fs.writeFileString(statePath, pendingState);
805
806 const error = yield* service.install({ start: false }).pipe(Effect.flip);
807 expect(error._tag).toBe("BootServiceUpdatePendingError");
808 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
809 yield* fs.remove((yield* service.status).unitPath);
810 expect((yield* service.install({ start: false }).pipe(Effect.flip))._tag).toBe(
811 "BootServiceUpdatePendingError",
812 );
813 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
814 }),
815 );
816
817 it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
818 Effect.gen(function* () {
819 const { service, commands, control, makeService } = yield* makeHarness();
820 yield* service.install();
821 const failure = yield* service
822 .withStopped(Effect.failSync(() => (control.active ? "running" : "repair failed")))
823 .pipe(Effect.flip);
824 expect(failure).toBe("repair failed");
825 expect(control.active).toBe(true);
826
827 control.failCommand = "systemctl --user stop t3code.service";
828 let ran = false;
829 const stopFailure = yield* service
830 .withStopped(
831 Effect.sync(() => {
832 ran = true;
833 }),
834 )
835 .pipe(Effect.flip);
836 expect(stopFailure).toMatchObject({
837 _tag: "BootServiceCommandError",
838 step: "stopping the installed service",
839 });
840 expect(ran).toBe(false);
841 expect(control.active).toBe(true);
842 control.failCommand = undefined;
843
844 control.active = false;
845 commands.length = 0;
846 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
847 expect(commands).toEqual([
848 "systemctl --user is-enabled t3code.service",
849 "systemctl --user is-active t3code.service",
850 "systemctl --user stop t3code.service",
851 "repair",
852 "systemctl --user restart t3code.service",
853 ]);
854 expect(control.active).toBe(true);
855 control.enabled = false;
856 yield* service.withStopped(Effect.void);
857 expect(control).toMatchObject({ active: true, enabled: false });
858 control.active = false;
859 control.enabled = false;
860 commands.length = 0;
861 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
862 expect(commands).toContain("systemctl --user stop t3code.service");
863 expect(commands).not.toContain("systemctl --user restart t3code.service");
864 expect(control.active).toBe(false);
865 control.enabled = true;
866 control.active = true;
867
868 const fs = yield* FileSystem.FileSystem;
869 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
870 const other = yield* makeService(undefined, "1.2.3", otherHome);
871 commands.length = 0;
872 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
873 expect(commands).toEqual([]);
874 }),
875 );
876
877 it.effect("restart and install leave a service that serves another T3 home alone", () =>
878 Effect.gen(function* () {
879 const { service, fs, baseDir, commands, makeService } = yield* makeHarness();
880 const plan = yield* service.install();
881 const unit = yield* fs.readFileString(plan.unitPath);
882 const path = yield* Path.Path;
883 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
884
885 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
886 commands.length = 0;
887 expect(yield* other.restart).toBe("skipped");
888 const refused = yield* other.install().pipe(Effect.flip);
889 expect(refused._tag).toBe("BootServiceOtherBaseDirError");
890 // The CLI prints a user message without a stack trace.
891 expect(CliError.getUserMessage(refused)).toBe(refused.message);
892 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
893 expect(commands).toEqual([]);
894 expect((yield* other.status).otherBaseDir).toBe(baseDir);
895 }),
896 );
897
898 it.effect("hands the whole install to systemd without changing the running service", () =>
899 Effect.gen(function* () {
900 const { fs, commands, invocations, control, makeService } = yield* makeHarness();
901 const path = yield* Path.Path;
902 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
903 const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
904 const outside = yield* makeService(undefined, "1.2.3", baseDir);
905 const plan = yield* outside.install();
906 const statePath = path.join(baseDir, "runtime", "service-state.json");
907 const state = yield* fs.readFileString(statePath);
908 const unit = yield* fs.readFileString(plan.unitPath);
909 const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
910 commands.length = 0;
911 invocations.length = 0;
912
913 const result = yield* inside.install({ allowDowngrade: true });
914
915 expect(yield* fs.readFileString(statePath)).toBe(state);
916 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
917 expect(commands).not.toContain("systemctl --user stop t3code.service");
918 expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
919 const handoffs = invocations.filter(({ command }) => command === "systemd-run");
920 expect(handoffs).toHaveLength(1);
921 expect(handoffs[0]?.args).toEqual([
922 "--user",
923 "--collect",
924 "--quiet",
925 `--property=StandardOutput=append:${plan.logPath}`,
926 `--property=StandardError=append:${plan.logPath}`,
927 "--setenv=T3_BOOT_SERVICE_UNIT=",
928 pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
929 "service",
930 "install",
931 "--base-dir",
932 path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
933 "--allow-downgrade",
934 ]);
935
936 const handoff = handoffs[0]!;
937 control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
938 const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
939 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
940 expect(yield* fs.readFileString(statePath)).toBe(state);
941 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
942 expect(control.active).toBe(true);
943 expect(commands).not.toContain("systemctl --user stop t3code.service");
944 }),
945 );
946
947 it.effect(
948 "queues an in-service restart without stopping the caller, even on handoff failure",
949 () =>
950 Effect.gen(function* () {
951 const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();
952 const plan = yield* service.install();
953 const state = yield* fs.readFileString(statePath);
954 const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
955 yield* fs.writeFileString(marker, "1.2.3\n");
956 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
957 commands.length = 0;
958 control.failCommand = "systemctl --user daemon-reload";
959
960 const error = yield* inside.restart.pipe(Effect.flip);
961 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
962 expect(commands).toEqual(["systemctl --user daemon-reload"]);
963 expect(control.active).toBe(true);
964
965 control.failCommand = undefined;
966 commands.length = 0;
967 const outcome = yield* inside.restart;
968 expect(commands).toEqual([
969 "systemctl --user daemon-reload",
970 "systemctl --user enable t3code.service",
971 "systemctl --user restart --no-block t3code.service",
972 ]);
973 expect(outcome).toBe("queued");
974 expect(yield* fs.readFileString(statePath)).toBe(state);
975 expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
976 }),
977 );
978
979 it.effect("restarts an installed service when repair fails", () =>
980 Effect.gen(function* () {
981 const { service, commands, control } = yield* makeHarness();
982 yield* service.install();
983 commands.length = 0;
984 control.failCommand = "systemctl --user daemon-reload";
985
986 const error = yield* service.install().pipe(Effect.flip);
987 expect(error._tag).toBe("BootServiceCommandError");
988 expect(
989 commands.filter(
990 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
991 ),
992 ).toEqual([
993 "systemctl --user stop t3code.service",
994 "systemctl --user daemon-reload",
995 "systemctl --user restart t3code.service",
996 ]);
997 }),
998 );
999
1000 it.effect("restarts without overwriting a pending remote update", () =>
1001 Effect.gen(function* () {
1002 const { service, fs, statePath, commands } = yield* makeHarness();
1003 yield* service.install();
1004 const pendingState = JSON.stringify({
1005 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
1006 activeVersion: "1.2.3",
1007 update: {
1008 id: "remote-update",
1009 fromVersion: "1.2.3",
1010 targetVersion: "1.2.4",
1011 status: "pending",
1012 },
1013 });
1014 yield* fs.writeFileString(statePath, pendingState);
1015 for (const allowDowngrade of [false, true]) {
1016 commands.length = 0;
1017
1018 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
1019 "BootServiceUpdatePendingError",
1020 );
1021 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
1022 expect(
1023 commands.filter(
1024 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
1025 ),
1026 ).toEqual([
1027 "systemctl --user stop t3code.service",
1028 "systemctl --user restart t3code.service",
1029 ]);
1030 }
1031 }),
1032 );
1033
1034 it.effect("installs, reports current state, and uninstalls on macOS", () =>
1035 Effect.gen(function* () {
1036 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
1037 const path = yield* Path.Path;
1038 const plan = yield* service.install();
1039
1040 expect(
1041 plan.unitPath.endsWith(
1042 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
1043 ),
1044 ).toBe(true);
1045 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1046 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
1047 );
1048 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1049 protocol: SERVICE_LAUNCHER_PROTOCOL,
1050 activeVersion: "1.2.3",
1051 });
1052 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1053 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
1054 );
1055 expect(yield* service.status).toMatchObject({
1056 current: true,
1057 installedVersion: "1.2.3",
1058 });
1059 expect(yield* service.uninstall).toBe(true);
1060 expect((yield* service.status).installed).toBe(false);
1061 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
1062 // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it.
1063 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
1064 Duration.seconds(120),
1065 );
1066 }),
1067 );
1068
1069 // regression: #8173 keep provider CLIs available in the macOS service
1070 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
1071 Effect.gen(function* () {
1072 const { service, fs } = yield* makeHarness("darwin", "");
1073 const plan = yield* service.install();
1074
1075 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1076 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
1077 );
1078 expect((yield* service.status).current).toBe(true);
1079 }),
1080 );
1081
1082 it.effect("adds missing provider directories to a minimal installer PATH", () =>
1083 Effect.gen(function* () {
1084 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
1085 const plan = yield* service.install();
1086
1087 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1088 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
1089 );
1090 expect((yield* service.status).current).toBe(true);
1091 }),
1092 );
1093
1094 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
1095 Effect.gen(function* () {
1096 const { service, makeService } = yield* makeHarness("darwin");
1097 yield* service.install();
1098
1099 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
1100 expect((yield* restartedService.status).current).toBe(true);
1101 }),
1102 );
1103
1104 // regression: #17532
1105 it.effect("puts the runtime an update installs on the launch agent PATH", () =>
1106 Effect.gen(function* () {
1107 const { makeService, fs, baseDir, runtime } = yield* makeHarness("darwin");
1108 const path = yield* Path.Path;
1109 const previous = runtime.versionDir;
1110 const installed = pinnedRuntimePaths(path, baseDir, "1.2.4", "darwin").versionDir;
1111 // The 1.2.3 CLI, or the 1.2.3 service's own PATH, installs 1.2.4.
1112 const updated = yield* makeService(
1113 `/usr/bin:${previous}:/bin`,
1114 "1.2.4",
1115 undefined,
1116 false,
1117 runtime.entryPath,
1118 );
1119 const plan = yield* updated.install();
1120
1121 expect(yield* fs.readFileString(plan.unitPath)).toContain(
1122 ` <key>PATH</key>\n <string>/usr/bin:${installed}:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>`,
1123 );
1124 }),
1125 );
1126
1127 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
1128 Effect.gen(function* () {
1129 const { service, fs } = yield* makeHarness(
1130 "darwin",
1131 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
1132 );
1133 const plan = yield* service.install();
1134 const plist = yield* fs.readFileString(plan.unitPath);
1135
1136 expect(plist).toContain(
1137 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
1138 );
1139 expect(plist).not.toContain("\u0001");
1140 expect((yield* service.status).current).toBe(true);
1141 }),
1142 );
1143
1144 it.effect("ignores a bootout for an agent that is not loaded", () =>
1145 Effect.gen(function* () {
1146 const { service, control } = yield* makeHarness("darwin");
1147 yield* service.install();
1148 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
1149
1150 yield* service.install();
1151 expect((yield* service.status).current).toBe(true);
1152 }),
1153 );
1154
1155 it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
1156 Effect.gen(function* () {
1157 const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
1158 const path = yield* Path.Path;
1159 const plan = yield* service.install();
1160 const markerPath = path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE);
1161 const bootstrap = `launchctl bootstrap gui/501 ${plan.unitPath}`;
1162 control.failCommand = bootstrap;
1163
1164 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1165 expect(yield* service.status).toMatchObject({
1166 current: false,
1167 problems: ["restart-pending"],
1168 });
1169 expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n");
1170
1171 control.failCommand = undefined;
1172 commands.length = 0;
1173 yield* service.install();
1174
1175 expect(commands).toContain(bootstrap);
1176 expect(yield* fs.exists(markerPath)).toBe(false);
1177 expect((yield* service.status).current).toBe(true);
1178 }),
1179 );
1180});