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