Open History to see the last commit
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 & <Co></string>");
125 expect(plist).toContain("<string>/Users/theo/Tools & <Scripts>:/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 invocations: ProcessRunner.ProcessRunInput[] = [];
144 const timeouts = new Map<string, unknown>();
145 const control: {
146 failCommand: string | undefined;
147 stateAfterStop?: string;
148 linger: string;
149 enabled: boolean;
150 active: boolean;
151 } = {
152 failCommand: undefined,
153 linger: "yes",
154 enabled: true,
155 active: true,
156 };
157 const runner = ProcessRunner.ProcessRunner.of({
158 run: Effect.fn("test.run_boot_service_command")(function* (
159 input: ProcessRunner.ProcessRunInput,
160 ) {
161 const command = `${input.command} ${input.args.join(" ")}`;
162 commands.push(command);
163 invocations.push(input);
164 timeouts.set(command, input.timeout);
165 const failed = command === control.failCommand;
166 if (!failed && command === "loginctl enable-linger --no-ask-password 501")
167 control.linger = "yes";
168 if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
169 if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
170 // A stop that fails (a timeout, say) has still stopped the service.
171 if (command === "systemctl --user stop t3code.service") control.active = false;
172 if (
173 control.stateAfterStop !== undefined &&
174 (command === "systemctl --user stop t3code.service" ||
175 command.startsWith("launchctl bootout --wait "))
176 ) {
177 yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
178 }
179 return {
180 stdout:
181 input.args[0] === "--version"
182 ? `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
183 : input.command === "loginctl" && input.args[0] === "show-user"
184 ? `${control.linger}\n`
185 : input.args[1] === "is-enabled"
186 ? control.enabled
187 ? "enabled\n"
188 : "disabled\n"
189 : "",
190 stderr: "",
191 code: ChildProcessSpawner.ExitCode(
192 failed ||
193 (input.args[1] === "is-active" && !control.active) ||
194 (input.args[1] === "is-enabled" && !control.enabled)
195 ? 1
196 : 0,
197 ),
198 timedOut: false,
199 stdoutTruncated: false,
200 stderrTruncated: false,
201 stdoutInvalidUtf8: false,
202 stderrInvalidUtf8: false,
203 };
204 }),
205 });
206 const makeService = (
207 environmentPath: string | undefined = installerPath,
208 cliVersion = "1.2.3",
209 serviceBaseDir = baseDir,
210 insideService = false,
211 ) =>
212 Effect.gen(function* () {
213 const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform);
214 yield* fs.makeDirectory(path.dirname(paths.entryPath), { recursive: true });
215 yield* fs.writeFileString(paths.entryPath, "#!/bin/sh\n");
216 yield* fs.writeFileString(paths.sentinelPath, `${cliVersion}\n`);
217 return yield* BootService.make({
218 baseDir: serviceBaseDir,
219 logsDir: path.join(serviceBaseDir, "userdata", "logs"),
220 cliVersion,
221 host: { execPath: "/usr/bin/t3" },
222 });
223 }).pipe(
224 Effect.provideService(ProcessRunner.ProcessRunner, runner),
225 Effect.provide(
226 Layer.mergeAll(
227 Layer.succeed(HostProcess.Platform, platform),
228 Layer.succeed(HostProcess.UserId, 501),
229 Layer.succeed(HostProcess.ExecutablePath, "/usr/bin/t3"),
230 Layer.succeed(
231 HttpClient.HttpClient,
232 HttpClient.make(() => Effect.die("no release download expected")),
233 ),
234 ConfigProvider.layer(
235 ConfigProvider.fromEnv({
236 env: {
237 HOME: home,
238 ...(environmentPath === undefined || environmentPath === ""
239 ? {}
240 : { PATH: environmentPath }),
241 ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
242 },
243 }),
244 ),
245 ),
246 ),
247 );
248 const service = yield* makeService();
249 return { service, makeService, fs, statePath, commands, invocations, timeouts, control, runtime };
250});
251
252it.layer(NodeServices.layer)("boot service install", (it) => {
253 it.effect(
254 "fails before installing files or validating a runtime when lingering needs an administrator",
255 () =>
256 Effect.gen(function* () {
257 const { service, fs, statePath, commands, control, runtime } = yield* makeHarness();
258 const before = yield* service.status;
259 control.linger = "no";
260 control.failCommand = "loginctl enable-linger --no-ask-password 501";
261 yield* fs.remove(runtime.sentinelPath);
262
263 const error = yield* service.install().pipe(Effect.flip);
264
265 expect(error).toMatchObject({
266 _tag: "BootServicePrerequisiteError",
267 problem: "linger-disabled",
268 });
269 expect(error.message).toContain('sudo loginctl enable-linger "$(id -un)"');
270 expect(error.message).toContain("last login session ends");
271 expect(yield* fs.exists(before.unitPath)).toBe(false);
272 expect(yield* fs.exists(statePath)).toBe(false);
273 expect(commands.some((command) => command.includes("--version"))).toBe(false);
274 expect(
275 commands.some(
276 (command) => command.includes("daemon-reload") || command.includes("restart"),
277 ),
278 ).toBe(false);
279 expect(yield* fs.readFileString(before.logPath)).toContain("[linger-disabled]");
280 }),
281 );
282
283 it.effect(
284 "detects a partial install and preserves the running service when repair lacks permission",
285 () =>
286 Effect.gen(function* () {
287 const { service, fs, statePath, commands, control } = yield* makeHarness();
288 const plan = yield* service.install();
289 const before = yield* fs.readFileString(statePath);
290 const unit = yield* fs.readFileString(plan.unitPath);
291 control.linger = "no";
292 control.failCommand = "loginctl enable-linger --no-ask-password 501";
293
294 expect(yield* service.status).toMatchObject({
295 current: false,
296 problems: ["linger-disabled"],
297 });
298 commands.length = 0;
299 expect((yield* service.install().pipe(Effect.flip))._tag).toBe(
300 "BootServicePrerequisiteError",
301 );
302 expect(yield* fs.readFileString(statePath)).toBe(before);
303 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
304 expect(commands).not.toContain("systemctl --user stop t3code.service");
305 }),
306 );
307
308 it.effect("enables lingering before installing and repairs stopped or disabled services", () =>
309 Effect.gen(function* () {
310 const { service, commands, control } = yield* makeHarness();
311 control.linger = "no";
312 yield* service.install();
313 expect(control.linger).toBe("yes");
314 expect(commands.indexOf("loginctl enable-linger --no-ask-password 501")).toBeLessThan(
315 commands.indexOf("systemctl --user daemon-reload"),
316 );
317
318 control.enabled = false;
319 control.active = false;
320 expect(yield* service.status).toMatchObject({
321 current: false,
322 problems: ["service-disabled", "service-stopped"],
323 });
324 yield* service.install();
325 expect((yield* service.status).current).toBe(true);
326 }),
327 );
328
329 it.effect.each([
330 { command: "systemctl --user show-environment", problem: "user-manager-unavailable" },
331 { command: "loginctl show-user 501 --property=Linger --value", problem: "linger-unavailable" },
332 ])("reports failed prerequisite probes without installing: $command", ({ command, problem }) =>
333 Effect.gen(function* () {
334 const { service, fs, statePath, control } = yield* makeHarness();
335 control.failCommand = command;
336 expect(yield* service.install().pipe(Effect.flip)).toMatchObject({
337 _tag: "BootServicePrerequisiteError",
338 problem,
339 });
340 expect(yield* fs.exists(statePath)).toBe(false);
341 }),
342 );
343
344 it.effect("installs, reports current state, and uninstalls", () =>
345 Effect.gen(function* () {
346 const { service, fs, statePath, timeouts, runtime } = yield* makeHarness();
347 const plan = yield* service.install();
348
349 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
350 protocol: SERVICE_LAUNCHER_PROTOCOL,
351 activeVersion: "1.2.3",
352 });
353 expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]);
354 expect(yield* fs.readFileString(plan.unitPath)).toContain(
355 `ExecStart=${runtime.entryPath} __service-launcher`,
356 );
357 expect(yield* service.status).toMatchObject({
358 current: true,
359 installedVersion: "1.2.3",
360 });
361 const pendingState = JSON.stringify({
362 protocol: SERVICE_LAUNCHER_PROTOCOL,
363 activeVersion: "1.2.3",
364 update: {
365 id: "u",
366 fromVersion: "1.2.3",
367 targetVersion: "1.2.4",
368 dbPath: "/tmp/state.sqlite",
369 status: "pending",
370 },
371 });
372 yield* fs.writeFileString(statePath, pendingState);
373 expect((yield* service.status).current).toBe(false);
374 expect(yield* service.uninstall).toBe(true);
375 expect((yield* service.status).installed).toBe(false);
376 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
377 // 60s default would cancel it mid-shutdown.
378 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
379 Duration.seconds(120),
380 );
381 }),
382 );
383
384 it.effect.each(["linux", "darwin"] as const)(
385 "reports the installed version across launcher protocols on %s",
386 (platform) =>
387 Effect.gen(function* () {
388 const { service, fs, statePath } = yield* makeHarness(platform);
389 yield* service.install();
390
391 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
392 yield* fs.writeFileString(
393 statePath,
394 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
395 );
396 expect(yield* service.status).toMatchObject({
397 current: false,
398 installedVersion: "1.2.4-nightly.1",
399 });
400 }
401 }),
402 );
403
404 it.effect("reports an unknown version for invalid service state", () =>
405 Effect.gen(function* () {
406 const { service, fs, statePath } = yield* makeHarness();
407 yield* service.install();
408
409 for (const stateText of [
410 "{",
411 '{"activeVersion":"latest"}',
412 '{"activeVersion":"1.2"}',
413 '{"activeVersion":123}',
414 ]) {
415 yield* fs.writeFileString(statePath, stateText);
416 const status = yield* service.status;
417 expect(status.current).toBe(false);
418 expect(status.installedVersion).toBeUndefined();
419 }
420 }),
421 );
422
423 it.effect.each(["linux", "darwin"] as const)(
424 "preserves a newer version that finishes updating during stop on %s",
425 (platform) =>
426 Effect.gen(function* () {
427 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
428 const plan = yield* service.install();
429 const unit = yield* fs.readFileString(plan.unitPath);
430 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
431 commands.length = 0;
432
433 const error = yield* service.install().pipe(Effect.flip);
434
435 expect(error).toMatchObject({
436 _tag: "BootServiceDowngradeRefusedError",
437 installedVersion: "1.2.4",
438 targetVersion: "1.2.3",
439 });
440 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
441 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
442 expect(
443 commands.filter(
444 (command) =>
445 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
446 !command.includes("show-environment"),
447 ),
448 ).toEqual(
449 platform === "linux"
450 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
451 : [
452 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
453 `launchctl bootstrap gui/501 ${plan.unitPath}`,
454 ],
455 );
456 }),
457 );
458
459 it.effect("allows an explicit downgrade", () =>
460 Effect.gen(function* () {
461 const { service, fs, statePath } = yield* makeHarness();
462 yield* service.install();
463 yield* fs.writeFileString(
464 statePath,
465 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
466 );
467
468 yield* service.install({ allowDowngrade: true });
469
470 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
471 expect((yield* service.status).current).toBe(true);
472 }),
473 );
474
475 it.effect("repairs versions with equal SemVer precedence without an override", () =>
476 Effect.gen(function* () {
477 const { service, fs, statePath } = yield* makeHarness();
478 yield* service.install();
479 yield* fs.writeFileString(
480 statePath,
481 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
482 );
483
484 yield* service.install();
485
486 expect((yield* service.status).current).toBe(true);
487 }),
488 );
489
490 it.effect("install with start=false rewrites the files and marks a restart pending", () =>
491 Effect.gen(function* () {
492 const { service, fs, statePath, commands, makeService } = yield* makeHarness();
493 yield* service.install();
494 commands.length = 0;
495
496 const newer = yield* makeService(undefined, "1.2.4");
497 const plan = yield* newer.install({ start: false });
498
499 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
500 protocol: SERVICE_LAUNCHER_PROTOCOL,
501 activeVersion: "1.2.4",
502 });
503 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
504 expect(
505 commands.filter(
506 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
507 ),
508 ).toEqual([]);
509 const status = yield* newer.status;
510 expect(status.current).toBe(false);
511 expect(status.problems).toContain("restart-pending");
512
513 commands.length = 0;
514 expect(yield* newer.restart).toBe("restarted");
515 expect((yield* newer.status).problems).not.toContain("restart-pending");
516 expect((yield* newer.status).current).toBe(true);
517 }),
518 );
519
520 it.effect("install with start=false keeps the marker when a later write fails", () =>
521 Effect.gen(function* () {
522 const { service, fs, statePath, makeService } = yield* makeHarness();
523 const path = yield* Path.Path;
524 yield* service.install();
525 const newer = yield* makeService(undefined, "1.2.4");
526 const unitPath = (yield* service.status).unitPath;
527 yield* fs.remove(unitPath);
528 yield* fs.makeDirectory(unitPath);
529 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
530
531 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
532 expect(error._tag).toBe("BootServiceInstallError");
533 expect(
534 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
535 ).toBe(true);
536 }),
537 );
538
539 it.effect("install with start=false refuses while a remote update is pending", () =>
540 Effect.gen(function* () {
541 const { service, fs, statePath } = yield* makeHarness();
542 yield* service.install();
543 const pendingState = JSON.stringify({
544 protocol: SERVICE_LAUNCHER_PROTOCOL,
545 activeVersion: "1.2.3",
546 update: {
547 id: "u",
548 fromVersion: "1.2.3",
549 targetVersion: "1.2.4",
550 dbPath: "/tmp/state.sqlite",
551 status: "pending",
552 },
553 });
554 yield* fs.writeFileString(statePath, pendingState);
555
556 const error = yield* service.install({ start: false }).pipe(Effect.flip);
557 expect(error._tag).toBe("BootServiceUpdatePendingError");
558 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
559 }),
560 );
561
562 it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
563 Effect.gen(function* () {
564 const { service, commands, control, makeService } = yield* makeHarness();
565 yield* service.install();
566 const failure = yield* service
567 .withStopped(
568 Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
569 )
570 .pipe(Effect.flip);
571 expect(failure).toBe("repair failed");
572 expect(control.active).toBe(true);
573
574 // A failed stop skips the operation but still starts the service again.
575 control.failCommand = "systemctl --user stop t3code.service";
576 let ran = false;
577 const stopFailure = yield* service
578 .withStopped(
579 Effect.sync(() => {
580 ran = true;
581 }),
582 )
583 .pipe(Effect.flip);
584 expect(stopFailure).toMatchObject({
585 _tag: "BootServiceCommandError",
586 step: "stopping the installed service",
587 });
588 expect(ran).toBe(false);
589 expect(control.active).toBe(true);
590 control.failCommand = undefined;
591
592 // An enabled unit that is not active (crash-looping in auto-restart, say)
593 // is still stopped for the repair and started again afterwards.
594 control.active = false;
595 commands.length = 0;
596 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
597 expect(commands).toEqual([
598 "systemctl --user is-enabled t3code.service",
599 "systemctl --user is-active t3code.service",
600 "systemctl --user stop t3code.service",
601 "repair",
602 "systemctl --user restart t3code.service",
603 ]);
604 expect(control.active).toBe(true);
605 // A running unit the user disabled is started again but stays disabled.
606 control.enabled = false;
607 yield* service.withStopped(Effect.void);
608 expect(control).toMatchObject({ active: true, enabled: false });
609 // A unit that was neither enabled nor active stays stopped.
610 control.active = false;
611 control.enabled = false;
612 commands.length = 0;
613 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
614 expect(commands).toContain("systemctl --user stop t3code.service");
615 expect(commands).not.toContain("systemctl --user restart t3code.service");
616 expect(control.active).toBe(false);
617 control.enabled = true;
618 control.active = true;
619
620 const fs = yield* FileSystem.FileSystem;
621 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
622 const other = yield* makeService(undefined, "1.2.3", otherHome);
623 commands.length = 0;
624 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
625 expect(commands).toEqual([]);
626 }),
627 );
628
629 it.effect("restart stops and starts an installed service, and is a no-op otherwise", () =>
630 Effect.gen(function* () {
631 const { service, commands } = yield* makeHarness();
632 expect(yield* service.restart).toBe("skipped");
633 yield* service.install();
634 commands.length = 0;
635
636 expect(yield* service.restart).toBe("restarted");
637 expect(
638 commands.filter(
639 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
640 ),
641 ).toEqual([
642 "systemctl --user stop t3code.service",
643 "systemctl --user daemon-reload",
644 "systemctl --user enable t3code.service",
645 "systemctl --user restart t3code.service",
646 ]);
647 }),
648 );
649
650 it.effect("restart leaves a service that serves another T3 home alone", () =>
651 Effect.gen(function* () {
652 const { service, fs, commands, makeService } = yield* makeHarness();
653 yield* service.install();
654 commands.length = 0;
655 const path = yield* Path.Path;
656 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
657
658 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
659 expect(yield* other.restart).toBe("skipped");
660 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
661 }),
662 );
663
664 it.effect("restart brings the service back when activation fails", () =>
665 Effect.gen(function* () {
666 const { service, commands, control } = yield* makeHarness();
667 yield* service.install();
668 commands.length = 0;
669 control.failCommand = "systemctl --user daemon-reload";
670
671 const error = yield* service.restart.pipe(Effect.flip);
672 expect(error._tag).toBe("BootServiceCommandError");
673 expect(
674 commands.filter(
675 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
676 ),
677 ).toEqual([
678 "systemctl --user stop t3code.service",
679 "systemctl --user daemon-reload",
680 "systemctl --user restart t3code.service",
681 ]);
682 }),
683 );
684
685 it.effect("hands the whole install to systemd without changing the running service", () =>
686 Effect.gen(function* () {
687 const { fs, commands, invocations, control, makeService } = yield* makeHarness();
688 const path = yield* Path.Path;
689 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
690 const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
691 const outside = yield* makeService(undefined, "1.2.3", baseDir);
692 const plan = yield* outside.install();
693 const statePath = path.join(baseDir, "runtime", "service-state.json");
694 const state = yield* fs.readFileString(statePath);
695 const unit = yield* fs.readFileString(plan.unitPath);
696 const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
697 commands.length = 0;
698 invocations.length = 0;
699
700 const result = yield* inside.install({ allowDowngrade: true });
701
702 expect(yield* fs.readFileString(statePath)).toBe(state);
703 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
704 expect(commands).not.toContain("systemctl --user stop t3code.service");
705 expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
706 const handoffs = invocations.filter(({ command }) => command === "systemd-run");
707 expect(handoffs).toHaveLength(1);
708 expect(handoffs[0]?.args).toEqual([
709 "--user",
710 "--collect",
711 "--quiet",
712 `--property=StandardOutput=append:${plan.logPath}`,
713 `--property=StandardError=append:${plan.logPath}`,
714 "--setenv=T3_BOOT_SERVICE_UNIT=",
715 pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
716 "service",
717 "install",
718 "--base-dir",
719 path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
720 "--allow-downgrade",
721 ]);
722
723 const handoff = handoffs[0]!;
724 control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
725 const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
726 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
727 expect(yield* fs.readFileString(statePath)).toBe(state);
728 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
729 expect(control.active).toBe(true);
730 expect(commands).not.toContain("systemctl --user stop t3code.service");
731 }),
732 );
733
734 it.effect(
735 "queues an in-service restart without stopping the caller, even on handoff failure",
736 () =>
737 Effect.gen(function* () {
738 const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();
739 const plan = yield* service.install();
740 const state = yield* fs.readFileString(statePath);
741 const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
742 yield* fs.writeFileString(marker, "1.2.3\n");
743 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
744 commands.length = 0;
745 control.failCommand = "systemctl --user daemon-reload";
746
747 const error = yield* inside.restart.pipe(Effect.flip);
748 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
749 expect(commands).toEqual(["systemctl --user daemon-reload"]);
750 expect(control.active).toBe(true);
751
752 control.failCommand = undefined;
753 commands.length = 0;
754 const outcome = yield* inside.restart;
755 expect(commands).toEqual([
756 "systemctl --user daemon-reload",
757 "systemctl --user enable t3code.service",
758 "systemctl --user restart --no-block t3code.service",
759 ]);
760 expect(outcome).toBe("queued");
761 expect(yield* fs.readFileString(statePath)).toBe(state);
762 expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
763 }),
764 );
765
766 it.effect("restarts an installed service when repair fails", () =>
767 Effect.gen(function* () {
768 const { service, commands, control } = yield* makeHarness();
769 yield* service.install();
770 commands.length = 0;
771 control.failCommand = "systemctl --user daemon-reload";
772
773 const error = yield* service.install().pipe(Effect.flip);
774 expect(error._tag).toBe("BootServiceCommandError");
775 expect(
776 commands.filter(
777 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
778 ),
779 ).toEqual([
780 "systemctl --user stop t3code.service",
781 "systemctl --user daemon-reload",
782 "systemctl --user restart t3code.service",
783 ]);
784 }),
785 );
786
787 it.effect("restarts without overwriting a pending remote update", () =>
788 Effect.gen(function* () {
789 const { service, fs, statePath, commands } = yield* makeHarness();
790 yield* service.install();
791 const pendingState = JSON.stringify({
792 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
793 activeVersion: "1.2.3",
794 update: {
795 id: "remote-update",
796 fromVersion: "1.2.3",
797 targetVersion: "1.2.4",
798 status: "pending",
799 },
800 });
801 yield* fs.writeFileString(statePath, pendingState);
802 for (const allowDowngrade of [false, true]) {
803 commands.length = 0;
804
805 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
806 "BootServiceUpdatePendingError",
807 );
808 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
809 expect(
810 commands.filter(
811 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
812 ),
813 ).toEqual([
814 "systemctl --user stop t3code.service",
815 "systemctl --user restart t3code.service",
816 ]);
817 }
818 }),
819 );
820
821 it.effect("fails closed on Windows", () =>
822 Effect.gen(function* () {
823 const { service } = yield* makeHarness("win32");
824 expect((yield* service.status).supported).toBe(false);
825 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
826 }),
827 );
828
829 it.effect("installs, reports current state, and uninstalls on macOS", () =>
830 Effect.gen(function* () {
831 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
832 const path = yield* Path.Path;
833 const plan = yield* service.install();
834
835 expect(
836 plan.unitPath.endsWith(
837 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
838 ),
839 ).toBe(true);
840 expect(yield* fs.readFileString(plan.unitPath)).toContain(
841 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
842 );
843 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
844 protocol: SERVICE_LAUNCHER_PROTOCOL,
845 activeVersion: "1.2.3",
846 });
847 expect(yield* fs.readFileString(plan.unitPath)).toContain(
848 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
849 );
850 expect(yield* service.status).toMatchObject({
851 current: true,
852 installedVersion: "1.2.3",
853 });
854 expect(yield* service.uninstall).toBe(true);
855 expect((yield* service.status).installed).toBe(false);
856 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
857 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
858 // 60s default would cancel it and let bootstrap race a loaded job.
859 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
860 Duration.seconds(120),
861 );
862 }),
863 );
864
865 it.effect("restarts the launch agent when repair fails", () =>
866 Effect.gen(function* () {
867 const { service, commands, control } = yield* makeHarness("darwin");
868 yield* service.install();
869 const plistPath = (yield* service.status).unitPath;
870 commands.length = 0;
871 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
872
873 const error = yield* service.install().pipe(Effect.flip);
874 expect(error._tag).toBe("BootServiceCommandError");
875 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
876 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
877 "launchctl enable gui/501/com.t3tools.t3code.service",
878 `launchctl bootstrap gui/501 ${plistPath}`,
879 `launchctl bootstrap gui/501 ${plistPath}`,
880 ]);
881 }),
882 );
883
884 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
885 Effect.gen(function* () {
886 const { service, fs } = yield* makeHarness("darwin", "");
887 const plan = yield* service.install();
888
889 expect(yield* fs.readFileString(plan.unitPath)).toContain(
890 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
891 );
892 expect((yield* service.status).current).toBe(true);
893 }),
894 );
895
896 it.effect("adds missing provider directories to a minimal installer PATH", () =>
897 Effect.gen(function* () {
898 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
899 const plan = yield* service.install();
900
901 expect(yield* fs.readFileString(plan.unitPath)).toContain(
902 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
903 );
904 expect((yield* service.status).current).toBe(true);
905 }),
906 );
907
908 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
909 Effect.gen(function* () {
910 const { service, makeService } = yield* makeHarness("darwin");
911 yield* service.install();
912
913 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
914 expect((yield* restartedService.status).current).toBe(true);
915 }),
916 );
917
918 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
919 Effect.gen(function* () {
920 const { service, fs } = yield* makeHarness(
921 "darwin",
922 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
923 );
924 const plan = yield* service.install();
925 const plist = yield* fs.readFileString(plan.unitPath);
926
927 expect(plist).toContain(
928 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
929 );
930 expect(plist).not.toContain("\u0001");
931 expect((yield* service.status).current).toBe(true);
932 }),
933 );
934
935 it.effect("ignores a bootout for an agent that is not loaded", () =>
936 Effect.gen(function* () {
937 const { service, control } = yield* makeHarness("darwin");
938 yield* service.install();
939 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
940
941 yield* service.install();
942 expect((yield* service.status).current).toBe(true);
943 }),
944 );
945
946 it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
947 Effect.gen(function* () {
948 const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
949 const path = yield* Path.Path;
950 const plan = yield* service.install();
951 const markerPath = path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE);
952 const bootstrap = `launchctl bootstrap gui/501 ${plan.unitPath}`;
953 control.failCommand = bootstrap;
954
955 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
956 expect(yield* service.status).toMatchObject({
957 current: false,
958 problems: ["restart-pending"],
959 });
960 expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n");
961
962 control.failCommand = undefined;
963 commands.length = 0;
964 yield* service.install();
965
966 expect(commands).toContain(bootstrap);
967 expect(yield* fs.exists(markerPath)).toBe(false);
968 expect((yield* service.status).current).toBe(true);
969 }),
970 );
971
972 it.effect("restarts without overwriting a pending remote update on macOS", () =>
973 Effect.gen(function* () {
974 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
975 yield* service.install();
976 const plistPath = (yield* service.status).unitPath;
977 const pendingState = JSON.stringify({
978 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
979 activeVersion: "1.2.3",
980 update: {
981 id: "remote-update",
982 fromVersion: "1.2.3",
983 targetVersion: "1.2.4",
984 status: "pending",
985 },
986 });
987 yield* fs.writeFileString(statePath, pendingState);
988 for (const allowDowngrade of [false, true]) {
989 commands.length = 0;
990
991 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
992 "BootServiceUpdatePendingError",
993 );
994 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
995 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
996 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
997 `launchctl bootstrap gui/501 ${plistPath}`,
998 ]);
999 }
1000 }),
1001 );
1002});