Skip to content

Commit d44edf4

Browse files
t3dotggclaude
andcommitted
fix(cli): the Windows service stops through Task Scheduler and repoints its task
Task Scheduler is now the only control channel. `schtasks /End` kills the task's console host, and the launcher already takes its closed console as SIGTERM, so the named control pipe is gone. A lock file in the T3 home says whether a launcher runs, makes a replacement wait for the one stopping, and tells the CLI when a stop has finished. After a remote update commits, the launcher points the task at the new runtime and registers it again, as it does for systemd and launchd. The runtime prune reads the task too, so it keeps the launcher's runtime. `withStopped` restarts a service whose task an interrupted stop left disabled while its launcher still ran. Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent c915ded commit d44edf4

10 files changed

Lines changed: 249 additions & 150 deletions

File tree

‎apps/server/src/bin.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,13 @@ if (
3838
})
3939
) {
4040
// 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);
4548
} else {
4649
const { runCliCommand } = await loadCliMain();
4750
await runCliCommand();

‎apps/server/src/cli/serviceLauncher.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
11
import { type LauncherOptions, main as runServiceLauncher } from "../serviceLauncher.ts";
22

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+
320
export async function runServiceLauncherCli(options?: LauncherOptions): Promise<void> {
421
try {
522
await runServiceLauncher(options);

‎apps/server/src/cloud/bootService.test.ts‎

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers.
22
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeSqlite from "node:sqlite";
34
import * as NodeServices from "@effect/platform-node/NodeServices";
45
import { expect, it } from "@effect/vitest";
56
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -17,6 +18,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
1718
import { vi } from "vite-plus/test";
1819

1920
import * as ProcessRunner from "../processRunner.ts";
21+
import { serviceLauncherLockPath } from "../serviceLauncher.ts";
2022
import * as BootService from "./bootService.ts";
2123
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
2224
import {
@@ -165,6 +167,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
165167
lingerStartsManager: boolean;
166168
enabled: boolean;
167169
active: boolean;
170+
/** A Windows launcher: it holds its lock until its task ends. */
171+
launcher?: { readonly close: () => void };
168172
} = {
169173
failCommand: undefined,
170174
linger: "yes",
@@ -188,6 +192,11 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
188192
control.managerReachable ||= control.lingerStartsManager;
189193
}
190194
if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true;
195+
if (input.command === "schtasks") {
196+
if (input.args[0] === "/Create" || input.args.includes("/ENABLE")) control.enabled = true;
197+
if (input.args.includes("/DISABLE")) control.enabled = false;
198+
if (input.args[0] === "/End") control.launcher?.close();
199+
}
191200
if (!failed && command === "systemctl --user restart t3code.service") control.active = true;
192201
// The manager loads units only from its own unit directory.
193202
const unitOutsideManager =
@@ -217,13 +226,15 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
217226
})
218227
: input.args[0] === "--version"
219228
? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n`
220-
: input.command === "loginctl" && input.args[0] === "show-user"
221-
? `${control.linger ?? ""}\n`
222-
: input.args[1] === "is-enabled"
223-
? control.enabled
224-
? "enabled\n"
225-
: "disabled\n"
226-
: "",
229+
: input.command === "schtasks" && input.args[0] === "/Query"
230+
? `<Task><Settings><Enabled>${control.enabled}</Enabled></Settings></Task>`
231+
: input.command === "loginctl" && input.args[0] === "show-user"
232+
? `${control.linger ?? ""}\n`
233+
: input.args[1] === "is-enabled"
234+
? control.enabled
235+
? "enabled\n"
236+
: "disabled\n"
237+
: "",
227238
stderr: "",
228239
code: ChildProcessSpawner.ExitCode(
229240
failed ||
@@ -289,7 +300,12 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
289300
...(environmentPath === undefined || environmentPath === ""
290301
? {}
291302
: { PATH: environmentPath }),
292-
...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}),
303+
...(insideService
304+
? {
305+
T3_BOOT_SERVICE_UNIT:
306+
platform === "win32" ? "t3code-task.xml" : "t3code.service",
307+
}
308+
: {}),
293309
...(underSudo ? { SUDO_USER: "julius" } : {}),
294310
},
295311
}),
@@ -1267,7 +1283,7 @@ process.disconnect();
12671283
`schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`,
12681284
"schtasks /Run /TN t3code-PC-theo",
12691285
]);
1270-
// No launcher answers the control pipe here.
1286+
// No launcher holds the lock here.
12711287
expect(yield* service.status).toMatchObject({
12721288
installed: true,
12731289
current: false,
@@ -1285,6 +1301,29 @@ process.disconnect();
12851301
}),
12861302
);
12871303

1304+
it.effect("stops a Windows launcher by ending its task, and restarts one left disabled", () =>
1305+
Effect.gen(function* () {
1306+
const { service, commands, control } = yield* makeHarness("win32");
1307+
const plan = yield* service.install();
1308+
const launcher = new NodeSqlite.DatabaseSync(serviceLauncherLockPath(plan.baseDir));
1309+
launcher.exec("BEGIN EXCLUSIVE");
1310+
control.launcher = launcher;
1311+
// An interrupted stop disables the task and leaves its launcher running.
1312+
control.enabled = false;
1313+
expect((yield* service.status).problems).toEqual(["service-disabled"]);
1314+
1315+
commands.length = 0;
1316+
yield* service.withStopped(Effect.sync(() => commands.push("repair")));
1317+
expect(commands.filter((command) => !command.includes("/Query"))).toEqual([
1318+
"schtasks /Change /TN t3code-PC-theo /DISABLE",
1319+
"schtasks /End /TN t3code-PC-theo",
1320+
"repair",
1321+
"schtasks /Change /TN t3code-PC-theo /ENABLE",
1322+
"schtasks /Run /TN t3code-PC-theo",
1323+
]);
1324+
}),
1325+
);
1326+
12881327
it.effect("hands an in-service install and restart to Task Scheduler on Windows", () =>
12891328
Effect.gen(function* () {
12901329
const { service, fs, statePath, commands, makeService } = yield* makeHarness("win32");

‎apps/server/src/cloud/bootService.ts‎

Lines changed: 43 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease";
1919
import * as ProcessRunner from "../processRunner.ts";
2020
import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts";
2121
import {
22-
requestServiceLauncherStop,
23-
serviceControlPipePath,
2422
serviceLauncherIsRunning,
23+
serviceLauncherLockPath,
2524
serviceTaskName,
25+
waitForServiceLauncherExit,
2626
} from "../serviceLauncher.ts";
2727
import {
2828
ensurePinnedRuntimeInstalled,
@@ -38,6 +38,7 @@ import {
3838
SERVICE_STATE_FILE,
3939
SERVICE_UNIT_ENV,
4040
compareExactServiceVersions,
41+
serviceTaskIsDisabled,
4142
serviceUnitBaseDirOf as bootServiceBaseDirOf,
4243
parseServiceState,
4344
serviceStateActiveVersion,
@@ -196,7 +197,7 @@ export function renderBootServiceTask(
196197
"--log-file",
197198
plan.logPath,
198199
"--service-unit",
199-
BOOT_SERVICE_UNIT_FILE,
200+
BOOT_SERVICE_TASK_FILE,
200201
]
201202
.map(quoteWindowsArgument)
202203
.join(" ");
@@ -252,7 +253,7 @@ export type BootServiceStep = {
252253
readonly timeout?: Duration.Input;
253254
} & (
254255
| { readonly command: string; readonly args: ReadonlyArray<string> }
255-
/** A step no command can do, such as waiting on the Windows launcher's control pipe. */
256+
/** A step no command can do, such as waiting for the Windows launcher to exit. */
256257
| { readonly run: Effect.Effect<void, BootServiceCommandError> }
257258
);
258259

@@ -279,6 +280,9 @@ const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome:
279280
"user",
280281
);
281282

283+
const scheduledTaskPath = (path: Path.Path, localAppData: string) =>
284+
path.join(localAppData, "t3code", BOOT_SERVICE_TASK_FILE);
285+
282286
const launchdPlistPath = (path: Path.Path, homeDir: string) =>
283287
path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE);
284288

@@ -427,10 +431,10 @@ function schtasksManager(input: {
427431
readonly path: Path.Path;
428432
readonly homeDir: string;
429433
readonly session: WindowsSession;
430-
/** Asks the installed launcher to stop and waits for it; Task Scheduler cannot. */
434+
/** Ends the task and waits for its launcher to exit; Task Scheduler does not wait. */
431435
readonly stopLauncher: Effect.Effect<void, BootServiceCommandError>;
432436
}): BootServiceManager {
433-
const unitPath = input.path.join(input.session.localAppData, "t3code", BOOT_SERVICE_TASK_FILE);
437+
const unitPath = scheduledTaskPath(input.path, input.session.localAppData);
434438
const task = ["/TN", input.session.taskName];
435439
const register = {
436440
step: "registering the scheduled task",
@@ -469,7 +473,7 @@ function schtasksManager(input: {
469473
{ ...run, step: "restarting the service after a failed update" },
470474
],
471475
// Ending the task kills only its console host; the launcher sees the console close and
472-
// stops gracefully while the replacement waits for its control pipe.
476+
// stops gracefully while the replacement waits for its lock.
473477
handoff: [
474478
register,
475479
{
@@ -572,6 +576,10 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun
572576
const homeDir = yield* HostProcess.HomeDirectory;
573577
if (homeDir === "") return undefined;
574578
if (platform === "darwin") return launchdPlistPath(path, homeDir);
579+
if (platform === "win32") {
580+
const localAppData = (yield* HostProcess.Environment).LOCALAPPDATA ?? "";
581+
return localAppData === "" ? undefined : scheduledTaskPath(path, localAppData);
582+
}
575583
if (platform !== "linux") return undefined;
576584
const unitDir =
577585
(yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ??
@@ -770,9 +778,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
770778
// Root under sudo must not reach or start a separate root service.
771779
const rootUnderSudo =
772780
uid === 0 && (yield* Config.String("SUDO_USER").pipe(Config.withDefault(""))) !== "";
773-
const runningInsideService =
774-
(yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault(""))) ===
775-
BOOT_SERVICE_UNIT_FILE;
781+
const runningInsideService = [BOOT_SERVICE_UNIT_FILE, BOOT_SERVICE_TASK_FILE].includes(
782+
yield* Config.String(SERVICE_UNIT_ENV).pipe(Config.withDefault("")),
783+
);
776784
const fs = yield* FileSystem.FileSystem;
777785
const path = yield* Path.Path;
778786
const processRunner = yield* ProcessRunner.ProcessRunner;
@@ -831,21 +839,22 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
831839
systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows",
832840
};
833841
// The unit is per user, so the launcher to stop is the one serving the installed unit's home.
834-
const launcherControlPath = (unit: Option.Option<string>) =>
835-
serviceControlPipePath(
842+
const launcherLockPath = (unit: Option.Option<string>) =>
843+
serviceLauncherLockPath(
836844
Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir,
837845
);
846+
// Ending the task closes the launcher's console, which the launcher takes as its SIGTERM.
847+
// Task Scheduler then reports the task stopped at once, so the lock says when it really is.
838848
const stopWindowsLauncher = Effect.gen(function* () {
839849
const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
850+
yield* runner
851+
.run({ command: "schtasks", args: ["/End", "/TN", windowsSession.taskName] })
852+
.pipe(Effect.ignore);
840853
yield* Effect.tryPromise({
841-
try: () => requestServiceLauncherStop(launcherControlPath(unit)),
854+
try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal),
842855
catch: (cause) =>
843856
new BootServiceCommandError({ step: "stopping the installed service", cause }),
844857
});
845-
// Agents the server left behind keep its console host, and so the task, running.
846-
yield* runner
847-
.run({ command: "schtasks", args: ["/End", "/TN", windowsSession.taskName] })
848-
.pipe(Effect.ignore);
849858
});
850859
const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE);
851860
const resolveTarget = (systemdUnitDir: string | undefined) => {
@@ -1049,23 +1058,20 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
10491058
(release) => Effect.sync(release),
10501059
);
10511060

1052-
// Running means the launcher answers its control pipe: a task can stay running after the
1061+
// Running means the launcher holds its lock: a task can stay running after the
10531062
// launcher exits, while agents it left behind hold the console host open.
10541063
const readSchtasksProblems = Effect.fn("cloud.boot_service.read_schtasks_problems")(function* (
10551064
unit: Option.Option<string>,
10561065
) {
10571066
const [task, running] = yield* Effect.all(
10581067
[
10591068
probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]),
1060-
Effect.promise(() => serviceLauncherIsRunning(launcherControlPath(unit))),
1069+
Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))),
10611070
],
10621071
{ concurrency: "unbounded" },
10631072
);
1064-
const settings = Option.isSome(task)
1065-
? (/<Settings>[\s\S]*?<\/Settings>/.exec(task.value.stdout)?.[0] ?? "")
1066-
: "";
10671073
const problems: BootServiceProblem[] = [];
1068-
if (!succeeded(task) || settings.includes("<Enabled>false</Enabled>")) {
1074+
if (Option.isNone(task) || task.value.code !== 0 || serviceTaskIsDisabled(task.value.stdout)) {
10691075
problems.push("service-disabled");
10701076
}
10711077
if (!running) problems.push("service-stopped");
@@ -1206,11 +1212,17 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
12061212
if (Option.isSome(previousStateText)) {
12071213
const installedVersion = serviceStateActiveVersion(previousStateText.value);
12081214
if (serviceStateHasPendingUpdate(previousStateText.value)) {
1209-
const quote = (word: string) => `'${word.replaceAll("'", "'\\''")}'`;
1215+
const windows = platform === "win32";
1216+
const quote = (word: string) => `'${word.replaceAll("'", windows ? "''" : "'\\''")}'`;
1217+
const launcher = (version: string) =>
1218+
quote(pinnedRuntimePaths(path, input.baseDir, version, platform).entryPath);
12101219
return yield* new BootServiceUpdatePendingError(
12111220
!currentlyInstalled && installedVersion !== undefined
12121221
? {
1213-
recoveryCommand: `T3CODE_HOME=${quote(input.baseDir)} ${quote(pinnedRuntimePaths(path, input.baseDir, installedVersion, platform).entryPath)} __service-launcher`,
1222+
// PowerShell has no inline variable assignment; the launcher takes a flag.
1223+
recoveryCommand: windows
1224+
? `& ${launcher(installedVersion)} __service-launcher --base-dir ${quote(input.baseDir)}`
1225+
: `T3CODE_HOME=${quote(input.baseDir)} ${launcher(installedVersion)} __service-launcher`,
12141226
}
12151227
: {},
12161228
);
@@ -1345,7 +1357,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
13451357
([enabled, active]) => succeeded(active) || succeeded(enabled),
13461358
)
13471359
: manager.kind === "schtasks"
1348-
? !(yield* readSchtasksProblems(unit)).includes("service-disabled")
1360+
? // A task disabled while its launcher runs was left that way by an interrupted stop.
1361+
yield* Effect.map(
1362+
readSchtasksProblems(unit),
1363+
(problems) =>
1364+
!problems.includes("service-disabled") || !problems.includes("service-stopped"),
1365+
)
13491366
: succeeded(
13501367
yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]),
13511368
);

‎apps/server/src/cloud/serviceProtocol.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
1414
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
1515
/** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */
1616
export const SERVICE_RESTART_PENDING_FILE = ".restart-pending";
17+
/** Held by a Windows launcher while it runs: Task Scheduler tracks only the task's console host. */
18+
export const SERVICE_LAUNCHER_LOCK_FILE = "service-launcher.lock";
1719

1820
const unquoteSystemdValue = (raw: string) =>
1921
(raw.startsWith('"') && raw.endsWith('"')
@@ -27,6 +29,10 @@ const unescapeXmlText = (value: string) =>
2729
const unquoteWindowsArgument = (raw: string) =>
2830
unescapeXmlText(raw).replace(/(\\+)$/, (slashes) => slashes.slice(slashes.length / 2));
2931

32+
/** Whether Task Scheduler's copy of a task is disabled as a whole, not one of its triggers. */
33+
export const serviceTaskIsDisabled = (taskXml: string): boolean =>
34+
/<Settings>[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("<Enabled>false</Enabled>") === true;
35+
3036
export function serviceUnitBaseDirOf(contents: string): string | undefined {
3137
const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1];
3238
if (systemd !== undefined) return unquoteSystemdValue(systemd.trim());

0 commit comments

Comments
 (0)