Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessExecutablePath,
5 HostProcessPlatform,
6 HostProcessUserId,
7} from "@t3tools/shared/hostProcess";
8import * as ConfigProvider from "effect/ConfigProvider";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import { HttpClient } from "effect/unstable/http";
15import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
16
17import * as ProcessRunner from "../processRunner.ts";
18import * as BootService from "./bootService.ts";
19import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
20import {
21 parseServiceState,
22 SERVICE_LAUNCHER_PROTOCOL,
23 SERVICE_RESTART_PENDING_FILE,
24 serviceStateHasPendingUpdate,
25} from "./serviceProtocol.ts";
26
27const linuxRuntime = "/home/theo/.t3/runtime/versions/1.2.3/t3";
28const linuxPlan = {
29 program: [linuxRuntime, "__service-launcher"],
30 baseDir: "/home/theo/.t3",
31 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
32 unitPath: "/home/theo/.config/systemd/user/t3code.service",
33};
34
35it("runs the pinned runtime's own executable as the systemd launcher", () => {
36 const unit = BootService.renderBootServiceUnit(linuxPlan);
37
38 expect(unit).toContain(`ExecStart=${linuxRuntime} __service-launcher`);
39 expect(unit).toContain("KillMode=mixed");
40 expect(unit).not.toContain("node");
41});
42
43it("reads the served T3 home back out of a rendered unit or plist", () => {
44 const plan = (baseDir: string) => ({
45 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
46 baseDir,
47 logPath: `${baseDir}/userdata/logs/boot-service.log`,
48 unitPath: "/home/theo/.config/systemd/user/t3code.service",
49 });
50
51 expect(
52 BootService.bootServiceBaseDirOf(BootService.renderBootServiceUnit(plan("/home/theo/.t3"))),
53 ).toBe("/home/theo/.t3");
54 // Spaces and specifiers are quoted and escaped on the way in.
55 expect(
56 BootService.bootServiceBaseDirOf(
57 BootService.renderBootServiceUnit(plan("/home/theo/T3 Data/100%")),
58 ),
59 ).toBe("/home/theo/T3 Data/100%");
60 expect(
61 BootService.bootServiceBaseDirOf(
62 BootService.renderBootServicePlist(plan("/Users/theo/a&b"), {
63 homeDir: "/Users/theo",
64 environmentPath: "/usr/bin",
65 }),
66 ),
67 ).toBe("/Users/theo/a&b");
68 expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
69});
70
71it("survives the kernel OOM-killing a greedy agent child", () => {
72 const unit = BootService.renderBootServiceUnit(linuxPlan);
73
74 expect(unit).toContain("OOMPolicy=continue");
75});
76
77const macRuntime = "/Users/theo/.t3/runtime/versions/1.2.3/t3";
78const macPlan = {
79 program: [macRuntime, "__service-launcher"],
80 baseDir: "/Users/theo/.t3",
81 logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
82 unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
83};
84const macInstallerPath =
85 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
86const macRenderOptions = { homeDir: "/Users/theo", environmentPath: macInstallerPath };
87
88it("runs the pinned runtime's own executable as the launch agent", () => {
89 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
90
91 expect(plist).toContain(
92 ` <array>\n <string>${macRuntime}</string>\n <string>__service-launcher</string>\n </array>`,
93 );
94 expect(plist).not.toContain("node</string>");
95});
96
97it("preserves the installer's provider search path in the launch agent", () => {
98 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
99
100 expect(plist).toContain(` <key>PATH</key>\n <string>${macInstallerPath}</string>`);
101});
102
103it("restarts the launch agent on the systemd cadence", () => {
104 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
105
106 expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
107 expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
108 expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
109 expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
110});
111
112it("appends both stdio streams to the boot service log", () => {
113 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
114
115 expect(plist).toContain(
116 "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
117 );
118 expect(plist).toContain(
119 "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
120 );
121});
122
123it("escapes XML in host paths", () => {
124 const plist = BootService.renderBootServicePlist(
125 { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
126 { homeDir: "/Users/theo", environmentPath: "/Users/theo/Tools & <Scripts>:/usr/bin" },
127 );
128
129 expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
130 expect(plist).toContain("<string>/Users/theo/Tools & <Scripts>:/usr/bin</string>");
131});
132
133const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
134 platform: NodeJS.Platform = "linux",
135 installerPath = macInstallerPath,
136) {
137 const fs = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
140 const baseDir = path.join(home, ".t3");
141 const statePath = path.join(baseDir, "runtime", "service-state.json");
142 // A complete pinned runtime is already present, so install only validates
143 // it and never downloads a release archive.
144 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3", platform);
145 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
146 yield* fs.writeFileString(runtime.entryPath, "#!/bin/sh\n");
147 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
148
149 const commands: string[] = [];
150 const timeouts = new Map<string, unknown>();
151 const control: {
152 failCommand: string | undefined;
153 stateAfterStop?: string;
154 linger: string;
155 enabled: boolean;
156 active: boolean;
157 } = {
158 failCommand: undefined,
159 linger: "yes",
160 enabled: true,
161 active: true,
162 };
163 const runner = ProcessRunner.ProcessRunner.of({
164 run: Effect.fn("test.run_boot_service_command")(function* (
165 input: ProcessRunner.ProcessRunInput,
166 ) {
167 const command = `${input.command} ${input.args.join(" ")}`;
168 commands.push(command);
169 timeouts.set(command, input.timeout);
170 const failed = command === control.failCommand;
171 if (!failed && command === "loginctl enable-linger --no-ask-password 501")
172 control.linger = "yes";
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 if (
176 control.stateAfterStop !== undefined &&
177 (command === "systemctl --user stop t3code.service" ||
178 command.startsWith("launchctl bootout --wait "))
179 ) {
180 yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
181 }
182 return {
183 stdout:
184 input.args[0] === "--version"
185 ? // The runtime under test reports the version of the directory it
186 // was launched from, like the real executable.
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 || (input.args[1] === "is-active" && !control.active) ? 1 : 0,
198 ),
199 timedOut: false,
200 stdoutTruncated: false,
201 stderrTruncated: false,
202 stdoutInvalidUtf8: false,
203 stderrInvalidUtf8: false,
204 };
205 }),
206 });
207 const makeService = (
208 environmentPath: string | undefined = installerPath,
209 cliVersion = "1.2.3",
210 serviceBaseDir = baseDir,
211 ) =>
212 Effect.gen(function* () {
213 // Every version the tests install is present and verified on disk, so
214 // install never downloads.
215 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
216 yield* fs.makeDirectory(path.dirname(paths.entryPath), { recursive: true });
217 yield* fs.writeFileString(paths.entryPath, "#!/bin/sh\n");
218 yield* fs.writeFileString(paths.sentinelPath, `${cliVersion}\n`);
219 return yield* BootService.make({
220 baseDir: serviceBaseDir,
221 logsDir: path.join(serviceBaseDir, "userdata", "logs"),
222 cliVersion,
223 host: { execPath: "/usr/bin/t3" },
224 });
225 }).pipe(
226 Effect.provideService(ProcessRunner.ProcessRunner, runner),
227 Effect.provide(
228 Layer.mergeAll(
229 Layer.succeed(HostProcessPlatform, platform),
230 Layer.succeed(HostProcessUserId, 501),
231 Layer.succeed(HostProcessExecutablePath, "/usr/bin/t3"),
232 Layer.succeed(
233 HttpClient.HttpClient,
234 HttpClient.make(() => Effect.die("no release download expected")),
235 ),
236 ConfigProvider.layer(
237 ConfigProvider.fromEnv({
238 env: {
239 HOME: home,
240 ...(environmentPath === undefined || environmentPath === ""
241 ? {}
242 : { PATH: environmentPath }),
243 },
244 }),
245 ),
246 ),
247 ),
248 );
249 const service = yield* makeService();
250 return { service, makeService, fs, statePath, commands, timeouts, control, runtime };
251});
252
253it.layer(NodeServices.layer)("boot service install", (it) => {
254 it.effect(
255 "fails before installing files or validating a runtime when lingering needs an administrator",
256 () =>
257 Effect.gen(function* () {
258 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
259 const before = yield* service.status;
260 control.linger = "no";
261 control.failCommand = "loginctl enable-linger --no-ask-password 501";
262 yield* fs.remove(runtime.sentinelPath);
263
264 const error = yield* service.install().pipe(Effect.flip);
265
266 expect(error).toMatchObject({
267 _tag: "BootServicePrerequisiteError",
268 problem: "linger-disabled",
269 });
270 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
271 expect(error.message).toContain("last login session ends");
272 expect(yield* fs.exists(before.unitPath)).toBe(false);
273 expect(yield* fs.exists(statePath)).toBe(false);
274 expect(commands.some((command) => command.includes("--version"))).toBe(false);
275 expect(
276 commands.some(
277 (command) => command.includes("daemon-reload") || command.includes("restart"),
278 ),
279 ).toBe(false);
280 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
281 }),
282 );
283
284 it.effect(
285 "detects a partial install and preserves the running service when repair lacks permission",
286 () =>
287 Effect.gen(function* () {
288 const { service, fs, statePath, commands, control } = yield* makeHarness();
289 const plan = yield* service.install();
290 const before = yield* fs.readFileString(statePath);
291 const unit = yield* fs.readFileString(plan.unitPath);
292 control.linger = "no";
293 control.failCommand = "loginctl enable-linger --no-ask-password 501";
294
295 expect(yield* service.status).toMatchObject({
296 current: false,
297 problems: ["linger-disabled"],
298 });
299 commands.length = 0;
300 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
301 "BootServicePrerequisiteError",
302 );
303 expect(yield* fs.readFileString(statePath)).toBe(before);
304 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
305 expect(commands).not.toContain("systemctl --user stop t3code.service");
306 }),
307 );
308
309 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
310 Effect.gen(function* () {
311 const { service, commands, control } = yield* makeHarness();
312 control.linger = "no";
313 yield* service.install();
314 expect(control.linger).toBe("yes");
315 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
316 commands.indexOf("systemctl --user daemon-reload"),
317 );
318
319 control.enabled = false;
320 control.active = false;
321 expect(yield* service.status).toMatchObject({
322 current: false,
323 problems: ["service-disabled", "service-stopped"],
324 });
325 yield* service.install();
326 expect((yield* service.status).current).toBe(true);
327 }),
328 );
329
330 it.effect.each([
331 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
332 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
333 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
334 Effect.gen(function* () {
335 const { service, fs, statePath, control } = yield* makeHarness();
336 control.failCommand = command;
337 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
338 _tag: "BootServicePrerequisiteError",
339 problem,
340 });
341 expect(yield* fs.exists(statePath)).toBe(false);
342 }),
343 );
344
345 it.effect("installs, reports current state, and uninstalls", () =>
346 Effect.gen(function* () {
347 const { service, fs, statePath, timeouts, runtime } = yield* makeHarness();
348 const plan = yield* service.install();
349
350 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
351 protocol: SERVICE_LAUNCHER_PROTOCOL,
352 activeVersion: "1.2.3",
353 });
354 expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
355 expect(yield* fs.readFileString(plan.unitPath)).toContain(
356 `ExecStart=${runtime.entryPath} __service-launcher`,
357 );
358 expect(yield* service.status).toMatchObject({
359 current: true,
360 installedVersion: "1.2.3",
361 });
362 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
363 const pendingState = JSON.stringify({
364 protocol: SERVICE_LAUNCHER_PROTOCOL,
365 activeVersion: "1.2.3",
366 update: {
367 id: "u",
368 fromVersion: "1.2.3",
369 targetVersion: "1.2.4",
370 dbPath: "/tmp/state.sqlite",
371 status: "pending",
372 },
373 });
374 yield* fs.writeFileString(statePath, pendingState);
375 expect((yield* service.status).current).toBe(false);
376 expect(yield* service.uninstall).toBe(true);
377 expect((yield* service.status).installed).toBe(false);
378 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
379 // 60s default would cancel it mid-shutdown.
380 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
381 Duration.seconds(120),
382 );
383 }),
384 );
385
386 it.effect.each(["linux", "darwin"] as const)(
387 "reports the installed version across launcher protocols on %s",
388 (platform) =>
389 Effect.gen(function* () {
390 const { service, fs, statePath } = yield* makeHarness(platform);
391 yield* service.install();
392
393 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
394 yield* fs.writeFileString(
395 statePath,
396 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
397 );
398 expect(yield* service.status).toMatchObject({
399 current: false,
400 installedVersion: "1.2.4-nightly.1",
401 });
402 }
403 }),
404 );
405
406 it.effect("reports an unknown version for invalid service state", () =>
407 Effect.gen(function* () {
408 const { service, fs, statePath } = yield* makeHarness();
409 yield* service.install();
410
411 for (const stateText of [
412 "{",
413 '{"activeVersion":"latest"}',
414 '{"activeVersion":"1.2"}',
415 '{"activeVersion":123}',
416 ]) {
417 yield* fs.writeFileString(statePath, stateText);
418 const status = yield* service.status;
419 expect(status.current).toBe(false);
420 expect(status.installedVersion).toBeUndefined();
421 }
422 }),
423 );
424
425 it.effect.each(["linux", "darwin"] as const)(
426 "preserves a newer version that finishes updating during stop on %s",
427 (platform) =>
428 Effect.gen(function* () {
429 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
430 const plan = yield* service.install();
431 const unit = yield* fs.readFileString(plan.unitPath);
432 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
433 commands.length = 0;
434
435 const error = yield* service.install().pipe(Effect.flip);
436
437 expect(error).toMatchObject({
438 _tag: "BootServiceDowngradeRefusedError",
439 installedVersion: "1.2.4",
440 targetVersion: "1.2.3",
441 });
442 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
443 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
444 expect(
445 commands.filter(
446 (command) =>
447 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
448 !command.includes("show-environment"),
449 ),
450 ).toEqual(
451 platform === "linux"
452 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
453 : [
454 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
455 `launchctl bootstrap gui/501 ${plan.unitPath}`,
456 ],
457 );
458 }),
459 );
460
461 it.effect("allows an explicit downgrade", () =>
462 Effect.gen(function* () {
463 const { service, fs, statePath } = yield* makeHarness();
464 yield* service.install();
465 yield* fs.writeFileString(
466 statePath,
467 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
468 );
469
470 yield* service.install({ allowDowngrade: true });
471
472 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
473 expect((yield* service.status).current).toBe(true);
474 }),
475 );
476
477 it.effect("repairs versions with equal SemVer precedence without an override", () =>
478 Effect.gen(function* () {
479 const { service, fs, statePath } = yield* makeHarness();
480 yield* service.install();
481 yield* fs.writeFileString(
482 statePath,
483 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
484 );
485
486 yield* service.install();
487
488 expect((yield* service.status).current).toBe(true);
489 }),
490 );
491
492 it.effect("install with start=false rewrites the files and marks a restart pending", () =>
493 Effect.gen(function* () {
494 const { service, fs, statePath, commands, makeService } = yield* makeHarness();
495 yield* service.install();
496 commands.length = 0;
497
498 const newer = yield* makeService(undefined, "1.2.4");
499 const plan = yield* newer.install({ start: false });
500
501 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
502 protocol: SERVICE_LAUNCHER_PROTOCOL,
503 activeVersion: "1.2.4",
504 });
505 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
506 expect(
507 commands.filter(
508 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
509 ),
510 ).toEqual([]);
511 // The files say 1.2.4 but the process is still 1.2.3: not current, and
512 // the reason is named so `t3 service status` can point at restart.
513 const status = yield* newer.status;
514 expect(status.current).toBe(false);
515 expect(status.problems).toContain("restart-pending");
516
517 commands.length = 0;
518 expect(yield* newer.restart).toBe(true);
519 expect((yield* newer.status).problems).not.toContain("restart-pending");
520 expect((yield* newer.status).current).toBe(true);
521 }),
522 );
523
524 it.effect("install with start=false keeps the marker when a later write fails", () =>
525 Effect.gen(function* () {
526 const { service, fs, statePath, makeService } = yield* makeHarness();
527 const path = yield* Path.Path;
528 yield* service.install();
529 const newer = yield* makeService(undefined, "1.2.4");
530 // A non-empty directory in the unit's place: it still counts as an
531 // installed unit, and the rename that writes the new unit fails.
532 const unitPath = (yield* service.status).unitPath;
533 yield* fs.remove(unitPath);
534 yield* fs.makeDirectory(unitPath);
535 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
536
537 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
538 expect(error._tag).toBe("BootServiceInstallError");
539 expect(
540 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
541 ).toBe(true);
542 }),
543 );
544
545 it.effect("install with start=false refuses while a remote update is pending", () =>
546 Effect.gen(function* () {
547 const { service, fs, statePath } = yield* makeHarness();
548 yield* service.install();
549 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
550 const pendingState = JSON.stringify({
551 protocol: SERVICE_LAUNCHER_PROTOCOL,
552 activeVersion: "1.2.3",
553 update: {
554 id: "u",
555 fromVersion: "1.2.3",
556 targetVersion: "1.2.4",
557 dbPath: "/tmp/state.sqlite",
558 status: "pending",
559 },
560 });
561 yield* fs.writeFileString(statePath, pendingState);
562
563 const error = yield* service.install({ start: false }).pipe(Effect.flip);
564 expect(error._tag).toBe("BootServiceUpdatePendingError");
565 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
566 }),
567 );
568
569 it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
570 Effect.gen(function* () {
571 const { service, commands } = yield* makeHarness();
572 expect(yield* service.restart).toBe(false);
573 yield* service.install();
574 commands.length = 0;
575
576 expect(yield* service.restart).toBe(true);
577 expect(
578 commands.filter(
579 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
580 ),
581 ).toEqual([
582 "systemctl --user stop t3code.service",
583 "systemctl --user daemon-reload",
584 "systemctl --user enable t3code.service",
585 "systemctl --user restart t3code.service",
586 ]);
587 }),
588 );
589
590 it.effect("restart leaves a service that serves another T3 home alone", () =>
591 Effect.gen(function* () {
592 const { service, fs, commands, makeService } = yield* makeHarness();
593 yield* service.install();
594 commands.length = 0;
595 const path = yield* Path.Path;
596 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
597
598 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
599 expect(yield* other.restart).toBe(false);
600 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
601 }),
602 );
603
604 it.effect("restart brings the service back when activation fails", () =>
605 Effect.gen(function* () {
606 const { service, commands, control } = yield* makeHarness();
607 yield* service.install();
608 commands.length = 0;
609 control.failCommand = "systemctl --user daemon-reload";
610
611 const error = yield* service.restart.pipe(Effect.flip);
612 expect(error._tag).toBe("BootServiceCommandError");
613 expect(
614 commands.filter(
615 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
616 ),
617 ).toEqual([
618 "systemctl --user stop t3code.service",
619 "systemctl --user daemon-reload",
620 "systemctl --user restart t3code.service",
621 ]);
622 }),
623 );
624
625 it.effect("restarts an installed service when repair fails", () =>
626 Effect.gen(function* () {
627 const { service, commands, control } = yield* makeHarness();
628 yield* service.install();
629 commands.length = 0;
630 control.failCommand = "systemctl --user daemon-reload";
631
632 const error = yield* service.install().pipe(Effect.flip);
633 expect(error._tag).toBe("BootServiceCommandError");
634 expect(
635 commands.filter(
636 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
637 ),
638 ).toEqual([
639 "systemctl --user stop t3code.service",
640 "systemctl --user daemon-reload",
641 "systemctl --user restart t3code.service",
642 ]);
643 }),
644 );
645
646 it.effect("restarts without overwriting a pending remote update", () =>
647 Effect.gen(function* () {
648 const { service, fs, statePath, commands } = yield* makeHarness();
649 yield* service.install();
650 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
651 const pendingState = JSON.stringify({
652 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
653 activeVersion: "1.2.3",
654 update: {
655 id: "remote-update",
656 fromVersion: "1.2.3",
657 targetVersion: "1.2.4",
658 status: "pending",
659 },
660 });
661 yield* fs.writeFileString(statePath, pendingState);
662 for (const allowDowngrade of [false, true]) {
663 commands.length = 0;
664
665 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
666 "BootServiceUpdatePendingError",
667 );
668 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
669 expect(
670 commands.filter(
671 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
672 ),
673 ).toEqual([
674 "systemctl --user stop t3code.service",
675 "systemctl --user restart t3code.service",
676 ]);
677 }
678 }),
679 );
680
681 it.effect("fails closed on Windows", () =>
682 Effect.gen(function* () {
683 const { service } = yield* makeHarness("win32");
684 expect((yield* service.status).supported).toBe(false);
685 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
686 }),
687 );
688
689 it.effect("installs, reports current state, and uninstalls on macOS", () =>
690 Effect.gen(function* () {
691 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
692 const path = yield* Path.Path;
693 const plan = yield* service.install();
694
695 expect(
696 plan.unitPath.endsWith(
697 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
698 ),
699 ).toBe(true);
700 expect(yield* fs.readFileString(plan.unitPath)).toContain(
701 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
702 );
703 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
704 protocol: SERVICE_LAUNCHER_PROTOCOL,
705 activeVersion: "1.2.3",
706 });
707 expect(yield* fs.readFileString(plan.unitPath)).toContain(
708 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
709 );
710 expect(yield* service.status).toMatchObject({
711 current: true,
712 installedVersion: "1.2.3",
713 });
714 expect(yield* service.uninstall).toBe(true);
715 expect((yield* service.status).installed).toBe(false);
716 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
717 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
718 // 60s default would cancel it and let bootstrap race a loaded job.
719 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
720 Duration.seconds(120),
721 );
722 }),
723 );
724
725 it.effect("restarts the launch agent when repair fails", () =>
726 Effect.gen(function* () {
727 const { service, commands, control } = yield* makeHarness("darwin");
728 yield* service.install();
729 const plistPath = (yield* service.status).unitPath;
730 commands.length = 0;
731 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
732
733 const error = yield* service.install().pipe(Effect.flip);
734 expect(error._tag).toBe("BootServiceCommandError");
735 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
736 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
737 "launchctl enable gui/501/com.t3tools.t3code.service",
738 `launchctl bootstrap gui/501 ${plistPath}`,
739 `launchctl bootstrap gui/501 ${plistPath}`,
740 ]);
741 }),
742 );
743
744 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
745 Effect.gen(function* () {
746 const { service, fs } = yield* makeHarness("darwin", "");
747 const plan = yield* service.install();
748
749 expect(yield* fs.readFileString(plan.unitPath)).toContain(
750 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
751 );
752 expect((yield* service.status).current).toBe(true);
753 }),
754 );
755
756 it.effect("adds missing provider directories to a minimal installer PATH", () =>
757 Effect.gen(function* () {
758 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
759 const plan = yield* service.install();
760
761 expect(yield* fs.readFileString(plan.unitPath)).toContain(
762 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
763 );
764 expect((yield* service.status).current).toBe(true);
765 }),
766 );
767
768 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
769 Effect.gen(function* () {
770 const { service, makeService } = yield* makeHarness("darwin");
771 yield* service.install();
772
773 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
774 expect((yield* restartedService.status).current).toBe(true);
775 }),
776 );
777
778 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
779 Effect.gen(function* () {
780 const { service, fs } = yield* makeHarness(
781 "darwin",
782 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
783 );
784 const plan = yield* service.install();
785 const plist = yield* fs.readFileString(plan.unitPath);
786
787 expect(plist).toContain(
788 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
789 );
790 expect(plist).not.toContain("\u0001");
791 expect((yield* service.status).current).toBe(true);
792 }),
793 );
794
795 it.effect("ignores a bootout for an agent that is not loaded", () =>
796 Effect.gen(function* () {
797 const { service, control } = yield* makeHarness("darwin");
798 yield* service.install();
799 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
800
801 yield* service.install();
802 expect((yield* service.status).current).toBe(true);
803 }),
804 );
805
806 it.effect("restarts without overwriting a pending remote update on macOS", () =>
807 Effect.gen(function* () {
808 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
809 yield* service.install();
810 const plistPath = (yield* service.status).unitPath;
811 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
812 const pendingState = JSON.stringify({
813 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
814 activeVersion: "1.2.3",
815 update: {
816 id: "remote-update",
817 fromVersion: "1.2.3",
818 targetVersion: "1.2.4",
819 status: "pending",
820 },
821 });
822 yield* fs.writeFileString(statePath, pendingState);
823 for (const allowDowngrade of [false, true]) {
824 commands.length = 0;
825
826 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
827 "BootServiceUpdatePendingError",
828 );
829 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
830 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
831 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
832 `launchctl bootstrap gui/501 ${plistPath}`,
833 ]);
834 }
835 }),
836 );
837});