Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

bootService.test.ts

833 lines31.7 KB

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/http";
15import * as ChildProcessSpawner from "effect/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 &amp; &lt;Co&gt;</string>");
130 expect(plist).toContain("<string>/Users/theo/Tools &amp; &lt;Scripts&gt;:/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 const pendingState = JSON.stringify({
363 protocol: SERVICE_LAUNCHER_PROTOCOL,
364 activeVersion: "1.2.3",
365 update: {
366 id: "u",
367 fromVersion: "1.2.3",
368 targetVersion: "1.2.4",
369 dbPath: "/tmp/state.sqlite",
370 status: "pending",
371 },
372 });
373 yield* fs.writeFileString(statePath, pendingState);
374 expect((yield* service.status).current).toBe(false);
375 expect(yield* service.uninstall).toBe(true);
376 expect((yield* service.status).installed).toBe(false);
377 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
378 // 60s default would cancel it mid-shutdown.
379 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
380 Duration.seconds(120),
381 );
382 }),
383 );
384​
385 it.effect.each(["linux", "darwin"] as const)(
386 "reports the installed version across launcher protocols on %s",
387 (platform) =>
388 Effect.gen(function* () {
389 const { service, fs, statePath } = yield* makeHarness(platform);
390 yield* service.install();
391​
392 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
393 yield* fs.writeFileString(
394 statePath,
395 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
396 );
397 expect(yield* service.status).toMatchObject({
398 current: false,
399 installedVersion: "1.2.4-nightly.1",
400 });
401 }
402 }),
403 );
404​
405 it.effect("reports an unknown version for invalid service state", () =>
406 Effect.gen(function* () {
407 const { service, fs, statePath } = yield* makeHarness();
408 yield* service.install();
409​
410 for (const stateText of [
411 "{",
412 '{"activeVersion":"latest"}',
413 '{"activeVersion":"1.2"}',
414 '{"activeVersion":123}',
415 ]) {
416 yield* fs.writeFileString(statePath, stateText);
417 const status = yield* service.status;
418 expect(status.current).toBe(false);
419 expect(status.installedVersion).toBeUndefined();
420 }
421 }),
422 );
423​
424 it.effect.each(["linux", "darwin"] as const)(
425 "preserves a newer version that finishes updating during stop on %s",
426 (platform) =>
427 Effect.gen(function* () {
428 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
429 const plan = yield* service.install();
430 const unit = yield* fs.readFileString(plan.unitPath);
431 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
432 commands.length = 0;
433​
434 const error = yield* service.install().pipe(Effect.flip);
435​
436 expect(error).toMatchObject({
437 _tag: "BootServiceDowngradeRefusedError",
438 installedVersion: "1.2.4",
439 targetVersion: "1.2.3",
440 });
441 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
442 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
443 expect(
444 commands.filter(
445 (command) =>
446 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
447 !command.includes("show-environment"),
448 ),
449 ).toEqual(
450 platform === "linux"
451 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
452 : [
453 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
454 `launchctl bootstrap gui/501 ${plan.unitPath}`,
455 ],
456 );
457 }),
458 );
459​
460 it.effect("allows an explicit downgrade", () =>
461 Effect.gen(function* () {
462 const { service, fs, statePath } = yield* makeHarness();
463 yield* service.install();
464 yield* fs.writeFileString(
465 statePath,
466 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
467 );
468​
469 yield* service.install({ allowDowngrade: true });
470​
471 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
472 expect((yield* service.status).current).toBe(true);
473 }),
474 );
475​
476 it.effect("repairs versions with equal SemVer precedence without an override", () =>
477 Effect.gen(function* () {
478 const { service, fs, statePath } = yield* makeHarness();
479 yield* service.install();
480 yield* fs.writeFileString(
481 statePath,
482 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
483 );
484​
485 yield* service.install();
486​
487 expect((yield* service.status).current).toBe(true);
488 }),
489 );
490​
491 it.effect("install with start=false rewrites the files and marks a restart pending", () =>
492 Effect.gen(function* () {
493 const { service, fs, statePath, commands, makeService } = yield* makeHarness();
494 yield* service.install();
495 commands.length = 0;
496​
497 const newer = yield* makeService(undefined, "1.2.4");
498 const plan = yield* newer.install({ start: false });
499​
500 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
501 protocol: SERVICE_LAUNCHER_PROTOCOL,
502 activeVersion: "1.2.4",
503 });
504 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
505 expect(
506 commands.filter(
507 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
508 ),
509 ).toEqual([]);
510 // The files say 1.2.4 but the process is still 1.2.3: not current, and
511 // the reason is named so `t3 service status` can point at restart.
512 const status = yield* newer.status;
513 expect(status.current).toBe(false);
514 expect(status.problems).toContain("restart-pending");
515​
516 commands.length = 0;
517 expect(yield* newer.restart).toBe(true);
518 expect((yield* newer.status).problems).not.toContain("restart-pending");
519 expect((yield* newer.status).current).toBe(true);
520 }),
521 );
522​
523 it.effect("install with start=false keeps the marker when a later write fails", () =>
524 Effect.gen(function* () {
525 const { service, fs, statePath, makeService } = yield* makeHarness();
526 const path = yield* Path.Path;
527 yield* service.install();
528 const newer = yield* makeService(undefined, "1.2.4");
529 // A non-empty directory in the unit's place: it still counts as an
530 // installed unit, and the rename that writes the new unit fails.
531 const unitPath = (yield* service.status).unitPath;
532 yield* fs.remove(unitPath);
533 yield* fs.makeDirectory(unitPath);
534 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
535​
536 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
537 expect(error._tag).toBe("BootServiceInstallError");
538 expect(
539 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
540 ).toBe(true);
541 }),
542 );
543​
544 it.effect("install with start=false refuses while a remote update is pending", () =>
545 Effect.gen(function* () {
546 const { service, fs, statePath } = yield* makeHarness();
547 yield* service.install();
548 const pendingState = JSON.stringify({
549 protocol: SERVICE_LAUNCHER_PROTOCOL,
550 activeVersion: "1.2.3",
551 update: {
552 id: "u",
553 fromVersion: "1.2.3",
554 targetVersion: "1.2.4",
555 dbPath: "/tmp/state.sqlite",
556 status: "pending",
557 },
558 });
559 yield* fs.writeFileString(statePath, pendingState);
560​
561 const error = yield* service.install({ start: false }).pipe(Effect.flip);
562 expect(error._tag).toBe("BootServiceUpdatePendingError");
563 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
564 }),
565 );
566​
567 it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
568 Effect.gen(function* () {
569 const { service, commands } = yield* makeHarness();
570 expect(yield* service.restart).toBe(false);
571 yield* service.install();
572 commands.length = 0;
573​
574 expect(yield* service.restart).toBe(true);
575 expect(
576 commands.filter(
577 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
578 ),
579 ).toEqual([
580 "systemctl --user stop t3code.service",
581 "systemctl --user daemon-reload",
582 "systemctl --user enable t3code.service",
583 "systemctl --user restart t3code.service",
584 ]);
585 }),
586 );
587​
588 it.effect("restart leaves a service that serves another T3 home alone", () =>
589 Effect.gen(function* () {
590 const { service, fs, commands, makeService } = yield* makeHarness();
591 yield* service.install();
592 commands.length = 0;
593 const path = yield* Path.Path;
594 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
595​
596 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
597 expect(yield* other.restart).toBe(false);
598 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
599 }),
600 );
601​
602 it.effect("restart brings the service back when activation fails", () =>
603 Effect.gen(function* () {
604 const { service, commands, control } = yield* makeHarness();
605 yield* service.install();
606 commands.length = 0;
607 control.failCommand = "systemctl --user daemon-reload";
608​
609 const error = yield* service.restart.pipe(Effect.flip);
610 expect(error._tag).toBe("BootServiceCommandError");
611 expect(
612 commands.filter(
613 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
614 ),
615 ).toEqual([
616 "systemctl --user stop t3code.service",
617 "systemctl --user daemon-reload",
618 "systemctl --user restart t3code.service",
619 ]);
620 }),
621 );
622​
623 it.effect("restarts an installed service when repair fails", () =>
624 Effect.gen(function* () {
625 const { service, commands, control } = yield* makeHarness();
626 yield* service.install();
627 commands.length = 0;
628 control.failCommand = "systemctl --user daemon-reload";
629​
630 const error = yield* service.install().pipe(Effect.flip);
631 expect(error._tag).toBe("BootServiceCommandError");
632 expect(
633 commands.filter(
634 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
635 ),
636 ).toEqual([
637 "systemctl --user stop t3code.service",
638 "systemctl --user daemon-reload",
639 "systemctl --user restart t3code.service",
640 ]);
641 }),
642 );
643​
644 it.effect("restarts without overwriting a pending remote update", () =>
645 Effect.gen(function* () {
646 const { service, fs, statePath, commands } = yield* makeHarness();
647 yield* service.install();
648 const pendingState = JSON.stringify({
649 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
650 activeVersion: "1.2.3",
651 update: {
652 id: "remote-update",
653 fromVersion: "1.2.3",
654 targetVersion: "1.2.4",
655 status: "pending",
656 },
657 });
658 yield* fs.writeFileString(statePath, pendingState);
659 for (const allowDowngrade of [false, true]) {
660 commands.length = 0;
661​
662 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
663 "BootServiceUpdatePendingError",
664 );
665 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
666 expect(
667 commands.filter(
668 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
669 ),
670 ).toEqual([
671 "systemctl --user stop t3code.service",
672 "systemctl --user restart t3code.service",
673 ]);
674 }
675 }),
676 );
677​
678 it.effect("fails closed on Windows", () =>
679 Effect.gen(function* () {
680 const { service } = yield* makeHarness("win32");
681 expect((yield* service.status).supported).toBe(false);
682 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
683 }),
684 );
685​
686 it.effect("installs, reports current state, and uninstalls on macOS", () =>
687 Effect.gen(function* () {
688 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
689 const path = yield* Path.Path;
690 const plan = yield* service.install();
691​
692 expect(
693 plan.unitPath.endsWith(
694 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
695 ),
696 ).toBe(true);
697 expect(yield* fs.readFileString(plan.unitPath)).toContain(
698 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
699 );
700 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
701 protocol: SERVICE_LAUNCHER_PROTOCOL,
702 activeVersion: "1.2.3",
703 });
704 expect(yield* fs.readFileString(plan.unitPath)).toContain(
705 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
706 );
707 expect(yield* service.status).toMatchObject({
708 current: true,
709 installedVersion: "1.2.3",
710 });
711 expect(yield* service.uninstall).toBe(true);
712 expect((yield* service.status).installed).toBe(false);
713 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
714 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
715 // 60s default would cancel it and let bootstrap race a loaded job.
716 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
717 Duration.seconds(120),
718 );
719 }),
720 );
721​
722 it.effect("restarts the launch agent when repair fails", () =>
723 Effect.gen(function* () {
724 const { service, commands, control } = yield* makeHarness("darwin");
725 yield* service.install();
726 const plistPath = (yield* service.status).unitPath;
727 commands.length = 0;
728 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
729​
730 const error = yield* service.install().pipe(Effect.flip);
731 expect(error._tag).toBe("BootServiceCommandError");
732 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
733 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
734 "launchctl enable gui/501/com.t3tools.t3code.service",
735 `launchctl bootstrap gui/501 ${plistPath}`,
736 `launchctl bootstrap gui/501 ${plistPath}`,
737 ]);
738 }),
739 );
740​
741 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
742 Effect.gen(function* () {
743 const { service, fs } = yield* makeHarness("darwin", "");
744 const plan = yield* service.install();
745​
746 expect(yield* fs.readFileString(plan.unitPath)).toContain(
747 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
748 );
749 expect((yield* service.status).current).toBe(true);
750 }),
751 );
752​
753 it.effect("adds missing provider directories to a minimal installer PATH", () =>
754 Effect.gen(function* () {
755 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
756 const plan = yield* service.install();
757​
758 expect(yield* fs.readFileString(plan.unitPath)).toContain(
759 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
760 );
761 expect((yield* service.status).current).toBe(true);
762 }),
763 );
764​
765 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
766 Effect.gen(function* () {
767 const { service, makeService } = yield* makeHarness("darwin");
768 yield* service.install();
769​
770 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
771 expect((yield* restartedService.status).current).toBe(true);
772 }),
773 );
774​
775 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
776 Effect.gen(function* () {
777 const { service, fs } = yield* makeHarness(
778 "darwin",
779 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
780 );
781 const plan = yield* service.install();
782 const plist = yield* fs.readFileString(plan.unitPath);
783​
784 expect(plist).toContain(
785 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
786 );
787 expect(plist).not.toContain("\u0001");
788 expect((yield* service.status).current).toBe(true);
789 }),
790 );
791​
792 it.effect("ignores a bootout for an agent that is not loaded", () =>
793 Effect.gen(function* () {
794 const { service, control } = yield* makeHarness("darwin");
795 yield* service.install();
796 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
797​
798 yield* service.install();
799 expect((yield* service.status).current).toBe(true);
800 }),
801 );
802​
803 it.effect("restarts without overwriting a pending remote update on macOS", () =>
804 Effect.gen(function* () {
805 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
806 yield* service.install();
807 const plistPath = (yield* service.status).unitPath;
808 const pendingState = JSON.stringify({
809 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
810 activeVersion: "1.2.3",
811 update: {
812 id: "remote-update",
813 fromVersion: "1.2.3",
814 targetVersion: "1.2.4",
815 status: "pending",
816 },
817 });
818 yield* fs.writeFileString(statePath, pendingState);
819 for (const allowDowngrade of [false, true]) {
820 commands.length = 0;
821​
822 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
823 "BootServiceUpdatePendingError",
824 );
825 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
826 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
827 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
828 `launchctl bootstrap gui/501 ${plistPath}`,
829 ]);
830 }
831 }),
832 );
833});