Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessArguments,
5 HostProcessExecutablePath,
6 HostProcessPlatform,
7 HostProcessUserId,
8} from "@t3tools/shared/hostProcess";
9import * as ConfigProvider from "effect/ConfigProvider";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
16
17import * as ProcessRunner from "../processRunner.ts";
18import * as BootService from "./bootService.ts";
19import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
20import {
21 parseServiceState,
22 SERVICE_LAUNCHER_PROTOCOL,
23 serviceStateHasPendingUpdate,
24} from "./serviceProtocol.ts";
25
26it("keeps systemd pinned to the stable launcher rather than a versioned server", () => {
27 const unit = BootService.renderBootServiceUnit({
28 nodePath: "/usr/bin/node",
29 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
30 baseDir: "/home/theo/.t3",
31 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
32 unitPath: "/home/theo/.config/systemd/user/t3code.service",
33 });
34
35 expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
36 expect(unit).toContain("KillMode=mixed");
37 expect(unit).not.toContain("versions/1.2.3");
38});
39
40it("survives the kernel OOM-killing a greedy agent child", () => {
41 const unit = BootService.renderBootServiceUnit({
42 nodePath: "/usr/bin/node",
43 launcherPath: "/home/theo/.t3/runtime/service-launcher.mjs",
44 baseDir: "/home/theo/.t3",
45 logPath: "/home/theo/.t3/userdata/logs/boot-service.log",
46 unitPath: "/home/theo/.config/systemd/user/t3code.service",
47 });
48
49 expect(unit).toContain("OOMPolicy=continue");
50});
51
52const macPlan = {
53 nodePath: "/opt/homebrew/bin/node",
54 launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
55 baseDir: "/Users/theo/.t3",
56 logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
57 unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
58};
59const macInstallerPath =
60 "/opt/homebrew/bin:/Users/theo/.npm-global/bin:/Users/theo/.nvm/versions/node/v22.16.0/bin:/usr/bin:/bin";
61const macRenderOptions = { homeDir: "/Users/theo", environmentPath: macInstallerPath };
62
63it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
64 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
65
66 expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
67 expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
68 expect(plist).not.toContain("versions/1.2.3");
69});
70
71it("preserves the installer's provider search path in the launch agent", () => {
72 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
73
74 expect(plist).toContain(` <key>PATH</key>\n <string>${macInstallerPath}</string>`);
75});
76
77it("restarts the launch agent on the systemd cadence", () => {
78 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
79
80 expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
81 expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
82 expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
83 expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
84});
85
86it("appends both stdio streams to the boot service log", () => {
87 const plist = BootService.renderBootServicePlist(macPlan, macRenderOptions);
88
89 expect(plist).toContain(
90 "<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
91 );
92 expect(plist).toContain(
93 "<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
94 );
95});
96
97it("escapes XML in host paths", () => {
98 const plist = BootService.renderBootServicePlist(
99 { ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
100 { homeDir: "/Users/theo", environmentPath: "/Users/theo/Tools & <Scripts>:/usr/bin" },
101 );
102
103 expect(plist).toContain("<string>/Users/theo/T3 & <Co></string>");
104 expect(plist).toContain("<string>/Users/theo/Tools & <Scripts>:/usr/bin</string>");
105});
106
107const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
108 platform: NodeJS.Platform = "linux",
109 usePinnedLauncher = false,
110 installerPath = macInstallerPath,
111) {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-boot-service-test-" });
115 const baseDir = path.join(home, ".t3");
116 const sourceLauncher = path.join(home, "service-launcher.mjs");
117 const statePath = path.join(baseDir, "runtime", "service-state.json");
118 yield* fs.writeFileString(sourceLauncher, "export {};\n");
119 const runtime = pinnedRuntimePaths(path, baseDir, "1.2.3");
120 yield* fs.makeDirectory(path.dirname(runtime.entryPath), { recursive: true });
121 yield* fs.writeFileString(runtime.entryPath, "export {};\n");
122 yield* fs.writeFileString(
123 path.join(path.dirname(runtime.entryPath), "service-launcher.mjs"),
124 "export const source = 'pinned runtime';\n",
125 );
126 yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
127
128 const commands: string[] = [];
129 const timeouts = new Map<string, unknown>();
130 const control: { failCommand: string | undefined; stateAfterStop?: string } = {
131 failCommand: undefined,
132 };
133 const runner = ProcessRunner.ProcessRunner.of({
134 run: Effect.fn("test.run_boot_service_command")(function* (
135 input: ProcessRunner.ProcessRunInput,
136 ) {
137 const command = `${input.command} ${input.args.join(" ")}`;
138 commands.push(command);
139 timeouts.set(command, input.timeout);
140 if (
141 control.stateAfterStop !== undefined &&
142 (command === "systemctl --user stop t3code.service" ||
143 command.startsWith("launchctl bootout --wait "))
144 ) {
145 yield* fs.writeFileString(statePath, control.stateAfterStop).pipe(Effect.orDie);
146 }
147 return {
148 stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
149 stderr: "",
150 code: ChildProcessSpawner.ExitCode(command === control.failCommand ? 1 : 0),
151 timedOut: false,
152 stdoutTruncated: false,
153 stderrTruncated: false,
154 stdoutInvalidUtf8: false,
155 stderrInvalidUtf8: false,
156 };
157 }),
158 });
159 const makeService = (environmentPath = installerPath) =>
160 BootService.make({
161 baseDir,
162 logsDir: path.join(baseDir, "userdata", "logs"),
163 cliVersion: "1.2.3",
164 host: {
165 execPath: "/usr/bin/node",
166 ...(usePinnedLauncher ? {} : { launcherSourcePath: sourceLauncher }),
167 },
168 }).pipe(
169 Effect.provideService(ProcessRunner.ProcessRunner, runner),
170 Effect.provide(
171 Layer.mergeAll(
172 Layer.succeed(HostProcessPlatform, platform),
173 Layer.succeed(HostProcessUserId, 501),
174 Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
175 Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
176 ConfigProvider.layer(
177 ConfigProvider.fromEnv({
178 env: { HOME: home, ...(environmentPath === "" ? {} : { PATH: environmentPath }) },
179 }),
180 ),
181 ),
182 ),
183 );
184 const service = yield* makeService();
185 return { service, makeService, fs, statePath, commands, timeouts, control };
186});
187
188it.layer(NodeServices.layer)("boot service install", (it) => {
189 it.effect("installs, reports current state, and uninstalls", () =>
190 Effect.gen(function* () {
191 const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
192 const plan = yield* service.install();
193
194 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
195 protocol: SERVICE_LAUNCHER_PROTOCOL,
196 activeVersion: "1.2.3",
197 });
198 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
199 expect(yield* service.status).toMatchObject({
200 current: true,
201 installedVersion: "1.2.3",
202 });
203 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
204 const pendingState = JSON.stringify({
205 protocol: SERVICE_LAUNCHER_PROTOCOL,
206 activeVersion: "1.2.3",
207 update: {
208 id: "u",
209 fromVersion: "1.2.3",
210 targetVersion: "1.2.4",
211 dbPath: "/tmp/state.sqlite",
212 status: "pending",
213 },
214 });
215 yield* fs.writeFileString(statePath, pendingState);
216 expect((yield* service.status).current).toBe(false);
217 expect(yield* service.uninstall).toBe(true);
218 expect((yield* service.status).installed).toBe(false);
219 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
220 // The stop can block up to systemd's 90s TimeoutStopSec; the runner's
221 // 60s default would cancel it mid-shutdown.
222 expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
223 Duration.seconds(120),
224 );
225 }),
226 );
227
228 it.effect.each(["linux", "darwin"] as const)(
229 "reports the installed version across launcher protocols on %s",
230 (platform) =>
231 Effect.gen(function* () {
232 const { service, fs, statePath } = yield* makeHarness(platform);
233 yield* service.install();
234
235 for (const protocol of [SERVICE_LAUNCHER_PROTOCOL - 1, SERVICE_LAUNCHER_PROTOCOL + 1]) {
236 yield* fs.writeFileString(
237 statePath,
238 `{"protocol":${protocol},"activeVersion":"1.2.4-nightly.1","update":{"status":"unknown"}}`,
239 );
240 expect(yield* service.status).toMatchObject({
241 current: false,
242 installedVersion: "1.2.4-nightly.1",
243 });
244 }
245 }),
246 );
247
248 it.effect("reports an unknown version for invalid service state", () =>
249 Effect.gen(function* () {
250 const { service, fs, statePath } = yield* makeHarness();
251 yield* service.install();
252
253 for (const stateText of [
254 "{",
255 '{"activeVersion":"latest"}',
256 '{"activeVersion":"1.2"}',
257 '{"activeVersion":123}',
258 ]) {
259 yield* fs.writeFileString(statePath, stateText);
260 const status = yield* service.status;
261 expect(status.current).toBe(false);
262 expect(status.installedVersion).toBeUndefined();
263 }
264 }),
265 );
266
267 it.effect.each(["linux", "darwin"] as const)(
268 "preserves a newer version that finishes updating during stop on %s",
269 (platform) =>
270 Effect.gen(function* () {
271 const { service, fs, statePath, commands, control } = yield* makeHarness(platform);
272 const plan = yield* service.install();
273 const launcher = yield* fs.readFileString(plan.launcherPath);
274 const unit = yield* fs.readFileString(plan.unitPath);
275 control.stateAfterStop = `{"protocol":${SERVICE_LAUNCHER_PROTOCOL + 1},"activeVersion":"1.2.4"}`;
276 commands.length = 0;
277
278 const error = yield* service.install().pipe(Effect.flip);
279
280 expect(error).toMatchObject({
281 _tag: "BootServiceDowngradeRefusedError",
282 installedVersion: "1.2.4",
283 targetVersion: "1.2.3",
284 });
285 expect(yield* fs.readFileString(statePath)).toBe(control.stateAfterStop);
286 expect(yield* fs.readFileString(plan.launcherPath)).toBe(launcher);
287 expect(yield* fs.readFileString(plan.unitPath)).toBe(unit);
288 expect(
289 commands.filter((command) =>
290 command.startsWith(platform === "linux" ? "systemctl " : "launchctl "),
291 ),
292 ).toEqual(
293 platform === "linux"
294 ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"]
295 : [
296 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
297 `launchctl bootstrap gui/501 ${plan.unitPath}`,
298 ],
299 );
300 }),
301 );
302
303 it.effect("allows an explicit downgrade", () =>
304 Effect.gen(function* () {
305 const { service, fs, statePath } = yield* makeHarness();
306 yield* service.install();
307 yield* fs.writeFileString(
308 statePath,
309 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.4"}`,
310 );
311
312 yield* service.install({ allowDowngrade: true });
313
314 expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.3");
315 expect((yield* service.status).current).toBe(true);
316 }),
317 );
318
319 it.effect("repairs versions with equal SemVer precedence without an override", () =>
320 Effect.gen(function* () {
321 const { service, fs, statePath } = yield* makeHarness();
322 yield* service.install();
323 yield* fs.writeFileString(
324 statePath,
325 `{"protocol":${SERVICE_LAUNCHER_PROTOCOL},"activeVersion":"1.2.3+previous-build"}`,
326 );
327
328 yield* service.install();
329
330 expect((yield* service.status).current).toBe(true);
331 }),
332 );
333
334 it.effect("copies the launcher from the prepared pinned runtime", () =>
335 Effect.gen(function* () {
336 const { service, fs } = yield* makeHarness("linux", true);
337 const plan = yield* service.install();
338
339 expect(yield* fs.readFileString(plan.launcherPath)).toBe(
340 "export const source = 'pinned runtime';\n",
341 );
342 }),
343 );
344
345 it.effect("restarts an installed service when repair fails", () =>
346 Effect.gen(function* () {
347 const { service, commands, control } = yield* makeHarness();
348 yield* service.install();
349 commands.length = 0;
350 control.failCommand = "systemctl --user daemon-reload";
351
352 const error = yield* service.install().pipe(Effect.flip);
353 expect(error._tag).toBe("BootServiceCommandError");
354 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
355 "systemctl --user stop t3code.service",
356 "systemctl --user daemon-reload",
357 "systemctl --user restart t3code.service",
358 ]);
359 }),
360 );
361
362 it.effect("restarts without overwriting a pending remote update", () =>
363 Effect.gen(function* () {
364 const { service, fs, statePath, commands } = yield* makeHarness();
365 yield* service.install();
366 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
367 const pendingState = JSON.stringify({
368 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
369 activeVersion: "1.2.3",
370 update: {
371 id: "remote-update",
372 fromVersion: "1.2.3",
373 targetVersion: "1.2.4",
374 status: "pending",
375 },
376 });
377 yield* fs.writeFileString(statePath, pendingState);
378 for (const allowDowngrade of [false, true]) {
379 commands.length = 0;
380
381 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
382 "BootServiceUpdatePendingError",
383 );
384 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
385 expect(commands.filter((command) => command.startsWith("systemctl "))).toEqual([
386 "systemctl --user stop t3code.service",
387 "systemctl --user restart t3code.service",
388 ]);
389 }
390 }),
391 );
392
393 it.effect("fails closed on Windows", () =>
394 Effect.gen(function* () {
395 const { service } = yield* makeHarness("win32");
396 expect((yield* service.status).supported).toBe(false);
397 expect((yield* service.install().pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
398 }),
399 );
400
401 it.effect("installs, reports current state, and uninstalls on macOS", () =>
402 Effect.gen(function* () {
403 const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
404 const plan = yield* service.install();
405
406 expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
407 true,
408 );
409 expect(yield* fs.readFileString(plan.unitPath)).toContain(
410 ` <key>PATH</key>\n <string>${macInstallerPath}:/usr/local/bin:/usr/sbin:/sbin</string>`,
411 );
412 expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
413 protocol: SERVICE_LAUNCHER_PROTOCOL,
414 activeVersion: "1.2.3",
415 });
416 expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
417 expect(yield* service.status).toMatchObject({
418 current: true,
419 installedVersion: "1.2.3",
420 });
421 expect(yield* service.uninstall).toBe(true);
422 expect((yield* service.status).installed).toBe(false);
423 expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
424 expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
425 // A bootout can block up to the plist's 90s ExitTimeOut; the runner's
426 // 60s default would cancel it and let bootstrap race a loaded job.
427 expect(timeouts.get("launchctl bootout --wait gui/501/com.t3tools.t3code.service")).toEqual(
428 Duration.seconds(120),
429 );
430 }),
431 );
432
433 it.effect("restarts the launch agent when repair fails", () =>
434 Effect.gen(function* () {
435 const { service, commands, control } = yield* makeHarness("darwin");
436 yield* service.install();
437 const plistPath = (yield* service.status).unitPath;
438 commands.length = 0;
439 control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
440
441 const error = yield* service.install().pipe(Effect.flip);
442 expect(error._tag).toBe("BootServiceCommandError");
443 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
444 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
445 "launchctl enable gui/501/com.t3tools.t3code.service",
446 `launchctl bootstrap gui/501 ${plistPath}`,
447 `launchctl bootstrap gui/501 ${plistPath}`,
448 ]);
449 }),
450 );
451
452 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
453 Effect.gen(function* () {
454 const { service, fs } = yield* makeHarness("darwin", false, "");
455 const plan = yield* service.install();
456
457 expect(yield* fs.readFileString(plan.unitPath)).toContain(
458 " <key>PATH</key>\n <string>/usr/bin:/opt/homebrew/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
459 );
460 expect((yield* service.status).current).toBe(true);
461 }),
462 );
463
464 it.effect("adds missing provider directories to a minimal installer PATH", () =>
465 Effect.gen(function* () {
466 const { service, fs } = yield* makeHarness("darwin", false, "/usr/bin:/bin");
467 const plan = yield* service.install();
468
469 expect(yield* fs.readFileString(plan.unitPath)).toContain(
470 " <key>PATH</key>\n <string>/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin:/usr/sbin:/sbin</string>",
471 );
472 expect((yield* service.status).current).toBe(true);
473 }),
474 );
475
476 it.effect("keeps an installed launch agent current when the process PATH changes", () =>
477 Effect.gen(function* () {
478 const { service, makeService } = yield* makeHarness("darwin");
479 yield* service.install();
480
481 const restartedService = yield* makeService("/usr/local/bin:/usr/bin:/bin");
482 expect((yield* restartedService.status).current).toBe(true);
483 }),
484 );
485
486 it.effect("drops PATH directories that cannot be represented in a launch agent plist", () =>
487 Effect.gen(function* () {
488 const { service, fs } = yield* makeHarness(
489 "darwin",
490 false,
491 "/opt/homebrew/bin:/Users/theo/\u0001invalid:/usr/bin",
492 );
493 const plan = yield* service.install();
494 const plist = yield* fs.readFileString(plan.unitPath);
495
496 expect(plist).toContain(
497 " <key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/usr/local/bin:/bin:/usr/sbin:/sbin</string>",
498 );
499 expect(plist).not.toContain("\u0001");
500 expect((yield* service.status).current).toBe(true);
501 }),
502 );
503
504 it.effect("ignores a bootout for an agent that is not loaded", () =>
505 Effect.gen(function* () {
506 const { service, control } = yield* makeHarness("darwin");
507 yield* service.install();
508 control.failCommand = "launchctl bootout --wait gui/501/com.t3tools.t3code.service";
509
510 yield* service.install();
511 expect((yield* service.status).current).toBe(true);
512 }),
513 );
514
515 it.effect("restarts without overwriting a pending remote update on macOS", () =>
516 Effect.gen(function* () {
517 const { service, fs, statePath, commands } = yield* makeHarness("darwin");
518 yield* service.install();
519 const plistPath = (yield* service.status).unitPath;
520 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
521 const pendingState = JSON.stringify({
522 protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
523 activeVersion: "1.2.3",
524 update: {
525 id: "remote-update",
526 fromVersion: "1.2.3",
527 targetVersion: "1.2.4",
528 status: "pending",
529 },
530 });
531 yield* fs.writeFileString(statePath, pendingState);
532 for (const allowDowngrade of [false, true]) {
533 commands.length = 0;
534
535 expect((yield* service.install({ allowDowngrade }).pipe(Effect.flip))._tag).toBe(
536 "BootServiceUpdatePendingError",
537 );
538 expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
539 expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
540 "launchctl bootout --wait gui/501/com.t3tools.t3code.service",
541 `launchctl bootstrap gui/501 ${plistPath}`,
542 ]);
543 }
544 }),
545 );
546});