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

bootService.test.ts

887 lines34.3 KB

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