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