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

bootService.test.ts

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