@devries-cameron20 / t3code Mirror · read-only / commits / 93c10239b4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 22:15 UTC

feat(cli): t3 service runs on Windows, so Windows hosts update remotely (#34524)

Co-authored-by: Kayzel <me@kayzel.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Theo Browne committed Nov 11, 2026 at 15:34 UTC 93c10239b415e35a887d69f519b83754b128767e
16 files changed +1110 -123
apps/server/src/bin.ts
+7 -4
@@ -38,10 +38,13 @@ if (
38 })
39 ) {
40 // The launcher owns shutdown until its child exits, so it bypasses the Effect CLI runtime.
41 - // The service unit passes no arguments; flags and help go through the full CLI.
42 - if (process.argv[2] === "__service-launcher" && process.argv.length === 3) {
43 - const { runServiceLauncherCli } = await import("./cli/serviceLauncher.ts");
44 - await runServiceLauncherCli();
41 + // A service unit passes nothing, or on Windows the launcher's own flags; help and anything
42 + // else go through the full CLI.
43 + const launcher =
44 + process.argv[2] === "__service-launcher" ? await import("./cli/serviceLauncher.ts") : undefined;
45 + const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3));
46 + if (launcher !== undefined && launcherOptions !== undefined) {
47 + await launcher.runServiceLauncherCli(launcherOptions);
48 } else {
49 const { runCliCommand } = await loadCliMain();
50 await runCliCommand();
apps/server/src/cli/server.ts
+5 -2
@@ -6,6 +6,7 @@ import * as Schema from "effect/Schema";
6 import { Command, GlobalFlag } from "effect/cli";
7 import * as CliError from "effect/cli/CliError";
8
9 +import { awaitServiceLauncherStop } from "../cloud/serviceLauncherClient.ts";
10 import * as ServerConfig from "../config.ts";
11 import { awaitLauncherLoss } from "../launcherWatch.ts";
12 import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
@@ -35,8 +36,10 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* (
36 const logLevel = yield* GlobalFlag.LogLevel;
37 const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer));
38 const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort });
38 - const run = runServer.pipe(
39 - Effect.provideService(ServerConfig.ServerConfig, config),
39 + const run = Effect.raceFirst(
40 + runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config)),
41 + awaitServiceLauncherStop().pipe(Effect.andThen(Effect.interrupt)),
42 + ).pipe(
43 // Settings' Reclaim stops the server; repair once the database is closed, before the restart.
44 Effect.ensuring(
45 DatabaseMaintenance.runRequestedReclaim(config.dbPath).pipe(
apps/server/src/cli/service.ts
+1 -1
@@ -154,7 +154,7 @@ function formatServiceStatus(
154 protection?: ServiceProtection.ServiceProtectionState,
155 ): string {
156 if (!status.supported) {
157 - return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
157 + return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd, Windows with Task Scheduler";
158 }
159 if (!status.installed) {
160 return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
apps/server/src/cli/serviceLauncher.ts
+20 -3
@@ -1,8 +1,25 @@
1 -import { main as runServiceLauncher } from "../serviceLauncher.ts";
1 +import { type LauncherOptions, main as runServiceLauncher } from "../serviceLauncher.ts";
2
3 -export async function runServiceLauncherCli(): Promise<void> {
3 +/** The flags a Windows task passes, parsed here so the launcher starts without the full CLI. */
4 +export function parseServiceLauncherArgs(args: ReadonlyArray<string>): LauncherOptions | undefined {
5 + let baseDir: string | undefined;
6 + let logFile: string | undefined;
7 + let serviceUnit: string | undefined;
8 + for (let index = 0; index < args.length; index += 2) {
9 + const flag = args[index];
10 + const value = args[index + 1];
11 + if (value === undefined) return undefined;
12 + if (flag === "--base-dir") baseDir = value;
13 + else if (flag === "--log-file") logFile = value;
14 + else if (flag === "--service-unit") serviceUnit = value;
15 + else return undefined;
16 + }
17 + return { baseDir, logFile, serviceUnit };
18 +}
19 +
20 +export async function runServiceLauncherCli(options?: LauncherOptions): Promise<void> {
21 try {
5 - await runServiceLauncher();
22 + await runServiceLauncher(options);
23 } catch (cause) {
24 const message = cause instanceof Error ? cause.message : String(cause);
25 process.stderr.write(`[service-launcher] ${message}\n`);
apps/server/src/cli/update.ts
+1 -1
@@ -596,7 +596,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
596 }
597 if (servicePlan?.handedOff === true) {
598 yield* Console.log(
599 - ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
599 + ` Background service switching to ${targetVersion} outside this session, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`,
600 );
601 } else if (servicePlan !== undefined && restartService) {
602 yield* Console.log(` Background service restarted on ${targetVersion}`);
apps/server/src/cloud/bootService.test.ts
+190 -22
@@ -1,5 +1,6 @@
1 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers.
2 import * as NodeChildProcess from "node:child_process";
3 +import * as NodeSqlite from "node:sqlite";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { expect, it } from "@effect/vitest";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -17,10 +18,13 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18 import { vi } from "vite-plus/test";
19
20 import * as ProcessRunner from "../processRunner.ts";
21 +import { serviceLauncherLockPath } from "../serviceLauncher.ts";
22 import * as BootService from "./bootService.ts";
23 import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
24 import {
25 + disabledServiceTask,
26 parseServiceState,
27 + serviceTaskIsDisabled,
28 SERVICE_ENV_FILE,
29 SERVICE_LAUNCHER_PROTOCOL,
30 SERVICE_RESTART_PENDING_FILE,
@@ -45,7 +49,13 @@ vi.mock("node:fs", async (importOriginal) => {
49 };
50 });
51
48 -it("reads the served T3 home back out of a rendered unit or plist", () => {
52 +const windowsTaskOptions = {
53 + userId: "PC\\theo",
54 + homeDir: "C:\\Users\\theo",
55 + conhostPath: "C:\\Windows\\System32\\conhost.exe",
56 +};
57 +
58 +it("reads the served T3 home back out of a rendered unit, plist, or task", () => {
59 const plan = (baseDir: string) => ({
60 program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"],
61 baseDir,
@@ -69,6 +79,11 @@ it("reads the served T3 home back out of a rendered unit or plist", () => {
79 }),
80 ),
81 ).toBe("/Users/theo/a&b");
82 + expect(
83 + BootService.bootServiceBaseDirOf(
84 + BootService.renderBootServiceTask(plan("C:\\Users\\theo\\T3 a&b\\"), windowsTaskOptions),
85 + ),
86 + ).toBe("C:\\Users\\theo\\T3 a&b\\");
87 expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined();
88 });
89
@@ -99,6 +114,12 @@ it.each([
114 (plan: BootService.BootServicePlan) =>
115 BootService.renderBootServicePlist(plan, { homeDir: "/Users/theo", environmentPath: "" }),
116 ],
117 + [
118 + "a task",
119 + "C:\\Users\\theo\\T3 a&b <c>",
120 + (plan: BootService.BootServicePlan) =>
121 + BootService.renderBootServiceTask(plan, windowsTaskOptions),
122 + ],
123 ] as const)("reads the launcher back out of %s", (_, baseDir, render) => {
124 const program = `${baseDir}/runtime/versions/1.2.3/t3`;
125 expect(
@@ -148,6 +169,10 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
169 lingerStartsManager: boolean;
170 enabled: boolean;
171 active: boolean;
172 + /** A Windows launcher: it holds its lock until its task ends. */
173 + launcher?: { readonly close: () => void };
174 + /** Task Scheduler's own copy of the task. */
175 + task?: { xml: string; enabled: boolean };
176 } = {
177 failCommand: undefined,
178 linger: "yes",
@@ -171,6 +196,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
196 control.managerReachable ||= control.lingerStartsManager;
197 }
198 if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
199 + const taskMissing =
200 + input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined;
201 + if (input.command === "schtasks" && !failed) {
202 + if (input.args[0] === "/Create") {
203 + const xml = yield* fs.readFileString(input.args[2] ?? "");
204 + control.task = { xml, enabled: !serviceTaskIsDisabled(xml) };
205 + }
206 + if (control.task !== undefined && input.args[0] === "/Change") {
207 + control.task.enabled = input.args.includes("/ENABLE");
208 + }
209 + if (input.args[0] === "/Delete") delete control.task;
210 + if (input.args[0] === "/End") control.launcher?.close();
211 + }
212 if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
213 // The manager loads units only from its own unit directory.
214 const unitOutsideManager =
@@ -199,28 +237,35 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
237 ],
238 })
239 : input.args[0] === "--version"
202 - ? `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n`
203 - : input.command === "loginctl" && input.args[0] === "show-user"
204 - ? `${control.linger ?? ""}\n`
205 - : input.args[1] === "is-enabled"
206 - ? control.enabled
207 - ? "enabled\n"
208 - : "disabled\n"
209 - : "",
240 + ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n`
241 + : input.command === "schtasks" && input.args.includes("/XML")
242 + ? control.task?.enabled === false
243 + ? disabledServiceTask(control.task.xml)
244 + : (control.task?.xml ?? "")
245 + : input.command === "loginctl" && input.args[0] === "show-user"
246 + ? `${control.linger ?? ""}\n`
247 + : input.args[1] === "is-enabled"
248 + ? control.enabled
249 + ? "enabled\n"
250 + : "disabled\n"
251 + : "",
252 stderr: "",
253 code: ChildProcessSpawner.ExitCode(
212 - failed ||
213 - unitOutsideManager ||
214 - ((command === "systemctl --user show-environment" || input.command === "busctl") &&
215 - (!control.managerReachable ||
216 - (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) ||
217 - (input.command === "loginctl" &&
218 - input.args[0] === "show-user" &&
219 - control.linger === undefined) ||
220 - (input.args[1] === "is-active" && !control.active) ||
221 - (input.args[1] === "is-enabled" && !control.enabled)
222 - ? 1
223 - : 0,
254 + taskMissing && input.args.includes("/HRESULT")
255 + ? 0x80070002
256 + : failed ||
257 + taskMissing ||
258 + unitOutsideManager ||
259 + ((command === "systemctl --user show-environment" || input.command === "busctl") &&
260 + (!control.managerReachable ||
261 + (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) ||
262 + (input.command === "loginctl" &&
263 + input.args[0] === "show-user" &&
264 + control.linger === undefined) ||
265 + (input.args[1] === "is-active" && !control.active) ||
266 + (input.args[1] === "is-enabled" && !control.enabled)
267 + ? 1
268 + : 0,
269 ),
270 timedOut: false,
271 stdoutTruncated: false,
@@ -265,10 +310,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
310 env: {
311 HOME: home,
312 ...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }),
313 + USERPROFILE: home,
314 + LOCALAPPDATA: path.join(home, "AppData", "Local"),
315 + USERDOMAIN: "PC",
316 + USERNAME: "theo",
317 ...(environmentPath === undefined || environmentPath === ""
318 ? {}
319 : { PATH: environmentPath }),
271 - ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
320 + ...(insideService
321 + ? {
322 + T3_BOOT_SERVICE_UNIT:
323 + platform === "win32" ? "t3code-task.xml" : "t3code.service",
324 + }
325 + : {}),
326 ...(underSudo ? { SUDO_USER: "julius" } : {}),
327 },
328 }),
@@ -1224,6 +1278,120 @@ process.disconnect();
1278 }),
1279 );
1280
1281 + it.effect("installs, reports a stopped launcher, and uninstalls on Windows", () =>
1282 + Effect.gen(function* () {
1283 + const { service, fs, statePath, commands, control, runtime } = yield* makeHarness("win32");
1284 + const path = yield* Path.Path;
1285 + const plan = yield* service.install();
1286 + const task = yield* fs.readFileString(plan.unitPath);
1287 +
1288 + expect(plan.unitPath).toBe(
1289 + path.join(path.dirname(plan.baseDir), "AppData", "Local", "t3code", "t3code-task.xml"),
1290 + );
1291 + expect(BootService.bootServiceProgramOf(task)).toBe(runtime.entryPath);
1292 + expect(BootService.bootServiceBaseDirOf(task)).toBe(plan.baseDir);
1293 + expect(task).toContain("<UserId>PC\\theo</UserId>");
1294 + expect(task).toContain("<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>");
1295 + expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1296 + protocol: SERVICE_LAUNCHER_PROTOCOL,
1297 + activeVersion: "1.2.3",
1298 + });
1299 + expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([
1300 + `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`,
1301 + "schtasks /Run /TN t3code-PC-theo",
1302 + ]);
1303 + // No launcher holds the lock here.
1304 + expect(yield* service.status).toMatchObject({
1305 + installed: true,
1306 + current: false,
1307 + problems: ["service-stopped"],
1308 + });
1309 +
1310 + // A task that Task Scheduler refuses to delete stays installed, so a retry finds it.
1311 + control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F";
1312 + expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError");
1313 + expect((yield* service.status).installed).toBe(true);
1314 + control.failCommand = undefined;
1315 +
1316 + commands.length = 0;
1317 + expect(yield* service.uninstall).toBe(true);
1318 + expect(commands).toEqual([
1319 + "schtasks /Change /TN t3code-PC-theo /DISABLE",
1320 + "schtasks /End /TN t3code-PC-theo",
1321 + "schtasks /Delete /TN t3code-PC-theo /F",
1322 + ]);
1323 + expect(control.task).toBeUndefined();
1324 + expect((yield* service.status).installed).toBe(false);
1325 +
1326 + // One removed by hand leaves nothing to disable or delete.
1327 + yield* service.install();
1328 + delete control.task;
1329 + expect(yield* service.uninstall).toBe(true);
1330 + }),
1331 + );
1332 +
1333 + it.effect("stops a Windows launcher by ending its task, and restarts one left disabled", () =>
1334 + Effect.gen(function* () {
1335 + const { service, commands, control, makeService } = yield* makeHarness("win32");
1336 + const plan = yield* service.install();
1337 + const launcher = new NodeSqlite.DatabaseSync(serviceLauncherLockPath(plan.baseDir));
1338 + launcher.exec("BEGIN EXCLUSIVE");
1339 + control.launcher = launcher;
1340 +
1341 + // Task Scheduler runs its own copy of the task, so a deferred restart registers the new one.
1342 + const newer = yield* makeService(undefined, "1.2.4");
1343 + yield* newer.install({ start: false });
1344 + const newerRuntime = pinnedRuntimePaths(yield* Path.Path, plan.baseDir, "1.2.4", "win32");
1345 + expect(BootService.bootServiceProgramOf(control.task?.xml ?? "")).toBe(
1346 + newerRuntime.entryPath,
1347 + );
1348 + expect(control.task?.enabled).toBe(true);
1349 +
1350 + // An interrupted stop disables the task and leaves its launcher running.
1351 + yield* service.install({ start: false, allowDowngrade: true });
1352 + control.task = { xml: control.task?.xml ?? "", enabled: false };
1353 + yield* newer.install({ start: false });
1354 + expect(control.task).toMatchObject({ enabled: false });
1355 + expect(BootService.bootServiceProgramOf(control.task.xml)).toBe(newerRuntime.entryPath);
1356 + expect((yield* service.status).problems).toEqual(["service-disabled", "restart-pending"]);
1357 +
1358 + commands.length = 0;
1359 + yield* service.withStopped(Effect.sync(() => commands.push("repair")));
1360 + expect(commands.filter((command) => !command.includes("/Query"))).toEqual([
1361 + "schtasks /Change /TN t3code-PC-theo /DISABLE",
1362 + "schtasks /End /TN t3code-PC-theo",
1363 + "repair",
1364 + "schtasks /Change /TN t3code-PC-theo /ENABLE",
1365 + "schtasks /Run /TN t3code-PC-theo",
1366 + ]);
1367 + }),
1368 + );
1369 +
1370 + it.effect("hands an in-service install and restart to Task Scheduler on Windows", () =>
1371 + Effect.gen(function* () {
1372 + const { service, fs, statePath, commands, makeService } = yield* makeHarness("win32");
1373 + const plan = yield* service.install();
1374 + const inside = yield* makeService(undefined, "1.2.4", undefined, true);
1375 + const handoff = [
1376 + `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`,
1377 + "schtasks /End /TN t3code-PC-theo",
1378 + "schtasks /Run /TN t3code-PC-theo",
1379 + ];
1380 + commands.length = 0;
1381 +
1382 + expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath });
1383 + expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff);
1384 + expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4");
1385 + expect(
1386 + yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`),
1387 + ).toBe("1.2.4\n");
1388 +
1389 + commands.length = 0;
1390 + expect(yield* inside.restart).toBe("queued");
1391 + expect(commands).toEqual(handoff);
1392 + }),
1393 + );
1394 +
1395 // regression: #8173 keep provider CLIs available in the macOS service
1396 it.effect("reconstructs a launch agent search path when the installer has no PATH", () =>
1397 Effect.gen(function* () {
apps/server/src/cloud/bootService.ts
+368 -29
@@ -18,6 +18,12 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
18
19 import * as ProcessRunner from "../processRunner.ts";
20 import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
21 +import {
22 + serviceLauncherIsRunning,
23 + serviceLauncherLockPath,
24 + serviceTaskName,
25 + waitForServiceLauncherExit,
26 +} from "../serviceLauncher.ts";
27 import {
28 ensurePinnedRuntimeInstalled,
29 launcherOwnsVersionsDir,
@@ -32,6 +38,8 @@ import {
38 SERVICE_STATE_FILE,
39 SERVICE_UNIT_ENV,
40 compareExactServiceVersions,
41 + disabledServiceTask,
42 + serviceTaskIsDisabled,
43 serviceUnitBaseDirOf as bootServiceBaseDirOf,
44 parseServiceState,
45 serviceStateActiveVersion,
@@ -51,6 +59,10 @@ export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
59 export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
60 export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
61 export const BOOT_SERVICE_LOG_FILE = "boot-service.log";
62 +/** `schtasks /Query /HRESULT` exits with this when the task is not registered. */
63 +const WINDOWS_TASK_NOT_FOUND = 0x80070002;
64 +/** Task Scheduler keeps its own copy; this one lets status and repair read the task back. */
65 +const BOOT_SERVICE_TASK_FILE = `${BOOT_SERVICE_NAME}-task.xml`;
66
67 /** systemd expands `%` specifiers, including in unquoted append-log paths. */
68 function escapeSystemdSpecifiers(value: string): string {
@@ -64,6 +76,9 @@ function quoteSystemdValue(value: string): string {
76 : escaped;
77 }
78
79 +/** Windows paths cannot contain `"`; only backslashes before the closing quote need doubling. */
80 +const quoteWindowsArgument = (value: string) => `"${value.replace(/(\\+)$/, "$1$1")}"`;
81 +
82 export interface BootServicePlan {
83 readonly program: ReadonlyArray<string>;
84 readonly baseDir: string;
@@ -169,20 +184,87 @@ export function renderBootServicePlist(
184 ].join("\n");
185 }
186
172 -export interface BootServiceStep {
187 +/**
188 + * Task Scheduler can neither set variables nor redirect output, so the launcher takes them as
189 + * flags. A console program started by a task opens a window unless a headless console hosts it.
190 + * No XML declaration: schtasks rejects `encoding="UTF-8"` but reads undeclared XML as UTF-8.
191 + */
192 +export function renderBootServiceTask(
193 + plan: BootServicePlan,
194 + options: { readonly userId: string; readonly homeDir: string; readonly conhostPath: string },
195 +): string {
196 + const launcherArguments = [
197 + ...plan.program,
198 + "--base-dir",
199 + plan.baseDir,
200 + "--log-file",
201 + plan.logPath,
202 + "--service-unit",
203 + BOOT_SERVICE_TASK_FILE,
204 + ]
205 + .map(quoteWindowsArgument)
206 + .join(" ");
207 + // conhost reports exit code 0 whatever the launcher returns, so restart-on-failure never
208 + // fires. A repeating trigger with IgnoreNew starts the task again within a minute instead.
209 + // Priority 5 is normal; the default 7 runs below it.
210 + return [
211 + `<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">`,
212 + ` <RegistrationInfo>`,
213 + ` <Description>T3 Code server</Description>`,
214 + ` </RegistrationInfo>`,
215 + ` <Triggers>`,
216 + ` <LogonTrigger>`,
217 + ` <UserId>${escapeXmlText(options.userId)}</UserId>`,
218 + ` </LogonTrigger>`,
219 + ` <TimeTrigger>`,
220 + ` <StartBoundary>2000-01-01T00:00:00</StartBoundary>`,
221 + ` <Repetition>`,
222 + ` <Interval>PT1M</Interval>`,
223 + ` </Repetition>`,
224 + ` </TimeTrigger>`,
225 + ` </Triggers>`,
226 + ` <Principals>`,
227 + ` <Principal id="Author">`,
228 + ` <UserId>${escapeXmlText(options.userId)}</UserId>`,
229 + ` <LogonType>InteractiveToken</LogonType>`,
230 + ` <RunLevel>LeastPrivilege</RunLevel>`,
231 + ` </Principal>`,
232 + ` </Principals>`,
233 + ` <Settings>`,
234 + ` <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>`,
235 + ` <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>`,
236 + ` <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>`,
237 + ` <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>`,
238 + ` <Priority>5</Priority>`,
239 + ` </Settings>`,
240 + ` <Actions Context="Author">`,
241 + ` <Exec>`,
242 + ` <Command>${escapeXmlText(options.conhostPath)}</Command>`,
243 + ` <Arguments>--headless ${escapeXmlText(launcherArguments)}</Arguments>`,
244 + ` <WorkingDirectory>${escapeXmlText(options.homeDir)}</WorkingDirectory>`,
245 + ` </Exec>`,
246 + ` </Actions>`,
247 + `</Task>`,
248 + ``,
249 + ].join("\n");
250 +}
251 +
252 +export type BootServiceStep = {
253 readonly step: string;
174 - readonly command: string;
175 - readonly args: ReadonlyArray<string>;
254 /** Non-zero exit is logged and ignored. */
255 readonly optional?: boolean;
256 readonly timeout?: Duration.Input;
179 -}
257 +} & (
258 + | { readonly command: string; readonly args: ReadonlyArray<string> }
259 + /** A step no command can do, such as waiting for the Windows launcher to exit. */
260 + | { readonly run: Effect.Effect<void, BootServiceCommandError> }
261 +);
262
263 /** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */
264 const STOP_STEP_TIMEOUT = Duration.seconds(120);
265
266 export interface BootServiceManager {
185 - readonly kind: "systemd" | "launchd";
267 + readonly kind: "systemd" | "launchd" | "schtasks";
268 readonly unitPath: string;
269 readonly render: (plan: BootServicePlan) => string;
270 readonly stop: ReadonlyArray<BootServiceStep>;
@@ -201,6 +283,9 @@ const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome:
283 "user",
284 );
285
286 +const scheduledTaskPath = (path: Path.Path, localAppData: string) =>
287 + path.join(localAppData, "t3code", BOOT_SERVICE_TASK_FILE);
288 +
289 const launchdPlistPath = (path: Path.Path, homeDir: string) =>
290 path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE);
291
@@ -337,6 +422,82 @@ function launchdManager(input: {
422 };
423 }
424
425 +export interface WindowsSession {
426 + readonly localAppData: string;
427 + /** `DOMAIN\user`, the account whose logon starts the task. */
428 + readonly userId: string;
429 + readonly taskName: string;
430 + readonly systemRoot: string;
431 +}
432 +
433 +/** The steps one `schtasks` command cannot do. */
434 +interface WindowsTaskSteps {
435 + /** Disables the task, or the repeating trigger restarts a service that should stay stopped. */
436 + readonly disable: Effect.Effect<void, BootServiceCommandError>;
437 + /** Ends the task and waits for its launcher to exit; Task Scheduler does not wait. */
438 + readonly stopLauncher: Effect.Effect<void, BootServiceCommandError>;
439 + readonly remove: Effect.Effect<void, BootServiceCommandError>;
440 +}
441 +
442 +function schtasksManager(input: {
443 + readonly path: Path.Path;
444 + readonly homeDir: string;
445 + readonly session: WindowsSession;
446 + readonly steps: WindowsTaskSteps;
447 +}): BootServiceManager {
448 + const unitPath = scheduledTaskPath(input.path, input.session.localAppData);
449 + const task = ["/TN", input.session.taskName];
450 + const register = {
451 + step: "registering the scheduled task",
452 + command: "schtasks",
453 + args: ["/Create", "/XML", unitPath, ...task, "/F"],
454 + };
455 + const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] };
456 + const stop: ReadonlyArray<BootServiceStep> = [
457 + { step: "disabling the scheduled task", run: input.steps.disable },
458 + {
459 + step: "stopping the installed service",
460 + run: input.steps.stopLauncher,
461 + timeout: STOP_STEP_TIMEOUT,
462 + },
463 + ];
464 + return {
465 + kind: "schtasks",
466 + unitPath,
467 + render: (plan) =>
468 + renderBootServiceTask(plan, {
469 + userId: input.session.userId,
470 + homeDir: input.homeDir,
471 + conhostPath: input.path.join(input.session.systemRoot, "System32", "conhost.exe"),
472 + }),
473 + stop,
474 + // Registration also enables the task.
475 + activate: [register, run],
476 + restart: [
477 + {
478 + step: "enabling the scheduled task",
479 + command: "schtasks",
480 + args: ["/Change", ...task, "/ENABLE"],
481 + },
482 + { ...run, step: "restarting the service after a failed update" },
483 + ],
484 + // Ending the task kills only its console host; the launcher sees the console close and
485 + // stops gracefully while the replacement waits for its lock.
486 + handoff: [
487 + register,
488 + {
489 + step: "ending the scheduled task",
490 + command: "schtasks",
491 + args: ["/End", ...task],
492 + optional: true,
493 + },
494 + { ...run, step: "restarting the service" },
495 + ],
496 + deactivate: [...stop, { step: "removing the scheduled task", run: input.steps.remove }],
497 + finalize: [],
498 + };
499 +}
500 +
501 function selectBootServiceManager(input: {
502 readonly platform: NodeJS.Platform;
503 readonly homeDir: string;
@@ -345,10 +506,14 @@ function selectBootServiceManager(input: {
506 readonly uid: number | undefined;
507 readonly path: Path.Path;
508 readonly environmentPath: string;
509 + readonly windows?: { readonly session: WindowsSession; readonly steps: WindowsTaskSteps };
510 }): BootServiceManager | undefined {
511 if (input.homeDir === "") {
512 return undefined;
513 }
514 + if (input.platform === "win32" && input.windows !== undefined) {
515 + return schtasksManager({ path: input.path, homeDir: input.homeDir, ...input.windows });
516 + }
517 if (input.platform === "linux") {
518 return systemdManager({
519 path: input.path,
@@ -409,6 +574,10 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun
574 const homeDir = yield* HostProcess.HomeDirectory;
575 if (homeDir === "") return undefined;
576 if (platform === "darwin") return launchdPlistPath(path, homeDir);
577 + if (platform === "win32") {
578 + const localAppData = (yield* HostProcess.Environment).LOCALAPPDATA ?? "";
579 + return localAppData === "" ? undefined : scheduledTaskPath(path, localAppData);
580 + }
581 if (platform !== "linux") return undefined;
582 const unitDir =
583 (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ??
@@ -421,7 +590,7 @@ export class BootServiceUnsupportedError extends Schema.TaggedError<BootServiceU
590 { platform: Schema.String },
591 ) {
592 override get message(): string {
424 - return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
593 + return `Background setup supports Linux with systemd, macOS with launchd, and Windows with Task Scheduler; this machine reports '${this.platform}'.`;
594 }
595 }
596
@@ -472,7 +641,7 @@ export function formatBootServiceProblem(problem: BootServiceProblem): string {
641 case "service-disabled":
642 return "The service is not enabled to start automatically. Run `t3 service install` to repair it.";
643 case "service-stopped":
475 - return "The service is not running. Check the service log and `systemctl --user status t3code.service`, then run `t3 service install`.";
644 + return "The service is not running. Check the service log (on Linux, also `systemctl --user status t3code.service`), then run `t3 service install`.";
645 case "restart-pending":
646 return "A newer version is installed but the service is still running the previous one. Run `t3 service restart` to switch.";
647 }
@@ -598,16 +767,18 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
767 const releaseBaseUrl = Option.getOrUndefined(
768 yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option),
769 );
601 - const homeDir = yield* Config.String("HOME").pipe(Config.withDefault(""));
770 + const homeDir = yield* Config.String(platform === "win32" ? "USERPROFILE" : "HOME").pipe(
771 + Config.withDefault(""),
772 + );
773 const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault(""));
774 const installerPath = yield* Config.String("PATH").pipe(Config.withDefault(""));
775 const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault(""));
776 // Root under sudo must not reach or start a separate root service.
777 const rootUnderSudo =
778 uid === 0 && (yield* Config.String("SUDO_USER").pipe(Config.withDefault(""))) !== "";
608 - const runningInsideService =
609 - (yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
610 - BOOT_SERVICE_UNIT_FILE;
779 + const runningInsideService = [BOOT_SERVICE_UNIT_FILE, BOOT_SERVICE_TASK_FILE].includes(
780 + yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault("")),
781 + );
782 const fs = yield* FileSystem.FileSystem;
783 const path = yield* Path.Path;
784 const processRunner = yield* ProcessRunner.ProcessRunner;
@@ -654,6 +825,107 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
825 ),
826 ).join(":");
827
828 + const windowsVariable = (name: string) =>
829 + platform === "win32" ? Config.String(name).pipe(Config.withDefault("")) : Config.succeed("");
830 + const windowsSession: WindowsSession = {
831 + localAppData: yield* windowsVariable("LOCALAPPDATA"),
832 + userId: `${yield* windowsVariable("USERDOMAIN")}\\${yield* windowsVariable("USERNAME")}`,
833 + taskName: serviceTaskName(
834 + yield* windowsVariable("USERDOMAIN"),
835 + yield* windowsVariable("USERNAME"),
836 + ),
837 + systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows",
838 + };
839 + // The unit is per user, so the launcher to stop is the one serving the installed unit's home.
840 + const launcherLockPath = (unit: Option.Option<string>) =>
841 + serviceLauncherLockPath(
842 + Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir,
843 + );
844 + const windowsTask = ["/TN", windowsSession.taskName];
845 + /** Runs a command that changes the task; a task that is not registered has nothing to change. */
846 + const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* (
847 + step: string,
848 + verb: string,
849 + flag: string,
850 + ) {
851 + const toError = (cause: unknown) => new BootServiceCommandError({ step, cause });
852 + const changed = yield* runner
853 + .run({ command: "schtasks", args: [verb, ...windowsTask, flag] })
854 + .pipe(Effect.mapError(toError));
855 + if (changed.code === 0) return;
856 + const queried = yield* runner
857 + .run({
858 + command: "schtasks",
859 + args: ["/Query", ...windowsTask, "/HRESULT"],
860 + timeout: Duration.seconds(5),
861 + })
862 + .pipe(Effect.mapError(toError));
863 + if (Number(queried.code) >>> 0 === WINDOWS_TASK_NOT_FOUND) return;
864 + return yield* new BootServiceCommandError({
865 + step,
866 + exitCode: Number(changed.code),
867 + stdoutLength: changed.stdout.length,
868 + stderrLength: changed.stderr.length,
869 + });
870 + });
871 + // Under the unit lease: a launcher registering its task again reads whether it is disabled
872 + // first, and must not do that around this.
873 + const disableWindowsTask = Effect.suspend(() =>
874 + Effect.acquireUseRelease(
875 + Effect.tryPromise({
876 + try: () => acquireServiceSelectionLock(unitPath),
877 + catch: (cause) =>
878 + new BootServiceCommandError({ step: "disabling the scheduled task", cause }),
879 + }),
880 + () => changeWindowsTask("disabling the scheduled task", "/Change", "/DISABLE"),
881 + (release) => Effect.sync(release),
882 + ),
883 + );
884 + /**
885 + * Task Scheduler runs its own copy of the task, so an install that starts nothing still
886 + * registers the new one. A task that was disabled or absent stays stopped.
887 + */
888 + const refreshWindowsTask = Effect.fn("cloud.boot_service.refresh_windows_task")(function* (
889 + unit: string,
890 + ) {
891 + const register = (xmlPath: string) =>
892 + runStep("registering the scheduled task", "schtasks", [
893 + "/Create",
894 + "/XML",
895 + xmlPath,
896 + ...windowsTask,
897 + "/F",
898 + ]);
899 + const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]);
900 + if (
901 + Option.isSome(registered) &&
902 + registered.value.code === 0 &&
903 + !serviceTaskIsDisabled(registered.value.stdout)
904 + ) {
905 + return yield* register(unitPath);
906 + }
907 + return yield* Effect.scoped(
908 + Effect.gen(function* () {
909 + const disabledPath = yield* fs.makeTempFileScoped({
910 + directory: path.dirname(unitPath),
911 + prefix: ".service-task-",
912 + });
913 + yield* fs.writeFileString(disabledPath, disabledServiceTask(unit));
914 + yield* register(disabledPath);
915 + }),
916 + );
917 + });
918 + // Ending the task closes the launcher's console, which the launcher takes as its SIGTERM.
919 + // Task Scheduler then reports the task stopped at once, so the lock says when it really is.
920 + const stopWindowsLauncher = Effect.gen(function* () {
921 + const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
922 + yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore);
923 + yield* Effect.tryPromise({
924 + try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal),
925 + catch: (cause) =>
926 + new BootServiceCommandError({ step: "stopping the installed service", cause }),
927 + });
928 + });
929 const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
930 const resolveTarget = (systemdUnitDir: string | undefined) => {
931 const manager = selectBootServiceManager({
@@ -664,6 +936,18 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
936 uid,
937 path,
938 environmentPath,
939 + ...(windowsSession.localAppData === "" || windowsSession.userId === "\\"
940 + ? {}
941 + : {
942 + windows: {
943 + session: windowsSession,
944 + steps: {
945 + disable: disableWindowsTask,
946 + stopLauncher: stopWindowsLauncher,
947 + remove: changeWindowsTask("removing the scheduled task", "/Delete", "/F"),
948 + },
949 + },
950 + }),
951 });
952 const unitPath = manager?.unitPath ?? "";
953 const plan: BootServicePlan = {
@@ -745,12 +1029,21 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1029 Effect.forEach(
1030 steps,
1031 (entry) => {
748 - const run = runStep(
749 - entry.step,
750 - entry.command,
751 - entry.args,
752 - entry.timeout === undefined ? undefined : { timeout: entry.timeout },
753 - );
1032 + const run =
1033 + "run" in entry
1034 + ? entry.run.pipe(
1035 + Effect.timeoutOrElse({
1036 + duration: entry.timeout ?? Duration.seconds(60),
1037 + orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })),
1038 + }),
1039 + Effect.tapError(logFailure),
1040 + )
1041 + : runStep(
1042 + entry.step,
1043 + entry.command,
1044 + entry.args,
1045 + entry.timeout === undefined ? undefined : { timeout: entry.timeout },
1046 + );
1047 return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
1048 },
1049 { discard: true },
@@ -844,6 +1137,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1137 (release) => Effect.sync(release),
1138 );
1139
1140 + // Running means the launcher holds its lock: a task can stay running after the
1141 + // launcher exits, while agents it left behind hold the console host open.
1142 + const readSchtasksProblems = Effect.fn("cloud.boot_service.read_schtasks_problems")(function* (
1143 + unit: Option.Option<string>,
1144 + ) {
1145 + const [task, running] = yield* Effect.all(
1146 + [
1147 + probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]),
1148 + Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))),
1149 + ],
1150 + { concurrency: "unbounded" },
1151 + );
1152 + const problems: BootServiceProblem[] = [];
1153 + if (Option.isNone(task) || task.value.code !== 0 || serviceTaskIsDisabled(task.value.stdout)) {
1154 + problems.push("service-disabled");
1155 + }
1156 + if (!running) problems.push("service-stopped");
1157 + return problems;
1158 + });
1159 +
1160 const install = Effect.fn("cloud.boot_service.install")(function* (options?: {
1161 readonly allowDowngrade?: boolean;
1162 readonly start?: boolean;
@@ -959,7 +1272,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1272 ]);
1273 return { ...plan, handedOff: true };
1274 }
962 - if (installed && start) {
1275 + // Task Scheduler restarts the task itself, so the files are written as for a deferred
1276 + // restart while this launcher keeps running, then the restart is handed to the manager.
1277 + const handOff = installed && start && runningInsideService && manager.kind === "schtasks";
1278 + if (installed && start && !handOff) {
1279 yield* runSteps(manager.stop);
1280 }
1281
@@ -975,11 +1291,17 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1291 if (Option.isSome(previousStateText)) {
1292 const installedVersion = serviceStateActiveVersion(previousStateText.value);
1293 if (serviceStateHasPendingUpdate(previousStateText.value)) {
978 - const quote = (word: string) => `'${word.replaceAll("'", "'\\''")}'`;
1294 + const windows = platform === "win32";
1295 + const quote = (word: string) => `'${word.replaceAll("'", windows ? "''" : "'\\''")}'`;
1296 + const launcher = (version: string) =>
1297 + quote(pinnedRuntimePaths(path, input.baseDir, version, platform).entryPath);
1298 return yield* new BootServiceUpdatePendingError(
1299 !currentlyInstalled && installedVersion !== undefined
1300 ? {
982 - recoveryCommand: `T3CODE_HOME=${quote(input.baseDir)} ${quote(pinnedRuntimePaths(path, input.baseDir, installedVersion, platform).entryPath)} __service-launcher`,
1301 + // PowerShell has no inline variable assignment; the launcher takes a flag.
1302 + recoveryCommand: windows
1303 + ? `& ${launcher(installedVersion)} __service-launcher --base-dir ${quote(input.baseDir)}`
1304 + : `T3CODE_HOME=${quote(input.baseDir)} ${launcher(installedVersion)} __service-launcher`,
1305 }
1306 : {},
1307 );
@@ -1013,19 +1335,23 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1335 2,
1336 )}\n`,
1337 );
1016 - if (!start && (currentlyInstalled || Option.isSome(previousStateText))) {
1338 + if ((!start || handOff) && (currentlyInstalled || Option.isSome(previousStateText))) {
1339 const written = yield* fs.readFileString(statePath);
1340 if (serviceStateActiveVersion(written) !== input.cliVersion) {
1341 return yield* new BootServiceUpdatePendingError();
1342 }
1343 }
1022 - yield* writeDurably(unitPath, manager.render(plan));
1344 + const unit = manager.render(plan);
1345 + yield* writeDurably(unitPath, unit);
1346 + if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit);
1347 }),
1348 ),
1349 ).pipe(
1350 Effect.andThen(
1351 Effect.gen(function* () {
1028 - if (start) {
1352 + if (handOff) {
1353 + yield* runSteps(manager.handoff ?? []);
1354 + } else if (start) {
1355 yield* runSteps(manager.activate);
1356 yield* withSelectionLock(
1357 statePath,
@@ -1044,10 +1370,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1370 cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause,
1371 ),
1372 Effect.tapError(() =>
1047 - installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
1373 + installed && start && !handOff
1374 + ? runSteps(manager.restart).pipe(Effect.ignore)
1375 + : Effect.void,
1376 ),
1377 );
1050 - return plan;
1378 + return handOff ? { ...plan, handedOff: true } : plan;
1379 });
1380
1381 const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
@@ -1109,9 +1437,16 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1437 ),
1438 ([enabled, active]) => succeeded(active) || succeeded(enabled),
1439 )
1112 - : succeeded(
1113 - yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1114 - );
1440 + : manager.kind === "schtasks"
1441 + ? // A task disabled while its launcher runs was left that way by an interrupted stop.
1442 + yield* Effect.map(
1443 + readSchtasksProblems(unit),
1444 + (problems) =>
1445 + !problems.includes("service-disabled") || !problems.includes("service-stopped"),
1446 + )
1447 + : succeeded(
1448 + yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
1449 + );
1450 return yield* Effect.acquireUseRelease(
1451 // Require every stop before repair when restoring, so the server releases the database.
1452 // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job.
@@ -1170,7 +1505,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1505 ? contents.replace(/(<key>PATH<\/key>\n\s*<string>)[^<]*(<\/string>)/, "$1$2")
1506 : contents;
1507 const problems: BootServiceProblem[] =
1173 - manager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : [];
1508 + manager.kind === "systemd"
1509 + ? [...(yield* readSystemdProblems(true))]
1510 + : manager.kind === "schtasks"
1511 + ? [...(yield* readSchtasksProblems(Option.some(unit)))]
1512 + : [];
1513 if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending");
1514 return {
1515 supported: true,
apps/server/src/cloud/serviceLauncherClient.test.ts
+18
@@ -119,6 +119,24 @@ it.effect("preserves a launcher rejection as a distinct error", () =>
119 }),
120 );
121
122 +it.effect("stops the server when the launcher asks over IPC", () =>
123 + Effect.gen(function* () {
124 + const host = new FakeLauncherProcess({
125 + protocol: SERVICE_LAUNCHER_PROTOCOL,
126 + childVersion: "1.0.0",
127 + });
128 + const stopped = yield* Effect.forkChild(
129 + ServiceLauncherClient.awaitServiceLauncherStop({ currentVersion: "1.0.0" }).pipe(
130 + Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host),
131 + Effect.provideService(HostProcess.Environment, host.env),
132 + ),
133 + { startImmediately: true },
134 + );
135 + host.emit({ type: "stop" });
136 + yield* Fiber.join(stopped);
137 + }),
138 +);
139 +
140 it.effect("rejects contradictory trial context instead of leaving activation closed", () =>
141 Effect.gen(function* () {
142 const host = new FakeLauncherProcess({
apps/server/src/cloud/serviceLauncherClient.ts
+17
@@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8
9 import packageJson from "../../package.json" with { type: "json" };
@@ -141,6 +142,22 @@ export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_clie
142 },
143 );
144
145 +/** Completes when the launcher asks this server to stop, which Windows cannot signal. */
146 +export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")(
147 + function* (options?: { readonly currentVersion?: string }) {
148 + const startup = yield* resolveStartup(options).pipe(Effect.option);
149 + if (Option.isNone(startup) || !startup.value.managed) return yield* Effect.never;
150 + const { host } = startup.value;
151 + return yield* Effect.callback<void>((resume) => {
152 + const onMessage = (...args: ReadonlyArray<unknown>) => {
153 + if (decodeServiceLauncherParentMessage(args[0])?.type === "stop") resume(Effect.void);
154 + };
155 + host.on("message", onMessage);
156 + return Effect.sync(() => host.off("message", onMessage));
157 + });
158 + },
159 +);
160 +
161 export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: {
162 readonly currentVersion?: string;
163 }) {
apps/server/src/cloud/serviceProtocol.ts
+27 -3
@@ -21,6 +21,8 @@ export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
21 export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
22 /** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
23 export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
24 +/** Held by a Windows launcher while it runs: Task Scheduler tracks only the task's console host. */
25 +export const SERVICE_LAUNCHER_LOCK_FILE = "service-launcher.lock";
26
27 const unquoteSystemdValue = (raw: string) =>
28 (raw.startsWith('"') && raw.endsWith('"')
@@ -31,21 +33,38 @@ const unquoteSystemdValue = (raw: string) =>
33 const unescapeXmlText = (value: string) =>
34 value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
35
36 +const unquoteWindowsArgument = (raw: string) =>
37 + unescapeXmlText(raw).replace(/(\\+)$/, (slashes) => slashes.slice(slashes.length / 2));
38 +
39 +/** Whether Task Scheduler's copy of a task is disabled as a whole, not one of its triggers. */
40 +export const serviceTaskIsDisabled = (taskXml: string): boolean =>
41 + /<Settings>[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("<Enabled>false</Enabled>") === true;
42 +
43 +/** A task as Task Scheduler should hold it while its service must stay stopped. */
44 +export const disabledServiceTask = (taskXml: string): string =>
45 + serviceTaskIsDisabled(taskXml)
46 + ? taskXml
47 + : taskXml.replace(" </Settings>", " <Enabled>false</Enabled>\n </Settings>");
48 +
49 export function serviceUnitBaseDirOf(contents: string): string | undefined {
50 const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
51 if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());
52 const plist = /<key>T3CODE_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(contents)?.[1];
38 - return plist === undefined ? undefined : unescapeXmlText(plist);
53 + if (plist !== undefined) return unescapeXmlText(plist);
54 + const task = /<Arguments>[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1];
55 + return task === undefined ? undefined : unquoteWindowsArgument(task);
56 }
57
41 -/** The executable an installed unit or plist starts: the launcher's runtime. */
58 +/** The executable an installed unit, plist, or task starts: the launcher's runtime. */
59 export function serviceUnitProgramOf(contents: string): string | undefined {
60 const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1];
61 if (systemd !== undefined) return unquoteSystemdValue(systemd);
62 const plist = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(
63 contents,
64 )?.[1];
48 - return plist === undefined ? undefined : unescapeXmlText(plist);
65 + if (plist !== undefined) return unescapeXmlText(plist);
66 + const task = /<Arguments>--headless "([^"]*)"/.exec(contents)?.[1];
67 + return task === undefined ? undefined : unquoteWindowsArgument(task);
68 }
69
70 export interface PendingServiceUpdate {
@@ -93,6 +112,10 @@ export type ServiceLauncherParentMessage =
112 | {
113 readonly type: "committed";
114 readonly updateId: string;
115 + }
116 + | {
117 + /** Shut down as on SIGTERM, which Windows cannot deliver. */
118 + readonly type: "stop";
119 };
120
121 const SEMVER_NUMBER = "(?:0|[1-9]\\d*)";
@@ -309,6 +332,7 @@ export function decodeServiceLauncherParentMessage(
332 if (value.type === "update-accepted" && typeof value.updateId === "string") {
333 return { type: value.type, updateId: value.updateId };
334 }
335 + if (value.type === "stop") return { type: value.type };
336 return value.type === "committed" && typeof value.updateId === "string"
337 ? { type: value.type, updateId: value.updateId }
338 : undefined;
apps/server/src/serviceLauncher.test.ts
+191 -1
@@ -15,7 +15,11 @@ import * as FileSystem from "effect/FileSystem";
15 import * as Path from "effect/Path";
16 import { vi } from "vite-plus/test";
17
18 -import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts";
18 +import {
19 + renderBootServicePlist,
20 + renderBootServiceTask,
21 + renderBootServiceUnit,
22 +} from "./cloud/bootService.ts";
23 import {
24 databaseBackupBlocker,
25 Launcher,
@@ -23,15 +27,20 @@ import {
27 readServiceEnvironment,
28 type BackupSpaceProbe,
29 readServiceState,
30 + registerServiceTask,
31 + serviceLauncherIsRunning,
32 + serviceLauncherLockPath,
33 writeServiceState,
34 } from "./serviceLauncher.ts";
35 import {
36 compareExactServiceVersions,
37 decodeServiceState,
38 isExactServiceVersion,
39 + disabledServiceTask,
40 SERVICE_ENV_FILE,
41 SERVICE_LAUNCHER_PROTOCOL,
42 SERVICE_RESTART_PENDING_FILE,
43 + SERVICE_STOP_MARKER_FILE,
44 } from "./cloud/serviceProtocol.ts";
45
46 const spawnedChildren = vi.hoisted((): Array<NodeChildProcess.ChildProcess> => []);
@@ -222,6 +231,77 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
231 }),
232 );
233
234 + it.effect("registers its task again without enabling one the CLI disabled", () =>
235 + Effect.gen(function* () {
236 + const fs = yield* FileSystem.FileSystem;
237 + const path = yield* Path.Path;
238 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-task-" });
239 + const unitPath = path.join(root, "t3code-task.xml");
240 + const unit = renderBootServiceTask(unitPlan(root, "1.1.0"), {
241 + userId: "PC\\theo",
242 + homeDir: "C:\\Users\\theo",
243 + conhostPath: "conhost.exe",
244 + });
245 + yield* fs.writeFileString(unitPath, unit);
246 + // Task Scheduler's copy: `t3 doctor` disabled it to keep the service stopped.
247 + let task = disabledServiceTask(unit.replace("1.1.0", "1.0.0"));
248 + const schtasks = async (...args: ReadonlyArray<string>) => {
249 + if (args[0] === "/Create") task = await NodeFSP.readFile(args[2] ?? "", "utf8");
250 + return { stdout: task };
251 + };
252 +
253 + yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks));
254 + assert.equal(task, disabledServiceTask(unit));
255 + assert.deepEqual(yield* fs.readDirectory(root), ["t3code-task.xml"]);
256 +
257 + task = unit.replace("1.1.0", "1.0.0");
258 + yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks));
259 + assert.equal(task, unit);
260 + }),
261 + );
262 +
263 + it.effect("finds its unit through the manager's environment, not service.env", () =>
264 + Effect.gen(function* () {
265 + const fs = yield* FileSystem.FileSystem;
266 + const path = yield* Path.Path;
267 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-unit-" });
268 + const home = path.join(root, "home");
269 + const unitPath = path.join(home, "Library", "LaunchAgents", "t3code.plist");
270 + const render = (version: string) =>
271 + renderBootServicePlist(unitPlan(root, version), { homeDir: home, environmentPath: "" });
272 + yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true });
273 + yield* fs.writeFileString(unitPath, render("1.0.0"));
274 + // The server may run with another HOME; the launch agent still lives in the manager's.
275 + yield* fs.writeFileString(path.join(root, SERVICE_ENV_FILE), "HOME=/elsewhere\n");
276 + yield* writeFakeRuntime(
277 + fs,
278 + path,
279 + path.join(root, "runtime", "versions", "1.1.0"),
280 + "process.exit(0);\n",
281 + );
282 + yield* Effect.promise(() =>
283 + writeServiceState(path.join(root, "runtime", "service-state.json"), {
284 + protocol: SERVICE_LAUNCHER_PROTOCOL,
285 + activeVersion: "1.1.0",
286 + update: {
287 + id: "update-1",
288 + fromVersion: "1.0.0",
289 + targetVersion: "1.1.0",
290 + status: "committed",
291 + },
292 + }),
293 + );
294 + vi.stubEnv("HOME", home);
295 + vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.plist");
296 +
297 + yield* Effect.promise(() =>
298 + expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."),
299 + );
300 +
301 + assert.equal(yield* fs.readFileString(unitPath), render("1.1.0"));
302 + }),
303 + );
304 +
305 it.effect("adopts a legacy install record without rewriting it", () =>
306 Effect.gen(function* () {
307 const fs = yield* FileSystem.FileSystem;
@@ -610,6 +690,15 @@ if (context.update?.status === "pending") {
690 environmentPath: "/usr/bin:/custom/runtime/versions/1.0.0",
691 }),
692 },
693 + {
694 + name: "Task Scheduler",
695 + legacyInstall: false,
696 + render: (plan: Parameters<typeof renderBootServiceTask>[0]) =>
697 + renderBootServiceTask(
698 + { ...plan, program: [`${plan.program[0]}.exe`, "__service-launcher"] },
699 + { userId: "PC\\theo", homeDir: "C:\\Users\\theo", conhostPath: "conhost.exe" },
700 + ),
701 + },
702 ])(
703 "commits and repoints $name only after the trial reports prepared",
704 ({ render, legacyInstall }) =>
@@ -1031,6 +1120,107 @@ if (context.update?.status === "pending") {
1120 }),
1121 );
1122
1123 + it.effect("holds its lock while it serves and stops the server over IPC, marker set", () =>
1124 + Effect.gen(function* () {
1125 + const fs = yield* FileSystem.FileSystem;
1126 + const path = yield* Path.Path;
1127 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-control-" });
1128 + const statePath = path.join(root, "runtime", "service-state.json");
1129 + const databasePath = path.join(root, "userdata", "state.sqlite");
1130 + const reportPath = path.join(root, "stopped-with-marker");
1131 + yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true });
1132 + yield* fs.writeFileString(databasePath, "database");
1133 + const encoded = JSON.stringify({
1134 + databasePath,
1135 + reportPath,
1136 + markerPath: path.join(root, "runtime", SERVICE_STOP_MARKER_FILE),
1137 + });
1138 + const childSource = `
1139 +const fs = require("node:fs");
1140 +const paths = ${encoded};
1141 +process.on("message", (message) => {
1142 + if (message.type !== "stop") return;
1143 + fs.writeFileSync(paths.reportPath, String(fs.existsSync(paths.markerPath)));
1144 + process.exit(0);
1145 +});
1146 +process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath });
1147 +`;
1148 + for (const version of ["1.0.0", "1.1.0"]) {
1149 + yield* writeFakeRuntime(
1150 + fs,
1151 + path,
1152 + path.join(root, "runtime", "versions", version),
1153 + childSource,
1154 + );
1155 + }
1156 + yield* Effect.promise(() =>
1157 + writeServiceState(statePath, {
1158 + protocol: SERVICE_LAUNCHER_PROTOCOL,
1159 + activeVersion: "1.0.0",
1160 + }),
1161 + );
1162 + const lockPath = serviceLauncherLockPath(root);
1163 + const serving = Promise.withResolvers<void>();
1164 + const launcher = new Launcher(
1165 + root,
1166 + yield* Effect.promise(() => readServiceState(statePath)),
1167 + {
1168 + lockPath,
1169 + stopChildOverIpc: true,
1170 + // The update request proves the child is up; refusing it leaves the server running.
1171 + backupSpaceProbe: {
1172 + readFreeBytes: () => {
1173 + serving.resolve();
1174 + return Promise.resolve(0);
1175 + },
1176 + canClone: () => Promise.resolve(false),
1177 + },
1178 + },
1179 + );
1180 + const running = launcher.run();
1181 + yield* Effect.promise(() => Promise.race([serving.promise, running]));
1182 +
1183 + assert.isTrue(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1184 + // What losing the task's console does.
1185 + yield* Effect.promise(() => launcher.stop("SIGTERM"));
1186 + yield* Effect.promise(() => running);
1187 + assert.equal(yield* fs.readFileString(reportPath), "true");
1188 + assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1189 + }),
1190 + );
1191 +
1192 + it.effect("leaves a pending update alone when stopped while it starts up", () =>
1193 + Effect.gen(function* () {
1194 + const fs = yield* FileSystem.FileSystem;
1195 + const path = yield* Path.Path;
1196 + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-startup-stop-" });
1197 + const statePath = path.join(root, "runtime", "service-state.json");
1198 + // Recovery would roll this back: the target runtime is missing.
1199 + const pending = {
1200 + protocol: SERVICE_LAUNCHER_PROTOCOL,
1201 + activeVersion: "1.0.0",
1202 + update: {
1203 + id: "update-1",
1204 + fromVersion: "1.0.0",
1205 + targetVersion: "1.1.0",
1206 + dbPath: path.join(root, "userdata", "state.sqlite"),
1207 + status: "pending",
1208 + },
1209 + } as const;
1210 + yield* Effect.promise(() => writeServiceState(statePath, pending));
1211 + const lockPath = serviceLauncherLockPath(root);
1212 + const launcher = new Launcher(root, pending, { lockPath });
1213 +
1214 + const running = launcher.run();
1215 + yield* Effect.promise(() => launcher.stop("SIGTERM"));
1216 + yield* Effect.promise(() => running);
1217 +
1218 + // The lock is released only once the launcher is done with the home.
1219 + assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath)));
1220 + assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending);
1221 + }),
1222 + );
1223 +
1224 it.effect("records no update when the server exits during the backup check", () =>
1225 Effect.gen(function* () {
1226 const fs = yield* FileSystem.FileSystem;
apps/server/src/serviceLauncher.ts
+228 -31
@@ -22,9 +22,12 @@ import {
22 decodeServiceLauncherChildMessage,
23 isExactServiceVersion,
24 parseLegacyServiceState,
25 + disabledServiceTask,
26 parseServiceState,
27 + serviceTaskIsDisabled,
28 serviceUnitBaseDirOf,
29 SERVICE_ENV_FILE,
30 + SERVICE_LAUNCHER_LOCK_FILE,
31 SERVICE_LAUNCHER_CONTEXT_ENV,
32 SERVICE_LAUNCHER_PROTOCOL,
33 SERVICE_STATE_FILE,
@@ -40,6 +43,9 @@ const HANDOFF_DELAY_MS = 2_000;
43 */
44 const PREPARED_TIMEOUT_MS = 30 * 60_000;
45 const TERMINATE_GRACE_MS = 5_000;
46 +// A replacement started by a handoff waits up to two minutes for the stopping launcher.
47 +const LOCK_RETRY_MS = 500;
48 +const LOCK_ATTEMPTS = 240;
49 // Match contracts' SERVER_EXIT_CODE_STATE_DIR_OWNED without depending on Effect.
50 const STATE_DIR_OWNED_EXIT_CODE = 78;
51
@@ -76,14 +82,53 @@ const runtimeSpawnArguments = (paths: ReturnType<typeof runtimePaths>) => ({
82 */
83 export interface ServiceUnit {
84 readonly path: string;
79 - /** systemd keeps a loaded copy of the unit; launchd re-reads the plist at bootstrap. */
85 + /** systemd and Task Scheduler keep a loaded copy; launchd re-reads the plist at bootstrap. */
86 readonly reload: () => Promise<void>;
87 }
88
89 +const runSchtasks = (...args: ReadonlyArray<string>) =>
90 + NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, {
91 + windowsHide: true,
92 + timeout: 30_000,
93 + });
94 +
95 +/**
96 + * Registering replaces the task, so one the CLI disabled to keep the service stopped is
97 + * registered disabled. The caller holds the unit lease, as the CLI does to disable it.
98 + */
99 +export async function registerServiceTask(
100 + unitPath: string,
101 + taskName: string,
102 + schtasks: (...args: ReadonlyArray<string>) => Promise<{ readonly stdout: string }> = runSchtasks,
103 +): Promise<void> {
104 + const register = (xmlPath: string) => schtasks("/Create", "/XML", xmlPath, "/TN", taskName, "/F");
105 + const registered = await schtasks("/Query", "/TN", taskName, "/XML");
106 + if (!serviceTaskIsDisabled(registered.stdout)) {
107 + await register(unitPath);
108 + return;
109 + }
110 + const disabledPath = `${unitPath}.${process.pid}.disabled`;
111 + try {
112 + const unit = await NodeFSP.readFile(unitPath, "utf8");
113 + await NodeFSP.writeFile(disabledPath, disabledServiceTask(unit));
114 + await register(disabledPath);
115 + } finally {
116 + await NodeFSP.rm(disabledPath, { force: true });
117 + }
118 +}
119 +
120 function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined {
121 const unitName = env[SERVICE_UNIT_ENV]?.trim();
122 + if (!unitName) return undefined;
123 + if (unitName.endsWith(".xml")) {
124 + const localAppData = env.LOCALAPPDATA?.trim();
125 + if (!localAppData) return undefined;
126 + const path = NodePath.win32.join(localAppData, "t3code", unitName);
127 + const taskName = serviceTaskName(env.USERDOMAIN ?? "", env.USERNAME ?? "");
128 + return { path, reload: () => registerServiceTask(path, taskName) };
129 + }
130 const home = env.HOME?.trim();
86 - if (!unitName || !home) return undefined;
131 + if (!home) return undefined;
132 if (unitName.endsWith(".plist")) {
133 return {
134 path: NodePath.join(home, "Library", "LaunchAgents", unitName),
@@ -114,12 +159,13 @@ function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): Servi
159 };
160 }
161
117 -// systemd's ExecStart value, or the plist string before the __service-launcher argument.
162 +// systemd's ExecStart value, or the plist string or task argument before __service-launcher.
163 // Only the version segment changes, so quoted or escaped paths stay as rendered.
164 // The launch agent's PATH names a versions directory without the executable; leave it.
165 const SERVICE_UNIT_PROGRAMS = [
166 /^(ExecStart=.*?[\\/]runtime[\\/]versions[\\/])([^\\/\s"]+)([\\/]t3)(?=["\s])/m,
167 /(<string>[^<]*?[\\/]runtime[\\/]versions[\\/])([^\\/<]+)([\\/]t3<\/string>\s*<string>__service-launcher<\/string>)/,
168 + /(<Arguments>--headless "[^"<]*?[\\/]runtime[\\/]versions[\\/])([^\\/"<]+)([\\/]t3\.exe" "__service-launcher")/,
169 ] as const;
170
171 /**
@@ -601,10 +647,15 @@ function waitForExit(child: NodeChildProcess.ChildProcess): Promise<void> {
647
648 async function terminateChild(
649 child: NodeChildProcess.ChildProcess,
604 - signal: NodeJS.Signals = "SIGTERM",
650 + signal: NodeJS.Signals,
651 + overIpc: boolean,
652 ): Promise<void> {
653 if (child.exitCode !== null || child.signalCode !== null) return;
607 - child.kill(signal);
654 + if (overIpc) {
655 + await sendMessage(child, { type: "stop" }).catch(() => child.kill(signal));
656 + } else {
657 + child.kill(signal);
658 + }
659 const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS);
660 try {
661 await waitForExit(child);
@@ -613,6 +664,46 @@ async function terminateChild(
664 }
665 }
666
667 +/** Task Scheduler names are machine-wide, so each Windows account runs its own task. */
668 +export const serviceTaskName = (domain: string, userName: string) => `t3code-${domain}-${userName}`;
669 +
670 +export const serviceLauncherLockPath = (baseDir: string) =>
671 + NodePath.join(baseDir, "runtime", SERVICE_LAUNCHER_LOCK_FILE);
672 +
673 +// An exclusive SQLite transaction, like the server's owner lock: the OS drops it when the holder dies.
674 +async function tryAcquireLauncherLock(
675 + lockPath: string,
676 +): Promise<{ readonly close: () => void } | undefined> {
677 + const { DatabaseSync } = await import("node:sqlite");
678 + const db = new DatabaseSync(lockPath);
679 + try {
680 + db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;");
681 + return db;
682 + } catch (cause) {
683 + db.close();
684 + if (cause instanceof Error && "errcode" in cause && cause.errcode === 5) return undefined;
685 + throw cause;
686 + }
687 +}
688 +
689 +export async function serviceLauncherIsRunning(lockPath: string): Promise<boolean> {
690 + if (!NodeFS.existsSync(lockPath)) return false;
691 + const lock = await tryAcquireLauncherLock(lockPath);
692 + lock?.close();
693 + return lock === undefined;
694 +}
695 +
696 +/** Resolves once no launcher holds the lock; the caller bounds the wait through `signal`. */
697 +export async function waitForServiceLauncherExit(
698 + lockPath: string,
699 + signal: AbortSignal,
700 +): Promise<void> {
701 + while (await serviceLauncherIsRunning(lockPath)) {
702 + signal.throwIfAborted();
703 + await new Promise((resolve) => setTimeout(resolve, 100));
704 + }
705 +}
706 +
707 const stopMarkerPath = (baseDir: string) =>
708 NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
709 const restartPendingPath = (baseDir: string) =>
@@ -632,6 +723,9 @@ export class Launcher {
723 readonly #backupSpaceProbe: Partial<BackupSpaceProbe> | undefined;
724 readonly #serviceUnit: ServiceUnit | undefined;
725 readonly #environment: Readonly<NodeJS.ProcessEnv>;
726 + readonly #output: number | undefined;
727 + readonly #lockPath: string | undefined;
728 + readonly #stopChildOverIpc: boolean;
729
730 constructor(
731 baseDir: string,
@@ -640,12 +734,22 @@ export class Launcher {
734 readonly backupSpaceProbe?: Partial<BackupSpaceProbe>;
735 readonly serviceUnit?: ServiceUnit;
736 readonly environment?: Readonly<NodeJS.ProcessEnv>;
737 + /** Launcher and server output, for managers that cannot redirect it. */
738 + readonly output?: number;
739 + /** Makes this the only launcher for its home; a replacement waits for the one stopping. */
740 + readonly lockPath?: string;
741 + /** Windows `kill()` is TerminateProcess, which skips the server's shutdown finalizers. */
742 + readonly stopChildOverIpc?: boolean;
743 } = {},
744 ) {
745 this.#baseDir = baseDir;
746 this.#backupSpaceProbe = options.backupSpaceProbe;
747 this.#serviceUnit = options.serviceUnit;
748 this.#environment = { ...(options.environment ?? process.env) };
749 + this.#output = options.output;
750 + this.#lockPath = options.lockPath;
751 + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
752 + this.#stopChildOverIpc = options.stopChildOverIpc ?? process.platform === "win32";
753 this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
754 this.#state = state;
755 }
@@ -656,14 +760,48 @@ export class Launcher {
760 process.once("SIGTERM", onSigterm);
761 process.once("SIGINT", onSigint);
762 try {
659 - this.#enqueue(() => this.#recover());
660 - await this.#completion.promise;
763 + const lock =
764 + this.#lockPath === undefined ? undefined : await this.#acquireLock(this.#lockPath);
765 + try {
766 + // The launcher that held the lock may have moved the state since main read it.
767 + if (lock !== undefined) this.#state = await readServiceState(this.#statePath);
768 + // A stop that arrived before this point leaves nothing to start or recover.
769 + if (!this.#stopRequested) this.#enqueue(() => this.#recover());
770 + await this.#completion.promise;
771 + } finally {
772 + if (lock !== undefined) {
773 + // Releasing the lock says this launcher is done with the home.
774 + await this.#transitions.catch(() => undefined);
775 + lock.close();
776 + }
777 + }
778 } finally {
779 process.off("SIGTERM", onSigterm);
780 process.off("SIGINT", onSigint);
781 }
782 }
783
784 + async #acquireLock(lockPath: string): Promise<{ readonly close: () => void } | undefined> {
785 + for (let attempt = 1; !this.#stopRequested; attempt++) {
786 + const lock = await tryAcquireLauncherLock(lockPath);
787 + if (lock !== undefined) return lock;
788 + if (attempt >= LOCK_ATTEMPTS) {
789 + throw new Error("Another T3 Code service launcher still runs for this T3 home.");
790 + }
791 + await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
792 + }
793 + return undefined;
794 + }
795 +
796 + #terminate(child: NodeChildProcess.ChildProcess, signal: NodeJS.Signals = "SIGTERM") {
797 + return terminateChild(child, signal, this.#stopChildOverIpc);
798 + }
799 +
800 + #log(line: string): void {
801 + if (this.#output === undefined) process.stderr.write(line);
802 + else NodeFS.writeSync(this.#output, line);
803 + }
804 +
805 #enqueue(transition: () => Promise<void>): void {
806 this.#transitions = this.#transitions
807 .then(transition, transition)
@@ -679,7 +817,7 @@ export class Launcher {
817 this.#clearTimer();
818 const child = this.#child?.process;
819 this.#child = null;
682 - if (child !== undefined) await terminateChild(child);
820 + if (child !== undefined) await this.#terminate(child);
821 this.#completion.reject(error);
822 }
823
@@ -699,7 +837,7 @@ export class Launcher {
837 this.#stopping = true;
838 const child = this.#child?.process;
839 this.#child = null;
702 - if (child !== undefined) await terminateChild(child, signal);
840 + if (child !== undefined) await this.#terminate(child, signal);
841 this.#done = true;
842 this.#completion.resolve();
843 });
@@ -813,7 +951,10 @@ export class Launcher {
951 const spawnArguments = runtimeSpawnArguments(paths);
952 const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, {
953 env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) },
816 - stdio: ["inherit", "inherit", "inherit", "ipc"],
954 + stdio:
955 + this.#output === undefined
956 + ? ["inherit", "inherit", "inherit", "ipc"]
957 + : ["ignore", this.#output, this.#output, "ipc"],
958 });
959 await new Promise<void>((resolve, reject) => {
960 const onError = (error: Error) => reject(error);
@@ -825,7 +966,7 @@ export class Launcher {
966 });
967 });
968 if (this.#stopping) {
828 - await terminateChild(child);
969 + await this.#terminate(child);
970 return;
971 }
972
@@ -940,7 +1081,7 @@ export class Launcher {
1081 this.#backupSpaceProbe,
1082 ).catch(() => undefined);
1083 this.#child = null;
943 - await terminateChild(child.process);
1084 + await this.#terminate(child.process);
1085 await finishOnlineBackup?.();
1086 // A stop during a minutes-long copy should not start a trial; restart resumes the pending update.
1087 if (this.#stopRequested) return;
@@ -1076,7 +1217,7 @@ export class Launcher {
1217 }
1218 // Signal listeners alone do not keep Node alive.
1219 this.#timer = setInterval(() => {}, 2_147_483_647);
1079 - process.stderr.write(
1220 + this.#log(
1221 "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n",
1222 );
1223 }
@@ -1089,7 +1230,7 @@ export class Launcher {
1230 ): Promise<void> {
1231 if (child !== undefined) {
1232 this.#child = null;
1092 - await terminateChild(child.process);
1233 + await this.#terminate(child.process);
1234 }
1235 await restoreDatabaseBackup(this.#baseDir, pending);
1236 const outcome = terminalUpdate({ pending, status, reason });
@@ -1108,26 +1249,82 @@ export class Launcher {
1249 }
1250 }
1251
1111 -export async function main(): Promise<void> {
1112 - const baseDir = process.env.T3CODE_HOME?.trim();
1252 +/** Task Scheduler cannot set variables or redirect output, so a Windows task passes them as flags. */
1253 +export interface LauncherOptions {
1254 + readonly baseDir?: string | undefined;
1255 + readonly logFile?: string | undefined;
1256 + readonly serviceUnit?: string | undefined;
1257 +}
1258 +
1259 +export async function main(options: LauncherOptions = {}): Promise<void> {
1260 + const baseDir = (options.baseDir ?? process.env.T3CODE_HOME)?.trim();
1261 if (baseDir === undefined || baseDir === "") {
1262 throw new Error("T3CODE_HOME is required by the T3 Code service launcher.");
1263 }
1116 - const environment = await readServiceEnvironment(baseDir);
1117 - const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
1118 - const contents = await NodeFSP.readFile(statePath, "utf8");
1119 - let state = parseServiceState(contents);
1120 - if (state === undefined) {
1121 - state = adoptLegacyServiceState(contents);
1122 - if (state === undefined) throw new Error("Service state is invalid or unsupported.");
1123 - if (!(await runtimeExists(baseDir, state.activeVersion))) {
1124 - throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`);
1264 + const output =
1265 + options.logFile === undefined ? undefined : NodeFS.openSync(options.logFile, "a", 0o600);
1266 + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime.
1267 + const windows = process.platform === "win32";
1268 + try {
1269 + // What the service manager started the launcher with. It locates the unit; service.env
1270 + // changes only what the server gets.
1271 + const managerEnvironment = {
1272 + ...process.env,
1273 + T3CODE_HOME: baseDir,
1274 + ...(options.serviceUnit === undefined ? {} : { [SERVICE_UNIT_ENV]: options.serviceUnit }),
1275 + };
1276 + const environment = await readServiceEnvironment(baseDir, managerEnvironment);
1277 + const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE);
1278 + const contents = await NodeFSP.readFile(statePath, "utf8");
1279 + let state = parseServiceState(contents);
1280 + if (state === undefined) {
1281 + state = adoptLegacyServiceState(contents);
1282 + if (state === undefined) throw new Error("Service state is invalid or unsupported.");
1283 + if (!(await runtimeExists(baseDir, state.activeVersion))) {
1284 + throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`);
1285 + }
1286 + }
1287 + const serviceUnit = serviceUnitFromEnvironment(managerEnvironment);
1288 + const launcher = new Launcher(baseDir, state, {
1289 + environment,
1290 + ...(serviceUnit === undefined ? {} : { serviceUnit }),
1291 + ...(output === undefined ? {} : { output }),
1292 + ...(windows ? { lockPath: serviceLauncherLockPath(baseDir) } : {}),
1293 + });
1294 + // Ending a scheduled task kills its console host without a signal; the console read fails instead.
1295 + const watchConsole = windows && process.stdin.isTTY === true;
1296 + const onConsoleLost = () => void launcher.stop("SIGTERM");
1297 + if (watchConsole) {
1298 + process.stdin.on("error", () => undefined);
1299 + process.stdin.once("close", onConsoleLost);
1300 + process.stdin.resume();
1301 + }
1302 + try {
1303 + await launcher.run();
1304 + } finally {
1305 + if (watchConsole) {
1306 + process.stdin.off("close", onConsoleLost);
1307 + process.stdin.destroy();
1308 + }
1309 }
1310 + } catch (cause) {
1311 + if (output !== undefined) {
1312 + NodeFS.writeSync(
1313 + output,
1314 + `[service-launcher] ${cause instanceof Error ? cause.message : String(cause)}\n`,
1315 + );
1316 + }
1317 + // Agents the server left behind keep the console host, and so the task, running; ending it
1318 + // lets the next repeating trigger start the service again.
1319 + if (windows && options.serviceUnit !== undefined) {
1320 + const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? "");
1321 + NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], {
1322 + stdio: "ignore",
1323 + windowsHide: true,
1324 + });
1325 + }
1326 + throw cause;
1327 + } finally {
1328 + if (output !== undefined) NodeFS.closeSync(output);
1329 }
1127 - const serviceUnit = serviceUnitFromEnvironment();
1128 - await new Launcher(
1129 - baseDir,
1130 - state,
1131 - serviceUnit === undefined ? { environment } : { environment, serviceUnit },
1132 - ).run();
1330 }
docs/internals/server-updates.md
+12 -1
@@ -1,7 +1,7 @@
1 # Server updates
2
3 A [stable launcher](../../apps/server/src/serviceLauncher.ts) owns the runtime
4 -selected by systemd or launchd. It is the only runtime writer of durable service
4 +selected by systemd, launchd, or Task Scheduler. It is the only runtime writer of durable service
5 state. Server children request updates over inherited IPC; they never rewrite
6 their service definition or select their own replacement. Local service commands
7 may replace the launcher and state, optionally deferring the restart. Foreground
@@ -36,6 +36,17 @@ runtime that installed it. Until a deferred local upgrade restarts, systemd (bef
36 daemon-reload) and launchd (before bootstrap) can respawn the old launcher, which
37 rejects the state the new installer wrote.
38
39 +Task Scheduler tracks only the console host it started, not the launcher. `schtasks /End`
40 +kills that host and nothing else; the launcher takes its closed console as SIGTERM. The task
41 +reads as stopped at once, and `/Run` then starts a second launcher beside the first, so a
42 +Windows launcher holds a lock file for as long as it runs. A replacement waits for that lock,
43 +and the CLI treats its release as the stop having finished.
44 +
45 +Task Scheduler also runs its own copy of the task, and registering one enables it. So every
46 +write of the task file registers it, including an install that defers its restart. The CLI
47 +disables the task under the unit lease, and a registration under that lease keeps a disabled
48 +task disabled, so the repeating trigger cannot restart a service the CLI is holding stopped.
49 +
50 ## Commit boundary
51
52 The launcher durably records the pending update before acknowledging it, then
docs/user/background-service.md
+9 -8
@@ -1,7 +1,7 @@
1 # Running T3 Code in the background
2
3 -On Linux and macOS, T3 Code can run as a service for your user so you do not need
4 -to keep a terminal open.
3 +On Linux, macOS, and Windows, T3 Code can run as a service for your user so you
4 +do not need to keep a terminal open.
5
6 ## Manage the service
7
@@ -92,11 +92,12 @@ Mac logged in and awake for unattended remote access. Installing over SSH while
92 nobody is logged in at the Mac's screen can fail at the final start step; the
93 service is still installed and will start at the next login.
94
95 -Windows background services are not supported. To keep a Windows host available
96 -through T3 Connect, leave the desktop app running with its local environment
97 -enabled, or keep `t3 serve` running in a terminal. Minimize the desktop app rather
98 -than closing its last window, which stops its local server. Linking T3 Connect
99 -does not configure automatic startup at Windows sign-in.
95 +Windows starts the service when you log in and stops it when you sign out. It
96 +runs without a window as the `t3code-<domain>-<user name>` task in Task Scheduler, and Task
97 +Scheduler starts it again within a minute if it exits. Lock the screen instead
98 +of signing out, and keep the PC awake, for unattended remote access. Installing
99 +over SSH while nobody is signed in at the PC can fail at the final start step;
100 +the service is still installed and will start at the next sign-in.
101
102 `t3 up` installs the service when you set up T3 Connect, but the two are managed
103 separately. Signing out of T3 Connect does not stop or uninstall the service.
@@ -147,7 +148,7 @@ that session open.
148 | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
149 | `linger-unavailable` | Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available. |
150 | `user-manager-unavailable` | Run `systemctl --user status` in a login session for the service user; check your distribution's systemd user-session support. |
150 -| `service-disabled` or `service-stopped` | Read the log and `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. |
151 +| `service-disabled` or `service-stopped` | Read the log and, on Linux, `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. |
152 | `restart-pending` | A newer version is installed but the service still runs the previous one. Run `t3 service restart`. |
153
154 On macOS, check **System Settings → General → Login Items** if the service no
docs/user/install.md
+10 -10
@@ -28,15 +28,15 @@ installer or the desktop app did not create is already there, it leaves that
28 one alone and stops. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
29 `T3CODE_VERSION` to pin an exact version.
30
31 -| Task | Command |
32 -| ------------------------------------------------ | ----------------------------------------------------------------------- |
33 -| Start the server and open the web app | `t3` |
34 -| Start the server without a browser | `t3 serve` |
35 -| Use it from your other devices | `t3 up` ([details](./remote-access.md)) |
36 -| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
37 -| Move to the newest release | `t3 update` |
38 -| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
39 -| Remove it again | `t3 uninstall` |
31 +| Task | Command |
32 +| ------------------------------------- | ----------------------------------------------------------------------- |
33 +| Start the server and open the web app | `t3` |
34 +| Start the server without a browser | `t3 serve` |
35 +| Use it from your other devices | `t3 up` ([details](./remote-access.md)) |
36 +| Keep it running in the background | `t3 service install` ([details](./background-service.md)) |
37 +| Move to the newest release | `t3 update` |
38 +| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
39 +| Remove it again | `t3 uninstall` |
40
41 Run `t3 help` or `t3 --help` for the full reference. To start in a new working
42 directory, use an explicit path such as `t3 ./my-project`. A bare directory name
@@ -239,6 +239,6 @@ For provider-specific setup and accounts, see [Codex](./providers-codex.md),
239 - [Working with threads](./thread-sidebar.md): start tasks and organize parallel work.
240 - [Permission modes](./permission-modes.md): choose when agents ask before acting.
241 - [Remote access](./remote-access.md): connect from another device.
242 -- [Running in the background](./background-service.md): keep a Linux or macOS host available.
242 +- [Running in the background](./background-service.md): keep a host available.
243 - [Updating T3 Code](./updating.md): update the app and connected servers.
244 - [Managed policy](./managed-policy.md): configure T3 Code for everyone on a machine.
docs/user/remote-access.md
+6 -7
@@ -16,16 +16,15 @@ t3 up
16 ```
17
18 It asks how your other devices reach the machine: T3 Connect, the local network,
19 -or both. Choose T3 Connect and follow the sign-in instructions. On Linux and
20 -macOS, it then runs T3 Code as a [background service](./background-service.md).
19 +or both. Choose T3 Connect and follow the sign-in instructions. It then runs
20 +T3 Code as a [background service](./background-service.md).
21 `t3 connect` is the same as `t3 up --connect`. Run `t3 up` again to change your
22 choice, and `t3 status` to see it.
23
24 -The background service is not available on Windows, so there `t3 up` prints the
25 -`t3 serve` command to keep running in a terminal. You can also keep the desktop
26 -app running with its local environment enabled. Closing the desktop app's last
27 -window stops its local server. Saving your sign-in alone does not start a server
28 -or make the machine reachable.
24 +Instead of the background service, you can keep the desktop app running with
25 +its local environment enabled. Closing the desktop app's last window stops its
26 +local server. Saving your sign-in alone does not start a server or make the
27 +machine reachable.
28
29 On your other device, sign in to the same T3 Connect account and choose the
30 environment. On the app.t3.codes home page with no computer added yet, signing