Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as ConfigProvider from "effect/ConfigProvider";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import { HttpClient } from "effect/http";
11import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13import * as ProcessRunner from "../processRunner.ts";
14import * as BootService from "./bootService.ts";
15import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
16import {
17 parseServiceState,
18 SERVICE_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 timed-out stop may still stop 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 // systemd can take 90s to stop, exceeding the runner's 60s default.
331 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
332 Duration.seconds(120),
333 );
334 }),
335 );
336
337 it.effect.each(["linux", "darwin"] as const)(
338 "reports the installed version across launcher protocols on %s",
339 (platform) =>
340 Effect.gen(function* () {
341 const { service, fs, statePath } = yield* makeHarness(platform);
342 yield* service.install();
343
344 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
345 yield* fs.writeFileString(
346 statePath,
347 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
348 );
349 expect(yield* service.status).toMatchObject({
350 current: false,
351 installedVersion: "1.2.4-nightly.1",
352 });
353 }
354 }),
355 );
356
357 // regression: #5302 prevent accidental service downgrades
358 it.effect("reports an unknown version for invalid service state", () =>
359 Effect.gen(function* () {
360 const { service, fs, statePath } = yield* makeHarness();
361 yield* service.install();
362
363 for (const stateText of [
364 "{",
365 '{"activeVersion":"latest"}',
366 '{"activeVersion":"1.2"}',
367 '{"activeVersion":123}',
368 ]) {
369 yield* fs.writeFileString(statePath, stateText);
370 const status = yield* service.status;
371 expect(status.current).toBe(false);
372 expect(status.installedVersion).toBeUndefined();
373 }
374 }),
375 );
376
377 it.effect.each(["linux", "darwin"] as const)(
378 "preserves a newer version that finishes updating during stop on %s",
379 (platform) =>
380 Effect.gen(function* () {
381 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
382 const plan = yield* service.install();
383 const unit = yield* fs.readFileString(plan.unitPath);
384 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
385 commands.length = 0;
386
387 const error = yield* service.install().pipe(Effect.flip);
388
389 expect(error).toMatchObject({
390 _tag: "BootServiceDowngradeRefusedError",
391 installedVersion: "1.2.4",
392 targetVersion: "1.2.3",
393 });
394 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
395 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
396 expect(
397 commands.filter(
398 (command) =>
399 command.startsWith(platform === "linux" ? "systemctl " : "launchctl ") &&
400 !command.includes("show-environment"),
401 ),
402 ).toEqual(
403 platform === "linux"
404 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
405 : [
406 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
407 `launchctl bootstrap gui/501 ${plan.unitPath}`,
408 ],
409 );
410 }),
411 );
412
413 // regression: #5302 prevent accidental service downgrades
414 it.effect("allows an explicit downgrade", () =>
415 Effect.gen(function* () {
416 const { service, fs, statePath } = yield* makeHarness();
417 yield* service.install();
418 yield* fs.writeFileString(
419 statePath,
420 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
421 );
422
423 yield* service.install({ allowDowngrade: true });
424
425 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
426 expect((yield* service.status).current).toBe(true);
427 }),
428 );
429
430 it.effect("repairs versions with equal SemVer precedence without an override", () =>
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.3+previous-build"}`,
437 );
438
439 yield* service.install();
440
441 expect((yield* service.status).current).toBe(true);
442 }),
443 );
444
445 it.effect.each(["linux", "darwin"] as const)(
446 "install with start=false rewrites files, preserves service.env, and marks a restart pending on %s",
447 (platform) =>
448 Effect.gen(function* () {
449 const { service, fs, baseDir, statePath, commands, makeService } =
450 yield* makeHarness(platform);
451 const path = yield* Path.Path;
452 const envPath = path.join(baseDir, SERVICE_ENV_FILE);
453 const envBytes = new TextEncoder().encode(
454 '# user configuration\r\nT3CODE_TOKEN="literal $HOME # token"',
455 );
456 yield* fs.writeFile(envPath, envBytes);
457 yield* service.install();
458 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
459 yield* service.install();
460 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
461 commands.length = 0;
462
463 const newer = yield* makeService(undefined, "1.2.4");
464 const plan = yield* newer.install({ start: false });
465 expect(new Uint8Array(yield* fs.readFile(envPath))).toEqual(envBytes);
466
467 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
468 protocol: SERVICE_LAUNCHER_PROTOCOL,
469 activeVersion: "1.2.4",
470 });
471 expect(yield* fs.readFileString(plan.unitPath)).toContain("versions/1.2.4/t3");
472 expect(
473 commands.filter(
474 (command) =>
475 /^(systemctl|launchctl) /.test(command) && !command.includes("show-environment"),
476 ),
477 ).toEqual([]);
478 const status = yield* newer.status;
479 expect(status.current).toBe(false);
480 expect(status.problems).toContain("restart-pending");
481
482 commands.length = 0;
483 expect(yield* newer.restart).toBe("restarted");
484 expect((yield* newer.status).problems).not.toContain("restart-pending");
485 expect((yield* newer.status).current).toBe(true);
486 }),
487 );
488
489 it.effect("install with start=false keeps the marker when a later write fails", () =>
490 Effect.gen(function* () {
491 const { service, fs, statePath, makeService } = yield* makeHarness();
492 const path = yield* Path.Path;
493 yield* service.install();
494 const newer = yield* makeService(undefined, "1.2.4");
495 const unitPath = (yield* service.status).unitPath;
496 yield* fs.remove(unitPath);
497 yield* fs.makeDirectory(unitPath);
498 yield* fs.writeFileString(path.join(unitPath, "occupied"), "");
499
500 const error = yield* newer.install({ start: false }).pipe(Effect.flip);
501 expect(error._tag).toBe("BootServiceInstallError");
502 expect(
503 yield* fs.exists(path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE)),
504 ).toBe(true);
505 }),
506 );
507
508 it.effect("install with start=false refuses while a remote update is pending", () =>
509 Effect.gen(function* () {
510 const { service, fs, statePath } = yield* makeHarness();
511 yield* service.install();
512 const pendingState = JSON.stringify({
513 protocol: SERVICE_LAUNCHER_PROTOCOL,
514 activeVersion: "1.2.3",
515 update: {
516 id: "u",
517 fromVersion: "1.2.3",
518 targetVersion: "1.2.4",
519 dbPath: "/tmp/state.sqlite",
520 status: "pending",
521 },
522 });
523 yield* fs.writeFileString(statePath, pendingState);
524
525 const error = yield* service.install({ start: false }).pipe(Effect.flip);
526 expect(error._tag).toBe("BootServiceUpdatePendingError");
527 expect(yield* fs.readFileString(statePath)).toBe(pendingState);
528 }),
529 );
530
531 it.effect("pauses only this home's running service for maintenance, even when it fails", () =>
532 Effect.gen(function* () {
533 const { service, commands, control, makeService } = yield* makeHarness();
534 yield* service.install();
535 const failure = yield* service
536 .withStopped(
537 Effect.suspend(() => Effect.fail(control.active ? "running" : "repair failed")),
538 )
539 .pipe(Effect.flip);
540 expect(failure).toBe("repair failed");
541 expect(control.active).toBe(true);
542
543 control.failCommand = "systemctl --user stop t3code.service";
544 let ran = false;
545 const stopFailure = yield* service
546 .withStopped(
547 Effect.sync(() => {
548 ran = true;
549 }),
550 )
551 .pipe(Effect.flip);
552 expect(stopFailure).toMatchObject({
553 _tag: "BootServiceCommandError",
554 step: "stopping the installed service",
555 });
556 expect(ran).toBe(false);
557 expect(control.active).toBe(true);
558 control.failCommand = undefined;
559
560 control.active = false;
561 commands.length = 0;
562 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
563 expect(commands).toEqual([
564 "systemctl --user is-enabled t3code.service",
565 "systemctl --user is-active t3code.service",
566 "systemctl --user stop t3code.service",
567 "repair",
568 "systemctl --user restart t3code.service",
569 ]);
570 expect(control.active).toBe(true);
571 control.enabled = false;
572 yield* service.withStopped(Effect.void);
573 expect(control).toMatchObject({ active: true, enabled: false });
574 control.active = false;
575 control.enabled = false;
576 commands.length = 0;
577 yield* service.withStopped(Effect.sync(() => commands.push("repair")));
578 expect(commands).toContain("systemctl --user stop t3code.service");
579 expect(commands).not.toContain("systemctl --user restart t3code.service");
580 expect(control.active).toBe(false);
581 control.enabled = true;
582 control.active = true;
583
584 const fs = yield* FileSystem.FileSystem;
585 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-doctor-other-" });
586 const other = yield* makeService(undefined, "1.2.3", otherHome);
587 commands.length = 0;
588 expect(yield* other.withStopped(Effect.sync(() => control.active))).toBe(true);
589 expect(commands).toEqual([]);
590 }),
591 );
592
593 it.effect("restart leaves a service that serves another T3 home alone", () =>
594 Effect.gen(function* () {
595 const { service, fs, commands, makeService } = yield* makeHarness();
596 yield* service.install();
597 commands.length = 0;
598 const path = yield* Path.Path;
599 const otherHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-other-home-" });
600
601 const other = yield* makeService(undefined, "1.2.3", path.join(otherHome, ".t3"));
602 expect(yield* other.restart).toBe("skipped");
603 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([]);
604 }),
605 );
606
607 it.effect("hands the whole install to systemd without changing the running service", () =>
608 Effect.gen(function* () {
609 const { fs, commands, invocations, control, makeService } = yield* makeHarness();
610 const path = yield* Path.Path;
611 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-handoff-" });
612 const baseDir = path.join(home, "T3 Data 100%", "${UNSET}", "$literal");
613 const outside = yield* makeService(undefined, "1.2.3", baseDir);
614 const plan = yield* outside.install();
615 const statePath = path.join(baseDir, "runtime", "service-state.json");
616 const state = yield* fs.readFileString(statePath);
617 const unit = yield* fs.readFileString(plan.unitPath);
618 const inside = yield* makeService(undefined, "1.2.4", baseDir, true);
619 commands.length = 0;
620 invocations.length = 0;
621
622 const result = yield* inside.install({ allowDowngrade: true });
623
624 expect(yield* fs.readFileString(statePath)).toBe(state);
625 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
626 expect(commands).not.toContain("systemctl --user stop t3code.service");
627 expect(result).toMatchObject({ handedOff: true, logPath: plan.logPath });
628 const handoffs = invocations.filter(({ command }) => command === "systemd-run");
629 expect(handoffs).toHaveLength(1);
630 expect(handoffs[0]?.args).toEqual([
631 "--user",
632 "--collect",
633 "--quiet",
634 `--property=StandardOutput=append:${plan.logPath}`,
635 `--property=StandardError=append:${plan.logPath}`,
636 "--setenv=T3_BOOT_SERVICE_UNIT=",
637 pinnedRuntimePaths(path, baseDir, "1.2.4", "linux").entryPath,
638 "service",
639 "install",
640 "--base-dir",
641 path.join(home, "T3 Data 100%", "$${UNSET}", "$$literal"),
642 "--allow-downgrade",
643 ]);
644
645 const handoff = handoffs[0]!;
646 control.failCommand = `${handoff.command} ${handoff.args.join(" ")}`;
647 const error = yield* inside.install({ allowDowngrade: true }).pipe(Effect.flip);
648 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
649 expect(yield* fs.readFileString(statePath)).toBe(state);
650 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
651 expect(control.active).toBe(true);
652 expect(commands).not.toContain("systemctl --user stop t3code.service");
653 }),
654 );
655
656 it.effect(
657 "queues an in-service restart without stopping the caller, even on handoff failure",
658 () =>
659 Effect.gen(function* () {
660 const { service, fs, statePath, commands, control, makeService } = yield* makeHarness();
661 const plan = yield* service.install();
662 const state = yield* fs.readFileString(statePath);
663 const marker = `${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`;
664 yield* fs.writeFileString(marker, "1.2.3\n");
665 const inside = yield* makeService(undefined, "1.2.3", undefined, true);
666 commands.length = 0;
667 control.failCommand = "systemctl --user daemon-reload";
668
669 const error = yield* inside.restart.pipe(Effect.flip);
670 expect(error).toMatchObject({ _tag: "BootServiceCommandError", exitCode: 1 });
671 expect(commands).toEqual(["systemctl --user daemon-reload"]);
672 expect(control.active).toBe(true);
673
674 control.failCommand = undefined;
675 commands.length = 0;
676 const outcome = yield* inside.restart;
677 expect(commands).toEqual([
678 "systemctl --user daemon-reload",
679 "systemctl --user enable t3code.service",
680 "systemctl --user restart --no-block t3code.service",
681 ]);
682 expect(outcome).toBe("queued");
683 expect(yield* fs.readFileString(statePath)).toBe(state);
684 expect(yield* fs.readFileString(marker)).toBe("1.2.3\n");
685 }),
686 );
687
688 it.effect("restarts an installed service when repair fails", () =>
689 Effect.gen(function* () {
690 const { service, commands, control } = yield* makeHarness();
691 yield* service.install();
692 commands.length = 0;
693 control.failCommand = "systemctl --user daemon-reload";
694
695 const error = yield* service.install().pipe(Effect.flip);
696 expect(error._tag).toBe("BootServiceCommandError");
697 expect(
698 commands.filter(
699 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
700 ),
701 ).toEqual([
702 "systemctl --user stop t3code.service",
703 "systemctl --user daemon-reload",
704 "systemctl --user restart t3code.service",
705 ]);
706 }),
707 );
708
709 it.effect("restarts without overwriting a pending remote update", () =>
710 Effect.gen(function* () {
711 const { service, fs, statePath, commands } = yield* makeHarness();
712 yield* service.install();
713 const pendingState = JSON.stringify({
714 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
715 activeVersion: "1.2.3",
716 update: {
717 id: "remote-update",
718 fromVersion: "1.2.3",
719 targetVersion: "1.2.4",
720 status: "pending",
721 },
722 });
723 yield* fs.writeFileString(statePath, pendingState);
724 for (const allowDowngrade of [false, true]) {
725 commands.length = 0;
726
727 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
728 "BootServiceUpdatePendingError",
729 );
730 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
731 expect(
732 commands.filter(
733 (command) => command.startsWith("systemctl ") && !command.includes("show-environment"),
734 ),
735 ).toEqual([
736 "systemctl --user stop t3code.service",
737 "systemctl --user restart t3code.service",
738 ]);
739 }
740 }),
741 );
742
743 it.effect("installs, reports current state, and uninstalls on macOS", () =>
744 Effect.gen(function* () {
745 const { service, fs, statePath, commands, timeouts, runtime } = yield* makeHarness("darwin");
746 const path = yield* Path.Path;
747 const plan = yield* service.install();
748
749 expect(
750 plan.unitPath.endsWith(
751 path.join("Library", "LaunchAgents", "com.t3tools.t3code.service.plist"),
752 ),
753 ).toBe(true);
754 expect(yield* fs.readFileString(plan.unitPath)).toContain(
755 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
756 );
757 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
758 protocol: SERVICE_LAUNCHER_PROTOCOL,
759 activeVersion: "1.2.3",
760 });
761 expect(yield* fs.readFileString(plan.unitPath)).toContain(
762 ` <string>${runtime.entryPath}</string>\n <string>__service-launcher</string>`,
763 );
764 expect(yield* service.status).toMatchObject({
765 current: true,
766 installedVersion: "1.2.3",
767 });
768 expect(yield* service.uninstall).toBe(true);
769 expect((yield* service.status).installed).toBe(false);
770 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
771 // launchd can take 90s to bootout; the runner's 60s default could let bootstrap race it.
772 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
773 Duration.seconds(120),
774 );
775 }),
776 );
777
778 // regression: #8173 keep provider CLIs available in the macOS service
779 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
780 Effect.gen(function* () {
781 const { service, fs } = yield* makeHarness("darwin", "");
782 const plan = yield* service.install();
783
784 expect(yield* fs.readFileString(plan.unitPath)).toContain(
785 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
786 );
787 expect((yield* service.status).current).toBe(true);
788 }),
789 );
790
791 it.effect("adds missing provider directories to a minimal installer PATH", () =>
792 Effect.gen(function* () {
793 const { service, fs } = yield* makeHarness("darwin", "/usr/bin:/bin");
794 const plan = yield* service.install();
795
796 expect(yield* fs.readFileString(plan.unitPath)).toContain(
797 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
798 );
799 expect((yield* service.status).current).toBe(true);
800 }),
801 );
802
803 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
804 Effect.gen(function* () {
805 const { service, makeService } = yield* makeHarness("darwin");
806 yield* service.install();
807
808 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
809 expect((yield* restartedService.status).current).toBe(true);
810 }),
811 );
812
813 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
814 Effect.gen(function* () {
815 const { service, fs } = yield* makeHarness(
816 "darwin",
817 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
818 );
819 const plan = yield* service.install();
820 const plist = yield* fs.readFileString(plan.unitPath);
821
822 expect(plist).toContain(
823 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
824 );
825 expect(plist).not.toContain("\u0001");
826 expect((yield* service.status).current).toBe(true);
827 }),
828 );
829
830 it.effect("ignores a bootout for an agent that is not loaded", () =>
831 Effect.gen(function* () {
832 const { service, control } = yield* makeHarness("darwin");
833 yield* service.install();
834 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
835
836 yield* service.install();
837 expect((yield* service.status).current).toBe(true);
838 }),
839 );
840
841 it.effect("keeps failed launch agent installs pending until activation succeeds", () =>
842 Effect.gen(function* () {
843 const { service, fs, statePath, commands, control } = yield* makeHarness("darwin");
844 const path = yield* Path.Path;
845 const plan = yield* service.install();
846 const markerPath = path.join(path.dirname(statePath), SERVICE_RESTART_PENDING_FILE);
847 const bootstrap = `launchctl bootstrap gui/501 ${plan.unitPath}`;
848 control.failCommand = bootstrap;
849
850 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
851 expect(yield* service.status).toMatchObject({
852 current: false,
853 problems: ["restart-pending"],
854 });
855 expect(yield* fs.readFileString(markerPath)).toBe("1.2.3\n");
856
857 control.failCommand = undefined;
858 commands.length = 0;
859 yield* service.install();
860
861 expect(commands).toContain(bootstrap);
862 expect(yield* fs.exists(markerPath)).toBe(false);
863 expect((yield* service.status).current).toBe(true);
864 }),
865 );
866});