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("preserves the running service when a cached runtime cannot load node-pty", () =>
215 Effect.gen(function* () {
216 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
217 const plan = yield* service.install();
218 const stateBefore = yield* fs.readFileString(statePath);
219 const unitBefore = yield* fs.readFileString(plan.unitPath);
220 control.failCommand = commands.find((command) => command.includes("--input-type=commonjs"));
221 expect(control.failCommand).toBeDefined();
222 commands.length = 0;
223
224 const error = yield* service.install().pipe(Effect.flip);
225
226 expect(error.message).toContain("loading node-pty");
227 expect(yield* fs.readFileString(statePath)).toBe(stateBefore);
228 expect(yield* fs.readFileString(plan.unitPath)).toBe(unitBefore);
229 expect(yield* fs.exists(runtime.sentinelPath)).toBe(true);
230 expect(commands).not.toContain("systemctl --user stop t3code.service");
231 expect(commands).not.toContain("systemctl --user restart t3code.service");
232 }),
233 );
234
235 it.effect(
236 "fails before installing files or validating a runtime when lingering needs an administrator",
237 () =>
238 Effect.gen(function* () {
239 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
240 const before = yield* service.status;
241 control.linger = "no";
242 control.failCommand = "loginctl enable-linger --no-ask-password 501";
243 yield* fs.remove(runtime.sentinelPath);
244
245 const error = yield* service.install().pipe(Effect.flip);
246
247 expect(error).toMatchObject({
248 _tag: "BootServicePrerequisiteError",
249 problem: "linger-disabled",
250 });
251 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
252 expect(error.message).toContain("last login session ends");
253 expect(yield* fs.exists(before.unitPath)).toBe(false);
254 expect(yield* fs.exists(statePath)).toBe(false);
255 expect(
256 commands.some((command) => command.startsWith("npm ") || command.includes("--version")),
257 ).toBe(false);
258 expect(
259 commands.some(
260 (command) => command.includes("daemon-reload") || command.includes("restart"),
261 ),
262 ).toBe(false);
263 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
264 }),
265 );
266
267 it.effect(
268 "detects a partial install and preserves the running service when repair lacks permission",
269 () =>
270 Effect.gen(function* () {
271 const { service, fs, statePath, commands, control } = yield* makeHarness();
272 const plan = yield* service.install();
273 const before = yield* fs.readFileString(statePath);
274 const unit = yield* fs.readFileString(plan.unitPath);
275 control.linger = "no";
276 control.failCommand = "loginctl enable-linger --no-ask-password 501";
277
278 expect(yield* service.status).toMatchObject({
279 current: false,
280 problems: ["linger-disabled"],
281 });
282 commands.length = 0;
283 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
284 "BootServicePrerequisiteError",
285 );
286 expect(yield* fs.readFileString(statePath)).toBe(before);
287 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
288 expect(commands).not.toContain("systemctl --user stop t3code.service");
289 }),
290 );
291
292 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
293 Effect.gen(function* () {
294 const { service, commands, control } = yield* makeHarness();
295 control.linger = "no";
296 yield* service.install();
297 expect(control.linger).toBe("yes");
298 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
299 commands.indexOf("systemctl --user daemon-reload"),
300 );
301
302 control.enabled = false;
303 control.active = false;
304 expect(yield* service.status).toMatchObject({
305 current: false,
306 problems: ["service-disabled", "service-stopped"],
307 });
308 yield* service.install();
309 expect((yield* service.status).current).toBe(true);
310 }),
311 );
312
313 it.effect.each([
314 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
315 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
316 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
317 Effect.gen(function* () {
318 const { service, fs, statePath, control } = yield* makeHarness();
319 control.failCommand = command;
320 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
321 _tag: "BootServicePrerequisiteError",
322 problem,
323 });
324 expect(yield* fs.exists(statePath)).toBe(false);
325 }),
326 );
327
328 it.effect("installs, reports current state, and uninstalls", () =>
329 Effect.gen(function* () {
330 const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
331 const plan = yield* service.install();
332
333 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
334 protocol: SERVICE_LAUNCHER_PROTOCOL,
335 activeVersion: "1.2.3",
336 });
337 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
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 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
359 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
360 // 60s default would cancel it mid-shutdown.
361 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
362 Duration.seconds(120),
363 );
364 }),
365 );
366
367 it.effect.each(["linux", "darwin"] as const)(
368 "reports the installed version across launcher protocols on %s",
369 (platform) =>
370 Effect.gen(function* () {
371 const { service, fs, statePath } = yield* makeHarness(platform);
372 yield* service.install();
373
374 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
375 yield* fs.writeFileString(
376 statePath,
377 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
378 );
379 expect(yield* service.status).toMatchObject({
380 current: false,
381 installedVersion: "1.2.4-nightly.1",
382 });
383 }
384 }),
385 );
386
387 it.effect("reports an unknown version for invalid service state", () =>
388 Effect.gen(function* () {
389 const { service, fs, statePath } = yield* makeHarness();
390 yield* service.install();
391
392 for (const stateText of [
393 "{",
394 '{"activeVersion":"latest"}',
395 '{"activeVersion":"1.2"}',
396 '{"activeVersion":123}',
397 ]) {
398 yield* fs.writeFileString(statePath, stateText);
399 const status = yield* service.status;
400 expect(status.current).toBe(false);
401 expect(status.installedVersion).toBeUndefined();
402 }
403 }),
404 );
405
406 it.effect.each(["linux", "darwin"] as const)(
407 "preserves a newer version that finishes updating during stop on %s",
408 (platform) =>
409 Effect.gen(function* () {
410 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
411 const plan = yield* service.install();
412 const launcher = yield* fs.readFileString(plan.launcherPath);
413 const unit = yield* fs.readFileString(plan.unitPath);
414 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
415 commands.length = 0;
416
417 const error = yield* service.install().pipe(Effect.flip);
418
419 expect(error).toMatchObject({
420 _tag: "BootServiceDowngradeRefusedError",
421 installedVersion: "1.2.4",
422 targetVersion: "1.2.3",
423 });
424 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
425 expect(yield* fs.readFileString(plan.launcherPath)).toBe(launcher);
426 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
427 expect(
428 commands.filter(
429 (command) =>
430 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
431 !command.includes("show-environment"),
432 ),
433 ).toEqual(
434 platform === "linux"
435 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
436 : [
437 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
438 `launchctl bootstrap gui/501 ${plan.unitPath}`,
439 ],
440 );
441 }),
442 );
443
444 it.effect("allows an explicit downgrade", () =>
445 Effect.gen(function* () {
446 const { service, fs, statePath } = yield* makeHarness();
447 yield* service.install();
448 yield* fs.writeFileString(
449 statePath,
450 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
451 );
452
453 yield* service.install({ allowDowngrade: true });
454
455 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
456 expect((yield* service.status).current).toBe(true);
457 }),
458 );
459
460 it.effect("repairs versions with equal SemVer precedence without an override", () =>
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.3+previous-build"}`,
467 );
468
469 yield* service.install();
470
471 expect((yield* service.status).current).toBe(true);
472 }),
473 );
474
475 it.effect("copies the launcher from the prepared pinned runtime", () =>
476 Effect.gen(function* () {
477 const { service, fs } = yield* makeHarness("linux", true);
478 const plan = yield* service.install();
479
480 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
481 "export const source = 'pinned runtime';\n",
482 );
483 }),
484 );
485
486 it.effect("restarts an installed service when repair fails", () =>
487 Effect.gen(function* () {
488 const { service, commands, control } = yield* makeHarness();
489 yield* service.install();
490 commands.length = 0;
491 control.failCommand = "systemctl --user daemon-reload";
492
493 const error = yield* service.install().pipe(Effect.flip);
494 expect(error._tag).toBe("BootServiceCommandError");
495 expect(
496 commands.filter(
497 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
498 ),
499 ).toEqual([
500 "systemctl --user stop t3code.service",
501 "systemctl --user daemon-reload",
502 "systemctl --user restart t3code.service",
503 ]);
504 }),
505 );
506
507 it.effect("restarts without overwriting a pending remote update", () =>
508 Effect.gen(function* () {
509 const { service, fs, statePath, commands } = yield* makeHarness();
510 yield* service.install();
511 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
512 const pendingState = JSON.stringify({
513 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
514 activeVersion: "1.2.3",
515 update: {
516 id: "remote-update",
517 fromVersion: "1.2.3",
518 targetVersion: "1.2.4",
519 status: "pending",
520 },
521 });
522 yield* fs.writeFileString(statePath, pendingState);
523 for (const allowDowngrade of [false, true]) {
524 commands.length = 0;
525
526 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
527 "BootServiceUpdatePendingError",
528 );
529 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
530 expect(
531 commands.filter(
532 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
533 ),
534 ).toEqual([
535 "systemctl --user stop t3code.service",
536 "systemctl --user restart t3code.service",
537 ]);
538 }
539 }),
540 );
541
542 it.effect("fails closed on Windows", () =>
543 Effect.gen(function* () {
544 const { service } = yield* makeHarness("win32");
545 expect((yield* service.status).supported).toBe(false);
546 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
547 }),
548 );
549
550 it.effect("installs, reports current state, and uninstalls on macOS", () =>
551 Effect.gen(function* () {
552 const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
553 const path = yield* Path.Path;
554 const plan = yield* service.install();
555
556 expect(
557 plan.unitPath.endsWith(
558 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
559 ),
560 ).toBe(true);
561 expect(yield* fs.readFileString(plan.unitPath)).toContain(
562 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
563 );
564 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
565 protocol: SERVICE_LAUNCHER_PROTOCOL,
566 activeVersion: "1.2.3",
567 });
568 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
569 expect(yield* service.status).toMatchObject({
570 current: true,
571 installedVersion: "1.2.3",
572 });
573 expect(yield* service.uninstall).toBe(true);
574 expect((yield* service.status).installed).toBe(false);
575 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
576 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
577 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
578 // 60s default would cancel it and let bootstrap race a loaded job.
579 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
580 Duration.seconds(120),
581 );
582 }),
583 );
584
585 it.effect("restarts the launch agent when repair fails", () =>
586 Effect.gen(function* () {
587 const { service, commands, control } = yield* makeHarness("darwin");
588 yield* service.install();
589 const plistPath = (yield* service.status).unitPath;
590 commands.length = 0;
591 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
592
593 const error = yield* service.install().pipe(Effect.flip);
594 expect(error._tag).toBe("BootServiceCommandError");
595 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
596 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
597 "launchctl enable gui/501/com.t3tools.t3code.service",
598 `launchctl bootstrap gui/501 ${plistPath}`,
599 `launchctl bootstrap gui/501 ${plistPath}`,
600 ]);
601 }),
602 );
603
604 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
605 Effect.gen(function* () {
606 const { service, fs } = yield* makeHarness("darwin", false, "");
607 const plan = yield* service.install();
608
609 expect(yield* fs.readFileString(plan.unitPath)).toContain(
610 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
611 );
612 expect((yield* service.status).current).toBe(true);
613 }),
614 );
615
616 it.effect("adds missing provider directories to a minimal installer PATH", () =>
617 Effect.gen(function* () {
618 const { service, fs } = yield* makeHarness("darwin", false, "/usr/bin:/bin");
619 const plan = yield* service.install();
620
621 expect(yield* fs.readFileString(plan.unitPath)).toContain(
622 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
623 );
624 expect((yield* service.status).current).toBe(true);
625 }),
626 );
627
628 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
629 Effect.gen(function* () {
630 const { service, makeService } = yield* makeHarness("darwin");
631 yield* service.install();
632
633 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
634 expect((yield* restartedService.status).current).toBe(true);
635 }),
636 );
637
638 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
639 Effect.gen(function* () {
640 const { service, fs } = yield* makeHarness(
641 "darwin",
642 false,
643 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
644 );
645 const plan = yield* service.install();
646 const plist = yield* fs.readFileString(plan.unitPath);
647
648 expect(plist).toContain(
649 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
650 );
651 expect(plist).not.toContain("\u0001");
652 expect((yield* service.status).current).toBe(true);
653 }),
654 );
655
656 it.effect("ignores a bootout for an agent that is not loaded", () =>
657 Effect.gen(function* () {
658 const { service, control } = yield* makeHarness("darwin");
659 yield* service.install();
660 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
661
662 yield* service.install();
663 expect((yield* service.status).current).toBe(true);
664 }),
665 );
666
667 it.effect("restarts without overwriting a pending remote update on macOS", () =>
668 Effect.gen(function* () {
669 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
670 yield* service.install();
671 const plistPath = (yield* service.status).unitPath;
672 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
673 const pendingState = JSON.stringify({
674 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
675 activeVersion: "1.2.3",
676 update: {
677 id: "remote-update",
678 fromVersion: "1.2.3",
679 targetVersion: "1.2.4",
680 status: "pending",
681 },
682 });
683 yield* fs.writeFileString(statePath, pendingState);
684 for (const allowDowngrade of [false, true]) {
685 commands.length = 0;
686
687 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
688 "BootServiceUpdatePendingError",
689 );
690 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
691 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
692 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
693 `launchctl bootstrap gui/501 ${plistPath}`,
694 ]);
695 }
696 }),
697 );
698});