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

bootService.test.ts

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