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

bootService.test.ts

891 lines33.9 KB

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