feat(connect): keep macOS hosts reachable after reboot

This commit is contained in:
Theo Browne committed 2026-07-30 03:16:05 -07:00
1 parent 90f3913a81
commit ec3c5f68d2
12 files changed
+690 -91

No files matched your search

+22
View File
@@ -23,3 +23,25 @@ export const writeFileStringAtomically = (input: {
yield* fs.rename(tempPath, input.filePath);
}),
);
export const writeSymbolicLinkAtomically = (input: {
readonly linkPath: string;
readonly targetPath: string;
}) =>
Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const targetDirectory = path.dirname(input.linkPath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
const tempDirectory = yield* fs.makeTempDirectoryScoped({
directory: targetDirectory,
prefix: `${path.basename(input.linkPath)}.`,
});
const tempPath = path.join(tempDirectory, "link.tmp");
yield* fs.symlink(input.targetPath, tempPath);
yield* fs.rename(tempPath, input.linkPath);
}),
);
+1 -1
View File
@@ -695,7 +695,7 @@ export const connectCommand = Command.make("connect", {
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
yield* Console.log(
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
"\n✓ Background service ready\n\nT3 Code will start automatically and stay reachable in the background.",
);
return;
}
+3 -3
View File
@@ -16,7 +16,7 @@ it("reports the installed service version and host paths", () => {
[
"T3 Code service",
" Status: installed · [email protected]",
" Unit: /home/me/.config/systemd/user/t3code.service",
" Definition: /home/me/.config/systemd/user/t3code.service",
" Logs: /home/me/.t3/userdata/logs/boot-service.log",
].join("\n"),
);
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
);
});
it("explains service availability without systemd", () => {
it("explains service availability on unsupported platforms", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
"Supported on: Linux with systemd",
"Supported on: macOS with launchd or Linux with systemd",
);
});
+3 -4
View File
@@ -48,7 +48,7 @@ export function formatServiceStatus(
cliVersion: string,
): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
return "T3 Code service\n Status: unavailable on this machine\n Supported on: macOS with launchd or Linux with systemd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
@@ -56,7 +56,7 @@ export function formatServiceStatus(
return [
"T3 Code service",
` Status: ${status.current ? `installed · t3@${cliVersion}` : "needs an update or repair"}`,
` Unit: ${status.unitPath}`,
` Definition: ${status.unitPath}`,
` Logs: ${status.logPath}`,
...(status.current ? [] : [" Next: Run `npx t3@latest service update`."]),
].join("\n");
@@ -156,8 +156,7 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
Prompt.confirm({
message: installed
? "The installed T3 Code service needs an update or repair. Update it now?"
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
: "Start T3 Code automatically and keep this machine reachable in the background?",
initial: true,
}),
);
+142 -2
View File
@@ -12,6 +12,7 @@ import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { reconcileService } from "../cli/service.ts";
@@ -64,6 +65,7 @@ const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessUserId, 501),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
@@ -143,6 +145,34 @@ it("quotes systemd values containing spaces and escapes percent specifiers", ()
assert.include(unit, "StandardError=append:/home/me/100%%logs/boot.log");
});
it("renders a restartable per-user macOS LaunchAgent", () => {
const launchAgent = BootService.renderBootServiceLaunchAgent({
nodePath: "/opt/homebrew/bin/node",
t3EntryPath: "/Users/theo/T3 & Data/runtime/service/current/node_modules/t3/dist/bin.mjs",
baseDir: "/Users/theo/T3 & Data",
logPath: "/Users/theo/T3 & Data/userdata/logs/boot-service.log",
unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.server.plist",
pathEnvironment: "/opt/homebrew/bin:/usr/bin:/bin",
});
assert.include(launchAgent, "<string>com.t3tools.t3code.server</string>");
assert.include(launchAgent, "<key>RunAtLoad</key>\n <true/>");
assert.include(launchAgent, "<key>KeepAlive</key>\n <true/>");
assert.include(launchAgent, "<string>/Users/theo/T3 &amp; Data</string>");
assert.include(
launchAgent,
"<string>/Users/theo/T3 &amp; Data/runtime/service/current/node_modules/t3/dist/bin.mjs</string>",
);
assert.include(
launchAgent,
"<key>T3_BOOT_SERVICE_UNIT</key>\n <string>com.t3tools.t3code.server</string>",
);
assert.include(
launchAgent,
"<key>PATH</key>\n <string>/opt/homebrew/bin:/usr/bin:/bin</string>",
);
});
it("flags package-manager cache entry points as ephemeral", () => {
assert.isTrue(
BootService.isEphemeralCacheEntry("/home/theo/.npm/_npx/abc123/node_modules/t3/dist/bin.mjs"),
@@ -388,7 +418,117 @@ it.layer(NodeServices.layer)("BootService", (it) => {
}),
);
it.effect("fails on non-Linux platforms without touching the filesystem", () =>
it.effect("installs and starts a pinned macOS LaunchAgent", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home, "darwin"),
);
const plan = yield* service.install;
const runtimeDir = path.join(dirs.baseDir, "runtime", "versions", "0.0.27");
const activeRuntimeLink = path.join(dirs.baseDir, "runtime", "service", "current");
const launchAgentPath = path.join(
dirs.home,
"Library",
"LaunchAgents",
"com.t3tools.t3code.server.plist",
);
assert.equal(
plan.t3EntryPath,
path.join(activeRuntimeLink, "node_modules", "t3", "dist", "bin.mjs"),
);
assert.equal(yield* fs.readLink(activeRuntimeLink), runtimeDir);
assert.deepEqual(
commands.map((entry) => [entry.command, ...entry.args].join(" ")),
[
`npm install --prefix ${runtimeDir} --no-fund --no-audit [email protected]`,
"/bin/launchctl enable gui/501/com.t3tools.t3code.server",
"/bin/launchctl bootout gui/501/com.t3tools.t3code.server",
`/bin/launchctl bootstrap gui/501 ${launchAgentPath}`,
"/bin/launchctl print gui/501/com.t3tools.t3code.server",
],
);
const plist = yield* fs.readFileString(launchAgentPath);
assert.include(plist, `<string>${plan.t3EntryPath}</string>`);
assert.notInclude(plist, dirs.stableEntry);
// The recording npm runner does not materialize files, so complete the
// managed runtime before checking the current-state contract.
yield* fs.makeDirectory(path.dirname(path.join(runtimeDir, "node_modules/t3/dist/bin.mjs")), {
recursive: true,
});
yield* fs.writeFileString(
path.join(runtimeDir, "node_modules", "t3", "dist", "bin.mjs"),
"#!/usr/bin/env node\n",
);
const status = yield* service.status;
assert.isTrue(status.supported);
assert.isTrue(status.installed);
assert.isTrue(status.current);
assert.isTrue(yield* service.uninstall);
assert.isFalse(yield* fs.exists(launchAgentPath));
}),
);
it.effect("restores the previous macOS runtime when LaunchAgent activation fails", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const initialCommands: Array<RecordedCommand> = [];
const initialService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(initialCommands)),
provideHostRefs(dirs.home, "darwin"),
);
yield* initialService.install;
const activeRuntimeLink = path.join(dirs.baseDir, "runtime", "service", "current");
const previousRuntime = yield* fs.readLink(activeRuntimeLink);
const launchAgentPath = path.join(
dirs.home,
"Library",
"LaunchAgents",
"com.t3tools.t3code.server.plist",
);
const previousLaunchAgent = yield* fs.readFileString(launchAgentPath);
const repairCommands: Array<RecordedCommand> = [];
const repairService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.28",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(
makeRecordingRunnerLayer(repairCommands, {
failWhen: (command, args) => command === "/bin/launchctl" && args.includes("bootstrap"),
}),
),
provideHostRefs(dirs.home, "darwin"),
);
const error = yield* repairService.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.equal(yield* fs.readLink(activeRuntimeLink), previousRuntime);
assert.equal(yield* fs.readFileString(launchAgentPath), previousLaunchAgent);
}),
);
it.effect("fails on unsupported platforms without touching the filesystem", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const commands: Array<RecordedCommand> = [];
@@ -399,7 +539,7 @@ it.layer(NodeServices.layer)("BootService", (it) => {
host: makeHost("/usr/local/lib/node_modules/t3/dist/bin.mjs"),
}).pipe(
Effect.provide(makeRecordingRunnerLayer(commands)),
provideHostRefs(dirs.home, "darwin"),
provideHostRefs(dirs.home, "win32"),
);
const error = yield* service.install.pipe(Effect.flip);
+255 -35
View File
@@ -11,16 +11,19 @@ import * as Schema from "effect/Schema";
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import { ensurePinnedRuntimeInstalled, pinnedRuntimePaths } from "./pinnedRuntime.ts";
/**
* Installs T3 Code as a per-user boot service. Linux-only for now: systemd
* user unit + loginctl enable-linger. The service runs a stable or pinned
* Installs T3 Code as a per-user background service: systemd + linger on
* Linux, or a LaunchAgent on macOS. The service runs a stable or pinned
* runtime — never an ephemeral `npx t3` cache whose eviction could break
* startup.
*/
@@ -29,6 +32,8 @@ const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
export const BOOT_SERVICE_LAUNCH_AGENT_LABEL = "com.t3tools.t3code.server";
export const BOOT_SERVICE_LAUNCH_AGENT_FILE = `${BOOT_SERVICE_LAUNCH_AGENT_LABEL}.plist`;
const EPHEMERAL_CACHE_SEGMENTS = [
"/_npx/", // npx
@@ -76,6 +81,39 @@ export interface BootServicePlan {
readonly baseDir: string;
readonly logPath: string;
readonly unitPath: string;
/** Captured for launchd, whose default PATH omits common CLI install locations. */
readonly pathEnvironment?: string;
}
export interface LaunchAgentPaths {
readonly unitPath: string;
readonly activeRuntimeLinkPath: string;
readonly activeEntryPath: string;
readonly serviceTarget: string;
}
export function launchAgentPaths(
path: Path.Path,
homeDir: string,
baseDir: string,
userId: number,
): LaunchAgentPaths {
const activeRuntimeLinkPath = path.join(baseDir, "runtime", "service", "current");
return {
unitPath: path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_LAUNCH_AGENT_FILE),
activeRuntimeLinkPath,
activeEntryPath: path.join(activeRuntimeLinkPath, "node_modules", "t3", "dist", "bin.mjs"),
serviceTarget: `gui/${String(userId)}/${BOOT_SERVICE_LAUNCH_AGENT_LABEL}`,
};
}
export function escapeLaunchdXml(value: string): string {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&apos;");
}
/**
@@ -114,12 +152,61 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
].join("\n");
}
/**
* LaunchAgents are loaded for a user's GUI session after login. KeepAlive
* restarts crashes, while the stable entry path lets remote updates switch
* exact runtimes without rewriting or unloading the plist from inside the
* process it owns.
*/
export function renderBootServiceLaunchAgent(plan: BootServicePlan): string {
const value = escapeLaunchdXml;
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
'<plist version="1.0">',
"<dict>",
" <key>Label</key>",
` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`,
" <key>ProgramArguments</key>",
" <array>",
` <string>${value(plan.nodePath)}</string>`,
` <string>${value(plan.t3EntryPath)}</string>`,
" <string>serve</string>",
" </array>",
" <key>EnvironmentVariables</key>",
" <dict>",
" <key>T3CODE_HOME</key>",
` <string>${value(plan.baseDir)}</string>`,
` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
` <string>${BOOT_SERVICE_LAUNCH_AGENT_LABEL}</string>`,
...(plan.pathEnvironment === undefined
? []
: [" <key>PATH</key>", ` <string>${value(plan.pathEnvironment)}</string>`]),
" </dict>",
" <key>WorkingDirectory</key>",
` <string>${value(plan.baseDir)}</string>`,
" <key>RunAtLoad</key>",
" <true/>",
" <key>KeepAlive</key>",
" <true/>",
" <key>ThrottleInterval</key>",
" <integer>5</integer>",
" <key>StandardOutPath</key>",
` <string>${value(plan.logPath)}</string>`,
" <key>StandardErrorPath</key>",
` <string>${value(plan.logPath)}</string>`,
"</dict>",
"</plist>",
"",
].join("\n");
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
}
}
@@ -134,9 +221,13 @@ export class BootServiceCommandError extends Schema.TaggedErrorClass<BootService
},
) {
override get message(): string {
return this.exitCode === undefined
? `Background setup failed while ${this.step}.`
: `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
const detail =
this.exitCode === undefined
? `Background setup failed while ${this.step}.`
: `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;
return this.step.includes("LaunchAgent")
? `${detail} If macOS blocked the background item, allow T3 Code in System Settings > General > Login Items & Extensions.`
: detail;
}
}
@@ -157,7 +248,7 @@ export type BootServiceError =
export interface BootServiceStatus {
readonly supported: boolean;
readonly installed: boolean;
/** False when the installed unit no longer matches what install would write. */
/** False when the installed service no longer matches what install would write. */
readonly current: boolean;
readonly unitPath: string;
readonly logPath: string;
@@ -166,7 +257,7 @@ export interface BootServiceStatus {
export class BootService extends Context.Service<
BootService,
{
/** Installs the pinned runtime + unit, enables linger, starts the service. */
/** Installs the runtime + user service and starts it immediately. */
readonly install: Effect.Effect<BootServicePlan, BootServiceError>;
/**
* Stops and removes the unit; leaves the pinned runtime for reuse.
@@ -192,23 +283,37 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
const hostArguments = yield* HostProcessArguments;
const host = input.host ?? {
execPath: hostExecPath,
// When running the packed CLI this is dist/bin.mjs; when stable (global
// install, repo checkout) the boot service runs this same artifact.
// When running the packed CLI this is dist/bin.mjs. Linux can reuse a
// stable global install or checkout; macOS pins the exact CLI version.
cliEntryPath: hostArguments[1] ?? "",
};
const platform = yield* HostProcessPlatform;
const hostEnvironment = yield* HostProcessEnvironment;
const userId = yield* HostProcessUserId;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const systemdUnitDir = path.join(homeDir, ".config", "systemd", "user");
const systemdUnitPath = path.join(systemdUnitDir, BOOT_SERVICE_UNIT_FILE);
const launchAgent =
userId === null ? null : launchAgentPaths(path, homeDir, input.baseDir, userId);
const unitDir =
platform === "darwin" && launchAgent !== null
? path.dirname(launchAgent.unitPath)
: systemdUnitDir;
const unitPath =
platform === "darwin" && launchAgent !== null ? launchAgent.unitPath : systemdUnitPath;
const logPath = path.join(input.logsDir, "boot-service.log");
const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
const requireSupportedPlatform = Effect.gen(function* () {
if (
homeDir === "" ||
(platform !== "linux" && platform !== "darwin") ||
(platform === "darwin" && userId === null)
) {
return yield* new BootServiceUnsupportedError({ platform });
}
});
@@ -244,15 +349,24 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
const runOptionalStep = Effect.fn("cloud.boot_service.run_optional_step")(function* (
command: string,
args: ReadonlyArray<string>,
) {
return yield* runner.run({ command, args }).pipe(
Effect.map((result) => result.code === 0),
Effect.orElseSucceed(() => false),
);
});
/**
* Ensures plannedEntryPath exists before the unit points at it. A stable
* install (global bin, repo checkout) is used as-is; an ephemeral cache
* entry is replaced by `npm install --prefix`-ing the exact running
* version into <baseDir>/runtime/versions/<v>. A real install (not a copy
* of bin.mjs) because t3 ships native deps like node-pty.
* Ensures plannedRuntimeEntryPath exists before the service points at it.
* macOS always gets an exact managed runtime so the LaunchAgent can use a
* stable symlink across remote updates. Linux can reuse a stable global or
* checkout entry; ephemeral cache entries are pinned on both platforms.
*/
const ensurePinnedRuntime = Effect.gen(function* () {
if (!isEphemeralCacheEntry(host.cliEntryPath)) {
if (platform !== "darwin" && !isEphemeralCacheEntry(host.cliEntryPath)) {
return;
}
yield* ensurePinnedRuntimeInstalled({
@@ -286,21 +400,44 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
// Where the unit will point: derivable without touching the network, so
// status can compare units purely; install materializes it first.
const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath)
? runtimePaths.entryPath
: host.cliEntryPath;
// Where the service definition will point; install materializes it first.
const plannedRuntimeEntryPath =
platform === "darwin" || isEphemeralCacheEntry(host.cliEntryPath)
? runtimePaths.entryPath
: host.cliEntryPath;
const plannedEntryPath =
platform === "darwin" && launchAgent !== null
? launchAgent.activeEntryPath
: plannedRuntimeEntryPath;
const plan: BootServicePlan = {
nodePath: host.execPath,
t3EntryPath: plannedEntryPath,
baseDir: input.baseDir,
logPath,
unitPath,
pathEnvironment: hostEnvironment.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
};
const writeUnit = (contents: string) =>
writeFileStringAtomically({ filePath: unitPath, contents }).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
const writeActiveRuntimeLink = (targetPath: string) => {
if (launchAgent === null) {
return Effect.void;
}
return writeSymbolicLinkAtomically({
linkPath: launchAgent.activeRuntimeLinkPath,
targetPath,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
};
const install: BootService["Service"]["install"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* requireSupportedPlatform;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -316,15 +453,54 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
);
const previousRuntimeLink =
platform === "darwin" && launchAgent !== null
? yield* fs.exists(launchAgent.activeRuntimeLinkPath).pipe(
Effect.flatMap((exists) =>
exists
? fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(Effect.map(Option.some))
: Effect.succeed(Option.none<string>()),
),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
)
: Option.none<string>();
yield* fs.makeDirectory(unitDir, { recursive: true }).pipe(
Effect.andThen(fs.writeFileString(unitPath, renderBootServiceUnit(plan))),
Effect.andThen(
platform === "darwin"
? writeActiveRuntimeLink(runtimePaths.versionDir).pipe(
Effect.andThen(writeUnit(renderBootServiceLaunchAgent(plan))),
)
: writeUnit(renderBootServiceUnit(plan)),
),
Effect.mapError((cause) => new BootServiceInstallError({ cause })),
Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)),
);
// If any activation step fails, remove the unit again: a leftover file
// would make service status report it as installed even though it was
// never enabled or lingered.
yield* Effect.gen(function* () {
if (platform === "darwin" && launchAgent !== null && userId !== null) {
const domain = `gui/${String(userId)}`;
// An explicit install repairs a background item the user previously
// disabled in System Settings.
yield* runStep("enabling the LaunchAgent", "/bin/launchctl", [
"enable",
launchAgent.serviceTarget,
]);
// bootout is expected to fail on first install. On repair it stops
// the old job before bootstrap loads the new definition.
yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
yield* runStep("loading the LaunchAgent", "/bin/launchctl", [
"bootstrap",
domain,
unitPath,
]);
yield* runStep("checking the LaunchAgent", "/bin/launchctl", [
"print",
launchAgent.serviceTarget,
]);
return;
}
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
@@ -344,7 +520,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
// username argument: loginctl defaults to the calling user, which is
// always right, while $USER can be stale (su without -l) or unset.
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
}).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit)));
}).pipe(Effect.tapError(() => rollbackFailedInstall(previousUnit, previousRuntimeLink)));
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
@@ -356,9 +532,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
// next lifecycle command misreports the state.
const rollbackFailedInstall = Effect.fn("cloud.boot_service.rollback_failed_install")(function* (
previousUnit: Option.Option<string>,
previousRuntimeLink: Option.Option<string>,
) {
if (platform === "darwin" && launchAgent !== null && userId !== null) {
yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
if (Option.isSome(previousRuntimeLink)) {
yield* writeActiveRuntimeLink(previousRuntimeLink.value).pipe(Effect.ignore);
} else {
yield* fs.remove(launchAgent.activeRuntimeLinkPath).pipe(Effect.ignore);
}
if (Option.isSome(previousUnit)) {
yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
yield* runOptionalStep("/bin/launchctl", ["bootstrap", `gui/${String(userId)}`, unitPath]);
} else {
yield* fs.remove(unitPath).pipe(Effect.ignore);
}
return;
}
if (Option.isSome(previousUnit)) {
yield* fs.writeFileString(unitPath, previousUnit.value).pipe(Effect.ignore);
yield* writeUnit(previousUnit.value).pipe(Effect.ignore);
} else {
yield* runStep("cleaning up the service", "systemctl", [
"--user",
@@ -381,13 +574,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* requireSupportedPlatform;
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
return false;
}
if (platform === "darwin" && launchAgent !== null) {
// A disabled or already-unloaded agent returns non-zero from bootout;
// the plist is still safe to remove and is the durable source of truth.
yield* runOptionalStep("/bin/launchctl", ["bootout", launchAgent.serviceTarget]);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
return true;
}
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
@@ -402,7 +604,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
if (
homeDir === "" ||
(platform !== "linux" && platform !== "darwin") ||
(platform === "darwin" && launchAgent === null)
) {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
const unitExists = yield* fs.exists(unitPath);
@@ -410,11 +616,25 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
return { supported: true, installed: false, current: false, unitPath, logPath };
}
const unit = yield* fs.readFileString(unitPath);
const entryExists = yield* fs.exists(plannedEntryPath);
if (platform === "darwin" && launchAgent !== null) {
const activeRuntimeIsCurrent = yield* fs.readLink(launchAgent.activeRuntimeLinkPath).pipe(
Effect.map((target) => target === runtimePaths.versionDir),
Effect.orElseSucceed(() => false),
);
const loaded = yield* runOptionalStep("/bin/launchctl", ["print", launchAgent.serviceTarget]);
const current =
unit === renderBootServiceLaunchAgent(plan) &&
entryExists &&
activeRuntimeIsCurrent &&
loaded;
return { supported: true, installed: true, current, unitPath, logPath };
}
// A unit is current only if it matches what install would write now (an
// older CLI wrote a different runtime/node path) AND the entry point it
// references still exists (a pinned runtime under ~/.t3 can be deleted to
// reclaim space). Either mismatch makes connect offer a repair.
const entryExists = yield* fs.exists(plannedEntryPath);
const current = unit === renderBootServiceUnit(plan) && entryExists;
return { supported: true, installed: true, current, unitPath, logPath };
}).pipe(
+133 -16
View File
@@ -13,13 +13,17 @@ import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_LAUNCH_AGENT_LABEL,
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
launchAgentPaths,
renderBootServiceLaunchAgent,
renderBootServiceUnit,
} from "./bootService.ts";
import * as SelfUpdate from "./selfUpdate.ts";
@@ -76,6 +80,7 @@ const provideHostRefs = (input: {
Layer.succeed(HostProcessEnvironment, input.env),
Layer.succeed(HostProcessExecutablePath, NODE_PATH),
Layer.succeed(HostProcessArguments, [NODE_PATH, input.entryPath, "serve"]),
Layer.succeed(HostProcessUserId, 501),
),
);
@@ -192,6 +197,41 @@ it.layer(NodeServices.layer)("resolveServerSelfUpdateCapability", (it) => {
}),
);
it.effect("reports boot-service for the T3-managed macOS LaunchAgent", () =>
Effect.gen(function* () {
const { fs, home, path } = yield* makeHome();
const baseDir = path.join(home, ".t3");
const launchAgent = launchAgentPaths(path, home, baseDir, 501);
yield* fs.makeDirectory(path.dirname(launchAgent.unitPath), { recursive: true });
yield* fs.writeFileString(
launchAgent.unitPath,
renderBootServiceLaunchAgent({
nodePath: NODE_PATH,
t3EntryPath: launchAgent.activeEntryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: launchAgent.unitPath,
}),
);
const method = yield* SelfUpdate.resolveServerSelfUpdateCapability({
desktopManaged: false,
}).pipe(
provideHostRefs({
platform: "darwin",
env: {
HOME: home,
T3CODE_HOME: baseDir,
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_LAUNCH_AGENT_LABEL,
},
entryPath: launchAgent.activeEntryPath,
}),
);
assert.equal(method, "boot-service");
}),
);
it.effect("reports desktop-managed for desktop-supervised backends", () =>
Effect.gen(function* () {
const { home, path } = yield* makeHome();
@@ -262,11 +302,21 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
const path = yield* Path.Path;
const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
const baseDir = path.join(home, ".t3");
const platform = options?.platform ?? "linux";
const launchdBootService = options?.bootService === true && platform === "darwin";
const launchAgent = launchAgentPaths(path, home, baseDir, 501);
const entryPath =
options?.entryPath ??
path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs");
const env: NodeJS.ProcessEnv =
options?.bootService === true
(launchdBootService
? launchAgent.activeEntryPath
: path.join(home, ".t3/runtime/versions/0.0.28/node_modules/t3/dist/bin.mjs"));
const env: NodeJS.ProcessEnv = launchdBootService
? {
HOME: home,
T3CODE_HOME: baseDir,
[BOOT_SERVICE_UNIT_ENV]: BOOT_SERVICE_LAUNCH_AGENT_LABEL,
}
: options?.bootService === true
? {
HOME: home,
INVOCATION_ID: "abc123",
@@ -274,18 +324,37 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}
: { HOME: home };
if (options?.bootService === true) {
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}),
);
if (launchdBootService) {
const previousRuntime = path.join(baseDir, "runtime", "versions", "0.0.28");
yield* fs.makeDirectory(path.dirname(launchAgent.unitPath), { recursive: true });
yield* fs.makeDirectory(path.dirname(launchAgent.activeRuntimeLinkPath), {
recursive: true,
});
yield* fs.symlink(previousRuntime, launchAgent.activeRuntimeLinkPath);
yield* fs.writeFileString(
launchAgent.unitPath,
renderBootServiceLaunchAgent({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: launchAgent.unitPath,
}),
);
} else {
const unitDir = path.join(home, ".config", "systemd", "user");
yield* fs.makeDirectory(unitDir, { recursive: true });
yield* fs.writeFileString(
path.join(unitDir, "t3code.service"),
renderBootServiceUnit({
nodePath: NODE_PATH,
t3EntryPath: entryPath,
baseDir,
logPath: path.join(baseDir, "userdata", "logs", "boot-service.log"),
unitPath: path.join(unitDir, "t3code.service"),
}),
);
}
}
const commands: Array<RecordedCommand> = [];
@@ -333,7 +402,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
configLayer,
),
),
provideHostRefs({ platform: options?.platform ?? "linux", env, entryPath }),
provideHostRefs({ platform, env, entryPath }),
);
return {
fs,
@@ -341,6 +410,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
home,
baseDir,
entryPath,
launchAgent,
commands,
spawns,
exitCount: () => exited,
@@ -520,6 +590,53 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("switches the macOS LaunchAgent runtime and restarts it", () =>
Effect.gen(function* () {
const context = yield* makeContext({
platform: "darwin",
bootService: true,
});
const result = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(result, { targetVersion: "0.0.29", method: "boot-service" });
assert.equal(
yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath),
context.path.join(context.baseDir, "runtime", "versions", "0.0.29"),
);
assert.deepEqual(
context.commands.map((entry) => entry.command),
["npm", NODE_PATH, "/bin/launchctl"],
);
assert.deepEqual(context.commands[2], {
command: "/bin/launchctl",
args: ["kickstart", "-k", "gui/501/com.t3tools.t3code.server"],
});
assert.lengthOf(context.spawns, 0);
assert.equal(context.exitCount(), 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous macOS runtime when launchd rejects the restart", () =>
Effect.gen(function* () {
const context = yield* makeContext({
platform: "darwin",
bootService: true,
failWhen: (command) => command === "/bin/launchctl",
});
const previousRuntime = yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath);
const error = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
assert.include(error.reason, "Restarting the T3 Code LaunchAgent failed");
assert.equal(
yield* context.fs.readLink(context.launchAgent.activeRuntimeLinkPath),
previousRuntime,
);
assert.lengthOf(context.spawns, 0);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
Effect.gen(function* () {
let failRestart = true;
+89 -7
View File
@@ -13,6 +13,7 @@ import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as NodeChildProcess from "node:child_process";
import * as Context from "effect/Context";
@@ -24,11 +25,13 @@ import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ServerConfig from "../config.ts";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import { writeFileStringAtomically, writeSymbolicLinkAtomically } from "../atomicWrite.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
BOOT_SERVICE_LAUNCH_AGENT_LABEL,
BOOT_SERVICE_UNIT_ENV,
BOOT_SERVICE_UNIT_FILE,
launchAgentPaths,
quoteSystemdValue,
renderBootServiceUnit,
} from "./bootService.ts";
@@ -82,11 +85,11 @@ export function isPublishedCliEntry(entryPath: string): boolean {
* The update path this process can offer, or null when only a manual
* relaunch works. "desktop-managed" — the T3 Code desktop app spawned this
* backend and owns its version; only updating the app updates it.
* "boot-service" — this is the systemd-supervised process from
* bootService.ts: rewrite the unit and let systemd swap it. "respawn" — a
* foreground POSIX process running a published artifact: replace it with a
* detached child. Windows foreground runs are unsupported for now (no
* equivalent of the detach-and-exec handoff below).
* "boot-service" — this is the systemd- or launchd-supervised process from
* bootService.ts: switch the service to the verified runtime and restart it.
* "respawn" — a foreground POSIX process running a published artifact:
* replace it with a detached child. Windows foreground runs are unsupported
* for now (no equivalent of the detach-and-exec handoff below).
*/
export const resolveServerSelfUpdateCapability = Effect.fn(
"cloud.server_self_update.resolve_capability",
@@ -101,6 +104,7 @@ export const resolveServerSelfUpdateCapability = Effect.fn(
const platform = yield* HostProcessPlatform;
const env = yield* HostProcessEnvironment;
const hostArguments = yield* HostProcessArguments;
const userId = yield* HostProcessUserId;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -110,6 +114,26 @@ export const resolveServerSelfUpdateCapability = Effect.fn(
}
const homeDir = env.HOME ?? "";
if (platform === "darwin" && homeDir !== "" && userId !== null) {
const launchAgent = launchAgentPaths(path, homeDir, env.T3CODE_HOME ?? "", userId);
const unitExists = yield* fs
.exists(launchAgent.unitPath)
.pipe(Effect.orElseSucceed(() => false));
if (
unitExists &&
entryPath === launchAgent.activeEntryPath &&
env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL
) {
return "boot-service" as const;
}
// A marked LaunchAgent process with an unexpected definition must not
// detach a second server outside its supervisor.
if (env[BOOT_SERVICE_UNIT_ENV] === BOOT_SERVICE_LAUNCH_AGENT_LABEL) {
return null;
}
}
if (platform === "linux" && homeDir !== "") {
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const unitReferencesEntry = yield* fs.readFileString(unitPath).pipe(
@@ -159,6 +183,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const env = yield* HostProcessEnvironment;
const platform = yield* HostProcessPlatform;
const userId = yield* HostProcessUserId;
const hostExecPath = yield* HostProcessExecutablePath;
const hostArguments = yield* HostProcessArguments;
const capability: ServerSelfUpdateCapability | null = yield* resolveServerSelfUpdateCapability({
@@ -224,6 +250,11 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
const writeRuntimeLinkAtomically = (linkPath: string, targetPath: string) =>
writeSymbolicLinkAtomically({ linkPath, targetPath }).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, path),
);
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
@@ -297,7 +328,58 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
);
}
if (activeMethod === "boot-service") {
if (activeMethod === "boot-service" && platform === "darwin" && userId !== null) {
const homeDir = env.HOME ?? "";
const launchAgent = launchAgentPaths(path, homeDir, serverConfig.baseDir, userId);
const previousRuntime = yield* fs
.readLink(launchAgent.activeRuntimeLinkPath)
.pipe(
Effect.mapError((cause) =>
failWith("Could not read the active launchd runtime.", cause),
),
);
yield* writeRuntimeLinkAtomically(
launchAgent.activeRuntimeLinkPath,
runtimePaths.versionDir,
).pipe(
Effect.mapError((cause) =>
failWith("Could not activate the requested launchd runtime.", cause),
),
);
yield* Effect.logInfo("Server self-update installed; restarting LaunchAgent.", {
targetVersion,
});
yield* Effect.gen(function* () {
const kickstart = yield* runner
.run({
command: "/bin/launchctl",
args: ["kickstart", "-k", launchAgent.serviceTarget],
})
.pipe(
Effect.mapError((cause) =>
failWith("Could not restart the T3 Code LaunchAgent.", cause),
),
);
if (kickstart.code !== 0) {
return yield* failWith(
`Restarting the T3 Code LaunchAgent failed (exit code ${String(kickstart.code)}).`,
);
}
}).pipe(
Effect.catch((restartError) =>
writeRuntimeLinkAtomically(launchAgent.activeRuntimeLinkPath, previousRuntime).pipe(
Effect.mapError((rollbackCause) =>
failWith("Could not restore the previous launchd runtime.", {
restartError,
rollbackCause,
}),
),
Effect.andThen(Effect.fail(restartError)),
),
),
);
} else if (activeMethod === "boot-service") {
const homeDir = env.HOME ?? "";
const unitPath = path.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE);
const previousUnit = yield* fs