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, 07:15 UTC
fix(server): write the Windows service task as UTF-16LE so non-ASCII paths survive (#38494)
Julius Marminge committed
Nov 18, 2026 at 00:46 UTC
37e9217b5696f33f347cdd282830e897a04c10ab
7 files changed
+61
-27
apps/server/src/cli/update.ts
+4
-1
@@ -38,6 +38,7 @@ import {
38
} from "../cloud/pinnedRuntime.ts";
39
import {
40
compareExactServiceVersions,
41
+ decodeServiceUnit,
42
isExactServiceVersion,
43
SERVICE_LAUNCHER_PROTOCOL,
44
} from "../cloud/serviceProtocol.ts";
@@ -574,7 +575,9 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
575
// A handed-off service install rewrites the unit later, while the old launcher may be stopped.
576
if (servicePlan?.handedOff !== true) {
577
// A stopped service's unit still names the launcher runtime it will start.
577
- const unit = yield* fs.readFileString(status.unitPath).pipe(Effect.option);
578
+ const unit = yield* fs
579
+ .readFile(status.unitPath)
580
+ .pipe(Effect.map(decodeServiceUnit), Effect.option);
581
yield* prunePinnedRuntimes({
582
baseDir: input.baseDir,
583
keep: [currentVersion, targetVersion],
apps/server/src/cloud/bootService.test.ts
+5
-2
@@ -22,6 +22,7 @@ import { serviceLauncherLockPath } from "../serviceLauncher.ts";
22
import * as BootService from "./bootService.ts";
23
import { pinnedRuntimePaths } from "./pinnedRuntime.ts";
24
import {
25
+ decodeServiceUnit,
26
disabledServiceTask,
27
parseServiceState,
28
serviceTaskIsDisabled,
@@ -256,7 +257,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
257
input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined;
258
if (input.command === "schtasks" && !failed) {
259
if (input.args[0] === "/Create") {
259
- const xml = yield* fs.readFileString(input.args[2] ?? "");
260
+ const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? ""));
261
control.task = { xml, enabled: !serviceTaskIsDisabled(xml) };
262
}
263
if (control.task !== undefined && input.args[0] === "/Change") {
@@ -1443,7 +1444,7 @@ process.disconnect();
1444
const { service, fs, statePath, commands, control, runtime } = yield* makeHarness("win32");
1445
const path = yield* Path.Path;
1446
const plan = yield* service.install();
1446
- const task = yield* fs.readFileString(plan.unitPath);
1447
+ const task = decodeServiceUnit(yield* fs.readFile(plan.unitPath));
1448
1449
expect(plan.unitPath).toBe(
1450
path.join(path.dirname(plan.baseDir), "AppData", "Local", "t3code", "t3code-task.xml"),
@@ -1452,6 +1453,8 @@ process.disconnect();
1453
expect(BootService.bootServiceBaseDirOf(task)).toBe(plan.baseDir);
1454
expect(task).toContain("<UserId>PC\\theo</UserId>");
1455
expect(task).toContain("<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>");
1456
+ // schtasks decodes undeclared UTF-8 with the ANSI code page; UTF-16LE with a BOM is read as is.
1457
+ expect([...(yield* fs.readFile(plan.unitPath)).subarray(0, 2)]).toEqual([0xff, 0xfe]);
1458
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
1459
protocol: SERVICE_LAUNCHER_PROTOCOL,
1460
activeVersion: "1.2.3",
apps/server/src/cloud/bootService.ts
+22
-14
@@ -38,7 +38,9 @@ import {
38
SERVICE_STATE_FILE,
39
SERVICE_UNIT_ENV,
40
compareExactServiceVersions,
41
+ decodeServiceUnit,
42
disabledServiceTask,
43
+ encodeServiceTask,
44
serviceTaskIsDisabled,
45
serviceUnitBaseDirOf as bootServiceBaseDirOf,
46
serviceUnitEnvironmentValueOf,
@@ -207,7 +209,7 @@ export function renderBootServicePlist(
209
/**
210
* Task Scheduler can neither set variables nor redirect output, so the launcher takes them as
211
* flags. A console program started by a task opens a window unless a headless console hosts it.
210
- * No XML declaration: schtasks rejects `encoding="UTF-8"` but reads undeclared XML as UTF-8.
212
+ * No XML declaration: the file is written as UTF-16LE with a BOM (see `encodeServiceTask`).
213
*/
214
export function renderBootServiceTask(
215
plan: BootServicePlan,
@@ -926,6 +928,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
928
(release) => Effect.sync(release),
929
),
930
);
931
+ const readUnit = () => fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit));
932
/**
933
* Task Scheduler runs its own copy of the task, so an install that starts nothing still
934
* registers the new one. A task that was disabled or absent stays stopped.
@@ -955,7 +958,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
958
directory: path.dirname(unitPath),
959
prefix: ".service-task-",
960
});
958
- yield* fs.writeFileString(disabledPath, disabledServiceTask(unit));
961
+ yield* fs.writeFile(disabledPath, encodeServiceTask(disabledServiceTask(unit)));
962
yield* register(disabledPath);
963
}),
964
);
@@ -963,7 +966,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
966
// Ending the task closes the launcher's console, which the launcher takes as its SIGTERM.
967
// Task Scheduler then reports the task stopped at once, so the lock says when it really is.
968
const stopWindowsLauncher = Effect.gen(function* () {
966
- const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
969
+ const unit = yield* readUnit().pipe(Effect.option);
970
yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore);
971
yield* Effect.tryPromise({
972
try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal),
@@ -1014,13 +1017,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1017
? installedBaseDir
1018
: undefined;
1019
};
1017
- const writeDurably = (filePath: string, contents: string) =>
1020
+ const writeDurably = (filePath: string, contents: string | Uint8Array) =>
1021
Effect.scoped(
1022
Effect.gen(function* () {
1023
const directory = path.dirname(filePath);
1024
yield* fs.makeDirectory(directory, { recursive: true });
1025
const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: ".service-write-" });
1023
- yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });
1026
+ yield* typeof contents === "string"
1027
+ ? fs.writeFileString(tempPath, contents, { mode: 0o600 })
1028
+ : fs.writeFile(tempPath, contents, { mode: 0o600 });
1029
// Opened read-write: Windows refuses to flush a handle without write access.
1030
yield* (yield* fs.open(tempPath, { flag: "r+" })).sync;
1031
yield* fs.rename(tempPath, filePath);
@@ -1217,7 +1222,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1222
// The unit is per user. Rewriting one that serves another home moves the
1223
// service onto this home's data, which looks like every thread vanished.
1224
const refuseOtherBaseDir = Effect.gen(function* () {
1220
- const existingUnit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1225
+ const existingUnit = yield* readUnit().pipe(Effect.option);
1226
const installedBaseDir = Option.isSome(existingUnit)
1227
? otherBaseDirOf(existingUnit.value)
1228
: undefined;
@@ -1322,9 +1327,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1327
input.baseDir.replaceAll("$", () => "$$"),
1328
...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []),
1329
]);
1325
- const unit = yield* fs
1326
- .readFileString(unitPath)
1327
- .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1330
+ const unit = yield* readUnit().pipe(
1331
+ Effect.mapError((cause) => new BootServiceInstallError({ cause })),
1332
+ );
1333
return { ...planForUnit(unit), handedOff: true };
1334
}
1335
// Task Scheduler restarts the task itself, so the files are written as for a deferred
@@ -1378,7 +1383,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1383
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
1384
// Files can match the new version even when activation fails; keep that install retryable.
1385
yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 });
1381
- const plan = planForUnit(currentlyInstalled ? yield* fs.readFileString(unitPath) : "");
1386
+ const plan = planForUnit(currentlyInstalled ? yield* readUnit() : "");
1387
yield* writeDurably(
1388
statePath,
1389
// @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document.
@@ -1398,7 +1403,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1403
}
1404
}
1405
const unit = manager.render(plan);
1401
- yield* writeDurably(unitPath, unit);
1406
+ yield* writeDurably(
1407
+ unitPath,
1408
+ manager.kind === "schtasks" ? encodeServiceTask(unit) : unit,
1409
+ );
1410
if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit);
1411
return plan;
1412
}),
@@ -1437,7 +1445,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1445
1446
const restart: BootService["Service"]["restart"] = Effect.gen(function* () {
1447
const manager = yield* requireManager;
1440
- const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1448
+ const unit = yield* readUnit().pipe(Effect.option);
1449
if (Option.isNone(unit)) return "skipped" as const;
1450
const installedBaseDir = bootServiceBaseDirOf(unit.value);
1451
if (
@@ -1470,7 +1478,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1478
): Effect.fn.Return<A, E | BootServiceError, R> {
1479
if (detectedManager === undefined) return yield* operation;
1480
const manager = detectedManager;
1473
- const unit = yield* fs.readFileString(unitPath).pipe(Effect.option);
1481
+ const unit = yield* readUnit().pipe(Effect.option);
1482
if (Option.isNone(unit)) return yield* operation;
1483
const installedBaseDir = bootServiceBaseDirOf(unit.value);
1484
if (
@@ -1546,7 +1554,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
1554
return { supported: true, installed: false, current: false, unitPath, logPath };
1555
}
1556
const [unit, runtimeEntryExists, runtimeSentinel, stateText] = yield* Effect.all([
1549
- fs.readFileString(unitPath),
1557
+ readUnit(),
1558
fs.exists(runtimePaths.entryPath),
1559
fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),
1560
fs.readFileString(statePath).pipe(Effect.option),
apps/server/src/cloud/selfUpdate.ts
+2
-2
@@ -43,7 +43,7 @@ import {
43
import { bootServiceProgramOf, bootServiceUnitPath } from "./bootService.ts";
44
import { runStagedServicePreflight } from "./servicePreflight.ts";
45
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
46
-import { isExactServiceVersion } from "./serviceProtocol.ts";
46
+import { decodeServiceUnit, isExactServiceVersion } from "./serviceProtocol.ts";
47
48
export function resolveServerSelfUpdateCapability(input: {
49
readonly desktopManaged: boolean;
@@ -92,7 +92,7 @@ export const pruneRuntimesOnStart = Effect.fn("cloud.server_self_update.prune_on
92
const unit =
93
unitPath === undefined
94
? Option.none<string>()
95
- : yield* fs.readFileString(unitPath).pipe(Effect.option);
95
+ : yield* fs.readFile(unitPath).pipe(Effect.map(decodeServiceUnit), Effect.option);
96
const program = Option.flatMapNullishOr(unit, bootServiceProgramOf);
97
// The unit may name it through another spelling of a symlinked T3 home.
98
const references = Option.isNone(program)
apps/server/src/cloud/serviceProtocol.ts
+10
@@ -43,6 +43,16 @@ const unquoteWindowsArgument = (raw: string) =>
43
export const serviceTaskIsDisabled = (taskXml: string): boolean =>
44
/<Settings>[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("<Enabled>false</Enabled>") === true;
45
46
+/** schtasks reads undeclared XML in the ANSI code page, but UTF-16LE with a BOM as written. */
47
+export const encodeServiceTask = (taskXml: string): Uint8Array =>
48
+ Buffer.from(`\uFEFF${taskXml}`, "utf16le");
49
+
50
+/** A unit file's text: UTF-16LE task files have a BOM, other units (and older tasks) are UTF-8. */
51
+export const decodeServiceUnit = (bytes: Uint8Array): string =>
52
+ bytes[0] === 0xff && bytes[1] === 0xfe
53
+ ? Buffer.from(bytes.buffer, bytes.byteOffset + 2, bytes.byteLength - 2).toString("utf16le")
54
+ : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("utf8");
55
+
56
/** A task as Task Scheduler should hold it while its service must stay stopped. */
57
export const disabledServiceTask = (taskXml: string): string =>
58
serviceTaskIsDisabled(taskXml)
apps/server/src/serviceLauncher.test.ts
+2
-1
@@ -38,6 +38,7 @@ import {
38
compareExactServiceVersions,
39
decodeServiceState,
40
isExactServiceVersion,
41
+ decodeServiceUnit,
42
disabledServiceTask,
43
SERVICE_ENV_FILE,
44
SERVICE_LAUNCHER_PROTOCOL,
@@ -469,7 +470,7 @@ setInterval(() => {}, 1_000);
470
// Task Scheduler's copy: `t3 doctor` disabled it to keep the service stopped.
471
let task = disabledServiceTask(unit.replace("1.1.0", "1.0.0"));
472
const schtasks = async (...args: ReadonlyArray<string>) => {
472
- if (args[0] === "/Create") task = await NodeFSP.readFile(args[2] ?? "", "utf8");
473
+ if (args[0] === "/Create") task = decodeServiceUnit(await NodeFSP.readFile(args[2] ?? ""));
474
return { stdout: task };
475
};
476
apps/server/src/serviceLauncher.ts
+16
-7
@@ -23,7 +23,9 @@ import {
23
decodeServiceLauncherChildMessage,
24
isExactServiceVersion,
25
parseLegacyServiceState,
26
+ decodeServiceUnit,
27
disabledServiceTask,
28
+ encodeServiceTask,
29
parseServiceState,
30
serviceTaskIsDisabled,
31
serviceUnitBaseDirOf,
@@ -121,8 +123,8 @@ export async function registerServiceTask(
123
}
124
const disabledPath = `${unitPath}.${process.pid}.disabled`;
125
try {
124
- const unit = await NodeFSP.readFile(unitPath, "utf8");
125
- await NodeFSP.writeFile(disabledPath, disabledServiceTask(unit));
126
+ const unit = decodeServiceUnit(await NodeFSP.readFile(unitPath));
127
+ await NodeFSP.writeFile(disabledPath, encodeServiceTask(disabledServiceTask(unit)));
128
await register(disabledPath);
129
} finally {
130
await NodeFSP.rm(disabledPath, { force: true });
@@ -256,7 +258,9 @@ async function serviceLogPath(
258
): Promise<string | undefined> {
259
if (options.logFile !== undefined) return options.logFile;
260
if (serviceUnit === undefined) return undefined;
259
- const contents = await NodeFSP.readFile(serviceUnit.path, "utf8").catch(() => undefined);
261
+ const contents = await NodeFSP.readFile(serviceUnit.path)
262
+ .then(decodeServiceUnit)
263
+ .catch(() => undefined);
264
return contents === undefined ? undefined : serviceUnitLogPathOf(contents);
265
}
266
@@ -665,7 +669,7 @@ export async function writeServiceState(filePath: string, state: ServiceState):
669
await replaceFileDurably(filePath, `${JSON.stringify(state, null, 2)}\n`);
670
}
671
668
-async function replaceFileDurably(filePath: string, contents: string): Promise<void> {
672
+async function replaceFileDurably(filePath: string, contents: string | Uint8Array): Promise<void> {
673
const directory = NodePath.dirname(filePath);
674
const tempPath = NodePath.join(
675
directory,
@@ -674,7 +678,7 @@ async function replaceFileDurably(filePath: string, contents: string): Promise<v
678
let handle: NodeFSP.FileHandle | undefined;
679
try {
680
handle = await NodeFSP.open(tempPath, "wx", 0o600);
677
- await handle.writeFile(contents, "utf8");
681
+ await handle.writeFile(contents);
682
await handle.sync();
683
await handle.close();
684
handle = undefined;
@@ -1360,7 +1364,7 @@ export class Launcher {
1364
) {
1365
return;
1366
}
1363
- const contents = await NodeFSP.readFile(unit.path, "utf8");
1367
+ const contents = decodeServiceUnit(await NodeFSP.readFile(unit.path));
1368
const installedBaseDir = serviceUnitBaseDirOf(contents);
1369
if (
1370
installedBaseDir === undefined ||
@@ -1369,7 +1373,12 @@ export class Launcher {
1373
return;
1374
}
1375
const repointed = repointServiceUnit(contents, version);
1372
- if (repointed !== contents) await replaceFileDurably(unit.path, repointed);
1376
+ if (repointed !== contents) {
1377
+ await replaceFileDurably(
1378
+ unit.path,
1379
+ unit.path.endsWith(".xml") ? encodeServiceTask(repointed) : repointed,
1380
+ );
1381
+ }
1382
// A previous rename may have succeeded before reload failed.
1383
await unit.reload();
1384
} finally {