Compare commits

...
12 changed files with 976 additions and 96 deletions

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,
}),
);
+300 -4
View File
@@ -10,8 +10,10 @@ import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawne
import {
HostProcessArguments,
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { reconcileService } from "../cli/service.ts";
@@ -31,6 +33,7 @@ const makeRecordingRunnerLayer = (
options?: {
readonly failCommand?: string;
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
},
) =>
Layer.succeed(
@@ -44,7 +47,7 @@ const makeRecordingRunnerLayer = (
input.command === options?.failCommand ||
options?.failWhen?.(input.command, input.args) === true;
return {
stdout: "",
stdout: options?.stdoutFor?.(input.command, input.args) ?? "",
stderr: failed ? `${input.command} exploded` : "",
code: ChildProcessSpawner.ExitCode(failed ? 1 : 0),
timedOut: false,
@@ -60,10 +63,16 @@ const makeHost = (entry: string): BootService.BootServiceHost => ({
cliEntryPath: entry,
});
const provideHostRefs = (home: string, platform: NodeJS.Platform = "linux") =>
const provideHostRefs = (
home: string,
platform: NodeJS.Platform = "linux",
pathEnvironment = "/test/bin:/usr/bin:/bin",
) =>
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessEnvironment, { HOME: home, PATH: pathEnvironment }),
Layer.succeed(HostProcessUserId, 501),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
);
@@ -143,6 +152,50 @@ 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("uses typed supervisor context for launchd recovery guidance", () => {
assert.include(
new BootService.BootServiceCommandError({
step: "loading the background service",
supervisor: "launchd",
}).message,
"System Settings > General > Login Items & Extensions",
);
assert.notInclude(
new BootService.BootServiceCommandError({
step: "checking the LaunchAgent",
}).message,
"System Settings",
);
});
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 +441,250 @@ 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 print-disabled gui/501",
"/bin/launchctl print gui/501/com.t3tools.t3code.server",
"/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);
const differentPathService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(makeRecordingRunnerLayer([])),
provideHostRefs(dirs.home, "darwin", "/different/setup/path"),
);
assert.isTrue((yield* differentPathService.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"),
stdoutFor: (command, args) =>
command === "/bin/launchctl" && args.includes("print-disabled")
? 'disabled services = {\n "com.t3tools.t3code.server" => true\n}\n'
: undefined,
}),
),
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);
assert.isTrue(
repairCommands.some(
({ command, args }) =>
command === "/bin/launchctl" &&
args.join(" ") === "disable gui/501/com.t3tools.t3code.server",
),
);
}),
);
it.effect("leaves a previously stopped macOS LaunchAgent stopped after rollback", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const initialService = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(Effect.provide(makeRecordingRunnerLayer([])), provideHostRefs(dirs.home, "darwin"));
yield* initialService.install;
const launchAgentPath = path.join(
dirs.home,
"Library",
"LaunchAgents",
"com.t3tools.t3code.server.plist",
);
const previousLaunchAgent = yield* fs.readFileString(launchAgentPath);
const commands: 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(commands, {
failWhen: (command, args) =>
command === "/bin/launchctl" &&
(args.includes("print") || args.includes("bootstrap")),
}),
),
provideHostRefs(dirs.home, "darwin"),
);
const error = yield* repairService.install.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.equal(yield* fs.readFileString(launchAgentPath), previousLaunchAgent);
assert.lengthOf(
commands.filter(
({ command, args }) => command === "/bin/launchctl" && args.includes("bootstrap"),
),
1,
);
}),
);
it.effect("stops an orphaned macOS LaunchAgent when its plist is already gone", () =>
Effect.gen(function* () {
const { dirs } = 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"),
);
assert.isTrue(yield* service.uninstall);
assert.deepEqual(commands, [
{
command: "/bin/launchctl",
args: ["print", "gui/501/com.t3tools.t3code.server"],
},
{
command: "/bin/launchctl",
args: ["bootout", "gui/501/com.t3tools.t3code.server"],
},
]);
}),
);
it.effect("keeps the macOS plist when launchd cannot stop a loaded agent", () =>
Effect.gen(function* () {
const { dirs, fs, path } = yield* makeTestContext();
const launchAgentPath = path.join(
dirs.home,
"Library",
"LaunchAgents",
"com.t3tools.t3code.server.plist",
);
yield* fs.makeDirectory(path.dirname(launchAgentPath), { recursive: true });
yield* fs.writeFileString(launchAgentPath, "existing launch agent");
const service = yield* BootService.make({
baseDir: dirs.baseDir,
logsDir: dirs.logsDir,
cliVersion: "0.0.27",
host: makeHost(dirs.stableEntry),
}).pipe(
Effect.provide(
makeRecordingRunnerLayer([], {
failWhen: (command, args) => command === "/bin/launchctl" && args.includes("bootout"),
}),
),
provideHostRefs(dirs.home, "darwin"),
);
const error = yield* service.uninstall.pipe(Effect.flip);
assert.isTrue(isCommandError(error));
assert.isTrue(yield* fs.exists(launchAgentPath));
}),
);
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 +695,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);
+383 -38
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,79 @@ 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");
}
const LAUNCH_AGENT_PATH_BLOCK = / <key>PATH<\/key>\n <string>[^\n]*<\/string>\n/;
function isCurrentLaunchAgentDefinition(plist: string, plan: BootServicePlan): boolean {
if (!LAUNCH_AGENT_PATH_BLOCK.test(plist)) {
return false;
}
const planWithoutPath: BootServicePlan = {
nodePath: plan.nodePath,
t3EntryPath: plan.t3EntryPath,
baseDir: plan.baseDir,
logPath: plan.logPath,
unitPath: plan.unitPath,
};
return (
plist.replace(LAUNCH_AGENT_PATH_BLOCK, "") === renderBootServiceLaunchAgent(planWithoutPath)
);
}
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}'.`;
}
}
@@ -130,13 +235,18 @@ export class BootServiceCommandError extends Schema.TaggedErrorClass<BootService
exitCode: Schema.optional(Schema.Number),
stdoutLength: Schema.optional(Schema.Number),
stderrLength: Schema.optional(Schema.Number),
supervisor: Schema.optional(Schema.Literals(["systemd", "launchd"])),
cause: Schema.optional(Schema.Defect()),
},
) {
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.supervisor === "launchd"
? `${detail} If macOS blocked the background item, allow T3 Code in System Settings > General > Login Items & Extensions.`
: detail;
}
}
@@ -157,7 +267,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 +276,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 +302,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 });
}
});
@@ -217,10 +341,20 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
step: string,
command: string,
args: ReadonlyArray<string>,
options?: { readonly timeout?: Duration.Input },
options?: {
readonly timeout?: Duration.Input;
readonly supervisor?: "systemd" | "launchd";
},
) {
return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(
Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),
Effect.mapError(
(cause) =>
new BootServiceCommandError({
step,
cause,
supervisor: options?.supervisor,
}),
),
Effect.filterOrFail(
(result) => result.code === 0,
(result) =>
@@ -229,6 +363,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
exitCode: Number(result.code),
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
supervisor: options?.supervisor,
}),
),
Effect.tapError((error) =>
@@ -244,15 +379,78 @@ 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),
);
});
const isLaunchAgentLoaded = Effect.fn("cloud.boot_service.is_launch_agent_loaded")(function* () {
if (launchAgent === null) {
return false;
}
return yield* runner
.run({
command: "/bin/launchctl",
args: ["print", launchAgent.serviceTarget],
})
.pipe(
Effect.map((result) => result.code === 0),
Effect.mapError(
(cause) =>
new BootServiceCommandError({
step: "checking the LaunchAgent",
supervisor: "launchd",
cause,
}),
),
);
});
const readLaunchAgentDisabled = Effect.fn("cloud.boot_service.read_launch_agent_disabled")(
function* () {
if (launchAgent === null || userId === null) {
return Option.none<boolean>();
}
return yield* runner
.run({
command: "/bin/launchctl",
args: ["print-disabled", `gui/${String(userId)}`],
})
.pipe(
Effect.map((result) =>
result.code === 0
? Option.some(
result.stdout
.split("\n")
.some(
(line) =>
line.includes(BOOT_SERVICE_LAUNCH_AGENT_LABEL) && line.includes("=> true"),
),
)
: Option.none<boolean>(),
),
Effect.orElseSucceed(() => Option.none<boolean>()),
);
},
);
const runLaunchAgentStep = Effect.fn("cloud.boot_service.run_launch_agent_step")(function* (
step: string,
args: ReadonlyArray<string>,
) {
return yield* runStep(step, "/bin/launchctl", args, { supervisor: "launchd" });
});
/**
* 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 +484,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 +537,57 @@ 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>();
const previousLaunchAgentDisabled =
platform === "darwin" ? yield* readLaunchAgentDisabled() : Option.none<boolean>();
const previousLaunchAgentLoaded = platform === "darwin" ? yield* isLaunchAgentLoaded() : false;
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,
previousLaunchAgentDisabled,
previousLaunchAgentLoaded,
),
),
);
// 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* runLaunchAgentStep("enabling the LaunchAgent", [
"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* runLaunchAgentStep("loading the LaunchAgent", ["bootstrap", domain, unitPath]);
yield* runLaunchAgentStep("checking the LaunchAgent", ["print", launchAgent.serviceTarget]);
return;
}
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
@@ -344,7 +607,16 @@ 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,
previousLaunchAgentDisabled,
previousLaunchAgentLoaded,
),
),
);
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
@@ -356,9 +628,39 @@ 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>,
previousLaunchAgentDisabled: Option.Option<boolean>,
previousLaunchAgentLoaded: boolean,
) {
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);
if (Option.getOrElse(previousLaunchAgentDisabled, () => false)) {
yield* runOptionalStep("/bin/launchctl", ["disable", launchAgent.serviceTarget]);
} else if (previousLaunchAgentLoaded) {
yield* runOptionalStep("/bin/launchctl", [
"bootstrap",
`gui/${String(userId)}`,
unitPath,
]);
}
} else {
yield* fs.remove(unitPath).pipe(Effect.ignore);
if (Option.getOrElse(previousLaunchAgentDisabled, () => false)) {
yield* runOptionalStep("/bin/launchctl", ["disable", launchAgent.serviceTarget]);
}
}
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,12 +683,35 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
});
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
yield* requireSystemdLinux;
yield* requireSupportedPlatform;
let stoppedLaunchAgent = false;
if (platform === "darwin" && launchAgent !== null) {
if (yield* isLaunchAgentLoaded()) {
yield* runLaunchAgentStep("stopping the LaunchAgent", [
"bootout",
launchAgent.serviceTarget,
]);
stoppedLaunchAgent = true;
} else {
// Catch a job loaded between the print and bootout without treating
// the expected "not loaded" result as an uninstall failure.
stoppedLaunchAgent = yield* runOptionalStep("/bin/launchctl", [
"bootout",
launchAgent.serviceTarget,
]);
}
}
const exists = yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (!exists) {
return false;
return stoppedLaunchAgent;
}
if (platform === "darwin" && launchAgent !== null) {
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
return true;
}
yield* runStep("stopping the service", "systemctl", [
"--user",
@@ -402,7 +727,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 +739,27 @@ 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 disabled = yield* readLaunchAgentDisabled();
const current =
isCurrentLaunchAgentDefinition(unit, plan) &&
entryExists &&
activeRuntimeIsCurrent &&
loaded &&
!Option.getOrElse(disabled, () => false);
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
+21 -16
View File
@@ -32,17 +32,17 @@ the mismatch and action disappear.
The server resolves its capability once at startup and publishes it in the environment descriptor.
| Advertised value | Process shape | Client behavior |
| ----------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `boot-service` | Linux server running under the T3-managed systemd user service | Call the update RPC; the service unit is replaced and restarted. |
| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
| Advertised value | Process shape | Client behavior |
| ----------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `boot-service` | Server running under the T3-managed systemd user service or macOS LaunchAgent | Call the update RPC; the managed service switches runtime and restarts. |
| `respawn` | Published npm CLI running in the foreground on macOS or Linux | Call the update RPC; the process hands off to a detached replacement. |
| `desktop-managed` | Backend supervised by the desktop app | Tell the user to update the desktop app on the server machine. |
| absent | Older server, development checkout, Windows foreground process, or an unrecognized supervisor | Offer the exact manual relaunch command. |
Desktop ownership takes precedence over process-shape detection. A desktop-managed backend must
never spawn a second CLI server beside the app-owned process. Likewise, a process launched by an
unrecognized systemd unit does not claim the foreground respawn path because its supervisor could
bring the old version back.
unrecognized systemd unit or marked LaunchAgent does not claim the foreground respawn path because
its supervisor could bring the old version back.
## Update Flow
@@ -56,7 +56,7 @@ flowchart TD
F --> G[Run version preflight]
G -->|fails| H[Remove failed runtime and keep current server]
G -->|passes| I{Handoff method}
I -->|boot-service| J[Rewrite and restart T3 systemd unit]
I -->|boot-service| J[Switch runtime and restart managed service]
I -->|respawn| K[Start delayed replacement and exit current process]
J --> L[Client reconnects]
K --> L
@@ -77,10 +77,11 @@ preflight also removes the candidate runtime so retrying the same version perfor
## Host Service Lifecycle
The systemd user service is a host lifecycle concern, not a T3 Connect resource. The standalone
`t3 service install`, `uninstall`, `update`, and `status` commands own it. Install and update both
reconcile the unit through `BootService`; running `npx t3@latest service update` therefore pins and
activates the latest CLI release without requiring a connected client.
The systemd user service or macOS LaunchAgent is a host lifecycle concern, not a T3 Connect
resource. The standalone `t3 service install`, `uninstall`, `update`, and `status` commands own it.
Install and update both reconcile the unit through `BootService`; running
`npx t3@latest service update` therefore pins and activates the latest CLI release without requiring
a connected client.
The `t3 connect` onboarding flow may offer service installation, but it calls the same reconciliation
operation as `t3 service install`. Connect logout only disables cloud access and clears its
@@ -88,9 +89,13 @@ authorization; it does not uninstall the host service.
## Process Handoff
For `boot-service`, the server atomically rewrites the T3-managed user unit to point at the verified
runtime, reloads systemd, and restarts the unit. Reload and restart failures restore the previous
unit before returning an error.
For a systemd `boot-service`, the server atomically rewrites the T3-managed user unit to point at
the verified runtime, reloads systemd, and restarts the unit. Reload and restart failures restore
the previous unit before returning an error.
For a macOS `boot-service`, the LaunchAgent always starts a stable entry path. The server atomically
switches that path to the verified runtime and asks launchd to restart the job. A rejected restart
restores the previous runtime link before returning an error.
For `respawn`, the server starts a detached, delayed replacement that replays the original CLI
arguments. It then acknowledges the request and schedules the current process to exit. The delays
+12 -5
View File
@@ -1,7 +1,14 @@
# Running T3 Code in the Background
On a Linux host, T3 Code can run as a background service for your user. It starts when the machine
boots and keeps running after you log out.
On macOS or Linux, T3 Code can run as a background service for your user. The simplest setup is:
```sh
npx t3 connect
```
After T3 Connect links the machine, accept the default background setup. T3 Code starts immediately
and returns automatically after a reboot. On macOS, the per-user LaunchAgent starts after you sign
in. On Linux, the systemd user service starts at boot and keeps running after you log out.
## Manage the Service
@@ -33,10 +40,10 @@ Updating restarts T3 Code briefly. Let active agent work and terminal commands f
## Using It with T3 Connect
T3 Connect may offer to install the service during setup so the host stays reachable after you log
out. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
T3 Connect offers to install the service during setup so the host starts automatically and stays
reachable in the background. The service and T3 Connect are still managed separately.
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
want T3 Code to start in the background.
The background service currently requires Linux with systemd.
The background service requires macOS with launchd or Linux with systemd.
+2 -2
View File
@@ -21,8 +21,8 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
/** How a server can replace itself with another version when asked over RPC:
"boot-service" rewrites the systemd user unit and restarts it; "respawn"
installs the target version and respawns the foreground process. */
"boot-service" hands off through its systemd unit or macOS LaunchAgent;
"respawn" installs the target version and replaces the foreground process. */
export const ServerSelfUpdateMethod = Schema.Literals(["boot-service", "respawn"]);
export type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;
+7
View File
@@ -51,4 +51,11 @@ export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(
},
);
export const HostProcessUserId = Context.Reference<number | null>(
"@t3tools/shared/hostProcess/HostProcessUserId",
{
defaultValue: () => (typeof process.getuid === "function" ? process.getuid() : null),
},
);
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");