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